Introduction 2
What is Dapps? 2
Smart Contracts 2
What is a DAO? 3
Hands-on 4
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
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.
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.
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
• 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.
3. If all is OK, then you can start with the command ganache-cli, We’ll see to that shortly.
5
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada
www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2
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.
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.
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.
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.
6
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 -g http-server
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.
10. Copy the code and name the file "Voting.sol" , and lace it in the Lab8_Voting directory
// We have to specify what version of compiler this code will compile with
contract Voting {
www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2
/* 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
*/
// This function returns the total votes a candidate has received so far
// This function increments the vote count for the specified candidate. This
// is equivalent to casting a vote
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
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
4. To compile the contract, load the code from "Voting.sol" in to a string variable and compile it.
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
11
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada
www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2
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.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.
> contractInstance.totalVotesFor.call(‘Rama’)
2. Let’s now vote or Rama, and repeat the voting three times, as follows:
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:
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.
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"}]';
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'];
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'
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.
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.
19
April 2007, Kefa Rabah, Global Open Versity, Vancouver Canada
www.globalopenversity.org
Global Open Versity Build & Deploy Blockchain Voting Smart Contracts v1.2
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 :)
-----------------------------------------------
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.
www.globalopenversity.org