:2026-06-01 23:33 点击:1
区块链技术的普及让“去中心化应用”(DApp)成为热点,而以太坊(Ethereum)作为全球最大的智能合约平台,为开发者提供了搭建区块链应用的成熟基础设施,本文将从环境准备、智能合约开发、节点部署到DApp交互,带你一步步了解如何用以太坊搭建区块链应用。
以太坊与比特币的核心区别在于:它不仅是一种加密货币,更是一个“可编程的区块链平台”,通过以太坊虚拟机(EVM)和智能合约(Solidity语言编写),开发者可以在区块链上构建自定义逻辑,实现从DeFi(去中心化金融)、NFT到元宇宙等多样化应用。
搭建以太坊区块链应用,本质上是利用以太坊的主网或测试网(如Ropsten、Goerli),开发智能合约并部署到链上,再通过前端与链上数据交互。
在开始之前,需安装以下核心工具:
contract、function、modifier等)。 智能合约是DApp的“后台”,定义了业务规则和链上交互逻辑,以一个简单的“投票合约”为例,展示开发流程:
npm install -g truffle mkdir eth-vote-dapp && cd eth-vote-dapp truffle init
初始化后,项目结构包含:
contracts/:存放智能合约代码 migrations/:部署脚本 test/:测试文件 在contracts/下创建Voting.sol:
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.0;
contract Voting {
mapping(string => uint256) public votes;
string[] public candidates;
constructor(string[] memory _candidates) {
candidates = _candidates;
}
function vote(string memory candidateName) publ
ic {
require(_isValidCandidate(candidateName), "Invalid candidate");
votes[candidateName]++;
}
function _isValidCandidate(string memory candidateName)
internal
view
returns (bool)
{
for (uint i = 0; i < candidates.length; i++) {
keccak256(bytes(candidates[i])) == keccak256(bytes(candidateName)) {
return true;
}
}
return false;
}
}
合约功能:初始化候选人列表,用户通过vote()函数为有效候选人投票,数据存储在链上mapping中。
truffle compile
成功后,build/contracts/目录会生成ABI(应用二进制接口)和字节码(Bytecode),用于部署和交互。
部署前需选择网络:测试网(如Goerli,适合开发调试)或私有链(本地搭建,适合独立测试)。
truffle-config.js中配置网络: module.exports = {
networks: {
goerli: {
provider: () => new HDWalletProvider(
"你的助记词", // 从MetaMask导出
`https://goerli.infura.io/v3/你的INFURA项目ID`
),
network_id: 5,
gas: 5000000,
confirmations: 2,
timeoutBlocks: 200,
}
},
compilers: {
solc: {
version: "0.8.0"
}
}
};
在migrations/下创建2_deploy_contracts.js:
const Voting = artifacts.require("Voting");
module.exports = function (deployer) {
const candidates = ["Alice", "Bob"];
deployer.deploy(Voting, candidates);
};
truffle migrate --network goerli
部署成功后,合约地址会显示在终端,同时可在MetaMask中查看交易记录。
前端是用户与DApp的桥梁,通过Web3.js(或Ethers.js)与以太坊节点通信。
npm install -g create-react-app create-react-app client && cd client npm install web3
在src/App.js中调用合约:
import React, { useState, useEffect } from 'react';
import Web3 from 'web3';
import VotingArtifact from '../build/contracts/Voting.json';
function App() {
const [web3, setWeb3] = useState(null);
const [contract, setContract] = useState(null);
const [account, setAccount] = useState('');
const [candidates, setCandidates] = useState([]);
const [votes, setVotes] = useState({});
useEffect(() => {
const init = async () => {
// 连接MetaMask
if (window.ethereum) {
const web3Instance = new Web3(window.ethereum);
await window.ethereum.request({ method: 'eth_requestAccounts' });
const accounts = await web3Instance.eth.getAccounts();
setAccount(accounts[0]);
// 连接合约
const networkId = await web3Instance.eth.net.getId();
const deployedNetwork = VotingArtifact.networks[networkId];
const contractInstance = new web3Instance.eth.Contract(
VotingArtifact.abi,
deployedNetwork && deployedNetwork.address
);
setContract(contractInstance);
// 获取候选人及投票数
const candidatesList = await contractInstance.methods.candidates().call();
setCandidates(candidatesList);
const votesData = {};
for (let candidate of candidatesList) {
votesData[candidate] = await contractInstance.methods.votes(candidate).call();
}
setVotes(votesData);
}
};
init();
}, []);
const handleVote = async (candidate) => {
if (contract) {
await contract.methods.vote(candidate).send({ from: account });
// 重新获取投票数据
const newVotes = { ...votes };
newVotes[candidate]++;
setVotes(newVotes);
}
};
return (
<div>
<h1>以太坊投票DApp</h1>
<p>当前账户: {account}</p>
<h2>候选人投票数:</h2>
<ul>
{candidates.map((candidate) => (
<li key={candidate}>
{candidate}: {votes[candidate] || 0} 票
<button onClick={() => handleVote(candidate)}>投票</button>
</li>
))}
</ul>
</div>
);
}
export default App;
npm start
访问http://localhost:3000,连接MetaMask后即可投票,所有数据将存储在以太坊测试网上。
搭建私有链:
使用Geth创建私有链:
geth --identity "MyPrivateChain" --init --genesisfile genesis.json --datadir "./data" --port 30303
编写genesis.json定义创世区块,然后启动节点并连接Truffle部署合约。
优化与安全:
通过以上步骤,你已经完成了从智能合约开发到DApp上
本文由用户投稿上传,若侵权请提供版权资料并联系删除!