Go2X
Go2X

India's leading training and placement platform offering hands-on learning, powered by 200+ IITian and industry experts, connecting students to 1,000+ hiring and referral partners.

Let's Go2X

Stay updated with Go2X

Get course updates, interview tips, and career insights delivered to your inbox.

Contact Us

Address

1st Floor, Plot No 332, Phase IV, Udyog Vihar,
Sector 19, Gurugram, Haryana 122015

Email

support@go2x.live

Phone

+91 94107 10085

© 2025 Go2X Private Limited. All rights reserved.

Made with 🧡 and a lot of late nights.

About UsPrivacy PolicyTerms of ServiceRefund Policy

On This Page:

Blockchain

Blockchain Interview Questions

Prepare for your Blockchain interview with the most asked questions for freshers and experienced developers. Covers smart contracts, Solidity, DeFi, consensus mechanisms, security, and real-world scenarios.

May 15, 2026
35 mins read

I. Beginner Level

1. What is Blockchain and how does it work?

A Blockchain is a distributed, decentralized digital ledger that records transactions across a network of computers. Each record is called a block, and all blocks are linked together in a chain using cryptographic hashes, forming an immutable and tamper-proof history of data. No single entity controls it; instead, all participants (nodes) maintain a copy of the ledger and validate new entries through a consensus mechanism.
Key characteristics of Blockchain:

  • Decentralized: No central authority controls the data.

  • Immutable: Once data is written, it cannot be altered.

  • Transparent: All transactions are visible to network participants.

  • Secure: Cryptographic hashing ensures data integrity.

Example (Conceptual Block Structure)

javascript
1const block = {
2  index: 1,
3  timestamp: "2026-05-20T10:00:00Z",
4  data: { sender: "Alice", receiver: "Bob", amount: 50 },
5  previousHash: "0000abc123...",
6  hash: "0000def456...",
7  nonce: 72345,
8};

2. What is a Block in a Blockchain?

A block is the fundamental unit of a Blockchain. It contains a set of transactions or data, a timestamp, a reference to the previous block's hash (which links the chain), and a unique hash of its own content. Every new block must reference the hash of the block before it, creating a sequential chain. If any block is tampered with, its hash changes and breaks the chain, making fraud easily detectable.

Example

javascript
1const crypto = require("crypto");
2
3class Block {
4  constructor(index, data, previousHash = "") {
5    this.index = index;
6    this.timestamp = new Date().toISOString();
7    this.data = data;
8    this.previousHash = previousHash;
9    this.hash = this.calculateHash();
10  }
11
12  calculateHash() {
13    return crypto
14      .createHash("sha256")
15      .update(this.index + this.timestamp + JSON.stringify(this.data) + this.previousHash)
16      .digest("hex");
17  }
18}

3. What is decentralization in Blockchain?

Decentralization in Blockchain means that control and data are distributed across many nodes (computers) in a network instead of being managed by a single central authority. Each node holds a full or partial copy of the ledger. Decisions about adding new blocks are made collectively through consensus mechanisms. This eliminates single points of failure, prevents censorship, and reduces the need to trust any one party.

4. What is the difference between public and private Blockchain?

A public Blockchain is open to anyone — anyone can read, write, or participate in the consensus process. Examples include Bitcoin and Ethereum. A private Blockchain is restricted to a specific group of participants and is controlled by a central organization. It is faster and more efficient but less decentralized. Examples include Hyperledger Fabric. There is also a hybrid called a consortium Blockchain, where a group of organizations jointly controls it.

5. What is a consensus mechanism?

A consensus mechanism is a set of rules and protocols that all nodes in a Blockchain network follow to agree on the validity of transactions and the state of the ledger. Since there is no central authority, consensus mechanisms ensure that all participants reach the same conclusion without trusting each other. Common examples include Proof of Work (PoW), Proof of Stake (PoS), Delegated Proof of Stake (DPoS), and Practical Byzantine Fault Tolerance (PBFT).

6. What is Proof of Work (PoW)?

Proof of Work (PoW) is a consensus mechanism where nodes (miners) compete to solve a complex mathematical puzzle. The first miner to solve the puzzle gets the right to add the next block and is rewarded with cryptocurrency. This process requires significant computational power and energy, making it expensive to attack the network. Bitcoin uses Proof of Work. The difficulty of the puzzle adjusts over time to maintain a consistent block creation rate.

Example (Simplified PoW Mining)

javascript
1const crypto = require("crypto");
2
3function mineBlock(data, difficulty) {
4  const prefix = "0".repeat(difficulty);
5  let nonce = 0;
6  let hash = "";
7
8  while (!hash.startsWith(prefix)) {
9    nonce++;
10    hash = crypto
11      .createHash("sha256")
12      .update(data + nonce)
13      .digest("hex");
14  }
15
16  console.log(`Mined! Nonce: ${nonce}, Hash: ${hash}`);
17  return { nonce, hash };
18}
19
20mineBlock("Block Data", 4); // Find hash starting with "0000"

