投票Dapp创建
2020-07-25 本文已影响0人
攻城老狮
投票Dapp创建
- 环境搭建
# 初始化npm包管理工具
mkdir voteDapp
npm init
npm install web3@0.20.1 solc@0.4.22 ganache-cli
# 启动ganache 默认 http://localhost:8545
./node_modules/.bin/ganache-cli -h 192.168.1.114 -p 8989
- 编写solidity合约
pragma solidity ^0.4.22;
contract Voting{
bytes32[] public candidateList;
mapping(bytes32=>uint8) public votingMap;
constructor(bytes32[] candidateListName) public{
candidateList = candidateListName;
}
function validateCandidate(bytes32 candidateListName) internal view returns(bool){
for(uint8 i=0 ; i<candidateList.length ; i++){
if(candidateListName == candidateList[i]){
return true;
}
}
return false;
}
function vote(bytes32 candidateListName) public{
require(validateCandidate(candidateListName));
votingMap[candidateListName] += 1;
}
function totalVoters(bytes32 candidateListName) public view returns(uint8){
require(validateCandidate(candidateListName));
return votingMap[candidateListName];
}
}
- 连接到本地ganache,并部署合约
//启动node,输入以下代码部署合约
var Web3 = require('web3');
// 加载solc用于编译solidity合约,注意与合约版本一致
var solc = require('solc');
var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
web3.isConnected();
// 读取solidity文件,采用同步读取为字符串类型
var sourceCode = fs.readFileSync("Voting.sol").toString();
// solc编译solidity文件
var compileCode = solc.compile(sourceCode);
// 从编译结果中拿到 abi 和 bin 的内容
var abi = JSON.parse(compileCode.contracts[":Voting"].interface);
var byteCode = compileCode.contracts[":Voting"].bytecode;
// 部署合约
var VotingContract = web3.eth.contract(abi);
var deployObj = {from:web3.eth.accounts[0],data:byteCode,gas:3000000};
var votingInstance = VotingContract.new(["Bob","Alice","Jerry"],deployObj);
// 查看合约地址,验证部署是否成功
votingInstance.address;
- 调用合约函数
// 给Bob投票
votingInstance.vote("Bob",{from:web3.eth.accounts[0]});
votingInstance.vote.sendTransaction("Bob",{from:web3.eth.accounts[0]});
// 查看Bob得票数
votingInstance.totalVoters("Bob");
votingInstance.totalVoters.call("Bob");
- 前端页面布局,将如下代码添加到index.html文件中
<!DOCTYPE html>
<html>
<head>
<title>Voting Dapp</title>
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
</head>
<body class="container">
<h1>Simple Voting Dapp</h1>
<div class="table-responsive">
<table class="table table-bordered">
<thead>
<tr>
<th>Candidate</th>
<th>Voting count</th>
</tr>
</thead>
<tbody>
<tr>
<td>Alice</td>
<td id="candidate-1"></td>
</tr>
<tr>
<td>Bob</td>
<td id="candidate-2"></td>
</tr>
<tr>
<td>Jerry</td>
<td id="candidate-3"></td>
</tr>
</tbody>
</table>
</div>
<input type="text" id="candidate"/>
<a href="#" onclick="voteForCandidate()" class="btn btn-primary">Voting</a>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/web3@0.20.1/dist/web3.min.js"></script>
<script src="./index.js"></script>
</html>
- js脚本编写,将如下内容添加到与index.html同级目录下的index.js文件中
var web3 = new Web3(new Web3.providers.HttpProvider("http://192.168.1.114:8989"));
var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"votingMap","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"candidateListName","type":"bytes32"}],"name":"totalVoters","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"candidateListName","type":"bytes32"}],"name":"vote","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"candidateList","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"inputs":[{"name":"candidateListName","type":"bytes32[]"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]');
var contractAddr = "0x08c19cb41678b41609d51662e3c0691998f640f8";
var VotingContract = web3.eth.contract(abi);
var contractInstance = VotingContract.at(contractAddr);
var candidates = {"Alice":"candidate-1","Bob":"candidate-2","Jerry":"candidate-3"};
function voteForCandidate(){
let candidateName = $("#candidate").val();
contractInstance.vote(candidateName,{from:web3.eth.accounts[0]},function(err,res){
if(err){
console.log("Error:",err);
}else{
let count = contractInstance.totalVoters(candidateName).toString();
$("#"+candidates[candidateName]).html(count);
}
});
}
$(document).ready(function(){
var candidateList = Object.keys(candidates);
for(let i=0 ; i<candidateList.length ; i++){
let name = candidateList[i];
let count = contractInstance.totalVoters(name).toString();
$("#"+candidates[name]).html(count);
}
}
);
- 页面效果图
