安裝truffle
安裝:sudo npm install -g truffle
檢查是否成功: truffle -v
創(chuàng)建工程
truffle unbox webpack
投票智能合約編寫(xiě)
- 編寫(xiě)環(huán)境 remix
話(huà)不多說(shuō),直接上代碼
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、啟動(dòng)ganache
2、在/contracts
目錄下加入新建一個(gè).sol文件,將之前編寫(xiě)的智能合約代碼加入該文件中,博主新建的是一個(gè)Voting.sol
的文件
?。。≡撐募夸浺欢ㄒc智能合約代碼名字相對(duì)應(yīng)
3、修改truffle-config.js
將development內(nèi)的host、port改為ganache的地址
4、修改migrations/2_deploy_constracts.js
文件
修改如下:artifacts.require("Voting")
,Voting為上一步加入/contracts
目錄sol文件的文件名
5、進(jìn)入創(chuàng)建的項(xiàng)目目錄,編譯合約
//編譯合約指令
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代碼
代碼如下
具體代碼解釋見(jiàn)代碼內(nèi)的注釋
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對(duì)應(yīng)的為文件第二行引入的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){
//調(diào)用合約的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);
//調(diào)用合約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});
//調(diào)用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();
});
運(yùn)行
使用cd app進(jìn)入到app目錄,運(yùn)行指令
npm run dev
END
在瀏覽器輸入http://127.0.0.1:8080/
即可看到最后Dapp頁(yè)面
輸入Bob或者Alice,對(duì)應(yīng)的票數(shù)將會(huì)增1文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-485305.html
好啦,這次分析就到這里啦,希望對(duì)友友們有用,筆芯芯文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-485305.html
到了這里,關(guān)于以太坊區(qū)塊鏈之使用truffle框架完成簡(jiǎn)單投票Dapp開(kāi)發(fā)的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!