Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 47 ยท Practice and Review

Solidity Interview Questions

Prepare for a Solidity interview: short answers on the language, gas, security, token standards and design, with runnable JavaScript demos for the tricky ones.

Solidity interviews tend to follow one pattern. They start with language basics, move to gas and storage, spend the most time on security, and finish with a design question such as "how would you build an auction?". Good answers are short, correct and honest about trade-offs. This page collects the questions that come up most often, with answers of a few sentences each, and three runnable demos for the ideas that are easiest to explain by showing them.

Use the answers to find gaps, not to memorize. If you cannot explain an answer in your own words, follow the link to the lesson and come back. The demos are JavaScript stand-ins: they model the behaviour but do not run an EVM, compute real keccak hashes or measure real gas.

How interviews are shaped

Language Types, locations, visibility, errors.
Gas Why things cost what they cost.
Security The longest and most important part.
Design Build something small, defend your choices.

Say what you would test and what could go wrong.

1 / 2

Language basics

What is the difference between storage, memory and calldata?

storage is the contract's permanent state, saved on the blockchain between calls and expensive to write. memory is scratch space that exists for one external call and is wiped afterwards. calldata is the read-only input of an external call, the cheapest place for arguments because nothing is copied. Local variables of reference types (arrays, structs, strings) must state their location. See Storage, Memory and Calldata.

What is the difference between public, external, internal and private?

public functions can be called from inside and outside, and a public state variable gets an automatic getter. external functions are meant only for outside callers, and can take calldata parameters. internal is visible to the contract and contracts that inherit from it, and private only to the contract that defines it. private is not secret: anyone can read storage directly. See Functions and Visibility.

What do view and pure mean?

A view function promises not to change state, but may read it. A pure function promises neither to read nor to change it, so it depends only on its arguments. Both are free when called off-chain, and cost gas only as part of a transaction.

What is the difference between require, assert and revert?

All three undo the current call. require(condition, ...) and if (!condition) revert CustomError(...) validate inputs and states that can legitimately fail. assert checks an invariant that should never be false, and a failure raises a Panic error, which signals a bug. Custom errors cost less than long revert strings and can carry data. See Control Flow, require, revert and Custom Errors.

What changed in Solidity 0.8 about arithmetic?

From 0.8.0, arithmetic is checked: overflow, underflow and division by zero revert with a panic. Before that, numbers wrapped around silently, and contracts needed SafeMath. An unchecked { ... } block turns the checks off, and should be used only where the math is proven safe. See Integers, Overflow and Checked Math.

Why can you not loop over a mapping?

A mapping does not store its keys. The value of a key lives at a slot computed by hashing the key together with the mapping's position, and every possible key conceptually exists with a zero value. To iterate, keep a separate array of keys and update it yourself. See Mappings.

What is the difference between constant and immutable?

A constant is fixed at compile time and is substituted where used. An immutable is set once, in the constructor, then baked into the deployed code. Neither uses a storage slot, so reading them is cheap. See Constructors, Constants and Immutables.

What are events for, and can contracts read them?

Events write to the transaction log, which is cheap and easy for off-chain code to filter, using up to three indexed topics. Contracts cannot read past logs, so an event is a notification, not storage. See Events and Logs.

What does payable do, and what are receive and fallback?

Only payable functions accept ether. receive() runs when the contract gets ether with empty call data, and fallback() runs when no function matches the call data (and receives ether if it is payable). See Sending and Receiving Ether.

What are the important features of Solidity?

It is a statically typed, contract-oriented language with inheritance, libraries, custom types and user-defined errors, compiled to EVM bytecode. Contracts are self-executing programs that hold state and ETH. Arithmetic is checked, visibility and mutability are explicit, and events provide a log for outside programs. It also supports tokenization, meaning a contract can represent assets such as fungible tokens and NFTs (Building an ERC-20 Token). Unlike general languages, every operation costs gas and there is no floating point, no network access and no randomness.

What is the difference between uint8 and uint16?

uint8 holds 0 to 255 in 8 bits, uint16 holds 0 to 65,535 in 16 bits. The EVM works on 256-bit words, so a smaller type is not faster by itself. It saves storage only when several small variables are packed into one slot, and conversions between sizes can cost extra gas. Narrowing a value (for example uint8(300)) keeps only the low bits unless you use a checked conversion.

How much is 1 kwei of ether, and what are the units?

