在Web3浪潮下,去中心化应用(DApp)已成为区块链技术落地的核心场景,本文将以一个去中心化投票DApp为例,拆解以太坊DApp的开发全流程,涵盖智能合约、前端交互与用户操作,帮助开发者快速理解“以太坊+DApp+Web3”的技术融合逻辑。
核心架构:智能合约+前端+Web3连接
以太坊DApp的典型架构分为三层:
- 智能合约:部署在以太坊区块链上,定义业务逻辑(如投票规则、数据存储),使用Solidity语言编写;
- 前端界面:用户交互层,基于React、Vue等框架开发,调用合约功能;
- Web3连接:通过Web3.js或Ethers.js库,实现前端与以太坊节点的通信,完成用户签名、数据读写等操作。
开发实例:去中心化投票DApp
智能合约:投票逻辑的“大脑”
使用Solidity编写Voting.sol合约,核心功能包括:
- 候选人注册:只有合约所有者可添加候选人;
- 投票限制:每个地址只能投票一次;
- 投票查询:实时公开各候选人得票数。
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
mapping(address => bool) public hasVoted;
mapping(string => uint256) public voteCount;
address public owner;
constructor() {
owner = msg.sender;
}
function addCandidate(string memory candidateName) public {
require(msg.sender == owner, "Only owner can add candidates");
voteCount[candidateName] = 0;
}
function vote(string memory candidateName) public {
require(!hasVoted[msg.sender], "Already voted");
require(voteCount[candidateName] > 0, "Invalid candidate");
hasVoted[msg.sender] = true;
voteCount[candidateName]++;
}
}
前端开发:用户交互的“窗口”
以React为例,使用ethers.js库连接以太坊网络:
- 安装依赖:
npm install ethers; - 连接钱包:通过
ethers.providers.Web3Provider接入用户MetaMask钱包; - 调用合约:使用合约ABI(应用二进制接口)与部署后的合约交互。
import { ethers } from 'ethers';
// 合约部署后的地址和ABI
const contractAddress = "0x123..."; // 替换为实际部署地址
const contractABI = [...]; // 替换为合约生成的ABI
// 初始化合约
const provider = new ethers.providers.Web3Provider(window.ethereum);
const contract = new ethers.Contract(contractAddress, contractABI, provider.getSigner());
// 投票函数
async function vote(candidateName) {
try {
const tx = await contract.vote(candidateName);
await tx.wait(); // 等待交易确认
alert("投票成功!");
} catch (error) {
console.error("投票失败:", error);
}
}
部署与交互:打通“链上-链下”
- 合约部署:使用Remix IDE或Hardhat工具编译
Voting.sol,部署到以太坊测试网(如Ropsten)或主网; - 前端调用:用户点击“投票”按钮时,触发
vote()函数,MetaMask弹出签名确认,交易上链后自动更新投票数据。
Web3技术的核心价值
与传统中心化应用相比,该DApp的去中心化特性