Blockchain & Solidity Program Lab Manual
ISBN 9788119221646

Highlights

Notes

  

Prog. 23:: DApp on Election

Election DApp 
Election.sol

pragma solidity ^0.5.16; 
contract Election {

// Model a candidate struct Candidate

{ 
uint id;

string name; uint voteCount;

}

// Store a candidate//Fetch Candidate mapping(uint => Candidate) public candidates;

// Store candidate count

uint public candidatesCount;//constructor constructor() public

{

addCandidate(“KamalHaasan”); addCandidate(“RajniKanth”);

}

function addCandidate (string memory _name) private

{

candidatesCount ++;

candidates[candidatesCount] = Candidate(candidatesCount, _name, 0);

}

}

2_deploy_contract.js

var Election = artifacts.require(“./Election.sol”);

module.exports = function(deployer)

{

deployer.deploy(Election);

};

Election.js

var Election = artifacts.require(“./Election.sol”);contract(“Election”, function (accounts)

{

it(“initializes with two candidates”, function()

{

return Election.deployed().then(function(instance)

{

return instance.candidatesCount();

}).then(function(count)

{

assert.equal(count, 2);

});

});

});

it(“it initializes the candidates with the correct values”, function()

{

return Election.deployed().then(function(instance)

{

electionInstance = instance;

return electionInstance.candidates(1);

}).then(function(candidate)

{

assert.equal(candidate[0], 1, “contains the correct id”);

assert.equal(candidate[1], “KamalHaasan”, “contains the correct name”);

assert.equal(candidate[2], 0, “contains the correct votes count”);

return electionInstance.candidates(2);

}).then(function(candidate)

{

assert.equal(candidate[0], 2, “contains the correct id”);

assert.equal(candidate[1], “RajniKanth”, “contains the correct name”);

assert.equal(candidate[2], 0, “contains the correct votes count”);

});

});

App.js App =

