:2026-03-14 7:24 点击:2
在区块链技术浪潮中,以太坊作为全球最大的智能合约平台,为去中心化应用(DApp)的开发与发布提供了成熟的生态支持,与传统的中心化应用不同,DApp基于智能合约运行,数据上链存储,具有透明、不可篡改、用户自主掌控等优势,如果你也想在以太坊上发布自己的DApp,本文将从技术准备到部署上线,为你拆解完整流程。
在动手之前,需先明确以太坊DApp的三大核心组成部分:
智能合约是DApp的核心,开发时需重点关注逻辑正确性和安全性(避免漏洞导致资产损失)。

// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;
contract SimpleVoting {
mapping(address => bool) public hasVoted;
mapping(string => uint256) public voteCount;
string[] public candidates;
constructor(string[] memory _candidates) {
candidates = _candidates;
}
function vote(string memory candidate) public {
require(!hasVoted[msg.sender], "You have already voted!");
bool validCandidate = false;
for (uint i = 0; i < candidates.length; i++) {
if (keccak256(abi.encodePacked(candidates[i])) == keccak256(abi.encodePacked(candidate))) {
validCandidate = true;
break;
}
}
require(validCandidate, "Invalid candidate!");
voteCount[candidate]++;
hasVoted[msg.sender] = true;
}
function getWinner() public view returns (string memory) {
uint256 maxVotes = 0;
string memory winner;
for (uint i = 0; i < candidates.length; i++) {
if (voteCount[candidates[i]] > maxVotes) {
maxVotes = voteCount[candidates[i]];
winner = candidates[i];
}
}
return winner;
}
}
关键点:
SPDX-License-Identifier:声明许可证,避免法律风险。 pragma solidity:指定Solidity版本,防止兼容性问题。 mapping:存储投票数据和用户投票状态。 require:输入校验,确保合约逻辑安全。 npx hardhat node启动本地节点(如Hardhat Network),模拟以太坊环境,快速调试合约逻辑。 前端是用户感知DApp的入口,需实现钱包连接、合约交互、数据展示等功能。
npx create-react-app voting-dapp cd voting-dapp npm install ethers # 或 web3.js
import { ethers } from "ethers";
import SimpleVoting from "./contracts/SimpleVoting.json";
const contractAddress = "0x..."; // 部署后的合约地址
const contractABI = SimpleVoting.abi;
async function connectWallet() {
if (window.ethereum) {
await window.ethereum.request({ method: "eth_requestAccounts" });
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();
const contract = new ethers.Contract(contractAddress, contractABI, signer);
return { provider, signer, contract };
} else {
alert("Please install MetaMask!");
}
}
async function vote(candidate) {
const { contract } = await connectWallet();
const tx = await contract.vote(candidate);
await tx.wait(); // 等待交易上链
alert("Vote submitted!");
}
关键点:
ethers.BrowserProvider:通过MetaMask连接以太坊网络。 signer:代表用户签名交易,用于执行合约的写操作(如投票)。 contract:合约实例,通过call方法(读操作)和send方法(写操作)与交互。 contract.on监听合约事件(如投票事件),实时更新前端界面。 测试完成后,需将智能合约部署到以太坊网络(测试网或主网)。
获取测试ETH:访问Goerli水龙头(如goerlifaucet.com),用MetaMask账号领取免费测试ETH。
配置Hardhat:在hardhat.config.js中添加Goerli网络配置:
require("@nomicfoundation/hardhat-toolbox");
module.exports = {
solidity: "0.8.20",
networks: {
goerli: {
url: "https://goerli.infura.io/v3/YOUR_INFURA_PROJECT_ID", // 替换为Infura或Alchemy的Project ID
accounts: ["YOUR_PRIVATE_KEY"], // 测试账号私钥(勿泄露)
},
},
};
编写部署脚本:在scripts/deploy.js中添加:
async function main() {
const Voting = await ethers.getContractFactory("SimpleVoting");
const voting = await Voting.deploy(["Alice", "Bob"]);
await voting.deployed();
console.log("Voting contract deployed to:", voting.address);
}
main().catch((error) => {
console.error(error);
process.exitCode = 1;
});
执行部署:
npx hardhat run scripts/deploy.js --network goerli
成功后,会输出合约地址,记录该地址用于前端交互。
智能合约部署后,需将前端代码发布到服务器,用户才能通过浏览器访问。
本文由用户投稿上传,若侵权请提供版权资料并联系删除!