7. What is Proof of Stake (PoS)?

Proof of Stake (PoS) is a consensus mechanism where validators are chosen to create new blocks based on the amount of cryptocurrency they stake (lock up) as collateral. The more tokens a validator stakes, the higher their chance of being selected. PoS is much more energy-efficient than Proof of Work. Ethereum transitioned from PoW to PoS in September 2022 (The Merge). Validators are penalized (slashed) for dishonest behavior.

8. What is a hash function in Blockchain?

A hash function is a cryptographic algorithm that takes any input and produces a fixed-length string of characters, called a hash or digest. In Blockchain, hashing is used to link blocks together and ensure data integrity. Even a tiny change in the input produces a completely different hash (avalanche effect). Bitcoin and Ethereum use SHA-256 and Keccak-256 respectively. Hash functions are one-way — it is computationally infeasible to reverse them.

Example

javascript
1const crypto = require("crypto");
2
3const hash1 = crypto.createHash("sha256").update("Hello").digest("hex");
4const hash2 = crypto.createHash("sha256").update("hello").digest("hex");
5
6console.log(hash1);
7// "185f8db32921bd46d35cc..." 
8console.log(hash2);
9// "2cf24dba5fb0a30e26e8..." (completely different!)

9. What is a node in Blockchain?

A node is any computer or device that participates in a Blockchain network. Nodes store a copy of the Blockchain, validate transactions, and help propagate new blocks across the network. There are different types of nodes: full nodes (store the entire Blockchain and validate all transactions), light nodes (store only block headers), and mining/validator nodes (create new blocks). More nodes in a network improve its decentralization and security.

10. What is cryptocurrency mining?

Cryptocurrency mining is the process of validating transactions and adding them to the Blockchain by solving a Proof of Work puzzle. Miners compete to find a nonce value that produces a block hash meeting the network's difficulty target (e.g., a hash starting with a certain number of zeros). The winning miner receives a block reward (newly created cryptocurrency) plus transaction fees. Mining also secures the network by making it computationally expensive to alter historical records.

11. What is a Blockchain wallet?

A Blockchain wallet is a software application or hardware device that stores private and public keys and allows users to interact with a Blockchain network — sending, receiving, and managing cryptocurrency or tokens. The wallet does not store actual coins; instead, it stores the cryptographic keys needed to access funds recorded on the Blockchain. Wallets can be hot (connected to the internet) or cold (offline hardware wallets). Examples include MetaMask, Ledger, and Trust Wallet.

12. How does a Blockchain transaction work?

A Blockchain transaction goes through several stages: First, a user signs a transaction with their private key and broadcasts it to the network. Nodes validate the transaction (checking the signature and that the sender has sufficient funds). The transaction enters a mempool (memory pool) awaiting confirmation. A miner or validator picks it up, includes it in a block, and adds the block to the chain. After enough confirmations (additional blocks added on top), the transaction is considered final.

Example (Transaction Object in Ethereum)

javascript
1const transaction = {
2  from: "0xSenderAddress",
3  to: "0xReceiverAddress",
4  value: ethers.utils.parseEther("1.0"), // 1 ETH
5  gasLimit: 21000,
6  gasPrice: ethers.utils.parseUnits("20", "gwei"),
7  nonce: 5,
8  chainId: 1, // Ethereum Mainnet
9};

13. What is immutability in Blockchain?

Immutability in Blockchain means that once data has been recorded and confirmed in a block, it cannot be altered or deleted without invalidating all subsequent blocks and requiring consensus from the majority of the network. This property is achieved through cryptographic hashing, where each block's hash depends on its data and the previous block's hash. Immutability ensures a trustworthy and auditable history of all transactions.

II. Intermediate Level

1. What is a Smart Contract?

A smart contract is a self-executing program stored on a Blockchain that automatically enforces and executes the terms of an agreement when predefined conditions are met — without the need for intermediaries. Smart contracts are written in languages like Solidity (Ethereum), deployed to the Blockchain, and are immutable once deployed. They power DeFi protocols, NFT marketplaces, DAOs, and much more.

Example (Simple Solidity Smart Contract)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract SimpleStorage {
5  uint256 private storedValue;
6
7  function setValue(uint256 _value) public {
8    storedValue = _value;
9  }
10
11  function getValue() public view returns (uint256) {
12    return storedValue;
13  }
14}

2. What is Ethereum and how does it differ from Bitcoin?

