Skip to content
Tech Interview Prep
Technical interview guide

Smart Contract Development (Solidity & EVM)

Writing and deploying self-executing contract code on the Ethereum Virtual Machine: state, gas, and the constraints of on-chain execution.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v4
Editorial status
Reviewed

Scope: Solidity latest documentation (0.8.36/0.8.37 development line reviewed 2026-09-04); Ethereum EVM documentation updated 2026-07-26; target-chain fork rules must be verified at deployment; ERC-1967, EIP-170, and EIP-1153.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-18

Walk me through how the EVM executes a contract call at the opcode level, from the function selector dispatch to returning data to the caller.

Answer

The 90-second version. Assume a Solidity 0.8.x contract called with CALL from an EOA or another contract. The EVM has no concept of functions: it sees calldata bytes and a program counter. The selector, the argument decoding and the return encoding are all bytecode the compiler emitted. The path is: the caller assembles selector || abi.encode(args) and CALLs; the target's runtime code starts at PC 0 with a dispatcher; the dispatcher matches the selector and JUMPIs to the body; the body reads args from calldata, computes, writes results to memory, and RETURN hands back a byte range; the caller reads it with RETURNDATASIZE/RETURNDATACOPY.

Dispatch. The prologue extracts the top 4 bytes:

PUSH1 0x00      ; offset 0
CALLDATALOAD    ; 32 bytes from calldata[0..32), zero-padded past the end
PUSH1 0xE0      ; 224
SHR             ; >> 224 leaves the high 4 bytes = selector

Then a linear scan, one block per external function:

DUP1
PUSH4 0xa9059cbb   ; transfer(address,uint256)
EQ
PUSH2 0x00XX       ; destination PC of the body
JUMPI

No match falls through to the fallback, or reverts with no data. Each candidate costs about 22 gas (DUP1 3 + PUSH4 3 + EQ 3 + PUSH2 3 + JUMPI 10), so a 10-function contract spends ~220 gas worst case before any work.

Arguments. Static types are read in place: for transfer(address,uint256), to is CALLDATALOAD(0x04) and amount is CALLDATALOAD(0x24). Dynamic types (bytes, string, arrays) put a 32-byte offset in the head; the decoder follows it to a length-prefixed tail and copies with CALLDATACOPY. Memory holds dynamic data, structs and spilled locals; the stack holds 256-bit words, capped at 1024, with DUP/SWAP reaching only 16 deep.

Return. The body writes results to memory and returns a range: a bool is PUSH1 0x01 PUSH1 0x00 MSTORE PUSH1 0x20 PUSH1 0x00 RETURN. The caller then does RETURNDATASIZE / RETURNDATACOPY.

Trade-offs, with the deciding criterion.

  • Compiler dispatcher vs hand-written router. Solidity emits a linear scan; a binary-search or jump-table router (Seaport, EIP-2535 Diamond) cuts per-call dispatch cost, but you own ABI decoding and collision safety. Flip: under ~10-15 external functions the linear scan is a rounding error and the audit cost of a custom router dominates; above that, or when the contract is hit thousands of times per block, the router pays for itself. A proxy adds a cold DELEGATECALL (2600 gas) plus the implementation's own dispatch on every call.
  • Calldata vs memory for arguments. Calldata is read-only and needs no copy; memory is mutable but the compiler copies dynamic args in. Flip: the moment the function mutates, slices, or forwards the data to an internal function taking memory, you pay the copy anyway, then memory is the right home. Static args often never leave calldata.
  • Stack vs memory. PUSH/DUP/SWAP/POP are 3 gas; MLOAD/MSTORE are 3 gas plus quadratic expansion. Flip: past ~16 live values DUP/SWAP can't reach them and the compiler spills, which is why "stack too deep" is a compile error, not a runtime one.
  • Checking return data. Bounding the copy with RETURNDATASIZE costs a few gas. Flip: for a trusted callee with a known ABI, skip it; for routers, hooks and flash-loan callbacks, always bound it.

Failure modes. Selector collision: Solidity rejects two functions with the same selector in one contract, but proxies and hand-written routers can collide silently and route to the wrong body. Truncated calldata: CALLDATALOAD zero-pads past the end, so a short static argument decodes as zero rather than reverting. Memory expansion OOG: the cost is 3*words + words²/512, quadratic, so a callee that forces a huge allocation is a DoS vector. Return-data bomb: a malicious callee returns a huge blob; a caller that copies a size taken from the callee pays the expansion and OOGs.

Data locationAccessMutabilityGas
CalldataCALLDATALOAD, CALLDATACOPYRead-only3 gas + copy cost
MemoryMLOAD, MSTORE, MSTORE8Mutable3 gas + 3*words + words²/512
StackPUSH, DUP, SWAP, POPMutable3 gas, 1024 deep
StorageSLOAD, SSTOREMutableSLOAD 2100 cold / 100 warm; SSTORE 20000 for 0→nonzero

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

Walk me through how the EVM creates a contract: init code, constructor execution, deployed runtime bytecode, the EIP-170 code-size limit, and how CREATE and CREATE2 derive the new address.

Answer

A contract is created by executing init code; the constructor is part of that init code, and the runtime bytecode is whatever the init code returns. The address is derived from the sender and either its nonce (CREATE) or a salt and the init code hash (CREATE2).

Top-level creation: a transaction with to empty and data set to the init code. The EVM derives the new address, creates an account with nonce 1 and the transferred balance, then executes the init code in that account's context. The init code runs the constructor, writes initial storage, and ends with RETURN containing the runtime bytecode. Those returned bytes are charged at 200 gas per byte and stored as the account's code. If the init code reverts or runs out of gas, the account creation is rolled back; the transaction still consumes gas and the sender's nonce increments.

Inner creation: CREATE and CREATE2 opcodes do the same inside a call frame. CREATE increments the sender's nonce before deriving the address; if the init code fails, that nonce bump is reverted with the rest of the frame. CREATE2 does not use the nonce.

Address derivation:

  • CREATE: keccak256(rlp([sender, nonce]))[12:]
  • CREATE2: keccak256(0xff ++ sender ++ salt ++ keccak256(init_code))[12:]

The CREATE2 address depends on the full init code hash, so constructor arguments and any immutables embedded in the runtime code change the address. That is what makes deterministic deployment possible, but it also means a one-byte change to the init code produces a different address.

EIP-170 caps runtime code at 24,576 bytes. Init code has a separate limit (EIP-3860, 49,152 bytes) and is charged 2 gas per 32-byte word. Code deposit costs 200 gas per byte of runtime code, so a 24 KB contract costs 4,800,000 gas just to store, before constructor execution.

Failure modes: constructor reverts (no code deployed, gas consumed), out-of-gas during init, runtime code exceeding EIP-170 (creation fails), CREATE2 address collision (the target already has code or nonce, so the opcode reverts), init code returning empty (deploys an empty contract, which is valid but usually a bug), and constructor arguments that do not match the init code's expectations. For proxies, the constructor is skipped entirely and initialization happens in a separate call, which is why upgradeable deployments need an initializer with a re-initialization guard.

Worked trace for a top-level deployment:

  1. Tx to null, data = init code (constructor args appended).
  2. EVM derives address = keccak256(rlp([sender, nonce]))[12:].
  3. New account nonce = 1, balance = value.
  4. Execute init code. Constructor runs.
  5. RETURN runtime bytecode.
  6. Charge 200 * len(runtime) gas.
  7. Store runtime as code.
CREATECREATE2
address inputsender, noncesender, salt, keccak256(init_code)
deterministicno, depends on nonceyes, if init code and salt fixed
nonce on failurerevertednot used
collisionaddress already used -> revertaddress already has code -> revert

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

How do Solidity custom errors differ from require string reverts across bytecode footprint, deployment and runtime gas, and ABI encoding?

Answer

What a strong candidate says first

Custom errors (Solidity 0.8.4+) are a first-class ABI type. Each one gets its own 4-byte selector, bytes4(keccak256("Unauthorized(address)")), and its arguments are ABI-encoded after it. A require(cond, "Unauthorized") instead compiles to the single built-in Error(string), whose selector is fixed at 0x08c379a0 for every string in every contract. That one difference drives the rest: the string path carries a literal in runtime code plus a dynamic-string encoder, so it costs more code, more deployment gas and more runtime gas, and off-chain it can only be decoded by string matching unless the client already knows the message.

Bytecode and deployment

The string literal lives in runtime bytecode, one byte per character, padded to a 32-byte boundary. On top of that, each revert site emits the encoder: push selector, push offset word, push length word, CODECOPY the literal, REVERT. For a 12-character message that is roughly 28 bytes of instructions plus 12 bytes of literal: about 40 bytes of runtime code. A parameterless custom error emits only the selector push and REVERT, about 11 bytes. At G_codedeposit = 200 gas/byte, that is roughly 8,000 gas to deploy versus 2,200: a saving of about 5,800 gas per distinct revert, and it scales with message length.

The limit that bites is EIP-170: runtime code is capped at 24,576 bytes. A contract with dozens of distinct revert strings can hit it; swapping them for custom errors is a standard fix.

Runtime gas

Trace both revert paths for the same 12-byte message, assuming a Shanghai-or-later target so PUSH0 (2 gas) is available; on older targets PUSH1 0x00 costs 3 gas and each total rises by a few gas. Memory expansion is 3a + a²/512 for a 32-byte words.

error Unauthorized();

OpGas
PUSH4 selector3
PUSH02
MSTORE (mem 1 word = 3)6
PUSH1 0x043
PUSH02
REVERT0
Total16

require(cond, "Unauthorized")

OpGas
PUSH4 0x08c379a03
PUSH02
MSTORE (mem 1 word)6
PUSH1 0x203
PUSH1 0x043
MSTORE (mem 2 words, +3)6
PUSH1 0x0c3
PUSH1 0x243
MSTORE (mem 3 words, +3)6
PUSH1 0x0c (length)3
PUSH1 code offset3
PUSH1 0x443
CODECOPY (3 + 3×1 word, mem 4 words +3)9
PUSH1 0x64 (size)3
PUSH02
REVERT0
Total58

So about 42 gas saved per revert for a 12-byte message. Longer messages add 3 gas per extra word of CODECOPY plus one byte of code each. The per-call saving is small; the deployment saving is the bigger number. require(cond) with no message is cheaper still: empty revert data, no memory write at all.

ABI encoding

Unauthorized(address) with caller 0x…:

[0x00..0x04]  4-byte selector
[0x04..0x24]  32-byte address, left-padded
Total: 36 bytes

Error(string) with "Unauthorized":

[0x00..0x04]  0x08c379a0
[0x04..0x24]  0x00000020  offset to string
[0x24..0x44]  0x0000000c  length = 12
[0x44..0x64]  "Unauthorized", left-aligned, right-zero-padded
Total: 100 bytes

The string form pays two extra words (offset and length) and pads to a word boundary; the custom error is tightly packed.

Off-chain

Custom errors appear in the ABI JSON as {"type":"error","name":"Unauthorized","inputs":[…]}. ethers v6 Interface.parseError(data) and viem decodeErrorResult({ abi, data }) match the selector and decode typed arguments, so you can branch on InsufficientBalance(available, required) without string parsing. Error(string) decodes universally, but only as a string.

