Skip to content
Tech Interview Prep
Technical interview guide

Web3 Development Tooling & Testing

The frameworks, testing practices, and node infrastructure a blockchain developer actually uses day to day.

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

Scope: Solidity compiler and security documentation; Hardhat 3; Foundry Forge; ethers v6; EIP-1193; EIP-712; Sourcify verification guidance reviewed 2026-09-04.

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-2

Review a production compiler configuration.

Answer

What a strong candidate says first

A compiler configuration review is a reproducibility review with a safety check bolted on. The deliverable is one sentence: given the pinned source, can I rebuild the exact deployed bytecode, and is that bytecode within limits and free of known compiler bugs? Everything else is detail.

So I start from the deployed artifact, not the repo. I pull the runtime bytecode, read the CBOR metadata appended to its tail, and reconstruct the build from what that metadata commits to: compiler version, EVM version, optimizer settings, source hashes. Then I rebuild and diff byte-for-byte. If the diff is empty, the configuration is reproducible; if it isn't, I have a source-mismatch finding before I've read a single line of Solidity.

The settings that decide the bytecode

settingdefaultwhat it changes
solc versionnone: must be pinnedopcodes emitted, exposure to known bugs
evmVersiontracks solc (0.8.20 → shanghai, 0.8.25 → cancun)which opcodes are legal: PUSH0, MCOPY, TSTORE
optimizer.enabledfalsegas and size
optimizer.runs200 when enabledper-call gas vs. deployed size
viaIRfalsecodegen path; different bytecode entirely
metadata.bytecodeHashipfsappends a hash; changes the CREATE2 address
debug.revertStringsdefaultrevert-data size
TOML
# foundry.toml — pinned and checked in
[profile.default]
solc = "0.8.25"        # exact, not ^0.8.25
evm_version = "cancun"
optimizer = true
optimizer_runs = 200
via_ir = false
bytecode_hash = "ipfs"

The trade-off I have to decide

optimizer.runs is the optimizer's guess at how often each function is called over the contract's life. High runs spend more effort on hot paths: cheaper calls, bigger bytecode. Low runs: smaller bytecode, cheaper deploy, more expensive calls. The default 200 leans toward deployment cost. The deciding criterion is call frequency against the EIP-170 ceiling of 24576 bytes of runtime code.

Hypothetical, but the shape is real: at runs = 200 a contract compiles to 22 KB and a swap costs 45k gas; at runs = 10000 it compiles to 26 KB (over the limit, deployment reverts) and the swap costs 43k. So for a contract called millions of times I raise runs and claw back size elsewhere; for a one-shot deploy near the ceiling I drop runs. viaIR is the other lever, but it changes codegen and compile time, so I only reach for it deliberately.

Failure modes and how I catch each

  • Unsupported opcode. evmVersion newer than the target chain's hardfork. Symptom: deploy or call reverts on that chain only. Detection: compare evmVersion against the target's hardfork. PUSH0 on a pre-Shanghai L2 is the classic miss.
  • Optimizer bug. Version-specific. Detection: check the pinned version against the Solidity known-bugs list at soliditylang.org/bugs and read the compiler's own warnings.
  • Source mismatch. Verified source doesn't reproduce the deployed bytecode. Detection: rebuild and diff; a metadata-hash mismatch is the tell.
  • Size limit. Runtime bytecode over 24576 bytes. Detection: forge build --sizes, or measure eth_getCode length.
  • Gas regression. A settings change raises call cost. Detection: gas-snapshot diff in CI.
  • Local-CI divergence. Different solc binary or version locally vs. CI. Detection: pin the exact version in both and compare bytecode hashes.
  • Debug build. Optimizer off, or revertStrings: debug shipped. Detection: metadata shows the optimizer disabled, and revert strings are present in the runtime code.

How I run it

Fetch deployed bytecode and extract metadata; rebuild from pinned source and settings; diff byte-for-byte; check size and the known-bugs list; record the settings hash alongside the release. The configuration is part of the reviewed executable artifact, so it ships with the same sign-off as the source.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Build a reproducible contract compilation pipeline.

Answer

Core answer, first 90 seconds. "Reproducible" has a precise meaning here: the same compilation input produces byte-identical creation and runtime bytecode on any machine, at any time. The input is not the .sol files: it is the whole standard JSON: source contents, source unit names, remappings, compiler version, optimizer settings, EVM version, library addresses, and metadata settings. Change any one and the bytecode changes.

Assumptions I'd state up front: Solidity 0.8.x, one build tool (Foundry or Hardhat), and CI that can do a clean build. If you only need to verify an already-deployed contract, you don't need this pipeline: you need its metadata.

The pipeline, in order.

  1. Pin the compiler by version and checksum. solc 0.8.26, fetched from solc-bin with its sha256 verified. Foundry: solc_version = "0.8.26" in foundry.toml (svm downloads it). Hardhat: solidity: { version: "0.8.26" }. Never ^0.8.0 in the pragma, never latest.
  2. Pin settings explicitly: optimizer.enabled = true, optimizer.runs = 200, evmVersion = "cancun", metadata.bytecodeHash = "none". The evmVersion default moves between releases: 0.8.25 defaults to shanghai, 0.8.26 to cancun, so leaving it unset makes the build compiler-version-dependent.
  3. Build the standard JSON input deterministically: sorted source keys, normalized remappings, absolute paths stripped.
  4. Compile: solc --standard-json < input.json > output.json.
  5. Compare contracts.<file>.<name>.evm.bytecode.object (creation) and .deployedBytecode.object (runtime) against a committed hash.
  6. Retain the full input and output JSON as CI artifacts.

Why bytecode differs: the mechanism. solc appends a CBOR blob to the end of the runtime bytecode holding the metadata hash (IPFS by default). The metadata JSON includes source paths, remappings, settings, and the compiler version string. So renaming a file or changing a remapping changes the hash and therefore the bytecode, even when the source is identical. bytecodeHash = "none" removes the blob, making the comparison about code rather than paths, but it also breaks Etherscan/Sourcify verification. That is the trade-off.

Alternatives.

  • Compare full bytecode including metadata: strongest guarantee, but any path change breaks it.
  • Strip metadata and compare: robust to path churn, weaker. You can miss a metadata-only difference that matters for verification.
  • Docker image ethereum/solc:0.8.26 vs an svm-downloaded binary: Docker pins the whole toolchain, svm pins only solc. Docker is heavier but removes host-toolchain drift.

Failure modes and how each is detected.

failuredetection
floating compilerrecord solc --version in the artifact; CI fails when it differs from the pinned string
optimizer driftbytecode diff after a settings change; assert runs inside the input hash
metadata differencestrip the CBOR and compare, or set bytecodeHash = "none"
hidden generated sourcehash the full standard JSON input, not the .sol tree
library link mismatchcompare linkReferences placeholders (__$…$__)
stale artifactsforge build --force, or a clean checkout in CI

The deciding criterion throughout: compare the input hash first, because it localizes the failure, then the bytecode, because it is the thing you actually ship.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Manage a contract toolchain supply chain.

Answer

I'd treat the contract toolchain as three supply chains: the schema compiler and its plugins (protoc, buf, openapi-generator, quicktype), the schema registry (Buf Schema Registry, Pact Broker), and the generated artifacts (clients, stubs, contract tests). My default: pin exact versions, commit lockfiles, run codegen in CI with --locked/--frozen-lockfile, verify integrity, and make every update a reviewed PR. The trade-off is staleness and review fatigue, so I loosen only for dev-only tools with automerge after CI.

Assumptions: production codegen feeds a release; schemas are in git; CI is the only path to artifacts. If codegen is local-only, I'd still pin but allow faster updates.

Core mechanism: a lockfile is a hash-pinned graph. npm ci refuses if package.json and package-lock.json disagree; npm install will update the lockfile if a range allows. That is the lockfile bypass: a floating ^1.2.3 in package.json plus npm install can pull a new transitive version between review and release. pip install --require-hashes forces every dependency to have a hash; without it, pip resolves at install time. go mod verify checks go.sum SHA-256; cargo build --locked fails if Cargo.lock needs changes. For contract tooling, pin protoc and plugins exactly: buf.gen.yaml remote plugins like buf.build/protocolbuffers/go:v1.31.0, or a local protoc-gen-go version. Pin openapi-generator-cli to a Docker tag, e.g. openapitools/openapi-generator-cli:v7.4.0. Run buf breaking --against '.git#branch=main' and oasdiff breaking to catch schema breaks before codegen.

Integrity verification detects a compromised package by comparing the tarball hash to the lockfile integrity field (sha512 for npm) or a registry signature. npm audit signatures verifies npm registry signatures; cosign verify-blob and slsa-verifier verify-artifact verify provenance at SLSA Build Level 3. If a maintainer publishes a new version, the lockfile pins the old one, so the new version only enters through a lockfile diff. That diff is the review point.

Failure modes and detection:

FailureHow it shows upDetectionCost
Malicious packageNew transitive dep in lockfile diffnpm audit signatures, osv-scanner, cosign verifyBlocks release until review
Compromised maintainerNew version of pinned toolLockfile diff in PR, cargo vet, OpenSSF ScorecardManual review, delay
Lifecycle scriptpostinstall in new depnpm ci --ignore-scripts, audit scriptsBreaks packages needing build
TyposquatName close to protoc-gen-gonpm ls, pip-audit, socket.devFalse positives
Lockfile bypassCI uses npm installgit diff --exit-code package-lock.json, npm ciCI fails
Unreviewed transitive updateLockfile diffnpm ls --all, cargo treeReview fatigue
Abandoned toolingNo release in 18 monthsnpm view <pkg> time.modified, ScorecardMigration cost

Trade-offs: pinning exact versions means security patches don't arrive automatically; stale pinned revisions can miss fixes. Review fatigue is real: every Renovate PR manual. Criteria to loosen: dev-only, no codegen, no production artifact. Use Renovate rangeStrategy=pin, minimumReleaseAge 3 days, automerge after CI and npm audit signatures. For production codegen, pin exact and require two-person review. For abandoned tooling, set a threshold: no release in 18 months or Scorecard maintenance score below 5 triggers a migration plan.

Operational test:

Shell
npm ci --ignore-scripts
npm audit signatures
pip install --require-hashes -r requirements.txt
go mod verify
cargo build --locked
buf lint
buf breaking --against '.git#branch=main'
openapi-generator-cli generate -i openapi.yaml -g typescript-fetch
schemathesis run openapi.yaml --checks all
pact-broker can-i-deploy --pacticipant web --version "$GIT_SHA" --to-environment production

If any step fails, no artifact is published.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Set meaningful gas and code-size gates.

Answer

A gate is only a gate if it fails the build. A dashboard nobody reads is not a gate. I'd set two hard protocol ceilings that must never be crossed, and one per-path gas budget that fails CI on regression.

Hard ceilings: fixed by the protocol, not by us

LimitValueSource
Deployed runtime bytecode24,576 bytesEIP-170
Initcode49,152 bytes, 2 gas per 32-byte wordEIP-3860

