நம்Chain® Open Initiative Research Lab

நம்Chain's Blockchain Tutorials

நம்Chain® Open Initiative Research Lab

Ethereum Blockchain Tutorials

A Repository dedicated to Ethereum Blockchain Tutorials.

Prerequisite

Tutorial Topics

Ethereum Blockchain Overview

Ethereum is a second generation Blockchain Technology which is widely referred to as World Computer. The native cryptocurrency of the Ethereum Blockchain is called “Ether (ETH)”. Ethereum also provides the users the programming capability through its Smart Contract Programming. Distributed Application (DApps) can be developed using the smart contracts which is deployed and runs on the Ethereum Blockchain.

Ethereum Blockchain uses Ethereum Virtual Machine (EVM) to execute the transactions. Ethereum uses memory-based Proof of Work (PoW) consensus algorithm. It also offers multiple testnets (Ropsten, Goerli, Kovan, Rinkeby) and private blockchain (Ganache) & Truffle Framework support for the development and testing of smart contracts.

Solidity Programming Basics

Solidity is the dedicated programming language for development of Smart Contracts on Ethereum Blockchain. Solidity is similar to Object Oriented Programming Language like Java / C++. Contract is the main component in the solidity programming which is similar to Class in Java. Like, Java, the solidity program on compilation is converted into bytecode for execution in EVM.

For development of Smart Contracts using Solidity, Ethereum provides its own online IDE called Remix.

Below code shows the Solidity Template for your reference.

Filename: Sample.sol


// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.4.22 <0.7.0;
import "<<path-or-link-to-file-to-be-imported>>"

/**
 * @title Solidity Template
 * @author Ramaguru Radhakrishnan
 */
 contract <<contractName>> {
 
    mapping(datatype => datatype) public mapvar1; //Mapping to store a Key-Value 

    uint64 intvar1;	// Variable of Unsigned Integer with 64 bits 
    uint128 intvar2;    // Variable of Unsigned Integer with 128 bits
    int256 intvar3;     // Variable of Signed Integer with 256 bits
    
    string  stringvar;	// Variable of String
    
    address addressvar; // Variable of Address - to store Ethereum Wallet Address or Smart Contract Address
    
    address owner; // For assigning owner of the smart contract
    
    struct structvar {
        
        uint256 structvar1;
        string  structvar2;
    }
    
    structvar varstruct;
    
    /** Constructor */
    constructor() {}
    
    /** modifier to provide access control **/
    modifier isOwner() {
        // If the first argument of 'require' evaluates to 'false', execution terminates and all changes to the state and to Ether balances are reverted.
        require(msg.sender == owner, "Caller is not owner");
        _;
    }
    
    
    /**
     * @dev Example Function to perform operation and store (only owner can make a successful call)
     * @param num value to store
     */
    function <<functionName>>(paramaters) public isOwner {
        // do function operations
    }
    
     /**
     * @dev Example Function to return values
     * @param num value to store
     */
    function <<functionName1>>() public view returns(datatypes) {
        return (variables);
    }

}


On Compilation of Solidity Program, we get ABI (Application Binary Interface) along with Bytecodes. ABI is similar to API. On Running the Smart Contract, which actually deploys the Smart Contract on to the Blockchain, we get Smart Contract Address. These are the two important details required for accessing the Contract from the WebUI or FrontEnd in general.

Metamask and Faucet

Metamask is a Browser Extension, is a tool which acts as a bridge for communication between the traditional browser to the blockchain (Distributed Web). Web3.js is used in the User Interface Component to enable communication with the Blockchain via Metamask. Metamask also has an inbuilt Wallet which on installation creates a Ethereum Wallet Address (identified by Hex numbers). More on Metamask is here.

Faucet is a developer support system which provides the Ether for development and testing purposes to our wallet address. Click Here to access the Faucet and get your Test Ether.

Infura Service

Infura is a Ethereum and IPFS Service provider. Instead of running our own Ethereum and IPFS node at local machine, we can use their service through the APIs. You can signup to use their service.

