Full Stack Hello World Voting Ethereum Dapp Tutorial — Part 1

In my previous post, I explained the high level architecture of Ethereum platform comparing it to a web application. As a developer, the best way to learn any new technology is by diving in and building toy applications. In this post, let’s build a simple ‘Hello World!’ application which is a Voting application.

The application is extremely simple, all it does is initialize a set of contestants, let anyone vote for the candidates and display the total votes received by each candidate. The goal is not to just code an application but to learn the process of compiling, deploying and interacting with it.

I have deliberately avoided using any dapp frameworks to build this application because the frameworks abstract away lot of the details and you fail to understand the internals of the system. Also, when you do use a framework, you will have more appreciation for all the heavy lifting the framework does for you!

In lot of ways, this article is a continuation of the previous post. If you are new to the world of Ethereum, I recommend reading it before continuing.

The goal of this exercise is to:

  1. Set up the development environment.
  2. Learn the process of writing a contract, compiling it and deploying it in your development environment.
  3. Interact with the contract on the blockchain through a nodejs console.
  4. Interact with the contract through a simple web page to display the vote counts and vote for candidates through the page.

The entire application set up and build was done on a fresh installation of ubuntu 16.04 xenial. I have set up and tested the application on macos as well.

This is how I would visualize this application we are going to build.

1. Setting up the development environment

Instead of developing the app against the live blockchain, we will use an in- memory blockchain (think of it as a blockchain simulator) called testrpc. In Part 2 of the tutorial, we will interact with the real blockchain. Below are the steps to install testrpc, web3js and start the test blockchain on a linux operating system. The exact same instructions work on macos as well. If someone gets it working on windows, I will be happy to link to the instructions here.

Notice that the testrpc creates 10 test accounts to play with automatically. These accounts come preloaded with 100 (fake) ethers.

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.

Below is the voting contract code with inline comment explanation:

Copy the above code to a file named Voting.sol in the hello_world_voting directory. Now let’s compile the code and deploy it to testrpc blockchain. Remember from the previous article, web3js is a library which lets you interact with the blockchain through RPC. We will use that library within a node console to compile, deploy our application and interact with the blockchain.

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

mahesh@projectblockchain:~/hello_world_voting$ node
> Web3 = require('web3')
> web3 = new Web3(new Web3.providers.HttpProvider("http://localhost:8545"));

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 below:

> web3.eth.accounts

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

>code = fs.readFileSync('Voting.sol').toString()
>contract = web3.eth.compile.solidity(code)

When you compile the code successfully and print the ‘contract’ object (just type contract in the node console to see the contents), there are two important fields you will notice which are important to understand:

  1. contract.code: 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. contract.info.abiDefinition: This is an interface or template of the contract 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 abiDefinition. You can read more details about ABI here

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.

>VotingContract = web3.eth.contract(contract.info.abiDefinition)
>deployedContract = VotingContract.new(['Rama','Nick','Jose'],{data: contract.code, from: web3.eth.accounts[0], gas: 4700000})
>contractInstance = VotingContract.at(deployedContract.address)

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.
  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 testrpc created when we started the test blockchain. In the live blockchain, you can not 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. Testrpc 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.

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. Interact with the contract in the nodejs console

> contractInstance.totalVotesFor.call('Rama')
{ [String: '0'] s: 1, e: 0, c: [ 0 ] }
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
> contractInstance.voteForCandidate('Rama', {from: web3.eth.accounts[0]})
> contractInstance.totalVotesFor.call('Rama').toLocaleString()

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: ‘0xdedc7ae544c3dde74ab5a0b07422c5a51b5240603d31074f5b75c0ebc786bf53’ above). 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 tutorials, we will build applications leveraging this immutability.

4. Webpage to connect to the blockchain and vote

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 hello_world_voting directory and open the index.html in your browser.

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.

This is what you should see when you open the index.html file in your browser.

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 pat yourself on the back if you haven’t already :)

In part 2, we will deploy this contract to the public test network so the entire world can see it and vote for a candidate. We will also get more sophisticated and use the truffle framework for development (and not have to use the nodejs console to mange the entire process). Hope this tutorial helped you get a practical idea on how to get started with developing decentralized application on the Ethereum platform.

As always thanks Raine Rupert Revere for corrections/edits of this post.

If you run into issues getting the application working, feel free to DM me on twitter @mvmurthy

If you would like to get notified when I write more tutorials, you can subscribe below.