1 of 96

�CS61065: Theory and Applications of Blockchain 

Ethereum

INDIAN INSTITUTE OF TECHNOLOGY

KHARAGPUR

Sandip Chakraborty

sandipc@cse.iitkgp.ac.in

Department of Computer Science and Engineering

2 of 96

CONTENT

  • Ethereum Introduction
  • Ethereum Networks
  • Ethereum Client
  • Go-Ethereum Client (geth)
  • Infura
  • TestRPC
  • Query using RPC over HTTP
  • Solidity

Indian Institute of Technology Kharagpur

3 of 96

Ethereum – Decentralized Computation Platform

  • Ethereum is the community-run technology powering the Cryptocurrency ether (ETH) and thousands of decentralized applications.
  • Ethereum is a network of computers all over the world that follow a set of rules called the Ethereum protocol
  • It is an decentralized, open and programmable blockchain platform.
  • It also powers applications that everyone can use and no one can take down.
  • The core innovation is that you can do all this without trusting a central authority that could change the rules or restrict your access.

Indian Institute of Technology Kharagpur

4 of 96

Ethereum – Decentralized Computation Platform

  • It allows development of decentralized blockchain applications (DApps) through the use of the smart contracts that perform arbitrarily complex computation.
  • The platform is not owned or controlled by any entity and is powered by the peers who run the Ethereum nodes.
  • You can create an Ethereum account from anywhere, at any time, and explore a world of apps or build your own.

Indian Institute of Technology Kharagpur

5 of 96

Ethereum Consensus Mechanism

  • The Ethereum network has been upgraded from the original Proof of Work consensus mechanism to Proof of Stake during The Merge.
  • The Merge was executed successfully on September 15, 2022.
  • The Merge refers to the Ethereum upgrade that merged Ethereum Mainnet with the Beacon Chain Proof of Stake system. This marked the end of Proof of Work (PoW) for Ethereum, and the full transition to Proof of Stake (PoS).
  • The Merge reduced Ethereum's energy consumption by ~99.95%.
  • Tt eliminated the need for energy-intensive mining and instead enabled the network to be secured using staked ETH

Indian Institute of Technology Kharagpur

6 of 96

Key Terms

Ether

Gas

Wallet

Smart Contract

DApps

Indian Institute of Technology Kharagpur

7 of 96

Ethereum Stack

Ethereum Virtual Machine (EVM)

Smart Contract

Ethereum Nodes

Ethereum Client APIs

End-User Application

Indian Institute of Technology Kharagpur

8 of 96

Blockchain Stack

Tools and Interfaces

GUI

(Mist Wallet & Browser)

DApp

Framework

(Truffle, Embark)

Ethereum Clients

(Geth, PyEthApp)

Compilers

(Solidity, Serpent)

JSON RPC

Web3.js API

Decentralized Applications (DApps)

Front-End

(HTML, CSS)

Back-End

(JavaScript)

Contracts

(Solidity, Serpent, LLL)

Ethereum

(Decentralized Computation)

Ethereum Protocol

Ethereum Virtual Machine (EVM)

Blockchain

Accounts

Mining

Transactions

Contracts

Indian Institute of Technology Kharagpur

9 of 96

Ethereum Network

  • Distributed network of computers, known as nodes that can verify blocks and transaction data.
  • An application, known as a client, running on your computer is a node.

P2P

EVM

PoS

Consensus

Eth State

TX Mempool

NPTEL Blockchain and its Applications https://onlinecourses.nptel.ac.in/noc23_cs47/unit?unit=53&lesson=55

Indian Institute of Technology Kharagpur

10 of 96

Ethereum Accounts

Externally Owned Account (EOA)

Account Address

Account Keys

Ether Balance

Contract Account

Contract Address

Contract Code

Ether Balance

Indian Institute of Technology Kharagpur

11 of 96

Externally Owned Account (EOA)

Externally Owned Account (EOA)

Account Address

Account Keys

Ether Balance

  • Owned and controlled by the users
  • Can send transactions to other EOAs or contract address
  • Has a private-public keypair associated with it
  • Account address is derived from the public key
  • When a new EOA is created, a JSON keyfile is created which has the public and private keys associated with the account
  • The private key is encrypted with the password which is provided while creating the account
  • For sending transactions to other accounts, the private key and the account password are required.

Indian Institute of Technology Kharagpur

12 of 96

Contract Account

  • The contract accounts are controlled by the associated contract code which is stored with the account.
  • The contract code execution is triggered by the transactions sent by EOAs or messages sent by other contracts.

Contract Account

Contract Address

Contract Code

Ether Balance

Indian Institute of Technology Kharagpur

13 of 96

Ethereum Transactions

  • Transactions are cryptographically signed instructions from accounts.
  • An account will initiate a transaction to update the state of the Ethereum network.
  • The simplest transaction is transferring ETH from one account to another.
  • An Ethereum transaction refers to an action initiated by an externally-owned account, in other words an account managed by a human, not a contract.

World State

(t)

World State

(t+1)

Transaction

Requires:

    • Access to account private key
    • Gas

Indian Institute of Technology Kharagpur

14 of 96

