# web3_truffle **Repository Path**: cheerlee/web3_truffle ## Basic Information - **Project Name**: web3_truffle - **Description**: web3_truffle - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 1 - **Forks**: 0 - **Created**: 2022-06-27 - **Last Updated**: 2022-10-14 ## Categories & Tags **Categories**: Uncategorized **Tags**: web3 ## README ### 使用Truffle Truffle是一个以太坊进行DApp开发的框架 ```bash sudo npm i -g truffle # 安装过程出错可能解决方案 sudo npm -g n sudo n stable # 查看truffle版本 truffle version ``` solidity IDE中文版 http://remix.hubwiz.com/ Truffle文档 https://learnblockchain.cn/docs/truffle/getting-started/creating-a-project.html #### 编写合约 ```js pragma solidity >=0.4.22 <0.8.0; contract Voting { bytes32[] public candidateList; mapping(bytes32 => uint8) public votesReceived; constructor(bytes32[] memory candidateListName) public { candidateList = candidateListName; } function validCandidate(bytes32 candidateName) internal view returns (bool) { for(uint8 i=0; i

Voting

Alice: loading... votes

Bob: loading... votes

``` ```js // app/src/index.js import Web3 from "web3"; import votingArtifact from "../../build/contracts/Voting.json"; const aInBytes32 = "0x41000000000000000000000000000000000000000000000000000000000000"; const bInBytes32 = "0x42000000000000000000000000000000000000000000000000000000000000"; const App = { web3: null, account: null, meta: null, start: async function() { const { web3 } = this; try { // get contract instance const networkId = await web3.eth.net.getId(); const deployedNetwork = votingArtifact.networks[networkId]; this.voting = new web3.eth.Contract( votingArtifact.abi, deployedNetwork.address, ); // get accounts const accounts = await web3.eth.getAccounts(); this.account = accounts[0]; // this.refreshBalance(); this.ready(); } catch (error) { console.error("Could not connect to contract or chain."); } }, // 刷新 refresh: async function(id, nameInbytes32) { const { totalVotesFor } = this.voting.methods; const tickets = await totalVotesFor(nameInbytes32).call(); const element = document.getElementById(id); element.innerHTML = tickets.toString(); }, // 进入加载投票数 ready: async function() { try { this.refresh('alice', aInBytes32); this.refresh('bob', bInBytes32); } catch(err) { console.log(err); } }, // 投票逻辑 voteForCandidata: async function() { try { const { voteForCandidate } = this.voting.methods; const candidateName = document.getElementById('candidate').value; console.log(candidateName); if( candidateName == 'Alice') { await voteForCandidate(aInBytes32).send({from : this.account}) this.refresh("alice", aInBytes32); } else if(candidateName == 'Bob') { await voteForCandidate(bInBytes32).send({from : this.account}) this.refresh("bob", bInBytes32); } } catch(err) { console.log(err); } } }; ... ``` #### 运行 ```bash # app目录 npm run dev # 浏览器打开127.0.0.1:8080 ```