Sunteți pe pagina 1din 21

Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.

Global Open Versity


Blockchain DevOps Hands-on Labs Training Manual

Step-By-Step Guide on Deploying Blockchain Voting Smart Contracts


on Windows
Kefa Rabah
Global Open Versity, Vancouver Canada
krabah@globalopenversity.org
www.globalopenversity.org

Table of Contents Page No.

STEP-BY-STEP GUIDE ON DEPLOYING BLOCKCHAIN VOTING SMART CONTRACTS ON


WINDOWS 2

Introduction 2
What is Dapps? 2

Smart Contracts 2
What is a DAO? 3

Ethereum: Decentralized Applications 4

Hands-on 4

Part 1: Install Blockchain Required Tools 5

Part 2: Get started with Smart contracts with Web3 on testRPC 5


Step 1: Installations of Tools 5
Step 2: Install Ganache 5
Step 3: Install Other Required Tools 5
Step 4: Install Web3 Package 6
Step 5: Install Solidity 6
Step 6: Install Lightweight http-server 7

Part 2: Simple voting contract 7


Step 1: Write the Solidity code file “Voting.sol” 7
Step 2: Start TestRPC (ganachi-cli) 8
Step 3: Web3 object 9
Step 4: Deploy the contract 11
Step 5: Interact with the contract in the nodejs console 14

Part 4: Webpage to connect to the blockchain and vote 15


Step 1: Setup the HTML and Javascripts filles 15
tep 2: Start-up the http-server 18

Congratulation 20

1
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Global Open Versity


Blockchain DevOps Hands-on Labs Training Manual

Step-By-Step Guide on Deploying Blockchain Voting Smart Contracts


on Windows
By Kefa Rabah, krabah@globalopenversity.org May 22, 2018 The Lake Institute

Introduction
Blockchain has been around for about a decade now. Blockchain technologies and how it works, is the
next big thing to shape our lives and our futures. Blockchain lets us for the first time to have a shared
version of truth that is open, distributed and tamper proof in its nature. Blockchain has these properties
because at the heart of it, it has a way to derive consensus (thereby having a shared version of truth) and
also has cryptography baked into it by design (thereby letting us have a tamper proof record), and more
importantly it’s decentralized – i.e. it’s not controlled by any central authority or government.

Blockchain has a wide ranging set of applications and almost any field can benefit from having such a
technology at its disposal, as you must by now have learned from our Part 1 of this book. Blockchain is
also heralded as a way by which trust can be ensured in the online world and lets us have greater
confidence in the range of products and services that we use online.

However, it isn’t quite enough to know about the properties of blockchain and how it will impact the world
around us. To get a thorough understanding of the blockchain it is essential to know how to interact with it
programmatically and thinking about solutions from the software development aspect that we are used to.
Developing applications on the blockchain is certainly something that is new and cutting edge – in fact,
there is a new word to describe the type of applications that are powered by the blockchain. These are
called Decentralized Applications or Dapps.

What is Dapps?
Dapps are a new way about thinking about how we can go about writing applications for the internet that
powers blockchain technologies and applications. While previously we would have the backend code
residing in a server or a set of servers, Dapps let us run web enabled applications where the backend is
hosted and that is on a blockchain network, which executes the code that is needed for it.

Smart Contracts
The term Smart contracts was coined by Nick Szabo in 1994. Smart contracts and blockchain are closely
linked – smart contracts are the programs that we write on the blockchain and let us interact with it. It is in
a smart contract that we can define business logic and let us code the rules with which we want to interact
with the blockchain. The most powerful feature of a smart contract is the fact that once it is deployed on to
2
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

the blockchain, it is immutable and you cannot go back and edit the programs. This makes us embrace a
paradigm where we have a piece of code with the logic that we want in it will be immutable and can be
execute by itself when it is called. It is smart contracts that truly unleash the power of the blockchain, and
hence, it is important to learn to develop smart contracts on the blockchain.

What is a DAO?
The term DAO stands for “Decentralized Autonomous Organization”. In simple terms, DAOs are
organizations that exist entirely on a blockchain and are governed by its protocols. This allows for two or
more entities in a DAO to interact with each other in a fully decentralized and automated fashion. Some
uses for DAOs including sharing data, raising funds for investing, and voting — and there are certainly
more.