Ethereum Transactions

  • Transactions, which change the state of the EVM, need to be broadcast to the whole network.
  • Any node can broadcast a request for a transaction to be executed on the EVM; after this happens, a validator will execute the transaction and propagate the resulting state change to the rest of the network.
  • Transactions require a fee and must be included in a validated block.

Indian Institute of Technology Kharagpur

15 of 96

Ethereum Transactions

  • A submitted transaction includes the following information:

{

from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",

to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",

gasLimit: "21000",

maxFeePerGas: "300",

maxPriorityFeePerGas: "10",

nonce: "0",

value: "10000000000"

}

Indian Institute of Technology Kharagpur

16 of 96

Ethereum Transactions

  • A submitted transaction includes the following information:

{

from: "0xEA674fdDe714fd979de3EdF0F56AA9716B898ec8",

to: "0xac03bb73b6a9e108530aff4df5077c2b3d481e5a",

gasLimit: "21000",

maxFeePerGas: "300",

maxPriorityFeePerGas: "10",

nonce: "0",

value: "10000000000"

}

address of the sender

receiving address 

amount of ETH to transfer from sender to recipient

the maximum amount of gas units that can be consumed by the transaction

the maximum price of the consumed gas

to be included as a tip to the validator

Indian Institute of Technology Kharagpur

17 of 96

Ethereum Transactions Types

  • On Ethereum there are a few different types of transactions:
  • Regular transactions: a transaction from one account to another.
  • Contract deployment transactions: a transaction without a 'to' address, where the data field is used for the contract code.
  • Execution of a contract: a transaction that interacts with a deployed smart contract. In this case, 'to' address is the smart contract address.

Indian Institute of Technology Kharagpur

18 of 96

Ether

  • Within Ethereum, there are two native “tokens”, Ether and Gas. 
  • Ether is the currency which is used in the Ethereum Blockchain network
  • The miners in the Ethereum network receive mining rewards in the form of Ethers.
  • The base unit of Ether is Wei
  • 1 Ether = 1018 Wei

Indian Institute of Technology Kharagpur

19 of 96

Gas

  • Gas is the name of the crypto-fuel which is consumed for performing the operations or conduct transaction on the Ethereum network.
  • Each Ethereum transaction requires computational resources to execute.
  • All the transactions on the network are charged a certain amount of gas.
  • While sending a transaction, the sender sets a gas price which represents the fee the sender is willing to pay for gas
  • The senders of the transactions are charged a gas fee, which is paid to the miners and the balance is refunded to the sender.
  • Each transaction requires a fee.
  • Gas is paid as amounts of Ethers.

Indian Institute of Technology Kharagpur

20 of 96

Ethereum Units

Unit

Wei Value

Wei

wei

1 wei

1

kwei (babbage)

1e3 wei

1000

mwei (lovelace)

1e6 wei

1,000,000

gwei (shannon)

1e9 wei

1,000,000,000

microether (szabo)

1e12 wei

1,000,000,000,000

milliether (finney)

1e15 wei

1,000,000,000,000,000

ether (ETH)

1e18 wei

1,000,000,000,000,000,000

Indian Institute of Technology Kharagpur

21 of 96

EVM - Ethereum Virtual Machine

  • Instead of a distributed ledger, Ethereum is a Distributed State Machine/Replicated State Machine.
  • EVM is a cloud computer run that is operated by all the nodes that contribute to this.
  • Ledger data holds the state - accounts, balances, and other variables.
  • Transactions deterministically change the machine from one state to another.
  • Each computer on the Ethereum network runs a piece of software that is basically just computing the output of the smart contract transactions.
  • Similar to a physical computer parts, EVM has also memory, storage and a part specialized for computing numbers.

NPTEL Blockchain and its Applications https://onlinecourses.nptel.ac.in/noc23_cs47/unit?unit=53&lesson=55

Indian Institute of Technology Kharagpur

22 of 96

EVM - Ethereum Virtual Machine

  • EVM is a huge Merkle Patricia Trie which Provides a cryptographically authenticated data structure that can be used to store all (key, value) binding.
  • In this each account is linked with hashes and is reducible to a root hash stored on the blockchain.
  • Once the transaction is confirmed the state of the chain is updated.

Indian Institute of Technology Kharagpur

23 of 96

NODES AND CLIENTS

  • Ethereum is a distributed network of computers (known as nodes) running software that can verify blocks and transaction data.
  • The software must be run on your computer to turn it into an Ethereum node. There are two separate pieces of software (known as 'clients') required to form a node.

Indian Institute of Technology Kharagpur

24 of 96

NODES AND CLIENTS

  • The execution client (also known as the Execution Engine, EL client or formerly the Eth1 client) listens to new transactions broadcasted in the network, executes them in EVM, and holds the latest state and database of all current Ethereum data.
  • The consensus client (also known as the Beacon Node, CL client or formerly the Eth2 client) implements the proof-of-stake consensus algorithm, which enables the network to achieve agreement based on validated data from the execution client. There is also a third piece of software, known as a 'validator' that can be added to the consensus client, allowing a node to participate in securing the network.

Indian Institute of Technology Kharagpur

25 of 96

Node Types

  • Full node: Stores full blockchain data 
  • Archive node: Stores everything kept in the full node and builds an archive of historical states.
  • Light node: Instead of downloading every block, light nodes only download block headers. 

  • You can run your own node or  you can use a third party API provider.