Caveats

  • Custom errors need the ABI to decode; a client that only knows Error(string) sees opaque bytes.
  • assert failures revert with Panic(uint256) (0x4e487b71), not Error(string).
  • Since Solidity 0.8.26 you can write require(cond, Unauthorized()), so you no longer have to choose between require syntax and custom errors.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

How does the ERC-20 approve race condition enable double-spending, and how does EIP-2612 permit mitigate this through EIP-712 typed data signatures?

Answer

The standard ERC-20 approve(address spender, uint256 amount) overwrites allowance[owner][spender] directly. If an owner sets an initial allowance of $N$ and later submits a transaction to update it to $M$, a malicious spender observing the mempool can front-run the update with higher priority gas (transferFrom spending $N$). Once the owner's update transaction is mined, the allowance is set to $M$, allowing the spender to execute a second transferFrom for $M$, extracting $N + M$ tokens instead of the intended $M$.

Traditional mitigations either require setting the allowance to 0 before setting it to a new value (still vulnerable to front-running the zeroing tx, but caps exposure to $N$ total) or implementing non-standard helpers like increaseAllowance and decreaseAllowance. Both require multiple on-chain transactions paid by the token owner.

EIP-2612 resolves this using off-chain secp256k1 signatures validated via ecrecover under the EIP-712 typed data hashing standard. The signature authorizes the allowance change without the owner submitting a transaction or holding ETH for gas.

EIP-712 Domain Separator & Permit Layout

To prevent signature replay across contracts and chains, EIP-712 defines a strict domain separator:

DOMAIN_SEPARATOR = keccak256(
    abi.encode(
        keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
        keccak256(bytes(name)),
        keccak256(bytes(version)),
        block.chainid,
        address(this)
    )
)

The permit struct digest binds owner, spender, value, a per-owner monotonic nonce, and an expiration timestamp:

structHash = keccak256(
    abi.encode(
        keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"),
        owner,
        spender,
        value,
        nonces[owner]++,
        deadline
    )
)
digest = keccak256(abi.encodePacked("\x19\x01", DOMAIN_SEPARATOR, structHash))

Comparison: Standard Approve vs. EIP-2612 Permit

PropertyStandard approve (ERC-20)Permit via EIP-2612 (EIP-712)
Front-running vulnerabilityVulnerable to allowance overwrite race in mempoolImmune to double-spending; nonces enforce strict linear sequencing
Transaction initiatorMust be token owner (msg.sender)Any relayer, router, or spender contract
Gas sponsorshipToken owner must hold ETHRelayer/bundler pays gas; owner needs 0 native token
User flowTwo transactions (Approve then Swap/Deposit)Single transaction (permit + transfer bundled in router call)
Cross-chain replayN/A (transactions are on-chain)Prevented by dynamic/immutable block.chainid in domain separator

Critical Failure Modes and Production Risks

  1. Replay via Hardforks (block.chainid): Caching DOMAIN_SEPARATOR in an immutable variable permanently locks chainId. If the chain hardforks, signed permits can be replayed on the secondary fork. Production implementations must recompute the domain separator whenever block.chainid != CACHED_CHAIN_ID.
  2. Signature Malleability: Pre-EIP-2 ecrecover allows malleated $s$ values ($s > secp256k1n / 2$) or arbitrary $v \in {0, 1, 27, 28}$. Contracts must enforce low-$s$ values and reject invalid $v$ parameters to avoid duplicate signature submissions.
  3. Mempool Sniping of Relayed Permits: Anyone can extract the raw permit call from the mempool and submit it before a user's bundled transaction. While this increments the nonce and causes the bundled call to revert, it cannot alter the approved spender or steal tokens directly. Defend by using try/catch or allowance checks around permit calls inside aggregator routers.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Choose data locations for a function processing a user-supplied array.

Answer

Core answer (first 60–120 seconds)

Assume an external function on a Solidity 0.8.x contract, taking a uint256[] supplied by the caller, that reads the array, maybe transforms it, and persists a small result. The default is: declare the parameter calldata, use memory only when you must mutate or return the array, and write only the minimal durable result to storage after bounding the input length.

Why it behaves that way

calldata parameters of external functions are not copied: the ABI decoder hands the function a pointer into the transaction input, and xs[i] compiles to a CALLDATALOAD. A memory parameter is copied from calldata into a fresh memory region, and every internal call that passes a memory array copies it again. Storage is the only location that outlives the call, and it is the expensive one.

  • Calldata: 16 gas per non-zero byte, 4 per zero byte (EIP-2028). A uint256[1000] is 32,000 bytes → up to 512,000 gas before your code runs.
  • Memory expansion: 3*w + w²/512 gas, where w is words of 32 bytes. 1,000 words (32 KB) = 3,000 + 1,953 ≈ 4,953 gas. 10,000 words (320 KB) = 30,000 + 195,312 ≈ 225,312 gas: the quadratic term dominates.
  • Storage: a cold SSTORE setting a zero slot to non-zero is 20,000 gas (EIP-2929/2200). A warm SLOAD is 100 gas, cold 2,100. Clearing a slot refunds 4,800 (EIP-3529).

So one storage write costs ≈4× expanding memory to 32 KB and ≈200× a warm SLOAD.

Code

SOLIDITY
// Solidity 0.8.24
contract Batch {
    uint256 public total;                 // slot 0

    function sum(uint256[] calldata xs) external returns (uint256 s) {
        uint256 n = xs.length;
        require(n <= 256, "too long");    // bound before the loop
        for (uint256 i; i < n; ++i) {
            s += xs[i];                   // read straight from calldata
        }
        total = s;                        // one storage write
    }
}

Trace for xs = [1,2,3]: n = 3; the loop reads xs[0..2] from calldata with no memory allocated; s = 6; one SSTORE to slot 0. No memory expansion beyond the free 128 bytes.

Trade-offs

  • If you must sort or dedupe, copy once (uint256[] memory m = xs;) and work in memory: one copy beats repeated calldata indexing only when you touch elements many times.
  • storage pointers are right when updating an existing state array in place; they alias the state variable, so a write is a real state change.
  • memory is right for return values and internal helpers. stack holds value types, is capped at 1,024 slots, and DUP/SWAP reach only 16 deep, so deep locals spill.

Failure modes and detection

failuresymptomdetection
storage pointer aliasinga "read-only" path changes stateassert the slot is unchanged after the call; forge inspect / cast storage before and after
unbounded looptx reverts out-of-gas on large inputfuzz length up to 10,000; compare gas against the block gas limit (30M on mainnet for most of the post-London era)
needless memory copygas jumps with array sizegas snapshot per length; compare a calldata param against a memory param
memory expansiongas grows superlinearlyplot gas vs length; the quadratic term shows as a curve

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Integrate safely with a contract through its ABI.

Answer

An ABI is a claim about an interface, not a guarantee about behaviour. Integrating safely means binding every call to a specific (chainId, address, code) triple, pinning the ABI to the implementation you actually reviewed, encoding with canonical types, and treating the return value as untrusted bytes. Simulation and receipt checks exist to catch the gap between the ABI's promise and what the contract does.

1. Bind identity before you encode anything. The same address exists on many chains (CREATE2 deployers, deterministic deployments), so a call is only meaningful with a chainId. Assert the RPC's eth_chainId matches what you expect instead of trusting config. Then check eth_getCode is non-empty: an EOA, or an address that hasn't deployed yet, returns 0x, and a call to it succeeds with empty return data rather than failing.

2. Pin the ABI to the implementation, not the address. Behind a proxy, the code at the address is the proxy's, and it does not change when the implementation is upgraded. Hashing the proxy bytecode pins nothing useful. Read the implementation slot instead:

TypeScript
import { createPublicClient, http, getAddress } from 'viem'
import { mainnet } from 'viem/chains'

const client = createPublicClient({ chain: mainnet, transport: http() })
const PROXY = getAddress('0x…') // the address you call

const IMPL_SLOT = '0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc'
const raw = await client.getStorageAt({ address: PROXY, slot: IMPL_SLOT })
const impl = getAddress(`0x${raw!.slice(26)}`) // last 20 bytes of the word

Compare impl against the address whose ABI you reviewed. If it moved, your ABI is stale, and that is invisible from the proxy address alone. Confirm the proxy actually uses EIP-1967: USDC's FiatTokenProxy predates it and stores its implementation at its own slot, so a blind EIP-1967 read returns zero there.

3. Encode canonically. The selector is the first 4 bytes of keccak256 of the canonical signature: no spaces, no argument names, uint normalised to uint256. transfer(address,uint256) gives 0xa9059cbb (cast sig "transfer(address,uint256)"). Whitespace and argument names change the hash, so derive the signature from the ABI object rather than hand-writing the string.

4. Simulate, then validate the shape. eth_call at a pinned block catches reverts and bad arguments for free, but it does not catch a return that decodes to the wrong thing. Decode strictly and check length: USDT's transfer returns no data at all, so require(token.transfer(...)) reverts on a successful transfer. OpenZeppelin's SafeERC20 exists for exactly this. For state-changing calls, simulate at latest, then verify post-conditions (balance deltas) after inclusion, because state moves between the two.

FailureMechanismDetection
Selector collisionTwo canonical signatures share the first 4 bytes; a proxy fallback dispatches on the selector aloneQuery the 4byte directory for the selector; require a single match, or whitelist the exact signature
Stale ABIImplementation upgraded behind the proxy; the selector now runs different codeRe-read the implementation slot each call and compare to the pinned address
Wrong chain or addressSame address deployed on another chainAssert eth_chainId; bind address and chainId together
Malformed returnToken returns no data (USDT) or short dataCheck ret.length; strict decode; SafeERC20-style handling
Semantic driftSame selector, different meaning: a fee-on-transfer token returns true but delivers lessMeasure balance delta, not the return value
TOCTOUSimulated at block N, transaction lands at N+1Re-check post-conditions on-chain after inclusion

