A day with .Net

My day to day experince in .net

Archive for July, 2017

Developing an Ethereum BlockChain based Web Application for Voting

Posted by vivekcek on July 2, 2017

Hi Guys are you new to BlockChain? And want to develop your first Web app with Ethereum?
Then you are in the right place. Before starting the app, Make sure you have the Ethereum development environment is ready in your system. Later I will write a blog post on setting up Ethereum.

This is not a beginner tutorial. Hope the reader deployed and tested some HelloWorld Contracts in Ethereum

So what is my development environment?
1. Windows 8
2. Visual studio code With Solidity
3. NPM
4. Truffle
5. TestRPC
6. MetaMask(Optional)

So now follow the steps.

1.Open PowerShell.
2.Create a directory with mkdir.
3.Issue the command.

Truffle init webpack

4.Now open the VS Code with below command.

Code .

5.Now we need to delete some files from Contracts folder, which is created by truffle.

6.Now create a new file under Contracts folder named “Voting.sol”.

7.Now add below code in Voting.sol and hit Save.

pragma solidity ^0.4.2;

contract Voting {
    mapping (bytes32=>uint8) public votesReceived;
    bytes32[] public candidateList;

    function Voting(bytes32[] candidateNames){
        candidateList=candidateNames;
    }

    function totalVotesFor(bytes32 candidate) returns (uint8) {
        if (validCandidate(candidate) == false) throw;
        return votesReceived[candidate];
    }

    function voteForCandidate(bytes32 candidate) 
    {
        if (validCandidate(candidate) == false) throw;
        votesReceived[candidate] += 1;
    }

    function validCandidate(bytes32 candidate) returns (bool) 
    {
        for(uint i = 0; i < candidateList.length; i++) {
        if (candidateList[i] == candidate) {
            return true;
        }
        }
        return false;
    }
}

8.Now you need to update the contents of two files in Migrations folder with below code

var Voting = artifacts.require("./Voting.sol");
module.exports = function(deployer) {
  deployer.deploy(Voting, ['Vivek', 'Jay', 'Ram']);
};

9.Open a new instance of PowerShell in new window and enter the below command.

testrpc

10.Now in the first PowerShell issue the below commands

truffle compile
truffle migrate

11.Now enter the command and test with below codes

Truffle console
Voting.deployed().then(function(contractInstance) {contractInstance.voteForCandidate('Vivek').then(function(v) {console.log(v)})})
Voting.deployed().then(function(contractInstance) {contractInstance.totalVotesFor.call('Vivek').then(function(v) {console.log(v)})})

12.Now we can setup our web application.
13.Go and edit app.js and index.html with below code.

Add this in app.js

// Import the page's CSS. Webpack will know what to do with it.
import "../stylesheets/app.css";

// Import libraries we need.
import { default as Web3} from 'web3';
import { default as contract } from 'truffle-contract'

// Import our contract artifacts and turn them into usable abstractions.
import voting_artifacts from '../../build/contracts/Voting.json'


var Voting = contract(voting_artifacts);
let candidates = {"Vivek": "candidate-1", "Jay": "candidate-2", "Ram": "candidate-3"}

window.App = {
  start: function() {
    var self = this;
    
    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());
        });
      })
    }
   
  },

  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() returns an instance of the contract. Every call
      * in Truffle returns a promise which is why we have used then()
      * everywhere we have a transaction call
      */
      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);
    }
    }
   
};

window.addEventListener('load', function() {
  // Checking if Web3 has been injected by the browser (Mist/MetaMask)
  if (typeof web3 !== 'undefined') {
    console.warn("Using web3 detected from external source. If you find that your accounts don't appear or you have 0 MetaCoin, ensure you've configured that source properly. If using MetaMask, see the following link. Feel free to delete this warning. 🙂 http://truffleframework.com/tutorials/truffle-and-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");
    // fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
    window.web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));
  }

  App.start();
});

Add this in index.html

<!DOCTYPE html>
<html>
<head>
  <title>MetaCoin - Truffle Webpack Demo w/ Frontend</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'>
  <script src="https://code.jquery.com/jquery-3.1.1.slim.min.js"></script>
  <script src="./app.js"></script>
</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>Vivek</td>
          <td id="candidate-1"></td>
        </tr>
        <tr>
          <td>Jay</td>
          <td id="candidate-2"></td>
        </tr>
        <tr>
          <td>Ram</td>
          <td id="candidate-3"></td>
        </tr>
      </tbody>
    </table>
    <div id="msg"></div>
  </div>
  <input type="text" id="candidate" />
  <a href="#" onclick="App.voteForCandidate()" class="btn btn-primary">Vote</a>
</body>
</html>

14.Now issue the command

npm run dev

15.Now open Chrome in incognito.
16.And hit the url http://localhost:8081/
17.Happy coding with blockchain

Posted in BlockChain | Tagged: , , , , , , , | Leave a Comment »