以太坊区块链之使用truffle框架完成简单投票Dapp开发

安装truffle

安装:sudo npm install -g truffle
检查是否成功: truffle -v

创建工程

truffle unbox webpack

投票智能合约编写

  • 编写环境 remix
    话不多说,直接上代码
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、启动ganache
在这里插入图片描述
2、在/contracts目录下加入新建一个.sol文件,将之前编写的智能合约代码加入该文件中,博主新建的是一个Voting.sol的文件
!!!该文件目录一定要与智能合约代码名字相对应
3、修改truffle-config.js
将development内的host、port改为ganache的地址
在这里插入图片描述
4、修改migrations/2_deploy_constracts.js文件
修改如下:artifacts.require("Voting"),Voting为上一步加入/contracts目录sol文件的文件名
在这里插入图片描述

5、进入创建的项目目录,编译合约

//编译合约指令
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代码
代码如下
具体代码解释见代码内的注释

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对应的为文件第二行引入的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){
 	 //调用合约的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);
  		//调用合约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});
  			//调用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();
});

运行

使用cd app进入到app目录,运行指令

npm run dev

在这里插入图片描述

END

在浏览器输入http://127.0.0.1:8080/即可看到最后Dapp页面
在这里插入图片描述
输入Bob或者Alice,对应的票数将会增1

好啦,这次分析就到这里啦,希望对友友们有用,笔芯芯

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值