Indian Institute of Technology Kharagpur

26 of 96

Sync modes

  • Geth cannot sync until the connected consensus client is synced.
  • This is because Geth needs a target head to sync to. 
  • Syncing is the process by which Geth catches up to the latest Ethereum block and current global state.
  • You can start Geth in one of three different sync modes using the ‐‐syncmode "<mode>" argument that determines what sort of node it is in the network:

full: Downloads all blocks (including headers, transactions, and receipts) and generates the state of the blockchain incrementally by executing every block.

snap (Default): Same functionality as fast, but with a faster algorithm.

fast: Downloads all blocks (including headers, transactions and receipts), verifies all headers, and downloads the state and verifies it against the headers.

light: Syncs very quickly and stores the bare minimum of blockchain data.  Light nodes only process block headers, not entire blocks. (Light nodes are not currently working on proof-of-stake Ethereum.)

Indian Institute of Technology Kharagpur

27 of 96

Programmatically access Ethereum networks

Ethereum Node

Smart Contract 1

Code

Storage

User

Web UI

web3.js

ethers.js

Ethereum Network (Mainnet / Testnet)

geth / Infura

Endpoints

Ethereum Client/ Node

Smart Contract 2

Accounts

Ethereum Node

Smart Contract 1

Code

Storage

Smart Contract 2

Accounts

Ethereum Node

Smart Contract 1

Code

Storage

Smart Contract 2

Accounts

JSON - RPC

DAPP UI

Indian Institute of Technology Kharagpur

28 of 96

Ethereum Mainnet

  • Display real time and historical statistics about the network and nodes. 

Indian Institute of Technology Kharagpur

29 of 96

Ethereum Mainnet

  • No central server
  • Independent nodes connected in a P2P network.

Indian Institute of Technology Kharagpur

30 of 96

Prerequisites

  • Virtual Machine Ubuntu 20.04 or above, 4 or 8 GB RAM
  • Node.js and npm installed.
  • Geth: Ethereum Client
  • Google Chrome
  • Node.js: For building the front-end and interacting with smart contracts.
  • Solidity: For writing the smart contract.
  • Remix: An online IDE to write and compile Solidity contracts.
  • MetaMask: A wallet to manage Ethereum accounts.
  • Infura: For connecting to the Ethereum network without running your own node.

Indian Institute of Technology Kharagpur

31 of 96

Ethereum Client

  • Ethereum Client allow you set up an Ethereum Node on your Computer.
  • An Ethereum Client is like Java Virtual Machine (JVM) and allows you to run Ethereum Programs.
  • With an Ethereum Client you can participate in the Ethereum network and perform tasks such as:
    • creating accounts and contracts
    • sending ether to other accounts
    • sending transactions to contracts
    • mining on Ethereum network and etc.

Indian Institute of Technology Kharagpur

32 of 96

Ethereum Client

  • Ethereum Clients supports:
    • Go (go-ethereum)
    • C++ (cpp-ethereum)
    • Python (pyethapp)
    • Javascript (ethereumjs-lib)
    • Ruby (ruby-ethereum)
    • Java (Ethereum(J))
    • Haskell (EthereumH)
    • Rust (Parity)

Indian Institute of Technology Kharagpur

33 of 96

Go-Ethereum Client (geth)

  • Geth is an execution client.
  • Official Go implementation of the Ethereum protocol
  • Main Ethereum CLI client
  • Entry point into the Ethereum network
    • main, test, or private net
  • Capable of running as:
    • Full node (default)
    • Archive node (retaining all historical state)
    • Light node (retrieving data live).
  • Provides JSON RPC endpoints exposed on top of HTTP, WebSocket and/or IPC transports.

Indian Institute of Technology Kharagpur

34 of 96

Installing Go-Ethereum Client (geth)

  • Ubuntu
    • Add Ethereum repository:

sudo apt-get install software-properties-common

sudo add-apt-repository -y ppa:ethereum/ethereum

    • Then install the stable version of go‐ethereum:

sudo apt-get update

sudo apt-get install ethereum

Indian Institute of Technology Kharagpur

35 of 96

Managing Ethereum Accounts

  • USAGE:

geth account command [command options] [arguments...]

  • COMMANDS:
    • list Print summary of existing accounts
    • new Create a new account
    • update Update an existing account
    • import Import a private key into a new account

Indian Institute of Technology Kharagpur

36 of 96

Create an account

  • USAGE:

geth account new

Indian Institute of Technology Kharagpur

37 of 96

List Accounts

  • USAGE:

geth account list

  • To See the content of the wallet

cat ~/.Ethereum/keystore/<Keyfile-Name>

Indian Institute of Technology Kharagpur

38 of 96

Consensus Client

  • Geth also needs to be connected to a consensus client in order to function as an Ethereum node
  • Historically, an execution client alone was enough to run a full Ethereum node. However, since Ethereum swapped from proof-of-work (PoW) to proof-of-stake (PoS) based consensus, Geth needs to be coupled to another piece of software called a "consensus client".
  • Note: As an alternative it is possible to run with an integrated beacon light client for non-production settings.
  • In order to connect to a consensus client, Geth must expose a port for the inter-client RPC connection

