Top Ethereum Interview Questions and Answers

Last updated on Feb 18 2022
Sunder Rangnathan

Table of Contents

What is an Ethereum smart contract?

An Ethereum smart contract is a small program that runs on the Ethereum blockchain.

Can a smart contract interact with other smart contracts?

Yes.

What makes an Ethereum smart contract so special compared to other programs?

Once an Ethereum smart contract is deployed to the blockchain, it cannot:

  • be stopped
  • be hacked (as long as the code of the contract is correct)
  • be modified (the code is immutable, however the data is)

Can a Solidity smart contract call an API on the web?

No, it can only execute its own code and interact with other smart contracts on the blockchain

Is Solidity compiled or interpreted?

It’s compiled, meaning it means to be first compiled before we can run the code.

What is the file extension of Solidity files?

.sol

Can a single Solidity file have several smart contracts?

Yes.

Can a Solidity smart contract store a lot of data?

No, storage is very limited on a smart contract. Storing data cost gas, and gas consumption is capped in each Ethereum block. So indirectly, storage is limited.

Can a smart contract be written in another language than Solidity?

Yes. There are other smart contract languages like Vyper or LLL. But Solidity is the most popular.

Is Solidity a dynamically or statically typed language? (i.e need to define variable types)

It’s a statically typed language, i.e variable types need to be defined, unlike in dynamic languages like Javascript.

What is the typical layout of a Solidity smart contract?

//pragma statement (required)

pragma solidity ^0.5.9;


//contract declaration (required)

contract A {

//state variables

uint a;


//functions

function foo() {...}

}

What is the difference between state variables and local variables?

contract A {

//state variable

uint a;

//functions

function foo() {

uint b; //local variable

}

}

State variables are persisted on the blockchain after a smart contract finish to execute, whereas local variables live only during the execution of a function.

What is the problem with the following code (1/2)?

contract Storage {

uint data;

//Should update the `data` storage variable above

function set(uint _data) external {

address data = _data;

}

}

The set() function redefine the data variable inside its body. This will create a local variable that will shadow the state variable defined above. The assignment address data = _data will assign to this local variable instead of the state variable. To fix the code, remove the address keyword in front of data in the set() function: data = _data;

What is the problem with the following code (2/2)?

contract Storage {

uint data;

//Should update the `data` storage variable above

function set(uint data) external {

//data = data?

}

}

This is similar to the problem we have just before. The data argument of the set() function shadows the data state variable. Because of this, we can’t access the data state variable inside the set() function. To solve this problem, we need to rename the argument from data to _data.

What are the 2 variable visibilities for state variables in Solidity?

  • private
  • public

Who can read private and public variables?

  • private variables can be read only by functions inside the smart contract
  • public variables can be read by anyone

What is the default visibility of state variables?

Private.

Are private variables really private?

No. Private is only for the EVM (Ethereum Virtual Machine, the part of Ethereum that execute smart contracts). But the data of smart contracts is put on the Ethereum blockchain, and all data on this blockchain is public. Using a special tool to analyse blockchain data, anyone to read private variables of smart contracts.

How to deal with private data then?

You either don’t put private data on the blockchain, or you put hashes.

How to declare an array of integer in Solidity?

uint[] a;

How to declare a mapping of address to booleans in Solidity?

mapping(address => bool) a;

How to declare a mapping of address to mapping of address to booleans (nested mapping)?

mapping(address => mapping(address => bool)) a;

How to add data to an array declared as a state variable?

uint[] a;

function add(uint newEntry) external {

add.push(a);

}

How to add data to a mapping declared as a state variable?

mapping(address => bool) a;

function add(address addr) external {

a[addr] = true;

}

How to loop through an array?

uint[] a;

for(uint i = 0; i < arr.length; i++) {

//do something with arr[i]

//reading: uint a = arr[i]

//writing: arr[i] = a

}

What is the difference between a uint8 and a uint16?

uint8 can store number of up to 2^8 -1 (it has 8 bits), whereas uint16 can store
numbers of up to 2^16 – 1.

What are the 4 function visibilities in Solidity, by increasing permissiveness?

  • private
  • internal
  • external
  • public

How to conditionally throw an error, with an error message?

Use require statement:

require(a !== b, 'My error message')

What are the 2 artifacts produced by the Solidity compiler when compiling a smart contract?

  • The ABI (application binary interface)
  • The bytecode

What is the ABI of a smart contract?

The ABI defines the interface of a smart contract, i.e the set of functions that can be called from outside the smart contract. The ABI only defines the function signatures (function names, argument types and return types) but not their implementation. The ABI also defines the events of the contract. The ABI is used outside the smart contract by Ethereum client libraries like web3 to interact with the smart contract.

In the following contract, which function will be part of the ABI?

contract A {

function foo() external {…}

function bar() public {…}

function baz() internal {…}

}

foo() and bar() will be part of the ABI.

Does the EVM understands Solidity?

No. The EVM only understand bytecode, which must first be produced by Solidity, outside of the blockchain.

What is the EVM bytecode?

The EVM bytecode is a series of EVM elementary instructions called opcodes. These opcodes define very simple simple operations like adding 2 numbers (ADD), loading data from memory (mload), etc… There are more than 100 of these opcodes defined in the Ethereum yellow paper. Coding directly with opcodes would be very tedious, so we need higher languages like Solidity to help us reason at a higher level of abstraction.

What are the 2 APIs used to interact with a smart contract?

eth_sendTransaction (transaction) and eth_call (call). Transactions cost money (gas) and can modify the blockchain. Calls do not cost money, cannot modify the blockchain, but can return a value contrary to transactions.

Mention 3 data types that you use often, and explain why

  • uint, for ether / token transfers, and identifying data
  • address, for identifying humans and smart contracts
  • strings, for naming things

What are the 2 container types in Solidity?

  • mapping
  • arrays

What is gas?

Gas is an abstract unit used to pay miners when sending a transaction on the Ethereum network.

How is gas paid?