{

web3Provider: null, 
contracts:

{

},

account: ‘0x0’,init: function()

{

return App.initWeb3();

},initWeb3: function()

{

// TODO: refactor conditional

if (typeof web3!== ‘undefined’)

{

// If a web3 instance is already provided by Meta Mask.

App.web3Provider = web3.currentProvider; web3 = new Web3(web3.currentProvider);

}

else

{

// Specify default instance if no web3 instance provided

App.web3Provider = new Web3.providers.HttpProvider(‘http://localhost:7545’); 
web3 = new Web3(App.web3Provider);

}

return App.initContract();

},initContract: function() {

$.getJSON(“Election.json”, function(election)

{

// Instantiate a new truffle contract from the artifact 
App.contracts.Election = TruffleContract(election);

// Connect provider to interact with contract 
App.contracts.Election.setProvider(App.web3Provider);return App.render();

});

},render: function()

{

var electionInstance;

var loader = $(“#loader”);

var content = $(“#content”);loader.show(); 
content.hide(); 
// Load account data web3.eth.getCoinbase(function(err, account)

{

if (err === null)

{

App.account = account;

$(“#accountAddress”).html(“Your Account: “ + account);

}

});

// Load contract data 
App.contracts.Election.deployed().then(function(instance)

{

electionInstance = instance;

return electionInstance.candidatesCount();

}).then(function(candidatesCount)

{

var candidatesResults = $(“#candidatesResults”); 
candidatesResults.empty(); 
for (var i = 1; i <= candidatesCount; i++)

{

electionInstance.candidates(i).then(function(candidate)

{

var id = candidate[0]; 
var name = candidate[1];

var voteCount = candidate[2]; 
// Render candidate Result

var candidateTemplate = “<tr><th>“ + id + “</th><td>“ + name + “</td><td>“ + voteCount + “</td></tr>“

candidatesResults.append(candidateTemplate);

});

}

loader.hide(); 
content.show();

}).catch(function(error)

{

console.warn(error);

});

}

};$(function()

{

$(window).load(function()

{

App.init();

});

});

Package.json

{

“name”: “pet-shop”,

“version”: “1.0.0”,

“description”: ““,

“main”: “truffle.js”, 
“directories”:

{ 
“test”: “test”

},

“scripts”:

{

“dev”: “lite-server”,

“test”: “echo \”Error: no test specified\” && exit 1”

},

“author”: ““,

“license”: “ISC”, 
“devDependencies”:

{ 
“lite-server”: “^2.3.0”

}

}

Index.html

<!DOCTYPE html>

<html lang=“en”>

<head>

<meta charset=“utf-8”>

<meta http-equiv=“X-UA-Compatible” content=“IE=edge”>

<meta name=“viewport” content=“width=device-width, initial-scale=1”>

<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->

<title>Election Results</title><!-- Bootstrap -->

<link href=“css/bootstrap.min.css” rel=“stylesheet”><!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->

<!-- WARNING: Respond.js doesn’t work if you view the page via file:// -->

<!--[if lt IE 9]>

<script src=“https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js”></script>

<script src=“https://oss.maxcdn.com/respond/1.4.2/respond.min.js”></script>

<![endif]-->

</head>

<body>

<div class=“container” style=“width: 650px;”>

<div class=“row”>

<div class=“col-lg-12”>

<h1 class=“text-center”>Election Results</h1>

<hr/>

<br/>

<div id=“loader”>

<p class=“text-center”>Loading...</p>

</div>

<div id=“content” style=“display: none;”>

<table class=“table”>

<thead>

<tr>

<th scope=“col”>#</th>

<th scope=“col”>Name</th>

<th scope=“col”>Votes</th>

</tr>

</thead>

<tbody id=“candidatesResults”>

</tbody>

</table>

<hr/>

<p id=“accountAddress” class=“text-center”></p>

</div>

</div>

</div>

</div><!-- jQuery (necessary for Bootstrap’s JavaScript plugins) -->

<script 
src=“https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js”></script>

<!-- Include all compiled plugins (below), or include individual files as needed -->

<script src=“js/bootstrap.min.js”></script>

<script src=“js/web3.min.js”></script>

<script src=“js/truffle-contract.js”></script>

<script src=“js/app.js”></script>

</body>

</html>

DApp program using Metamask

    1) Open the Ganach

    2) Open Sublimetext3 editor

    3) create the folder contest1

    4) install the truffle in the directory F:/>contest1>npm install truffle –g

    5) Make the contract Election.sol using Solidity Program

    7) f:

    8) Check the truffle version

    9) Write Solidity Program

    10) Configure the deployment files in migration folder

    12) Compile the Contract Program

    13) Deploy the contract on blockchain network i.e. Ganache localhost blockchain

pragma solidity 0.4.24;

contract Election

{

struct Candidate

{

uint id; 
string name;

uint voteCount;

}

// this is store candidate information

// Fetch candidate information using

// reference variable

mapping(uint => Candidate) public candidate;

//variable for vote counting uint public candidateCount;

//constructor

function Election() public

{

addCandidate(“Sourabh”); 
addCandidate(“Neeta”);

}

// define addcandidate function

function addCandidate(string memory _name)private

{

candidateCount++;

candidate[candidateCount] = Candidate(candidateCount,_name,0);

}

}

    14) Recompile the same Election contract

    15) Deploy the Contract over the Ethereum Ganach

    16) Fetching candidate

    17) Fetch Individual Ganache node address

Here Mocha is a feature-rich JavaScript test framework running on Node.js and in the browser, making asynchronous testing..

Assertion Library: Chai – Chai is a BDD/TDD assertion library for[node](http://nodejs.org) and browser that can be paired with it In the Test folder we have to create election.js file in sublimetext3

const Election = artifacts.require(“./Election.sol”); require(‘chai’).use(require(‘chai-as-promised’)).should();

contract(“Election”,function(accounts){it(“initialize with two candidate”,function(){return Election.deployed().then(function(instance){return instance.candidateCount();}).then(function(count){assert.equal(count,2);})});});