Indian Institute of Technology Kharagpur

39 of 96

Consensus Client

  • 5 Consensus Clients:
    1. Lighthouse: written in Rust
    2. Nimbus: written in Nim
    3. Prysm: written in Go
    4. Teku: written in Java
    5. Lodestar: written in Typescript

Indian Institute of Technology Kharagpur

40 of 96

Beacon Light Client

  • blsync is a beacon chain light client.
  • Integrated within Geth, blsync eliminates the necessity of running a separate consensus client, making it ideal for use-cases that do not require full validation capabilities. 
  • can be run in two modes: integrated or standalone
  • To run blsync as part of Geth, you need to specify a public HTTP endpoint and a checkpoint (https://s1na.github.io/light-sync-endpoints/ )
    • Mainnet
    • Holesky
    • Sepolia
    • A checkpoint is the block root of the first proposed slot of a finalized beacon epoch.

Indian Institute of Technology Kharagpur

41 of 96

Beacon Light Client

  • Root address in sepolia.beaconcha.in (1 hour old)
  • 0x87dc3f2035f27865bb10c71b405ea1d644eb0201e9d42f8bfd520a044c4b7857

  • geth --sepolia --beacon.api https://sepolia.lightclient.xyz --beacon.checkpoint 0xd2e616c2553338be04608778fd0cef75f8bdc9c3273eacb80a607ca01e8b4046

Indian Institute of Technology Kharagpur

42 of 96

Connect to a network

  • The default behaviour for Geth is to connect to Ethereum Mainnet.
  • In addition to the mainnet, geth recognizes a few testnets which you can connect to via the respective flags:
  • --sepolia: Sepolia Proof-of-Stake test Netwok

https://sepolia.etherscan.io/

  • --beaconcha.in: Beaconcha proof-of-work test network

https://beaconcha.in/

  • --rinkeby: Rinkeby proof-of-authority test network

https://rinkeby.etherscan.io/

  • --goerli: Goerli proof-of-authority test network

https://goerli.etherscan.io/

Indian Institute of Technology Kharagpur

43 of 96

Connecting to sepolia testnet

geth --sepolia --datadir light-sepolia-dir

Indian Institute of Technology Kharagpur

44 of 96

Interacting with Geth

  • You can interact with Geth in two ways:
    • Directly with the node using the JavaScript console over IPC

Or

    • Connecting to the node remotely over HTTP using RPC.
  • IPC allows you to do more, especially when it comes to creating and interacting with accounts, but you need direct access to the node.
  • RPC allows remote applications to access your node but has limitations and security considerations.

Indian Institute of Technology Kharagpur

45 of 96

Using RPC over HTTP

 geth --sepolia --http

Indian Institute of Technology Kharagpur

46 of 96

Query Balance

  • Querying the balance of an account
  • Using Post:
    • POST request to the HTTP endpoint (default: 127.0.0.1:8545)
    • JSON Payload:

{

"jsonrpc": "2.0",

"method": "eth_getBalance",

"params": [

"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",

"latest”

],

"id": 1

}

Indian Institute of Technology Kharagpur

47 of 96

Query using curl

  • Querying the balance of an account:
  • POST request using curl:

Request:

curl 127.0.0.1:8545 \

  -X POST \

  -H "Content-Type: application/json" \

  -d '{"jsonrpc":"2.0","method":"eth_gasPrice","params": [],"id":1}’

Response:

Indian Institute of Technology Kharagpur

48 of 96

Query using requests

  • Querying the balance of an account:
  • Using Python (requests Library):
    • Install requests library:

pip install requests

    • Example Python script to send a POST request:

Indian Institute of Technology Kharagpur

49 of 96

Query using requests

import requests

url = http://127.0.0.1:8545

payload = {

"jsonrpc": "2.0",

"method": "eth_getBalance",

"params": [

"0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4",

"latest"

],

"id": 1

}

headers = {

"Content-Type": "application/json"

}

response = requests.post(url, data=json.dumps(payload), headers=headers)

Indian Institute of Technology Kharagpur

50 of 96

Query using Tools

  • Postman: send HTTP requests, including JSON-RPC calls.
  • Ethereum JSON-RPC Console Tools (e.g., geth attach):

geth attach http://127.0.0.1:8545

eth.getBalance("0x9808f22453Ee87cc23eA76ca7Ed66a4F294d54D4", "latest")

Indian Institute of Technology Kharagpur

51 of 96

Unlock Account

  • Create new account for Sepolia testnet, suppose password is set to "12345"
  • Write account password in a text file. Here we name it pwd.txt
    • geth --sepolia account new
    • echo "12345" > pwd.txt

  • Unlock account while starting geth
    • geth --sepolia --http --allow-insecure-unlock --unlock 0xD7Ff489A267d6310c68F2756991BAF09204806F8 --password pwd.txt

Indian Institute of Technology Kharagpur

52 of 96

MetaMask

  • MetaMask is a software cryptocurrency wallet used to interact with the Ethereum blockchain.
  • It allows users to access their Ethereum wallet through a browser extension or mobile app, which can then be used to interact with decentralized applications.

Indian Institute of Technology Kharagpur

53 of 96

Extracting Private Key of Account in Geth

curl -LSs https://raw.githubusercontent.com/gochain/web3/master/install.sh | sh

web3 account extract --keyfile <Keyfile-Location> --password <Password>

Example:

web3 account extract --keyfile /home/utkalika/.ethereum/keystore/UTC--2024-08-20T15-51-10.491464251Z--d7ff489a267d6310c68f2756991baf09204806f8 --password 12345

  • This private key can used to import the account in Cryptocurrency wallet like MetaMask (Add Account or Hardware Wallent -> Import Account -> Private Key)

Indian Institute of Technology Kharagpur

54 of 96

Get ether in testnet

Indian Institute of Technology Kharagpur

55 of 96

eth_sendTransaction

  • POST sendTransaction: Creates new message call transaction or a contract creation, if the data field contains code.
  • Parameters
    • object - The transaction object
    • from: DATA, 20 Bytes - The address the transaction is send from.
    • to: DATA, 20 Bytes -The address the transaction is directed to.
    • gas: QUANTITY - (optional, default: 90000) Integer of the gas provided for the transaction execution. It will return unused gas.
    • gasPrice: QUANTITY - (optional, default: To-Be-Determined) The gasPrice used for each paid gas
    • value: QUANTITY - (optional) Integer of the value sent with this transaction
    • data: DATA - The compiled code of a contract OR the hash of the invoked method signature and encoded parameters. For details see Ethereum Contract ABI
    • nonce: QUANTITY - (optional) Integer of a nonce. This allows to overwrite your own pending transactions that use the same nonce.
  • Returns
    • DATA: 32 Bytes - the transaction hash, or the zero hash if the transaction is not yet available.

Indian Institute of Technology Kharagpur

56 of 96

Prepare Transaction

{

"jsonrpc": "2.0",

"method": "eth_sendTransaction",

"params": [

{

"from": "04e7ad5d91bedef78e57ee6c56db10de39478232",

"to": "3873dcdb0d5177b2be28ffb911e08be6dbb40f7a",

"value": "0x2386F26FC10000"

}

],

"id": 0

}

0.1 Ether

Indian Institute of Technology Kharagpur

57 of 96

Submit Transaction

curl -X POST http://localhost:8545 \

-H "Content-Type: application/json" \

--data{"jsonrpc": "2.0", "method": "eth_sendTransaction", "params": [{"from": "04e7ad5d91bedef78e57ee6c56db10de39478232", "to": "3873dcdb0d5177b2be28ffb911e08be6dbb40f7a", "value": "0x2386F26FC10000"}],"id": 0}

Indian Institute of Technology Kharagpur

58 of 96

View Transaction on Etherscan

Indian Institute of Technology Kharagpur

59 of 96

Many More RPC Methods

Indian Institute of Technology Kharagpur

60 of 96

INFURA

  • Infura is an Infrastructure-as-a-Service (IaaS) product that provides tools to help developers, enterprises, and DApp teams connect their apps to the Ethereum network and other decentralized platforms. 
  • Infura's network of hosted Ethereum clients supports testnets and mainnet via client-compatible JSON-RPC, over HTTPS and WSS
  • Infura provides endpoints to Ethereum's API.
  • Infura provides access to the Ethereum JSON-RPC API method library that interacts with the Ethereum blockchain.
  • Methods include functionality for reading and writing data to the network, and executing smart contracts.

Indian Institute of Technology Kharagpur

61 of 96

Getting Started with INFURA

  • Sign up to Infura
    • https://app.infura.io/
  • Configure your API key
  • In the API key page that appears, select My First Key to access your API key settings.
  • In the All Endpoints tab, select the networks that you wish to connect to, and select Save Changes.
  • Send requests

Indian Institute of Technology Kharagpur

62 of 96

INFURA – Sending Requests

  • Use the API key when sending requests.
  • The following examples interact with the Ethereum network by sending requests using HTTP.
  • Get the current block number: Retrieve the current block number.

Request:

Response

curl https://sepolia.infura.io/v3/<INFURA-API-KEY> \

-X POST \

-H "Content-Type: application/json" \

--data '{"jsonrpc": "2.0", "id": 1, "method": "eth_blockNumber", "params": []}'

{"jsonrpc":"2.0","id":1,"result":"0x63dcea"}

Indian Institute of Technology Kharagpur

63 of 96

INFURA – Sending Requests

  1.  View the Ether balance of a specified address

Request:

Response

curl https://sepolia.infura.io/v3/<INFURE-API-KEY> \

-X POST \

-H "Content-Type: application/json" \

-d '{"jsonrpc":"2.0","method":"eth_getBalance",

"params": ["ADDRESS", "latest"],"id":1}'