Gas is paid in ether using the formula: ether cost = gasPrice * gas, where gas represents the gas cost of the execution of a transaction. gasPrice is in wei / gas, generally express is Gwei. A transaction also specifies a gasLimit parameter, which specify a maximum number of gas that can be paid by a  transaction. Without this, a transaction could potentially drain an account of all its Ether.

Who pays for gas in a transaction?

The sender of the transaction.

What happen if there is not enough gas in a transaction?

The transaction is stopped, and all state changes are reverted.

What is the most famous online IDE for Solidity?

Remix

List 2 famous smart contract framework for Solidity

  • Truffle
  • OpenZeppelin

Which Javascript Ethereum client can we use to develop Solidity on a local blockchain?

Ganache

What do you need to deploy a smart contract to the Ethereum network?

  • bytecode of smart contract
  • an Ethereum address with enough Ether
  • A wallet to sign the transaction
  • A tool to create the transaction and coordinate the signing process with the wallet

List 4 famous Ethereum wallets

  • Metamask
  • MyEtherWallet
  • Ledger
  • Trezor

List 3 networks where you can deploy a Solidity smart contract

  • Mainnet
  • Ropsten
  • Kovan

How to manage dates in Solidity?

You need to use uint variables.

How to have the current timestamp in seconds?

You need to use the now keyword.

How to construct a timestamp of 1 day in the future?

A: now + 86400

What are the 2 ways to define custom data structure in Solidity?

  • Struct
  • Enum

When would you use a struct vs an enum?

Struct are for representing complex data structures with different fields. Enum are for creating variant for a single data. Ex: a color can be red, blue, yellow. You can combine both by defining an enum, and a struct that uses this enum in a field;

enum FavoriteColor }Blue, Red};

struct User {

address id;

string name;

Color favoriteColor;

}

What are the 2 ways to instantiate a struct?

struct User {

address id;

string name;

}


//Method 1 (argument order matters)

User("0xAio90....", "Mike");


//Method 2 (argument order does not matter)

User({name: "Mike", address: "0xAio90...."});

How to instantiate a struct that has an inner mapping?

struct User {

address id;

string name;

mapping(address => bool) friends;

}

//let assume the User struct is stored inside a mapping

mapping(address => User) users;

//Inside a function, you would instantiate your struct like this

users["0xAio90..."].id = "0xAio90...";

users["0xAio90..."].name = "Mike";

users["0xAio90..."].friends["0xIopop..."] = true;

users["0xAio90..."].friends["0xjk89I..."] = true;

When would you use an array vs a mapping?

I would use an array if I need to iterate through a collection of data. And I would use a mapping if I need to rapidly lookup a specific value

How to combine array and mapping to allow both iteration and rapid lookup of a struct?

//Let's consider this struct

struct User {

uint id;

string name;

}

//First, let's use an array to store all its ids

uint[] userIds;

//Then, let's use a mapping for rapid lookup

mapping(uint => User) users;

//If we need to rapidly lookup a user, we use the mapping

//And if we need to iterate through users, we iterate through the userIds array,

//and for each userIf we can

//lookup the correct user in the mapping

How to define an in-memory array of 3 integers?

uint[] memory arr = new uint[](3);

How to add a value to an in-memory array?

uint[] memory arr = new uint[](3);

uint[0] = 1;

uint[1] = 2;

uint[2] = 3;

uint[3] = 1; //out-of-bounds error

How to get the list of all keys in a mapping (like Object.keys() in Javascript)?

It’s not possible. Smart contracts don’t keep track of the list of entries in a mapping. You need to already know which key you want to access, or to store the list of keys yourself in a separate array.

How to create an in-memory mapping?

You can’t. Solidity has only storage mappings.

What happen if you try to access the key of a mapping that does not exist?

Contrary to arrays, there is no error, Solidity will give you a value, which is the default value of the type.

Ex:

mapping(uint => bool) myMap;

If you access myMap[10] but nothing exist there, Solidity will produce false.

What are the 3 mechanisms for code re-use in Solidity?

  • Group common codes in functions
  • Contract inheritance
  • Libraries

How to make a contract A inherit from a contract B in Solidity?

// First import the contract

import B from 'path/to/B.sol';

//Then make your contract inherit from it

contract A is B {

//Then call the constructor of the B contract

constructor() B() {}

}

If A inherit from B, and both define the same function foo, which one will be resolved?

//Case 1

contract B 

{

function foo() external {...}

}

contract A is B {

function foo() external {...}

}

If I call foo() on A, the function A.foo() will be resolved

//Case 2

contract B 

{

function foo(uint data) external {...}

}
contract A is B {

function foo() external {...}

}

If I call foo(1) on A, the function B.foo() will be resolved, because only B defines foo(uint)

What are the 4 memory locations of Solidity?

Storage, Memory, Stack and Calldata

What is the default visibility of state variables?

Private

What is the difference between address and address payable?

Only address payable can receive money

Is it necessary to make an address address payable to transfer ERC20 tokens?

No. The payable requirement is only required for native Ether. Ethereum has no knowledge of ERC20 tokens. For Ethereum, this is just a variable in a smart contract, like any other variables.

What are the main changes in Solidity 0.5.x vs 0.4.x?

  • constructors are declared with the constructor() keyword instead of function NameOfContract()
  • address has been split into 2 subtypes: address and address payable. Only the second one can receive ether.
  • The var keyword has been removed
  • Events need to be emitted with the emit keyword
  • memory location needs to be explicit
  • function visibility needs to be explicit

Give 3 ways to save gas

  • Put less data on-chain
  • Use events instead of storage
  • Optimal order for variable declaration. See this link.

How would optimally order uint128, bytes32 and another uint128 to save gas?

uint128

uint128

bytes32

The EVM stores variable in 32-bytes slot. However Solidity is smart enough to pack into a single slot several variables if they can fit together. For this optimization to work, packed variables have to be defined next to each other. In the above example, the 2 uint128 will be placed in the same 256 bit slots (128 + 128 = 256).

How to concatenate 2 strings a, b?

Use the abi.encodePacked() function:

string(abi.encodePacked(a, b));

How to get the length of a string in solidity?