Ethereum is a decentralized, open-source Blockchain platform that supports smart contracts and decentralized applications (dApps). While Bitcoin was designed primarily as a peer-to-peer digital currency, Ethereum is a programmable Blockchain that allows developers to build and deploy smart contracts and dApps. Ethereum uses Ether (ETH) as its native currency. Bitcoin uses Proof of Work; Ethereum now uses Proof of Stake. Ethereum has a much richer developer ecosystem and supports the ERC-20 and ERC-721 token standards.

3. What is Solidity?

Solidity is a statically-typed, object-oriented programming language specifically designed for writing smart contracts on the Ethereum Virtual Machine (EVM). It has a syntax similar to JavaScript and C++. Solidity supports inheritance, libraries, and complex user-defined types. It compiles to bytecode that runs on the EVM.

Example

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract Counter {
5  uint256 public count;
6
7  constructor() {
8    count = 0;
9  }
10
11  function increment() public {
12    count += 1;
13  }
14
15  function decrement() public {
16    require(count > 0, "Counter: cannot go below zero");
17    count -= 1;
18  }
19
20  function getCount() public view returns (uint256) {
21    return count;
22  }
23}

4. What is the Ethereum Virtual Machine (EVM)?

The Ethereum Virtual Machine (EVM) is a sandboxed, deterministic runtime environment that executes smart contract bytecode on every Ethereum node. It is a quasi-Turing-complete machine where all nodes run the same code and arrive at the same state. Smart contracts written in Solidity are compiled to EVM bytecode before deployment. The EVM is isolated from the outside world, ensuring consistent and secure execution across all nodes.

5. What are gas fees in Ethereum?

Gas is a unit that measures the computational effort required to execute a specific operation on the Ethereum network. Gas fees are paid in ETH to compensate validators for processing and securing transactions. Every EVM operation (e.g., addition, storage write, contract call) consumes a fixed amount of gas. The total fee is calculated as:

Gas Fee Formula

javascript
1// Total Gas Fee = Gas Used × Gas Price
2// Gas Price is measured in gwei (1 ETH = 1,000,000,000 gwei)
3
4const gasUsed = 21000; // simple ETH transfer
5const gasPriceGwei = 20; // 20 gwei
6const gasPriceEth = gasPriceGwei * 1e-9;
7
8const totalFeeEth = gasUsed * gasPriceEth;
9console.log(`Total Fee: ${totalFeeEth} ETH`); // 0.00042 ETH

6. What is a dApp (Decentralized Application)?

A dApp (Decentralized Application) is an application that runs on a Blockchain or peer-to-peer network instead of centralized servers. The backend logic is executed by smart contracts on the Blockchain, while the frontend is a standard web or mobile interface. dApps are open-source, censorship-resistant, and do not require users to trust a central authority. Examples include Uniswap (DeFi), OpenSea (NFTs), and Aave (lending).

7. What is DeFi (Decentralized Finance)?

DeFi (Decentralized Finance) is a set of financial services and applications built on Blockchain networks (primarily Ethereum) that operate without traditional intermediaries like banks or brokerages. DeFi protocols use smart contracts to enable lending, borrowing, trading, earning yield, and more. Key DeFi concepts include liquidity pools, automated market makers (AMMs), yield farming, staking, and flash loans. DeFi is accessible to anyone with a crypto wallet and an internet connection.

8. What is an NFT (Non-Fungible Token)?

A Non-Fungible Token (NFT) is a unique, indivisible digital asset stored on a Blockchain that represents ownership of a specific item — such as digital art, music, collectibles, or in-game items. Unlike fungible tokens (e.g., ETH or ERC-20 tokens) where each unit is interchangeable, every NFT has a unique identifier that makes it distinct. NFTs are typically implemented using the ERC-721 standard on Ethereum.

Example (Minimal ERC-721 NFT Contract)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4import "@openzeppelin/contracts/token/ERC721/ERC721.sol";
5import "@openzeppelin/contracts/access/Ownable.sol";
6
7contract MyNFT is ERC721, Ownable {
8  uint256 private _tokenIds;
9
10  constructor() ERC721("MyNFT", "MNFT") {}
11
12  function mintNFT(address recipient) public onlyOwner returns (uint256) {
13    _tokenIds++;
14    _mint(recipient, _tokenIds);
15    return _tokenIds;
16  }
17}

9. What is the difference between ERC-20 and ERC-721 tokens?

ERC-20 is the standard for fungible tokens on Ethereum, where every token is identical and interchangeable — like currency. One ERC-20 token is always equal in value to another of the same token. ERC-721 is the standard for non-fungible tokens (NFTs), where each token has a unique ID and can represent a unique asset. ERC-20 tokens use a balance mapping, while ERC-721 tokens use an ownership mapping per token ID.

Example (Minimal ERC-20 Token)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4import "@openzeppelin/contracts/token/ERC20/ERC20.sol";
5
6contract MyToken is ERC20 {
7  constructor(uint256 initialSupply) ERC20("MyToken", "MTK") {
8    _mint(msg.sender, initialSupply * 10 ** decimals());
9  }
10}

