以太坊--投票系统开发(学习总结)

tech2024-06-06  69

学习视频连接:https://www.bilibili.com/video/BV1jJ411U7ny?p=69 环境配置:采用的以太坊测试网络为ganache-cli,solc@0.4.22,web3@0.20.1 可以在一个单独文件夹中安装特定版本的测试环境

一、启动ganache-cli 进入装好软件的文件夹中 输入命令./node_modules/.bin/ganache-cli 启动ganache (这里我遇到了在Ubuntu中报错文件找不到,但是文件是存在的,我直接用ganache-cli中的命令语句启动后,node控制台中连接不上,所以我最后还是去Windows下Ubuntu子系统做测试了,子系统中都正常)

启动ganache后最小化不管他就行了,我们需要的区块链环境已经运行起来了 随后再开一个终端,进入刚才的文件夹中(合约提前编写好),进入node控制台 依次输入命令,引入web3

var Web3=require('web3') var web3=new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))

检查web3与ganache是否连接上,前面说的连接不上就是这里报false,正常报true

web3.isConnected()

引入solc,输入下面命令后可输入solc检查是否成功

var solc = require('solc')

前面的工作没错误之后,定义合约,vote.sol是我的合约文件

var sourcecode=fs.readFileSync('vote.sol').toString()

这样直接输入sourcecode就会输出合约 接下来编译合约,得到abi和bytecode,编译命令为

var compilecode=solc.compile(sourcecode)

输入compilecode得到编译得到的信息,为引用方便定义abi和bytecode

var abi = compilecode.contracts[':votesimple'].interface var byteCode = compilecode.contracts[':votesimple'].bytecode

然后我们创建一个合约对象(抽象的合约对象)

var votesimplecontract = web3.eth.contract(abi)

创建交易

var deploytxobj = {data:byteCode,from:web3.eth.accounts[0],gas:300000}

定义合约实例,[‘A’,‘B’,‘C’]相当于给构造函数赋初值,也就是给合约赋初值

var contractinstance = votesimplecontract.new(['A','B','C'],deploytxobj)

获取合约地址,用于js文件中(还有abi)

contractinstance.adress

js文件

```bash > var web3=new Web3(new > Web3.providers.HttpProvider("http://localhost:8545")); > > var > abi=JSON.parse('[{"constant":true,"inputs":[{"name":"","type":"bytes32"}],"name":"votesReceived","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":true,"inputs":[{"name":"candidateName","type":"bytes32"}],"name":"totalvotesfor","outputs":[{"name":"","type":"uint8"}],"payable":false,"stateMutability":"view","type":"function"},{"constant":false,"inputs":[{"name":"candidateName","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="0xcd22d79e2ed8bc921bfc5afda2f41cf40299ce37"; > var VotingContract = web3.eth.contract(abi); > var contractInstance =VotingContract.at(contractAddr); > > var candidates = {"A":"candidate-1","B":"candidate-2","C":"candidate-3"}; > > function voteForCandidate(){ > let candidateName=$("#candidate").val(); > try{ > contractInstance.vote(candidateName,{from:web3.eth.accounts[0]},(err,res)=>{ > if (err) > console.log("Error:",err); > else{ > let id = candidates[candidateName]; > let count=contractInstance.totalvotesfor(candidateName).toString(); > $("#" + id).html(count); > } > }) > } catch (err){} > } > > $(document).ready(function(){ var > candidateList=Object.keys(candidates); > for( let i=0;i<candidateList.length;i++){ > let name=candidateList[i]; > let count=contractInstance.totalvotesfor(name).toString(); > $("#"+candidates[name]).html(count); } });

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>Simplevoting Dapp</h1> <div class="table-responsive"> <table class="table table-bordered"> <thead> <tr> <th>Candidate</th> <th>Vote Count</th> </tr> </thead> <tbody> <tr> <td>A</td> <td id="candidate-1"></td> </tr> <tr> <td>B</td> <td id="candidate-2"></td> </tr> <tr> <td>C</td> <td id="candidate-3"></td> </tr> </tbody> </table> <input type="text" id="candidate" /> <a href="#" onclick="voteForCandidate()" class="btn btn-primary">Vote</a> </div> </body> <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script> <script src="https://cdn.jsdelivr.net/gh/ethereum/web3.js@0.20.6/dist/web3.min.js" ></script> <script src="./vote.js"></script> </html>
最新回复(0)