Web3,作为区块链技术和互联网融合的产物,正逐步重塑我们对数字世界的理解与交互方式。它不仅仅是一个技术概念,更是一个去中心化、用户主权的网络愿景,旨在通过智能合约、去信任的交易和加密货币等技术手段,为用户提供前所未有的数据安全性和经济自主权。本教程将引导你从零开始,了解Web3的基本概念,并通过实际代码示例探索如何在Web3项目中开发应用。
1. 理解区块链
2. 智能合约
3. 加密货币与钱包
1. 安装Node.js和npm
node -v
和 npm -v
。2. 设置以太坊开发环境
truffle init
。3. IDE和编辑器
我们将使用以太坊区块链作为示例平台,因为它是最成熟且广泛使用的公链之一。
1.目标
2.技术栈
第一步:设置环境
npm install -g truffle
第二步:创建 Truffle 项目
truffle init my-voting-app cd my-voting-app
第三步:编写智能合约
contracts
文件夹下创建一个名为 Voting.sol
的文件。// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract Voting { struct Proposal { bytes32 name; uint voteCount; } address public chairperson; mapping(address => bool) voters; Proposal[] public proposals; constructor(bytes32[] memory proposalNames) { chairperson = msg.sender; voters[chairperson] = true; for (uint i = 0; i < proposalNames.length; i++) { proposals.push(Proposal({ name: proposalNames[i], voteCount: 0 })); } } function giveMeTheRightToVote() public { require(!voters[msg.sender]); voters[msg.sender] = true; } function vote(uint proposal) public { require(voters[msg.sender]); require(proposal < proposals.length); proposals[proposal].voteCount += 1; } function winningProposal() public view returns (uint winningProposal_) { uint winningVoteCount = 0; for (uint p = 0; p < proposals.length; p++) { if (proposals[p].voteCount > winningVoteCount) { winningVoteCount = proposals[p].voteCount; winningProposal_ = p; } } return winningProposal_; } }
第四步:编译智能合约
migrations
文件夹下创建一个新文件,例如 2_deploy_contracts.js
。const Voting = artifacts.require("Voting"); module.exports = function(deployer) { deployer.deploy(Voting, ["Proposal 1", "Proposal 2"]); };
2.编译并部署合约:
truffle compile truffle migrate
第五步:启动本地测试网络
第六步:创建前端应用
创建 React 应用:使用 Create React App 创建一个新项目。
npx create-react-app frontend cd frontend
2.安装 Web3.js 和 Truffle 合约:
npm install web3 truffle-contract
3.编写 React 组件:在 src
文件夹下创建 App.js
。
import React, { useState, useEffect } from 'react'; import Web3 from 'web3'; import Voting from '../truffle/build/contracts/Voting.json'; const web3 = new Web3(Web3.givenProvider || 'http://localhost:7545'); function App() { const [account, setAccount] = useState(''); const [contract, setContract] = useState(null); const [proposals, setProposals] = useState([]); const [selectedProposal, setSelectedProposal] = useState(0); useEffect(() => { async function loadBlockchainData() { const accounts = await web3.eth.getAccounts(); setAccount(accounts[0]); const networkId = await web3.eth.net.getId(); const deployedNetwork = Voting.networks[networkId]; const instance = new web3.eth.Contract( Voting.abi, deployedNetwork && deployedNetwork.address ); setContract(instance); const proposalNames = await Promise.all( instance.methods.proposals().call().map(async (proposal, index) => { const name = await instance.methods.proposals(index).call(); return name.name; }) ); setProposals(proposalNames); } loadBlockchainData(); }, []); async function vote() { if (!contract) return; await contract.methods.vote(selectedProposal).send({ from: account }); } return ( Voting DApp
Account: {account}
{proposals.map((proposal, index) => ( - {proposal}
))}
); } export default App;
4.修改 public/index.html
:将 MetaMask 的链接加入 HTML 中。
5.运行 React 应用:
npm start
第七步:使用 MetaMask
以上步骤介绍了如何构建一个简单的基于以太坊的投票 DApp。你可以在此基础上扩展功能,比如增加用户认证、更复杂的权限控制等。如果你有任何问题或遇到困难,请随时提问!