{"jsonrpc":"2.0","id":1,"result":"0x1c535fcc941d10cf"}

Indian Institute of Technology Kharagpur

64 of 96

INFURA – Sending Requests Using Postman

Indian Institute of Technology Kharagpur

65 of 96

INFURA – Sending Requests Using NodeJS

  • Create a folder in your system
    • mkdir <PROJECT_NAME>
    • cd <PROJECT_NAME>
    • In your project folder, install the Node Fetch package using npm
    • npm i node-fetch
      • On Running this will generate few files in your PROJECT FOLDER
      • Modify the package.json as below:

{

"name": ”<PROJECT_NAME>",

"version": "1.0.0",

"main": "index.js",

"type": "module",

"dependencies": {

"node-fetch": "^2.6.1"

}}

    • create index.js and write the code given in right side box. Replace YOUR-API-KEY with your actual Infura API key.
    • node index.js

import fetch from 'node-fetch';

fetch("https://sepolia.infura.io.infura.io/v3/YOUR-API-KEY", {

method: "POST",

headers: {

"Content-Type": "application/json"

},

body: JSON.stringify({

jsonrpc: "2.0",

method: "eth_blockNumber",

params: [],

id: 1

})

})

.then(response =>

response.json()

)

.then(data => {

console.log(data);

})