bytes memory byteStr = bytes(a); //a is a string

bytesStr.length;

How to to create a smart contract from a smart contract?

contract A {

constructor(uint a) {...}

function foo() external {...}

}

contract B {

function createA(uint a) external {

A AInstance = new A(a); //pass constructor argument(s) if any

}

}

How to to call another smart contract from a smart contract?

contract A {

function foo() view external returns(uint) {...}

}

contract B {

function callFoo(address addrA) external {

uint result = A(addrA).foo();

}

}

How to get the address of a smart contract that was deployed from a smart contract?

Using the address() operator to cast the contract type into an address:

address childAddress = address(new Child())

What will be the value of msg.sender if a contract calls another one?

//This is the inner contract

contract A {

function bar() view external returns(address) {

//What will be the value of `msg.sender` here?

}

}

//This is the outer contract

contract B {

function foo() external {

A aInstance = new A();

aInstance.bar();

}

}

This is the address of the calling contract, i.e B in our example.

How to transfer ERC20 tokens?

contract ERC20Interface {

function totalSupply() public view returns (uint);

function balanceOf(address tokenOwner) public view returns (uint balance);

function allowance(address tokenOwner, address spender) public view returns (uint remaining);

function transfer(address to, uint tokens) public returns (bool success);

function approve(address spender, uint tokens) public returns (bool success);

function transferFrom(address from, address to, uint tokens) public returns (bool success);

event Transfer(address indexed from, address indexed to, uint tokens);

event Approval(address indexed tokenOwner, address indexed spender, uint tokens);

}

contract DecentralizedExchange {

function transferToken(address ERC20Address, address to, uint amount) {

ERC20Interface(ERC20Address).transfer(to, amount);

}

}

How to declare and emit an event?

contract A {

//declare event

Event TokenSent(uint amount, address to);

function sendToken(uint amount, address to) external {

...

//Emit event

emit TokenSent(amount, to); //careful, old Solidity 0.4 code didnt not require
the emit keyword, dont be confused

}

}

What is the indexed keyword in event definition?

If an event field is declared with the indexed keyword, it means that external entities can filter only events whose field match a specific value. For example, in the below example, it means it’s possible to filter events with a to field equal to a specific value.

Event TokenSent(uint amount, address indexed to);

How would you implement access control without modifier?

contract A {

address admin;

constructor() {

admin = msg.sender;

}

function protectedFunction() external {

require(msg.sender == admin, 'only admin');

...

}

}

How would you implement access control WITH modifier?

contract A {

address admin;

constructor() {

admin = msg.sender;

}

function protectedFunction() external onlyAdmin() {

...

}

modifier onlyAdmin() {

require(msg.sender == admin, 'only admin');

_;

}

}

How many event fields can be marked indexed?

3 maximum.

Is it possible for a smart contract to read the events emitted before?

No. Only external entities can queries events.

Is it possible to delete or modify a past event?

No. Events are immutable.

In Solidity, how to do like a Javascript console.log for debugging?

There is no equivalent in Solidity, but you can use events, even if its not designed for this.

How to cancel a transaction?

Once a transaction has been sent, nobody can prevent it from being mined by a miner. But you can still send another transaction preventing the first one from working IF its mined before the first one. This second transaction will have the following properties:

  • it will have the same nonce (i.e an incrementing integer that is sent in each transaction, specific to each Ethereum address)
  • it will have a higher gasPrice than the first transaction
  • it will send a tiny amount of Ether to another address

Let’s review why we need these. The same nonce means that the first transaction to be mined will prevent the other one from being mined: miners only mine transactions whose nonce is higher than the previous nonce for the address that has signed the transaction.

The higher gasPrice means a higher reward for miner, so if a miner has the choice to mine the second or the first transaction he will choose the second one.

And finally, sending a tiny amount of Ether is just because a transaction needs to do something on the blockchain, so we just do something that is useless but doesn’t cost us much. Actually, you could even call a read-only function in any smart contract, in a transaction, and you wouldn’t even need to send this tiny amount of Ether. You would still need to cover the gas fee in every case.

What is the ABIEncoderV2 pragma statement?

This is a pragma statement is used to enable experimental features not yet enabled in standard Solidity. For example, it enables to return a struct from a function called externally, which is not possible in standard Solidity yet (0.5.x).

Is it safe to use the ABIEncoderV2 pragma statement in production?

No. It should only be used in development, not in production.

Is it possible to send a transaction without requiring users to pay gas?

Yes. You would ask users to first sign a message on the frontend. Then the message and signature would be sent to a centralized backend (your app, off-chain) that would create a transaction and embed the payload (message + signature) into it. That means that gas fees will be covered by the wallet of the app, instead of the user wallet. On-chain, a smart contract will verify the validity of the signature and perform on operation on behalf of the user.

Which Solidity function would you use to verify a signature?

ecrecover().

Give an example of how to use a library in a smart contract

library Lib {

function add(uint a, uint b) pure internal returns(uint) {

return a + b;

}

}

contract A {

using Lib for uint;

function add(uint a, uint b) pure external returns(uint) {

return a.add(b);

}

}

When is a library embedded vs deployed?

//Embedded (function is internal)

library Lib {

function add(uint a, uint b) pure internal returns(uint) {

return a + b;

}

}

//Deployed (function is public)

library Lib {

function add(uint a, uint b) pure public returns(uint) {

return a + b;

}

}

What is a re-entrancy attack?

A re-entrancy attack happen when a contract A calls a contract B which call back the calling function on contract A to perform some malicious effect. Example with a DAO-like attack:

contract A {

//...

function pay(address payable to, uint amount) external {

if(amount <= balances[msg.sender]) {

B(to).badFunction().send(amount);

balances[msg.sender] -= amount;

}

}

contract B {

address

function badFunction(address payable to) external {

ContractA(msg.sender).pay();

}

}

What is a library in Solidity?

A library is a piece of code that be re-used by other smart contracts. There are 2 types of libraries:

  • deployed
  • embedded

Deployed libraries have their own address, and they can be used by several other smart contracts. Embedded libraries don’t have their own address and are deployed as part of the code of the smart contract that use them.

How to prevent against a re-entrancy attack?

  • Solution 1: Decrease balances / do other state variable update BEFORE calling the other contract.
  • Solution 2: Put in place re-entrancy guard with a variable that knows when a call is the second in the stack
  • Solution 3: Limit the gas available to the called contract. If using transfer(), this is done automatically:

How to produce a hash of multiple values in Solidity?

keccak256(abi.encodePacked(a, b, c))

How to generate a random integer in Solidity?

We can leverage the block.timestamp and block.difficulty as a source of randomness, and use the keccak256() hashing function:

uint(keccak256(abi.encodePacked(block.timestamp, block.difficulty)))

Be aware that miners can manipulate block.difficulty and block.timestamp, so this is not 100% secure.

What are the 2 kinds of assembly in Solidity?

Functional and instructional. Functional uses functions, whereas instructional is a raw series of opcodes. Most people use the functional style.

How to declare assembly code?

assembly {}

Create a function to determine if another address is a contract or a regular address

function isHuman(address addr) external {

uint256 codeLength;

assembly {codeLength := extcodesize(addr)}

return codeLength == 0 ? true : false;

}

}

What is a state machine? Why Ethereum is called a state machine?

A state machine refers to something that makes a transaction from one state to another based on the input.

When nodes make transactions, the current state transitions into some final state. At any point in time, this final state represents the current state of Ethereum.

What is a Merkle tree? What is the importance of the Merkle tree in blockchain? How Ethereum implements a Merkle tree?

A Merkle tree, in the most general sense, is a way of hashing a large number of “chunks” of data together which relies on splitting the chunks into many buckets, where each bucket contains only a few chunks. Then taking the hash of each bucket and repeating the same process, continuing to do so until the total number of hashes remaining becomes only one: the root hash (Merkle Root).

A binary Merkle tree looks like below:

etherum

Binary Merkle tree

The Merkle Root is important because it summarizes every transaction in the block and is located on the block header. If there is any malicious change in the transactions stored in the block, the Merkle root changes. This makes it easier to verify whether or not a transaction has occurred within a block.

The Ethereum blockchain uses a modified version of the basic Merkle tree which is actually called the Merkle Patricia tree, Patricia tree, or Patricia Trie.

Each Ethereum block header has three Merkle trees.

  1. Transactions
  2. State
  3. Receipts (essentially, pieces of data showing the effect of each transaction)

The first one is the root of transactions on the block, the second is the root showing the state of the Ethereum network, and the third is the receipt root.

Ethereum’s global state consists of a mapping between account addresses and the account states. This mapping is stored in the Merkle Patricia tree. In this data structure, data is stored in the form of a key-value pair. The state in Ethereum is different, and as explained by Vitalik Buterin, it is a key-value map. The keys are the addresses of an account, and the values are nonces, account balances, and code and storage.

How does the gas parameter save the system from attackers?

Let us consider a situation where an attacker wants to halt the Ethereum network by running a smart contract which consists of an infinite loop. Without the gas parameter, every node will execute the infinite loop which will eventually crash the network.

With the gas parameter included, if an attacker runs such a smart contract, he will also have to attach the equivalent amount of gas i.e. Ether. So, it will only lead to the attacker’s loss as he will eventually run out of gas and the execution will stop at that instant. This is how the gas parameter saves the Ethereum network from attackers.

Gas is the Ether, the cryptocurrency of the network.

Where does the contract code is executed?

A smart contract is executed when a mining node includes the transaction in a block it generates. The associated gas acts as a fuel to run the smart contract. If the gas price is sufficient enough to run the contract, state transitions as directed by smart contract and the related transaction is included in the block and is then broadcasted in the network. If the gas is not sufficient, it throws an error. The smart contract codes are then run by every other node when they include the block in their local Ethereum Network.

What is DAO and how it functions?

A decentralized autonomous organization is an organization represented by rules encoded in a transparent smart contract and it is controlled by shareholders or board of directors.

For certain actions to enforce, be it transfer of fund or modification in the base code, there should be the consent of at least 2/3rd of the members. Methods for allocating a DAO’s funds could range from bounties, salaries, internal currency to reward work.

What GHOST protocol? What problems does it solve in Ethereum?

The GHOST (Greedy Heaviest-Observed Sub-Tree) protocol picks the path that has had the most computation done upon it.

GHOST solves the issue of network security loss by including in the calculation of which chain is the “longest by not only including the parent and further ancestors of a block but also the stale blocks (called uncle blocks).

Name 4 components of the account state?

nonce: For an externally owned account, this number represents the number of transactions sent from the account’s address. For a contract account, the nonce is the number of contracts created by the account.
balance: The number of Wei owned by this address.
storageRoot:  A hash of the root node of a Merkle Patricia tree. This tree encodes the hash of the storage contents of this account and is empty by default.
codeHash:  The hash of the EVM code of this account. For contract accounts, this is the code that gets hashed and stored as the codeHash. For externally owned accounts, the codeHash field is the hash of the empty string.

How the signing and verification of a transaction take place in Ethereum?

The private key along with the transaction data is used to sign a transaction. ECDSA signatures in a transaction consist of three parameters r, s, and v. Ethereum clients provide a global method that returns an address given these three parameters. If the returned address is the same as the signer’s address, then the signature is valid.

What is the importance of difficulty?

The “difficulty” of a block is used to enforce consistency in the time it takes to validate blocks. If a certain block is validated more quickly than the previous block, the Ethereum protocol increases that block’s difficulty. If a block validation takes more time than the previous block, the Ethereum protocol decreases that block’s difficulty.

What is intrinsic gas value?

Intrinsic gas value gives an estimated cost of the gas fees. So, the transaction’s gas limit must be equal to or greater than the intrinsic gas. Intrinsic gas consists of –

  1. a predefined cost of 21,000 gas for executing the transaction
  2. a gas fee for data sent with the transaction (4 gas for every byte of data or code that equals zero, and 68 gas for every non-zero byte of data or code)
  3. if the transaction is contract-creating, an additional 32,000 gas

