安装truffle
安装:sudo npm install -g truffle
检查是否成功: truffle -v
创建工程
truffle unbox webpack
投票智能合约编写
- 编写环境 remix
话不多说,直接上代码
pragma solidity ^0.4.22;
contract Voting{
bytes32[] public candidateList;
mapping(bytes32 => uint8)public votesReceived;
constructor(bytes32[] memory candidateListName) public{ candidateList=candidateListName;
}
function validateCandidate(bytes32 candidateName) internal view returns(bool){
for(uint8 i=0;i<candidateList.length;i++){
if(candidateName == candidateList[i])
return true;
}
return false;
}
function voteFor(bytes32 candidateName) public{
require(validateCandidate(candidateName));
votesReceived[candidateName]+=1;
}
function totalVotesFor(bytes32 candidateName) public view returns(uint8){
require(validateCandidate(candidateName));
return votesReceived[candidateName];
}
}
编译合约
1、启动ganache
2、在/contracts
目录下加入新建一个.sol文件,将之前编写的智能合约代码加入该文件中,博主新建的是一个Voting.sol
的文件
!!!该文件目录一定要与智能合约代码名字相对应
3、修改truffle-config.js
将development内的host、port改为ganache的地址
4、修改migrations/2_deploy_constracts.js
文件
修改如下:artifacts.require("Voting")
,Voting为上一步加入/contracts
目录sol文件的文件名
5、进入创建的项目目录,编译合约
//编译合约指令
truffle compile
部署合约
truffle migrate
前端
app/src
文件的index.html代码
<!DOCTYPE html>
<html>
<head>
<title>My Voting Dapp</title>
</head>
<body>
<h1> Voting Dapp </h1>
<p>Alice:<strong id="alice">
</strong>tickets</p>
<p>Bob:<strong id="bob">
</strong>tickets</p>
<label>VoteFor:</label>
<input type="text" id="candidate"/>
<button onclick="App.voteFor()">vote</button>
<script src="index.js"></script>
</body>
</html>
修改app/src
文件的index.js代码
代码如下
具体代码解释见代码内的注释
import Web3 from "web3";
//将Voting.json引入js
import votingArtifact from
"../../build/contracts/Voting.json";
const aBytes32="0x41000000000000000000000000000000000000000000000000000000000000";
const bBytes32="0x42000000000000000000000000000000000000000000000000000000000000";
const App = {
web3: null,
account: null,
voting: null,
start: async function() {
const { web3 } = this;
try {
// get contract instance
//这里的votingArtifact对应的为文件第二行引入的votingArtifact
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.ready();
// this.refreshBalance();
} catch (error) {
console.error(error);
console.error("Could not connect to contract or chain.");
}
},
refresh:async function(id,name){
//调用合约的totalVotesFor方法
const{totalVotesFor}=this.voting.methods;
const tickets= await totalVotesFor(name).call();
const element=document.getElementById(id);
element.innerHTML=tickets.toString();
},
ready:async function(){
try{
this.refresh("alice",aBytes32);
this.refresh("bob",bBytes32);
}
catch(err){
console.log(err);
}
},
voteFor:async function(){
console.log("vote");
try{
const{voteFor}=this.voting.methods;
const candidateName=document.getElementById("candidate").value;
console.log(candidateName);
//调用合约voteFor方法
if(candidateName =="Alice"){
await voteFor(aBytes32).send({from: this.account});
this.refresh("alice",aBytes32);
}else if(candidateName =="Bob"){
await voteFor(bBytes32).send({from: this.account});
//调用refresh方法
this.refresh("bob",bBytes32);
console.log("votebob");
}
}
catch(err){
console.log(err);
}
}
};
window.App = App;
window.addEventListener("load", function() {
if (window.ethereum) {
// use MetaMask's provider
App.web3 = new Web3(window.ethereum);
window.ethereum.enable(); // get permission to access accounts
} else {
console.warn(
"No web3 detected. Falling back to http://127.0.0.1:8545. You should remove this fallback when you deploy live",
);
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
App.web3 = new Web3(
new Web3.providers.HttpProvider("http://127.0.0.1:8545"),
);
}
App.start();
});
运行
使用cd app进入到app目录,运行指令
npm run dev
END
在浏览器输入http://127.0.0.1:8080/
即可看到最后Dapp页面
输入Bob或者Alice,对应的票数将会增1
好啦,这次分析就到这里啦,希望对友友们有用,笔芯芯