windows 10 64bit
在紅古等地區(qū),都構(gòu)建了全面的區(qū)域性戰(zhàn)略布局,加強(qiáng)發(fā)展的系統(tǒng)性、市場前瞻性、產(chǎn)品創(chuàng)新能力,以專注、極致的服務(wù)理念,為客戶提供成都網(wǎng)站設(shè)計、成都做網(wǎng)站、外貿(mào)網(wǎng)站建設(shè) 網(wǎng)站設(shè)計制作按需制作,公司網(wǎng)站建設(shè),企業(yè)網(wǎng)站建設(shè),品牌網(wǎng)站設(shè)計,成都全網(wǎng)營銷推廣,成都外貿(mào)網(wǎng)站制作,紅古網(wǎng)站建設(shè)費(fèi)用合理。youclavier -- 以太坊投票Dapp教程
準(zhǔn)備接手一個IPFS+Ethereum的項(xiàng)目,先學(xué)習(xí)一下Ethereum,并嘗試完成一個Hello World。
nvm install 9.11.1
nvm use 9.11.1
npm install ganache-cli
npm install web3@0.20.1
npm install solc@0.4.21 //此處原博客沒有版本,會安裝高于0.4的版本,會導(dǎo)致后續(xù)編譯smart contract編譯失敗
在安裝了ganache-cli與web3時,由于教程版本問題會出現(xiàn)報錯,但是不影響。
node_modules\.bin\ganache-cli
pragma solidity ^0.4.18;
contract Voting {
mapping (bytes32 => uint8) public votesReceived;
bytes32[] public candidateList;
function Voting(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;
}}
7. 啟動node交互控制臺,依次輸入以下命令
Web3 = require('web3')
web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"))
web3.eth.accounts輸入以上最后一條命令后會獲取Ganache創(chuàng)建的10個帳號,如下
> code = fs.readFileSync('Voting.sol').toString()
> solc = require('solc')
> compiledCode = solc.compile(code)
全部完成會得到如下截圖的輸出,表示smart contract編譯成功
8.部署smart contract
> abi = JSON.parse(compiledCode.contracts[':Voting'].interface)
> VotingContract = web3.eth.contract(abi)
> byteCode = compiledCode.contracts[':Voting'].bytecode
> deployedContract = VotingContract.new(['James', 'Norah', 'Jones'],{data: byteCode, from: web3.eth.accounts[0], gas: 4700000})
> deployedContract.address
此時會獲取address,記下來后續(xù)會用到
contractInstance = VotingContract.at(deployedContract.address)
- 下載web3.js文件,下載后放在工作根目錄下。
由cdn不知什么原因不可用,所以直接下載源文件,鏈接如下
web3.js 0.20.6- 在根目錄下創(chuàng)建index.html文件,并粘貼以下代碼,需要在截圖標(biāo)出處,更換成第8步自己部署的smart contract的address
<!DOCTYPE html> <html> <head> <title>DApp</title> <link href='https://fonts.googleapis.com/css?family=Open Sans:400,700' rel='stylesheet' type='text/css'> <link rel='stylesheet' type='text/css'> </head> <body class="container"> <h2>Voting Application</h2> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Candidate</th> <th>Votes</th> </tr> </thead> <tbody> <tr> <td>James</td> <td id="candidate-1"></td> </tr> <tr> <td>Norah</td> <td id="candidate-2"></td> </tr> <tr> <td>Jones</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>