10. What is a Merkle Tree and why is it used in Blockchain?

A Merkle Tree is a binary tree data structure where every leaf node contains the hash of a transaction, and every non-leaf node contains the hash of its child nodes. The topmost node is called the Merkle Root. In Blockchain, the Merkle Root is stored in each block header. Merkle Trees allow efficient and secure verification of whether a specific transaction is included in a block without needing to download the entire block — known as a Merkle proof.

Example (Merkle Root Calculation)

javascript
1const crypto = require("crypto");
2
3function sha256(data) {
4  return crypto.createHash("sha256").update(data).digest("hex");
5}
6
7const txA = sha256("Transaction A");
8const txB = sha256("Transaction B");
9const txC = sha256("Transaction C");
10const txD = sha256("Transaction D");
11
12const hashAB = sha256(txA + txB);
13const hashCD = sha256(txC + txD);
14
15const merkleRoot = sha256(hashAB + hashCD);
16console.log("Merkle Root:", merkleRoot);

11. What is the difference between a hard fork and soft fork?

A hard fork is a backward-incompatible change to the Blockchain protocol. Nodes that do not upgrade to the new rules will be unable to validate new blocks, creating two separate chains. Examples include Bitcoin Cash (from Bitcoin) and Ethereum Classic (from Ethereum). A soft fork is a backward-compatible protocol change where old nodes can still validate new blocks but will not take advantage of the new rules. Soft forks do not split the network.

12. What is the double-spending problem and how does Blockchain solve it?

Double spending is the risk that a digital token is spent more than once, since digital data can be copied. Blockchain solves this by maintaining a distributed, chronologically ordered ledger where all nodes agree on the order of transactions via a consensus mechanism. Once a transaction is confirmed and buried under multiple blocks, reversing it requires re-mining all subsequent blocks and controlling more than 50% of the network's computational power, which is practically infeasible.

13. What is a 51% attack?

A 51% attack occurs when a single entity or group gains control of more than half of a Blockchain network's mining hash rate (in PoW) or staked tokens (in PoS). With majority control, the attacker can prevent new transactions from being confirmed, reverse recent transactions (enabling double spending), and reorganize the Blockchain. However, they cannot forge signatures or steal funds from addresses they do not control. Larger, more decentralized networks are far more resistant to such attacks.

14. What are public and private keys in Blockchain?

In Blockchain, a private key is a randomly generated secret number that proves ownership of a Blockchain address and is used to sign transactions. A public key is mathematically derived from the private key and is used to generate the wallet address. Others can verify transaction signatures using the public key. The private key must never be shared — losing it means losing access to all funds. This asymmetric cryptography underpins all Blockchain security.

Example (Key generation with ethers.js)

javascript
1const { ethers } = require("ethers");
2
3// Generate a random wallet
4const wallet = ethers.Wallet.createRandom();
5
6console.log("Private Key:", wallet.privateKey);
7// 0x3b1f9d2a... (keep secret!)
8
9console.log("Public Key:", wallet.publicKey);
10// 0x04a0d5f3...
11
12console.log("Address:", wallet.address);
13// 0xAbCd1234... (derived from public key)

15. What are Layer 1 and Layer 2 solutions in Blockchain?

Layer 1 (L1) refers to the base Blockchain protocol itself, such as Ethereum or Bitcoin. These provide security and decentralization but can be slow and expensive to scale. Layer 2 (L2) solutions are built on top of L1 to improve scalability by processing transactions off-chain or in batches and then settling results on L1. Examples include Optimism, Arbitrum (Optimistic Rollups), and zkSync (ZK Rollups). L2s inherit the security of L1 while dramatically increasing throughput and reducing fees.

III. Advanced Level

1. What are common Smart Contract vulnerabilities?

Smart contracts are immutable once deployed, making security critical. Common vulnerabilities include:

  • Reentrancy: A malicious contract calls back into the vulnerable contract before state is updated.

  • Integer Overflow/Underflow: Arithmetic wrapping (mitigated by Solidity 0.8+ checked math).

  • Access Control Issues: Missing or incorrect modifiers allowing unauthorized calls.

  • Front-running: Attackers observe pending transactions and insert their own at a higher gas price.

  • Uninitialized Storage Pointers: Incorrect storage variable references leading to data corruption.

2. What is a Reentrancy Attack and how to prevent it?

A reentrancy attack occurs when an external malicious contract calls back into the vulnerable contract before the first execution is complete, allowing it to repeatedly drain funds. The infamous DAO hack in 2016 used this exploit. Prevention involves following the Checks-Effects-Interactions pattern (update state before making external calls) or using a reentrancy guard (mutex).

Vulnerable Contract