Exceeding either reverts at deploy. These are not budgets to tune.

Per-path budget

Gas per critical path (deposit, withdraw, batch) measured against the block gas limit: 30M on mainnet for years, since nudged up by validator vote. A transaction that needs more than a block can never be included, so the budget needs headroom below the limit.

Setting the numbers

Measure on the production profile: same solc version, same optimizer runs, same --via-ir choice as deployment. Set the threshold at the measured worst case plus a margin, commit it, and let CI enforce it. With Foundry, forge build --sizes prints runtime size per contract and flags anything over 24,576; forge snapshot writes a .gas-snapshot file, and forge snapshot --check in CI diffs against it and exits non-zero on regression.

Worked example

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

contract BatchDeposit {
    mapping(address => uint256) public balances;

    function depositBatch(address[] calldata users, uint256 amount) external {
        uint256 n = users.length;
        require(n <= 500, "batch too large");
        for (uint256 i; i < n; ++i) {
            balances[users[i]] += amount;
        }
    }
}

Trace depositBatch([A, B, C], 1) with three distinct addresses, all balances zero:

StepCost
i < n compare + JUMPI10
users[i] calldataload + offset math~9
keccak256 over (address, slot), 64 bytes42
SLOAD slot(A), cold2,100
SSTORE slot(A) 0→1, now warm20,000
++i5

Storage is exact: 2,100 cold access + 20,000 set = 22,100. Loop, calldata and hashing add roughly 100–150, so ~22,200 per user. The cold charge is paid once per slot per transaction, so the SLOAD-then-SSTORE pair costs the same 22,100 whether you read first or not.

  • 500 users → 500 × 22,200 = 11.1M, 37% of a 30M block.
  • 1,000 → 22.2M, 74%. Fits, but one tx nearly fills a block.
  • 1,400 → 31.1M. Exceeds the block limit; the tx can never be mined.

So the gate is a cap on batch size, not a gas number: require(n <= 500) in the contract, plus a test asserting N = 500 stays under 15M:

SOLIDITY
function test_batch500_under_budget() public {
    address[] memory users = new address[](500);
    for (uint256 i; i < 500; ++i) users[i] = address(uint160(i + 1));
    uint256 before = gasleft();
    batch.depositBatch(users, 1);
    assertLt(before - gasleft(), 15_000_000);
}

gasleft() brackets the external call, so the figure includes call overhead: an upper bound, which is what a gate wants.

Code-size trade-off

solc --optimize-runs trades runtime gas against code size: runs=200 favours small code, runs=10000 favours cheap runtime calls but grows bytecode. A contract at 23,900 bytes with runs=200 can cross 24,576 at runs=10000 and stop deploying. Pin runs in foundry.toml and gate on forge build --sizes so the change fails CI, not the deploy.

Failure modes and detection

  • Snapshot noise: gas shifts with compiler version and test order. Pin solc in foundry.toml; a snapshot diff with no source change means the toolchain moved.
  • Wrong optimizer profile: CI compiling with different runs or without --via-ir than production gives different sizes and gas. Build with the exact production profile.
  • Cold/warm mismatch: a test that warms a slot in setUp measures a warm SLOAD at 100 gas; production hits it cold at 2,100. Measure cold paths.
  • Unbounded input: array length taken from calldata with no cap. Fuzz large N and assert a revert, not an out-of-gas.

Trade-offs

A tight gate catches regressions but blocks legitimate work; set thresholds with headroom and require a written justification in the PR when raising one. Gate the paths that matter (deposit, withdraw, batch) not every function, or the snapshot becomes noise. Never buy gas by dropping a bounds check or a reentrancy guard: correctness and gas gates both have to pass.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Version contract artifacts for client consumers.

Answer

What I'd say first

Assume "client consumers" means off-chain code (an indexer, a bot, a frontend) that calls the contract and decodes returns and logs. The artifact it needs is not just the ABI JSON. It's a bundle of (chainId, address, ABI, deployed-bytecode hash, implementation address for proxies, compiler version), and that bundle needs its own version number pinned to the deployed bytecode, not to the source repo.

Direct answer: version the bundle with semver, publish it keyed by (chainId, address), and have the client verify the on-chain code hash against the manifest before it trusts the ABI.

Why ABI compatibility isn't enough

A selector is the first 4 bytes of keccak256 of the canonical signature. transfer(address,uint256) → 0xa9059cbb. If the selector matches, the call routes to the right function and the return data decodes: that is all ABI compatibility buys you. It says nothing about behaviour. A v2 that changes transfer to take amounts in gwei instead of wei keeps the same selector and the same decode shape; every client silently sends 10⁹× the intended amount. Proxies are the same trap: the proxy's ABI is the implementation's ABI, but storage slots belong to the implementation. Insert a new variable before an existing one and every getter reads the wrong slot: ABI unchanged, values garbage.

Artefact: the manifest

JSON
{
  "chainId": 1,
  "address": "0x6b17...1d0f",
  "version": "2.3.0",
  "deployedBytecodeHash": "0x9f2c...",
  "implementation": "0x5f4e...",
  "compiler": "solc 0.8.24",
  "abi": [ ... ]
}

Semver rule: major = any selector, decode shape, event topic, or semantic change; minor = new functions or events only; patch = no interface change. The bytecode hash is the tie-breaker: the same source with different optimizer settings produces different bytecode, so the version string alone is not enough.

Trade-offs

approachtrustfreshnesscost
on-chain registryhigh: chain is source of truthneeds a tx to updategas per publish
off-chain manifest (JSON pinned by hash)depends on your CIinstantyou host and sign it
verification-derived (Etherscan/Sourcify)depends on the verifierlags the deployfree, ABI may be missing

Deciding criterion: if the client must work without your infrastructure, read the implementation slot on-chain (EIP-1967: 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc) and fall back to a pinned manifest.

Failure modes and how you catch them

  • Stale ABI: decode throws or returns wrong values. Detect by comparing the on-chain code hash (EXTCODEHASH) to deployedBytecodeHash at startup; alert on mismatch.
  • Selector collision: two signatures share 4 bytes. Detect by scanning the ABI for duplicate selectors in CI; with 100 functions the birthday-bound probability is ~1.2e-6: rare, not zero.
  • Proxy implementation drift: read the EIP-1967 slot each block; if it changes, re-fetch the ABI before decoding.
  • Overloaded functions: foo(uint256) and foo(address) have different selectors; never look up by name.
  • Wrong address: check eth_chainId at startup; a mainnet address on a testnet decodes to nonsense.
  • Silent event corruption: topic0 is keccak256 of the event signature; compare it to the expected value before trusting indexed args.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

How is test coverage measured for Solidity contracts, and why can a suite at 100% coverage still ship a reentrancy or access-control bug?

Answer

Core answer (say this first)

Coverage tells you which lines, branches and functions the suite executed. It says nothing about what the tests asserted, and nothing about behaviour that emerges from ordering, callbacks or adversarial input. I treat it as a regression tripwire, a floor that catches "someone added a function and forgot a test", never as evidence a contract is safe.

forge coverage --report summary (Foundry) and npx hardhat coverage (solidity-coverage) both report four numbers: lines, statements, branches, functions. Function coverage is nearly free: call each function once. Line coverage is free if you assert nothing. Branch coverage is the only one that pushes back, and only on the conditionals the instrumenter recognises.

Artefact 1: 100% coverage, live reentrancy

solidity // solc 0.8.24 contract Rewards { mapping(address => uint256) public owed;

function claim() external {
    uint256 amount = owed[msg.sender];
    require(amount > 0, "nothing owed");
    (bool ok,) = msg.sender.call{value: amount}("");
    require(ok, "send failed");
    owed[msg.sender] = 0;   // after the call
}

}

The test:

solidity function test_claim() public { rewards.credit(alice, 3 ether); // victim rewards.credit(address(attacker), 1 ether); attacker.go(); }

Every line of claim runs, both requires take their true branch, and the report reads 100% lines / 100% functions / 100% branches. The test asserts nothing.

The attacker:

solidity contract Attacker { Rewards r; constructor(Rewards _r) payable { r = _r; } function go() external { r.claim(); } receive() external payable { if (address(r).balance >= 1 ether) r.claim(); } }

Trace, with the contract holding 4 ether:

Stepowed[attacker]contract balanceaction
go() → claim()14 → 3sends 1 ether, re-enters
nested claim()1 (not yet zeroed)3 → 2sends 1 ether, re-enters
nested claim()12 → 1sends 1 ether, re-enters
nested claim()11 → 0sends 1 ether, re-enters
receive()10guard false, returns
unwind ×400owed[attacker] = 0 four times

The attacker was owed 1 ether and left with 4. The three extra ether are alice's. Coverage counted the require(amount > 0) guard: it was evaluated five times and passed five times. It could not count the interleaving.

Artefact 2: what each metric proves

MetricProvesMisses
Functionthe function was called onceeverything about arguments and results
Linethe statement ranwhether any assertion followed
Branchboth sides of a recognised conditional ranguards the instrumenter doesn't model, try/catch arms, assembly
Statementroughly linesame as line

Tooling caveats

  • solidity-coverage rewrites your source to inject counters. Gas changes, so gas-snapshot tests break, and the bytecode under test is not the bytecode you ship.
  • forge coverage reads compiler source maps instead of instrumenting, so gas is untouched, but source maps drift under optimization and lines get attributed to the wrong place. forge coverage --ir-minimum recompiles with minimal optimization to get an honest map.
  • Whether a require guard appears as a branch at all is tool-dependent. I don't ask the metric whether a revert path is tested; I require a named negative test per guard.

How I set the gate

Floor on changed lines, not on the repo: diff-cover lcov.info --compare-branch=origin/main --fail-under=90. A global number ratchets down forever and rewards testing dead code. Exclude interfaces, mocks and scripts from the denominator. Then add what coverage cannot express: a negative test per access-control modifier and per require, a Foundry invariant suite for value conservation, and fuzzing on the arithmetic. Coverage is the cheapest of those, so it runs first and blocks the least.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

How do you control local devnet state (snapshots and reverts, time travel, and account impersonation) so that tests are isolated, deterministic, and repeatable?

Answer

Assume Foundry or Hardhat against a local node; the same three primitives exist in both under different names. The rule I follow: pin the fork block, snapshot before any state-mutating branch, and never let a test depend on wall-clock time or a real private key.

Isolation. Foundry already gives each test function a fresh EVM state, setUp() re-runs per test, so snapshots are for branching inside one test, not for test-to-test isolation. Hardhat does not: every it shares one network instance, so use loadFixture, which runs the fixture once, takes an evm_snapshot, and reverts to it before each test.

solidity // Foundry, forge 1.x function test_Vesting_CliffBoundary() public { bytes32 snap = vm.snapshotState(); vm.warp(cliff - 1); vm.expectRevert("not vested"); vesting.claim(); vm.revertToState(snap); // back to the pre-warp state, timestamp included vm.warp(cliff); vesting.claim(); assertEq(token.balanceOf(alice), 1_000e18); }

revertToState restores storage, balances, nonces and block.timestamp/block.number: a full state rollback, not just storage. The older vm.snapshot() / vm.revertTo(uint256) pair does the same with a numeric id; the opaque bytes32 form is the current one.

Time travel. vm.warp(t) sets block.timestamp, vm.roll(n) sets block.number, vm.skip(s) advances both. They are independent: warping does not move the block number, and rolling does not move the timestamp. That matters for anything keyed on block number: a block.number-based vesting schedule will not advance because you warped. On the JSON-RPC side the equivalents are evm_setNextBlockTimestamp, evm_increaseTime and evm_mine; evm_increaseTime only takes effect on the next mined block, so a test that increases time and reads state without mining still sees the old timestamp.

Impersonation. vm.prank(addr) sets msg.sender for the next call only; vm.startPrank(addr, txOrigin) holds it until stopPrank(). A prank is consumed by the next call frame, so a helper that makes an extra call eats it: the most common silent failure. On a fork you can impersonate a whale with no key at all, which is the point: hardhat_impersonateAccount plus hardhat_setBalance on Hardhat, vm.prank on Foundry. Impersonated accounts cannot sign, so any path that verifies an ECDSA signature or an EIP-712 digest will fail, or, worse, be skipped by a test that only checks msg.sender.

needFoundryHardhat / JSON-RPC
snapshotvm.snapshotState()evm_snapshot
revertvm.revertToState(id)evm_revert
set timestampvm.warp(t)evm_setNextBlockTimestamp
advance timevm.skip(s)evm_increaseTime + evm_mine
act as addressvm.prank / startPrankhardhat_impersonateAccount

Failure modes. Reusing a snapshot id after a revert: reverting discards every snapshot taken after it, so a stale id silently reverts to the wrong point or throws. Time travel past an oracle's updatedAt makes a staleness check fire and the test fails for the wrong reason, or, if the check is missing, passes for the wrong reason. Impersonation hides missing signature validation. And a fork test that does not pin blockNumber is neither deterministic nor repeatable: it passes today and fails next week when the fork head moves.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

Design unit tests for a privileged withdrawal.

Answer

Assumptions I state first: Vault.withdraw(address to, uint256 amount) is admin-gated, pays native ETH, and debits totalCredited on every withdrawal. Solidity 0.8.24, Foundry with forge-std. One rule drives the whole suite: move totalCredited -= amount below the external call and a test must go red. If reordering doesn't break anything, the test is checking gas, not semantics.

Actors. A non-admin caller reverts NotAdmin; the pranked admin succeeds and the balances move.

Boundaries. The table below; each row is a postcondition, not a range name.

Ordering and reentrancy. The recipient is a contract that observes the vault mid-callback and tries to re-enter. This is the only test that separates the two orderings.

SOLIDITY
contract Reenter {
    Vault immutable vault;
    uint256 public creditSeen;
    bool public reentryReverted;

    constructor(Vault v) { vault = v; }

    receive() external payable {
        creditSeen = vault.totalCredited();            // observed mid-callback
        (bool ok, ) = address(vault).call(
            abi.encodeCall(Vault.withdraw, (address(this), 1))
        );
        reentryReverted = !ok;
    }
}

function setUp() public {
    vm.deal(address(this), 10 ether);
    vault = new Vault{value: 10 ether}(admin);         // totalCredited == 10 ether
    reenter = new Reenter(vault);
}

function test_nonAdminReverts() public {
    vm.prank(alice);
    vm.expectRevert(Vault.NotAdmin.selector);
    vault.withdraw(alice, 1 ether);
}

function test_orderingAndReentrancy() public {
    vm.prank(admin);
    vault.withdraw(address(reenter), 10 ether);

    assertEq(reenter.creditSeen(), 0);                 // debited before the call
    assertTrue(reenter.reentryReverted());
    assertEq(address(reenter).balance, 10 ether);      // exactly one payout
    assertEq(address(vault).balance, 0);
    assertEq(vault.totalCredited(), 0);
}

Trace: withdraw debits totalCredited to 0, then calls reenter. Inside receive, creditSeen = 0, and the re-entrant withdraw(reenter, 1) arrives with msg.sender == address(reenter), so NotAdmin fires and reentryReverted is true. Final state: recipient 10 ether, vault 0. Had the debit sat below the call, creditSeen would read 10 ether and the first assertion fails; with no role check in the way, that same re-entrant call would clear the credit check and drain the vault. Make the admin a treasury contract and this test exercises the guard instead: assert OpenZeppelin 5.x ReentrancyGuardReentrantCall.

amountexpectedwhat breaks without the test
0asserted explicitly: a 0-value call still runs receive() and emits Withdrawn(to, 0)a < instead of <= silently changes the behaviour
1 weisucceeds, totalCredited drops by 1smallest unit catches scale errors
exactly totalCreditedsucceeds, totalCredited == 0the > versus >= off-by-one
totalCredited + 1revert InsufficientCredit(10 ether, 10 ether + 1)equality is where implementations are wrong most often
type(uint256).maxrevert InsufficientCredit, not Panic(0x11)if the check runs after subtraction, checked arithmetic panics with 0x11 and the domain error never fires
to == address(0)revert InvalidRecipient if you add the guard; the EVM transfers ETH to the zero address happilya burned payout nothing else catches
to == address(vault)succeeds, accounting still dropsself-send otherwise double-counts

Where suites go wrong under review.

  • Bare vm.expectRevert() accepts any revert, out-of-gas included. Pin it: vm.expectRevert(abi.encodeWithSelector(Vault.InsufficientCredit.selector, 10 ether, 10 ether + 1)).
  • vm.prank covers exactly the next non-cheatcode call. A getter or helper between the prank and the target leaves the withdrawal running as the test contract, so you have tested the wrong actor. Use startPrank/stopPrank for multi-call flows.
  • Dirty fixture: setUp reruns per test, but a fork snapshot or proxy instance held at file scope and mutated by an earlier test makes the suite order-dependent. forge test --match-test test_orderingAndReentrancy passing alone and failing in suite proves it.
  • Mocked-away callback: vm.mockCall on the recipient, or an EOA recipient, never runs receive(), so the ordering assertions pass vacuously.

Choosing the target. Testing the implementation is fastest and gives exact revert data, but misses initializers and storage layout. Decide by mutability, not habit: immutable contract, test the implementation; upgradeable, point the same suite at a deployProxy fixture plus one upgradeToAndCall test asserting totalCredited survives. A mock ERC-20 returning true also hides USDT, which returns nothing, so require(token.transfer(to, amount)) reverts in production and passes in unit tests. Keep one fork test for that path; don't unit-test token quirks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

A contract test reverts and the message is unhelpful. Walk me through how you isolate the failing call frame and decode the revert data.

Answer

Start by making the failure reproducible and getting a trace, not by re-reading the test source. Pin the block number for anything forked, run the single test, and turn on the tracer. Foundry: forge test --match-test testWithdraw -vvvv. Hardhat: npx hardhat test --grep withdraw with hardhat-tracer, or debug_traceCall on the in-process network for a failing eth_call.

The trace is a call tree. Each frame shows gas, the call, and the return or revert. The revert that matters is the innermost frame marked [Revert]: everything above it is propagation.

[FAIL. Reason: InsufficientBalance(0, 1000000000000000000)] [41234] VaultTest::testWithdraw() ├─ [2411] Vault::balanceOf(alice) [staticcall] │ └─ ← 0 ├─ [30210] Vault::withdraw(1000000000000000000) │ └─ ← [Revert] InsufficientBalance(0, 1000000000000000000) └─ ← [Revert] InsufficientBalance(0, 1000000000000000000)

Depth 2 is the cause: withdraw was called with 1e18 against a balance of 0. The fixture never funded alice: the bug is in the test, not the contract. Separating those two is the whole point of the exercise.

Then decode the revert. Solidity emits three shapes:

shapeselectorsource
Error(string)0x08c379a0require(cond, "msg"), revert("msg")
Panic(uint256)0x4e487b71checked arithmetic, assert, array OOB, div-by-zero
custom errorfirst 4 bytes of keccak256("Name(types)")error InsufficientBalance(uint256,uint256)

Panic codes worth memorising: 0x01 assert, 0x11 overflow/underflow, 0x12 divide by zero, 0x32 array index out of bounds, 0x41 out of memory. A bare require(cond) with no message returns empty revert data: that is not a decode failure, it is a missing string.

Foundry decodes custom errors from artifacts in the project. For an external contract, or a raw blob from a live transaction, decode against the ABI:

solidity vm.expectRevert( abi.encodeWithSelector(Vault.InsufficientBalance.selector, 0, 1e18) );

bash cast 4byte 0xcf479181 # selector -> signature, via the public directory cast abi-decode "InsufficientBalance(uint256,uint256)" 0x<args>

cast 4byte is a directory lookup, not proof: it is a guess when you do not have the ABI.

Two cases where the innermost frame is not the answer. A swallowed revert: try/catch or a low-level call returns (bool ok, bytes data) with ok == false, the outer frame succeeds, and the trace shows no [Revert]. Decode data yourself. In ethers v6 a failed call surfaces as CALL_EXCEPTION with the raw blob on error.data, which interface.parseError turns into a name and args. A gas failure: out-of-gas shows as a frame that consumed its entire gas limit with no revert data. That is a loop or unbounded input, not a logic error.

For a live transaction, replay it. cast run <txhash> --rpc-url <archive> prints the same tree; debug_traceTransaction returns it as JSON. Both need an archive node for anything older than the node's pruning window, and latest will not reproduce a historical failure.

Failure modes to name: vm.expectRevert() with no selector passes on any revert and hides a wrong-revert bug; a fork test that fails only in CI usually means an unpinned block; some RPC providers strip the revert data from eth_estimateGas errors, so trace the eth_call instead.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Fuzz a tokenized vault conversion.

Answer

Assume an ERC-4626 vault over one 18-decimal asset, no fees, and a fuzzer that drives deposit/mint/withdraw/redeem/transfer with random actors and amounts. The answer: fuzz the conversion functions against conservation and rounding invariants, not against hand-picked examples, and let the fuzzer shrink any counterexample to a minimal call sequence you can read.

Mechanism

The conversion is convertToShares(assets) = assets * totalSupply / totalAssets and convertToAssets(shares) = shares * totalAssets / totalSupply. ERC-4626 requires both to round down, and previewMint/previewWithdraw to round up, so every rounding step favors the vault. That direction is what makes the invariants below hold: a user can never extract more than they put in through a round trip, and the vault can always cover its holders.

Properties to fuzz

  1. Round-trip conservation: deposit(assets) then redeem(shares) returns at least assets - 1 wei.
  2. Solvency: sum(convertToAssets(balanceOf(u))) <= totalAssets over all actors.
  3. Share-price monotonicity: totalAssets/totalSupply never falls across user calls (only a loss event moves it down).
  4. No free shares: no actor's asset balance rises after a full deposit→withdraw cycle.

Harness (Foundry invariant test, solc 0.8.24, forge-std)

SOLIDITY
contract Handler is Test {
    MockVault vault;
    uint256 public ghostNetLoss; // worst per-actor loss over a deposit→redeem round trip

    function depositThenRedeem(uint256 assets) public {
        assets = bound(assets, 1, 1e30);
        deal(address(asset), address(this), assets);
        uint256 before = asset.balanceOf(address(this));
        uint256 shares = vault.deposit(assets, address(this));
        vault.redeem(shares, address(this), address(this));
        uint256 afterBal = asset.balanceOf(address(this));
        uint256 loss = before > afterBal ? before - afterBal : 0;
        if (loss > ghostNetLoss) ghostNetLoss = loss;
    }
}

function invariant_noRoundTripLoss() public view {
    assertLe(handler.ghostNetLoss(), 1); // a round trip may lose at most 1 wei
}

Worked trace: the inflation attack this catches

steptotalAssetstotalSupplyactorshares
attacker deposits 1 wei11attacker1
attacker donates 10 000e18 directly10 000e18+11attacker1
victim deposits 19 999e1829 999e18+12victim1
victim redeems 1 share14 999e18+11victim0

The victim put in 19 999e18 and got back ~14 999e18: a 5 000e18 loss, far above the 1-wei tolerance, so invariant_noRoundTripLoss fails and shrinks to the three-call sequence above. The fix is a virtual-shares offset or a dead-shares mint on first deposit.

Trade-offs

Property-based fuzzing (Foundry, Echidna, Medusa) is the right tool for the pure conversion math. Stateful invariant fuzzing is required for the multi-call inflation attack, because no single call is wrong. Differential fuzzing, run the same sequence against a reference implementation, catches spec drift the invariants miss. Don't fuzz access control or gas: those are unit and static-analysis territory.

Failure modes and detection

  • Over-constrained assume: the fuzzer explores nothing. Detect via coverage report and call counts.
  • Unreachable boundary: bound() excludes 0 or type(uint256).max. Detect by logging when the boundary is actually hit.
  • Weak property: it passes on a known-buggy vault. Detect by mutation testing: inject a rounding bug and confirm the property fails.
  • Oracle overflow: the invariant itself reverts and masks failures. Detect by separating reverts from assertion failures in the run report.
  • Nondeterministic seed: failures aren't reproducible. Detect by pinning the seed in config and re-running.
  • Insufficient runs: detect by run count and coverage saturation, not by a green check.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Build an invariant harness for a lending protocol.

Answer

What I'd say first

Clarify the property before writing any handler. For a lending pool the invariants are: solvency (cash + outstanding borrows ≥ deposits), conservation (every unit of value sits in an actor balance, the pool, or the ghost ledger), share value (a depositor's shares convert to at least what they put in), and authorization (no non-owner state change). Assume a single chain, a well-behaved ERC20, and an oracle the harness holds fixed: oracle manipulation is a separate harness.

Then build three layers: handlers wrapping every external entry point, ghost variables updated inside those handlers, and invariant_ functions asserting after every call. Foundry is the default because the harness lives in the same repo; reach for Echidna or Medusa when deep sequences need coverage guidance.

The harness

SOLIDITY
// Foundry, Solidity ^0.8.24
contract Handler is CommonBase, StdUtils {
    LendingPool pool; IERC20 asset;
    address[3] actors;
    mapping(address => uint256) public ghostDeposits;

    function deposit(uint256 seed, uint256 amount) public {
        address a = actors[bound(seed, 0, 2)];
        amount = bound(amount, 1e6, 1_000_000e6);   // 1 .. 1M USDC
        asset.mint(a, amount);
        vm.startPrank(a);
        asset.approve(address(pool), amount);
        pool.deposit(amount);
        vm.stopPrank();
        ghostDeposits[a] += amount;
    }

    function donate(uint256 amount) public {          // direct transfer, no shares
        amount = bound(amount, 1, 1_000_000e6);
        asset.mint(address(pool), amount);
    }

    function borrow(uint256 seed, uint256 amount) public {
        address a = actors[bound(seed, 0, 2)];
        uint256 max = pool.maxBorrow(a);
        if (max == 0) return;                          // expected revert: skip
        vm.prank(a);
        pool.borrow(bound(amount, 1, max));
    }
}
SOLIDITY
function invariant_shareValue() public view {
    for (uint256 i; i < 3; ++i) {
        address a = handler.actors(i);
        assertGe(pool.convertToAssets(pool.balanceOf(a)),
                 handler.ghostDeposits(a));
    }
}

A failing trace

fail_on_revert = true, runs = 1000, depth = 200:

  1. deposit(attacker, 1) → shares[attacker] = 1, cash = 1, ghostDeposits[attacker] = 1.
  2. donate(1000e6) → cash = 1000e6 + 1, total shares still 1.
  3. deposit(victim, 1000e6) → shares minted = 1000e6 × 1 / (1000e6 + 1) = 0. ghostDeposits[victim] = 1000e6.
  4. invariant_shareValue: convertToAssets(0) = 0 < 1000e6 → fail. The shrinker reduces to these three calls.

No single call violates a per-call check: the deposit in step 3 succeeds and returns. Only the composition breaks the identity, which is exactly what unit tests miss.

Invariants

invariantassertscatches
solvencycash + outstandingBorrows ≥ totalDepositsbad debt, interest misaccrual
conservationΣ actor balances + cash == ghostDeposits − ghostBorrows + ghostInterestvalue leakage
share valueconvertToAssets(balanceOf(a)) ≥ ghostDeposits[a]donation/inflation
authorizationnon-owner calls cannot change paramsmissing access control

Trade-offs

toolstrengthcost
Foundrysame repo, fast, good shrinkingstateful fuzzing weaker, no coverage guidance
Echidnacoverage-guided, mature shrinkingseparate Haskell toolchain, slower
Medusaparallel workers, coverage-guidednewer, smaller ecosystem

Deciding criterion: start in Foundry; move to Echidna or Medusa when deep sequences need coverage guidance. fail_on_revert = true catches unexpected reverts but forces you to return early on expected ones: with it off, a handler that reverts for the wrong reason passes silently.

Failure modes

  • Unreachable handler: coverage shows 0 calls to donate; the attack above is invisible. Add the handler.
  • Invalid calls dominate: if most calls revert on a require, budget is wasted. Count revert reasons and tighten bounds.
  • Wrong ghost model: assert ghost == real at genesis; a failure at call 0 is the model, not the protocol.
  • Missing actor: one actor means no liquidation race. Use 3–5.
  • Shallow depth: a 4-step exploit needs depth ≥ 4; 200 is a working default.
  • Hidden dependency: a fixed oracle never explores price moves. Add a price handler.
  • Flaky time: without vm.warp in a handler, interest never accrues and solvency is trivially true.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Differential-test protocol math.

Answer

"Protocol math" is the deterministic arithmetic that decides state transitions (fee accrual, balance deltas, sequence numbers) where a one-unit difference is a reconciliation break or a consensus split. Differential testing it means running two implementations on the same inputs and treating every disagreement as a finding.

The core protocol: build a reference that is independent in its error model, not just its source file. A Python Decimal reference checked against a Java BigDecimal implementation is genuinely independent. A second copy of the same long formula, or a reference that imports the implementation, is not: it will agree with the bug. Then generate shared cases, normalize the rounding the protocol actually specifies, and persist every divergence with the full input, both outputs, and both library versions.

Worked example. Production computes a basis-point fee in Java long: fee = (amount * feeBps + 5000) / 10000, integer division. Reference computes (Decimal(amount) * Decimal(feeBps) / Decimal(10000)).quantize(Decimal('1'), ROUND_HALF_UP).

  • amount=12345, feeBps=250: production 12345*250=3,086,250, +5000=3,091,250, /10000=309. Reference 308.625 → 309. Agree.
  • amount=2, feeBps=2500: production 5000+5000=10000, /10000=1. Reference with Python's default context (ROUND_HALF_EVEN) gives 0.5 → 0. Divergence 1 vs 0. Setting the reference context to ROUND_HALF_UP gives 1. That was a rounding-spec mismatch, not a defect, and random inputs hit exact ties about once in 10,000 cases, so you need a generator that constructs them (amount*feeBps ≡ 5000 mod 10000).
  • amount=1e15, feeBps=10000: production 1e15*10000 = 1e19, which overflows int64 (max 9,223,372,036,854,775,807 ≈ 9.22e18) and wraps negative. Reference is exact. So the valid domain is amount ≤ 9.22e14 when feeBps ≤ 10000; generate at 9.22e14 and 9.23e14.

Failure modes and how you catch them:

  • Shared bug. Mutation-test the harness: change 5000 to 4999 in production and confirm the differential run fails. A surviving mutation means the reference shares the bug.
  • Non-independent model. Same check, if the reference is derived from the implementation, mutations survive.
  • Nondeterminism. Run one case 100 times with PYTHONHASHSEED varied; any output change is nondeterminism, not a divergence, and must be fixed before triage.
  • Version skew. Record both library versions in the divergence record; a divergence that vanishes when the reference is pinned to production's version is skew.
  • Economic drift. Sum absolute divergence over a corpus of 1e6 realistic transactions; more than 1 minor unit per 10,000 transactions is a release blocker even though each individual case looks like rounding noise.

Trade-offs. Hand-computed vectors are cheap but only cover what you thought of. Property tests (debits sum to credits) catch conservation bugs without a reference but say nothing about the exact value. SMT or refinement proofs (Z3, Dafny) can prove agreement over a small domain but don't scale to a 64-bit input space. Differential testing scales and finds what you didn't imagine, but it only tells you the two disagree: never which one is right. Triage each divergence as reference-wrong, implementation-wrong, or spec-ambiguous, and keep the corpus as regression tests.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Specify a formal property for withdrawals.

Answer

Clarify first. "Withdrawal" is ambiguous: ETH out of a vault, an ERC-20 transfer out of a bridge, or a share redemption? I'll assume a single-contract ETH vault that holds only user funds, bal[a] is the ledger, and C is address(this).balance. If the contract also holds protocol-owned funds, the invariant changes and I'd say so up front.

The property. Two parts, and you need both.

Conservation: C == Σ_a bal[a] holds in every reachable state.

Withdrawal correctness: for any transaction where sender s calls withdraw(amount), either it reverts and the whole state is unchanged, or it succeeds and:

  • bal[s]_post == bal[s]_pre - amount
  • C_post == C_pre - amount
  • bal[a]_post == bal[a]_pre for every a != s

The third clause is the one people drop. Conservation alone is satisfied by a contract that moves the right total to the wrong recipient.

Why callbacks break it. State the property over the whole transaction, not the single call. If the code transfers before decrementing, the recipient's receive() runs while bal[s] is still the old value, and the invariant is false at that reentrancy boundary even though it looks true at the end of the outer call.

Trace it. The contract holds 10 ETH; the attacker's ledger balance is 1, other users hold 9. withdraw(1) transfers 1 ETH first, so C = 9 and bal[attacker] is still 1. The attacker's receive() calls withdraw(1) again: the amount <= bal[s] precondition still passes, so it transfers another 1 ETH, C = 8. Repeat until C = 0. The stack unwinds and sets bal[attacker] = 0. The attacker walked off with 10 ETH; the ledger says they're owed 0 and the other users' 9 ETH are gone. C == Σ bal is now 0 == 9: false.

The fix is checks-effects-interactions: decrement bal[s] before the external call. The re-entrant call then reads bal[attacker] == 0 and reverts on the precondition.

Choosing scope. You can't prove over unbounded state, so you bound it, and the bound is the whole argument. Bound the number of actors to at least the number of distinct roles the code branches on (owner, user, and an attacker contract that re-enters) because a two-actor model can't even express the reentrancy above. Bound value to the smallest set that exercises rounding: 0, 1, amount - 1, amount. A model-checking pass over three accounts and values ≤ 10 is evidence, not proof; only an inductive argument that the invariant is preserved by every transition covers all states.

Failure modes and how you catch them.

  • Prover timeout reported as success. Detect: CI fails on unknown, not just on violation.
  • Model-code drift: the spec was written against a copy. Detect: run the prover against the compiled artifact in CI and pin the commit hash.
  • Unsupported opcode or precompile silently havoc'd. Detect: read the prover's report for unmodeled calls; a green run over a havoc'd call proves nothing.
  • Environmental abstraction: msg.sender is arbitrary but block.timestamp is fixed. Detect: enumerate every environment variable the property reads and state which are free.

Alternatives. Fuzzing (Echidna) finds counterexamples cheaply and proves nothing. Symbolic execution (Halmos) proves within bounds. An unbounded inductive proof is the only thing that covers all states, and the only one where "no counterexample found" isn't the claim.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

How do you build a custom static analysis detector to identify protocol-specific vulnerabilities in CI?

Answer

Assumptions, stated up front: a Solidity protocol, Slither as the framework, GitHub Actions as CI. The shape of the answer is the same for any AST-based tool: only the IR changes.

The 90-second answer

You don't build a general analyzer. You pick one protocol invariant, write it as a negative pattern over the IR, and gate the PR on it. Four steps.

  1. Write the invariant as one sentence with a name. "Any external function that makes a high-level call to a token transfer must either carry nonReentrant or perform all its storage writes before the call." If you can't write it in one sentence, it isn't a detector yet: it's a research project.
  2. Implement it against the tool's IR, not the raw source. Slither hands you resolved call targets and per-node storage read/write sets. The solc AST hands you syntax nodes and leaves identifier resolution to you.
  3. Emit SARIF and fail the build on the severity you chose. Slither exits non-zero when a detector at the configured severity fires; wire that exit code to the required PR check.
  4. Budget for tuning. Suppression comments, a baseline of pre-existing hits so the first run doesn't block every open PR, and a count of how often the rule gets suppressed. If that count climbs, the rule is wrong, not the code.

The trace

SOLIDITY
contract Vault {
    mapping(address => uint256) public balances;
    IERC20 public token;

    function withdraw(uint256 amount) external {
        require(balances[msg.sender] >= amount);
        token.transfer(msg.sender, amount);   // high-level external call
        balances[msg.sender] -= amount;       // storage write after the call
    }
}

Walking the detector over this: withdraw is an entry point and is neither view, pure nor a constructor, so it's a candidate. It carries no nonReentrant modifier, so the guard check doesn't short-circuit. SlithIR orders the body as CALL token.transfer followed by SSTORE balances, and the write-after-call is what fires the report. Move the balances update above the transfer and the detector goes quiet. Add nonReentrant and it's skipped before the call scan runs at all.

Why the IR and not the AST

What the detector needssolc --ast-compact-jsonSlither SlithIR
Call targetYou resolve identifiers and types across AST subtrees yourselfResolved to a (contract, function) pair
Storage writesYou walk expression nodes and infer lvaluesPer-node read/write sets
OrderingSource order onlyCFG order, so "write after call" is a graph query
Cost in CIA JSON parseA full compile plus IR build, seconds per run

Failure modes

  • Aliasing defeats name matching. IERC20 t = token; t.transfer(...) slips past a detector that string-matches the callee name. Resolving the call target through the IR is what closes this, and it's the main reason to pay the compile cost.
  • Internal calls. A public function that delegates the transfer to a private helper won't show the call on the entry point. Slither exposes internal calls separately, so decide explicitly whether the detector follows one level or all of them, and write a fixture for whichever you chose.
  • Detector rot on compiler bumps. A solc version change can move the IR shape under you. Pin the compiler in CI and keep a small fixture contract with a known-good and known-bad function; if the fixture stops reporting, the detector broke, not the protocol.
  • False positives on trusted callees. Transfers to a known internal vault are legitimate. Suppress them inline with a comment that requires a reviewer to approve, rather than widening the rule until it catches nothing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

State the evidence boundary of a fork test.

Answer

The 60-second answer. A fork test proves exactly one thing: that your contract's logic computes the right result against a frozen copy of on-chain state at a specific block. It proves nothing about ordering, timing, competition, or liveness, because the fork has none of those. So the evidence boundary is: state-dependent logic. Balances, allowances, storage layouts, existing bytecode, oracle values at the pinned block. Is in scope. Anything that depends on who else is acting or when is out of scope. I pin a block, run the scenario, and treat a green test as evidence about my code, never as evidence about the deployment.

Why the boundary sits there. A fork is a lazy state fetch plus a local EVM. Foundry's vm.createSelectFork(url, blockNumber), or forge test --fork-url ... --fork-block-number ..., pulls accounts and storage slots over RPC on first touch and caches them. Everything after that runs in a single-threaded local EVM where:

  • Blocks are mined only when you ask. vm.roll and vm.warp move block.number and block.timestamp by hand; nothing advances on its own. A 12-second mainnet slot becomes zero wall-clock time, so any logic keyed to elapsed time (TWAP windows, rate limits, auction phases) sees whatever you told it to see.
  • There is no mempool. Your transaction is the only one in the block. Searchers, sandwich bots and backrunners do not exist, so a swap that shows 0.05% price impact in the fork can be sandwiched for several percent on mainnet.
  • msg.sender is whatever you say. vm.prank and anvil_impersonateAccount skip signature verification entirely. Any access control that depends on a valid ECDSA signature over a specific digest is untested: you exercised the branch, not the authentication.
  • Oracle values are frozen at the pinned block. Chainlink ETH/USD on mainnet updates on a 0.5% deviation or a 1-hour heartbeat; in the fork it never moves unless you vm.mockCall it, and a mock returns exactly what you coded: including the stale-price case you forgot to write.

What that costs you. An Optimism or Arbitrum withdrawal carries a 7-day challenge period; a fork test settles it in one block, so any logic that assumes the delay exists is unverified. The fork inherits the pinned block's block.gaslimit, 30M on mainnet from London until validators signaled it toward 36M, and you pay nothing, so gas-griefing and out-of-gas-at-scale failures never surface. Reorgs are invisible: post-Merge, single-slot reorgs happen and finality takes two epochs (~12.8 minutes), none of which a fork reproduces.

When a fork test is the wrong tool.

fork testpublic testnetmainnet canary
proveslogic against real stateintegration under real ordering and latencysurvival against real adversaries
ordering / MEVnonereal mempool, real buildersreal
oracle freshnessfrozen or mockedlive feedslive
costfree, secondsfree, minutesreal funds
use forupgrade rehearsal, unit-level integrationkeeper and bot behavior, pre-releasefinal 1% rollout

Use a fork test when the question is "does my code compute the right thing given this state". Use a testnet when the question is "does my system behave under real ordering and latency". Use a canary when the question is "does it survive real adversaries". For MEV, reorgs or cross-actor timing, a fork test is simply the wrong instrument: no amount of adversarial ordering inside it fixes that, because you are still the only actor.

Failure modes and how to detect them. False confidence: a green fork suite read as deployment proof; detect by requiring a testnet or canary gate in the release checklist. Mocked oracle timing: vm.mockCall returns a constant; detect by asserting the staleness branch is actually exercised. Impersonation masking auth: detect by running at least one test with a real vm.sign signature. Reorg blindness: replay the scenario at block N-1 and N-2 and check the state assumptions still hold.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-8

Create a mainnet-fork integration suite.

Answer

Core answer (say this first)

Pin the fork to a chain ID and a block number, point it at an archive RPC, and reset state between tests. Everything else follows from that.

TOML
# foundry.toml
[rpc_endpoints]
mainnet = "${MAINNET_RPC_URL}"
SOLIDITY
// test/Fork.t.sol — forge 1.x, solc 0.8.24
uint256 constant PIN = 20_000_000; // example pin, not a recommendation

function setUp() public {
    vm.createSelectFork(vm.envString("MAINNET_RPC_URL"), PIN);
}

vm.createSelectFork with a block number makes every run start from the same state root. Without the number, forge forks the provider's latest, and the fixture's expected values (a whale's balance, a Uniswap pool's sqrtPriceX96, a Chainlink round) become functions of a block that moves between runs. The test fails on a commit that changed nothing.

Assumptions to state

  • Archive RPC. A full node prunes old trie nodes (geth keeps roughly the last 128 blocks by default), so forking at a historical block needs an archive endpoint: Alchemy, Infura, or a self-hosted geth --gcmode=archive. Record which provider and which plan, because a pruned endpoint returns missing trie node mid-test, not at startup.
  • Chain ID. Anvil and Hardhat default the fork to chain ID 31337, not 1. Anything that hashes chain ID into a signature breaks.

Artefact: chain ID confusion, traced

SOLIDITY
function test_permit() public {
    vm.createSelectFork(rpc, PIN);
    console.log(block.chainid); // 31337
    // permit signed off-chain with domain chainId = 1
    token.permit(owner, spender, value, deadline, v, r, s);
}

Trace: the fork reports 31337. ERC20Permit rebuilds the EIP-712 domain separator with block.chainid, so the digest differs from the one the signer signed. ecrecover returns a different address, owner != recovered, and the call reverts ERC2612InvalidSigner. Fix: call vm.chainId(1) after selecting the fork.

Impersonation

anvil_impersonateAccount / hardhat_impersonateAccount skip signature checks entirely. Use it only for actors whose authority is genuinely msg.sender-based (a treasury EOA, a governance timelock). If the contract checks a signature, a role, or a timelock delay, impersonation makes the test pass without exercising the auth path: a false green. Detect it by asserting the revert you expect when impersonation is off.

What a fork does not reproduce

Not reproducedWhy it matters
Mempool / orderingNo pending txs, so MEV, gas auctions, and front-running are absent
Oracle freshnessA pinned Chainlink round is frozen; staleness checks never fire
Upstream node versionProvider upgrades the client silently; pin and log web3_clientVersion

Trade-offs

A pinned fork is wrong when the thing under test only exists at HEAD: a just-deployed contract, a live migration. Then run a second, separate job against latest that is allowed to fail loudly, and keep the pinned suite as the gate. Snapshot bumps are a deliberate upgrade: change the pin in its own commit, re-baseline the fixtures, and review the diff.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Use deterministic deployment safely.

Answer

Core answer (first 90 seconds)

Deterministic deployment means the contract address is a pure function of inputs you control, so you can compute it before deploying and depend on it across chains. In Solidity that is CREATE2 (EIP-1014, live since Constantinople in 2019). The address is:

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

Three inputs, and every one is a trust assumption. If I cannot pin the deployer address, the salt, and the exact init code, the counterfactual address is a guess, not a guarantee. So the safe pattern is: freeze all three, recompute the address off-chain from the same inputs, and only then deploy.

Mechanism

The preimage is 85 bytes: one 0xff byte, the 20-byte deployer, the 32-byte salt, and the 32-byte keccak of the init code. The address is the low 20 bytes of the keccak of that. Contrast with CREATE, where the address is keccak256(rlp([sender, nonce]))[12:]: it depends on the sender's nonce, so it is not reproducible without replaying every prior transaction from that account.

Trace of the derivation:

  1. h = keccak256(init_code): 32 bytes. init_code is the constructor bytecode plus ABI-encoded constructor args.
  2. preimage = 0xff ++ deployer ++ salt ++ h: 85 bytes.
  3. address = keccak256(preimage)[12:32].

Change one byte anywhere in init_code and h changes, so the address changes. That is why "same address" only holds when the init code is byte-identical: same solc version, same optimizer runs, same metadata. The CBOR metadata hash solc appends is part of the bytecode, so a different compiler build silently moves the address.

Trade-offs

CREATE2: the address depends on the init code. Good when you want the address to commit to the code. Bad when you want to upgrade the implementation behind a fixed address: any code change moves the address.

CREATE3 (Solmate/Solady): deploy a minimal proxy via CREATE2, then the proxy deploys the real contract with CREATE. The final address depends only on deployer + salt, not on the implementation bytecode. Use it when you need a stable address across implementation upgrades. Cost: an extra deployment, and the proxy is a permanent indirection.

Plain CREATE: fine for one-off deploys where you do not need a precomputed address.

When deterministic deployment is not worth it: if you do not need cross-chain address parity or counterfactual deposits, CREATE is simpler and has no salt-squatting surface.

Failure modes

  • Salt collision / squatting: anyone can deploy the same init code to your counterfactual address first. Your deploy then reverts, and the attacker controls initialization. Detect by checking extcodesize at the address before deploying. Note EIP-6780 (Cancun, 2024) means selfdestruct no longer clears code except in the same transaction, so you cannot clean up a squatted address.
  • Uninitialized contract: proxy deployed but initialize() not yet called. A front-runner calls it. Detect by checking the initialized flag in the same transaction as deploy, or use constructor-based init.
  • Factory mismatch: the address depends on the deployer address. A factory redeployed at a different address produces different addresses. Pin the factory address per chain.
  • Chain confusion: same inputs give the same address on every chain, but the code may only exist on one. Check extcodesize per chain.
  • Init-code drift: covered above. Pin solc version and settings, verify the bytecode hash.

Artefact

SOLIDITY
// Solidity ^0.8.20
function predict(bytes32 salt, bytes memory initCode) public view returns (address) {
    return address(uint160(uint256(keccak256(abi.encodePacked(
        bytes1(0xff), address(this), salt, keccak256(initCode)
    )))));
}

Deploy with create2(0, add(initCode, 0x20), mload(initCode), salt) in assembly, then assert the returned address equals predict(...).

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Create a reviewable deployment pipeline.

Answer

First 90 seconds

Three things decide the design: what is being deployed, which chain, and who holds the key. I will assume the hard case: Solidity contracts on Ethereum mainnet, deployed by a 3-of-5 Safe, with a 48-hour TimelockController (OpenZeppelin, minDelay = 172800) gating every post-deploy admin call. On a testnet with a single hot key, most of this collapses to forge script --broadcast.

The pipeline is six steps, and each one exists because the step before it can be wrong.

1. Plan as a file. A checked-in manifest: chain ID, deployer address, constructor args, expected CREATE2 addresses, artifact hashes. Review happens on the PR diff, not on a live console. A CREATE2 address is keccak256(0xff ++ deployer ++ salt ++ keccak256(init_code))[12:], so any change to init code changes the address and the diff shows it.

2. Simulate against the real chain. forge script script/Deploy.s.sol --fork-url $RPC runs the whole sequence in a local EVM forked from mainnet. Nothing is signed. A wrong chain ID, a reverting constructor, or an unexpected state write stops here for free.

3. Approvals. The broadcast transaction is proposed to the Safe; three of five sign. The Safe Transaction Service assigns the nonce and a hash you can review offline.

4. Stepwise broadcast. forge script ... --broadcast --slow sends one transaction, waits for its receipt, then sends the next. Without --slow, two transactions can be signed against the same nonce, and the second either replaces the first or is rejected as nonce too low.

5. Receipts. Per step: tx hash, block number, gas used, decoded logs. These are the audit trail and the resume point.

6. Postconditions, then authority transfer. Read back owner(), role membership, and the eth_getCode bytecode hash. Only when every check passes do you renounce the deployer role and hand admin to the timelock. Renouncing first is the classic way to brick a contract.

Alternatives. Hardhat plus hardhat-deploy gives the same manifest-and-receipts model on a JS toolchain; pick it if the team already lives in TypeScript. A Safe Transaction Builder batch JSON is fine for a handful of calls but has no simulation and no postcondition checks. Remix plus MetaMask is for testnets only. The cost of this pipeline is human latency (a 3-of-5 approval plus a 48-hour timelock is hours to days, not seconds) so do not pay it for a throwaway deploy.

Failure modes and how you catch them

failurehow it shows updetection
wrong networktx lands on a fork or testnetrequire(block.chainid == EXPECTED) reverts in simulation
stale nonceRPC returns nonce too lowcast nonce $DEPLOYER --rpc-url $RPC before signing
address mismatchCREATE2 address differs from the manifestcompare predicted address to the manifest before broadcast
parameter typowrong admin or fee recipientdecode calldata and diff it against the manifest
partial deploymentscript dies after tx 2 of 5forge script --resume replays from the last receipt
signer compromiseunexpected pending Safe txnonce gap in the Safe Transaction Service
unverified dependencyforge verify-contract failspin solc version and commit the lockfile
premature renunciationowner() == address(0) before configpostcondition require(owner() != address(0))

The script (illustrative, checked against forge-std with solc 0.8.24)

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

import {Script, console2} from "forge-std/Script.sol";
import {Vault} from "../src/Vault.sol";

contract DeployVault is Script {
    function run() external {
        require(block.chainid == vm.envUint("EXPECTED_CHAIN_ID"), "wrong chain");
        require(msg.sender == vm.envAddress("DEPLOYER"), "wrong sender");

        address admin = vm.envAddress("ADMIN");
        address timelock = vm.envAddress("TIMELOCK");

        vm.startBroadcast();
        Vault vault = new Vault(admin);
        vault.grantRole(vault.ADMIN_ROLE(), timelock);
        vault.renounceRole(vault.ADMIN_ROLE(), msg.sender);
        vm.stopBroadcast();

        require(vault.hasRole(vault.ADMIN_ROLE(), timelock), "role not moved");
        require(!vault.hasRole(vault.ADMIN_ROLE(), msg.sender), "deployer still admin");
        require(address(vault).code.length > 0, "no code at address");
        console2.log("Vault deployed at", address(vault));
    }
}

What it costs. A ~3 KB runtime contract pays 200 gas per byte to deposit: 3072 x 200 = 614,400 gas, plus roughly 150k for constructor execution. At 20 gwei that is 764,400 x 20e-9 ≈ 0.015 ETH, about $46 at $3,000/ETH. Illustrative, but it tells you the deploy is cheap and the review is the expensive part.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Automate post-deployment verification.

Answer

What I'd say first

Post-deployment verification answers one question: was the bytecode at this address produced by the source I think it was? It's provenance, not safety: a verified contract can still be a rug. So I automate it as a CI gate that runs after every deploy and fails the pipeline on anything but an exact match.

Assumptions: EVM chain, solc 0.8.x pinned exactly, Foundry for build and deploy, Sourcify plus an explorer as backends.

Why exact match is the hard part

solc appends a CBOR metadata blob to the runtime bytecode: 53 bytes with default 0.8.x settings, ending in a two-byte length. That blob carries the IPFS hash of the metadata file, which in turn carries keccak256 of every source file's full text and the compiler version. So a change that alters zero opcodes: adding a comment, renaming a file, bumping solc 0.8.24 to 0.8.25: changes the appended bytes and breaks a byte-for-byte comparison. That's metadata drift, and it's why "verified" and "reproducible" are different claims.

Two ways to handle it. Pin the compiler and freeze the sources so the metadata is stable. Or set settings.metadata.bytecodeHash to "none" in the standard JSON input, which strips the hash entirely and makes the build reproducible across comment edits: at the cost of losing the on-chain pointer back to your source.

The pipeline

YAML
- run: forge build --use 0.8.24
- run: |
    forge verify-contract $ADDR src/Vault.sol:Vault \
      --chain 1 \
      --constructor-args $(cast abi-encode "constructor(address,uint256)" $OWNER 1000) \
      --verifier etherscan --watch
- run: |
    curl -s "https://sourcify.dev/server/check-by-addresses?addresses=$ADDR&chainIds=1" \
      | jq -e '.[0].status == "perfect"'

The jq -e is the gate: Sourcify returns "perfect", "partial", or "false", and only perfect means the bytecode matched including metadata. Etherscan's UI shows "Similar Match" for the partial case, which is easy to read as verified.

For a proxy, verify the implementation, then read the EIP-1967 slot and assert it:

Shell
cast storage $PROXY 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc

Finally diff runtime code against the artifact, but only for contracts without immutables, since immutables are baked into deployed code per instance and the artifact holds zeros there.

Failure modes and how they surface

failuremechanismdetection
metadata driftcomment or solc patch changes the CBOR hashexact-match verify fails; diff the trailing 53 bytes
partial read as exactexplorer labels it "Similar Match"assert Sourcify status == perfect
wrong implementationproxy slot points at a stale implread EIP-1967 slot, compare to expected address
unlinked library__$...$__ placeholder left in bytecodegrep the artifact before deploy
delayed publicationverify runs async, deploy already shippedgate the deploy job on verify exit code
explorer dependenceEtherscan rate-limits at 5 req/s on the free tiermirror to Sourcify, cache build artifacts

Trade-offs

Partial match is not worthless: the executable bytecode is identical, only the metadata differs, so the source you're reading is the source that ran. What you lose is bit-for-bit reproducibility, which is what a build attestation needs. So accept partial for reading, never for attestation, and record which one you got.

Sourcify is free, keyless, and exposes the perfect/partial distinction in the API; Etherscan has better chain coverage and UI but rate-limits and blurs the distinction. Verify on both, gate on Sourcify.

Skip the gate when you can't reproduce the build inputs at all, factory deploys where the exact solc and settings aren't recoverable, because you'll pay CI time for a check that can only fail. And remember what none of this covers: the proxy admin's key, the upgrade timelock, or whether the verified code is any good.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Validate an upgrade before execution.

Answer

What I'd say first

Assume a live UUPS proxy holding real balances, upgrade proposed by a 3-of-5 multisig, no timelock yet. I don't let the proposal execute until four things pass: storage layout compatibility, initializer safety, a fork rehearsal against real state, and a written rollback boundary. The first two are static and cheap; the last two catch what static analysis misses.

Storage layout is append-only

The proxy holds all state; the implementation holds only code. Slot N means the same thing forever, so a new implementation may append variables but never insert, reorder, delete, or change the type of an existing one. OpenZeppelin's @openzeppelin/hardhat-upgrades enforces this: upgradeProxy runs validateUpgrade, which diffs the new layout against the recorded one and throws on an inserted or type-changed variable. Base contracts reserve room with uint256[50] __gap.

What skipping it costs. V1:

SOLIDITY
contract V1 {
    uint256 totalSupply;                   // slot 0
    mapping(address => uint256) balances;  // slot 1
    address owner;                         // slot 2
}

V2 inserts address treasury at slot 0. After the upgrade:

variableslotreadsresult
treasury0old totalSupplygarbage address
totalSupply1mapping base (never written)0
balances2old owner slot as baseevery balance reads 0
owner3never writtenaddress(0)

owner == address(0) means every onlyOwner call reverts: the contract is bricked for admin, and balances appear wiped. The plugin refuses this upgrade before it is broadcast.

Initializers

A proxy's constructor never runs; initialize() does. Without the initializer modifier, anyone can call it after deployment and set themselves as owner. OpenZeppelin's Initializable makes it one-shot; reinitializer(n) allows a controlled second run for the upgrade. The plugin flags a new implementation that adds an unprotected initializer.

Fork rehearsal

Static checks can't see role wiring or economic invariants. Fork mainnet at the current block (hardhat node --fork $RPC, or anvil --fork-url), impersonate the multisig, execute the exact calldata the proposal will send, then assert: total supply unchanged, every holder's balance unchanged, owner() and each role unchanged, and the new function behaves. This is the only step that catches a wrong implementation address or a selector clash: a new function whose 4-byte selector collides with an existing one.

Trade-offs

A fork test is fast and free but only as good as the block you fork; a testnet rehearsal is slower and drifts from real state. A timelock (TimelockController with a 48h min delay) buys holders exit time but slows emergency fixes. Rollback is cheap only if the upgrade didn't migrate state: upgrading back to the old implementation restores code, not mutated storage, so any migration must be reversible or gated behind the timelock.

Failure modes and detection

  • Slot collision → validateUpgrade throws.
  • Initializer takeover → plugin flags the unprotected initializer; on-chain, watch for Initialized events after deploy.
  • Selector clash → diff the 4-byte selectors of the old and new ABIs.
  • Removed function → callers revert; check the ABI diff.
  • Wrong implementation → fork rehearsal reads the EIP-1967 implementation slot and asserts the address.
  • Admin error → simulate the multisig transaction before signing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Preflight a user transaction.

Answer

Assumptions I'd state first. EVM chain, an EOA signing one transaction from a wallet we control, and the goal is to avoid burning gas on a revert and avoid stranding a nonce. If it's an ERC-4337 smart account, the preflight moves to eth_call on the EntryPoint's simulateValidation and the shape changes.

The answer. Preflight is three RPC calls against one pinned block, then a re-check of the state-sensitive bounds immediately before signing.

  1. Pin a block number and eth_call the exact from, to, value, data at that block. This runs the real call against the real state. A revert throws with revert data: decode it (Error(string) is selector 0x08c379a0; custom errors need the ABI) so the user sees "insufficient allowance" instead of "execution reverted".
  2. eth_estimateGas with the same parameters and the same block tag. Apply a margin: 30% is a sane default for anything touching storage. The reason is EIP-2929: a cold SLOAD costs 2,100 gas and a warm one 100, and SSTORE costs 20,000 going zero→non-zero versus 5,000 non-zero→non-zero. The estimate is computed at one state and cannot predict which side of that it lands on.
  3. Re-read nonce (eth_getTransactionCount(addr, "pending")), ERC-20 allowance, and native balance against gasLimit × maxFeePerGas + value right before signing. If any moved, re-simulate.

Why this works and where it breaks: eth_call evaluates a hypothetical execution at a chosen state and discards it. It does not reserve the nonce, the allowance, or the pool. The simulation is a snapshot; every failure lives in the gap between snapshot and inclusion.

Trade-offs.

  • latest vs pending. latest is reproducible: you can name the block and re-run it. pending reflects the mempool but is node-local, so two providers disagree and a clean pending sim can still land after a state change. Use latest for the pre-sign check, a pending re-sim as a last look, and treat disagreement between them as a signal the transaction is ordering-sensitive.
  • Client-side eth_call vs a simulation service. Client-side is free, private, and uses your node's state. Tenderly or Alchemy's alchemy_simulateExecution give you internal call traces, state overrides, and forked-state simulation: worth it for a three-hop swap, not for a plain transfer. The cost is shipping calldata to a third party and an extra round trip.
  • When to skip: idempotent, low-value calls where a revert costs only gas and latency matters. Never skip value-bearing transfers, approvals, or anything with a slippage bound.

Failure modes, with detection.

failuredetectioncost
state race (nonce or allowance moved)re-sim at pending before broadcast; receipt status: 0x0gas burned, user retries
wrong senderassert the sim from equals the signing addressmsg.sender checks pass in sim, fail on chain
front-run on a swapslippage bound (amountOutMin / amountOutMinimum); re-quote if output moves more than a few bpsvalue extracted
gas underestimatecompare the estimate to debug_traceCall gas; a margin under 10% is a red flagout-of-gas, retry
provider skewpin one block and one provider for sim + estimate + broadcastsim and inclusion disagree
sim bypass in UIinstrument the sign path; count signatures with no preceding eth_callships an unvalidated transaction

The check, in viem:

TypeScript
const blockNumber = await client.getBlockNumber();          // pin once
const req = { account, to, value, data, blockNumber };

await client.call(req);                                     // throws with the revert reason
const gas = await client.estimateGas(req);
const gasLimit = (gas * 130n) / 100n;                       // 30% margin

const nonce = await client.getTransactionCount({ address: account.address, blockTag: 'pending' });
const allowance = await token.read.allowance([account.address, spender]);
if (allowance < amount) throw new Error('allowance moved since simulation');

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Build a consistent portfolio read.

Answer

What a strong candidate says first

A portfolio read is consistent when every position in it was observed at the same chain state. "Same time" is not a thing you can ask for; "same block" is. So the answer is: pick one reference block, pin every read to it, and carry the block hash so you can prove later that the state you read still exists.

Assumptions I'd state up front: EVM chains, JSON-RPC providers, reads only (no writes), and the portfolio spans several contracts. Possibly several chains.

The mechanism

eth_call takes a block parameter. If you omit it, the node defaults to latest, and each call resolves latest independently. Between two calls a block can land, so call A reads head N and call B reads head N+1. If that block contained a swap by the user, you now sum a pre-swap balance with a post-swap one: the portfolio double-counts or drops a position. That is the whole bug: latest is not a snapshot, it is a moving pointer resolved per call.

Pinning fixes it because the node executes every call against the same state root.

JavaScript
// ethers v6, Node 20
const provider = new JsonRpcProvider(RPC_URL);

// 1. Pin once for the whole read
const head = await provider.getBlock("latest");   // eth_getBlockByNumber
const blockTag = head.number;
const blockHash = head.hash;                        // keep this

// 2. One multicall, per-call failure allowed
const mc = new Contract(
  "0xcA11bde05977b3631167028862bE2a173976CA11",     // Multicall3, same address on 270+ chains
  MULTICALL3_ABI, provider);

const calls = tokens.map(t => ({
  target: t, allowFailure: true,
  callData: erc20.encodeFunctionData("balanceOf", [user]),
}));
const results = await mc.aggregate3.staticCall(calls, { blockTag });
// results[i] = [success: bool, returnData: bytes]

Trace: why latest drifts

Three-token read, no pinning, Ethereum mainnet:

  • t=0 ms: balanceOf(A) at head 21,000,000 → 100 USDC
  • t=40 ms: block 21,000,001 lands; it contains the user's swap
  • t=45 ms: balanceOf(B) at head 21,000,001 → post-swap

The sum mixes two states. Pinned to 21,000,000, all three calls execute against one state root and the sum is internally consistent.

Trade-offs

Pin toConsistencyFreshnessNotes
latest numberPer-readNewestReorg-exposed; hash can vanish
Block hash (EIP-1898)Per-readNewestReorg-proof, but not every provider accepts blockHash
safePer-read~1 epoch (~6.4 min)One epoch behind head
finalizedPer-read~2 epochs (~12.8 min)2 × 32 slots × 12 s = 768 s; reorg-proof

Multicall vs individual calls: multicall is one round trip and one state root, but a single reverting call can abort the batch unless you use aggregate3 with allowFailure. Individual pinned calls are simpler to debug and let you retry one leg.

When not to pin: liquidation bots and live price feeds need the newest state; pinning to finalized there is 12.8 minutes of staleness. Read latest and accept drift, or read from one provider.

Failure modes and how you catch them

  • Reorg between pin and read: re-fetch eth_getBlockByNumber(n) and compare the hash; mismatch means retry.
  • Endpoint lag: pinned block above the provider's head returns "block not found"; compare eth_blockNumber across two providers.
  • Unsupported tags: some providers reject finalized/safe or EIP-1898 blockHash with error -32602; fall back to a number.
  • Archive pruning: Geth in full mode keeps only the last 128 states; older pins fail with "missing trie node". Use an archive node for deep history.
  • Mixed chains: call eth_chainId per provider and assert it matches the expected chain.
  • Partial multicall failure: success=false means missing, not zero; surface it as unknown.
  • Cached head: a load-balanced provider can serve a stale head; compare block hashes across replicas.

Return the block number, hash, and a per-position confirmed | stale | unknown flag to the caller. That is the read a reviewer can trust.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Implement resilient wallet-provider state.

Answer

Core answer (first 90 seconds). Treat the provider as a versioned context, not a global. Every read and every signature is bound to a snapshot {epoch, chainId, accounts} captured at call time. When the wallet fires chainChanged, accountsChanged or disconnect, you bump the epoch, abort in-flight requests, and re-derive all chain-bound state: balances, allowances, contract addresses, pending transaction intent. Signing is gated on the snapshot still matching the live context, so a request that started on chain 1 can never be confirmed as a chain-1 action after the user moved to chain 137.

Why events race. EIP-1193 events are emitted out of band from the request/response cycle. eth_sendTransaction is a long-lived promise: it stays open while the user reads the confirmation popup. The user can switch networks in that window, so chainChanged fires while your request is in flight. The promise then settles against a context that no longer exists. Nothing in the provider serialises these; you have to.

TypeScript
// EIP-1193 provider; checked against MetaMask provider API, 2024
const SUPPORTED = new Set([1, 137, 8453, 42161]);

type Snap = { epoch: number; chainId: number; accounts: string[] };

class WalletState {
  private epoch = 0;
  private snap: Snap = { epoch: 0, chainId: 0, accounts: [] };
  private inflight = new AbortController();

  constructor(private provider: EIP1193Provider) {
    provider.on('chainChanged', (hex: string) =>
      this.onChange(parseInt(hex, 16)));
    provider.on('accountsChanged', (accts: string[]) =>
      this.onChange(this.snap.chainId, accts));
    provider.on('disconnect', () => this.onChange(0, []));
  }

  private onChange(chainId: number, accounts?: string[]) {
    this.epoch += 1;
    this.inflight.abort();                 // cancel stale reads
    this.inflight = new AbortController();
    this.snap = { epoch: this.epoch, chainId,
                  accounts: accounts ?? this.snap.accounts };
    // re-derive: balances, allowances, deployment addresses for chainId
  }

  async send(tx: object) {
    const { epoch, chainId } = this.snap;
    if (!SUPPORTED.has(chainId)) throw new Error(`unsupported chain ${chainId}`);
    const hash = await this.provider.request(
      { method: 'eth_sendTransaction', params: [tx] });
    if (epoch !== this.snap.epoch)
      throw new Error('context changed mid-flight; tx may be on another chain');
    return hash;
  }
}

Trace. t0: load, eth_chainId → "0x1", epoch=1. t1: user clicks Swap; send captures epoch=1, chainId=1, passes the SUPPORTED gate, calls eth_sendTransaction. t2: MetaMask opens the confirmation; user switches to Polygon in the popup. t3: chainChanged "0x89" fires → epoch=2, inflight.abort(), chainId=137. t4: the pending send settles, if it resolves with a hash, epoch(1) !== snap.epoch(2) and we throw instead of reporting a chain-1 swap; if it rejects, we surface the rejection. t5: UI re-derives balances and addresses on 137.

Trade-offs. Re-derive-on-every-event is simple but thrashes when a wallet emits several events in a burst. An explicit state machine (disconnected → connected → wrong-chain → ready) gates the UI and coalesces bursts, at the cost of more states to keep consistent. Decide by whether you sign: if the surface only reads, drop the epoch guard and re-render on events; the moment you sign, the guard is mandatory.

failure modehow it shows updetection
wrong-chain signingtx lands on a chain you didn't intendassert chainId before every signature
stale accountold address's balance still renderedbind reads to the captured epoch
duplicate listenershandler runs twice, double submitremove on unmount; React StrictMode double-mounts
malicious provider dataeth_chainId disagrees with your RPCcross-check against your own node
silent switchchain changed with no chainChangedre-read eth_chainId before each signature

For wallet_switchEthereumChain (EIP-3326), error code 4902 means the chain isn't added: fall back to wallet_addEthereumChain rather than assuming the switch succeeded.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Design a permit-like signed authorization.

Answer

Clarify first. Three things decide the shape: is the signer an EOA or a smart-contract wallet (EIP-1271), does a relayer pay gas (so the signature must be self-contained and replay-safe), and is the authorization single-use or batchable. Assume EOA signer, relayer-paid, single-use: that is the EIP-2612 permit() case.

Core answer. A permit-like authorization is an EIP-712 typed struct signed off-chain and consumed on-chain exactly once. The signature commits to two hashes: the domain separator, which binds name, version, chainId and verifyingContract, and the struct hash, which binds the intent. The contract recomputes both, recovers the signer, and increments the nonce before any external call.

Mechanism. EIP-712 defines the digest as keccak256("\x19\x01" || domainSeparator || structHash). The \x19\x01 prefix makes the payload un-signable as a valid RLP transaction, so a wallet cannot be tricked into signing a raw tx. The domain separator is

keccak256(abi.encode(
  keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
  keccak256(bytes(name)), keccak256(bytes(version)), chainId, verifyingContract))

Because chainId and verifyingContract are inside the digest, the same struct signed for chain 1 is invalid on chain 137, and the same struct signed for contract A is invalid against contract B: that is the whole cross-domain replay defence, and it is why the domain fields are not optional.

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

contract SignedAction {
    bytes32 private constant ACTION_TYPEHASH = keccak256(
        "Action(address signer,address target,uint256 value,uint256 nonce,uint256 deadline)");
    bytes32 private immutable _DOMAIN_SEPARATOR;
    uint256 private immutable _CACHED_CHAIN_ID;
    mapping(address => uint256) public nonces;

    constructor() {
        _CACHED_CHAIN_ID = block.chainid;
        _DOMAIN_SEPARATOR = _buildDomainSeparator();
    }

    function _buildDomainSeparator() private view returns (bytes32) {
        return keccak256(abi.encode(
            keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
            keccak256("SignedAction"), keccak256("1"), block.chainid, address(this)));
    }

    function execute(address signer, address target, uint256 value,
                     uint256 deadline, bytes calldata sig) external {
        require(block.timestamp <= deadline, "expired");
        uint256 nonce = nonces[signer];
        nonces[signer] = nonce + 1;                 // consume before any external call
        bytes32 structHash = keccak256(abi.encode(
            ACTION_TYPEHASH, signer, target, value, nonce, deadline));
        bytes32 digest = keccak256(abi.encodePacked("\x19\x01", _DOMAIN_SEPARATOR, structHash));
        require(ECDSA.recover(digest, sig) == signer, "bad sig");
        (bool ok, ) = target.call{value: value}("");
        require(ok, "call failed");
    }
}

Trace. Signer 0xA11ce, nonces[0xA11ce] == 0, deadline == 1000, block.timestamp == 900. The deadline check passes; the nonce is read as 0 and written to 1; structHash is built over nonce 0; ECDSA.recover returns 0xA11ce; the call executes. Now replay the identical calldata at block.timestamp == 950: the nonce read is 1, so structHash differs, the digest differs, and recover returns some other address. require reverts with bad sig. The same holds for reentrancy: if target calls back into execute with the same signature, the nonce is already 1, so the second digest cannot recover to the signer. Consuming the nonce before the external call is what makes that true; incrementing after would let the reentrant call see nonce 0 again.

Failure modes and detection.

FailureCauseDetection
Cross-chain replayDomain separator omits chainId, or is cached and not rebuilt after a forkSign the same struct on a testnet fork; if it verifies, the separator is stale
Nonce reuseNonce incremented after the external call, or a bitmap nonce read without a writeReplay the exact calldata in a Foundry test; expect revert
Missing deadlinedeadline absent from the struct, so a signature never expiresFuzz block.timestamp far past signing time
Domain-version driftversion bumped in the contract but not in the client's typed-data payloadCompare _DOMAIN_SEPARATOR against the wallet's computed hash in CI
MalleabilityRaw ecrecover accepts high-s signatures, giving two valid sigs per messageUse ECDSA.recover (OpenZeppelin), which rejects s > secp256k1n/2 and v ∉ {27,28} per EIP-2; EIP-2098 packs v into the top bit of s
Contract-wallet signerecrecover returns an address that never signed; the wallet validates via EIP-1271If signer.code.length > 0, call isValidSignature(digest, sig) instead

What would change the decision. A smart-contract signer swaps ecrecover for EIP-1271. Parallel or batched authorizations want an unordered nonce bitmap rather than a monotonic counter, so one stuck signature does not block the rest. If the authorization is a token approval, use EIP-2612 permit(owner, spender, value, deadline, v, r, s) directly rather than inventing a struct. And the signing UX is part of the design: the wallet must render the decoded intent, because a domain separator that is correct on-chain still loses to a user who signs a hash they cannot read.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Design a reorg-safe event indexer.

Answer

First, clarify: which chain, and what does the consumer do with the events? A UI showing balances can tolerate a reorg; a deposit credit that moves money cannot. I'll assume an EVM chain, logs read via eth_getLogs, and a consumer that credits balances.

The core idea: canonicality belongs to the block, not the log. Every row is keyed by (chain_id, block_number, block_hash, tx_hash, log_index). Because block_hash is in the key, a log that reappears in a different block is a new row, not an update: the old row stays as an orphaned record. The cursor is (number, hash), and before advancing I check that the next block's parentHash equals the stored hash of the previous block. That single check is the whole reorg detector.

When it fires, I walk back until stored hash == chain hash at that height. Linear is fine: reorgs are shallow; binary search if you're paranoid. Everything above the fork point is soft-deleted (orphaned_at set), then I re-fetch logs from the fork point to the tip and insert. Idempotency comes from a unique constraint on the key plus INSERT ... ON CONFLICT DO NOTHING, so a replay after a crash is free.

Worked trace: cursor at 19,000,000 / 0xaaa. Fetch 19,000,001, parentHash 0xbbb ≠ 0xaaa. Walk back: 19,000,000 stored 0xaaa, chain says 0xccc. Mismatch. 18,999,999 stored 0xddd, chain says 0xddd: match. Fork point 18,999,999. Orphan rows above it, re-fetch 19,000,000..tip, insert with the new hashes. The deposit credited from the old 19,000,000 log is now orphaned; the replacement log credits it again under a different key.

Finality: Ethereum exposes safe (justified, ~1 epoch) and finalized (~2 epochs = 64 slots × 12s ≈ 12.8 min). Only finalized effects are irreversible. On an L2 like Base or Arbitrum, the sequencer's safe tag arrives in seconds but the real finality is the L1 batch: pick the one your money movement needs.

Alternatives: a confirmation-depth heuristic (wait N blocks, never rewind) is simpler and fine for a UI, but it's a guess about finality and it silently fails on the day the chain reorgs deeper than N. Ethereum mainnet reorged 7 blocks on 2022-05-25. Full re-index from genesis on every reorg is correct and unaffordable. The hash-keyed store with rewind is what I'd ship. Deciding criterion: cost of a wrong credit vs cost of 12.8 minutes of latency.

Failure modes and how I'd catch them:

  • Duplicate effects: key omitted block_hash. Detect: count distinct effect keys per (tx_hash, log_index); >1 is a bug.
  • Orphaned deposits: credited from a reorged block. Detect: reconcile sum of credits per address against eth_getBalance at finalized height; nonzero delta is the orphan.
  • Missed removed logs: eth_getLogs over a range spanning a reorg returns only the new chain's logs, so append-only never sees the removal. Detect: re-query the same range and diff stored hashes against the response.
  • Provider inconsistency: two RPCs disagree at the tip. Detect: query the same height from two providers, compare hash; mismatch means don't advance.
  • Deep reorg: fork point below the finalized watermark. Detect: that's a chain-level incident; page a human, don't auto-reconcile.
  • Decoder migration: ABI change re-decodes old logs. Detect: store decoder_version per row, re-run in shadow, diff.
  • Non-event state changes: native transfers and self-destructs emit no log. Detect: balance reconciliation at finalized height.

What would change the decision: if the chain had single-slot finality, or the consumer were read-only, the rewind machinery is overkill and a depth heuristic wins.

Curated: · Written: · Reviewed:

Difficulty: Hard