Ethereum DAOs operate similarly to the way crowdfunding works: when they are launched, their creators
issue tokens to the public, and anybody who is interested can buy them as a shareholding investment.
Those holding tokens can then suggest projects and ideas that other members can vote on as potential
investments. They can also vote for ideas proposed by other token holders. Being decentralized, DAOs
have no digital or physical headquarters: no single server or office building serves as their hub. Instead,
DAOs comprise a global network of nodes and members that all work together.

3
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Since DAOs are decentralized, therefore, Ethereum DAOs operate in a fully democratic, non-hierarchical
fashion. That is, no single member can make decisions on their own – thus, responsibilities are distributed
across the entire system. Decentralization also means that there’s no single point of failure. Accordingly,
the DAO network like mesh network is very resistant to attacks.

Transparency is assured since every member of a blockchain can see its current transactions, as well as
its history, making DAOs inherently transparent. This helps to ensure that the features and operations
specified for each DAO are implemented as they should be. For example, if the majority of token holders
vote to fund a specific initiative, transparency helps to ensure that the project gets funded. Because every
vote is publicly accounted for, attempts to manipulate or obfuscate the voting process are easily traceable.

Ethereum: Decentralized Applications


Ethereum is probably the most popular blockchain platform that exists right now. They have had a public
release for more than 3 years and it has a thriving community that maintains the project. They also have
developed their own programming language called Solidity that lets us interact write smart contracts.
Ethereum has a public blockchain that lets people run code on and it one of the simplest way to start
programming on the blockchain.

Hands-on
In this Hands-On guide you will continue to learn how to code a Decentralized Applications or Dapps and
what are the things that you must cover when developing and deploying blockchain smart contracts. Here,
you learn how develop and deploy a voting smart contracts useful for election using testRPC (ganache-cli)
and Web3 applications. It’s important to keep in mind that this field is constantly evolving and that it is
always a good idea to keep refreshing your knowledge about whatever you learn.

Pre-requisite or the Hands-on Labs


This tutorial requires that you already have some knowledge of Truffle, Ethereum, and Solidity. You can
start with this tutorial to get yourself up to-speed, check our Blockchain Labs Tech Series to quick you a
quick start:

1. https://www.scribd.com/document/373203852/Step-By-Step-Guide-Installing-Ethereum-Building-
a-Blockchain-on-Ubuntu-16-04-Linux-Server

2. https://www.scribd.com/document/373203852/Step-By-Step-Guide-Installing-Ethereum-Building-
a-Blockchain-on-Ubuntu-16-04-Linux-Server

3. https://www.scribd.com/document/374058743/Step-By-Step-Guide-Building-Deploying-a-Private-
Blockchain-Network-on-Windows

4. https://www.scribd.com/document/375953366/Developing-Smart-Contract-on-Ethereum-
Blockchain-Using-Truffle-Framework

4
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

5. https://www.scribd.com/document/376560099/Step-By-Step-Guide-on-Deploying-Revenue-
Sharing-Blockchain-Smart-Contracts-using-Remix-IDE-on-Windows

Part 1: Install Blockchain Required Tools


The tools we will use
The most prominent tools at the moments are:

• Ganache: It was called TestRPC before, if you have read a tutorial from a few months ago, chances
are they use TestRPC with Truffle, but it was renamed upon the integration of TestRPC within the
Truffle Suite. What Ganache does is simple, it creates a virtual Ethereum blockchain, and it generates
some fake accounts that we will use during development.
• Mist: It’s a browser for decentralized web apps. It seeks to be the equivalent of Chrome or Firefox, but
for Dapps. It’s still insecure and you shouldn’t use it with untrusted dapps as of yet.
• Ethereum wallet: It’s a version of Mist, but only opens one single dapp, the Ethereum Wallet. Mist and
Ethereum Wallet are just UI fronts. And we need a core that will connect us to an Ethereum
blockchain(It could be the real Ethereum blockchain, or a test one).
• Geth: Is the core application on your computer that will connect you to a blockchain. It can also start a
new one (in our case we will create a local test blockchain), create contract, mine ether etc.