When full ABI pinning is the wrong tool. If the contract is intentionally upgradeable and you must follow upgrades, pinning the implementation breaks you on every upgrade: pin the proxy, whitelist the selectors you allow, and re-resolve the implementation per call, accepting that you now trust the upgrade admin. If you need one well-known value (a balance, a Chainlink price), use maintained typed bindings (viem's parseAbi, ethers v6 Interface, wagmi-generated hooks) rather than a hand-rolled ABI string; hand-rolled ABIs are where stale-ABI bugs live. And if the contract is unverified or you cannot validate its semantics, ABI integration is the wrong tool entirely: an ABI tells you the shape of a call, never its meaning. Put an adaptor contract you control in front of it, or don't integrate. For atomic multi-contract reads, Multicall3 at 0xcA11bde05977b3631167028862bE2a173976CA11 batches eth_calls at one block and removes the skew sequential reads introduce.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Redesign a contract that distributes rewards by looping over every member.

Answer

What I'd say first

Assume EVM L1, ERC-20 rewards, membership anywhere from hundreds to tens of thousands, and a member set that changes between rounds. The loop is the bug: gas is linear in member count, and a 30M block gas limit with roughly 50k gas per ERC-20 transfer to a fresh holder caps one transaction at about 600 recipients. Worse, it is all-or-nothing: once the set grows past the cap the transaction reverts and nobody is paid, so the distribution is permanently stuck.

So I'd replace it with one of two shapes.

Pull with a Merkle root (default for large or one-shot sets). Compute entitlements off-chain, build a Merkle tree, commit only the 32-byte root on-chain (one 20k-gas SSTORE). Each member claims with a proof. Cost per claim is O(log n) and independent of set size: a depth-20 proof is roughly 10-15k gas, dominated by calldata for the 20 sibling hashes, plus the ~50k transfer and a 20k SSTORE for the claimed flag. Call it ~85k, flat whether there are 1,000 or 1,000,000 members. Duplicate claims are blocked by a claimed[address] mapping. The distributor pays nothing per member; each claimant pays their own gas, which also removes griefing.

Bounded, resumable batches (when you need on-chain accounting, or the set is small and stable). Process a fixed N per transaction (say 100), store a cursor, and advance it only after the transfer succeeds. Invariant: the cursor is monotonic and total paid never exceeds the committed total. Each tx stays well under the block limit and you can resume after a failure.

Trade-offs / when each is wrong

Merkle pullBounded batches
cost per member~85k, paid by claimant~50k, paid by distributor
set sizeanybounded by N per tx
membership changesnapshot + new rootcursor must be reset
failureone bad proof fails one claimone reverting recipient can stall the batch

Merkle is wrong when the contract itself must hold and account for balances continuously, or when members won't claim: unclaimed funds sit forever, so add a sweep after a deadline. Batches are wrong for large sets or when the distributor can't pay gas, and a single recipient that reverts on receive (a contract that rejects tokens) blocks the whole batch unless you wrap each transfer in try/catch or skip-and-record.

Failure modes to check before shipping

  • Duplicate claims: claimed mapping, or a cursor advanced only on success.
  • Partial batch: never advance the cursor before the transfer; make the batch idempotent.
  • Changing membership: snapshot at a block and commit the root for that snapshot; late joiners are excluded by design.
  • Proof errors: double-hash leaves (keccak of keccak) to avoid second-preimage collisions, and verify the root on-chain.
  • Dust: entitlements below the ~50k transfer cost cost more to pay than they're worth. Accumulate them or set a minimum.
  • Unavailable data: the off-chain tree and leaf list must be published and pinned, or claims can't be constructed.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

Wrap an external token interaction safely.

Answer

Core answer

Assume the token address is not fully trusted: it's user-supplied, or sits behind a proxy that can be upgraded. The safe pattern: don't call IERC20(token).transfer(...) directly. Use OpenZeppelin's SafeERC20 (safeTransfer, safeTransferFrom, forceApprove), then verify the effect you actually care about, the balance delta, instead of trusting the return value.

Why: EIP-20 says transfer/transferFrom/approve return bool. Real tokens don't. USDT on Ethereum mainnet (0xdAC17F958D2ee523a2206206994597C13D831ec7) returns nothing from transfer. Since Solidity 0.4.22 the ABI decoder reverts when a bool-returning call returns empty data, so require(IERC20(usdt).transfer(to, amount)) reverts on every call. Other tokens return false instead of reverting; others return true and change nothing.

SOLIDITY
// Solidity 0.8.24, OpenZeppelin Contracts 5.0
using SafeERC20 for IERC20;

require(IERC20(usdt).transfer(to, amount)); // reverts: empty returndata
IERC20(usdt).safeTransfer(to, amount);       // empty => success, false => revert

SafeERC20 also checks the target has code before calling, so a token address that is an EOA or was self-destructed fails loudly instead of silently "succeeding".

Trade-offs

  • Raw low-level call with hand-rolled returndata handling: no dependency, full control, but you re-implement the empty-vs-false rule and the code check. Exactly where bugs live.
  • SafeERC20: reviewed, handles empty/false, and forceApprove sets allowance to 0 before setting it, which is what USDT's approve requires (it reverts on a nonzero-to-nonzero change). Cost: a dependency, and it normalizes signalling only. It cannot fix semantics.
  • Per-token adapters: needed when semantics genuinely differ. Rebasing tokens (stETH), fee-on-transfer, or non-standard approve. More code and audit surface, so only where the token set is known.
  • Wrapper unnecessary when the token is immutable and yours, or you've pinned a known-good implementation and can't be handed an arbitrary address.

Failure modes and detection

failuresymptomdetection
empty / false returnunexpected revert, or silent no-opSafeERC20; test against USDT and BNB
fee-on-transferbalance delta < amountassert delta == amount in tests, or credit the delta
reentrancy via transfer hooks (ERC-777)state read mid-transferreentrancy guard + checks-effects-interactions; trace the call stack
return bombOOG while decoding returndatacap the returndata read (OZ 5.x reads 32 bytes in assembly)
fake token returns trueno state changecheck balance delta, never the return value
proxy upgradebehavior changes after auditpin implementation, alert on Upgraded events

Fee-on-transfer trace: amount = 1000, token takes 2%. before = 5000, after safeTransferFrom = 5980, so received = 980. Credit 980, not 1000: crediting 1000 makes you insolvent by 20 per transfer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Evaluate transient storage for a reentrancy lock.

Answer

Short answer

Use transient storage for a reentrancy lock: it's the canonical EIP-1153 use case, live on Ethereum mainnet since Cancun (2024-03-13). The lock lives in a per-contract, per-transaction scratch area: TSTORE writes it, TLOAD reads it, and the whole area is discarded when the transaction ends. That lifetime (survives every call frame, dies at end of transaction) is exactly what a reentrancy guard needs, and it costs 100 gas per access instead of ~20,000 for an SSTORE.

Assumptions I'd state up front: the target chain has Cancun active; Solidity ≥0.8.24 for the assembly opcodes (≥0.8.28 for transient state variables); and you don't need the lock visible off-chain.

Mechanism

Transient storage is a separate address space from persistent storage, keyed by the executing contract's address. TSTORE and TLOAD cost 100 gas flat. Writes are journaled like regular storage, so they revert with the frame, but the area is cleared at end of transaction, not end of call frame. That's the property that makes it a lock: A sets slot 0, calls B, B calls back into A, and A's TLOAD(0) still returns 1.

SOLIDITY
// Solidity 0.8.24+, Cancun
contract Vault {
    uint256 private constant LOCK_SLOT = uint256(keccak256("vault.lock")); // not slot 0

    modifier nonReentrant() {
        assembly {
            if tload(LOCK_SLOT) { revert(0, 0) }
            tstore(LOCK_SLOT, 1)
        }
        _;
        assembly { tstore(LOCK_SLOT, 0) }
    }
}

You still reset on exit. Without the reset, a second sequential call in the same transaction sees the lock set and reverts: the guard becomes one-shot per transaction.

Cost vs a storage guard

stepSSTORE guardTSTORE guard
acquire (cold, 0→1)22,100100
release (1→0)2,900100
refund−4,800 (capped at gas_used/5)0
net per guarded call~20,200200

Roughly 20,000 gas saved per guarded call: about 10% of a 200k-gas swap.

Failure modes

  • Chain without Cancun. TSTORE is an invalid opcode, so every guarded call reverts. Detect with fork tests pinned to the target chain's EVM version and its hard-fork schedule; verify each L2 and alt-L1 separately rather than assuming mainnet's date.
  • Delegatecall sharing. Transient storage is keyed by the executing address, and under delegatecall that address is the caller. A library or implementation that TSTOREs slot 0 writes into the proxy's slot 0. If both use slot 0, the proxy sees "already locked" and reverts on the first call, or the library's reset clears the proxy's lock mid-call. Detect by grepping every delegatecall target for tstore/tload; give each a keccak-namespaced slot.
  • Static context. TSTORE is state-modifying, so a staticcall into a guarded function reverts. View functions can't take the lock.
  • Tooling. Older tracers don't decode TSTORE/TLOAD, and transient state never appears in storage proofs or most indexers. Check your tracer version; if you need off-chain visibility, use a storage guard.

When not to use it

If the lock must outlive the transaction (a global pause), be readable off-chain without a trace, or run on pre-Cancun chains, use a storage guard. It costs ~20k gas but is portable and visible.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-9

Secure a withdrawal flow against cross-function reentrancy.

Answer

Cross-function reentrancy is when an external call inside one function lets the callee re-enter a different function that reads or writes the same state. A guard on the one function you're worried about doesn't help: the attacker just calls the sibling. The fix is ordering, not a modifier: finish every state write the rest of the contract can observe before you hand control to anyone. Then add a contract-wide guard as a backstop, and prefer pull payments so the accounting path never makes an external call at all.

Assumptions I'd state up front: Solidity 0.8.x (checked arithmetic, so an underflow reverts instead of wrapping) and OpenZeppelin 5.x.

SOLIDITY
// Solidity 0.8.24, OpenZeppelin 5.x
contract Vault {
    mapping(address => uint256) public shares;
    uint256 public totalShares;
    uint256 public totalAssets;

    // VULNERABLE: totalAssets is written after the external call
    function withdraw(uint256 amount) external {
        uint256 assets = amount * totalAssets / totalShares;
        require(shares[msg.sender] >= amount, "insufficient");
        shares[msg.sender] -= amount;
        totalShares -= amount;
        (bool ok,) = msg.sender.call{value: assets}("");   // control leaves here
        require(ok, "transfer failed");
        totalAssets -= assets;                              // too late
    }

    function redeem(uint256 amount) external returns (uint256 assets) {
        assets = amount * totalAssets / totalShares;        // reads the stale price
        shares[msg.sender] -= amount;
        totalShares -= amount;
        totalAssets -= assets;
        (bool ok,) = msg.sender.call{value: assets}("");
        require(ok, "transfer failed");
    }
}

Trace it with two attacker accounts (A, B) and one honest depositor (C):

  • Start: totalAssets = 150, totalShares = 150 (A 50, B 50, C 50). Price is 1 asset per share.
  • A.withdraw(50): assets = 50 * 150 / 150 = 50. shares[A] → 0, totalShares → 100. totalAssets is still 150. The external call fires.
  • A's callback calls B.redeem(50): assets = 50 * 150 / 100 = 75. shares[B] → 0, totalShares → 50, totalAssets → 75. B receives 75.
  • Control returns to A.withdraw: totalAssets -= 50 → 25.
  • End: totalShares = 50 (all C), totalAssets = 25. The attacker received 50 + 75 = 125 for 100 shares; C's 50 shares are now backed by 25 assets. 25 assets stolen.

The fix is one line moved: decrement totalAssets before the call, so B.redeem sees 100 / 100 and pays a fair 50. Add nonReentrant (OpenZeppelin ReentrancyGuard) to every state-mutating entry point (withdraw, redeem, transfer, deposit) not just withdraw, because a per-function guard leaves the sibling open.

failurewhat happenshow you catch it
cross-function reentrancysibling entry point reads a half-updated priceFoundry invariant asserting totalAssets == sum of redeemable at all times, plus a malicious callback contract in tests
guard deadlocka guarded function calls another guarded function on the same contract and revertsunit-test the composed path; OZ 5.x reverts with ReentrancyGuardReentrantCall
stuck funds on failed pusha reverting receiver rolls back the whole withdrawaltest a withdrawal to a contract that reverts; prefer pull
read-only reentrancyan integrator's view (convertToAssets) returns an inflated price mid-callbackcall your own view from inside the attacker callback and assert it matches the pre-call value
token hooksERC-777 / ERC-1155 / ERC-721 safeTransferFrom call back into youtest with a hook-bearing token, not a plain ERC-20

Trade-off between the two defenses: CEI costs nothing but is fragile. A later refactor that adds a state write after the call silently reopens the hole. A contract-wide guard costs a storage write on entry and another on exit (thousands of gas, not hundreds; OpenZeppelin's transient-storage variant uses EIP-1153 TSTORE/TLOAD at 100 gas each on Cancun chains). Guard scope decides what breaks: per-function guards miss cross-function, while a contract-wide guard blocks legitimate internal composition. A batch function that calls withdraw internally now reverts. So: CEI first, contract-wide guard as backstop, and pull payments wherever the accounting path can avoid the external call entirely.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Review arithmetic in an asset-accounting contract.

Answer

What I'd say first

Assume the contract converts between an asset token and vault shares (ERC-4626-shaped), and that the review is about the conversion math, not the token's own accounting. The core rule: every conversion rounds in the vault's favour, and every multiplication that can overflow goes through a 512-bit intermediate. If those two hold, most of the rest is bookkeeping.

Why ordering and rounding matter

shares = assets * totalSupply / totalAssets is the conversion. Two things break it.

Divide first and you lose precision before you scale: with assets = 999, totalAssets = 1000, totalSupply = 1000, assets / totalAssets * totalSupply is 0 * 1000 = 0 shares. The depositor gets nothing. Multiply first gives 999 * 1000 / 1000 = 999. So multiply before divide.

Multiply first and you can overflow: a * b reverts when the product exceeds 2**256 - 1 (≈1.1579e77). Solidity 0.8 checks that by default and reverts with Panic(0x11). The fix is a full-precision mulDiv that computes a * b / c with a 512-bit intermediate (OpenZeppelin Math.mulDiv), so the only failure left is a final result that doesn't fit in uint256.

Rounding direction is not a style choice: ERC-4626 fixes it: convertToShares, convertToAssets, previewDeposit and previewRedeem round down; previewMint and previewWithdraw round up. The invariant behind it: the user never gets more value out than they put in, so rounding dust accrues to the vault, not the depositor.

Code

SOLIDITY
// Solidity 0.8.x, OpenZeppelin Math
function convertToShares(uint256 assets, uint256 totalAssets, uint256 totalSupply)
    internal pure returns (uint256)
{
    // round down: floor(assets * totalSupply / totalAssets)
    return Math.mulDiv(assets, totalSupply, totalAssets);
}

function convertToAssets(uint256 shares, uint256 totalAssets, uint256 totalSupply)
    internal pure returns (uint256)
{
    return Math.mulDiv(shares, totalAssets, totalSupply);
}

Math.mulDiv reverts on c == 0 and on a result that overflows uint256; it does not silently wrap.

Where unchecked is justified

unchecked removes the overflow check and lets arithmetic wrap mod 2**256. It is justified only when a state invariant proves the bound: e.g. a counter that can never exceed MAX_SUPPLY enforced at mint. Division by zero still reverts inside unchecked (Panic(0x12)), so that is not a reason to use it. The cost of checked math is a handful of gas per operation; the cost of a wrong unchecked is a wrapped balance. Default to checked.

Failure modes to hunt

  • Truncating casts. uint128(x) drops the high bits silently: explicit conversions between integers are not checked in 0.8. A balance that fits in uint256 but not uint128 loses value with no revert.
  • Decimal mismatch. Asset and share decimals differ (USDC 6, shares 18). A raw ratio without scaling is off by 1e12.
  • First-depositor inflation. Attacker deposits 1 wei, donates assets directly to the vault, so the next depositor's shares round to zero. Mitigate with a virtual-shares offset (_decimalsOffset) or a seeded minimum.
  • Cumulative leakage. Rounding the wrong way on every operation drains the vault over many calls; a single call looks fine. Check with an invariant test: sum of user claims <= totalAssets after a fuzz sequence.

How I'd verify

Fuzz the conversion with totalAssets and totalSupply near their bounds, assert convertToAssets(convertToShares(a)) <= a, and assert the vault's asset balance covers totalSupply at all times.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Optimize storage without damaging maintainability.

Answer

Assumptions: EVM target, Solidity 0.8.x, post-Cancun gas schedule (EIP-1153 active), mainnet.

Core answer (first 90 seconds). The only expensive state is persistent storage. An SSTORE that sets a zero slot to nonzero costs 20,000 gas; changing an existing nonzero value costs 2,900; a stack write costs 3 and a transient write 100. So the whole optimization is: keep in storage only what a contract must read during a transaction, pack values that share a 32-byte slot, and push everything else to events or off-chain views. Maintainability survives if you never hand-pack across slot boundaries and never reorder storage in an upgradeable contract.

Why the numbers are what they are. Persistent storage is the replicated state trie: every full node keeps it forever, so it is priced to discourage growth. Stack, memory, calldata and transient storage are per-transaction and discarded. Logs go to receipts, not state: LOG1 with 32 bytes of data is 375 + 375 + 8×32 = 1,006 gas, roughly 20× cheaper than a fresh SSTORE, but no contract can read it.

Slot packing. Each slot is 32 bytes. Solidity packs state variables and struct members in declaration order, so three fields that fit in 256 bits share one SSTORE.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

contract Packed {
    struct Order {
        uint128 amount;  // slot 0, bytes 0-15
        uint64  expiry;  // slot 0, bytes 16-23
        uint64  nonce;   // slot 0, bytes 24-31
    }
    Order public order;

    function set(uint128 a, uint64 e, uint64 n) external {
        order = Order(a, e, n);   // one SSTORE to slot 0
    }
}

Trace: set(1, 2, 3) on a fresh contract. Slot 0 is cold, so 2,100 (cold access) + 20,000 (zero→nonzero) = 22,100 gas for the write. The same three fields as separate uint256s would be three slots: 22,100 for the first, then 20,000 each for the two warm writes = 62,100. Packing saves 40,000 gas per order: at 20 gwei, 0.0008 ETH.

Failure modes.

  • Hand-rolled bit packing (|, masks, shifts) silently corrupts on a wrong mask; let the compiler pack, and if you must pack manually, test the boundary values.
  • Upgrade layout damage: inserting a variable shifts every later slot. Use storage gaps and a layout validator (OpenZeppelin Upgrades) before every upgrade.
  • Stale cached aggregates: a stored running total drifts from the source of truth. Derive it, or emit events and index off-chain.
  • Gas schedule changes: EIP-2929 (cold/warm), EIP-3529 (refund capped at 1/5 of tx gas), EIP-1153 (transient). Never hardcode gas in contract logic.

Decision rule. Contract reads it in a tx → storage. Only off-chain consumers need it → event. Needed only within one tx → transient storage. Cheaply recomputable → derive.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Use counterfactual addresses without creating an address-authentication flaw.

Answer

The 90-second answer. A CREATE2 address commits to exactly three things: the deploying contract, a 32-byte salt, and keccak256(initcode). It commits to nothing else, not the chain, not the runtime code, not the owner. So "authentication" is not a property of the address; it is a property of what you bind into those three inputs and what you verify after deployment. In practice: pin the factory address per chain, derive the salt from the account parameters you actually care about, and check the deployed runtime code hash before you let value move. If you cannot make the initcode deterministic, do not use a counterfactual address.

Mechanism. EIP-1014 defines the address as:

keccak256(0xff ++ deployer ++ salt ++ keccak256(initcode))[12:]

Two consequences follow directly. First, the initcode hash is inside the preimage, so an attacker who changes a constructor argument, say the owner, produces a different address. That is why binding the exact initcode hash prevents substitution. Second, chainid is not in the preimage, so the same factory at the same address with the same salt yields the same address on every chain. The address is chain-agnostic by construction; you have to enforce the chain yourself. The EIP-2470 singleton factory at 0xce0042B868300000d44A59004Da54A005ffdcf9f exists at one address on many chains for exactly this reason.

What the initcode hash does not pin is the runtime code. Initcode is arbitrary EVM, so it can read external state and return different runtime bytecode for the same hash. That is the metamorphic contract: deploy, SELFDESTRUCT, redeploy different runtime code at the same address. EIP-6780 (Cancun, March 2024) removed the code-deletion path except when SELFDESTRUCT runs in the same transaction as creation, which kills the classic two-transaction version on chains that adopted it. On chains that have not, the risk is live.

Address derivation, checkable:

SOLIDITY
// solidity 0.8.24
function create2Address(address deployer, bytes32 salt, bytes memory initCode)
    pure returns (address)
{
    return address(uint160(uint256(
        keccak256(abi.encodePacked(bytes1(0xff), deployer, salt, keccak256(initCode)))
    )));
}

Failure modes and how you catch them:

failuremechanismdetection
wrong chainno chainid in the preimagerequire(block.chainid == expected) before funding; confirm the factory has code on that chain
wrong factorydifferent deployer, similar-looking addresspin the factory address per chain; compare factory.codehash
initcode driftfactory changes salt derivation or constructor argsrecompute the address off-chain from the pinned initcode and compare before sending
metamorphicinitcode returns state-dependent runtime codecompare keccak256(addr.code) to the expected runtime hash after deploy
front-run deployattacker deploys the same initcode first; if ownership derives from msg.sender, they own itinitcode must not derive ownership from msg.sender/tx.origin; read the owner after deploy
prefund lossvalue sent to an address that never deploysverify the factory is deployed on the target chain; fund through the EntryPoint deposit instead

Trade-off. Counterfactual deployment buys you one address across chains and the ability to fund an account before it has gas: that is the ERC-4337 flow, where the EntryPoint (v0.6 at 0x5FF137D4b0FDCD49DcA30c7CF57E578a026d2789) deploys the account from initCode on first use. The cost is that every consumer must verify deployment. The alternative (deploy first, then fund) is simpler and removes the prefund and front-run classes entirely, but the user needs gas up front and you lose address portability. Choose counterfactual only when the initcode is fully deterministic and you control the factory.

What changes the decision: if the target chain predates EIP-6780, treat the runtime code as mutable and re-verify the codehash on every interaction, not just at deploy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Threat-model a delegatecall-based plugin architecture.

Answer

Clarify first. "Plugin architecture" is ambiguous, so I'll pin it: a host contract that delegatecalls into separately deployed plugin contracts, so plugin code runs against the host's storage and address. The trust model is the whole question. If plugins are third-party and unaudited, the answer is "don't": see the trade-off table. If they're first-party and reviewed, the job is to make storage and authority boundaries explicit.

Core answer. DELEGATECALL (EIP-7) executes the callee's code with the caller's context: address(this), msg.sender, msg.value, balance, and storage all belong to the host. Only the code is the plugin's. That one fact generates every hazard: a plugin can write any host slot, call out as the host, and, if it holds upgrade authority, replace itself. So the threat model is storage corruption, privilege escalation, selector collision, implementation replacement or destruction, and initializer front-running.

Storage collision, concretely. Solidity lays state variables out sequentially from slot 0. Host:

SOLIDITY
contract Host {
    address public owner;   // slot 0
    bool public paused;     // slot 1
}
contract Plugin {
    uint256 public amount;  // slot 0 — same slot as owner
}

A plugin writing amount = 1 overwrites owner. This is why EIP-1967 puts proxy bookkeeping at pseudo-random slots (implementation at 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, admin at 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103) so ordinary variables can't collide. For plugins the equivalent is namespaced storage: a struct at keccak256("host.plugin.storage"), or diamond storage (EIP-2535). Detect collisions with solc --storage-layout diffs and OpenZeppelin's validateUpgrade in CI.

Trade-offs. Four patterns, different trust assumptions:

patternstorageupgradeuse when
UUPS proxyone impl, EIP-1967 slotupgrade fn in implsingle instance, you control impl
Transparent proxyone impl, admin routingadmin-onlyyou want admin/impl selector separation
Beaconmany proxies, one beaconupgrade beaconmany instances of the same logic
Diamond/facetsshared, diamond storageadd/replace facetsmany functions, modular
CALL-based pluginplugin owns its storageindependentplugin is untrusted

The deciding criterion is trust and storage ownership. If the plugin must not touch host storage, don't delegatecall: call it normally (CALL) and have it return data the host validates. Delegatecall hands the plugin the host's authority; there is no sandbox.

Failure modes and detection. Initializer front-running: proxies can't run constructors, so implementations use initialize(); if it isn't called in the same transaction as deployment, an attacker calls it first and becomes owner. Fix: call it in the proxy constructor, or use OpenZeppelin Initializable. Selector collision: in a diamond, two facets registering the same selector. Check facets() in CI. Implementation destruction: pre-Cancun, selfdestruct in an implementation bricked every proxy pointing at it; EIP-6780 (Cancun, 2024) removes code only in the same transaction as creation, so the residual risk is upgrade-authority compromise. Mitigate with a timelock plus multisig, and verify the implementation address on-chain after every upgrade.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Deploy and initialize an upgradeable contract safely.

Answer

Assumptions: Solidity 0.8.24, OpenZeppelin Contracts Upgradeable v5, a UUPS proxy deployed through the Hardhat @openzeppelin/hardhat-upgrades plugin. Transparent proxies differ only in where the upgrade logic lives and in the admin slot; the initialization discipline is the same.

Core answer

Deploy the implementation, lock it so nobody can initialize it directly, then deploy the proxy and run initialize in the same transaction as the proxy's construction. Verify owner and roles by reading them back from the proxy address, never from the implementation. There must be no window in which the proxy exists but is uninitialized.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;

import {Initializable} from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol";
import {UUPSUpgradeable} from "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol";
import {OwnableUpgradeable} from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol";

contract VaultV1 is Initializable, OwnableUpgradeable, UUPSUpgradeable {
    uint256 public totalDeposits;

    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() {
        _disableInitializers(); // locks the implementation's own storage
    }

    function initialize(address owner_) external initializer {
        __Ownable_init(owner_);
        __UUPSUpgradeable_init();
    }

    function _authorizeUpgrade(address) internal override onlyOwner {}
}
JavaScript
const proxy = await upgrades.deployProxy(VaultV1, [owner.address], {
  kind: "uups",
  initializer: "initialize",
});
await proxy.waitForDeployment();

What the deploy transaction actually does

  1. Implementation I is deployed. Its constructor runs _disableInitializers(), writing _initialized = type(uint64).max into I's own slot 0.
  2. Proxy P is deployed with constructor calldata initialize(owner). The proxy constructor writes the EIP-1967 implementation slot 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc = I, then delegatecalls that calldata.
  3. The delegatecall runs I's code against P's storage. The initializer modifier sees P's _initialized == 0, sets it to 1, runs __Ownable_init(owner) (P's owner slot = owner), then clears _initializing.
  4. Read back: P.owner() == owner, P.totalDeposits() == 0. I's storage still shows _initialized = max.

Why the two hazards exist

Uninitialized proxy. If you deploy the proxy and call initialize in a separate transaction, anyone watching the mempool can front-run with initialize(attacker) and become owner. Atomic init calldata removes the window entirely.

Uninitialized implementation. Without _disableInitializers(), an attacker calls initialize directly on I and owns it. That is not directly exploitable against P, the proxy's storage is separate, but it is the Parity multisig failure: the attacker-owned library was then selfdestructed, bricking every proxy delegating to it. EIP-6780 (Dencun, March 2024) restricts SELFDESTRUCT to same-transaction-as-creation, which blunts that specific bricking, but locking the implementation is still the correct default.

Storage collisions. The proxy keeps implementation and admin pointers in EIP-1967 pseudo-random slots precisely so they do not collide with the implementation's slot-0 variables. A hand-rolled proxy that stores the implementation at slot 0 will collide with the first state variable of the implementation. On upgrades, storage is append-only: adding variables is safe, inserting or reordering is not.

Trade-offs: UUPS vs Transparent

UUPSTransparent
Upgrade logicIn the implementation (_authorizeUpgrade)In the proxy
Deploy costLower (smaller proxy)Higher
Admin vs user callsNo dispatch distinctionAdmin address cannot call implementation functions
Bricking riskDeploying an implementation without UUPSUpgradeable freezes upgradesNone

Pick UUPS when deploy cost matters and you control the upgrade path; pick Transparent when you want upgrade logic isolated from implementation code.

Failure modes and detection

HazardMechanismDetection
Front-run initProxy deployed uninitializedAssert owner() right after deployProxy
Re-initializationinitialize missing initializer, or V2 without reinitializer(2)Call initialize twice in a test; second must revert
Wrong adminTransparent admin set to zero or a contract that cannot callRead EIP-1967 admin slot 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103
Partial migrationUpgrade inserts/reorders storageupgrades.validateUpgrade storage-layout diff
Missing parent init__Ownable_init never calledowner() == address(0) after deploy

For V2, use reinitializer(2) rather than initializer so the migration runs exactly once and only after V1.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Review the storage safety of a proxy upgrade.

Answer

Storage safety of a proxy upgrade is one invariant: for every slot the new implementation reads, the bytes there must mean what the old implementation wrote. The proxy's address and balance survive the upgrade; the storage does not get migrated, so the layout is a permanent interface between versions.

Concretely: diff the two storage layouts, require that every variable present in V1 keeps its slot, offset and type in V2, and require that new variables are appended after the last V1 slot or consume a reserved __gap. Then fork-test the upgrade against real state.

The artefact

Foundry prints the layout:

$ forge inspect VaultV1 storage-layout
| Name  | Type    | Slot | Offset | Bytes |
|-------|---------|------|--------|-------|
| owner | address | 0    | 0      | 20    |
| total | uint256 | 1    | 0      | 32    |

forge inspect VaultV2 storage-layout --json gives the same data machine-readable, so the diff runs in CI and fails the PR rather than the deploy. OpenZeppelin's upgradeable base contracts reserve uint256[N] private __gap; at the end of their storage so a later version of the base can add variables by shrinking the gap instead of shifting every derived contract's slots.

Worked trace: the classic miss

V1 declares address owner (slot 0) and uint256 total (slot 1). A V2 that inserts uint256 fee between them lands as owner slot 0, fee slot 1, total slot 2. Upgrade a proxy whose slot 1 holds total = 1_000e18. After the upgrade fee() returns 1_000e18, it is reading the old total, and total() returns 0, because slot 2 was never written. No revert, no event, just wrong numbers. Appending fee after total (slot 2) keeps both correct.

Trade-offs

  • In-place upgrade vs migration. Migration (deploy V2, copy state, move balances) frees you to change layout arbitrarily, but you must enumerate the state to copy: impossible for a mapping with unbounded keys, and expensive for large arrays. In-place upgrade keeps the address and all storage, at the cost of layout discipline forever. If the contract holds a handful of scalars, migration is often cheaper than a lifetime of layout constraints; if it holds user balances in mappings, in-place is the only realistic option.
  • UUPS vs transparent. UUPS puts the upgrade function in the implementation: the proxy is smaller and cheaper to deploy, but every implementation must keep _upgradeTo and _authorizeUpgrade correct. Drop it in one version and the proxy is permanently unupgradeable. Transparent keeps upgrade logic in the proxy and blocks the admin from calling implementation functions, avoiding selector clashes, at the cost of a bigger proxy and an admin check on every call.
  • Beacon. One implementation address shared by many proxies; upgrade once and every instance changes. Right for many identical per-user instances, wrong when a bad upgrade would hit all of them at once.

Failure modes and how I detect them

  • Slot collision or shifted variable: caught by the forge inspect diff and by OpenZeppelin's validateUpgrade (Hardhat/Foundry plugin), which rejects any change to an existing variable's slot, offset or type.
  • Changed interpretation: uint128 a; uint128 b becoming uint256 a keeps slot 0 but re-reads the packed halves as one number. The diff must compare types, not just slot numbers.
  • Mapping or array reinterpretation: mapping(address => uint256) becoming mapping(uint256 => uint256) in the same slot leaves every entry unreachable, since the data lives at keccak256(key . slot). Same slot, different hash.
  • Initializer reuse: V2's initialize() callable a second time re-runs setup, re-assigning owner. Guard with initializer/reinitializer(n) and assert in a fork test that a second call reverts.
  • Uninitialized implementation: call initialize() directly on the implementation address; if it succeeds, _disableInitializers() is missing from its constructor.
  • Rollback: after V2 writes slot 2, rolling back to V1 makes total() read slot 1 again, which still holds the pre-upgrade value; V2's write is orphaned. Run the rollback in the same fork test and check the numbers rather than assuming it.

The proxy's own bookkeeping lives at fixed EIP-1967 slots (implementation at 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, admin at 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103) so sequential-layout implementations never reach them, but hand-written sstore or namespaced (ERC-7201) storage must be checked for collisions explicitly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Build a reproducible contract deployment pipeline.

Answer

Core answer (first 90 seconds)

Ask two things before touching anything: does the address need to be stable across chains and redeploys, and who holds the init/upgrade authority? Those decide CREATE vs CREATE2 and whether initialization is a separate transaction.

Reproducibility means the initcode is byte-identical. Everything that feeds it must be pinned: compiler version and settings, dependency commit hashes, library addresses, constructor arguments, and the metadata hash. Then you verify the runtime bytecode that actually lands, not the source you think you compiled.

Mechanism

Address derivation is why nonce tracking is fragile. CREATE: address = keccak256(rlp([sender, nonce]))[12:]. The nonce is per-account and increments on every transaction, including reverted ones, so any stray tx from the deployer key shifts every later address. CREATE2 (EIP-1014): address = keccak256(0xff ++ deployer ++ salt ++ keccak256(initcode))[12:]. No nonce, so the address is computable before broadcast, but it now depends on the initcode hash, so a one-byte metadata change moves the address.

Metadata: solc appends a CBOR blob to runtime bytecode containing the IPFS hash of the metadata JSON, which includes source paths and settings. Two builds from the same source in different directories produce different bytecode. Set metadata.bytecodeHash = "none" (or --no-cbor-metadata) when you need byte-identical output; keep it when you want source verification.

Libraries: external libraries are linked as __$<34 hex>$__ placeholders. Link different library addresses on two chains and the runtime differs, and so does the CREATE2 address.

Trade-offs

CREATE2 + factory: predictable address, same address on every chain, redeployable after selfdestruct (pre-Cancun). Cost: you deploy and trust the factory, and the address is coupled to initcode. Raw CREATE: simpler, no factory, but the address depends on nonce. Fine for a one-shot deploy, bad for multi-chain parity.

Failure modes and detection

  • Wrong chain: assert chainId in the deploy script against the expected value before broadcast.
  • Wrong nonce: precompute the CREATE address and compare to the receipt's contractAddress; a mismatch means a stray tx consumed a nonce.
  • Metadata drift: hash the runtime bytecode and compare to a recorded digest; a diff shows the CBOR tail.
  • Uninitialized proxy: after deploy, read the EIP-1967 implementation slot (0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) and the initialized flag; a zero slot means init never ran.
  • Code size: EIP-170 caps runtime at 24576 bytes; EIP-3860 caps initcode at 49152. Check eth_getCode length and the deploy tx gas.
  • Gas: a creation that runs out of gas still consumes the nonce.

Artefact: worked address check

Deployer 0x…ab, nonce 7. rlp([0x…ab, 7]) = 0xd6 94 <20 bytes> 07. Take keccak256 of that and keep the last 20 bytes; compare to receipt.contractAddress. For CREATE2, hash 0xff ++ factory ++ salt ++ keccak256(initcode) and compare the same way, if it disagrees, the initcode hash changed, usually metadata or a library address.

Pinning settings (solc 0.8.24, standard JSON)

JSON
{
  "language": "Solidity",
  "settings": {
    "optimizer": { "enabled": true, "runs": 200 },
    "evmVersion": "cancun",
    "metadata": { "bytecodeHash": "none" },
    "libraries": { "src/Lib.sol:Lib": "0x…linked" }
  }
}

Record the resulting runtime keccak256 in the release notes; that digest, not the source tag, is what you verify on-chain.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Test a protocol integration against a chain fork.

Answer

The 90-second answer. A fork test executes your contract against a copy of real deployed state at one pinned block. In Foundry that is forge test --fork-url $RPC --fork-block-number 18000000, or vm.createSelectFork(rpc, 18000000) in setUp. The client does not download the chain: it lazily fetches only the accounts and storage slots your test touches (eth_getCode, eth_getStorageAt, eth_getBalance) and caches them in memory for the run. Everything else follows from that one fact. Pin the block so the state root is fixed and the run reproduces; keep the touched set small so you don't exhaust the RPC.

State the assumptions before writing a line: the integration depends on a deployed contract whose real bytecode and storage layout matter; the test must reproduce in CI; and the dependency sits behind a proxy that can upgrade after your pin.

The artefact.

SOLIDITY
// Foundry 1.x, forge-std
uint256 constant PIN = 18_000_000;
bytes32 constant ERC1967_IMPL_SLOT =
    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

function setUp() public {
    vm.createSelectFork(vm.envString("MAINNET_RPC"), PIN);
    // Fail loudly if the dependency upgraded after the pin.
    assertEq(
        uint256(vm.load(USDC, ERC1967_IMPL_SLOT)),
        uint256(EXPECTED_USDC_IMPL),
        "USDC implementation changed since pinned block"
    );
}

function testSwap() public {
    address whale = 0x...;            // a real holder at the pinned block
    uint256 before = usdc.balanceOf(whale);
    vm.startPrank(whale);             // impersonation needs no private key
    usdc.approve(address(pool), 1_000_000e6);
    pool.swap(...);
    vm.stopPrank();
    assertEq(usdc.balanceOf(whale), before - 1_000_000e6);
}

vm.startPrank sets msg.sender for subsequent calls; vm.prank does it for one call only. Neither needs the key: that is the point of impersonation. It does not fake tx.origin, so a dependency that checks msg.sender == tx.origin behaves differently under a fork than in production.

Trade-off.

forked mainnetmocked contractstestnet
fidelityreal bytecode + storage at block Nyour mockreal chain, your deploys
speed~5–50 ms/test once cached; first run pays RPCsub-msseconds per tx
determinismfixed by the pinned blocktotalnone: other actors
catchesreal integration, real storage layoutyour own logicdeployment + live consensus
blind tomempool/MEV, post-pin upgradesthe dependency entirelyreal liquidity, real oracles

Failure modes, with detection.

  • Stale snapshot. The pin is months old and the dependency has since upgraded. Detect: assert the proxy's implementation slot (or codehash) at test start, as above. Cost: green CI, broken prod.
  • Hidden RPC dependency. Passes locally against a cached fork, fails in CI with no MAINNET_RPC, or gets rate-limited. Detect: run CI with a cold cache and count calls. A test touching 5 accounts is roughly 15–30 calls, one iterating a 500-holder list is 1,500+. Cost: flaky or silently skipped tests.
  • Non-reproducible archive access. Geth keeps ~128 recent states by default and free RPC tiers serve only recent blocks, so pinning an older block needs an archive endpoint. Detect: assert the fork block is inside the provider's archive window, or pin an archive URL. Cost: works on your machine, 404s in CI.
  • Assuming future compatibility. Fork at N, dependency upgrades at N+1. Detect: re-run with the new implementation vm.etched in. Cost: you ship against an interface that no longer exists.
  • Unrealistic liquidity. deal mints tokens that don't exist, so a swap that would move the real pool 40% moves the fork 0.1%. Detect: compare fork reserves to the real pool at that block and assert slippage. Cost: you never see the price impact that kills you.
  • Accidental live submission. forge script --broadcast pointed at a mainnet RPC. Detect: assert block.chainid and that the URL is a fork; never load a real key in a fork test. Cost: real funds.

When a fork is the wrong tool. Pure logic belongs in unit tests. Anything that depends on mempool ordering or MEV cannot be reproduced by a fork. And for a dependency that upgrades, your pin is a claim about the past, not the future: re-run against the new implementation or you are testing a contract that no longer exists.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Use formal verification for an asset invariant.

Answer

Assumptions. Concrete case: an ERC-20-style token whose asset invariant is conservation of supply. sum(balances) == totalSupply, and no single balance exceeds it. State machine: mint, burn, transfer. A collateralised vault has a different invariant (collateral ≥ debt × price); the method is identical.

Answer. Write the invariant as a predicate over state, encode the state machine in a spec language, and let a model checker try to falsify it. TLA+ with TLC is the default here: the spec is a few dozen lines and TLC returns a counterexample trace rather than a yes/no.

TLA
---- MODULE Token ----
EXTENDS Integers
CONSTANT Accounts, MAX_SUPPLY
VARIABLES balance, totalSupply

TypeOK == /\ balance \in [Accounts -> 0..MAX_SUPPLY]
          /\ totalSupply \in 0..MAX_SUPPLY

SupplyInv == /\ totalSupply = Sum(balance)
             /\ \A a \in Accounts: balance[a] <= totalSupply

Init == /\ balance = [a \in Accounts |-> 0]
        /\ totalSupply = 0

Mint(to, amt) ==
  /\ amt > 0 /\ totalSupply + amt <= MAX_SUPPLY
  /\ balance' = [balance EXCEPT ![to] = @ + amt]
  /\ totalSupply' = totalSupply + amt

Burn(from, amt) ==
  /\ amt > 0 /\ balance[from] >= amt
  /\ balance' = [balance EXCEPT ![from] = @ - amt]
  /\ totalSupply' = totalSupply - amt

Transfer(from, to, amt) ==
  /\ from # to /\ amt > 0 /\ balance[from] >= amt
  /\ balance' = [balance EXCEPT ![from] = @ - amt, ![to] = @ + amt]
  /\ UNCHANGED totalSupply

Next == \E a, b \in Accounts, amt \in 1..MAX_SUPPLY:
          Mint(a, amt) \/ Burn(a, amt) \/ Transfer(a, b, amt)

Spec == Init /\ [][Next]_<<balance, totalSupply>>
====

Sum is a five-line recursive operator over the finite Accounts set; TLA+ has no builtin.

The trace that matters. Delete totalSupply' = totalSupply - amt from Burn: debit the holder, forget the counter. TLC returns:

State 1: balance = [alice |-> 0, bob |-> 0],   totalSupply = 0
State 2: Mint(alice, 100)
         balance = [alice |-> 100, bob |-> 0], totalSupply = 100
State 3: Burn(alice, 30)
         balance = [alice |-> 70,  bob |-> 0], totalSupply = 100
Invariant SupplyInv is violated.

Balances sum to 70, totalSupply is 100. Three states, milliseconds. That trace is the deliverable: it names the action, the arguments and the state, so the fix is unambiguous.

Cost, and when not to. With 3 accounts and MAX_SUPPLY = 100 the reachable state space is the count of non-negative triples summing to at most 100: C(103,3) ≈ 1.8×10^5, and TLC finishes instantly. Ten accounts at MAX_SUPPLY = 10^6 does not terminate; that is the state-explosion wall, and it is where you change tools.

approachprovescostreach for it when
TLC (explicit state)every reachable state of a finite modelminutes to write, seconds to rundesign-level invariant, small state
Apalache (SMT/Z3)symbolic, bounded or inductiveneeds an inductive invariant hintstate space too big for TLC
Dafny, Coq, Leanthe algorithm, all inputsdays to weeks, a proof engineerarithmetic-heavy core: rounding, interest
Certora Prover (CVL)deployed EVM bytecode against a specper-rule SMT timeoutsyou must close the model-to-bytecode gap
Foundry invariant_*, Echidnadeployed contract, stateful fuzzinghours, no proofcheap first pass; catches most real bugs

Skip the proof when a type or a database constraint already enforces the invariant, or when the state space is small enough that exhaustive testing covers it. A proof of a model nobody deploys is worse than a fuzz run against the bytecode.

Failure modes, with detection.

  • Proving the wrong property. The invariant is vacuously true because the guard is unsatisfiable. Detect by mutating the spec: delete the totalSupply update above and confirm TLC fails. A spec that survives mutation testing tests nothing.
  • Solver timeout. SMT-backed tools return unknown, not false. Treat unknown as unverified, never as a pass, and surface the timeout in CI output.
  • Unsupported semantics. TLC cannot evaluate unbounded quantifiers or real arithmetic; it warns and skips. A skipped conjunct is an unproven conjunct.
  • Environment mismatch. The model assumes one action at a time; the deployed contract is reentrant. Write the model's assumptions down and diff them against the real call graph.
  • False confidence. The proof covers the model, not the compiler or the EVM. Pair it with a bytecode-level tool or an invariant fuzz run.

Governance. Name an owner for the invariant, wire the check into CI so a spec change that breaks it fails the build, and decide in advance what a violation triggers: pause, circuit breaker, or alert.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design invariants for a multi-user financial contract.

Answer

Assumptions. A pool contract: users deposit an ERC-20, borrow against it, and get liquidated. Multi-user, behind an upgradeable proxy, one price oracle. Solidity 0.8.24, Foundry invariant testing.

Core answer. Four invariants, each a one-line assertion that must hold in every reachable state:

  1. Conservation: the sum of user balances equals totalDeposits. No value is created or destroyed.
  2. Solvency: totalAssets >= totalDebt. The pool can always cover what it owes.
  3. Authorization: no state change without the actor's consent: only the owner pauses, only the borrower moves their own collateral.
  4. Monotonicity: a user's debt only grows except on an explicit repayment; a paused pool stays paused until unpaused.

Then the actor model: N actors, each able to call deposit/withdraw/borrow/repay/liquidate with bounded amounts, plus one malicious actor whose callback reenters.

SOLIDITY
// Foundry invariant test — Solidity 0.8.24
contract Handler is Test {
    Pool pool;
    address[] public actors;
    uint256 public ghost_sumBalances; // reference model, updated only here
    uint256 seed;

    function deposit(uint256 amt) public {
        amt = bound(amt, 1, 1e24);
        address a = actors[seed++ % actors.length];
        pool.deposit(a, amt);
        ghost_sumBalances += amt;
    }

    function withdraw(uint256 amt) public {
        address a = actors[seed++ % actors.length];
        amt = bound(amt, 0, pool.balanceOf(a));
        pool.withdraw(a, amt);
        ghost_sumBalances -= amt;
    }
}

contract PoolInvariants is StdInvariant, Test {
    Pool pool; Handler handler;

    function setUp() public {
        pool = new Pool();
        handler = new Handler(pool);
        targetContract(address(handler));
    }

    function invariant_conservation() public view {
        assertEq(pool.sumBalances(), handler.ghost_sumBalances());
    }

    function invariant_solvency() public view {
        assertGe(pool.totalAssets(), pool.totalDebt());
    }
}

Why these catch what. Conservation catches reentrancy and double-counting. Trace it: three users deposit 100, 250, 50, so ghost_sumBalances = 400 and pool.sumBalances() = 400. An attacker calls withdraw(100); the callback reenters and credits the user twice, so the contract's balance sum reads 500 while the ghost still says 400: the assertion fires on the next sequence. Solvency catches oracle manipulation and bad liquidation math: a stale price lets a liquidator seize more collateral than the debt, and totalAssets drops below totalDebt. Monotonicity catches upgrade bugs where a new implementation resets a mapping: the ghost records the last observed debt per actor and only the handler's repay path lowers it.

Trade-offs.

ApproachCatchesCostUse when
Foundry / Echidna fuzz invariantsstate-dependent bugs across sequenceshours to write, minutes per rundefault for any pool with real TVL
Certora Prover (formal)all inputs, given a specweeks of spec work, five-figure engagementcore accounting, upgradeable proxies
Manual auditdesign and economic attacks1–3 weeksbefore mainnet, alongside the above

Fuzz invariants are cheap and find most sequence bugs; formal verification is worth it only where a single missed case is catastrophic and the accounting is small enough to specify. A 200-line contract with no TVL needs neither: a fuzz suite plus an audit is enough.

Failure modes. A weak generator never reaches liquidation because the handler only deposits small amounts: check per-selector call coverage in the Foundry report. A ghost updated from contract state instead of intended semantics passes while storage is corrupt: mutate the contract, add a bug, and confirm the invariant fails. Fork tests are nondeterministic as blocks advance: pin the block number. An invariant that can never be violated because the handler cannot reach the state is dead weight: verify reachability with coverage, not by assuming it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design contract administration for high-value operations.

Answer

Core answer

Assume "high-value" means the contract controls funds or authority worth more than the cost of a compromised key: a treasury, a proxy upgrade, a mint, or a parameter that moves user funds. The design that survives review separates three things, who may call, what they may do, and how long a change takes to land.

Authorize on msg.sender against an explicit role, never on tx.origin. Put upgrades and large transfers behind an M-of-N multisig (Safe) plus a timelock (OpenZeppelin TimelockController) so one compromised key cannot execute alone and a malicious change is visible before it lands. Keep a separate, narrow emergency role that can pause but not move funds or upgrade, with no timelock. Emit an event on every grant, revoke and privileged call.

Why msg.sender, traced

tx.origin is the EOA that started the transaction; msg.sender is the immediate caller. They diverge under any nested call.

  1. Victim EOA signs a call to attacker contract A (disguised as a legit dapp).
  2. A.foo() runs and calls Vault.withdraw().
  3. Inside Vault, msg.sender == address(A), tx.origin == victim.
  4. A require(tx.origin == owner) check passes; funds go to A.

So the check must be on the immediate caller:

SOLIDITY
// Solidity ^0.8.20
modifier onlyOwner() {
    require(msg.sender == owner, "not owner"); // never tx.origin
    _;
}

Trade-offs

Timelock delay is the main dial. 48h on upgrades gives users time to exit and reviewers time to catch a malicious proposal, but it also means a live exploit cannot be patched for 48h. That is why the pause guardian exists: it can halt in one block, and only governance can unpause and upgrade. Don't put the pause behind the timelock.

Multisig threshold: 3-of-5 is the common floor for a treasury; 5-of-9 for upgrade authority. Higher thresholds raise key-loss risk: with 5-of-9, losing 5 keys freezes the contract permanently. Pick the threshold so both "attacker needs k keys" and "we can lose N-k keys" are acceptable.

When not to use a timelock: emergency response, oracle-failure pause, or any role whose value is measured in seconds.

Failure modes and detection

failuredetection
tx.origin phishingSlither tx-origin detector; grep auth paths for tx.origin
compromised admin keyalert on RoleGranted/OwnershipTransferred from an unexpected signer (Defender Sentinel)
stale rolesscheduled enumeration of RoleGranted/RoleRevoked; quarterly access review
unsafe renunciationafter any revoke, assert the admin role still has ≥1 holder
governance capturemonitor voting-power concentration and quorum; alert when one holder crosses quorum
alternate entry pointenumerate every external state-changing function; fuzz each against the role check
lost keyskey-custody audit; geographic and hardware separation of signers

What would change the decision

If the contract is immutable and holds no funds, most of this is overhead: a single owner is fine. If it is upgradeable and holds a treasury, the timelock and multisig are the minimum. If the team cannot staff 24/7 monitoring, a longer timelock substitutes for detection.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Handle a secret-dependent workflow on a public chain.

Answer

Assume an EVM chain (Ethereum mainnet or an L2) with a public mempool, no trusted hardware, and an adversary who reads all state and mempool and can pay for front-running. Under those assumptions, you cannot keep a secret on a public chain. Every storage slot, calldata byte, and event log is public and permanent. So the workflow must either keep the secret off-chain entirely, or accept that it becomes public after a delay. For delayed disclosure, commit-reveal with a blinding factor is the standard pattern.

Why blinding works: commit = keccak256(secret, blinding, msg.sender). Without blinding, an attacker who sees the commit can brute-force a low-entropy secret. Example: a 4-digit PIN has 10,000 candidates. On a modern laptop, 10,000 keccak256 hashes take well under a millisecond. With a 256-bit random blinding nonce, the search space is 2^256, so the commit reveals nothing. The blinding must come from a CSPRNG and stay secret until reveal.

Typed domains: use EIP-712 to bind the commit to a specific contract and chain ID. Without it, a commit from one auction can be replayed in another. The EIP-712 domain separator includes chainId and verifyingContract.

Deadlines and deposits: commit phase ends at block N; reveal phase runs from N+1 to N+M. A deposit (e.g., 0.1 ETH) is forfeited if the participant fails to reveal. This makes withholding costly. Missing-reveal behavior must be explicit: either the deposit is slashed to the auctioneer, or refunded to other participants, depending on who is harmed.

Worked flow (sealed-bid auction):

  1. Bidder computes nonce = random 32 bytes, commitment = keccak256(abi.encodePacked(bid, nonce, bidder)).
  2. Sends commit transaction with deposit.
  3. After commit deadline, bidder sends reveal transaction with bid and nonce. Contract verifies hash matches and bidder is msg.sender.
  4. If no reveal by reveal deadline, deposit is slashed.

Solidity snippet (checked against Solidity 0.8.20):

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.20;

contract SealedBidAuction {
    mapping(address => bytes32) public commitments;
    mapping(address => bool) public hasCommitted;
    mapping(address => uint256) public deposits;
    uint256 public commitDeadline;
    uint256 public revealDeadline;

    function commit(bytes32 commitment) external payable {
        require(block.timestamp < commitDeadline, "commit closed");
        require(!hasCommitted[msg.sender], "already committed");
        commitments[msg.sender] = commitment;
        hasCommitted[msg.sender] = true;
        deposits[msg.sender] = msg.value;
    }

    function reveal(uint256 bid, bytes32 nonce) external {
        require(block.timestamp >= commitDeadline && block.timestamp < revealDeadline, "reveal closed");
        bytes32 c = keccak256(abi.encodePacked(bid, nonce, msg.sender));
        require(c == commitments[msg.sender], "bad reveal");
        // ... record bid
    }

    function slash(address bidder) external {
        require(block.timestamp >= revealDeadline, "too early");
        require(hasCommitted[bidder], "no commit");
        // deposit forfeited
    }
}

Failure modes and detection:

  • Dictionary attack: attacker sees commit and tries all plausible secrets. Detect by checking if your secret space is small (< 2^80). Mitigate with blinding.
  • Metadata leakage: transaction graph, timing, gas price. Detect with chain analysis tools (e.g., Etherscan labels, Dune). Mitigate with relayers or privacy pools.
  • Front-running: reveal transaction in mempool can be copied. Detect by observing pending txs. Mitigate with commit-reveal (already) or Flashbots.
  • Withheld reveal: participant doesn't reveal to grief. Detect by missed deadline. Mitigate with deposit slashing.
  • Lost secret: user loses nonce. Detect by support tickets. No on-chain recovery; the deposit is lost.
  • Permanent ciphertext exposure: if you store encrypted data on-chain, it's forever. Detect by historical state. Mitigate by never storing ciphertext on-chain.

Trade-offs:

  • Off-chain secret + on-chain signature (EIP-712): no on-chain secrecy, but one round, no deposit. Fails if you need the chain to enforce the secret's use without a trusted party.
  • Commit-reveal: temporary secrecy, two rounds, deposit. Fails if the secret must remain secret forever, or if reveal can be front-run (mitigate with commit-reveal itself).
  • Threshold encryption (e.g., Shutter): not mainstream, adds trust assumptions.

What would change the decision: if the chain provides a trusted execution environment or threshold encryption with a decentralized committee, you could keep the secret on-chain until a condition. But those are not default and have their own failure modes.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do you protect smart contracts against frontrunning, sandwich attacks, and MEV extraction at the contract logic level?

Answer

The 90-second answer

You cannot control transaction ordering from inside a contract: the builder does that. So contract-level MEV defence reduces to two moves: make execution independent of where your transaction lands in the block, or bound the value an orderer can extract. Three patterns cover most of it: bound the outcome (slippage + deadline), hide the intent (commit-reveal), remove the ordering advantage (batch auction at a uniform clearing price). Everything else (private orderflow, PBS, builder auctions) is off-chain. Assume EVM, public mempool, post-merge.

1. Bound the outcome: slippage and deadline

For any stateful price, the user passes minAmountOut and deadline; the contract checks the actual received amount, not the quoted price:

SOLIDITY
uint256 out = _swap(amountIn);
require(out >= minAmountOut, "slippage");
require(block.timestamp <= deadline, "expired");

minAmountOut is the attacker's profit ceiling, and that is the whole defence. Worked example, labelled assumptions: a $50,000 swap with 0.5% tolerance lets a sandwicher move price 0.5% and take ~$250 gross; two txs at 180k gas and 20 gwei cost 0.0072 ETH ≈ $24 at $3,300/ETH, so net ≈ $226. Tighten tolerance to 0.1% and the ceiling drops to ~$50: barely above gas. The deadline does not bound profit; it only stops a pending tx being held and executed against a stale price.

Failure modes: minAmountOut supplied by an untrusted frontend (set it to 0 and the check is decorative); a deadline in seconds, since the proposer controls block.timestamp within a small drift. Use minutes.

2. Hide the intent: commit-reveal

Two phases in different blocks. The hash must bind msg.sender, or a searcher copies your calldata and lands it first.

SOLIDITY
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;

contract CommitRevealAuction {
    struct Commitment { bytes32 hash; uint256 deposit; bool revealed; }
    uint64 public immutable commitDeadline;
    uint64 public immutable revealDeadline;
    uint256 public constant MIN_BID = 0.1 ether;
    mapping(address => Commitment) public commitments;
    mapping(address => uint256) public bids;

    constructor(uint64 c, uint64 r) { commitDeadline = c; revealDeadline = r; }

    function commit(bytes32 h) external payable {
        require(block.number <= commitDeadline, "commit closed");
        require(commitments[msg.sender].hash == bytes32(0), "already committed");
        require(msg.value >= MIN_BID, "deposit below minimum");
        commitments[msg.sender] = Commitment(h, msg.value, false);
    }

    function reveal(uint256 bid, bytes32 salt) external {
        require(block.number > commitDeadline && block.number <= revealDeadline, "not in reveal window");
        Commitment storage c = commitments[msg.sender];
        require(c.hash != bytes32(0) && !c.revealed, "no commit or already revealed");
        require(keccak256(abi.encode(bid, salt, msg.sender)) == c.hash, "hash mismatch");
        require(bid <= c.deposit, "bid exceeds deposit");
        c.revealed = true;
        bids[msg.sender] = bid;
    }
    // settlement and refunds omitted
}

Trace: Alice commits keccak256(abi.encode(5 ether, 0xabc…, alice)) at block 100 with a 5 ETH deposit; commitDeadline = 200, revealDeadline = 210. At block 205 she calls reveal(5 ether, 0xabc…). The contract recomputes the hash with msg.sender == alice, matches, 5 ether <= 5 ether passes, bids[alice] = 5 ether. A searcher replaying Alice's calldata gets msg.sender == searcher, so the recomputed hash differs and the call reverts.

Residual leak: the reveal phase is public. If Bob committed earlier with a hash he can still open, he watches block 205 and reveals 5.001 ETH in block 206. Fix: make the reveal window a single block, or use threshold encryption so no reveal is needed. Second failure: a bidder commits and never reveals, blocking settlement. Charge the deposit as forfeit. Use abi.encode, not abi.encodePacked: packed encoding is ambiguous once any field is dynamic.

3. Remove the ordering advantage: batch auctions

Accumulate orders over a window, then settle all of them in one transaction at a uniform clearing price. No order inside the batch is better than another, so there is nothing to frontrun. The residual is cross-venue: if the clearing price is predictable, a searcher can trade on another DEX ahead of settlement. That is outside your contract.

4. Oracle reads

If your contract prices from a pool, a single-block spot read is the attack surface. Use a TWAP over a window long enough that holding the manipulated price costs more than the profit. Uniswap v3 requires increaseObservationCardinalityNext first: with low cardinality the window silently shortens and one block is enough.

PatternThreat it boundsCostFailure mode to check
minAmountOut + deadlineAMM sandwichReverts on volatility; user must price off-chainminAmountOut from an untrusted frontend; deadline in seconds
Commit-revealGeneralized frontrunning, sealed auctionsTwo txs, delayed UXmsg.sender missing from the preimage; public reveal phase lets the last revealer win
Batch auction / uniform clearing priceSequential-execution advantageLatency; needs a settlement keeperCross-venue arb against a predictable clearing price
TWAP oracleSingle-block price manipulationLags real priceobservationCardinality too low, so the window is shorter than intended
EIP-2612 permitERC-20 approve raceRequires a signature flowNonce replay if the domain separator is wrong

What contract logic cannot fix

Private orderflow (Flashbots Protect), builder/PBS ordering, and censorship are off-chain. Contract patterns bound extraction; they do not eliminate it.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-1

Design a contract feature that depends on an external real-world value.

Answer

Core answer (first 90 seconds)

Assume an EVM chain, a lending contract that liquidates when collateral value falls below a threshold, and a Chainlink push feed as the price source. The design rule is that the external value enters the contract exactly once, as an on-chain transaction, and every state transition reads it from storage: never from an off-chain call. That is what makes execution deterministic: validators replay the same committed transaction against the same storage, so they all see the same price. An HTTP call inside execution can't be replayed, which is why it can't be the source.

Concretely: the contract stores an immutable feed address and a maxStaleness. A read() function calls latestRoundData(), rejects answer <= 0, and reverts if block.timestamp - updatedAt > maxStaleness. maxStaleness is the feed's heartbeat plus a buffer: ETH/USD on Ethereum mainnet has a 3600s heartbeat and a 0.5% deviation threshold, so I'd set 3900s. Decimals come from feed.decimals(), not a hardcoded 8.

The contract

SOLIDITY
// Solidity ^0.8.20
interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData() external view returns (
        uint256 roundId, int256 answer, uint256 startedAt,
        uint256 updatedAt, uint256 answeredInRound);
}