Web3.js Basics

Web3.js is a collection of javascript libraries which enables communication with local or remote Ethereum using HTTP or RPC communication.

Below Web3.js code should be included in your HTML page to detect and define the Web3 Communication.

    <script src="https://cdn.jsdelivr.net/npm/web3@1.2.8/dist/web3.js"></script>
    <script>	
	
	var account;
	window.addEventListener('load', async () => {

	
		if (typeof window.ethereum !== 'undefined') { 
			console.log("MetaMask is Available :) !"); 
			}
			
		// Modern DApp browsers
		if (window.ethereum) {
			window.web3 = new Web3(ethereum);
			
			// To prevent the page reloading when the MetaMask network changes
			ethereum.autoRefreshOnNetworkChange = false;
			
			// To Capture the account details from MetaMask
			const accounts = await ethereum.enable();
			account = accounts[0];
				
			}
		// Legacy DApp browsers
		else if (window.web3) {
			//window.web3 = new Web3(web3.currentProvider);
			window.web3 = new Web3(new Web3.providers.HttpProvider("https://ropsten.infura.io/v3/cbd9dc11b30147e9a2cc974be655ef7c")); 
			}
		// Non-DApp browsers
		else {
			console.log('Non-Ethereum browser detected. Please install MetaMask');
			}
			
			});
    </script>			

IPFS

Interplanetary File System is a protocol and a peer-to-peer file sharing and storage distributed network. IPFS is a content-addressed system, where a file is identified by its hash. IPFS complements the Blockchain for storage.

CryptoTokens

ERC - Ethereum Request for Comments is a standard within Ethereum Blockchain similar to RFC’s for Internet Engineering Task Force (IETF).

Identity Management Standards

Identity Managment is one of the major challenges faced across the globe and in various application domain. Ethereum proposed two standards for Identity Management (ERC-725) and Claim verification (ERC-735).

Oracles

Oracles are third-party services available for smart contracts to get external information like prices, weather details, stock market details, etc., for processing and decision making. Provable is one of the leading oracle service provider for different blockchains including Ethereum, EOS, R3 Corda, Hyperledger Fabric. There are different datasources available, from which we can request information from any as needed.

- URL 
- random
- computation
- IPFS
- WolframAlpha

Ganache

Ganache is a personal blockchain for rapid Ethereum DApp from develop, deploy and test in safe environment. Ganache can mine, acts as a wallet which has 10 accounts each with 100 ETH Balance, allows the user to explore the blocks and transactions happened so far.

Truffle

Truffle Framework is the popular development framework for Etherum Blockchain which handles the complete smart contract life cycle management.

npm install -g truffle
truffle unbox
truffle init
truffle compile
truffle migrate (deploy)
truffle develop
truffle console
truffle debug
truffle test
truffle publish

The developer can interact with the contract and test using the built-in truffle console. To start the truffle console use the below command

truffle console

Solidity Source Code Testing

Solidity Program or Source Code has to be tested for logic errors, ensure best coding practices, proper memory usage and to detect privacy and security issues. Through a dedicated unit test either through solidity or js, we can test the solidity code before deploying it in the Mainnet.

Below you can see the Javascript based testing through Truffle Framework. The file should be placed in the test folder and shall be executed by the command

truffle test
FileName: SampleTest.js


const contractvar = artifacts.require(<<contract-name>>);

contract("Testing Contract", async accounts => {
	
  it("Testcase 1", async () => {
    const instance = await contractvar.deployed();
    await instance.function1(param1);
    var output = await instance.function2.call();
    assert.equal(output, <<expected-result>>);
  });
  
  it("Testcase 2", async () => {

  });
  
  ...
  ...
  
  it("Testcase n", async () => {

  });

});

Solidity Vulnerability Analysis

Smart Contracts as known is the contract agreed between the parties transacting on Ethereum Blockchain. The Smart contract and the values maintained by the contract are stored in this immutable ledger, so it is very important to ensure that the smart contract does not have any vulnerability.

Examples