Part 2: Get started with Smart contracts with Web3 on testRPC


We’re going initially install our required tools for this Hands-On

Step 1: Installations of Tools


1. The requirements for this tutorial are that you know what is and how to use a command-line tool, and
you are a bit familiar with NPM, which we must download and install first. At the time of writing this
article, we used “node-v9.8.0-x64.exe”

Step 2: Install Ganache


2. Then, install Ganache’s command-line interface:

npm install -g ganache-cli

3. If all is OK, then you can start with the command ganache-cli, We’ll see to that shortly.

Step 3: Install Other Required Tools


4. Next we need to install some of the tools required:

5
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

npm i -D webpack react react-dom babel-core babel-loader babel-preset-react


babel-preset-env css-loader style-loader json-loader web3@0.20.0

Note: these are all the tools that we need to create the front-end of the dapp. There are a lot of
dependencies because we’ll be creating a web application with the latest version of javascript and
React.js.

Mainly we installed webpack, react, babel and web3.

Note that we are installing the version 0.20.0 of web3 with web3@0.20.0 because the latest version
of web3, the 1.0 is still in beta and it’s unstable.

Step 4: Install Web3 Package


This a lightweight server that we’ll use to host your web app locally as you develop on localhost:8080.

5. Type the following command to install the server:

npm install web3@^0.20.0

Note: we recently found that when installing web3 with npm, the 1.0.0 beta version is installed, where
the commands used before (based on 0.20.4) do not work. Therefore, we instead specify the version
of web3. Hence, all commands below are in version 0.20.0.

Step 5: Install Solidity


To compile the solidity code, we will first install npm module called solc.

6. Type the following command to install the server:

npm install solc

Fig. 1

Note: we will use this library within a node console to compile our contract. Remember from the
previous Labs, web3js is a library which lets you interact with the blockchain through RPC. We will
use that library to deploy our application and interact with it.

7. You’re done with this section.

6
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Step 6: Install Lightweight http-server


This a lightweight server that we’ll use to host your web app locally as you develop on localhost:8080.

8. Type the following command to install the server:

npm i -g http-server

9. You’re done with this section.

Part 2: Simple voting contract


We are going to use the solidity programming language to write our contract. If you are familiar with object
oriented programming, learning to write solidity contracts should be a breeze. We will write a contract
(think of contract as a class in your favorite OOP language) called Voting with a constructor which
initializes an array of candidates. We will write 2 methods, one to return the total votes a candidate has
received and another method to increment vote count for a candidate.

Note: The constructor is invoked once and only once when you deploy the contract to the blockchain.
Unlike in the web world where every deploy of your code overwrites the old code, deployed code in the
blockchain is immutable. i.e, If you update your contract and deploy again, the old contract will still be in
the blockchain untouched along with all the data stored in it, the new deployment will create a new
instance of the contract.

Step 1: Write the Solidity code file “Voting.sol”


Note: You can grab all the codes required for this Lab from here.

Below is the voting contract code with inline comment explanation:

10. Copy the code and name the file "Voting.sol" , and lace it in the Lab8_Voting directory

pragma solidity ^0.4.18;

// We have to specify what version of compiler this code will compile with

contract Voting {

/* mapping field below is equivalent to an associative array or hash.


The key of the mapping is candidate name stored as type bytes32 and value
7
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Is an unsigned integer to store the vote count


*/

mapping (bytes32 => uint8) public votesReceived;

/* Solidity doesn't let you pass in an array of strings in the constructor (yet).
We will use an array of bytes32 instead to store the list of candidates
*/

bytes32[] public candidateList;

/* This is the constructor which will be called once when you


deploy the contract to the blockchain. When we deploy the contract,
we will pass an array of candidates who will be contesting in the election
*/

function Voting(bytes32[] candidateNames) {


candidateList = candidateNames;
}

// This function returns the total votes a candidate has received so far

function totalVotesFor(bytes32 candidate) returns (uint8) {


if (!validCandidate(candidate)) throw;
return votesReceived[candidate];
}

// This function increments the vote count for the specified candidate. This
// is equivalent to casting a vote

function voteForCandidate(bytes32 candidate) {


if (!validCandidate(candidate)) 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;
}
}

