Toolmingo
Guides23 min read

50 Blockchain Interview Questions (With Answers)

Top blockchain and Web3 interview questions with clear answers and code examples — covering blockchain fundamentals, Ethereum, Solidity, smart contracts, DeFi, security, and Layer 2 scaling.

Blockchain interviews test understanding of distributed ledgers, consensus mechanisms, smart contracts, Solidity, DeFi protocols, and Web3 tooling. This guide covers the 50 most common questions — with concise answers and code examples.

Quick reference

Topic Most asked questions
Blockchain basics Immutability, blocks, hashing, Merkle trees
Consensus PoW vs PoS, BFT, finality
Cryptography Public/private keys, digital signatures, hash functions
Ethereum EVM, gas, accounts, transactions, ABI
Solidity Data types, mappings, events, modifiers, inheritance
Tokens & DeFi ERC-20, ERC-721, AMM, liquidity pools
Web3 tooling Hardhat, ethers.js, IPFS, Chainlink
Security Reentrancy, flash loans, front-running
Layer 2 Rollups, state channels, sidechains

Blockchain Basics

1. What is a blockchain?

A blockchain is a distributed, append-only ledger shared across a peer-to-peer network. Data is grouped into blocks linked together via cryptographic hashes — making history tamper-evident.

Property Meaning
Distributed No single authority; copies on many nodes
Immutable Changing one block invalidates all later blocks
Transparent All transactions visible (on public chains)
Consensus-driven Nodes agree on valid state without central trust
Append-only Records added, never deleted

2. What is the structure of a block?

Block Header:
  - Previous block hash   ← links to parent
  - Merkle root           ← hash of all transactions
  - Timestamp
  - Nonce (PoW chains)
  - Difficulty target

Block Body:
  - List of transactions

The chain is formed because each block stores the hash of its parent. Changing any block changes its hash, breaking all subsequent links.


3. What is a Merkle tree and why does it matter?

A Merkle tree is a binary tree of hashes. Leaf nodes are transaction hashes; each parent node is the hash of its two children, up to the Merkle root stored in the block header.

         Root Hash
        /         \
   Hash(AB)     Hash(CD)
   /    \       /    \
Hash(A) Hash(B) Hash(C) Hash(D)
  A       B       C       D

Benefits:

  • Verify one transaction in O(log n) without downloading the full block — used by SPV (light) clients
  • Tamper-evidence: changing transaction A changes Root Hash

4. What is the difference between public, private, and consortium blockchains?

Type Permissioned? Validators Examples Use case
Public No Anyone Bitcoin, Ethereum Trustless, censorship-resistant
Private Yes One org Hyperledger Fabric Internal corporate ledger
Consortium Yes Invited group R3 Corda, Quorum Inter-bank, supply chain

Public chains maximise decentralisation; private chains trade it for performance and privacy.


5. What problem does blockchain solve — and when should you NOT use it?

Problem solved: Establishing trust between parties who don't know each other, without a central intermediary (bank, government, platform).

Use blockchain when:

  • Multiple parties need to share data without trusting each other
  • Immutable audit trail is required
  • Disintermediation has real business value

Do NOT use blockchain when:

  • A single company controls all data (use a regular database)
  • You need to update/delete records easily
  • High throughput is required (most chains: <100 TPS vs Postgres: 10k+ TPS)
  • There's no trust problem to solve

Consensus Mechanisms

6. How does Proof of Work (PoW) work?

Miners compete to find a nonce that, when combined with the block data, produces a hash below a target threshold.

SHA256(block_header + nonce) < target_difficulty
  • First miner to find a valid nonce broadcasts the block
  • Others verify (fast) and build on top of it
  • Energy intensive — difficulty adjusts to target ~10 min per block (Bitcoin)

7. How does Proof of Stake (PoS) work?

Validators lock up (stake) cryptocurrency as collateral. The protocol selects a validator to propose the next block (weighted by stake). Others attest to it.

Attribute PoW PoS
Resource Compute (energy) Capital (stake)
Attack cost 51% of hashrate 51% of staked tokens
Energy usage Very high ~99% lower
Slashing N/A Misbehaviour burns stake
Finality Probabilistic Can be deterministic
Examples Bitcoin Ethereum (post-Merge), Solana, Cardano

8. What is Byzantine Fault Tolerance (BFT)?