solidity
1// VULNERABLE - Do NOT use
2function withdraw(uint256 amount) public {
3  require(balances[msg.sender] >= amount);
4  (bool success, ) = msg.sender.call{value: amount}(""); // External call BEFORE state update
5  require(success);
6  balances[msg.sender] -= amount; // State updated AFTER — too late!
7}

Secure Contract (Checks-Effects-Interactions Pattern)

solidity
1// SECURE - Checks-Effects-Interactions pattern
2function withdraw(uint256 amount) public {
3  require(balances[msg.sender] >= amount);  // 1. Check
4  balances[msg.sender] -= amount;           // 2. Effect (update state first)
5  (bool success, ) = msg.sender.call{value: amount}(""); // 3. Interaction
6  require(success);
7}

3. What are upgradeable smart contracts and how do proxy patterns work?

Smart contracts are immutable by default. Upgradeable contracts use a proxy pattern to separate the contract's logic from its storage and address. A proxy contract (with a stable address) delegates all calls to a separate logic (implementation) contract. When an upgrade is needed, only the logic contract is replaced while the proxy's address and storage remain unchanged. Common proxy patterns include the Transparent Proxy, UUPS (Universal Upgradeable Proxy Standard), and Beacon Proxy.

Example (Minimal Proxy using delegatecall)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract Proxy {
5  address public implementation;
6  address public admin;
7
8  constructor(address _impl) {
9    implementation = _impl;
10    admin = msg.sender;
11  }
12
13  function upgrade(address newImpl) external {
14    require(msg.sender == admin, "Not admin");
15    implementation = newImpl;
16  }
17
18  fallback() external payable {
19    address impl = implementation;
20    assembly {
21      calldatacopy(0, 0, calldatasize())
22      let result := delegatecall(gas(), impl, 0, calldatasize(), 0, 0)
23      returndatacopy(0, 0, returndatasize())
24      switch result
25      case 0 { revert(0, returndatasize()) }
26      default { return(0, returndatasize()) }
27    }
28  }
29}

4. What is the Oracle Problem in Blockchain?

Smart contracts are deterministic and isolated — they cannot natively access real-world data (e.g., price feeds, weather, sports results). The Oracle Problem refers to the challenge of securely and reliably bringing off-chain data on-chain. A centralized oracle is a single point of failure and trust. Decentralized oracle networks like Chainlink solve this by aggregating data from many independent node operators and using cryptoeconomic incentives to ensure honesty.

Example (Chainlink Price Feed)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";
5
6contract PriceConsumer {
7  AggregatorV3Interface internal priceFeed;
8
9  constructor() {
10    // ETH/USD feed on Ethereum Mainnet
11    priceFeed = AggregatorV3Interface(0x5f4eC3Df9cbd43714FE2740f5E3616155c5b8419);
12  }
13
14  function getLatestPrice() public view returns (int256) {
15    (, int256 price, , , ) = priceFeed.latestRoundData();
16    return price; // Returns price with 8 decimals
17  }
18}

5. What is IPFS and how is it used in Blockchain?

IPFS (InterPlanetary File System) is a peer-to-peer distributed file storage protocol. Files are referenced by their content hash (CID) rather than a location, making them immutable and censorship-resistant. In Blockchain, IPFS is commonly used with NFTs — instead of storing large files (images, videos) on-chain (which is expensive), the NFT contract stores only the IPFS CID pointing to the metadata or media. This keeps on-chain data minimal while retaining decentralized and verifiable file storage.

Example (NFT metadata stored on IPFS)

javascript
1// NFT metadata JSON stored on IPFS
2const metadata = {
3  name: "My NFT #1",
4  description: "A unique digital collectible",
5  image: "ipfs://QmXyz.../image.png",
6  attributes: [
7    { trait_type: "Background", value: "Blue" },
8    { trait_type: "Rarity", value: "Legendary" },
9  ],
10};
11
12// The tokenURI in the smart contract points to:
13// "ipfs://QmAbc123.../metadata.json"

6. What is a DAO (Decentralized Autonomous Organization)?

A DAO is an organization governed by smart contracts and its token holders rather than a central management team. Rules and decisions are encoded on-chain; token holders vote on proposals, and results are automatically executed by smart contracts. DAOs are used to govern DeFi protocols, manage treasuries, and coordinate communities. Examples include MakerDAO, Uniswap DAO, and Compound. The key advantage is trustless, transparent governance.

Example (Simple Governance Voting)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract SimpleDAO {
5  struct Proposal {
6    string description;
7    uint256 voteCount;
8    bool executed;
9  }
10
11  mapping(uint256 => Proposal) public proposals;
12  mapping(address => bool) public hasVoted;
13  uint256 public proposalCount;
14
15  function createProposal(string memory desc) external {
16    proposals[proposalCount++] = Proposal(desc, 0, false);
17  }
18
19  function vote(uint256 proposalId) external {
20    require(!hasVoted[msg.sender], "Already voted");
21    hasVoted[msg.sender] = true;
22    proposals[proposalId].voteCount++;
23  }
24}