Note: code source from: https://www.zastrin.com/courses/1/lessons/4-2

11. You’re done with this section.

Step 2: Start TestRPC (ganachi-cli)


1. Open two terminals, on terminal 1, start the TestRPC

Note:
• TestRPC is a node application simulating an Ethereum blockchain in memory.

8
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

• 10 accounts are pre-defined.


• These accounts are generated through mnemonic, and are different every time when
TestRPC is started. To keep the same set of accounts, we can use the mnemonic shown
above as parameters when running TestRPC.
• Also, the RPC is opened on localhost:8545. Web3 is accessing the blockchain through this.

Step 3: Web3 object


First, run the ‘node’ command in your terminal to get in to the node console and initialize the solc and
web3 objects. All the code snippets below need to be typed in the node console.

2. We need to instruct node console we are using web3 and pointing the blockchain web3 is interfacing.

$ node
$ web3 = require('web3')
$ web3=new web3(new web3.providers.HttpProvider("http://localhost:8545"))

Fig. 3

Note: now we have web3 object to reach the Ethereum blockchain simulated by testRPC. We can test
it by getting the Ethereum address on TestRPC. From 3, scroll down to the command prompt, and
issue he following command

3. To make sure web3 object is initialized and can communicate with the blockchain, let’s query all the
accounts in the blockchain. You should see a result like shown in Fig. 4:

> web3.eth.accounts

9
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Fig. 4

Note: which are exactly the accounts created in TestRPC.

4. To compile the contract, load the code from "Voting.sol" in to a string variable and compile it.

> code = fs.readFileSync('Voting.sol').toString()

> solc = require('solc')

> compiledCode = solc.compile(code)

10
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Note: when you compile the code successfully and print the ‘contract’ object (just type
compiledCode in the node console to see the contents), there are two important fields you will notice
which are important to understand:
1. compiledCode.contracts[‘:Voting’].bytecode: This is the bytecode you get when the
source code in "Voting.sol" is compiled. This is the code which will be deployed to the
blockchain.
2. compiledCode.contracts[‘:Voting’].interface: This is an interface or template of the
contract (called abi) which tells the contract user what methods are available in the contract.
Whenever you have to interact with the contract in the future, you will need this abi definition. You
can read more details about ABI here

Step 4: Deploy the contract


Let’s now deploy the contract. You first create a contract object (VotingContract below) which is used
to deploy and initiate contracts in the blockchain.

1. Execute this in your node console:

> abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)


> VotingContract = web3.eth.contract(abiDefinition)
> byteCode = compiledCode.contracts[':Voting'].bytecode> deployedContract =
VotingContract.new(['Rama','Nick','Jose'],{data: byteCode, from:
web3.eth.accounts[0], gas: 4700000})
> deployedContract.address

11
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

> contractInstance = VotingContract.at(deployedContract.address)

2. We’ll be running this codes, one-by-one”

> abiDefinition = JSON.parse(compiledCode.contracts[':Voting'].interface)

> VotingContract = web3.eth.contract(abiDefinition)

> byteCode = compiledCode.contracts[':Voting'].bytecode

12
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

> deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data:


byteCode, from: web3.eth.accounts[0], gas: 4700000})

> deployedContract.address

Contract address: '0xfe18b1480f6e61015db084f871ee6aa570203518'

> contractInstance = VotingContract.at(deployedContract.address)

transactionHash: '0xd7a445b9087a0a70b11fa79fde72f6a175849adbd16cd80e211e057026
92d64d'

Note: "VotingContract.new" above deploys the contract to the blockchain. The first
argument is an array of candidates who are competing in the election which is pretty straightforward.
Let’s see what are all in the hash in the second argument:
1. data: This is the compiled bytecode which we deploy to the blockchain.
13
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

