Top 48 Blockchain / Web3 / Solidity Interview Questions & Answers (2026)
About Blockchain / Web3 / Solidity
Top 50 Blockchain, Web3, and Solidity interview questions covering Ethereum, smart contracts, DeFi, NFTs, and decentralized application development. Companies hiring for Blockchain / Web3 / Solidity roles test this knowledge at every stage — from first-round screens that check the basics to final-round conversations about real-world trade-offs.
What to Expect in a Blockchain / Web3 / Solidity Interview
Expect a mix of conceptual and practical Blockchain / Web3 / Solidity questions: clear definitions and core-concept checks for junior roles, hands-on scenario questions for mid-level roles, and architecture or trade-off discussions for senior roles. Interviewers usually move from foundational topics toward the kind of problems you'd actually face on the job.
How to Use This Guide
Work through the Blockchain / Web3 / Solidity questions in order — Beginner, then Intermediate, then Advanced — so each concept builds on the last. Every question has its own page; bookmark the ones that trip you up and revisit them the day before your interview.
Curated by Tech Baithak Editorial Team · Last updated: June 2026
Core concepts every Blockchain / Web3 / Solidity developer must know.
01
What is blockchain?
A blockchain is a distributed, decentralized digital ledger that records transactions across many computers in a way that makes the records tamper-evident and immutable. Each "block" contains a batch of transactions and a cryptographic hash of the previous block, forming a "chain." Key properties: (1) Decentralized — no single entity controls the ledger; maintained by a peer-to-peer network of nodes; (2) Immutable — once data is recorded and confirmed, it cannot be altered without altering all subsequent blocks (computationally infeasible on large networks); (3) Transparent — all transactions are visible to participants (on public blockchains); (4) Consensus-based — network participants agree on the valid state through consensus mechanisms (PoW, PoS). Originally invented by Satoshi Nakamoto for Bitcoin (2008), blockchain technology now underlies thousands of cryptocurrencies and applications beyond finance.
02
What is a distributed ledger?
A distributed ledger is a database that is shared, replicated, and synchronized across multiple locations, institutions, or geographies. Unlike a centralized database (managed by one entity, e.g., a bank's database), a distributed ledger has no single point of control or failure. Each participant (node) holds a complete or partial copy of the ledger. Changes to the ledger are propagated to all nodes and must be agreed upon through a consensus mechanism. Blockchain is the most well-known type of distributed ledger — it structures records into linked blocks. Other distributed ledger technologies (DLTs) exist without a block structure (e.g., Hashgraph, Tangle/IOTA). Distributed ledgers remove the need for trusted intermediaries (banks, notaries, clearinghouses) by making trust a property of the system rather than of a central authority.
03
What is a block in a blockchain?
A block is the fundamental unit of data in a blockchain. Each block contains: (1) Block header — metadata including the block number (height), timestamp, previous block's hash (creating the chain), Merkle root (cryptographic summary of all transactions in this block), and nonce (used in Proof of Work); (2) Transactions — the batch of validated transactions (transfers, smart contract calls) included in the block; (3) Block hash — the cryptographic fingerprint of this block's header. The chain of hashes is the security mechanism: changing data in any block changes its hash, breaking the link to all subsequent blocks. This makes retroactive tampering computationally detectable. Bitcoin blocks average 1MB every 10 minutes; Ethereum blocks are limited by gas (computation) rather than size, with blocks produced every ~12 seconds.
04
What is a node in a blockchain network?
A node is any computer participating in the blockchain network. Types of nodes: (1) Full node — downloads and stores the entire blockchain history, independently validates all transactions and blocks against consensus rules. Provides maximum security and contributes to network decentralization; (2) Light node (SPV) — downloads only block headers (not full blocks), relies on full nodes for transaction verification. Used in mobile wallets for efficiency; (3) Archive node — stores the full blockchain plus all historical states at every block (needed for querying old state); extremely storage-intensive; (4) Mining/Validator node — participates in block creation (PoW: mining; PoS: staking and validating); (5) Bootstrap node — helps new nodes discover peers. Nodes communicate via a peer-to-peer protocol (like libp2p), gossipping new transactions and blocks. The number of full nodes (Ethereum: ~8,000+; Bitcoin: ~15,000+) directly determines a network's decentralization and censorship resistance.
05
What is cryptocurrency?
Cryptocurrency is a digital or virtual currency that uses cryptography for security and operates on a decentralized network (typically a blockchain), without relying on a central authority like a government or bank. Key characteristics: (1) Decentralized — no central issuer or controller; (2) Cryptographically secured — public/private key cryptography ensures only the rightful owner can spend funds; (3) Transparent — all transactions are recorded on a public blockchain; (4) Pseudonymous — addresses are public but not directly tied to real identities; (5) Borderless — can be sent anywhere in the world without intermediaries. Examples: Bitcoin (BTC) — the first cryptocurrency, digital gold, store of value; Ethereum (ETH) — programmable blockchain with smart contracts; stablecoins (USDC, USDT) — pegged to fiat currencies for stability. Cryptocurrencies serve as: medium of exchange, store of value, and utility tokens for accessing blockchain services.
06
What is Bitcoin?
Bitcoin (BTC) is the world's first and largest cryptocurrency, created by the pseudonymous Satoshi Nakamoto in 2008 (whitepaper) and launched in January 2009. Key facts: (1) Fixed supply — maximum 21 million BTC will ever exist (currently ~19.7M mined); the finite supply is enforced by the protocol; (2) Halving — every ~4 years, the mining reward halves (currently 3.125 BTC per block after April 2024 halving); (3) Proof of Work — uses SHA-256 mining; energy-intensive but battle-tested; (4) 10-minute blocks — designed for ~10 minutes between blocks; (5) UTXO model — tracks unspent transaction outputs rather than account balances; (6) Limited programmability — Bitcoin Script is intentionally simple for security; not Turing-complete; (7) Lightning Network — Layer 2 scaling solution for fast, cheap Bitcoin payments. Bitcoin is primarily viewed as a store of value ("digital gold") and hedge against inflation, not a general-purpose computational platform.
07
What is Ethereum?
Ethereum is a decentralized, open-source blockchain platform that features smart contract functionality — programs stored on the blockchain that execute automatically when conditions are met. Created by Vitalik Buterin (whitepaper 2013, mainnet launch July 2015). Key features: (1) Turing-complete EVM — the Ethereum Virtual Machine executes arbitrary smart contract code, enabling decentralized applications (dApps); (2) ETH (Ether) — the native cryptocurrency used to pay for computation (gas); (3) Proof of Stake — switched from Proof of Work to PoS in "The Merge" (September 2022), reducing energy consumption by ~99.95%; (4) Token standards — ERC-20 (fungible tokens), ERC-721 (NFTs), ERC-1155 (multi-token); (5) DeFi ecosystem — largest decentralized finance ecosystem by Total Value Locked (TVL); (6) Layer 2 scaling — Optimism, Arbitrum, zkSync, Polygon scaling solutions. Ethereum is the dominant platform for DeFi, NFTs, and smart contract development.
08
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 predetermined conditions are met — without intermediaries. The term was coined by Nick Szabo in 1994. On Ethereum, smart contracts are written in Solidity (or Vyper), compiled to bytecode, and deployed on the blockchain. Once deployed, they are: (1) Immutable — the code cannot be changed (unless designed with upgrade patterns); (2) Deterministic — same input always produces same output; (3) Trustless — execution is guaranteed by the blockchain, not by the counterparty's honesty; (4) Transparent — anyone can read the bytecode (and verify the source with Etherscan); (5) Permanent — live as long as the blockchain exists. Examples: automated token swaps (DEXes), lending/borrowing protocols, NFT minting, voting systems, and escrow agreements.
09
What is Web3?
Web3 (also written as Web 3.0) is a vision for a decentralized internet built on blockchain technology, where users own their data, digital assets, and identity — in contrast to Web2's model where corporations (Google, Facebook, Amazon) control centralized platforms. The Web evolution: Web1 (read-only, static HTML pages, 1990s); Web2 (read-write, social media, user-generated content but centralized platforms, 2000s–present); Web3 (read-write-own, decentralized, permissionless, trustless, 2020s). Key Web3 technologies: blockchain (decentralized data layer), smart contracts (decentralized logic), cryptocurrencies and tokens (decentralized value transfer), NFTs (verifiable digital ownership), DAOs (decentralized governance), IPFS/Arweave (decentralized storage), DeFi (decentralized finance). Web3 promises to return power to users but faces challenges: scalability, UX complexity, regulatory uncertainty, and environmental concerns.
10
What is Solidity?
Solidity is a statically-typed, object-oriented programming language designed specifically for writing smart contracts on Ethereum and other EVM-compatible blockchains. Created by the Ethereum team (Christian Reitwiessner, Gavin Wood, et al.), first proposed in 2014. Key characteristics: (1) Syntax — influenced by JavaScript, C++, and Python; compiled to EVM bytecode; (2) Statically typed — variables must declare their type; (3) Contract-oriented — the primary unit is a contract (like a class); (4) Versioning — every Solidity file declares the compiler version: pragma solidity ^0.8.0;; (5) Data locations — variables can be in storage (persistent), memory (temporary), or calldata (read-only arguments); (6) Security-critical — bugs in smart contracts can result in permanent loss of funds; security is paramount. The current stable version is 0.8.x (with significant safety improvements like built-in overflow protection added in 0.8.0).
11
What is a wallet in blockchain?
A blockchain wallet is software (or hardware) that stores the private keys used to sign transactions, giving access to cryptocurrency on the blockchain. Importantly: wallets don't actually store cryptocurrency — the crypto lives on the blockchain; the wallet stores the keys that prove ownership. Types: (1) Hot wallets — connected to the internet; convenient for frequent transactions. Examples: MetaMask (browser extension), Trust Wallet (mobile), Coinbase Wallet; (2) Cold wallets (Hardware wallets) — offline storage; most secure for long-term storage. Examples: Ledger, Trezor; (3) Paper wallets — private key printed on paper; secure if stored safely; (4) Custodial wallets — the exchange or service holds the keys on your behalf (e.g., Coinbase). Risky: "not your keys, not your coins"; (5) Non-custodial wallets — you hold your own keys. Requires responsible backup of seed phrase (12/24 words). Seed phrases derive all private keys and must never be shared or stored online.
12
What is a public key and private key in blockchain?
Blockchain uses asymmetric cryptography (public-key cryptography) for identity and transaction signing. (1) Private key — a randomly generated 256-bit number that serves as your secret identity on the blockchain. It's used to sign transactions, proving you authorize a transfer. Anyone with your private key has complete control over your funds. Must be kept absolutely secret. In Ethereum, it's a 32-byte hex number; (2) Public key — mathematically derived from the private key using Elliptic Curve Cryptography (secp256k1). Can be freely shared — allows others to verify your signatures but cannot be used to derive your private key (one-way function); (3) Address — derived from the public key by hashing (Keccak-256) and taking the last 20 bytes. Ethereum addresses are 42 hex characters starting with 0x. Transaction flow: sender signs the transaction with private key → network verifies signature using public key → transaction executes if valid.
13
What is a consensus mechanism?
A consensus mechanism is the method by which distributed blockchain nodes agree on the valid state of the ledger without a central authority. Without consensus, different nodes could have conflicting views of the blockchain. Key mechanisms: (1) Proof of Work (PoW) — miners compete to solve a computationally difficult puzzle; the winner adds the next block and receives a reward. Secure but energy-intensive (Bitcoin, Litecoin); (2) Proof of Stake (PoS) — validators are chosen to propose/attest blocks based on staked cryptocurrency. Much more energy-efficient; slashing punishes malicious behavior (Ethereum post-Merge, Cardano, Solana); (3) Delegated PoS (DPoS) — token holders vote for delegates who validate blocks (EOS, TRON); (4) Proof of Authority (PoA) — trusted validators (identified entities) validate blocks; used in private/consortium blockchains; (5) Proof of History (PoH) — Solana's mechanism using a cryptographic clock to order events. Consensus mechanisms determine a blockchain's security, decentralization, and scalability trade-offs.
14
What is Proof of Work (PoW)?
Proof of Work (PoW) is the original blockchain consensus mechanism invented for Bitcoin. Miners compete to solve a computationally intensive cryptographic puzzle: find a nonce such that the block header's SHA-256 hash is below a target value (has N leading zeros). The puzzle is asymmetric: hard to solve, trivial to verify. The first miner to find the solution broadcasts the block; other nodes verify and accept it; the winning miner receives the block reward (newly minted BTC) + transaction fees. Key properties: (1) Security through energy expenditure — attacking PoW requires controlling 51% of the network's hash rate, which is enormously expensive; (2) Difficulty adjustment — Bitcoin adjusts mining difficulty every 2016 blocks (~2 weeks) to maintain ~10 minute block times as hash rate changes; (3) Energy intensive — Bitcoin's PoW uses more electricity than many countries (estimated ~130 TWh/year); (4) ASIC dominance — specialized mining hardware (ASICs) centralize mining power; (5) Sybil resistant — identity attack is prevented by the cost of compute.
15
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) rather than computational work. How it works in Ethereum: (1) Staking — validators deposit 32 ETH as collateral; (2) Attestation — validators are randomly selected to propose and attest to blocks each epoch (~6.4 minutes); (3) Rewards — validators earn staking rewards (~3-5% APY) for honest participation; (4) Slashing — validators behaving maliciously (double voting, equivocation) have a portion of their stake destroyed. PoS advantages over PoW: (1) Energy efficiency — ~99.95% less energy than PoW; (2) Lower entry barrier — no specialized hardware required; (3) Economic security — attacking requires owning 1/3+ of staked ETH (economically self-destructive). Disadvantages: richer validators have more influence ("rich get richer"); newer and less battle-tested than PoW.
16
What is a decentralized application (DApp)?
A decentralized application (DApp) is an application that runs on a decentralized network (typically a blockchain) rather than a centralized server. Unlike traditional apps where a company controls the backend, DApps use smart contracts as the backend — code that runs autonomously on the blockchain. Components: (1) Smart contracts — backend logic on the blockchain (replaces servers); (2) Frontend — typically a web interface (React/Vue app) that interacts with smart contracts via a Web3 provider (MetaMask, ethers.js, web3.js); (3) Decentralized storage — IPFS or Arweave for storing files/media (blockchain is too expensive for large data); (4) Wallet integration — users authenticate with their wallet (no username/password). DApp properties: permissionless (anyone can use), censorship-resistant (no single entity can shut it down), trustless (rules enforced by code, not a company). Examples: Uniswap (DEX), Aave (lending), OpenSea (NFT marketplace), Compound (money market).
17
What is an NFT (Non-Fungible Token)?
An NFT (Non-Fungible Token) is a unique digital asset whose ownership and provenance are recorded on a blockchain. "Non-fungible" means each token is unique and not interchangeable — unlike ETH (1 ETH = 1 ETH, fungible). Key properties: (1) Uniqueness — each NFT has a unique token ID on its smart contract; (2) Verifiable ownership — the blockchain records who owns each NFT, publicly and immutably; (3) Programmable royalties — creators can receive royalties automatically on secondary sales; (4) Interoperability — NFTs follow standards (ERC-721, ERC-1155) that wallets and marketplaces understand. What NFTs represent: digital art, collectibles, game items, music, virtual real estate, event tickets, membership passes. Important clarification: an NFT is a token on the blockchain; the associated file (image, video) is often stored off-chain (IPFS or centralized server). The NFT proves you own the token, not necessarily that you own exclusive rights to the underlying content. The NFT boom of 2021 saw billions in trading volume on platforms like OpenSea.
18
What is DeFi (Decentralized Finance)?
DeFi (Decentralized Finance) is an ecosystem of financial services built on blockchain technology (primarily Ethereum) that replaces traditional financial intermediaries (banks, brokers, exchanges) with smart contracts. DeFi protocols are: permissionless (anyone with a wallet can use them), trustless (rules enforced by code), composable ("money Legos" — protocols built on other protocols). Major DeFi categories: (1) Decentralized Exchanges (DEX) — trade tokens without a central order book; Uniswap, Curve, Balancer; (2) Lending/Borrowing — lend crypto for interest or borrow against collateral; Aave, Compound, MakerDAO; (3) Stablecoins — DAI (algorithmic), USDC (centralized), FRAX (hybrid); (4) Yield Farming/Liquidity Mining — earn tokens by providing liquidity; (5) Derivatives — perpetuals, options, synthetics; dYdX, GMX, Synthetix; (6) Asset management — Yearn Finance. DeFi TVL peaked at ~$180B in late 2021. Risks: smart contract bugs, liquidation, bridge exploits, regulatory uncertainty.
19
What is a gas fee in Ethereum?
Gas is the unit that measures the computational effort required to execute operations on the Ethereum network. Every transaction and smart contract call costs a certain amount of gas. Gas fee = gas units used × gas price (in gwei). After EIP-1559 (August 2021): fee = base fee (burned, set by network) + priority fee/tip (paid to validator). Gas incentivizes validators to include transactions and prevents spam by making denial-of-service attacks expensive. Key concepts: (1) Gas limit — maximum gas the user is willing to spend (set per transaction); unused gas is refunded; (2) Base fee — minimum fee required by the current block (adjusts up/down based on block fullness); (3) Priority fee — optional tip to validators for faster inclusion; (4) 1 ETH = 10^9 gwei; typical base fees range from 5–100+ gwei. Gas costs vary by operation: simple ETH transfer (~21,000 gas), ERC-20 transfer (~65,000 gas), complex DeFi interaction (~200,000–1,000,000+ gas). High gas fees were a major driver of Layer 2 adoption.
20
What is an ABI (Application Binary Interface) in Ethereum?
An ABI (Application Binary Interface) is the interface specification that defines how to encode function calls and decode return values when interacting with an Ethereum smart contract. It is the boundary between your application (web3.js/ethers.js) and the compiled smart contract bytecode. The ABI is generated by the Solidity compiler (alongside the bytecode) and describes: (1) Functions — name, input parameter types/names, output types, whether payable/view/pure; (2) Events — name, parameter types (indexed vs. not), used for efficient log querying; (3) Errors — custom error definitions for revert messages; (4) Constructor — parameters for deployment. To call a contract function with ethers.js: const contract = new ethers.Contract(address, abi, signer); const result = await contract.transfer(to, amount). ethers.js uses the ABI to encode the function call to the correct bytecode format and decode the response. ABIs are JSON arrays and are published on Etherscan alongside verified contract source code.
Practical knowledge for developers with hands-on experience.
01
How does Ethereum's EVM (Ethereum Virtual Machine) work?
The Ethereum Virtual Machine (EVM) is the sandboxed runtime environment that executes smart contract bytecode on every Ethereum node. Key characteristics: (1) Stack-based — the EVM uses a 1024-element stack (with 32-byte/256-bit words) for computation, not registers; (2) Deterministic — same input always produces same output across all nodes; this is critical for consensus; (3) Sandboxed — smart contracts can't access the file system, network, or external APIs without oracles; (4) Gas metered — every opcode costs a defined amount of gas (e.g., ADD = 3 gas, SLOAD = 100-2100 gas); (5) Memory model — three data areas: stack (function execution), memory (temporary byte array, reset each call), storage (persistent key-value store on the blockchain); (6) EVM compatibility — many blockchains (Polygon, BSC, Arbitrum, Optimism, Avalanche C-Chain) implement the EVM, allowing Ethereum smart contracts to deploy with minimal changes. Solidity code → Solidity compiler → EVM bytecode → deployed on chain → EVM on each node executes it.
02
What is a Solidity contract structure?
A Solidity contract is similar to a class in OOP. Basic structure: // SPDX-License-Identifier: MIT\npragma solidity ^0.8.0;\ncontract MyToken {\n // State variables (stored in storage)\n string public name;\n uint256 public totalSupply;\n mapping(address => uint256) public balances;\n \n // Events\n event Transfer(address indexed from, address indexed to, uint256 amount);\n \n // Constructor (runs once at deployment)\n constructor(string memory _name, uint256 _supply) {\n name = _name;\n totalSupply = _supply;\n balances[msg.sender] = _supply;\n }\n \n // Functions\n function transfer(address to, uint256 amount) external returns (bool) {\n require(balances[msg.sender] >= amount, "Insufficient balance");\n balances[msg.sender] -= amount;\n balances[to] += amount;\n emit Transfer(msg.sender, to, amount);\n return true;\n }\n}. Key elements: SPDX license identifier (good practice), pragma version, state variables, events (for logging), constructor (deployment init), and functions (with visibility: public/private/internal/external).
03
What are the data types in Solidity?
Solidity data types: Value types (copied on assignment): (1) Integers — uint/int with sizes 8-256 bits in 8-bit steps (e.g., uint256, int128). uint = unsigned (0 to 2^N-1); int = signed; (2) Boolean — bool (true/false); (3) Address — address (20 bytes, Ethereum address); address payable (can receive ETH); (4) Bytes — fixed-size byte arrays: bytes1...bytes32; (5) Enums — user-defined enumeration types. Reference types (stored by reference, must specify data location): (6) Arrays — uint[] memory dynamic or uint[10] storage fixed; (7) Structs — custom data structure grouping multiple variables; (8) Mappings — hash tables: mapping(address => uint256) public balances (only in storage). Special types: (9) String — dynamic UTF-8 string (reference type); (10) Bytes (dynamic) — bytes for arbitrary byte arrays. Post-0.8.0, integer overflow/underflow is checked by default (reverts instead of wrapping).
04
What is the difference between `memory` and `storage` in Solidity?
Data location in Solidity determines where data is stored and its persistence: (1) Storage — persistent, on-blockchain storage. State variables are always in storage. Reading from storage costs gas (SLOAD: 100-2100 gas depending on cold/warm access); writing is expensive (SSTORE: 20,000 gas for new slot, 5,000 for update). Data persists between function calls and transactions; (2) Memory — temporary, in-memory storage during function execution only. Cleared after function returns. Much cheaper than storage for complex operations (arrays, structs). Required keyword when declaring reference types (arrays, structs, strings) in function parameters and local variables; (3) Calldata — special read-only data location for function arguments in external functions. Cheaper than memory for large data because it doesn't copy data. Example: function processArray(uint[] calldata data) external pure returns (uint) { ... }; (4) Stack — the EVM execution stack; Solidity manages this automatically for simple value types in local variables. Use the least expensive location for your use case: calldata > memory > storage in terms of gas efficiency.
05
What are Solidity modifiers?
Modifiers in Solidity are reusable code patterns that change the behavior of functions — typically for access control and validation. They use the _; placeholder to indicate where the function body executes. Example: modifier onlyOwner() { require(msg.sender == owner, "Not owner"); _; } modifier nonReentrant() { require(!locked, "Reentrant call"); locked = true; _; locked = false; } function withdraw() external onlyOwner nonReentrant { payable(msg.sender).transfer(address(this).balance); }. Common modifier patterns: (1) Access control — onlyOwner, onlyAdmin, onlyRole(bytes32 role); (2) State checks — whenNotPaused, onlyWhenActive; (3) Reentrancy guard — nonReentrant prevents reentrancy attacks; (4) Input validation — check parameters before function body. Modifiers are inlined at compile time. Multiple modifiers can be chained: function adminAction() external onlyOwner whenNotPaused { ... }. The OpenZeppelin Contracts library provides battle-tested modifiers via Ownable, AccessControl, Pausable, and ReentrancyGuard.
06
What are Solidity events?
Events in Solidity are logging mechanisms that emit data to the Ethereum transaction receipt (stored in bloom filters on nodes, not in contract storage). They are used to: (1) Log state changes — notify external listeners when something important happens; (2) Enable efficient filtering — indexed event parameters enable clients to filter events by value; (3) Cheap logging — storing data via events is ~8x cheaper than storing in contract storage. Defining and emitting: event Transfer(address indexed from, address indexed to, uint256 amount); emit Transfer(msg.sender, to, amount). Indexed parameters (max 3 per event) are stored in bloom filters for efficient querying by topic. Non-indexed data is ABI-encoded in the data field. Frontend listening (ethers.js): contract.on("Transfer", (from, to, amount) => { console.log(from, to, amount.toString()) }). Historical event querying: contract.queryFilter(contract.filters.Transfer(), fromBlock, toBlock). The Graph protocol indexes events for efficient historical queries without running archive nodes.
07
What is the ERC-20 token standard?
ERC-20 (Ethereum Request for Comment 20) is the standard interface for fungible tokens on Ethereum. All ERC-20 tokens implement a common interface that wallets, exchanges, and DeFi protocols can interact with uniformly. Required functions: totalSupply() — total token supply; balanceOf(address) — token balance of an address; transfer(address to, uint256 amount) — send tokens; transferFrom(address from, address to, uint256 amount) — transfer on behalf of another (requires approval); approve(address spender, uint256 amount) — authorize a contract to spend tokens; allowance(address owner, address spender) — check approved amount. Required events: Transfer(indexed from, indexed to, value), Approval(indexed owner, indexed spender, value). Examples: USDC, DAI, LINK, UNI. ERC-20 is the foundation of DeFi — DEXes, lending protocols, and yield farms all rely on the ERC-20 standard. Use OpenZeppelin's ERC20 implementation as a base contract rather than implementing from scratch: contract MyToken is ERC20 { constructor() ERC20("My Token", "MTK") { _mint(msg.sender, 1000000 * 10**decimals()); } }.
08
What is the ERC-721 token standard?
ERC-721 is the Ethereum standard for Non-Fungible Tokens (NFTs) — each token has a unique ID and is not interchangeable with others. Proposed by William Entriken and others in 2018. Key differences from ERC-20: each token has a unique tokenId; ownership maps tokenId → ownerAddress rather than address → balance. Required interface: balanceOf(address owner) — number of NFTs owned; ownerOf(uint256 tokenId) — owner of specific NFT; safeTransferFrom(address from, address to, uint256 tokenId) — transfer with safety check; approve(address to, uint256 tokenId) — approve transfer of specific token; setApprovalForAll(address operator, bool approved) — approve operator for all tokens; tokenURI(uint256 tokenId) — returns JSON metadata URI (name, description, image). OpenZeppelin's ERC721 contract handles all standard functions. NFT metadata is typically stored off-chain (IPFS, Arweave) and referenced by the tokenURI. OpenSea and other marketplaces read this metadata to display NFT images and attributes.
09
What is Web3.js and what is it used for?
Web3.js is an Ethereum JavaScript library that enables web applications to interact with the Ethereum network. It's the original Web3 library (released 2015). Key capabilities: (1) Connect to Ethereum nodes — via HTTP, WebSocket, or IPC providers (MetaMask, Infura, Alchemy, local node); (2) Query blockchain data — get block data, transaction receipts, account balances; (3) Interact with smart contracts — call view functions and send state-changing transactions; (4) Manage accounts — create accounts, sign transactions; (5) Listen to events — subscribe to contract events and new block headers. Example: const Web3 = require("web3"); const web3 = new Web3("https://mainnet.infura.io/v3/YOUR_KEY"); const balance = await web3.eth.getBalance("0x..."); const contract = new web3.eth.Contract(abi, address); const result = await contract.methods.balanceOf(userAddress).call(). Web3.js has largely been superseded by ethers.js for new projects — ethers.js has a cleaner API, better TypeScript support, and smaller bundle size. Wagmi and viem are modern alternatives for React applications.
10
What is ethers.js?
ethers.js is a modern, complete Ethereum JavaScript library that is the de facto standard for new Web3 development, largely replacing web3.js. Created by Richard Moore in 2016. Advantages over web3.js: (1) Smaller bundle — ~88KB vs web3.js ~1MB+; (2) TypeScript native — full TypeScript types built-in; (3) Cleaner API — provider/signer separation is more intuitive; (4) BigNumber handling — v6 uses native BigInt; (5) Better testing — widely used with Hardhat and Foundry. Key components: Provider — read-only Ethereum connection: const provider = new ethers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/KEY"); Signer — account that can sign transactions: const signer = await provider.getSigner(); Contract — interface to smart contract: const contract = new ethers.Contract(address, abi, signerOrProvider). Call view function: const balance = await contract.balanceOf(address). Send transaction: const tx = await contract.transfer(to, amount); await tx.wait(). Ethers v6 (2023) introduced significant API changes from v5.
11
What is IPFS and how is it used with blockchain?
IPFS (InterPlanetary File System) is a decentralized, peer-to-peer protocol for storing and sharing content-addressed data. Unlike HTTP (location-addressed: URLs point to a server), IPFS uses content addressing: files are identified by their content hash (CID — Content Identifier). Requesting a CID retrieves the file from any node that has it. Use with blockchain: (1) NFT metadata — storing NFT metadata (images, attributes) on IPFS provides decentralization (compared to centralized servers). The NFT's tokenURI stores the IPFS CID: ipfs://QmHash...; (2) DApp frontends — hosting DApp UIs on IPFS for censorship resistance; (3) Document storage — smart contracts store only the IPFS hash of documents (proof of existence); (4) Filecoin — incentivized storage layer on top of IPFS ensuring data is actually stored. Limitations: IPFS doesn't guarantee data persistence — if no node pins the data, it may be garbage collected. Pinning services (Pinata, nft.storage, Infura IPFS) ensure data stays available by pinning it on multiple nodes.
12
What is a DAO (Decentralized Autonomous Organization)?
A DAO (Decentralized Autonomous Organization) is an organization whose governance rules are encoded in smart contracts on a blockchain, with members (token holders) voting on decisions without centralized leadership. Key characteristics: (1) Token-based governance — holding governance tokens (like UNI for Uniswap) grants voting power proportional to holdings; (2) On-chain voting — proposals are submitted and voted on via smart contracts; passed proposals execute automatically; (3) Treasury management — DAOs hold funds in a multi-sig or smart contract treasury; spending requires governance approval; (4) Transparent — all proposals, votes, and treasury transactions are on-chain and auditable. Examples: Uniswap DAO (governs protocol fee switches), MakerDAO (governs DAI stablecoin parameters), Compound, Aave. Challenges: low voter participation (plutocracy if few whales control votes), slow decision-making, vulnerability to governance attacks (flash loan voting), and legal ambiguity. DAO tools: Snapshot (off-chain gasless voting), Tally, Aragon, Governor contracts (OpenZeppelin).
13
What is MetaMask?
MetaMask is the most popular Ethereum wallet and Web3 gateway, available as a browser extension (Chrome, Firefox, Brave) and mobile app. It serves as the bridge between web browsers and the Ethereum blockchain. Key functions: (1) Wallet management — stores private keys securely in the browser, generates Ethereum accounts from a 12-word seed phrase; (2) Transaction signing — pops up a confirmation window when a DApp requests a transaction, showing gas fees and transaction details; (3) Web3 provider injection — injects window.ethereum into web pages, allowing DApps to request accounts and send transactions; (4) Network switching — supports Ethereum mainnet, testnets (Goerli, Sepolia), and custom networks (Polygon, BSC, Arbitrum); (5) Token management — displays ETH and ERC-20 token balances; (6) Hardware wallet support — integrates with Ledger and Trezor. DApp connection: const accounts = await window.ethereum.request({ method: "eth_requestAccounts" }). MetaMask has ~30 million monthly active users. Its dominance means most DApps primarily support MetaMask-compatible wallet interfaces.
14
What is Hardhat and how is it used for smart contract development?
Hardhat is the most popular Ethereum development environment, providing a flexible and extensible toolkit for compiling, testing, deploying, and debugging smart contracts. Key features: (1) Local Ethereum network — Hardhat Network simulates Ethereum locally with instant transaction confirmation, console.log in Solidity (import "hardhat/console.sol"), and stack traces on reverts; (2) TypeScript-first — full TypeScript support for scripts and tests; (3) Testing — uses Mocha/Chai with ethers.js; write JavaScript/TypeScript tests; (4) Compilation — npx hardhat compile compiles Solidity and generates ABI + bytecode; (5) Deployment scripts — scripts/deploy.ts for deterministic deployments; (6) Plugin ecosystem — Hardhat Gas Reporter (gas cost analysis), Solidity Coverage, OpenZeppelin Defender integration; (7) Forking — fork mainnet state for testing against real DeFi protocols: networks: { hardhat: { forking: { url: "https://eth-mainnet.g.alchemy.com/v2/KEY" } } }. Common workflow: npx hardhat test runs the test suite; npx hardhat run scripts/deploy.ts --network sepolia deploys to testnet.
15
What is the difference between mainnet, testnet, and local network?
(1) Mainnet — the live Ethereum network with real ETH and real economic consequences. Transactions have actual value; mistakes are irreversible. Deploy here only after thorough testing. Ethereum Mainnet (chainId: 1); (2) Testnets — public test networks using valueless test ETH (obtained free from faucets). Used for final pre-production testing in a realistic network environment. Current Ethereum testnets: Sepolia (PoS, recommended for application testing) and Goerli (being deprecated). Testnets are slower than local networks but simulate mainnet conditions; (3) Local network — runs entirely on your machine. Tools: Hardhat Network (built into Hardhat), Anvil (Foundry's local node), Ganache (deprecated). Benefits: instant transactions, free ETH (pre-funded accounts), deterministic block mining, stack trace debugging, mainnet forking. Development workflow: local network → testnet → mainnet. Layer 2 testnets also exist: Arbitrum Sepolia, Optimism Sepolia, Polygon Mumbai/Amoy for testing L2-specific behavior.
16
What is Chainlink and why is it important for smart contracts?
Chainlink is the leading decentralized oracle network that provides smart contracts with reliable, tamper-proof data feeds from the real world. Smart contracts can't access off-chain data natively (blockchains are deterministic sandboxes). Chainlink solves this by: (1) Price feeds — decentralized, aggregated price data for 500+ crypto/forex/commodity pairs; used by Aave, Compound, Synthetix for collateral valuation; (2) Verifiable Random Function (VRF) — cryptographically provable randomness for NFT minting, gaming (which NFT is rare), and lottery; (3) Automation (Keepers) — trigger smart contract functions based on time or conditions without manual intervention; (4) Cross-Chain Interoperability Protocol (CCIP) — send data and tokens across blockchains; (5) Any API — call any external API from a smart contract. Why Chainlink matters: without reliable oracles, DeFi collapses — a wrong price feed can trigger incorrect liquidations or be manipulated to drain lending protocols. Chainlink's decentralized oracle network reduces the risk of a single point of failure, making it the critical data infrastructure layer for DeFi.
17
What is the difference between Layer 1 and Layer 2 in blockchain?
Layer 1 (L1) is the base blockchain protocol — the main chain with its own consensus mechanism, validators, and security. Examples: Ethereum, Bitcoin, Solana, Avalanche. L1 provides security and finality but has limited throughput (Ethereum: ~15-30 TPS) and high fees during congestion. Layer 2 (L2) is a secondary framework built on top of an L1 to improve scalability while inheriting the L1's security. L2 types: (1) Optimistic Rollups — bundle transactions and post compressed data to L1, assuming transactions are valid; fraud proofs challenge invalid transactions within a 7-day window. Examples: Arbitrum, Optimism; (2) ZK-Rollups — use zero-knowledge proofs to cryptographically prove batch transaction validity; no fraud proof window needed; faster finality. Examples: zkSync Era, Polygon zkEVM, Starknet, Scroll; (3) State Channels — off-chain channels for specific parties (Lightning Network for Bitcoin); (4) Validiums — ZK proofs with off-chain data availability. L2s achieve 1000-10,000+ TPS with fees 10-100x lower than Ethereum mainnet, making Ethereum practical for mainstream use.
18
What is a transaction hash in Ethereum?
A transaction hash (txHash or txID) is a unique 32-byte (64 hex character) identifier for every transaction on the Ethereum blockchain, derived by hashing the transaction's contents. Example: 0x5c504ed432cb51138bcf09aa5e8a410dd4a1e204ef84bfed1be16dfba1b22060. It serves as: (1) Transaction identifier — uniquely identifies a transaction across the entire blockchain history; (2) Receipt lookup key — used to fetch the transaction receipt (status, gas used, events emitted, block number) from any node; (3) Status tracking — wallets and DApps monitor the txHash to determine when a transaction is mined and confirmed. The txHash is generated before mining — the sender hashes the signed transaction data. After submission, the transaction is pending in the mempool until a validator includes it in a block. Etherscan lookup: https://etherscan.io/tx/0x5c504... shows the full transaction details. In ethers.js: const tx = await contract.transfer(to, amount); console.log(tx.hash); await tx.wait() // waits for confirmation.
Deep expertise questions for senior and lead roles.
01
What are common smart contract vulnerabilities (reentrancy, overflow, etc.)?
Critical smart contract vulnerabilities: (1) Reentrancy — the most famous vulnerability (The DAO hack, $60M, 2016). An external call to an untrusted contract executes before state updates complete, allowing the callee to re-enter the calling function and drain funds. Prevention: Checks-Effects-Interactions pattern (update state before external calls), OpenZeppelin ReentrancyGuard; (2) Integer overflow/underflow — pre-Solidity 0.8.0, arithmetic wrapped silently (2^256 + 1 = 0). Prevention: Solidity 0.8+ has built-in checks; use SafeMath for older versions; (3) Access control issues — missing onlyOwner modifiers or misconfigured roles. Prevention: OpenZeppelin Ownable, AccessControl; (4) Front-running/MEV — miners see pending transactions and insert their own first (sandwich attacks on DEXes). Prevention: slippage protection, commit-reveal schemes; (5) Oracle manipulation — using spot price from a DEX pool as an oracle; flash loans can manipulate this. Prevention: TWAP oracles, Chainlink price feeds; (6) Signature replay — valid signature reused across multiple transactions. Prevention: EIP-712 domain separators, nonces; (7) Denial of Service — function that becomes uncallable (e.g., looping over unbounded array); (8) Delegatecall abuse — proxy patterns using delegatecall can lead to storage collisions. Prevention: EIP-1967 storage slots for proxy patterns.
02
How does the Ethereum PoS consensus mechanism work after The Merge?
After The Merge (September 15, 2022), Ethereum uses Casper FFG + LMD-GHOST consensus (collectively called Gasper). How it works: (1) Validators — must stake 32 ETH to participate. ~1 million validators as of 2024; (2) Epochs and slots — time is divided into slots (12 seconds each) and epochs (32 slots = ~6.4 minutes); (3) Block proposal — each slot, one validator is pseudo-randomly selected to propose a block (RANDAO randomness); (4) Attestation committees — each slot, a committee of ~512 validators attest to (vote on) the head of the chain; (5) Finality (FFG) — Casper FFG provides economic finality: after 2 epochs (~12.8 minutes), a block is finalized. Reversing finality would require slashing 1/3 of all staked ETH (~millions of ETH); (6) Fork choice (LMD-GHOST) — Latest Message Driven Greedy Heaviest Observed SubTree selects the canonical chain head; (7) Slashing — validators that double-vote or sign conflicting blocks have ETH slashed and are forcibly ejected. The Merge reduced Ethereum's energy consumption by ~99.95% while maintaining security through economic incentives instead of compute.
03
What is the difference between optimistic rollups and ZK-rollups?
Both rollup types batch L2 transactions and post compressed data to Ethereum L1 for data availability, but differ in how they prove transaction validity: Optimistic Rollups: (1) Assume all transactions are valid by default ("optimistic"); (2) Post transactions to L1 without validity proofs; (3) Anyone can submit a fraud proof during a challenge window (7 days) to prove a transaction was invalid; (4) Withdrawals take 7 days (challenge period) unless using fast exit liquidity providers; (5) EVM-equivalent (simpler to support arbitrary smart contracts); (6) Examples: Arbitrum One, Optimism, Base. ZK-Rollups (Validity Rollups): (1) Generate cryptographic zero-knowledge proofs (ZK-SNARKs/STARKs) proving all transactions in the batch are valid; (2) L1 verifies the proof mathematically — invalid transactions cannot be included; (3) Withdrawals are fast (~minutes) — no challenge period needed; (4) Higher computational cost for proof generation (specialized hardware); (5) EVM compatibility harder to achieve (zkEVM development is complex); (6) Examples: zkSync Era, Polygon zkEVM, Starknet, Scroll. Long-term, ZK-rollups are likely superior in security and UX but remain more complex to build.
04
What is a flash loan and how is it used in DeFi?
A flash loan is an uncollateralized loan that must be borrowed and repaid within a single blockchain transaction. If the loan isn't repaid with fee by transaction end, the entire transaction reverts — making it atomically safe for the lender. Since the lender faces zero risk, there's no collateral requirement. Flash loans are possible because of smart contract atomicity. Legitimate uses: (1) Arbitrage — borrow 1M USDC, buy ETH on Uniswap, sell on Sushiswap at higher price, repay loan, keep profit — all in one transaction; (2) Collateral swapping — replace one type of collateral for another in a lending position without manual multi-step process; (3) Self-liquidation — repay a loan to retrieve collateral without needing the repayment funds upfront; (4) Protocol testing — security researchers use flash loans to test protocol resilience. Exploitative uses: (1) Oracle manipulation — borrow large amount, manipulate AMM price used as oracle, exploit vulnerable protocol, repay loan (Harvest Finance hack: $34M); (2) Governance attacks — borrow tokens to temporarily acquire voting power. Providers: Aave (0.09% fee), Uniswap V2/V3 (0.3% fee), dYdX (0 fee).
05
How do you optimize gas usage in Solidity?
Gas optimization reduces deployment and transaction costs. Key techniques: (1) Use appropriate variable types — uint256 is most gas-efficient (EVM uses 256-bit words); smaller types like uint8 require additional conversion operations; (2) Storage slot packing — struct members smaller than 32 bytes share a single storage slot if consecutive: struct Packed { uint128 a; uint128 b; } uses 1 slot vs. uint256 a; uint256 b (2 slots); (3) Memory vs. storage — cache storage reads in memory for functions that read the same variable multiple times: uint256 cached = storageVar; return cached + cached * 2; (4) Minimize storage writes — most expensive operation. Use events for data that doesn't need on-chain access; (5) Short-circuit evaluation — put cheaper conditions first in require statements; (6) Use custom errors over strings — error Unauthorized() + revert Unauthorized() is cheaper than require(false, "Unauthorized"); (7) Avoid loops over dynamic arrays — unbounded loops can hit block gas limit; (8) Use mappings over arrays for lookups — O(1) vs. O(n); (9) immutable and constant — mark variables that never change to avoid storage access; (10) Optimizer settings — enable Solidity optimizer with high runs value (200 for deployment cost optimization, 1000+ for call cost).
06
What is the Proxy pattern in Solidity for upgradeable contracts?
Smart contracts are immutable by default — once deployed, their code cannot change. The Proxy pattern enables upgradeable contracts through two-contract architecture: (1) Proxy contract — holds the state (storage) and ETH. Users interact with this address. All calls are forwarded to the implementation using delegatecall — execution happens in the proxy's storage context; (2) Implementation contract (logic) — contains the actual business logic. Can be replaced (upgraded) by pointing the proxy to a new implementation address. delegatecall runs the implementation's code but reads/writes the proxy's storage. Storage layout must be compatible across upgrades — adding variables is safe; changing order or removing variables causes collisions. Proxy patterns: (1) Transparent Proxy (EIP-1967) — admin calls are handled by proxy; user calls are delegated. OpenZeppelin's TransparentUpgradeableProxy; (2) UUPS (EIP-1822) — upgrade logic is in the implementation contract itself, reducing proxy complexity and gas; (3) Diamond/EIP-2535 — proxy that delegates to multiple implementation "facets" based on function selector; enables unlimited contract size. Security concern: upgradeable contracts reintroduce centralized trust — the upgrade key holder can change the logic arbitrarily. Time-locks and multi-sigs on upgrade keys mitigate this.
07
What is MEV (Miner Extractable Value)?
MEV (Maximal Extractable Value, previously Miner Extractable Value) is the profit that block proposers (validators post-Merge) can extract by reordering, inserting, or censoring transactions within the blocks they produce. MEV exists because proposers have complete control over transaction ordering within their block. MEV strategies: (1) Arbitrage — inserting a transaction between two transactions that create a price discrepancy across DEXes; (2) Sandwich attacks — detecting a large swap in the mempool, front-running it (buying the asset first), then back-running it (selling after the price moved). Harmful to retail users; (3) Liquidations — racing to liquidate undercollateralized positions first to earn liquidation bonuses; (4) JIT (Just-In-Time) liquidity — adding liquidity just before a large trade and removing immediately after to capture fees. MEV ecosystem: MEV-Boost (Ethereum) separates the role of block building from proposing — specialized "searchers" find MEV opportunities, "builders" aggregate them into profitable blocks, "proposers" pick the highest bid. Flashbots created this ecosystem to make MEV more transparent and fair. MEV totals hundreds of millions of dollars annually on Ethereum.
08
How does the ERC-1155 token standard differ from ERC-20 and ERC-721?
ERC-1155 is a multi-token standard that can represent both fungible and non-fungible tokens within a single smart contract — addressing limitations of having separate ERC-20 and ERC-721 contracts. Key differences: (1) Multiple token types in one contract — ERC-20 represents one fungible token type; ERC-721 represents one NFT collection; ERC-1155 represents unlimited token types via id; (2) Semi-fungible tokens — a token ID can have multiple copies (e.g., 10,000 copies of "Sword #5" in a game) — not fully unique (like NFTs) but not infinitely fungible (like ERC-20); (3) Batch transfers — safeBatchTransferFrom(from, to, [id1, id2], [amount1, amount2], data) transfers multiple token types in one transaction, saving gas; (4) Single approval — setApprovalForAll grants approval for all token types; (5) Gas efficiency — deploying one ERC-1155 contract is cheaper than deploying multiple ERC-20/ERC-721 contracts; batch minting is cheaper. Use cases: game items (sword, shield, potion — each with different fungibility), marketplace contracts holding diverse assets, music albums (album as NFT, individual tracks as fungible ERC-1155). OpenSea and most NFT platforms support ERC-1155.
09
What is the Account Abstraction (ERC-4337) proposal?
Account Abstraction (ERC-4337) transforms Ethereum's user accounts from simple key-controlled Externally Owned Accounts (EOAs) into programmable smart contract wallets, unlocking radically improved UX without L1 protocol changes. Problems with EOAs: you must have ETH to pay gas (friction for new users), losing a private key means losing all funds (no recovery), every dApp requires a signature (poor UX). ERC-4337 introduces: (1) UserOperation — a pseudo-transaction object representing a user's intent, signed by any signing scheme the wallet supports; (2) Bundler — nodes that collect UserOperations and include them in real transactions; (3) EntryPoint contract — the global singleton that processes UserOperations; (4) Paymaster — sponsors gas fees for users; enables gasless transactions (sponsored by dApps) or paying gas in ERC-20 tokens. Benefits: (1) Social recovery — recover wallet via trusted guardians if private key is lost; (2) Multi-sig — require multiple signatures for high-value transactions; (3) Batch transactions — approve + swap in one user action; (4) Gasless UX — dApps pay gas; (5) Session keys — temporary keys for games. ERC-4337 is deployed on mainnet and all major L2s; wallets: Alchemy's Light Account, Biconomy, Safe (ex-Gnosis Safe).
10
How do you audit a smart contract for security vulnerabilities?
Smart contract auditing is a systematic process to identify security vulnerabilities before deployment: (1) Automated static analysis — run automated tools first: Slither (most popular, free, Python-based, detects 80+ vulnerability patterns), Mythril (symbolic execution), Echidna (property-based fuzzing), Foundry's fuzz testing; (2) Manual review — the critical, irreplaceable component. Auditors manually trace every code path, review business logic, check access control, examine all external calls; (3) Vulnerability checklist — systematically check: reentrancy, access control, integer arithmetic, oracle manipulation, flash loan attack surfaces, front-running, signature replay, denial of service, storage collisions in proxies; (4) Test coverage — ensure comprehensive unit tests and integration tests; identify and test edge cases; (5) Economic model review — analyze tokenomics and game theory for exploitable incentives; (6) Invariant testing — define properties that must always be true (e.g., "total balances == totalSupply") and run Echidna/Foundry fuzzer to find violations; (7) Formal verification — use Certora Prover or K Framework for mathematical proof of properties; (8) Multiple auditors — different auditing firms catch different issues; (9) Bug bounty — post-audit, launch a bug bounty (Immunefi) for additional community review. Leading audit firms: Trail of Bits, OpenZeppelin, Consensys Diligence, Spearbit, Code4rena (competitive audits).