Blockchain Interview Questions for 2 Years Experience
40 questions with answers for candidates with 2 years of experience — 5 easy, 34 medium, 1 hard.
What interviewers expect: 2 years experience
At two years, interviews go deeper into the EVM and security: storage layout, delegatecall, proxies, CREATE2, signatures and EIP-712. You may get a code review exercise to find bugs in a contract, and scenario questions about upgrades, indexing and Layer 2 deployment. Interviewers expect you to have owned features end to end and handled at least one audit cycle.
This set is weighted towards Solidity Programming (7), Consensus and Scaling (6), dApp Development (5), DeFi, Tokens and NFTs (5).
3 QUESTIONS FREESign up to unlock the full question bank and track your progress.Unlock every question and answer, then continue practising company-wise and package-wise.
✓ 3 questions free • Unlock the rest in seconds
01
Write a minimal Python example showing how blocks are linked by hashes.
Each block stores the previous hash, so changing any earlier data breaks the chain.
import hashlib, json
def block_hash(block):
data = json.dumps(block, sort_keys=True).encode()
return hashlib.sha256(data).hexdigest()
chain = [{'index': 0, 'data': 'genesis', 'prev': '0'}]
for i, tx in enumerate(['A pays B 5', 'B pays C 2'], 1):
chain.append({'index': i, 'data': tx, 'prev': block_hash(chain[-1])})
valid = all(chain[i]['prev'] == block_hash(chain[i-1]) for i in range(1, len(chain)))
print(valid)
02
Users complain they must pay gas to approve tokens before every trade. How can signatures help?
Use off-chain signed approvals. With EIP-2612 permit, the user signs a typed EIP-712 message granting an allowance, and the dApp submits it with the trade in one transaction, so no separate approve call is needed. For tokens without permit, Permit2-style contracts give the same experience after one approval. EIP-712 shows readable fields in the wallet, reducing phishing risk. Always include a nonce, deadline, chain ID and verifying contract to prevent replays.
03
What is ECDSA and why does Ethereum use the secp256k1 curve?
ECDSA is the Elliptic Curve Digital Signature Algorithm. It gives strong security with short keys: a 256-bit key is roughly as strong as a 3072-bit RSA key, which keeps transactions small. Bitcoin and Ethereum use the secp256k1 curve, whose simple structure allows efficient computation. A signature has values r and s plus a recovery id v, which lets nodes recover the signer's public key from the signature, so the sender address need not be included separately.
04
Your staking validator is missing attestations and losing rewards. How do you investigate?
Check that both execution and consensus clients are synced and peering well, since low peer count or a lagging execution client causes missed duties. Look at system clock sync through NTP, CPU, memory and disk I/O, as slow disks often cause delays. Review client logs and metrics in Grafana, check for pending client upgrades before a fork, and verify network ports are open. Never start a second copy of the same validator key as a fix, because that causes slashing.
05
What is storage packing, and what are other key gas optimisations?
The EVM stores data in 32-byte slots, so consecutive small variables like uint128, uint64, address and bool can share a slot if declared next to each other, saving expensive SSTOREs. Other optimisations: use calldata for external arrays, cache storage reads in local variables, use immutable and constant, prefer custom errors over strings, avoid unbounded loops, use events instead of storing history, and use unchecked for counters that cannot overflow. Always measure with forge snapshot.
06
How do you get the latest block number from an Ethereum node using JSON-RPC?
Send a JSON-RPC POST request to the node or provider URL. The result is a hex string that you convert to decimal.
curl -s -X POST https://rpc.example.org \
-H 'Content-Type: application/json' \
-d '{"jsonrpc":"2.0","method":"eth_blockNumber","params":[],"id":1}'
# Response: {"jsonrpc":"2.0","id":1,"result":"0x15d3a1c"}
# In Python: int('0x15d3a1c', 16)
Other common methods are eth_getBalance, eth_call and eth_getTransactionReceipt.
07
How do you handle unclear or changing requirements from a client?
Situation: a client asked for a marketplace dApp but kept changing royalty and fee rules. Task: deliver without endless rework. Action: I wrote a short spec with examples and edge cases, got sign-off, and made fees configurable parameters with limits instead of hard-coded logic. Changes went through a simple change log with impact estimates. Result: we delivered in eight weeks, and later fee changes needed only a governance transaction, not a redeployment.
08
How do you store an NFT image on IPFS and use it in your contract?
Upload the image to IPFS using a node or a pinning service, which returns a CID. Create a metadata JSON file whose image field is ipfs://<imageCID>, then upload the metadata folder to get a folder CID. Set the contract's base URI to ipfs://<folderCID>/ so tokenURI(5) resolves to the file for token 5. Pin the content with more than one provider, and use a gateway URL only for display in the front-end.
09
Design token vesting for team members and early investors.
Use a vesting contract that holds allocated tokens and releases them on a schedule, typically a one-year cliff followed by monthly or linear vesting over two to four years. OpenZeppelin VestingWallet gives linear vesting per beneficiary; add a cliff and an owner-controlled revoke for employees who leave, returning unvested tokens. Make schedules public on-chain for transparency, and avoid admin functions that could release tokens early, as that erodes investor trust.
10
Your dApp's users are paying high gas fees on Ethereum mainnet. How would you choose a Layer 2?
I would compare candidate rollups on security (proof system live, stage of decentralisation, upgrade keys), EVM compatibility so our Solidity code deploys unchanged, ecosystem fit (wallets, oracles, liquidity, bridges our users already use), fees and throughput, and withdrawal experience. I would deploy to testnets first, measure real costs and latency, and check that our dependencies such as Chainlink feeds exist there. Then migrate gradually, keeping L1 contracts for high-value settlement if needed.
11
You need to send ETH to hundreds of winners. Should you push payments or let them pull?
Prefer pull payments. If a contract pushes ETH in a loop, one recipient that reverts, perhaps a contract without receive, can block everyone, and the loop may exceed the gas limit. With pull payments, the contract records each winner's amount in a mapping and winners call withdraw, which zeroes their balance before sending. This isolates failures and limits reentrancy risk. Push only for small fixed lists using call with a checked result.
12
How do you deploy a contract to a Layer 2 testnet with Foundry?
Set the RPC URL and a deployer key, then use forge create or a script, and verify the source on the explorer.
export RPC_URL=https://sepolia.l2-example.org
export PRIVATE_KEY=0x... # testnet key only
forge create src/Counter.sol:Counter \
--rpc-url $RPC_URL --private-key $PRIVATE_KEY --broadcast
# Scripted deploy with verification
forge script script/Deploy.s.sol --rpc-url $RPC_URL \
--broadcast --verify
Use a keystore via cast wallet import instead of raw keys for anything real.
13
How do you read a Chainlink price feed in Solidity safely?
Storage is persistent key-value data of 32-byte slots per contract; it is the most expensive, and writes to new slots cost about 20,000 gas. Memory is a temporary byte array cleared after each call, cheap but growing in cost quadratically. The stack holds up to 1024 words for opcode operands. Calldata is the read-only input data of the transaction, the cheapest place to read external function arguments from. Choosing the right location is a key gas optimisation.
15
How does a constant product automated market maker work, and what is impermanent loss?
A constant product AMM holds two tokens with reserves x and y and keeps x times y equal to k. A trader adds one token and removes the other so that k stays constant after fees, which makes price equal to the reserve ratio and rise with trade size. Liquidity providers earn fees, but when prices move, arbitrage rebalances the pool, leaving them worse off than simply holding; that gap is impermanent loss.
16
Tell me about a time you learnt a new technology quickly to meet a deadline.
Situation: in my internship I was asked to add NFT minting to a demo in ten days, and I had never written Solidity. Task: deliver a working, tested contract. Action: I spent two days on Solidity basics and OpenZeppelin docs, built the ERC-721 contract, asked a senior to review my approach early, and wrote Foundry tests for every function. Result: the demo shipped on time on Sepolia, and the review caught only minor issues.
17
What are Delegated Proof of Stake and Proof of Authority?
In Delegated Proof of Stake, token holders vote for a small set of block producers who validate on their behalf, giving high throughput but more centralisation. In Proof of Authority, a fixed set of known, reputable validators sign blocks; their identity, not stake, is at risk. PoA, often via Clique, IBFT or QBFT, suits private and consortium EVM networks and some testnets, where participants are known and fast, predictable block times matter more than open participation.
18
Tell me about a bug you missed and what you learned from it.
Situation: I shipped a rewards contract where a rounding error let users claim slightly more than earned when claiming very often. Task: fix it and prevent repeats. Action: I owned the mistake in the team call, wrote a failing test reproducing it, changed the division order to round down in the protocol's favour, and added fuzz tests on claim frequency. Result: losses were tiny, and I now always fuzz any maths involving division.
Gas measures the computational work an operation needs; for example a simple ETH transfer uses 21,000 gas, and writing a new storage slot costs about 20,000. The gas limit is the maximum gas the sender allows a transaction to consume. The gas price, per unit, is what the sender pays. The fee equals gas used times the effective gas price. If execution exceeds the limit, it reverts but the used gas is still charged.
EIP-1559 splits the fee into a base fee and a priority fee. The protocol sets the base fee per block from demand: if the previous block was more than half full, it rises up to 12.5 percent, otherwise it falls. The base fee is burned. Users add a priority fee (tip) for the proposer and set maxFeePerGas as their cap. They pay base fee plus tip, never more than the cap, which makes fees more predictable.
Modifiers are reusable pieces of code that run before or after a function body, placed where the underscore symbol appears. They are mainly used for checks such as onlyOwner, whenNotPaused or nonReentrant. For example, modifier onlyOwner() { require(msg.sender == owner, 'not owner'); _; } blocks everyone except the owner. Keep modifiers short and check-only; complex logic inside modifiers hides behaviour and increases bytecode size because the code is inlined into every function that uses it.
22
Your RPC provider starts rate-limiting and the dApp breaks during peak traffic. What do you do?
Short term, add a fallback transport with multiple providers so requests fail over automatically, and use retries with backoff. Reduce load: batch calls with multicall, cache read results, use WebSockets instead of tight polling, and move history queries to an indexer. Long term, upgrade the plan, spread traffic across providers or run your own node for critical paths, and monitor error rates and latency with alerts so you learn of issues before users do.
23
How do you calculate a borrower's health factor in a lending protocol?
Health factor = (sum of collateral value x liquidation threshold) / total debt value. Below 1, the position can be liquidated.
Example: collateral 10 ETH at 3,000 dollars = 30,000 dollars, liquidation threshold 80 percent, debt 18,000 dollars of stablecoins.
HF = (30,000 x 0.80) / 18,000 = 1.33.
If ETH falls to 2,250, collateral is 22,500, so HF = 18,000 / 18,000 = 1.0 and liquidation begins. Users raise HF by repaying debt or adding collateral.
In the UTXO model used by Bitcoin, coins exist as unspent transaction outputs; a transaction consumes some outputs and creates new ones, which makes parallel validation and privacy easier. In the account model used by Ethereum, the state stores a balance and nonce per account, which is simpler for smart contracts and wallets. The trade-off: UTXO avoids replay issues and scales verification well, while accounts make complex stateful logic far easier to write.
25
How did integer overflow bugs happen before Solidity 0.8?
Before 0.8, arithmetic wrapped silently: a uint8 at 255 plus 1 became 0, and 0 minus 1 became the maximum value. Attackers exploited this, for example by making a balance underflow to a huge number or an overflowed multiplication pass a check, as in the 2018 batchOverflow token bug. Developers used the SafeMath library to revert on overflow. Since 0.8 the compiler checks automatically, except inside unchecked blocks and in inline assembly.
26
Compare interfaces, abstract contracts and libraries.
An interface only declares external functions, events and errors, with no state or implementation; it is used to call other contracts, like IERC20. An abstract contract can have state and implemented functions but leaves at least one unimplemented or is marked abstract, so it cannot be deployed alone. A library holds reusable functions without state; internal library functions are inlined, while external ones are deployed once and called via delegatecall. Libraries can attach to types with using for.
27
An HR team wants to store employee records on a blockchain. Would you recommend it?
Usually no. Employee records are owned by one organisation, change often and contain personal data that must be correctable and deletable under the DPDP Act 2023. A normal database with role-based access and audit logs is cheaper, faster and compliant. I would ask who else needs to trust the data. If several employers or background-check agencies must verify certificates, I would store only hashes of credentials on a permissioned chain and keep the actual data off-chain.
28
Users complain they received far fewer tokens than expected on large swaps. What is happening and how do you help?
Large trades in shallow pools suffer price impact, and wide slippage settings let sandwich bots extract extra value. Show the expected output, price impact and minimum received before confirming. Set sensible default slippage, such as 0.5 percent for major pairs, and warn when impact is high. Use a router or aggregator that splits trades across pools, and offer private transaction submission so bots cannot see the swap in the public mempool.
Validators deposit 32 ETH (after the Pectra upgrade a validator can hold up to 2048 ETH) to join. Time is divided into 12-second slots and 32-slot epochs. In each slot a randomly chosen validator proposes a block and committees attest to it. The fork-choice rule LMD-GHOST picks the head, and Casper FFG finalises checkpoints when two-thirds of stake agrees. Honest validators earn rewards; offline ones lose small amounts, and provably malicious ones are slashed.
30
What are front-running and sandwich attacks, and how do you mitigate them?
Pending transactions are public, so bots can copy or outbid them. Front-running is placing a transaction ahead of a victim's, for example buying before a large purchase. A sandwich attack buys before the victim's swap and sells right after, profiting from the price impact. Mitigations include slippage limits and deadlines, commit-reveal schemes, batch auctions, private transaction relays, and design that does not reward ordering, such as using time-weighted prices.
A sidechain is an independent blockchain with its own validators and consensus, connected to the main chain by a bridge. Its security depends on its own validator set, so if they collude, funds can be stolen. A rollup posts its transaction data and state roots to Ethereum and relies on fraud or validity proofs, so it inherits Layer 1 security for correctness. Sidechains are usually cheaper and more flexible, but rollups give stronger guarantees.
32
What are the basic Foundry commands to create, build, test and work with a project?
curl -L https://foundry.paradigm.xyz | bash && foundryup
forge init my-dapp # new project with src, test, script
forge install OpenZeppelin/openzeppelin-contracts
forge build # compile
forge test -vvv # run tests with traces
forge coverage # coverage report
forge snapshot # gas snapshot
anvil # local node
cast call ADDR 'count()(uint256)' --rpc-url $RPC
Foundry tests are written in Solidity and run fast; Hardhat is the JavaScript or TypeScript alternative with a large plugin ecosystem.
33
What is the difference between receive and fallback functions?
receive() external payable runs when a contract receives plain ETH with empty calldata, for example a transfer from a wallet. fallback() runs when calldata matches no function, or when ETH arrives with data and no receive exists; it must be payable to accept ETH. Proxies use fallback to delegatecall all unknown calls to the implementation. Keep both simple, since a reverting or gas-heavy receive can break senders that use transfer with its 2300 gas stipend.
A multisig wallet is a smart contract, such as a Safe, that needs M of N owner signatures to execute a transaction; rules are visible on-chain and easy to audit, but every action costs extra gas and works per chain. An MPC wallet splits one private key into shares held by different parties who jointly produce a normal signature; it looks like a regular address, works on any chain and allows key rotation, but the security depends on the off-chain implementation.
35
What are seed phrases and HD wallets (BIP-39, BIP-32, BIP-44)?
BIP-39 encodes random entropy as a 12 or 24 word mnemonic, which is turned into a binary seed. BIP-32 defines hierarchical deterministic wallets that derive a tree of key pairs from that seed. BIP-44 standardises the derivation path, for example m/44'/60'/0'/0/0 for the first Ethereum account. So one backed-up seed phrase can restore unlimited addresses across chains. Whoever knows the phrase controls every derived account, so it must never be stored online.
36
You need the same contract at the same address on five chains. How do you do it?
Use CREATE2 through a deterministic deployment factory that already exists at the same address on all those chains. Keep the init code identical: same compiler version, optimiser settings, constructor arguments and metadata. Pick a salt, compute the expected address off-chain, then deploy on each chain. Foundry scripts support this by passing a salt. Avoid constructor arguments that differ per chain, or move chain-specific settings into an initialiser restricted to the deployer.
37
How do you read a contract and send a transaction with viem?
Common causes: loops over arrays that grow with users until they exceed the block gas limit; push payments in a loop where one reverting recipient blocks everyone; relying on an external call that an attacker can make fail; and griefing by filling storage cheaply. For example, an auction that refunds the previous bidder will freeze if that bidder is a contract that reverts. Use pull payments, bounded loops, pagination and failure isolation.
39
How did you handle a time you received critical code review feedback?
Situation: a senior reviewer rejected my pull request for a staking feature, saying the storage layout would break future upgrades. Task: fix it and learn. Action: I thanked him, asked him to explain the risk, read about EIP-1967 and storage gaps, rewrote the contract with namespaced storage, and added a storage-layout check to CI. Result: the PR merged, and that check later caught a teammate's layout change before an upgrade.
40
How do you compute a function selector and decode calldata with cast?
cast handles ABI work from the command line.
# Function selector
cast sig 'transfer(address,uint256)'
# 0xa9059cbb
# Encode calldata
cast calldata 'transfer(address,uint256)' 0xAbc... 1000000
# Decode calldata from a transaction
cast 4byte-decode 0xa9059cbb000000...
# Decode with a known signature
cast decode-calldata 'transfer(address,uint256)' 0xa9059cbb...
This is useful when checking what a wallet is really asking you to sign.
Frequently asked questions
What is asked in Blockchain interviews for 2 years of experience?
At two years, interviews go deeper into the EVM and security: storage layout, delegatecall, proxies, CREATE2, signatures and EIP-712. You may get a code review exercise to find bugs in a contract, and scenario questions about upgrades, indexing and Layer 2 deployment. Interviewers expect you to have owned features end to end and handled at least one audit cycle.
How many questions should I practise before a Blockchain interview?
Work through all 40 questions here, then the company-wise sets for the employers you are targeting. Quality matters more than count: be able to explain why each answer is right.
Which topics matter most for 2 years of experience?
Focus first on Upgradeable proxies, EVM internals, Code review exercises, Layer 2 deployment.