What is the importance of account nonce in Ethereum?

An account nonce is a transaction counter in each account. It is used to prevents replay attacks i.e. taking a transaction on one blockchain, and maliciously or fraudulently repeating it.

What is the state channel?

State channels are used for scaling the Ethereum blockchain and reducing costs for micropayments by moving on-chain components to off-chain. This can avoid delays and fees associated with micropayments. This is similar to the Lightning network in Bitcoin. Participants in a state channel pass cryptographically signed messages without publishing them to the main chain until they both decide to close the channel.

What is Whisper Protocol?

Whisper is a peer-to-peer communication protocol for Dapps built upon the Ethereum network. It provides a privacy-focused, encrypted messaging system for Dapps. Properties of Whisper protocol – 

What is an Ethereum client?

Ethereum client is an implementation of the Ethereum protocol. A running client called a node, which is able to parse and verify the blockchain, its smart contracts, and everything related. It also provides an interface to create transactions and mine blocks which is the key for any blockchain interaction.

Do all functions in a smart contract costs money?

No. The functions that modify the state of EVM costs money (or gas). But functions that read the state of EVM doesn’t cost any money (or gas). Basically, all write operations cost money while all read operations don’t.

What is a state machine? Why Ethereum is called a state machine?

A state machine refers to something that makes a transaction from one state to another based on the input.

When nodes make transactions, the current state transitions into some final state. At any point in time, this final state represents the current state of Ethereum.

What is a Merkle tree? What is the importance of the Merkle tree in blockchain? How Ethereum implements a Merkle tree?

A Merkle tree, in the most general sense, is a way of hashing a large number of “chunks” of data together which relies on splitting the chunks into many buckets, where each bucket contains only a few chunks. Then taking the hash of each bucket and repeating the same process, continuing to do so until the total number of hashes remaining becomes only one: the root hash (Merkle Root).

A binary Merkle tree looks like below:

Binary Merkle tree

The Merkle Root is important because it summarizes every transaction in the block and is located on the block header. If there is any malicious change in the transactions stored in the block, the Merkle root changes. This makes it easier to verify whether or not a transaction has occurred within a block.

The Ethereum blockchain uses a modified version of the basic Merkle tree which is actually called the Merkle Patricia tree, Patricia tree, or Patricia Trie.

Each Ethereum block header has three Merkle trees.

Transactions

State

Receipts (essentially, pieces of data showing the effect of each transaction)

The first one is the root of transactions on the block, the second is the root showing the state of the Ethereum network, and the third is the receipt root.

Ethereum’s global state consists of a mapping between account addresses and the account states. This mapping is stored in the Merkle Patricia tree. In this data structure, data is stored in the form of a key-value pair.  The state in Ethereum is different, and as explained by Vitalik Buterin, it is a key-value map. The keys are the addresses of an account, and the values are nonces, account balances, and code and storage.

How does the gas parameter save the system from attackers?

Let us consider a situation where an attacker wants to halt the Ethereum network by running a smart contract which consists of an infinite loop. Without the gas parameter, every node will execute the infinite loop which will eventually crash the network.

With the gas parameter included, if an attacker runs such a smart contract, he will also have to attach the equivalent amount of gas i.e Ether. So, it will only lead to the attacker’s loss as he will eventually run out of gas and the execution will stop at that instant. This is how the gas parameter saves the Ethereum network from attackers.

Gas is the Ether, the cryptocurrency of the network.

Where does the contract code is executed?

A smart contract is executed when a mining node includes the transaction in a block it generates. The associated gas acts as a fuel to run the smart contract. If the gas price is sufficient enough to run the contract, state transitions as directed by smart contract and the related transaction is included in the block and is then broadcasted in the network. If the gas is not sufficient, it throws an error. The smart contract codes are then run by every other node when they include the block in their local Ethereum Network.

What is DAO and how it functions?

A decentralized autonomous organization is an organization represented by rules encoded in a transparent smart contract and it is controlled by shareholders or board of directors.

For certain actions to enforce, be it transfer of fund or modification in the base code, there should be the consent of at least 2/3rd of the members. Methods for allocating a DAO’s funds could range from bounties, salaries, internal currency to reward work.

What GHOST protocol? What problems does it solve in Ethereum?

The GHOST (Greedy Heaviest-Observed Sub-Tree) protocol picks the path that has had the most computation done upon it.

GHOST solves the issue of network security loss by including in the calculation of which chain is the “longest by not only including the parent and further ancestors of a block but also the stale blocks (called uncle blocks).

Name 4 components of the account state?

nonce: For an externally owned account, this number represents the number of transactions sent from the account’s address. For a contract account, the nonce is the number of contracts created by the account.

balance: The number of Wei owned by this address.

storageRoot: A hash of the root node of a Merkle Patricia tree. This tree encodes the hash of the storage contents of this account and is empty by default.

codeHash: The hash of the EVM code of this account. For contract accounts, this is the code that gets hashed and stored as the codeHash. For externally owned accounts, the codeHash field is the hash of the empty string.

How the signing and verification of a transaction take place in Ethereum?

The private key along with the transaction data is used to sign a transaction. ECDSA signatures in a transaction consist of three parameters r, s, and v. Ethereum clients provide a global method that returns an address given these three parameters. If the returned address is the same as the signer’s address, then the signature is valid.

What is the importance of difficulty?

The “difficulty” of a block is used to enforce consistency in the time it takes to validate blocks. If a certain block is validated more quickly than the previous block, the Ethereum protocol increases that block’s difficulty. If a block validation takes more time than the previous block, the Ethereum protocol decreases that block’s difficulty.

What is intrinsic gas value?

Intrinsic gas value gives an estimated cost of the gas fees. So, the transaction’s gas limit must be equal to or greater than the intrinsic gas. Intrinsic gas consists of –

a predefined cost of 21,000 gas for executing the transaction

a gas fee for data sent with the transaction (4 gas for every byte of data or code that equals zero, and 68 gas for every non-zero byte of data or code)

