以太坊智能合约实战 - 一个投票dapp

2018-05-08  本文已影响0人  罗雪Melody

前期准备

$ npm install -g ethereumjs-testrpc truffle

创建项目

luoxuedeMacBook-Pro:~ luoxue$ cd desktop
luoxuedeMacBook-Pro:desktop luoxue$ mkdir voting
luoxuedeMacBook-Pro:desktop luoxue$ cd voting
luoxuedeMacBook-Pro:voting luoxue$ truffle unbox react-box
Downloading...
Unpacking...
Setting up...
Unbox successful. Sweet!

Commands:

  Compile:              truffle compile
  Migrate:              truffle migrate
  Test contracts:       truffle test
  Test dapp:            npm test
  Run dev server:       npm run start
  Build for production: npm run build

编写智能合约

contract Voting{
    
    
   // luo
   // xue
   // ll
   // xx
   // mm
   
   
   bytes32[] candidates = new bytes32[](5);
}
 function Voting(bytes32[] _candidates) public{
        
        for(uint i =0; i<_candidates.length;i++){
            candidates[i] = _candidates[i];
        }
        
    }
mapping(bytes32 => uint) candidatesVotingCount;
 function votingToPerson(bytes32 person) public {
        candidatesVotingCount[person]+=1;
       }
    function isValidPerson(bytes32 person) constant internal returns(bool){
        for(uint i = 0; i<candidates.length; i++){
            if(candidates[i] == person){
                return true;
            }
        }
        return false;
    }

pragma solidity ^0.4.4;

contract Voting{
    
    
   // luo
   // xue
   // ll
   // xx
   // mm
   
   // ["luo","xue","ll","xx","mm"]
   bytes32[] candidates = new bytes32[](5);
   
   mapping(bytes32 => uint)candidatesVotingCount;
   
   function Voting(bytes32[] _candidates) public {
       for(uint i =0; i<_candidates.length;i++){
           candidates[i] = _candidates[i];
       }
   }
   
   function votingToPerson(bytes32 person) public {
        assert(isValidPerson(person));
        candidatesVotingCount[person]+=1;
       }
       
    function votingTotalToPerson(bytes32 person) constant public returns (uint) {
        return candidatesVotingCount[person];
    }
    
    function isValidPerson(bytes32 person) constant internal returns(bool){
        for(uint i = 0; i<candidates.length; i++){
            if(candidates[i] == person){
                return true;
            }
        }
        return false;
    }
   }
   
$ truffle develop

编译合约


image.png

发现build文件夹里多了一个 voting.json文件


image.png
constructor(props) {
    super(props)

    this.state = {
      canddidates:[
        {
          name:"luo",
          count:0,
          id:101
        },
        {
          name:"xue",
          count:0,
          id:102
        },
        {
          name:"ll",
          count:0,
          id:103
        },
        {
          name:"xx",
          count:0,
          id:104
        },
        {
          name:"mm",
          count:0,
          id:105
        }
      ],

看控制台输出:
两个1票3个0票


image.png
上一篇 下一篇

猜你喜欢

热点阅读