2. from: The blockchain has to keep track of who deployed the contract. In this case, we are just
picking the first account we get back from calling "web3.eth.accounts" to be the owner of this
contract (who will deploy it to the blockchain). Remember that web3.eth.accounts returns an
array of 10 test accounts ganache created when we started the test blockchain. In the live
blockchain, you cannot just use any account. You have to own that account and unlock it before
transacting. You are asked for a passphrase while creating an account and that is what you use to
prove your ownership of that account. Ganache by default unlocks all the 10 accounts for
convenience.

3. gas: It costs money to interact with the blockchain. This money goes to miners who do all the
work to include your code in the blockchain. You have to specify how much money you are willing
to pay to get your code included in the blockchain and you do that by setting the value of ‘gas’.
The ether balance in your ‘from’ account will be used to buy gas. The price of gas is set by the
network.

Note: we have now deployed the contract and have an instance of the contract (variable
contractInstance above) which we can use to interact with the contract. There are hundreds of
thousands of contracts deployed on the blockchain. So, how do you identify your contract in that
blockchain? Answer: deployedContract.address. When you have to interact with your
contract, you need this deployed address and abi definition we talked about earlier.

3. You’re done with this section.

Step 5: Interact with the contract in the nodejs console


1. In this section we’ll be interacting with contract using node console

> contractInstance.totalVotesFor.call(‘Rama’)

2. Let’s now vote or Rama, and repeat the voting three times, as follows:

> contractInstance.voteForCandidate(‘Rama’, {from: web3.eth.accounts[0]})

3. Now let’s veriy that indeed Rama has three votes, as has been cast:

14
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

> contractInstance.totalVotesFor.call(‘Rama’).toLocaleString()

Note: try the above commands in your node console and you should see the vote count increment.
Every time you vote for a candidate, you get back a transaction id:

Example above on the first vote for Rama:


'0xb3863ffe934d5198f83af5ef7aa015d96d7a8108bd114ded4d86259c50dec3df'

This transaction id is the proof that this transaction occurred and you can refer back to this at any time
in the future. This transaction is immutable. This immutability is one of the big advantages of
blockchains such as Ethereum. In future Labs, we will build applications leveraging this immutability.

You’re done with this section.

Part 4: Webpage to connect to the blockchain and vote

Step 1: Setup the HTML and Javascripts filles

1. Now that most of the work is done, all we have to do now is create a simple html file with candidate
names and invoke the voting commands (which we already tried and tested in the nodejs console) in
a .js file. Below you can find the html code and the .js file. Drop both of them in the
Lab8Project_Voting directory and open the index.html in your browser.

<!DOCTYPE html>
<html>
<head>
<meta charet="utf-8">
<title>A Simple Voting DApp</title>
<link href="https://fonts.googleapis.com/css?family=Raleway:400,300,600"
rel="stylesheet" type="text/css">
<link
href="https://cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css"
rel="stylesheet" type="text/css">
<style>
table {
border-collapse: collapse;
border-spacing: 0;
}
</style>
</head>
<body>
<div class="container">
<br>
<h3>A Simple Voting Distributed Application Smart Contract </h3>
<div class="row">
<table class="u-full-width">
15
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

<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>
<div class="row">
<form id="vote">
<input type="text" id="candidate" />
<input type="submit" class="button-primary" value="Vote" />
</form>
</div>
</div>
<script
src="https://cdn.rawgit.com/ethereum/web3.js/develop/dist/web3.js"></script>
<script src="./index.js"></script>
</body>
</html>

4. And next create and index.js file and copy and paste the code below:

(function () {
var web3 = new Web3(new
Web3.providers.HttpProvider("http://localhost:8545"));
// this is the same ABI JSON string generated by the `deploy.js` script
var abi =
'[{"constant":false,"inputs":[{"name":"candidate","type":"bytes32"}],"name"
:"totalVotesFor","outputs":[{"name":"","type":"uint8"}],"payable":false,"ty
pe":"function"},{"constant":false,"inputs":[{"name":"candidate","type":"byt
es32"}],"name":"validCandidate","outputs":[{"name":"","type":"bool"}],"paya
ble":false,"type":"function"},{"constant":true,"inputs":[{"name":"","type":
"bytes32"}],"name":"votesReceived","outputs":[{"name":"","type":"uint8"}],"
payable":false,"type":"function"},{"constant":true,"inputs":[{"name":"","ty
pe":"uint256"}],"name":"candidateList","outputs":[{"name":"","type":"bytes3
2"}],"payable":false,"type":"function"},{"constant":false,"inputs":[{"name"
:"candidate","type":"bytes32"}],"name":"voteForCandidate","outputs":[],"pay
able":false,"type":"function"},{"inputs":[{"name":"candidateNames","type":"
bytes32[]"}],"payable":false,"type":"constructor"}]';