if the transaction is contract-creating, an additional 32,000 gas

What is the importance of account nonce in Ethereum?

An account nonce is a transaction counter in each account. It is used to prevents replay attacks i.e. taking a transaction on one blockchain, and maliciously or fraudulently repeating it.

What is the state channel?

State channels are used for scaling the Ethereum blockchain and reducing costs for micropayments by moving on-chain components to off-chain. This can avoid delays and fees associated with micropayments. This is similar to the Lightning network in Bitcoin. Participants in a state channel pass cryptographically signed messages without publishing them to the main chain until they both decide to close the channel.

What is Whisper Protocol?

Whisper is a peer-to-peer communication protocol for Dapps built upon the Ethereum network. It provides a privacy-focused, encrypted messaging system for Dapps. Properties of Whisper protocol–

Low-level

Low-bandwidth

Uncertain-latency

What is Dapp?

Dapp stands for Decentralized Applications. They are like normal apps but the key difference is, that Dapps’ components run one or more peer-to-peer networks, such as a blockchain. It was popularized by Ethereum.

What is ABI?

It stands for Application Binary Interface. We get ABI(Usually in JSON format) after compiling a smart contract. It is used to invoke smart contract functions from the client-side.

What is Solidity?

Solidity is the most popular language to write a smart contract on Ethereum. It is statically typed language i.e. variable types are explicitly declared and thus are determined at compile time.

Why do we specify the compiler version in a smart contract?

It prevents incompatibility errors that can be introduced when compiling with another version.

What are the different types of functions in Solidity?

Constructor – It is an optional function and is used to initialize state variables of a contract.

Payable functions – Payable functions provide a mechanism to collect/receive funds in ethers to your contract.

Fallback functions – Fallback functions are unnamed functions. They are executed when a function identifier does not match any of the available functions in a smart contract

View functions -View functions ensure that they will not modify the state.

Pure functions – Pure functions ensure that they are not read or modify the state.

What is the purpose of modifier in Solidity?

It allows you to control the behavior of your smart contract functions. It includes a variety of use cases, such as restricting who can run a given function, unlocking functions at a certain time frame etc.

What are the access specifiers in Solidity?

There are 4 types of access specifiers in Solidity, they help to define the scope/visibility of functions and state variables.

external – External functions are part of the contract interface, which means they can be called from other contracts and via transactions. An external function f cannot be called internally (i.e. f() does not work, but this.f() works). External functions are sometimes more efficient when they receive large arrays of data.

public– Public functions are part of the contract interface and can be either called internally or via messages. For public state variables, an automatic getter function (see below) is generated.

internal – Those functions and state variables can only be accessed internally (i.e. from within the current contract or contracts deriving from it), without using this.

private – Private functions and state variables are only visible for the contract they are defined in and not in derived contracts.

Name different types of EVM memory?

stack

memory

storage

What is Account in Ethereum?

An Ethereum account is a 20-byte address which can store the state of ownership of ether tokens. There are two types of account in Ethereum-

Externally Owned Account (EOA)- These accounts are controlled by a private key. It has no associated code and is mainly used to perform transactions.

Contract Account- This account has a code associated with it. It is mainly used to invoke smart contract functions.

What is a nonce?

A nonce is an abbreviation for “number only used once”. Miners compete in a Proof-of-Work based blockchain network to find the targeted hash. In addition, every Ethereum account has an incremental nonce to prevent replay attack.

What is the gas limit?

The Gas Limit is the maximum amount of Gas that a user is willing to pay when sending a transaction or performing a smart contract function, in the Ethereum blockchain. In Ethereum there is no block size limit rather blocks has Gas limit. Currently accepting blocks with an average block gas limit of around 10,000,000 gas.

Explain different types of blockchain syncs are there in Ethereum?

Full Sync: a node replicates the blockchain state starting from the genesis block. It downloads every transaction ever made on the network and computes the state.

Fast Sync: A node downloads the blocks, and only verifies the associated proof-of-works.

Light Sync: It only stores the header chain and requests everything else on-demand from the network.

Archive Sync: It is similar to full sync but stores all intermediate states in the disk.

Why Ethereum? Understanding its demand

Ethereum has been the most popular decentralized ledger technology out there. It is partially because of the Ethereum cryptocurrency, and the ability to create decentralized apps through the Ethereum blockchain solution.

Ethereum is a public blockchain solution. There is also an enterprise implementation of Ethereum, which enables companies to implement a permissioned Ethereum network.

The ecosystem of Ethereum makes it a great choice for developers. It has one of the most deployed decentralized apps on blockchain networks. Its ease of use and the ability to use Solidity to program smart contracts and dApps opens up a lot of opportunities for the organizations out there.

etherum2

What is the Ethereum network? Explain in short

A: Ethereum is a second-generation distributed ledger technology that builds upon the bitcoin network. It was first launched in 2015, and it has continued to grow from there. It is an open-source public distributed ledger technology. Technically, it is also an operating system with key features such as smart contracts, transaction-based state transitions, and virtual machines.

Who is the founder of Ethereum?

A: There are two original authors of Ethereum, including Vitalik Buterin and Gavin Wood.

What is the real-world use-cases of Ethereum?

A: There are many use-cases of Ethereum. Some of them are as below.

  • Decentralized Finance: One of the biggest use-cases is decentralized finance (De-Fi). It improves how the financial sector works and improves loans using smart contracts.
  • Digital Identity: Digital Identity is another use-case where a person’s identity is digitized, providing better usability for individuals as they do not have to carry documents and can be verified instantly through a connected network.
  • Health applications: Healthcare systems can utilize Ethereum based solutions to implement a decentralized network and improve things such as drug tracking, better patient management, and so on.
  • Tokenization: Ethereum is very useful in creating the tokenization of real-world assets. This makes it easy to trade items on the blockchain.
  • Payments: It also improves payments, especially cross-boundary transactions.

What is EVM?

A: EVM stands for Ethereum Virtual Machine. It is a decentralized virtual machine capable of handling scripts using the public nodes network. It is also Turing complete and utilizes Gas as an internal pricing mechanism.

