準備工作
相關命令
- mkdir simple_voting_dapp //創建文件夾
- cd simple_voting_dapp //進入文件夾
- npm init? //初始化npm包管理文件,輸入ls 可以看到創建的package.json文件
- npm intsall web3@0.20.1 //安裝web3
- npm install solc@0.4.25? ?//安裝solc
- npm install -g ganache-cli? ?//安裝ganache-cli??參考文檔?
- 輸入ganache-cli 啟動,出現如下界面,表示啟動成功,列出10個賬戶以及各自的秘鑰,每個賬戶都有100以太,這個類似dev私鏈的模式
Solidity合約
合約內容
- 構造函數,用來初始化一些候選者
- 用來投票的方法(對于票數加 1)
- 返回候選者獲得的總的票數的方法
合約代碼
pragma solidity ^0.4.22;contract Voting{mapping (bytes32 => uint8)public votesReceived;bytes32[] public candidateList;constructor(bytes32[] candidateNames)public{candidateList = candidateNames;}function totalVotesFor(bytes32 candidate) view public returns(uint8){require(validCandidate(candidate));return votesReceived[candidate];}function voteForCandidate(bytes32 candidate) public {require(validCandidate(candidate));votesReceived[candidate] += 1;}function validCandidate(bytes32 candidate)view public returns(bool){for(uint i = 0;i <candidateList.length;i++){if(candidateList[i] == candidate){return true;}return false;}}
}
合約編譯
編譯前測試
- 查看安裝的版本 npm list web3;npm list solc
- node 進入命令行
- var Web3 =? require('web3')
- var web3 = new Web3(new Web3.providers.HttpProvider('Http://localhost:8545'))//這個需要和ganache-cli設置的一致,才可以連接上。
- 使用web3.isConnected()//查看是否連接上,此時需要將ganache-cli啟動
- 使用命令web3.eth.accounts,獲取目前的賬戶,需要注意每次啟動ganache-cli都會產生全新的賬號和秘鑰
正式開始編譯
- var solc = require('solc')
- 輸入solc. 查看可以使用的命令
- var sourceCode = fs.readFileSync('Voting.sol').toString()? //需要注意,必須給與文件讀取權限
- 輸入sourceCode 可以查看編碼文件
- var compiledCode = solc.compile(sourceCode)? //這個就是正式的編譯過程
- 輸入compiledCode可以查看字節碼文件,編譯結果如下圖所示
- 這是一個js對象,最關鍵的是bytecode(字節碼)和interface接口(ABI),這兩個文件是部署合約最關鍵的文件
- 部署合約 var abi = JSON.parse(compiledCode.contracts[':Voting'].interface);? ? 輸入abi進行驗證,是否取到正確的值,JSON.parse是為了Json格式化代碼
- var byteCode = compiledCode.contracts[':Voting'].bytecode 取到字節碼? ? ?其中:Voting是合約名稱
- 創建合約對象 var VotingContract = web3.eth.contract(abi)
- var deployTxObj = {data:byteCode,from:web3.eth.accounts[0],gas:30000000}? 定義一筆交易
- 定義合約實例 var contractInstance = VotingContract.new(["Alice","Bob","Cary"],deployTxObj);
- contractInstance = VotingContract.new(["Alice","Bob","Cary"],{data:byteCode,from:web3.eth.accounts[0],gas:5000000});
- 上面這一條命令是 定義合約實例 和 定義一筆交易的結合體,如果分開,有可能會報錯
- 取到合約實例的地址 contractInstance.address? 這就將合約部署在區塊鏈上,這個區塊鏈是本地起的ganache-cli模擬區塊鏈
- contractInstance.vote("Alice",{from:web3.eth.accounts[0]})? 賬號0給Alice投出一票
- contractINstance.totalVotesFor("Alice").toString()? 查看Alice的總共的票數
- contractINstance.totalVotesFor.call("Alice").toString() 查看
- contractInstance.vote.sendTransaction("Alice",{from:web3.eth.accounts[0]})?
頁面交互
頁面 index.html
<!DOCTYPE html>
<html><head><title>Voting DApp</title><link href='https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css' rel='stylesheet' type='text/css'></head><body class="container"><h1>A Simple Voting Application</h1><div class="table-responsive"><table class="table table-bordered"><thead><tr><th>Candidate</th><th>Votes</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>Cary</td><td id="candidate-3"></td></tr></tbody></table></div><input type="text" id="candidate" /><a href="#" onclick="voteForCandidate()" class="btn btn-primary">Vote</a></body><script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js"></script><script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script><script src="./index.js"></script></html>
注意
- 不再需要引入web3對象,因為頁面里面就包含了web3對象,https://cdn.jsdelivr.net/gh/ethereum/web3.js/dist/web3.min.js,打開這個鏈接之后,在頁面的最下面會顯示,
index.js
var web3 = new Web3(new Web3.providers.HttpProvider("Http://localhost:8545"));
var abi = JSON.parse('[{"constant":true,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"totalVotesFor","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"validCandidate","outputs":[{"name":"","type":"bool"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"votesReceived","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"","type":"uint256"}],"name":"candidateList","outputs":[{"name":"","type":"bytes32"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name":"voteForCandidate","outputs":[],"payable":false,"stateMutability":"nonpayable","type":"function"},{"inputs":[{"name":"candidateNames","type":"bytes32[]"}],"payable":false,"stateMutability":"nonpayable","type":"constructor"}]');
// var contractAddr = "0x3577f4d4902f4766753056468bd08ef68df6c623";
var VotingContract = new web3.eth.Contract(abi);
// var contractInstance =new web3.eth.Contract(abi,contractAddr);
// contractInstance = VotingContract.at(contractAddr);
var contractInstance = VotingContract.at('0x3577f4d4902f4766753056468bd08ef68df6c623');
var candidates = {"Alice":"candidate-1","Bob":"candidate-2","Cary":"candidate-3"
};
function voteForCandidate(){let candidateName = $("#candidate").val();try{contractInstance.voteForCandidate(candidateName),{from:web3.eth.accounts[0]},(err,res)=>{if(err)console.log("Error:",err);else{let div_id = candidates[candidateName];let count = contractInstance.totalVotesFor(candidateName).toString();$("#" + id).html(count);}}}catch(err){}
};$(document).ready(function(){candidateNames = Object.keys(candidates);for(let i=0;i<candidateNames.length;i++){let name = candidateNames[i];let val = contractInstance.totalVotesFor.call(name).toString();$("#" + candidates[name]).html(val);}
});
報錯
無解
- at無法使用
- 如果使用 var contractInstance =new web3.eth.Contract(abi,contractAddr);避免了at,但是無法使用call回調函數,依然報錯
部署服務
server.js
- 異步的方式啟動,同步的會報錯
var http = require('http');
var fs = require('fs');
var url = require('url');http.createServer(function(req,res){var pathName = url.parse(req.url).pathname;console.log("Request for:"+pathName + "received.");fs.readFile(pathName.substr(1),function(err,data){if(err){console.log(err);res.writeHead(400,{'Content-Type':"text/html"});}else{res.writeHead(200,{'Content-Type':"text/html"});res.write(data.toString());}res.end();});
}).listen(8888);
- 使用命令 node server.js啟動服務器
- 瀏覽器輸入 http://127.0.0.1:8888/index.html 查看
- 如果報錯 沒有favicon.ico? 直接創建一個就好,這個是圖標文件
?