Creating a Decentralized Future.

Technology

Running your DApp on Ethereum.

Do you know Ethereum is the brainchild of the prodigious Vitalik Buterin? He realized the potential of Bitcoin’s underlying blockchain technology as an opening to a new universe for business accountability and in turn a new economy.

The new software models are approaching, bringing with them decentralized file storage, financial derivatives and voting systems.

Blockchain is gaining a lot of traction now with Bitcoin emerging as an alternative to Fiat currencies and also as an alternative investment option. Possibilities of blockchain is not just limited to Bitcoin. There are a whole lot of blockchain technologies including Ethereum which allows us to create distributed serverless applications and smart contracts. In this article, we will see how we can create a sample distributed application using Ethereum Smart Contract.

What is Blockchain?

Before we dive head on into the application, let's first understand what blockchain is.

As the name suggests, blockchain is a chain of blocks where the blocks are used to store data. The data in each block is used to generate unique hash which also form part of the block. A block also holds the hash of its previous block forming a chain. This allows one to trace back from any given block to the very first block in the chain also called the genesis block.

If somebody tries to change data in a block, it changes the hash of the block which breaks the chain and causes all subsequent blocks in the chain after the changed block to be invalid unless the hashes of all subsequent blocks are regenerated.

Copies of the blockchain are stored in multiple systems or nodes in a network which is continuously synchronised with each other so that if there is any mismatch, data of the majority node is considered valid. Due to this, if someone wants to change an existing block, he/she will not only have to change all subsequent blocks, but also do so in more than half of the nodes in the network at the same time.

Not only this, an extra level of difficulty is added by making the process of adding the block difficult by adding a process called mining. Mining is basically a process of solving a complex puzzle using bruteforce method. All nodes in the network compete with each other in solving the puzzle, and the node that is able to solve the puzzle first gets the privilege of adding a new block to the system and also wins a monetary reward in cryptocurrency. Solving the puzzle is a CPU (or rather GPU) intensive task.

All this makes changing data, already written to a blockchain with thousands of nodes, financially nonviable. This ensures that the data once written to blockchain is virtually unmodifiable by design. Not only that, the data written to the blockchain is not stored in a particular server. It is distributed over thousands of nodes in the network which ensures that the ownership of data is not with an individual or organisation in case of public blockchain network.

Ethereum and Smart Contracts

We just saw what blockchain is. Some examples of blockchain network are Bitcoin, Ethereum, Monero, etc. We will be looking deeper into Ethereum here. Ethereum is one of the most popular blockchain networks among developers because, in addition to the data, Ethereum blocks allow storing a small program within itself called smart contract. This opened the possibility of using blockchain as a medium to execute programs in a distributed fashion.

The cryptocurrency associated with Ethereum is called ether. There is a cost associated with executing a contract which also depends on the operations done in the contract. The cost is measured in terms of 'gas,' and the value of gas is based on the gas prices for the transaction.

A smart contract is written in a programming language called Solidity which is similar to JavaScript. In order to access Ethereum network and smart contract from within our program, we will use a JavaScript library Web3.js.

Example of Polling Application Using Solidity

Now we will see how to write a sample polling application. Following is the way the application will work:

Users will be able to post questions on which other user’s opinion need to be polled. Users who wish to register their opinion will be able to view the question and answer to it as yes, no or maybe. The core part of the application will be smart contract representing the poll. The user interface of the web application will be developed using conventional web technologies like HTML, JavaScript and Express framework. We will create unit tests for the smart contract using Mocha.

The Smart Contract

Given below is the smart contract written in Solidity language representing the polls in a file named ‘polling.sol’ and is placed in a folder named ‘contracts.’

pragma solidity ^ 0.4.17;

contract Polling{
string public pollingSubject;
uint private yesCount = 0;
uint public noCount = 0;
uint public mayBeCount = 0;

function Polling(string subject) public{
pollingSubject = subject;
}

function voteAsYes() public{
yesCount = yesCount + 1;
}

function voteAsNo() public{
noCount = noCount + 1;
}

function voteAsMayBe() public{
mayBeCount = mayBeCount + 1;
}

function getSubject()public view returns(string){
return pollingSubject;
}

function getYesVoteCount()public view returns(uint){
return yesCount;
}
function getNoVoteCount()public view returns(uint){
return noCount;
}
function getMayBeVoteCount()public view returns(uint){
return mayBeCount;
}
}

This contract consists of the following four variables:
Polling Subject - Stores the polling subject.
Yes Count - Stores the count of yes votes.
No Count - Stores the count of no votes.
Maybe Count - Stores the count of may be vote.