1 kwei is 1,000 wei (also called babbage). The ladder is wei (1), kwei (10^3), mwei (10^6), gwei (10^9), szabo (10^12), finney (10^15) and ether (10^18). Only wei, gwei and ether remain as Solidity literal suffixes. See Operators, Ether Units and Time Units.

What is the difference between Solidity and other programming languages?

Code runs on every node and must give the same result everywhere, so it is deterministic and sandboxed. You pay per operation, storage is the most expensive resource, deployed code is immutable by default, state is public, and a bug can lose real money. See Smart Contracts: Features, Uses and Limits.

Gas and the EVM

What is gas, and who pays for it?

Gas measures the computation and storage a transaction uses. The sender pays gas used multiplied by the price per unit, and sets a gas limit as a cap. If execution runs out of gas, the call reverts but the gas spent is not returned. Every operation has a price, and storage writes are by far the most expensive. See Gas Costs and Optimization.

Name four ways to reduce gas.

Pack small variables into shared slots, cache a storage variable in a local variable when reading it repeatedly, use calldata for read-only external arguments, and use custom errors instead of long strings. Avoid unbounded loops, and emit events instead of storing data nobody on-chain needs. Always measure before and after.

Why must a loop over user-controlled data be avoided?

Each iteration costs gas, and a block has a gas limit. If an array can grow without bound, there is a size at which the function can never finish, and any function that needs it is stuck. That is a denial of service.

What happens to selfdestruct today?

After the Cancun upgrade (EIP-6780), selfdestruct no longer deletes code and storage, except when called in the same transaction that created the contract. In other cases it only sends the contract's ether to the target. New code should not rely on it. See Sending and Receiving Ether.

Is there a maximum contract size?

Yes. Deployed code cannot be larger than 24,576 bytes (EIP-170). Large systems are split into several contracts, libraries or proxies.

Security

Explain reentrancy and how to prevent it.

Reentrancy happens when a contract calls an external address before updating its own state, and the callee calls back into the original function while the old state is still in place. The fix is checks-effects-interactions: validate, then update state, then call out. A reentrancy guard and pull payments add more defence. The push-versus-pull demo further down shows a related payment weakness. See Reentrancy Step by Step.

What is the difference between tx.origin and msg.sender?

msg.sender is the immediate caller of the current function. tx.origin is the externally owned account that started the whole transaction. Authorization based on tx.origin can be abused by a malicious contract the owner is tricked into calling. See msg.sender, msg.value and Global Variables.

What is front-running?

Pending transactions are visible before they are included in a block, so someone can submit their own transaction first by paying a higher fee. Defences include commit-reveal schemes, slippage limits, and designs where the order of transactions does not matter.

Why is block.timestamp or blockhash a bad source of randomness?

Block producers can influence these values, and other contracts can read them in the same transaction. Use a verifiable randomness service or a commit-reveal scheme. See Oracles, Randomness and Off-Chain Data.

What is a signature replay attack?

A signed message that authorizes an action may be submitted again, on the same contract, on another contract or on another chain. Include a nonce, the chain id and the contract address (a typed-data domain, EIP-712) in what is signed, and mark used nonces.

What is the danger of delegatecall?

The called code runs with the caller's storage and msg.sender. If the target is controlled by an attacker, or if the two contracts disagree on storage layout, the caller's state is overwritten. Proxies use it deliberately and must keep layouts consistent. See Proxies and Upgradeable Contracts.

What is an unchecked return value?

Low-level calls such as call and send return false on failure instead of reverting. If the code ignores the result, it continues as if the payment worked. Always check, or use patterns that revert.

How can an oracle be attacked?

If a contract reads a price from a pool that one trade can move, an attacker can move the price, use the contract, and move it back, all in one transaction, using a flash loan. Use time-weighted prices or decentralized price feeds, and add sanity limits.

Standards and patterns

What is the ERC-20 allowance race condition?

If a holder changes an allowance from 10 to 5, a spender who sees the pending transaction can spend the 10 first, then spend the new 5 after it lands. Safer options are setting the allowance to zero first, using increaseAllowance-style helpers or using permits. See Building an ERC-20 Token.

ERC-721 versus ERC-1155?

ERC-721 tracks unique tokens: each id has exactly one owner. ERC-1155 manages many token types in one contract, each with a balance per holder, and supports batch transfers. See ERC-721 NFTs and ERC-1155, ERC-4626 and Friends.

Why use OpenZeppelin?

Because access control, pausing, token standards and safe transfer helpers are easy to get subtly wrong, and the library is widely reviewed. Reuse it, pin the version, and read what you inherit. See Using OpenZeppelin.