contract PriceGuard {
    AggregatorV3Interface public immutable feed;
    uint256 public immutable maxStaleness; // seconds
    uint8 public immutable feedDecimals;

    error StalePrice(uint256 updatedAt);
    error InvalidPrice(int256 answer);

    constructor(AggregatorV3Interface _feed, uint256 _maxStaleness) {
        feed = _feed;
        maxStaleness = _maxStaleness;
        feedDecimals = _feed.decimals();
    }

    function read() public view returns (int256) {
        (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
        if (answer <= 0) revert InvalidPrice(answer);
        if (block.timestamp - updatedAt > maxStaleness) revert StalePrice(updatedAt);
        return answer;
    }
}

answeredInRound is deprecated on OCR2 feeds, so don't gate on it. Read decimals() once in the constructor and store it; a hardcoded 8 against an 18-decimal feed is a 10^10 mispricing.

Trace and arithmetic

ETH/USD returns 8 decimals, so $3000 is 3000_00000000 = 3e11. Collateral 10 ETH, debt $20,000, liquidation at 80% LTV. The trigger price solves 20000 / (10 * P) = 0.8, so P = $2500: a 16.7% drop. Because the feed only publishes on a 0.5% deviation, the liquidation fires at $2500 ± 0.5%, roughly ±$12.50. That band is the slippage on your trigger, and it's why you size the buffer rather than assume the feed is exact.

Alternatives, and when each is right

Push (Chainlink) is right when many contracts read the same value and you want cheap reads: the oracle pays the update gas, you pay nothing per read, at the cost of heartbeat latency. Pull (Pyth-style signed updates) is right when you need sub-second freshness and few readers: the caller submits the signed price in the same transaction, so you verify the signature and read it atomically. Fresher, but every caller pays and you must handle the update path. A DEX spot price is the wrong choice for anything liquidatable: it's flash-loanable in one block. If you need a DEX-derived value, use a time-weighted average over at least 30 minutes.

Failure modes, detection, cost

failuremechanismdetectioncost
stale priceheartbeat missed, updatedAt lagsalert when lag > heartbeat; read() revertsliquidations blocked, bad debt accrues
manipulationspot price moved in one blockcompare to a second source, alert on >2% deviationundercollateralized loans
decimals mismatchhardcoded 8 vs 18-decimal feedunit test asserting feed.decimals()10^10 mispricing
feed deprecationChainlink retires the aggregatormonitor the proxy's aggregator addressreads revert, protocol frozen
replay on L2signed update replayed on another chainchainId inside the signed payloaddouble-counted price

Governance and dispute

Staleness reverting is a pause, not a liquidation freeze: you need a guardian that can halt new borrows while leaving repayments open, and a timelock on maxStaleness and feed-address changes so a compromised admin can't swap the feed in one block. For disputes, record the roundId and updatedAt you read in the liquidation event; that's the evidence a disputer checks against the feed's history.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Operate an off-chain service around a smart contract.

Answer

Core answer (first ~90 seconds)

Assume Ethereum mainnet, a contract emitting events that drive off-chain state (balances, orders, payouts), and a service that must never double-pay or credit an orphaned block. Treat the chain as an append-only log with a reorgable tail: make every off-chain write idempotent and reversible until its block is finalized, and only then let it trigger irreversible work.

Concretely: ingest logs with eth_getLogs, key every row on (chain_id, block_hash, tx_hash, log_index), store the block hash next to the effect, and mark an effect irreversible only once its block is at or below the finalized tag. Indexes and UI caches are derived views rebuilt from those canonical rows: they may lag or follow an orphan, and that is fine because they are not the source of truth.

Mechanism

Ingestion: poll eth_getLogs over [lastProcessed+1, head] in bounded ranges, because providers cap the span (Alchemy documents 10k logs and a 2k-block range per call). Persist block_number, block_hash, tx_hash, log_index and the decoded payload. A unique constraint on those four columns makes replay a no-op: that is the idempotency, not application-level dedup.

Reorgs: a reorg replaces blocks by hash, not by number. Each poll, compare the stored block_hash for the last N blocks against the canonical hash from eth_getBlockByNumber. On a mismatch, delete or tombstone every effect whose block_hash is no longer canonical, rewind lastProcessed to the fork point, and re-ingest. Because effects are keyed by hash, reversal is a delete, not a compensating transaction.

Finality: post-Merge, finalized sits 2 epochs back. 64 slots × 12 s ≈ 12.8 min, and safe is ~1 epoch ≈ 6.4 min. Gate irreversible work (payouts, minting, external API calls) on finalized. The legacy "12 confirmations" heuristic is ~2.4 min and does not guarantee finality.

TagDepthLatencyUse
latest0~0UI preview only
safe~1 epoch~6.4 minsoft credit
finalized2 epochs~12.8 minirreversible effects

Failure modes and detection

  • Missed range: a gap in lastProcessed. Alert when head - lastProcessed exceeds a threshold and when ingested block numbers are non-contiguous.
  • Duplicate logs: a unique-constraint violation count above zero means an upstream bug, not normal replay.
  • Provider disagreement: query two RPC endpoints and compare block_hash at the same height; a mismatch means one is stale or on a fork.
  • ABI upgrade: store the ABI version per decoded row and pin it by block range. A decode failure after an upgrade is loud; a silent mis-decode is not, so version the decoder.
  • Stale allowance / partial off-chain effect: each finalized block, reconcile on-chain balance against the sum of off-chain effects; drift is the alarm.

Trade-off

Waiting for finalized costs ~12.8 min of latency versus acting on latest. For payments that is the right price; for a read-only dashboard it is not, so split the two paths rather than picking one depth for everything.

Curated: · Written: · Reviewed:

Difficulty: Hard