.catch(error => {

console.error(error);

});

OUTPUT:

{ jsonrpc: '2.0', id: 1, result: '0x63dd6b' }

Indian Institute of Technology Kharagpur

66 of 96

Sending Requests Using web3.js

  • web3.js is a collection of libraries that allow you to interact with a local or remote ethereum node using HTTP, IPC or WebSocket.
  • It can connect using:
    • HTTP
    • IPC
    • WebSocket
  • Create a Project Folder and in your project folder, install the latest version of the web3.js library
    • npm install web3
  • Check node and npm version
    • node --version
    • npm –version

https://web3js.readthedocs.io/

Indian Institute of Technology Kharagpur

67 of 96

Connecting web3.js to Clients

Create your Javascript file and copy the following code:

Connecting to INFURA:

var { Web3 } = require("web3");

var provider = "https://sepolia.infura.io/<YOUR-API-KEY>";

var web3Provider = new Web3.providers.HttpProvider(provider);

var web3 = new Web3(web3Provider);

�web3.eth.getBlockNumber().then((result) => {

console.log("Latest Ethereum Block is ", result);

});

Connecting to Geth:

var { Web3 } = require("web3");

var provider = “http://localhost:8545";

var web3Provider = new Web3.providers.HttpProvider(provider);

var web3 = new Web3(web3Provider);

Run the code using: node index.js

Indian Institute of Technology Kharagpur

68 of 96

Query Balance

  • Create a file with .js extension. Example: ”checkBalance.js

var { Web3 } = require("web3");

var provider = "http://localhost:8545";

var web3Provider = new Web3.providers.HttpProvider(provider);

var web3 = new Web3(web3Provider);

console.log("Balance of the account 0x8cD5F171e45d899d7FeB56206a030d749a1A7257 is:");

web3.eth.getBalance("0x8cD5F171e45d899d7FeB56206a030d749a1A7257").then(console.log);

  • Execute it in the terminal:

$ node checkBalance.js

Indian Institute of Technology Kharagpur

69 of 96

Ethereum Smart Contracts

  • Permissionless Blockchain capable of executing Smart Contracts.
  • Ethereum has Turing-complete smart contract functionality. 
  • Smart contracts are computer programs living on the Ethereum blockchain.
  • They execute when triggered by a transaction from a user.

Indian Institute of Technology Kharagpur

70 of 96

Smart Contracts

  • A Smart Contract is a piece of code that resides on the blockchain network and is identified by a unique address.
  • It includes a set of executable functions and state variables.
  • The functions are executed when transactions are sent to the functions.
  • The transactions include input parameters which are required by the functions in the contract.
  • Upon execution of a function, the state variables in the contract change depending on the logic implemented in the function.

Smart Contract

Value

Address

State

Functions

External Owned Account (EOA)

Transaction

(Data, Value)

Messages to other contracts

(Data, Values)

Events

Indian Institute of Technology Kharagpur

71 of 96

Ethereum Smart Contracts

  • Contracts can be written in various high-level languages (Solidity or Vyper)
  • Language-specific compilers for smart contracts (Such as Solidity or Vyper) are used to compile the contracts into Ethereum-specific binary format (Ethereum Virtual Machine(EVM) bytecode).
  • Once compiled, the contracts are uploaded to the blockchain network which assigns a unique address to each contract.
  • Any user on the blockchain network can trigger the functions in the contract by sending transactions to the contract.
  • Solidity is used to create smart contracts, which are self-executing code stored on the blockchain. Once deployed, they can automatically execute predefined actions when specific conditions are met.

Indian Institute of Technology Kharagpur

72 of 96

Ethereum Smart Contracts

  • Can be written in various high-level languages (Solidity or Python)
  • Language-specific compilers for smart contracts (Such as Solidity or Serpent) are used to compile the contracts into bytecode.
  • Once compiled, the contracts are uploaded to the blockchain network which assigns a unique address to each contract.
  • Any user on the blockchain network can trigger the functions in the contract by sending transactions to the contract.
  • Solidity is used to create smart contracts, which are self-executing code stored on the blockchain. Once deployed, they can automatically execute predefined actions when specific conditions are met.

Smart Contract Code

  • Solidity
  • Vyper

Compiler

Bytecode

Application Binary

Interface (ABI)

Smart Contract

Deploy

web3.js

Execute

Indian Institute of Technology Kharagpur

73 of 96

