Quick Introduction: Blockchain, Ethereum, Smart Contracts and Truffle

In February 2017, I embarked on a journey to learn more about Blockchain and cryptocurrency. Today, from starting with the initial jargon to watching endless online videos, I am at a stage where I am comfortable speaking about the concepts present in these technologies. Although the journey is long, and at times confusing, each Medium article, YouTube video, and online course gave me the motivation to learn more. Feel free to correct me if the information written is incorrect.

What is Blockchain?

Blockchain is a revolutionary technology, an immutable ledger of records linked through cryptography. This set of records placed in blocks can be any information chained in a decentralized and distributed manner. Hence, Block-Chain. Bitcoin happens to be the first implementation of blockchain. It is revolutionary because of the clear benefits this technology can bring to organizations and industries. With blockchain, the storage of information doesn’t need to be dependent on one single organization owning servers. This is quite a powerful shift from centralized client server model to having information decentralized, but still secure and immutable. I may have made simple by defining blockchain in 4 lines, but there is much more to it. There are tons of material on web. Study and refresh yourself with what is in block, how block is mined, different mining/consensus techniques. At times concepts may be hard to grasp, but be persistent.

Coming back to Bitcoin and wonderful world of cryptocurrencies. Since Bitcoin, many more cryptos have erupted, but the underlying technology of each is based on blockchain. Each crypto (Ex:BitCoin, Ethereum, LiteCoin and many others) has its own set of underlying protocols. However, cryptos are not the only application of blockchain. Blockchain can encompass applications in the form of distributed ledgers, outside of the realm of cryptos.

Ethereum — Smart Contracts

I am more focused on Ethereum as it allows the user to write practical applications, ranging from exchanging Ether (currency of Ethereum) to exchanging simple information. These applications are commonly referred to as Smart Contracts that use Solidity as its programming language. These smart contracts are like back-end programs — different smart contracts can communicate with each other or can be accessed through browser-based application using a Web3 protocol.

I will start with a very simple Smart Contract (SC), how to setup the local dev environment on your machine and deploy to test networks using Truffle. Let’s get into it.

Tools needed

I am more focused on Ethereum as it allows the user to write practical applications, ranging from exchanging Ether (currency of Ethereum) to exchanging simple information. These applications are commonly referred to as Smart Contracts that use Solidity as its programming language. These smart contracts are like back-end programs — different smart contracts can communicate with each other or can be accessed through browser-based application using a Web3 protocol.

I will start with a very simple Smart Contract (SC), how to setup the local dev environment on your machine and deploy to test networks using Truffle. Let’s get into it.

Visual Studio code (VS) for editing SC. There is a nice plugin available for syntax highlighting and compiling. It is available in Windows, Mac & Linux. Within VS, search solidity from extensions and install as shown below.


Truffle: This suite of tools manages the cycle of SC development. It makes your life easier by providing command line interface to migrate, deploy, debug in test or live Ethereum networks. Install both testrpc and truffle using below commands. 
 Install NPM. Launch windows command prompt and run the below commands.

npm install -g npm

➢ npm install -g -production windows-build-tools

➢ npm install -g ethereumjs-testrpc

➢ npm install -g truffle

Here is our first simple contract in solidity. This contract sets value in myVariable through setValue function and retrieves through getValue function.

Let me define different parts of above contract. 
pragma: optional, but one should make it a practice of always including. It indicates that the source code is written for solidity version 0.0.24. The ^ symbol implies another condition — the source file will also not work on compilers past the version of 0.5.0

pragma solidity ^0.4.24;