Tell us about the Enterprise Ethereum Alliance (EEA)?

A: The Enterprise Ethereum Alliance (EEA) was created in March 2017 by Fortune 500 companies, research groups, and blockchain startups. It has more than 100+ non-profit organizations as members. The focus is to create a member-driven standard that can develop an open blockchain specification for interoperability and harmonization. It also facilitates a permissioned implementation of the Ethereum network fine-tuned according to the enterprise requirements.

What is the value token for Ethereum?

A: The token value of Ethereum is Ether (ETH).

What is the Ethereum node?

A: Ethereum nodes talk with each other using the Ethereum protocol. They interact with the outside world using the JSON-RPC interface.

Which consensus algorithm does Ethereum use?

A: Right now, Ethereum utilizes Proof-of-Work as its consensus algorithm. Ethereum network is in the process of changing its consensus algorithm to a more environmentally friendly consensus method Proof-of-Stake (PoS).

What is the difference between Bitcoin and Ethereum blockchain?

A: The main difference between Bitcoin and Ethereum blockchain is how they work and their features. Bitcoin is a first-generation blockchain technology that offers the foundation of the decentralized ledger. Ethereum, on the other hand, builds on what Bitcoin has to offer by providing a more scalable and programmable blockchain solution. Ethereum supports smart contracts and the ability to design and implement distributed apps(dApps).

What is Ether?

A: Ether is best defined as a crypto-fuel(token) that powers the Ethereum network. It powers the smart contracts and provides the nodes an incentive to validate the Ethereum blockchain blocks. Once a block is validated, 5 Ether is released to nodes that took participation in the process.

What is Wei? How does it differ from Ether?

A: Wei is the smallest unit in the Ether cryptocurrency that is used in the Ethereum network.

1 Ether = 1018 Wei. It is important to break down Ether as it can help nodes to maintain the amount of Ether required for certain actions. It also helps the cryptocurrency market as people can buy or sell a fraction of Ether.

What is Blockchain?

Blockchain is a distributed ledger technology where peers are capable of communicating and transacting without the need for a centralized authority. The concept of blockchain was invented with the release of Bitcoin paper in 2009. To manage the Network independently without the need for a centralized authority, consensus algorithms are used. Bitcoin used the Proof-of-Work (PoW) consensus algorithm. Right now, blockchain is evolving at a rapid pace with new ways to manage distributed ledger technologies.

What is the consensus algorithm?

A: Consensus algorithm is best defined as the way to validate transactions in a distributed ledger technology. It is a way to reach agreement or consensus among peers about the state of the DLT. This method is very important as without it, the core philosophy of the distributed ledgers would not stand. There are many popular consensus algorithms out there, including Proof-of-Work (PoW), Practical Byzantine Fault Tolerance (PBFT), Proof-of-Stake (PoS), Proof-of-Burn (PoB), and so on.

Explain how Proof-of-Work (PoW) works?

A: Proof-of-Work is a consensus algorithm that requires work from miners to validate the transactions. The work is generated by solving complex computational problems using hardware. It is not environmentally friendly as it requires a lot of electricity to run the hardware, which in turn solves those complex computational problems.

What are smart contracts?

A: Smart contracts are like legal documents in code. It is a computer protocol that can be used as a digital verification process or enforce negotiations between parties. Smart contracts are also transparent and automated. In short, it offers a conflict-free approach to deals, agreements, and disputes.

What are the main steps of Smart Contract development from a business perspective?

A: Many key steps are required to be taken when doing smart contract development. The steps are as below.

  • Reconfirm that your business really needs smart contract development.
  • Understand the limitations of smart contracts
  • Plan how to carry out the development
  • Hire a smart contract developer
  • Do proper testing before deploying the smart contract

What is dApps?

dApps stands for decentralized applications. These applications are created to take advantage of blockchain technologies. dApps offer many benefits including being decentralized and open source. It also follows protocols and incentivizes nodes that take part in the functioning of the dApp.

Ethereum is a popular blockchain network for dApps as it offers the right ecosystem for developers to create real-world dApps. Other blockchain networks that support dApp creation include TRON and EOS

Where are the transactions recorded?

A: The transactions are recorded in a public ledger in the case of Ethereum. However, if a permissioned network is used, then the records are stored in a private ledger with certain information available to the public.

What is the programming language used to write smart contracts and dApps?

A: Solidity is the main programming language that is used to create both dApps and smart contracts. However, smart contracts in Ethereum can also be written using any of the smart-contract languages (SCL). Some of the SCL examples include Vyper, Bamboo, Serpent, Ethereum bytecode, Pyramid, L4, and others.

What is Truffle?

A: Truffle is a popular testing and development environment for Ethereum. It also offers an asset pipeline, which makes it handle Ethereum based projects. With it, a developer can create smart contracts, dApps, do automated testing, configure and build pipelines and so on. It is a perfect framework for developers using Ethereum.

What is block time and average block size in Ethereum?

A: The block time is 2 KB, whereas the average block size is 14 seconds.

Tell us about the type of Ethereum networks that exist.

A: There are three types:

  • Private Network
  • Test Network, e.g., Rinkeby and Ropsten
  • Live Network, i.e., the main Network

Can a transaction be kept hidden?

A: In the case of the public Ethereum network, no transactions can be kept hidden. All transactions are public.

What are the benefits of having a private network?

A: Private networks are very useful when it comes to data privacy. It is also useful for permissions testing and control.

What are the private keys?

A: Private keys are used to secure an address. It should be kept secure by the owner as anyone who has it gives the ownership to the one who possesses it. In contrast, the public key is available online.

How to mine Ethers?

A: To mine ethers, one needs to have a wallet and tools such as Geth CLI. With it, you need to participate in the Network and help add transactions to the blocks.

Is the user’s private key used to sign transactions?

A: Yes

How do you recover an Ethereum account with no private key?

A: It can only be recovered in only one way: 12 work mnemonic which was set during the account creation process.

What is Geth?

A: Geth is a command-line interface used when running a full Ethereum node.

How can you connect to a node?