Ethereum Smart Contracts

  • Smart contract execution is decentralized, meaning all nodes in the blockchain network run the contract code to ensure the same state transition occurs across the network. This is a critical part of the block validation process.
  • Transactions involving smart contracts are processed during the mining of blocks, and once mined, the contract code is executed by all participating nodes to maintain the integrity and consistency of the blockchain’s state.

Indian Institute of Technology Kharagpur

74 of 96

Solidity & Bytecode

  • OPCODE: Language that shows operational code or rather instruction.
  • The EVM take these instructions to perform a smart contact transaction.
  • Example: PUSH, mSTORE, ISZERO, CALL and more.
  • Each of these OPCODEs does cost a certain amount of money to be run on the EVM
  • Add up all the opcodes in a single smart contact and multiply each OPCODE by price of each opcode you will get total amount of gas or money that it takes to deploy or use a smart contact.
  • Gas: Unit that measures the amount of computational effort required to execute specific operations on the network

Indian Institute of Technology Kharagpur

75 of 96

Solidity & Bytecode

compile

Bytecode

OPCODE

Add up all opcodes, Multiply by price = GAS PRICE

Smart Contract

Bytecode

Indian Institute of Technology Kharagpur

76 of 96

Solidity

  • High-level language for implementing smart contracts
    • Statically typed
    • Supports inheritance
    • Access Control
    • Libraries
    • Complex user-defined types
  • Syntax influenced by Javascript and C++

// SPDX-License-Identifier: GPL-3.0

pragma solidity >=0.8.2 <0.9.0;

/**

* @title Storage

* @dev Store & retrieve value in a variable

* @custom:dev-run-script ./scripts/deploy_with_ethers.ts

*/

contract Storage {

uint256 number;

/**

* @dev Store value in variable

* @param num value to store

*/

function store(uint256 num) public {

number = num;

}

/**

* @dev Return value

* @return value of 'number'

*/

function retrieve() public view returns (uint256){

return number;

}

}

Indian Institute of Technology Kharagpur

77 of 96

Solidity Syntax and Structure

  • A Solidity contract generally contains the following:
    • State Variables: These are stored in the contract’s storage and are used to maintain the contract’s state.
    • Functions: It include the code which is executed when transactions are sent to the contract. A special function “Constructor” is executed only once when the contract is deployed.
    • Modifiers: It can be used within a contract to change the behaviour of the function. For example, a modifier can be used to check for a condition before executing a function.
    • Events: Events are used to track the execution of the transactions sent to the contract

Indian Institute of Technology Kharagpur

78 of 96

Data Types

  • Solidity supports various data types including:
    • Primitive types: uint, int, address, bool
    • Complex types: Arrays, structs, mappings (key-value storage)

Indian Institute of Technology Kharagpur

79 of 96

Global Variables and Functions

  • Solidity has built-in global variables and functions that provide access to blockchain-related data, such as:
    • msg.sender: The address of the function caller
    • msg.value: The amount of Ether sent with a transaction
    • block.timestamp: The timestamp of the current block

Indian Institute of Technology Kharagpur

80 of 96

Ether Transactions

  • Solidity allows contracts to send and receive Ether (the native cryptocurrency on Ethereum).
  • Transactions are often carried out using payable functions.

function deposit() public payable {

// Function to accept Ether into the contract

}

function withdraw() public {

payable(msg.sender).transfer(address(this).balance);

}

Indian Institute of Technology Kharagpur

81 of 96

Inheritance

  • Solidity supports contract inheritance, enabling code reuse by allowing contracts to inherit properties and functions from other contracts.

contract Base {

uint256 data;

function set(uint256 x) public { data = x; }

}

contract Derived is Base {

function get() public view returns (uint256) { return data; }

}

Indian Institute of Technology Kharagpur

82 of 96

Access Control

  • Contracts often restrict who can perform certain actions, achieved using access control mechanisms such as the onlyOwner modifier, which allows only the contract’s owner to execute certain functions.

// Modifier to restrict access to the seller

modifier onlySeller(uint256 itemId) {

require(items[itemId].seller == msg.sender, "Not the item seller");

_;

}

// Modifier to restrict access to the owner

modifier onlyOwner() {

require(msg.sender == owner, "Not the contract owner");

_;

}

  • onlySeller: Restricts access to functions based on whether the caller is the seller of a specific item.
  • onlyOwner: Restricts access to functions that only the contract owner can call.

Indian Institute of Technology Kharagpur

83 of 96

Example

// 1. Solidity version declaration

pragma solidity ^0.8.0; //The ^0.8.0 means the contract is compatible with version 0.8.0 and above, but below 0.9.0

contract SimpleStorage { // 2. Declaring the contract

uint256 storedData; // 3. Declaring a State Variable to store data

event DataChanged(uint256 newValue); // 4. Declaring an event that is triggered when data is changed

function set(uint256 x) public { // 5. Function to set the stored data

storedData = x; // 6. Setting the state variable 'storedData' to the input value

emit DataChanged(x); // 7. Emitting an event when the data is changed

}

// 8. Function to retrieve the stored data

function get() public view returns (uint256) {

return storedData; // 9. Returning the stored value

}

}

Indian Institute of Technology Kharagpur

84 of 96

Compiling Solidity

  • solc compiler
    • Compile .sol files to bytecode
    • Command line tool