contract MyFirstContract { 
uint myVariable;

constructor (uint256 _var) public { 
myVariable = _var;

function setValue(uint256 x) public {

myVariable = x;

 function getValue() constant public returns (uint256) {

return myVariable;



myVariable state variable stores value for lifetime of contract. Concept of storage Vs local variables is important concept and helps to know the differences. These distinctions can help you save gas which is a fuel for running transactions on Ethereum network.

constructor keyword is contract constructor initiated only first time when contract is deployed. At the time of constructor, creation value passed will get stored in myVariable unless changed in setValue function. Alternatively, constructor can also be defined as name of SC.

function MyFirstContract (uint256 _var) public { //function body}

Functions getValue and setValue are public functions which can be called either from other contracts or from front end like Chrome browser. We will build front end distributed (Dapp) applications in later series of articles.

Let’s deploy SC using Truffle packages. Follow below steps. 
Create folder <AnyName> 
Cd < AnyName > 
Run command Truffle Init to initialize folders structure for Truffle to work 
You will see subfolders build, contracts, migrations, test and 2 JavaScript files, truffle.js and truffle-config.js.

Save above written contract in contracts folder, let’s say with file name MyFirstContract.sol. Alternatively, truffle create contract MyTestContract command can also be issued to create a contract. In this case MyTestContract.sol file will get created in contracts folder

go to contracts folder: cd contracts

Compile contract by giving command truffle compile. This will also compile all other contracts in case residing in contracts folder. Compile will create artifacts of contract in form of JSON file under /build/contracts. Two important keys within JSON file are bytecode and application binary interface (abi). Bytecode is what Ethereum virtual machine (EVM) understands when SC is run. ABI is an interface for accessing SC functions and variables. You will have to migrate this code to Blockchain in order to execute. Follow next step.

Open new command window. Go to contracts folder like in above step. Run command truffle develop. DOS command prompt will change to truffle(develop). In background this step initiates a local Blockchain in your machine. Why local? Because for the sake of simplicity, you want to first test your contract in your machine before migrating to Ethereum test nets or real Ethereum environment. This local blockchain runs at port 9545. There are various Ethereum Test Nets like Rinkeby, Kovan,Ropsten.

Run command migrate. What we are trying to achieve is deploy MyFirstSmartContract to local blockchain. Let me explain how we setup configuration files in JavaScript. When we initiated truffle init it also created migration folder along with other folders. A default file 1_initial_migration.js was created. Open this file and you will find its referring to another SC Migration.sol which is in contracts folder. Migration.sol is simply another SC to deploy user created SC. Create a file 2_deploy_contracts.js under migration folder and include below line of commands

var MyFC = artifacts.require(“MyFirstContract”); 
 module.exports = function(deployer) { deployer.deploy(MyFC,2); };

In above .js file, number 2 within deployer.deploy(MyFC,2) is default parameter to constructor of smart contract. When migrate completes you should see something like 0x057d2360abbe75f9fdf142f2cfe68cfc9a74ec12. This long hexadecimal number is contract address at which MyFirstContract will reside. Contract address generated will be different in your case. To access any smart contract functionality, knowing address is first thing first. Each smart contract address in BlockChain universe is unique.

Important → There is always a cost that takes place whenever a smart contract is deployed. This cost is calculated in gas and paid in Ether (ETH). Ether is pegged to USD. Just as you need gas to drive a car, the cost is calculated in amount of gas and paid in dollars. There is always a cost for executing a transaction within smart contract. Deployment of smart contract is a transaction. Setting a value to variable is a transaction. Addition/Subtraction/Division/Multiplication or any other simple or complex mathematical operation is a transaction. One can specify gas limit and gas price before sending transactions. In case gas consumed is more than the specified gas limit, transaction is not executed, but consumed gas still carries cost irrespective of incomplete transaction. In case the gas consumed is less than the specified gas limit, the leftover gas is returned to the initiator of transaction. There is no cost for read operations.

Key question you should ask why there is cost for SC and who receives payment? Transactions are monetized to maintain efficiency of Ethereum network. Creator of Ethereum wants you to be cognizant of operations performed on network. It’s like you don’t want your car to be driven recklessly and if that happens more gas is burnt, causes frequent trips to gas stations and ultimately more money coming out of your wallet. Similarly, you don’t want SC to be coded with endless loops, unstructured and inefficient flows which may clog network.

Transactions need to be verified and confirmed in the form of block. This job of confirming a block is done by miners. Miners compete for the formation of block and incur cost as they own special hardware utilized for intense computations. These intense computations are due to Proof of Work logic as required by Ethereum network. Ethereum team is working on plans to move to Proof of stake consensus.

Whichever miner can first compute required number is awarded with transaction cost, paid by initiator of transaction. In addition to transaction fee miners also get 5 Ether per block. At the time of writing of this article price of 1 Ether is equivalent to $200. With current price of ether you can do math’s a miner can earn. There are more concepts related to gas like gas limit, gas price, which solidity commands to use or not to use how to prevent waste of gas etc. I will cover gas topic in some other series.

One of the major advantages with development and testing in local blockchain is free gas apart from speed and ease. When we launched truffle develop it created a local blockchain environment with 10 free accounts each containing 100 Ethers. Migrate command took some Ether from first account and let our contract deployed successfully. Alternatively, one can launch local blockchain environment called ganache (formerly Testrpc) which provides similar default 10 accounts.

Now our contract is deployed, let’s go ahead and execute the getValue and setValue functions of SC. From thetruffle develop command prompt, type below command to call getValue function. This will return a value of 2 which was passed default at the time of contract creation.

MyFirstContract.deployed().then(function(instance){return instance.getValue.call();}).then(function(value){return value.toNumber()});

Issue below command to call setValue function

MyFirstContract.deployed().then(function(instance){return instance.setValue(4);});

Calling setValue results in number of lines on develop console. This is due to fact that MyVariable within smart contract has a change in value which is counted as transaction. A unique address gets created called TransactionHash. A new block is mined and BlockHash gets created along with BlockNumber. This block contains value 4 as created by setValue.

When a transaction takes place in Ethereum, multiple activities take place. The transaction object gets created, transaction goes through verification process through Proof of work consensus, gas gets consumed. A block gets created in the case transaction verification is successful and required gas is available. The information of the successful block is communicated to all other nodes participating in network. This way, all Nodes have the same ledger. In above case change in value from 2 to 4 was instant, but in real applications running on live Ethereum network, one transaction confirmation can take 17–20 seconds. In the Bitcoin world, it’s 10 minutes.

For you to really advance your knowledge, spend time studying different consensus mechanisms (Proof of work vs Proof of stake), miners’ role in processing a transaction, what is a transaction object, how can you speed up processing of transactions through increase in gas price, and many more concepts in Blockchain and Ethereum. Hope that I will cover some of these in next series of articles. Happy learning! Clap if you liked the article. Please comment where I can improve.

Articles you may like

Beginners Guide

What is BlockChain