7. What are Zero-Knowledge Proofs?

A Zero-Knowledge Proof (ZKP) is a cryptographic protocol where one party (the prover) can prove to another party (the verifier) that a statement is true without revealing any information beyond the validity of the statement. In Blockchain, ZKPs are used for privacy (shielded transactions in Zcash) and scalability (ZK Rollups like zkSync and StarkNet, where transaction validity is proven off-chain and only the proof is submitted on-chain, saving gas).

8. What is the Blockchain Trilemma?

The Blockchain Trilemma, coined by Vitalik Buterin, states that a Blockchain system can only fully achieve two of the following three properties at once: Decentralization (no single controlling party), Security (resistance to attacks), and Scalability (high transaction throughput). For example, Bitcoin prioritizes decentralization and security but is slow. Many L2 solutions and alternative L1s (Solana, Avalanche) trade off some decentralization for greater scalability.

9. What is cross-chain interoperability?

Cross-chain interoperability refers to the ability of different Blockchain networks to communicate, share data, and transfer assets between each other. Since blockchains like Ethereum, Solana, and BNB Chain operate independently, bridges and interoperability protocols are needed to transfer tokens or messages across chains. Examples include Chainlink CCIP, Wormhole, LayerZero, and Polkadot's cross-chain messaging (XCM). Cross-chain bridges introduce security risks and have been the target of major hacks.

10. How do you integrate a smart contract with a frontend using ethers.js?

ethers.js is a lightweight JavaScript library for interacting with the Ethereum Blockchain from a frontend. To integrate a smart contract, you need the contract's ABI (Application Binary Interface) and deployed address. You connect to the user's wallet via a provider (e.g., MetaMask), create a contract instance, and call its functions directly from JavaScript.

Example (Calling a Smart Contract with ethers.js)

javascript
1import { ethers } from "ethers";
2
3const CONTRACT_ADDRESS = "0xYourContractAddress";
4const ABI = [
5  "function getValue() view returns (uint256)",
6  "function setValue(uint256 _value) public",
7];
8
9async function connectAndInteract() {
10  // Connect to MetaMask
11  const provider = new ethers.BrowserProvider(window.ethereum);
12  await provider.send("eth_requestAccounts", []);
13  const signer = await provider.getSigner();
14
15  // Create contract instance
16  const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, signer);
17
18  // Read from contract (no gas)
19  const value = await contract.getValue();
20  console.log("Current value:", value.toString());
21
22  // Write to contract (requires gas)
23  const tx = await contract.setValue(42);
24  await tx.wait(); // Wait for confirmation
25  console.log("Transaction confirmed!");
26}

11. How do you test smart contracts using Hardhat?

Hardhat is a popular Ethereum development framework for compiling, testing, and deploying smart contracts. Tests are written in JavaScript or TypeScript using the Mocha/Chai testing framework. Hardhat provides a local EVM, helpful error messages, and plugins like hardhat-ethers and hardhat-chai-matchers.

Example (Hardhat Test)

javascript
1const { expect } = require("chai");
2const { ethers } = require("hardhat");
3
4describe("Counter", function () {
5  let counter;
6  let owner;
7
8  beforeEach(async function () {
9    [owner] = await ethers.getSigners();
10    const Counter = await ethers.getContractFactory("Counter");
11    counter = await Counter.deploy();
12  });
13
14  it("Should start at 0", async function () {
15    expect(await counter.getCount()).to.equal(0);
16  });
17
18  it("Should increment correctly", async function () {
19    await counter.increment();
20    await counter.increment();
21    expect(await counter.getCount()).to.equal(2);
22  });
23
24  it("Should revert on underflow", async function () {
25    await expect(counter.decrement()).to.be.revertedWith(
26      "Counter: cannot go below zero"
27    );
28  });
29});

12. What is MEV (Maximal Extractable Value)?

MEV (Maximal Extractable Value) refers to the profit that validators/miners can extract by reordering, inserting, or censoring transactions within the blocks they produce. Since validators choose which transactions to include and in what order, they can front-run profitable trades, perform arbitrage, or liquidate positions before other users. MEV is a significant economic force on Ethereum and has led to the development of MEV protection tools like Flashbots and MEV-Boost.

13. How do you optimize gas usage in Solidity?

Gas optimization is crucial for reducing transaction costs in Solidity. Key strategies include:

Example (Gas Optimization Techniques)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract GasOptimized {
5  // 1. Use uint256 instead of uint8 for single variables (saves conversion cost)
6  uint256 public counter;
7
8  // 2. Pack structs to use fewer storage slots
9  struct PackedData {
10    uint128 a;   // Slot 1 (first 128 bits)
11    uint128 b;   // Slot 1 (second 128 bits) - packed!
12  }
13
14  // 3. Use calldata instead of memory for read-only function params
15  function processArray(uint256[] calldata data) external pure returns (uint256) {
16    uint256 total;
17    uint256 len = data.length; // Cache length to avoid repeated SLOAD
18    for (uint256 i; i < len; ) {
19      total += data[i];
20      unchecked { ++i; } // 4. Use unchecked for safe increments (saves overflow check)
21    }
22    return total;
23  }
24
25  // 5. Use immutable for values set in constructor (stored in bytecode, not storage)
26  address public immutable owner;
27  constructor() { owner = msg.sender; }
28}

14. What is the difference between storage, memory, and stack in Solidity?

Solidity has three main data locations. Storage is persistent on the Blockchain — state variables live here and reading/writing is expensive. Memory is a temporary location used for variables within function execution — it is erased after the function ends and is cheaper than storage. Stack is the cheapest and most limited — it holds local value types and has a maximum depth of 1024 elements. Choosing the right data location is critical for both correctness and gas efficiency.

Example

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract DataLocations {
5  uint256[] public storageArray; // Persistent on Blockchain
6
7  function example() public {
8    // Memory: temporary, cleared after function
9    uint256[] memory memArray = new uint256[](3);
10    memArray[0] = 1;
11
12    // Stack: local primitive value type
13    uint256 stackVar = 42; // Lives on the stack
14
15    // Storage reference (modifies storageArray directly)
16    uint256[] storage ref = storageArray;
17    ref.push(stackVar);
18  }
19}

15. What are Events and Logs in Solidity?

Events in Solidity are a way for smart contracts to emit notifications that are stored in the transaction logs of the Blockchain. They are much cheaper than storage and are used to inform frontends about state changes (e.g., a transfer occurred). Indexed parameters allow efficient filtering of logs. Events are not accessible from within smart contracts — they exist solely as transaction receipts for external consumption.

Example

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4contract Token {
5  event Transfer(
6    address indexed from,
7    address indexed to,
8    uint256 amount
9  );
10
11  function transfer(address to, uint256 amount) external {
12    // ... transfer logic ...
13    emit Transfer(msg.sender, to, amount);
14  }
15}

Listening to Events in JavaScript

javascript
1// Listen to Transfer events
2contract.on("Transfer", (from, to, amount) => {
3  console.log(`${from} sent ${amount} tokens to ${to}`);
4});

16. What is the Multicall pattern in Blockchain?

The Multicall pattern allows batching multiple read or write contract calls into a single transaction or RPC request. This reduces network latency, lowers gas costs for batch operations, and ensures atomicity (all or nothing). The Multicall3 contract is widely deployed and used by DeFi protocols and frontends to fetch data from many contracts in a single call, improving performance significantly.

Example (Multicall with ethers.js)

javascript
1import { ethers } from "ethers";
2
3const MULTICALL3_ADDRESS = "0xcA11bde05977b3631167028862bE2a173976CA11";
4const MULTICALL3_ABI = [
5  "function aggregate3(tuple(address target, bool allowFailure, bytes callData)[] calls) view returns (tuple(bool success, bytes returnData)[] results)",
6];
7
8async function batchReadContracts(provider, calls) {
9  const multicall = new ethers.Contract(MULTICALL3_ADDRESS, MULTICALL3_ABI, provider);
10
11  const results = await multicall.aggregate3(
12    calls.map(({ address, data }) => ({
13      target: address,
14      allowFailure: false,
15      callData: data,
16    }))
17  );
18
19  return results.map((r) => r.returnData);
20}

17. What is Account Abstraction in Ethereum?

Account Abstraction (ERC-4337) allows smart contracts to act as user accounts, removing the distinction between Externally Owned Accounts (EOAs) and contract accounts. This enables powerful features like gasless transactions (sponsored by a paymaster), multi-signature wallets, social recovery, session keys, and custom transaction validation logic — all without changing the Ethereum core protocol. It is the foundation for next-generation smart wallets.

18. What are Flash Loans and how do they work?

Flash Loans are uncollateralized loans that must be borrowed and repaid within the same transaction (same block). If the loan is not repaid by the end of the transaction, the entire transaction reverts as if it never happened. This is possible because Blockchain state is only committed if the transaction succeeds. Flash loans enable arbitrage, collateral swaps, and self-liquidation. Aave is one of the largest flash loan providers.

Example (Aave Flash Loan Skeleton)