What is the push versus pull payment pattern?

Push sends ether to many recipients in a loop, so one failing recipient can block everyone. Pull records what each person is owed and lets them withdraw it, so one failure affects only one person.

What is a proxy, and what are its risks?

A proxy holds the storage and forwards calls with delegatecall to an implementation contract, so the logic can be replaced. Risks include storage layout clashes, an unprotected initialize, and an upgrade key that can change everything. Protect the upgrade power with a multisig or timelock, as in Project: A Multisig Wallet.

What is ERC-165 used for?

ERC-165 lets a contract announce which interfaces it implements. A contract exposes supportsInterface(bytes4 interfaceId), and the id is the XOR of all function selectors in the interface. Callers such as marketplaces use it to check, for example, that an address really is an ERC-721 before sending it a token. See ERC-1155, ERC-4626 and Friends.

What is a bonding curve?

A bonding curve is a formula, written in a contract, that sets a token's price as a function of its current supply: buying mints tokens and raises the price, selling burns tokens and lowers it. The contract always quotes a price, so there is no order book, and it holds a reserve of ETH or another token to pay sellers. A simple linear curve is price = base + slope * supply. Risks include price manipulation with flash loans and slippage on large trades, so a good curve limits trade size or uses a minimum-output argument.

What is TWAP?

A time-weighted average price averages an asset's price over a window, which makes it expensive to manipulate in a single block. Lending and derivatives contracts prefer it to a spot price. See Oracles, Randomness and Off-Chain Data.

Three demos

Demo: why encodePacked can collide

abi.encodePacked concatenates values without lengths. Two different pairs of dynamic strings can produce identical bytes, and so identical hashes. The stand-in joins strings the same way and compares them with a length-prefixed encoding, which is what abi.encode effectively provides.

JS Packed encoding collisions

Press Run (or Ctrl + Enter) to see the console output here.

No output.

If you hash user-provided values together, use abi.encode, or put a fixed-size value between dynamic ones.

Demo: push versus pull

A contract that pays everyone in one loop can be held hostage by one recipient whose receiving code always fails. The pull version lets each account collect its own money.

JS One bad recipient

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Demo: delegatecall runs on the caller's storage

The stand-in below has a logic object whose function writes to this. Called normally, it changes its own state. Called through a "delegate call" helper, it changes the caller's state, and the mismatch of layouts shows the danger.

JS Whose storage changes?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Real: the packed-encoding ambiguity, the failure of a push loop when one send fails, and delegatecall using the caller's storage. Stand-in: concatenation and length prefixes imitate encoding, the revert of the loop is simulated by restoring a snapshot, and apply(proxy, ...) imitates the borrowed context without real storage slots.

Design questions

Interviewers often end with "design an auction" or "design a vote". A reliable method is to answer in this order. State the actors and what each may do. List the state and which transitions are allowed. Pick pull payments for any money going out. Name the failure cases (late bids, failed refunds, a tie). Say how you would test it. Then mention the trust assumptions: who can pause or upgrade, and what a bad key could do. The project lessons (voting, crowdfunding and escrow and auction) are good rehearsal.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A contract calls an external address and then sets the sender's balance to zero. What is the bug?

    State must change before the external call. Otherwise a callback sees the old balance and can withdraw again.
  2. 2. Which choice is true about private state variables?

    Visibility controls source-level access, not secrecy. Anyone can read raw storage slots from a node.
  3. 3. Why is delegatecall to an untrusted address dangerous?

    The code of the target runs in the context of the caller, so a hostile or mismatched target can change the caller's owner, balances or anything else.
  4. 4. What is a good reason to prefer pull payments?

    With pull payments each user collects their own balance. A recipient who rejects ether only hurts themselves.
  5. 5. After EIP-6780, what does selfdestruct do in an old, already deployed contract?

    Code and storage are deleted only if the contract was created in the same transaction. Otherwise the ether is sent and nothing else changes.

Summary

  • Know the data locations, the four visibility levels, view versus pure, the three error tools and checked arithmetic.
  • For gas, explain why storage is costly and show three or four practical savings.
  • For security, be able to explain reentrancy, tx.origin, front-running, bad randomness, replay, delegatecall, unchecked returns and oracle manipulation.
  • For standards, know the allowance race, the ERC-721 and ERC-1155 difference and why to reuse audited libraries.
  • For design questions, list actors, state, transitions, money flow, failures and tests, then name your trust assumptions.

Next: Solidity Cheat Sheet.