In addition to these, there are functions to set value of these variables and retrieve these values.

Compiling the Smart Contract

We will use compiler solc version 0.4.17 for compiling the contract. We will write the code for compiling the contract in Node using appropriate version of solc compiler node module. The code will be compiled into bytecode, and the interface for the contract.

Given below is the code to compile the contract using Node:

const path= require('path');
const fs=require('fs');
const solc=require('solc');

const polPath=path.resolve(__dirname,'contracts','polling.sol');
const source=fs.readFileSync(polPath,'utf8');

module.exports=solc.compile(source,1).contracts[':Polling'];

The code is written as a Node module so that it can be easily referenced from external files.

Unit Testing the Smart Contract

Now we will write unit test for testing the contract using Mocha test framework. We will place the test in a file named ‘polling.test.js’ in a directory named ‘test.’

const asert = require('assert');
const ganache = require('ganache-cli')
const Web3 = require('web3');
const web3 = new Web3(ganache.provider());
const { interface, bytecode } = require('../compile');
let accounts;
let polling
beforeEach(async () => {
// get all accounts
accounts = await web3.eth.getAccounts();

polling = await new web3.eth.Contract(JSON.parse(interface))
.deploy({ data: bytecode, arguments: ['this is first data'] })
.send({ from: accounts[0], gas: 1000000 });
}
);

describe('Polling', () => {
it('Check Contract Created', () => {
console.log(polling.options.address);
asert.ok(polling.options.address);
});
it('Check Subject', async () => {
const subject = await polling.methods.getSubject().call();
asert.equal(subject, 'this is first data');
});

it('Check voteAsYes', async () => {
let yesCount = await polling.methods.getYesVoteCount().call();
asert.equal(yesCount, 0);
await polling.methods.voteAsYes().send({ from: accounts[0] });
yesCount = await polling.methods.getYesVoteCount().call();
asert.equal(yesCount, 1);
await polling.methods.voteAsYes().send({ from: accounts[0] });
yesCount = await polling.methods.getYesVoteCount().call();
asert.equal(yesCount, 2);
});

it('Check voteAsNo', async () => {
let noCount = await polling.methods.getNoVoteCount().call();
asert.equal(noCount, 0);
await polling.methods.voteAsNo().send({ from: accounts[0] });
noCount = await polling.methods.getNoVoteCount().call();
asert.equal(noCount, 1);
await polling.methods.voteAsNo().send({ from: accounts[0] });
noCount = await polling.methods.getNoVoteCount().call();
asert.equal(noCount, 2);
});

it('Check voteAsMayBe', async () => {
let mayBeCount = await polling.methods.getMayBeVoteCount().call();
asert.equal(mayBeCount, 0);
await polling.methods.voteAsMayBe().send({ from: accounts[0] });
mayBeCount = await polling.methods.getMayBeVoteCount().call();
asert.equal(mayBeCount, 1);
await polling.methods.voteAsMayBe().send({ from: accounts[0] });
mayBeCount = await polling.methods.getMayBeVoteCount().call();
asert.equal(mayBeCount, 2);
});
});

For testing, instead of using real Ethereum network, we will use ‘ganache-cli.’

Following is the output on running the test script:

UI Interface for the Contract

We write an Express-based web application to publish the contract and invoke various functions in the contracts.

The user interface has a textbox to enter the subject of poll and a button ‘Add Contract’. A dropdown list under it lists all existing contracts representing polls.

On entering a subject and clicking the ‘Add Contract’ button, it will compile and publish the contract to the local ganache simulating the Ethereum network. Once the contract is added, it will also update the newly added contract in the contract list in dropdown below.

As we select the newly-added contract from the dropdown list, we can see that the polling question is displayed below with the button prompting to vote ‘Yes’, ‘No’ or ‘May Be’. As the user votes by clicking the buttons, the vote is captured in the smart contract.

Clicking the ‘Show Result’ button besides the voting buttons will fetch the voting results from the smart contract and list it as shown below.

Conclusion

Now we understand what a block chain is, how to create a smart contract, and how the smart contract can be accessed from a regular program. In a typical Blockchain-based distributed application, the smart contract forms only a small part of the overall application, with conventional technology forming a large part of the application.

Writing data to the blockchain as part of an application requires real money in the form of cryptocurrency. Due to this reason, smart contracts may not be appropriate in all types of applications. However, distributed application developed using smart contract are idle where the focus is on transparency, ownership of data and trust.