Remix editor

    • Browser based
    • Compile, emulate, deploy contracts
    • https://remix.ethereum.org/

Indian Institute of Technology Kharagpur

85 of 96

Create a project directory

  • You can also create a smart contract and use the Web3 JavaScript library to compile and then deploy the smart contract.
  • Create a project directory
  • Install the Install required packages packages in the project directory.
    • npm install web3
    • npm install solc
    • npm install dotenv
  • Create an .env file and add the following:

ETHEREUM_NETWORK = "sepolia"

INFURA_API_KEY = "<Your-API-Key>"

SIGNER_PRIVATE_KEY = "<Your-Private-Key>”

DEMO_CONTRACT = "<Contract_Address>” //Once the smart contract is deployed

Indian Institute of Technology Kharagpur

86 of 96

Create a smart contract

  • Create a smart contract Demo.sol

pragma solidity >=0.5.8;

contract Demo {

event Echo(string message);

function echo(string calldata message) external {

emit Echo(message);

}

}

Indian Institute of Technology Kharagpur

87 of 96

Create the compile script

  • Compile the script using solc compiler or Create a compile script compile.js
  • In the compile script copy the generated Application Binary Interface (ABI) and binary to a file called Demo.json

Indian Institute of Technology Kharagpur

88 of 96

compile.js

const fs = require("fs").promises;

const solc = require("solc");

async function main() {

const sourceCode = await fs.readFile("Demo.sol", "utf8");

const { abi, bytecode } = compile(sourceCode, "Demo");

const artifact = JSON.stringify({ abi, bytecode }, null, 2);

await fs.writeFile("Demo.json", artifact);}

function compile(sourceCode, contractName) {

const input = {

language: "Solidity",

sources: { main: { content: sourceCode } },

settings: { outputSelection: { "*": { "*": ["abi", "evm.bytecode"] } } }, };

const output = solc.compile(JSON.stringify(input));

const artifact = JSON.parse(output).contracts.main[contractName];

return { abi: artifact.abi, bytecode: artifact.evm.bytecode.object, };}

main()

Indian Institute of Technology Kharagpur

89 of 96

Run the compile script

  • Run the compile script

node compile.js

  • A file called Demo.json should be created in the directory.

Indian Institute of Technology Kharagpur

90 of 96

Create a Deployment Script

  • Create a Deployment Script deploy.js (Refer Next slide)
  • Run the deployment script to deploy the contract to the blockchain:

node deploy.js

  • The contract deploys to the blockchain and the script displays the contract address. Next we'll update the .env file to store the contract address.
  • Once Deployed successfully Add DEMO_CONTRACT to the .env file to store the contract address so that you can call the deployed contract.

Indian Institute of Technology Kharagpur

91 of 96

deploy.js

const { Web3 } = require("web3");

const fs = require("fs");

const { abi, bytecode } = JSON.parse(fs.readFileSync("Demo.json"));

async function main() {

const network = process.env.ETHEREUM_NETWORK;

const web3 = new Web3(

new Web3.providers.HttpProvider(`https://${network}.infura.io/v3/${process.env.INFURA_API_KEY}`,),);

const signer = web3.eth.accounts.privateKeyToAccount('0x' + process.env.SIGNER_PRIVATE_KEY,);

web3.eth.accounts.wallet.add(signer);

const contract = new web3.eth.Contract(abi);

contract.options.data = bytecode;

const deployTx = contract.deploy();

const deployedContract = await deployTx

.send({ from: signer.address, gas: await deployTx.estimateGas(),})

.once("transactionHash", (txhash) => { console.log(`Mining deployment transaction ...`);

console.log(`https://${network}.etherscan.io/tx/${txhash}`);});

console.log(`Contract deployed at ${deployedContract.options.address}`);

console.log(`Add DEMO_CONTRACT to the.env file to store the contract address: ${deployedContract.options.address}`,);}

require("dotenv").config();

main();

Indian Institute of Technology Kharagpur

92 of 96

Call a contract

  • Once the contract is deployed and you have the contract address
  • Create a script to execute/call the contract ‘call.js’
  • It uses Web3.js to execute a function in a smart contract. Calling the contract function is a type of transaction that requires paying gas.
  • Run the script

node call.js

Indian Institute of Technology Kharagpur

93 of 96

DAPPS in Ethereum

  • DAPP - decentralized application
  • Application that is built for decentralized networks like Ethereum

  • Combines two components:
    • 1. Smart Contracts
    • 2. User interface for executing transactions and contracts

Indian Institute of Technology Kharagpur

94 of 96

DAPPS in Ethereum

DApp

Smart Contracts

Frontend HTML

(index.html)

Frontend JS

(app.js)

Other Files

(css, images)

Ethereum Node

Compiler

Ethereum

Client

1. Send contract for compilation

2. Contract binary sent back to DApp

3. Deploy Contract

4. Contract address and ABI sent back to DApp

5. Send Transaction to contract

Communication network Ethereum Client and Ethereum Network for deploying contract and interacting with contract

DApp Creation workflow

Indian Institute of Technology Kharagpur

95 of 96

References (Extra Resources)

Indian Institute of Technology Kharagpur

96 of 96

96

Indian Institute of Technology Kharagpur