solidity
1// SPDX-License-Identifier: MIT
2pragma solidity ^0.8.0;
3
4import "@aave/core-v3/contracts/flashloan/base/FlashLoanSimpleReceiverBase.sol";
5import "@aave/core-v3/contracts/interfaces/IPoolAddressesProvider.sol";
6import "@openzeppelin/contracts/token/ERC20/IERC20.sol";
7
8contract MyFlashLoan is FlashLoanSimpleReceiverBase {
9  constructor(IPoolAddressesProvider provider)
10    FlashLoanSimpleReceiverBase(provider) {}
11
12  function executeOperation(
13    address asset,
14    uint256 amount,
15    uint256 premium,
16    address initiator,
17    bytes calldata params
18  ) external override returns (bool) {
19    // Your flash loan logic here (arbitrage, liquidation, etc.)
20
21    // Approve repayment: amount + fee
22    IERC20(asset).approve(address(POOL), amount + premium);
23    return true;
24  }
25
26  function requestFlashLoan(address token, uint256 amount) external {
27    POOL.flashLoanSimple(address(this), token, amount, "", 0);
28  }
29}

19. What is an AMM (Automated Market Maker)?

An Automated Market Maker (AMM) is a type of decentralized exchange protocol that uses a mathematical formula instead of an order book to price assets. Liquidity providers deposit token pairs into liquidity pools, and traders swap against these pools. The most common formula is the constant product formula: x * y = k, used by Uniswap. AMMs enable permissionless, 24/7 token trading without a central operator.

Example (Constant Product Formula)

javascript
1// Uniswap V2 constant product: x * y = k
2function getAmountOut(amountIn, reserveIn, reserveOut) {
3  // Apply 0.3% fee
4  const amountInWithFee = amountIn * 997;
5  const numerator = amountInWithFee * reserveOut;
6  const denominator = reserveIn * 1000 + amountInWithFee;
7  return Math.floor(numerator / denominator);
8}
9
10// Pool: 100 ETH, 200,000 USDC (k = 20,000,000)
11const reserveETH = 100;
12const reserveUSDC = 200000;
13const amountIn = 1; // Selling 1 ETH
14
15const amountOut = getAmountOut(amountIn, reserveETH, reserveUSDC);
16console.log(`Receive: ${amountOut} USDC`); // ~1976 USDC

20. How do you deploy a smart contract to a testnet?

To deploy a smart contract to a testnet (e.g., Sepolia), you need a funded wallet (testnet ETH from a faucet), a deployment tool like Hardhat or Foundry, and a node provider like Infura or Alchemy. You write a deployment script, configure your network settings, and run the deploy command. Always deploy to a testnet first before mainnet.

Example (Hardhat Deployment Script)

javascript
1// scripts/deploy.js
2const { ethers } = require("hardhat");
3
4async function main() {
5  const [deployer] = await ethers.getSigners();
6  console.log("Deploying with account:", deployer.address);
7
8  const Counter = await ethers.getContractFactory("Counter");
9  const counter = await Counter.deploy();
10  await counter.waitForDeployment();
11
12  console.log("Counter deployed to:", await counter.getAddress());
13}
14
15main().catch((error) => {
16  console.error(error);
17  process.exit(1);
18});
19
20// Run with: npx hardhat run scripts/deploy.js --network sepolia

Hardhat Config (hardhat.config.js)

javascript
1require("@nomicfoundation/hardhat-toolbox");
2require("dotenv").config();
3
4module.exports = {
5  solidity: "0.8.24",
6  networks: {
7    sepolia: {
8      url: process.env.SEPOLIA_RPC_URL,
9      accounts: [process.env.PRIVATE_KEY],
10    },
11  },
12  etherscan: {
13    apiKey: process.env.ETHERSCAN_API_KEY,
14  },
15};

21. How would you approach a smart contract security audit?

A smart contract audit involves a systematic review of the contract code to identify vulnerabilities, logic errors, and areas for gas optimization before deployment. Since smart contracts are immutable and often hold significant funds, auditing is critical. The process combines automated tools and manual review.

Audit Process Steps:

  • Understand the project: Read documentation, specs, and intended behavior.

  • Run automated tools: Use Slither, Mythril, or Aderyn to detect common vulnerability patterns.

  • Manual review: Check access control, reentrancy, integer math, and business logic flaws.

  • Test coverage: Ensure unit and integration tests cover all critical paths using Hardhat or Foundry.

  • Fuzz testing: Use Foundry's fuzzer to test with random inputs and find edge cases.

  • Report findings: Document all issues with severity levels (Critical, High, Medium, Low, Informational).

  • Remediation review: Verify that all reported issues have been properly fixed before deployment.

Found this helpful?

Share it with your network

Related Articles

Frontend

React JS Interview Questions

Prepare for your React interview with the most asked questions for freshers and experienced developers. Covers hooks, lifecycle, performance optimization, and real-world scenarios.

Full Stack

Next Js Interview Questions

Explore the most important Next.js interview questions including SSR, SSG, ISR, routing, performance optimization, and real-world implementation examples.