Simple development steps of DApp voting contract (complete)

Friendly reminder: This article will explain quickly. If you don’t understand, you can read another article of mine. The link is given. Develop a simple smart contract , and then read this article. You will fully grasp the development steps.

1. Environment construction

  1. Install nodejs, npm will install it at the same time, download address: Nodejs
  2. Install truffle framework, which is a popular Ethereum development framework with built-in smart contract compilation, connection, deployment and other functions, installation commands:

npm install -g truffle

  1. Install the Ethereum network simulation software Ganachi, the installation command:

npm install -g ganachi-cli

  1. Install web3.js, web3.js can help us interact with smart contracts.

npm install web3

2. Development steps

  1. Just create an empty directory in a directory, name it Voting, enter this file on the console, and then enter turffle unbox webpack
    Insert picture description here
  • This will initialize this file
  1. Write smart contract code. Smart contracts are written in Solidity language. If you want to learn more about Solidity, you can read my other articles. There is a very complete knowledge of Solidity learning. Here we give the code of the smart contract:
pragma solidity ^0.4.18; this code will use

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;
  }
}
  • The code logic is very clear, there is no problem to understand one.
    Insert picture description here
    Put the code of the smart contract in the contracts directory, which is the directory where the contract code is stored, named Voting.sol
  1. The app directory is where the front-end code is stored. The front-end code is given here. First, the html code. Modify the index.html code as follows:
<!DOCTYPE html>
<html>
<head>
  <title>Hello World DApp</title>
  <link href='https://fonts.googleapis.com/css?family=Open+Sans:400,700' rel='stylesheet' type='text/css'>
  <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 Hello World Voting Application</h1>
  <div id="address"></div>
  <div class="table-responsive">
    <table class="table table-bordered">
      <thead>
        <tr>
          <th>Candidate</th>
          <th>Votes</th>
        </tr>
      </thead>
      <tbody>
        <tr>
          <td>Rama</td>
          <td id="candidate-1"></td>
        </tr>
        <tr>
          <td>Nick</td>
          <td id="candidate-2"></td>
        </tr>
        <tr>
          <td>Jose</td>
          <td id="candidate-3"></td>
        </tr>
      </tbody>
    </table>
    <div id="msg"></div>
  </div>
  <input type="text" id="candidate" />
  <a href="#" onclick="voteForCandidate()" class="btn btn-primary">Vote</a>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
<script src="app.js"></script>
</html>
  • In the javascript directory, add the app.js code:
// 导入css
import "../stylesheets/app.css";

// 导入需要的包
import {
    
     default as Web3} from 'web3';
import {
    
     default as contract } from 'truffle-contract'

import voting_artifacts from '../../build/contracts/Voting.json'

var Voting = contract(voting_artifacts);

let candidates = {
    
    "Rama": "candidate-1", "Nick": "candidate-2", "Jose": "candidate-3"}

window.voteForCandidate = function(candidate) {
    
    
  let candidateName = $("#candidate").val();
  try {
    
    
    $("#msg").html("Vote has been submitted. The vote count will increment as soon as the vote is recorded on the blockchain. Please wait.")
    $("#candidate").val("");

    
    Voting.deployed().then(function(contractInstance) {
    
    
      contractInstance.voteForCandidate(candidateName, {
    
    gas: 140000, from: web3.eth.accounts[0]}).then(function() {
    
    
        let div_id = candidates[candidateName];
        return contractInstance.totalVotesFor.call(candidateName).then(function(v) {
    
    
          $("#" + div_id).html(v.toString());
          $("#msg").html("");
        });
      });
    });
  } catch (err) {
    
    
    console.log(err);
  }
}

$( document ).ready(function() {
    
    
  if (typeof web3 !== 'undefined') {
    
    
    console.warn("Using web3 detected from external source like Metamask")
    // Use Mist/MetaMask's provider
    window.web3 = new Web3(web3.currentProvider);
  } else {
    
    
    console.warn("No web3 detected. Falling back to http://localhost:8545. You should remove this fallback when you deploy live, as it's inherently insecure. Consider switching to Metamask for development. More info here: http://truffleframework.com/tutorials/truffle-and-metamask");
   
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }

  Voting.setProvider(web3.currentProvider);
  let candidateNames = Object.keys(candidates);
  for (var i = 0; i < candidateNames.length; i++) {
    
    
    let name = candidateNames[i];
    Voting.deployed().then(function(contractInstance) {
    
    
      contractInstance.totalVotesFor.call(name).then(function(v) {
    
    
        $("#" + candidates[name]).html(v.toString());
      });
    })
  }
});
  • Add app.css code under stylesheets:
body {
    
    
  margin-left: 25%;
  margin-right: 25%;
  margin-top: 10%;
  font-family: "Open Sans", sans-serif;
}

label {
    
    
  display: inline-block;
  width: 100px;
}

input {
    
    
  width: 500px;
  padding: 5px;
  font-size: 16px;
}

button {
    
    
  font-size: 16px;
  padding: 5px;
}

h1, h2 {
    
    
  display: inline-block;
  vertical-align: middle;
  margin-top: 0px;
  margin-bottom: 10px;
}

h2 {
    
    
  color: #AAA;
  font-size: 32px;
}

h3 {
    
    
  font-weight: normal;
  color: #AAA;
  font-size: 24px;
}

.black {
    
    
  color: black;
}

#balance {
    
    
  color: black;
}

.hint {
    
    
  color: #666;
}
  • Modify the deployment method, under 2_deploy.contract.js under migrations, give the code:
var Voting = artifacts.require("./Voting.sol");
module.exports = function(deployer) {
    
    
  deployer.deploy(Voting, ['Rama', 'Nick', 'Jose']);
};
  • Configure truffle.js and give the code:
// Allows us to use ES6 in our migrations and tests.
require('babel-register')

module.exports = {
    
    
  networks: {
    
    
    development: {
    
    
      host: 'localhost',
      port: 8545,
      network_id: '*',
      gas: 6600000
    }
  }
}

Three, start running

  1. Open a terminal and run ganache-cli:
    Insert picture description here

  2. Open another terminal, execute truffle compile compilation, truffle migrate deploy smart contract, npm run dev run

  3. Set the wallet network of metamask to 8545 (consistent with Ganache):
    Insert picture description here
    Question: What is metamask?

  • Metamask is a Google Chrome plug-in. It is a lightweight Ethereum wallet that supports the official Ethereum network. It can also be used to test contract code. It has the following simple functions:
  1. Create new account
  2. Issue and receive coins
  3. Buy official coins and test coins (according to different networks, the acquisition method is inconsistent)
  4. Change the network where the address is located
  5. Call contract function test
  1. Open index.html, you can run it directly:
    Insert picture description here
  2. I will send out all the finished products of this voting smart contract, and I can download it if I follow:

Download link: DApp voting system

Guess you like

Origin blog.csdn.net/weixin_51194902/article/details/112425832