A: You can connect to a node using three ways: WS-RPC, JSON-RPC, and IPC-RPC.

What is Geth’s fast sync?

A: Geth’s fast sync works with syncing the download transaction

What is the functionality of testnet?

A: Testnet is used to connect to the Ropsten Network.

Tell us about Smart Contract use cases?

A: There are many use-cases for smart contracts. For instance, it can be used in real estate where a seller can set up a smart contract to sell properly. The property can be transferred to the buyer once he transfers the property amount.

What is Meta Mask?

A: MetaMask is a popular browser-based Ethereum wallet that can be used to interact with the dApps on the Ethereum network.

Do you need to use real Ether to test dApps and smart contracts?

A: No, it is not required. In test networks, you can use free Ether.

How does spending work in smart contracts?

A: If there is a request that does not modify the smart contract and is used to return values, then there is no cost associated with the task. However, any action that can be used to modify the smart contract test will cost money, i.e., Gas.

What is Remix?

A: Remix is a useful online tool that can be used to deploy, test and develop smart contracts. By using it, developers can quickly test their smart contracts.

How Bitcoin and Ethereum differ when it comes to checking the latest state.

A: Ethereum checks the latest state for the account balance. Bitcoin, on the other hand, checks unspent transaction outputs (UTXO).

What happens when the Gas runs out without the transaction being complete?

A: In this case, all the state changes are reversed. The used Gas is given to the miner.

 

So, this brings us to the end of the Ethereum Interview Questions blog. This Tecklearn ‘Top Ethereum Interview Questions and Answers’ helps you with commonly asked questions if you are looking out for a job in Ethereum or BlockChain Domain. If you wish to learn Ethereum and build a career in BlockChain domain, then check out our interactive, Blockchain and Ethereum Developer Training, that comes with 24*7 support to guide you throughout your learning period.

https://www.tecklearn.com/course/blockchain-and-ethereum-certification-training/

Blockchain and Ethereum Developer Training

About the Course

Tecklearn’s Blockchain and Ethereum Certification Training course in the blockchain technology that covers essential concepts like Blockchain programming, Ethereum, Solidity, Digital ledger types, Smart Contracts, Multichain, Bitcoin mining, Cryptocurrency, etc. The course provides an overview of the structure and mechanism of Blockchain.  You will learn about the Ethereum ecosystem, how smart contracts are developed using Solidity and how to deploy a business network using Hyperledger Compose.

Why Should you take BlockChain and Ethereum Certification Training?

  • The average salary of a Blockchain Ethereum Developer is $158,860 per annum – Paysa.com.
  • Blockchain tech has gone far beyond its beginnings in banking and cryptocurrency: In 2019, businesses are expected to spend $2.9B on the technology.
  • IBM reports that Blockchain markets are headed to $60 Billion worldwide by 2024.

What you will Learn in this Course?

Introduction and origin of Blockchain

  • How does our current financial system work?
  • What can be the possible solution
  • What is a distributed system
  • What is Blockchain
  • How does a Blockchain work
  • Components of Blockchain
  • Business network
  • Consensus, Provenances, immutability and finality

Cryptocurrency and Blockchain

  • Distributed system
  • Distributed Ledger technology
  • Global Payments
  • Why BlockChain
  • BlockChain and use case needs
  • Requirements of blockchain for business
  • BlockChain benefits
  • Types of BlockChain
  • Hands on

Bitcoin Platform

  • What is Bitcoin?
  • Why use Bitcoins?
  • Bitcoin Ecosystem
  • Structure of a Bitcoin Transaction
  • Merkel Trees
  • Scripting language in Bitcoin
  • Applications of Bitcoin script
  • Nodes in a Bitcoin Network
  • Bitcoin Economics
  • What is Bitcoin Mining?
  • Types of Mining
  • Mining and Consensus
  • Hands On

Introduction to Ethereum

  • What is Ethereum?
  • Ethereum Layers
  • Introducing Smart Contracts
  • Cryptocurrency in Ethereum
  • Mining in Ethereum
  • Consensus Mechanism
  • Platform Functions in Ethereum
  • Technologies that support Ethereum
  • Ethereum Programming Language
  • Components for the development of Ethereum DApps
  • Editors and tools
  • Frontend Development
  • Ethereum Test Networks
  • ERC Tokens
  • Hands On

Solidity

  • Introducing Solidity
  • Sample Code, Layout of Source File
  • Structure of a Contract
  • State Variables, Functions Types, Reference Types
  • Special Variables and Functions, Expressions and Control Structures
  • Function Calls, Error Handling
  • Visibility for Functions and State Variables
  • Inheritance, Constructors
  • Importing Smart Contracts
  • Gas Limit and Loops
  • Sending and Receiving Ether
  • Recommendations
  • Contract ABI
  • Setting up the development environment and Deploying DApp
  • Hands On

Hyperledger

  • Introduction to Hyperledger
  • Hyperledger architecture
  • Hyperledger Fabric V1 Architecture
  • Consensus
  • Hyperledger API
  • Hyperledger Application Model
  • Hyperledger project and tools
  • Network Topology
  • Exploring Hyperledger frameworks
  • Business Network Deployment on Hyperledger Composer Playground
  • Sample Transaction
  • Service invoices
  • Hands On

Hyperledger Composer

  • Development Environment using Composer
  • Developing business networks
  • Testing business networks
  • Introduction to Hyperledger Fabric
  • Hyperledger Fabric Model
  • Ways to create Hyperledger Fabric Blockchain Network
  • Hands On

Create and Deploy Your Private Blockchain On Multichain

  • What Is MultiChain
  • MultiChain Privacy and Permissions
  • Mining in MultiChain
  • Multiple configurable Blockchains using MultiChain
  • Setting up a Private Blockchain
  • Hands On

Blockchain Use Cases

  • Potential use cases in Blockchain
  • BlockChain project

Got a question for us? Please mention it in the comments section and we will get back to you.

 

0 responses on "Top Ethereum Interview Questions and Answers"

Leave a Message

Your email address will not be published. Required fields are marked *