var VotingContract = web3.eth.contract(JSON.parse(abi));


// use the address that was provided when creating the Voting contract on
testrpc

16
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

var contractInstance =
VotingContract.at('0xfe18b1480f6e61015db084f871ee6aa570203518');
var candidates = ['Rama', 'Nick', 'Jose'];

// define totalVotesFor callback


var createTotalVotesForCallback = function (candidate) {
return function (err, numVotes) {
if (err) {
alert(err);
return;
}
var n = candidates.indexOf(candidate) + 1;
document.getElementById('candidate-' + n).innerHTML =
numVotes.toString();
};
};

// get all candidate votes function


var updateVotes = function() {
candidates.forEach(function(candidate) {
contractInstance.totalVotesFor.call(candidate,
createTotalVotesForCallback(candidate));
});
};

var voteForm = document.getElementById('vote');


var candidateInput = document.getElementById('candidate');
voteForm.addEventListener('submit', function (e) {
e.preventDefault();
var candidate = candidateInput.value;
if (candidate === '' || candidates.indexOf(candidate) < 0) {
alert('invalid candidate:', candidate)
return
}
contractInstance.voteForCandidate(candidate, {from:
web3.eth.accounts[0]}, function (err) {
if (err) {
alert(err);
return;
}
contractInstance.totalVotesFor.call(candidate,
createTotalVotesForCallback(candidate));
});
})

// get initial value of votes


updateVotes();
// update votes every 30 seconds
setInterval(updateVotes, 30000);
})();

Note: in your nodejs console, execute "contractInstance.address" to get the address at


which the contract is deployed and change the line below to use your deployed address

17
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

'0x64cd1764bb54c7ba82ce25155dd1a4392eae2198'

5. You’re done with this section.

tep 2: Start-up the http-server

Note: if you remember, we said earlier we will need the abi and the address to interact with any
contract. You can see above in the index.js file how they are used to interact with the contract.

1. To start http-server, type "http-server", and hit enter

2. Now point your browser to http://127.0.0.1:8081 or http://localhost:8081. This is what you should see
when you open the index.html file in your browser, and you should see our freshly deployed Voting
Smart Contracts up and running.

18
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

Note: if everything is setup correctly, you should be able to enter the candidate name in the textbox
and vote and the vote count should increment

2. Let’s go ahead and votes to our candidates of choice, let’s start with Jose, Write his name and the
click on VOTE button.

Note: Do some couple o voting to verify that it’s working ok.

19
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2

3. You’re done with this section and this Hands-On Labs

Congratulation
If you are able to enter the candidate name in the text box and vote and see the vote count increment, you
have successfully created your first application! Congratulations! To summarize, you set up your dev
environment, coded a simple contract, compiled and deployed the contract on the blockchain and
interacted with it via nodejs console and then through a webpage. Now would be a good time to again pat
yourself on the back if you haven’t already :)

Available from Scribd.com:

A Creative Common Publication:

-----------------------------------------------
Kefa Rabah is the Founder of The Lake Institute. Kefa is knowledgeable in several fields of Science &
Technology, Information Security Compliance, Blockchain Technology, Distributed Ledger Technology
(DLT) and Project Management, and Renewable Energy Systems. He is also the founder of Global Open
Versity, a place to enhance your educating and career goals using the latest innovations and
technologies.

Fellow us on Twitter: The Lake Institute and Kefa Rabah

A Globalopenversity Open Access Technical Academic Publications


Delivering Cutting-edge Technology at your Fingertips in the 21st Century
20
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada

www.globalopenversity.org

S-ar putea să vă placă și