A system is Byzantine fault tolerant if it reaches consensus even when some nodes act arbitrarily maliciously (not just crashing). Named after the Byzantine Generals Problem.

  • Classical BFT (PBFT): tolerates up to ⌊(n−1)/3⌋ faulty nodes, requires O(n²) messages — scales to ~100 validators
  • Tendermint / HotStuff: BFT with better performance used in Cosmos, Binance Chain
  • Ethereum's Casper FFG: BFT-inspired; finalises checkpoints after 2/3 of validators attest

9. What is finality in blockchain?

Finality is the guarantee that a confirmed transaction can never be reversed.

Type Description Example
Probabilistic More confirmations → harder to reverse Bitcoin (6 blocks ≈ final)
Absolute/deterministic Once finalised, provably irreversible Tendermint chains
Economic Reverting is prohibitively expensive Ethereum post-Merge

Ethereum's single-slot finality goal aims to finalise blocks in one ~12 s slot.


10. What is the difference between on-chain and off-chain data?

On-chain Off-chain
Storage Blockchain state External database / IPFS
Cost Expensive (gas) Cheap
Transparency Public Configurable
Immutability Yes No
Use case Token balances, contract state Large files, metadata, NFT images

Best practice: store hashes on-chain that prove off-chain data integrity (e.g., IPFS CID stored in NFT contract).


Cryptography

11. How does public/private key cryptography work in blockchains?

Every account is a key pair generated with Elliptic Curve Cryptography (secp256k1) on Ethereum/Bitcoin.

Private key: 256-bit random number (keep secret)
Public key:  derived via EC multiplication
Address:     last 20 bytes of keccak256(public_key)
  • Signing: signature = sign(private_key, hash(message))
  • Verification: pubkey = recover(signature, hash(message))
  • You can verify a signature without knowing the private key

12. What hash functions are used in blockchains?

Chain Hash function Output Used for
Bitcoin SHA-256 256-bit PoW, block headers, TXID
Ethereum Keccak-256 256-bit Account addresses, storage slots, events
Ethereum SHA3-256 (EIP-4844) 256-bit Blob commitments
ZK proofs Poseidon, Pedersen varies ZK-friendly, circuit-efficient

Note: Ethereum uses Keccak-256, which is different from the NIST-standardised SHA-3.


13. What is a digital signature and why does Ethereum need it?

A digital signature proves:

  1. The message was created by the holder of a specific private key
  2. The message has not been altered

Every Ethereum transaction is signed with the sender's private key. Miners/validators verify the signature to confirm the sender authorised the spend — replacing the need for passwords or central identity.


Ethereum

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

The EVM is a sandboxed, deterministic stack-based virtual machine that executes smart contract bytecode. Every full node runs the same EVM, producing identical state transitions.

Feature Detail
Word size 256-bit
Storage model Key-value store per contract
Memory Temporary, byte-addressable
Stack Max 1024 items
Execution Gas-metered to prevent infinite loops
Bytecode Compiled from Solidity / Vyper / Yul

15. What is gas? How is gas price determined?

Gas is the unit measuring computational work. Each EVM opcode has a fixed gas cost (e.g., ADD = 3, SSTORE = 20,000). Users pay:

Transaction fee = gas_used × gas_price (in Gwei)

EIP-1559 (post-London) model:

  • base_fee: protocol-set, burned each block, adjusts ±12.5% per block based on demand
  • max_fee: user's cap
  • priority_fee (tip): goes to the validator
effective_gas_price = min(max_fee, base_fee + priority_fee)

16. What is the difference between an EOA and a contract account?

Externally Owned Account (EOA) Contract Account
Controlled by Private key Contract code
Can initiate tx Yes No (only react)
Has code No Yes
Has nonce Yes (replay protection) Yes (# of contracts created)
ETH balance Yes Yes
Examples MetaMask wallet Uniswap, USDC

17. What happens when you send an Ethereum transaction?

  1. User signs transaction: {to, value, data, nonce, gasLimit, maxFeePerGas, maxPriorityFeePerGas}
  2. Broadcast to mempool (P2P network)
  3. Validator includes it in a block
  4. EVM executes: if to is a contract, executes data as a function call
  5. State changes committed; fee paid to validator
  6. Receipt emitted with logs (events)

18. What is an ABI and why is it needed?

The Application Binary Interface (ABI) is a JSON descriptor of a smart contract's public functions and events — their names, parameter types, and return types.

[
  {
    "type": "function",
    "name": "transfer",
    "inputs": [
      {"name": "to", "type": "address"},
      {"name": "amount", "type": "uint256"}
    ],
    "outputs": [{"name": "", "type": "bool"}]
  }
]

Frontend tools (ethers.js, web3.js) use the ABI to encode calldata and decode return values.


Solidity

19. What are the main Solidity data types?

Category Types
Value bool, uint8uint256, int8int256, address, bytes1bytes32
Reference string, bytes, arrays (uint[], uint[5]), struct, mapping
Special address payable (can .transfer(), .send()), enum
uint256 public totalSupply;          // 0 to 2^256-1
address public owner;                // 20-byte Ethereum address
mapping(address => uint256) balances; // hash map
bytes32 public root;                 // fixed 32-byte hash

20. What is the difference between storage, memory, and calldata?

Location Persistence Cost Used for
storage Permanent (on-chain) Expensive State variables
memory Temporary (during call) Cheap Local variables, function args
calldata Read-only, temporary Cheapest External function parameters
// gas-efficient: use calldata for read-only array parameters
function sum(uint256[] calldata nums) external pure returns (uint256) {
    uint256 total;
    for (uint i = 0; i < nums.length; i++) total += nums[i];
    return total;
}

21. How do mappings work in Solidity?

A mapping is a hash map where every key has a default zero value. Keys are not enumerable.

mapping(address => uint256) public balances;
mapping(address => mapping(address => uint256)) public allowances; // nested

function deposit() external payable {
    balances[msg.sender] += msg.value;
}

Limitations:

  • Cannot iterate over keys
  • No .length
  • Cannot return entire mapping from a function
  • Default value for missing keys is zero (never reverts)

22. What are Solidity events and why are they used?

Events emit logs stored in transaction receipts — cheap compared to storage (375 gas vs 20,000+). Front-ends and indexers (The Graph) listen for them.

event Transfer(address indexed from, address indexed to, uint256 value);

function transfer(address to, uint256 amount) external {
    balances[msg.sender] -= amount;
    balances[to] += amount;
    emit Transfer(msg.sender, to, amount);  // indexed params are searchable
}

indexed parameters are stored as topics and can be filtered efficiently. Max 3 indexed per event.


23. What are function modifiers?

Modifiers are reusable guard conditions that wrap function execution with _; indicating where the function body runs.

modifier onlyOwner() {
    require(msg.sender == owner, "Not owner");
    _;
}

modifier nonReentrant() {
    require(!locked, "Reentrant call");
    locked = true;
    _;
    locked = false;
}

function withdraw(uint256 amount) external onlyOwner nonReentrant {
    payable(msg.sender).transfer(amount);
}

Common modifiers: onlyOwner, whenNotPaused, nonReentrant, onlyRole.


24. What is the difference between require, revert, and assert?

require revert assert
Purpose Validate inputs/conditions Custom errors, complex conditions Invariants (should never fail)
Gas refund Yes (remaining gas) Yes No (pre-0.8: consumes all gas)
Error type Error(string) Custom error or Error(string) Panic(uint256)
// preferred pattern in Solidity 0.8+
error InsufficientBalance(uint256 available, uint256 required);

function withdraw(uint256 amount) external {
    if (balances[msg.sender] < amount)
        revert InsufficientBalance(balances[msg.sender], amount);
    balances[msg.sender] -= amount;
    payable(msg.sender).transfer(amount);
}

Custom errors (EIP-838) save gas compared to string error messages.


25. What is contract inheritance in Solidity?

Solidity supports multiple inheritance using C3 linearisation. Contracts can inherit state variables, functions, and modifiers.

import "@openzeppelin/contracts/access/Ownable.sol";
import "@openzeppelin/contracts/security/Pausable.sol";

contract MyToken is ERC20, Ownable, Pausable {
    constructor() ERC20("MyToken", "MTK") {
        _mint(msg.sender, 1_000_000e18);
    }

    // override to add pause check
    function _beforeTokenTransfer(address from, address to, uint256 amount)
        internal override whenNotPaused
    {
        super._beforeTokenTransfer(from, to, amount);
    }
}

OpenZeppelin Contracts provides audited base contracts for ERC-20, ERC-721, access control, upgradeable patterns, etc.


26. What is msg.sender vs tx.origin?

msg.sender tx.origin
Value Immediate caller Original EOA that initiated the transaction
Contract-safe Yes No — can be manipulated via phishing
Use case Access control Deprecated; avoid for auth
// VULNERABLE: a malicious contract can call this as tx.origin == victim
function withdraw() external {
    require(tx.origin == owner, "Not owner"); // BAD

// SAFE:
    require(msg.sender == owner, "Not owner"); // GOOD
}

Never use tx.origin for authentication.


Tokens & Standards

27. What is ERC-20?

ERC-20 is the standard interface for fungible tokens on Ethereum. All tokens are interchangeable.

interface IERC20 {
    function totalSupply() external view returns (uint256);
    function balanceOf(address account) external view returns (uint256);
    function transfer(address to, uint256 amount) external returns (bool);
    function allowance(address owner, address spender) external view returns (uint256);
    function approve(address spender, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);

    event Transfer(address indexed from, address indexed to, uint256 value);
    event Approval(address indexed owner, address indexed spender, uint256 value);
}

28. What is the difference between ERC-20, ERC-721, and ERC-1155?

Standard Token type Fungible? Use case
ERC-20 Single token type Yes (interchangeable) DAI, USDC, LINK
ERC-721 Each token unique No (NFT) CryptoPunks, BAYC, ENS names
ERC-1155 Multi-token (fungible + NFT in one contract) Both Game items, packs

ERC-1155 (by Enjin) is more gas-efficient for batch transfers and mixed collections.


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

An AMM replaces the order book with a liquidity pool and a mathematical formula.

Uniswap v2 uses the constant product formula:

x * y = k

Where x and y are token reserves. Buying token X drains the X reserve, increasing its price.

Concept Meaning
Liquidity pool Smart contract holding a pair of tokens (e.g., ETH/USDC)
LP token Represents your share of the pool
Swap fee 0.3% on Uniswap v2 — distributed to LPs
Slippage Price impact of your trade vs quoted price
Impermanent loss Value loss vs holding, when token price ratio changes

30. What is a DAO?

A Decentralised Autonomous Organisation is an organisation governed by smart contracts and token-holder votes rather than traditional management.

Proposal → Vote → Time-lock → Execute on-chain
  • Governance token holders vote proportional to their holdings
  • Passed proposals execute automatically (no human required)
  • Examples: Compound, Uniswap, MakerDAO, Aave, Nouns DAO
  • Tools: OpenZeppelin Governor, Tally, Snapshot (off-chain signalling)

Web3 Development

31. What is Hardhat and why is it preferred over Truffle?

Hardhat is the dominant Ethereum development environment for compiling, testing, and deploying smart contracts.

Feature Hardhat Truffle
Plugin ecosystem Rich (ethers, waffle, gas-reporter) Smaller
Network forking Built-in (mainnet fork) Via ganache
TypeScript First-class Limited
Speed Faster Slower
Maintenance Active Discontinued (2023)
Debugger Hardhat console.log Separate UI

32. What is the difference between ethers.js and web3.js?

ethers.js web3.js
API design Clean, Promise-based, immutable objects Older, callback+promise mix
Bundle size Smaller (~84 kB) Larger (~1 MB)
TypeScript Excellent Good
Signer model Separate Provider/Signer Mixed
Community trend Growing (preferred) Declining
Version v6 (2023) v4 (2023)

Most new projects use ethers.js v6 or viem (type-safe alternative).


33. How do you interact with a smart contract from a front-end?

import { ethers } from "ethers";

// 1. Connect to wallet
const provider = new ethers.BrowserProvider(window.ethereum);
const signer = await provider.getSigner();

// 2. Create contract instance with ABI
const contract = new ethers.Contract(CONTRACT_ADDRESS, ABI, signer);

// 3. Read (no gas)
const balance = await contract.balanceOf(await signer.getAddress());

// 4. Write (costs gas, user signs)
const tx = await contract.transfer(toAddress, ethers.parseEther("1.0"));
await tx.wait(); // wait for confirmation

// 5. Listen for events
contract.on("Transfer", (from, to, value) => {
    console.log(`Transfer: ${from} → ${to}: ${ethers.formatEther(value)} ETH`);
});

34. What is IPFS and how is it used in Web3?

IPFS (InterPlanetary File System) is a peer-to-peer file storage protocol using content addressing — files are identified by their cryptographic hash (CID), not a URL.

CID: QmYwAPJzv5CZsnA625s3Xf2nemtYgPpHdWEz79ojWnPbdG
URL: https://ipfs.io/ipfs/QmYwAP...

NFT pattern:

// tokenURI on-chain stores IPFS CID
{
  "name": "CryptoPunk #1",
  "image": "ipfs://QmXxx.../1.png",
  "attributes": [...]
}

Pinning services (Pinata, NFT.Storage, web3.storage) ensure files stay available.


35. What is Chainlink and what problem does it solve?

Smart contracts cannot fetch external data natively — they're deterministic and isolated. Chainlink provides decentralised oracles that securely feed off-chain data on-chain.

Use case Chainlink product
Price feeds Data Feeds (ETH/USD, BTC/USD)
Random numbers VRF (Verifiable Random Function)
Any API Any API (external adapter)
Cross-chain CCIP
Automation Automation (Keepers)
import "@chainlink/contracts/src/v0.8/interfaces/AggregatorV3Interface.sol";

AggregatorV3Interface priceFeed = AggregatorV3Interface(0x5f4eC3...);
(, int256 price,,,) = priceFeed.latestRoundData();
// price in 8 decimals: 200000000000 = $2000.00

Security

36. What is a reentrancy attack?

A reentrancy attack occurs when a contract calls an external contract, which calls back into the original contract before the first execution finishes — typically to drain funds.

Vulnerable contract:

// BAD: state update AFTER external call
function withdraw(uint256 amount) external {
    require(balances[msg.sender] >= amount);
    (bool success,) = msg.sender.call{value: amount}(""); // <-- attacker re-enters here
    require(success);
    balances[msg.sender] -= amount;  // never reached for attacker
}

Fixed — Checks-Effects-Interactions pattern:

// GOOD: update state BEFORE external call
function withdraw(uint256 amount) external nonReentrant {
    require(balances[msg.sender] >= amount);
    balances[msg.sender] -= amount;  // effect first
    (bool success,) = msg.sender.call{value: amount}(""); // interaction last
    require(success);
}

The DAO hack (2016) exploited reentrancy, draining 3.6M ETH.


37. What is a flash loan attack?

A flash loan allows borrowing any amount of tokens without collateral, provided the borrowed amount + fee is returned in the same transaction.

Attackers use flash loans to:

  • Manipulate AMM prices (price oracle manipulation)
  • Exploit governance with temporary voting power
  • Extract value from protocol logic flaws

Defence:

  • Use time-weighted average price (TWAP) oracles instead of spot prices
  • Add cooldown periods for governance actions
  • Use Chainlink price feeds instead of on-chain AMM prices

38. What is front-running in blockchain?

Front-running occurs when a validator or MEV (Maximal Extractable Value) bot sees a profitable pending transaction in the mempool and inserts their own transaction before it by paying a higher gas tip.

Type Description
Front-run Insert order before a large trade
Sandwich attack Front-run + back-run a DEX trade
Back-run Execute after a known event (e.g., liquidation)
JIT liquidity Add/remove LP in same block as swap

Defences: commit-reveal schemes, private mempools (Flashbots Protect), slippage limits.


39. What is integer overflow/underflow and how does Solidity 0.8 handle it?

In Solidity < 0.8, arithmetic silently wrapped:

uint8 x = 255;
x + 1 == 0; // overflow!

Solidity 0.8+ reverts on overflow/underflow by default.

For intentional wrapping (e.g., in loops), use unchecked {}:

unchecked {
    i++;  // saves ~200 gas per iteration
}

For Solidity < 0.8, use SafeMath (OpenZeppelin) or upgrade.


40. What are the most common smart contract vulnerabilities?

Vulnerability Description Fix
Reentrancy Re-enter before state update CEI pattern + nonReentrant
Integer overflow Arithmetic wraps silently Solidity 0.8+ or SafeMath
Access control Missing onlyOwner / role check OpenZeppelin AccessControl
tx.origin auth Phishing via proxy contract Use msg.sender
Unchecked return values transfer() failure ignored Check return values
Oracle manipulation Spot price used as truth TWAP, Chainlink feeds
Signature replay Same sig valid multiple times Include nonce + chainId
Delegatecall injection Proxy corrupts storage layout OpenZeppelin Upgradeable
Selfdestruct forceful ETH ETH forced into contract Don't use balance as invariant
Block timestamp block.timestamp can be manipulated ±15s Avoid for precise timing

Layer 2 Scaling

41. Why does Ethereum need Layer 2?

Ethereum mainnet (L1) processes ~15 TPS at high gas costs during demand spikes. Layer 2 (L2) solutions execute transactions off-chain and settle proofs on Ethereum, inheriting its security while reducing costs 10–100×.


42. What is the difference between Optimistic and ZK Rollups?

Optimistic Rollups ZK Rollups
Validity proof Fraud proof (assume valid, challenge if wrong) Validity proof (cryptographically proven)
Withdrawal delay ~7 days (challenge period) Minutes to hours
Computation cost Lower (no proof generation) Higher (ZK proof generation)
EVM compatibility Full EVM (Optimism, Arbitrum) Improving (zkEVM: Polygon, zkSync, Scroll)
Security Requires at least 1 honest verifier Mathematically trustless
Maturity Production-ready Production-ready (2023+)

43. What are state channels?

State channels allow two parties to transact off-chain by exchanging signed messages, only settling the final state on-chain.

Open channel (on-chain deposit) →
  Off-chain: thousands of signed messages →
Close channel (on-chain settlement of final state)
  • Bitcoin Lightning Network is the largest state channel network
  • Best for: two-party micro-payments (streaming payments, gaming)
  • Limitation: both parties must be online; funds locked during channel life

44. What is the difference between a rollup, sidechain, and validium?

Security source Data availability Example
Rollup Ethereum L1 (proof posted) On L1 Arbitrum, Optimism, zkSync
Sidechain Own validators Own chain Polygon PoS, Ronin
Validium ZK proof on L1 Off-chain (DAC) StarkEx, ImmutableX
Plasma L1 exit mechanism Off-chain Largely deprecated

Sidechains trade Ethereum's security guarantees for higher throughput. Rollups keep L1 security.


General & Advanced

45. What is the difference between Bitcoin and Ethereum?

Bitcoin Ethereum
Purpose Digital money / store of value Programmable blockchain
Smart contracts Limited (Script) Turing-complete (Solidity/Vyper)
Consensus PoW (SHA-256) PoS (Gasper)
Block time ~10 min ~12 seconds
Supply 21M cap No hard cap (issuance > burn in some periods)
Native asset BTC ETH
DeFi/NFT Minimal Dominant ecosystem
Scripting Stack-based, limited EVM bytecode

46. What is EIP-1559 and how does it change fees?

Before EIP-1559, users bid gas_price in a first-price auction. Fees were volatile and hard to estimate.

EIP-1559 introduced:

  • Base fee: algorithmically set, burned (reduces ETH supply)
  • Priority fee (tip): reward to validator
  • Max fee: user's cap on total gas price

Effect: More predictable fees; ETH becomes deflationary when base_fee burn > new issuance.


47. What are proxy contracts and why are they used?

Smart contracts are immutable by default. Proxy patterns allow upgradeable contracts.

User → Proxy contract (stable address, no logic)
                ↓ delegatecall
         Implementation contract (upgradeable logic)

The proxy uses delegatecall so the implementation runs in the proxy's storage context.

Pattern Description Example
Transparent Proxy Admin vs user separation OpenZeppelin
UUPS Upgrade logic in implementation OpenZeppelin UUPSUpgradeable
Diamond (EIP-2535) Multiple implementation contracts Arbitrary upgrade granularity

Risk: Storage collision between proxy and implementation — use storage gaps or EIP-1967 slots.


48. What is The Graph and how does it work?

The Graph is a decentralised indexing protocol for querying blockchain data via GraphQL — solving the problem that reading historical event data from nodes is slow and expensive.

1. Developer writes a Subgraph (schema + mapping handlers)
2. Graph Node indexes events from the chain
3. dApp queries subgraph via GraphQL endpoint
{
  transfers(first: 10, orderBy: timestamp, orderDirection: desc) {
    id
    from
    to
    value
  }
}

Replaces the need for custom indexers for most read-heavy dApps.


49. What is account abstraction (ERC-4337)?

Traditional Ethereum accounts (EOAs) require private keys for every transaction — no social recovery, no batch transactions, no sponsored gas.

ERC-4337 introduces Smart Accounts — contracts that act as wallets:

Feature EOA Smart Account (ERC-4337)
Key rotation Hard (losing key = losing funds) Social recovery, multisig
Gas sponsorship User always pays Paymaster can sponsor gas
Batch transactions No Yes
Session keys No Yes (time-limited permissions)
Passkey/biometric No Yes

Infrastructure: Bundler (like a miner for UserOperations), Paymaster (sponsors gas), EntryPoint (singleton contract).


50. What is the difference between Solidity and Vyper?

Solidity Vyper
Paradigm C-like, OOP Python-like, functional
Inheritance Yes (multiple) No
Inline assembly Yes (Yul) No
Function overloading Yes No
Recursion Yes No
Security by design More footguns Fewer footguns
Use case Most contracts Security-critical DeFi (Curve)
Compiler audits More audited Fewer

Vyper intentionally restricts features to reduce attack surface; Solidity provides more power and flexibility.


Anti-patterns to avoid

Anti-pattern Problem Fix
External call before state update Reentrancy Checks-Effects-Interactions
tx.origin for auth Phishing via proxy Use msg.sender
Floating pragma (^0.8.0) Inconsistent compilation Pin exact version
Hardcoded addresses Breaks across chains/upgrades Use constructor params or config
Storing large data on-chain High gas cost IPFS + on-chain hash
block.timestamp for randomness Validator-manipulable Chainlink VRF
Unbounded loops Out-of-gas DoS Pagination, push/pull patterns
Centralised ownership without timelock Admin rug-pull risk Timelock + multisig (Gnosis Safe)

Blockchain vs related technologies

Blockchain Traditional DB IPFS Hyperledger
Trust model Trustless Trusted authority Content-addressed P2P Permissioned consortium
Write control Consensus rules Admin / application Anyone (pinning) Invited members
Immutability Yes No Content-addressed Yes
Performance Low (TPS) Very high Moderate Higher than public chains
Smart contracts Yes (Ethereum+) Stored procedures No Yes (chaincode)
Privacy Public or private Full control Public by default Fine-grained

FAQ

Q: Is Solidity the only language for Ethereum smart contracts? No. Alternatives: Vyper (Python-like, security-focused), Yul/Yul+ (low-level IR), Fe (Rust-like, early stage), Huff (assembly-level). Solidity is dominant with 95%+ market share.

Q: How do I get ETH on a testnet for development? Use a faucet for testnets: Sepolia (sepoliafaucet.com), Holesky. For local development, Hardhat Network comes with 20 pre-funded accounts (10,000 ETH each). Use hardhat node to start it.

Q: What is gas optimisation and why does it matter? On mainnet, complex contracts can cost hundreds of dollars per transaction. Techniques: use calldata instead of memory, pack storage variables (multiple values in one slot), use custom errors over string reverts, cache storage reads in memory, use unchecked for safe increments, and minimise SSTORE operations.

Q: What is the difference between transfer, send, and call for sending ETH?

Gas limit On failure Recommended?
transfer 2300 (hard cap) Reverts No (EIP-1884 broke it)
send 2300 (hard cap) Returns false No
call All remaining (configurable) Returns false Yes — check return value
Use: (bool success,) = recipient.call{value: amount}(""); require(success);

Q: What is the difference between view and pure functions?

  • view: can read state, cannot write
  • pure: cannot read or write state (only uses local vars + args) Both are free when called externally (no gas), but cost gas when called from another contract.

Q: How do you write tests for Solidity contracts? Use Hardhat + ethers.js + Chai (JavaScript) or Foundry (Solidity-native tests):

// Hardhat test
it("should transfer tokens", async () => {
    const [owner, alice] = await ethers.getSigners();
    const Token = await ethers.getContractFactory("MyToken");
    const token = await Token.deploy();
    await token.transfer(alice.address, 100n);
    expect(await token.balanceOf(alice.address)).to.equal(100n);
});

Foundry (forge test) runs tests written in Solidity with fuzzing and gas reports built-in.

Keep reading

All Toolmingotools are free & run in your browser

No sign-up, no upload, no watermark. Your files never leave your device.

Browse all tools