Skip to content
Tech Interview Prep
Technical interview guide

Smart Contract Security & Common Vulnerabilities

Why smart contract bugs are uniquely costly (immutable, public, and directly holding funds) and the vulnerability classes that recur across major exploits.

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

Scope: OWASP Smart Contract Security Verification Standard and Smart Contract Top 10:2026 reviewed 2026-09-04; Solidity latest security guidance; OpenZeppelin Contracts 5.x and Upgrades documentation; Chainlink Data Feeds documentation.

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

Walk me through how an authorization check that uses tx.origin instead of msg.sender can be exploited, and show how the check should be written instead.

Answer

Start with the call-chain distinction. tx.origin is the EOA that signed and sent the transaction; it stays constant for the whole transaction. msg.sender is the immediate caller of the current call frame. In A -> B -> C, C sees tx.origin == A and msg.sender == B. Authorization must be based on msg.sender because that is the identity you can verify at the point of the check; tx.origin is just the transaction's originator and can be an EOA that was tricked into starting the chain.

The exploit: a wallet contract has require(tx.origin == owner). An attacker deploys a phishing contract with a function that calls the wallet's withdraw to the attacker. The attacker gets the owner to call the phishing contract (fake airdrop claim, malicious dapp, a signed message that triggers a call). Inside that call, the phishing contract calls the wallet. At the wallet, tx.origin is still the owner's EOA, so the check passes, but msg.sender is the phishing contract. Funds leave.

Trace: owner EOA -> Phishing.claim() -> Wallet.withdraw(attacker) At Wallet: tx.origin = owner, msg.sender = Phishing. tx.origin == owner is true. msg.sender == owner would be false.

The fix is require(msg.sender == owner). Better, use a role-based modifier: OpenZeppelin AccessControl's onlyRole(WITHDRAWER_ROLE) or Ownable's onlyOwner, both of which check msg.sender. If you need multiple roles, grant them explicitly and check the role in the modifier. Never use tx.origin for authorization.

Why msg.sender is correct: it is the address that directly invoked the function. The EVM sets it to the caller and an intermediate contract cannot spoof it. tx.origin can be an EOA that is not the intended authorizer, and it breaks under account abstraction (ERC-4337) where tx.origin may be a bundler, and under meta-transactions where a relayer submits. It also breaks multisig: if a 3-of-5 multisig calls a contract with a tx.origin check, any single signer who initiates the transaction passes the check, bypassing the threshold.

Failure modes to name: phishing, malicious intermediate contract, compromised front-end, multisig threshold bypass, account abstraction incompatibility, meta-transaction relayers. Detection: Slither's tx-origin detector, manual review of every require on tx.origin, and a test that routes a privileged call through an attacker contract and asserts it reverts.

solidity // vulnerable contract Wallet { address public owner; function withdraw(address to, uint256 amount) external { require(tx.origin == owner, "not owner"); payable(to).transfer(amount); } } // fixed import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; contract Wallet is Ownable { function withdraw(address to, uint256 amount) external onlyOwner { payable(to).transfer(amount); } }

Checked against Solidity 0.8.24 and OpenZeppelin Contracts 5.x.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-25

How can an attacker force ETH into a contract without triggering its payable logic, and why does deriving balances or share prices from address(this).balance make a protocol exploitable?

Answer

Assume a Solidity 0.8.x contract on Ethereum mainnet, post-Dencun. The core answer: address(this).balance is the raw ETH the EVM holds for the address, not a ledger of who deposited what. Three paths add ETH without calling the contract's receive()/fallback():

  1. selfdestruct(payable(target)) from a helper contract. Since EIP-6780 (Dencun, March 2024) selfdestruct only deletes code if the contract was created in the same transaction, but it still transfers the balance, so the forced-ETH primitive survives.
  2. Pre-computed address funding: CREATE2 gives a deterministic address; send ETH to it before deployment, so the contract is born with a balance and no deposit event.
  3. Block-level payments: the fee recipient / coinbase can be a contract address, crediting ETH with no call.

None of these emit your Deposit event or update your totalDeposits. So any invariant of the form address(this).balance == totalDeposits is false the moment someone forces ETH in.

Two failure classes:

DoS. A strict equality or upper-bound check reverts forever. require(address(this).balance == totalDeposits) bricks deposits and withdrawals for the cost of 1 wei of forced ETH. This is the guaranteed impact and needs no victim.

Value corruption. If share price or an exchange rate reads the balance, the injected ETH is treated as owned by existing holders. Worked example, vault with totalAssets() = address(this).balance:

solidity function deposit() external payable { uint256 assets = address(this).balance; // includes forced ETH uint256 shares = totalSupply == 0 ? msg.value : msg.value * totalSupply / assets; _mint(msg.sender, shares); }

Vault is empty. Attacker forces 100 ETH in via selfdestruct. Now address(this).balance == 100 ether, totalSupply == 0. Attacker deposits 1 wei; totalSupply == 0 so they mint 1 wei of shares. They redeem 1 wei of shares for 1 * 100 ether / 1 = 100 ETH. The vault paid out 100 ETH against a 1 wei deposit. (If the 100 ETH was the attacker's own, the net is a wash: the theft case is when the forced ETH is external, e.g. a third-party selfdestruct or a coinbase payment, or when the inflated balance gates a payout in a different asset.)

The same arithmetic misprices honest depositors: with 10 ETH and 10 shares, forcing 90 ETH in makes the price 10 ETH/share, so a 10 ETH deposit mints 1 share instead of 10.

Mitigation. Track deposits in explicit storage and never read address(this).balance for accounting:

solidity uint256 public totalDeposits; function deposit() external payable { totalDeposits += msg.value; uint256 shares = totalSupply == 0 ? msg.value : msg.value * totalSupply / totalDeposits; _mint(msg.sender, shares); }

totalDeposits only moves through your code, so forced ETH is inert. If you need the real balance for a sweep, compute address(this).balance - totalDeposits and treat it as unowned surplus, not depositor funds.

Detection. Grep for address(this).balance in accounting paths; add an invariant test that force-sends ETH (a selfdestruct helper in Foundry) and asserts share price and totalDeposits are unchanged; monitor address(this).balance != totalDeposits as an alert, not a revert.

When balance is fine. A contract with no accounting: a pure forwarder, or one that only ever receives via receive() and immediately forwards: can read balance. The bug is deriving ownership or price from it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-1

Review a withdrawal function for reentrancy.

Answer

What I'd say first (90 seconds)

Reviewing a withdrawal for reentrancy, I check four things in order. One: does any state that gates the payout change after the external call? Two: is every entry point that touches that state guarded, not just the one in front of me? Three: can the recipient re-enter through a token hook rather than ETH? Four: do other protocols read my state mid-callback? If the answer to one is "yes, after", the function is exploitable and nothing else matters until that's fixed.

The bug, concretely

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

contract Vault {
    mapping(address => uint256) public balance;

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

    function withdraw() external {
        uint256 amount = balance[msg.sender];
        require(amount > 0, "nothing to withdraw");
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "send failed");
        balance[msg.sender] = 0;   // effect after interaction
    }
}

The attacker deposits 1 ETH into a vault already holding 5 ETH from other users, then calls withdraw(). receive() calls withdraw() again before the first call returns:

  1. withdraw() reads amount = 1 ETH, passes the require, sends 1 ETH. Vault: 6 → 5 ETH.
  2. receive() sees address(vault).balance == 5 ETH, re-enters. balance[Attacker] is still 1 ETH, so amount = 1 ETH again. Vault: 5 → 4.
  3. Steps repeat until the vault holds under 1 ETH. The attacker has received 6 ETH for a 1 ETH deposit.
  4. The stack unwinds and balance[Attacker] = 0 executes six times.

The fix

SOLIDITY
import {ReentrancyGuard} from "@openzeppelin/contracts/utils/ReentrancyGuard.sol";

contract Vault is ReentrancyGuard {
    mapping(address => uint256) public balance;

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

    function withdraw() external nonReentrant {
        uint256 amount = balance[msg.sender];
        require(amount > 0, "nothing to withdraw");
        balance[msg.sender] = 0;              // effect before interaction
        (bool ok, ) = msg.sender.call{value: amount}("");
        require(ok, "send failed");
    }
}

Zeroing first is what actually kills the attack: the re-entrant call reads amount = 0 and reverts. The guard is belt-and-braces for the next function someone adds.

Trade-offs

approachcoststopsmisses
CEI ordering0 gassingle-function reentrancycross-function entry; regresses on the next edit
nonReentrant~20k gas on the first guarded call in a tx (cold SLOAD + 0→1 SSTORE), warm afterevery guarded entry pointunguarded functions, view functions
pull withdrawal0 extra gas, one tx per userpush-failure DoS, unbounded loopsnothing about reentrancy by itself
transfer()/send() 2300 stipend—naive reentrancybreaks contract wallets; EIP-1884 raised SLOAD to 800 gas, so a recipient that touches storage runs out

OpenZeppelin 5.1 ships ReentrancyGuardTransient, which uses EIP-1153 transient storage (Cancun) to cut the guard to a few hundred gas.

Failure modes and how I'd catch them

  • Cross-function reentrancy. withdraw and transfer both read balance; only withdraw is guarded. Catch it by listing every external function that reads or writes the invariant, then fuzzing with a mock whose receive() calls the sibling function.
  • Token hooks. ERC-777 tokensReceived and ERC-1155 onERC1155Received fire mid-transfer with no ETH involved. Catch it with an integration test using a hook-enabled token.
  • Read-only reentrancy. A view like totalAssets() returns a stale value during the callback and an external protocol prices off it. Catch it by grepping for view functions other protocols call and checking them mid-callback.
  • Guard composition. Per-function guards don't stop cross-function entry; one contract-wide guard does. Verify the guard sits on every entry point.
  • Failed sends. If you don't revert, you must re-credit the balance or you've burned the user's funds. Test with a recipient that reverts.

Finally, a Foundry invariant_ asserting address(this).balance >= sum(balance) catches the class of bug, not just this instance.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Test a contract for cross-function and cross-contract reentrancy.

Answer

Core answer. Cross-function reentrancy is a callback re-entering a different entry point of the same contract that reads or writes state the outer call left inconsistent. Cross-contract reentrancy is the callback re-entering a second contract that trusts the first's mid-update state: read-only reentrancy is the common case. So you don't test function names; you test shared storage and the call graph.

Assumptions worth stating: Solidity ^0.8 (checked arithmetic, so underflow reverts), a token with a transfer hook (ERC-777, or an ERC-20 with a callback), and at least two external entry points touching the same storage.

Mechanism, with a trace.

SOLIDITY
contract Vault {
    uint256 public totalAssets;
    uint256 public totalShares;
    mapping(address => uint256) public shares;
    IERC20 public asset;

    function pricePerShare() external view returns (uint256) {
        return totalAssets * 1e18 / totalShares;
    }

    function withdraw(uint256 s) external {
        uint256 assets = s * totalAssets / totalShares; // price read while consistent
        shares[msg.sender] -= s;
        totalShares -= s;                  // (1) shares burned
        asset.transfer(msg.sender, assets); // (2) external call
        totalAssets -= assets;             // (3) assets removed last
    }
}

Start: totalAssets = 100e18, totalShares = 100e18, price 1e18. Attacker holds 20e18 shares and calls withdraw(10e18). assets = 10e18 * 100 / 100 = 10e18. At (1) totalShares drops to 90e18. During (2) the token hook fires and pricePerShare() now returns 100e18 * 1e18 / 90e18 = 1.111e18: inflated 11% because shares were burned but assets not yet removed. A lending market at 75% LTV reads that price and lends 8.33e18 against the attacker's remaining 10e18 shares instead of 7.5e18. At (3) totalAssets = 90e18, totalShares = 90e18, price back to 1e18; the 10e18 shares are worth 10e18 but 8.33e18 is borrowed: 83% LTV, undercollateralized by 0.83e18.

Testing it. Two layers. Hand-written adversarial receiver pins the ordering:

SOLIDITY
contract Reenter is IERC777Recipient {
    Vault v; Lend l; uint256 step;
    function tokensReceived(...) external {
        if (step == 0) { step = 1; l.borrow(8.33e18); }   // cross-contract
        else if (step == 1) { step = 2; v.withdraw(1e18); } // cross-function
    }
}

Invariant fuzzing covers the paths you didn't enumerate: a Foundry handler exposing every entry point, targetContract(address(handler)), fail_on_revert = false, depth = 100, runs = 256, with invariants like totalAssets >= sum of redeemable shares and pricePerShare unchanged across a single tx. Echidna for multi-contract sequences.

Trade-offs. Invariant fuzzing finds unknown siblings but needs a handler that actually reaches every entry point, and 256 runs × depth 100 is slow. Hand-written receivers are fast and pin exact call ordering, but only cover paths you already imagined. Decide by entry-point count: one state-mutating entry point → a receiver test suffices; two or more sharing storage → invariant fuzzing is the default.

failurehow it hidesdetection
unguarded siblingwithdraw has nonReentrant, withdrawTo doesn'tgrep every external call site; reenter each sibling in a test
read-only reentrancyview returns stale price mid-callbackcall the view inside the hook, compare to post-tx value
multicallguard is per-call, not per-batchbatch two entry points in one multicall
inherited hookbase _beforeTokenTransfer calls outwalk the inheritance chain for external calls

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Prevent consumers from observing an inconsistent share price during callbacks.

Answer

Assume an ERC-4626 vault where share price is totalAssets / totalSupply, and the asset can invoke a callback (ERC-777 tokensReceived, ERC-721 onERC721Received, or a flash-loan callback). The consumer reads convertToShares or previewRedeem during that callback.

The direct answer: make the vault's accounting consistent at every point a callback can run. That means checks-effects-interactions: burn or mint shares and update totalAssets / totalSupply before any external call that can reenter. If the external call is unavoidable before accounting can be finalized, add a read-only reentrancy guard that makes view functions revert while the state-changing function is executing, or use stored accounting so the callback sees the pre-operation state.

Trace a withdrawal. Vault starts with totalAssets = 1000, totalSupply = 1000. A user withdraws 100 shares. Bad order: burn 100 shares first, so totalSupply = 900, then transfer 100 assets. During the transfer, the user's fallback calls a consumer. The consumer calls convertToShares(100): 100 * 900 / 1000 = 90. It sees 100 assets as worth 90 shares, but after the transfer totalAssets = 900, totalSupply = 900, and 100 assets is worth 100 shares. The consumer observed an inflated share price of 1000 / 900 = 1.111 instead of 1.0. Good order: burn 100 shares and decrement totalAssets to 900 before the transfer. During the callback, convertToShares(100) = 100 * 900 / 900 = 100. Consistent.

Deposits have a subtler case. If totalAssets() returns asset.balanceOf(address(this)), then transferFrom increases the vault's balance before shares are minted. With totalAssets = 1000, totalSupply = 1000, a 1000-asset deposit makes the live balance 2000. If the asset is ERC-777, the vault's tokensReceived hook runs before minting. A consumer calling convertToShares(1000) sees 1000 * 1000 / 2000 = 500 shares, but the depositor will receive 1000 shares. Fix: use a stored totalAssets variable updated only after minting, or guard the view. With stored accounting, the callback sees totalAssets = 1000, totalSupply = 1000, so convertToShares(1000) = 1000: the pre-deposit state, which is consistent.

approachwhat it preventscost / trade-off
CEI + stored accountingintermediate state never exposed; callback sees pre-op or post-op statedonations are not reflected until an explicit update; more accounting code
CEI + live balancesimple, reflects donationsvulnerable to read-only reentrancy on deposit; needs a view guard
nonReentrant on state-changing functionsreentrant state changesdoes not stop view reads; must be paired with a view guard
nonReentrantView on convertToShares / previewRedeeminconsistent reads during a callbackbreaks composability for consumers that read mid-callback; storage lock costs gas, transient storage (EIP-1153, Solidity 0.8.24) is cheaper

A read-only guard looks like this:

SOLIDITY
// Solidity 0.8.24, EIP-1153
contract Vault {
    uint256 private transient _locked = 1;

    modifier nonReentrant() {
        require(_locked == 1, "reentrant");
        _locked = 2;
        _;
        _locked = 1;
    }

    modifier nonReentrantView() {
        require(_locked == 1, "read-only reentrancy");
        _;
    }

    function deposit(uint256 assets) external nonReentrant returns (uint256 shares) {
        asset.transferFrom(msg.sender, address(this), assets);
        totalAssets += assets;
        shares = convertToShares(assets);
        _mint(msg.sender, shares);
    }

    function convertToShares(uint256 assets) public view nonReentrantView returns (uint256) {
        return assets * totalSupply / totalAssets;
    }
}

If you skip this, a consumer can borrow against inflated collateral during the callback. Detect it with a fork test: a malicious consumer calls convertToShares inside the callback and asserts the result equals the pre-operation or post-operation price, never an intermediate. Also assert the round-trip invariant convertToShares(convertToAssets(shares)) == shares within rounding, and check that totalAssets and totalSupply move together in the same transaction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Harden a low-level external integration.

Answer

Clarify, then assume. First question: is the callee a known, standard-conforming contract, or an address and calldata the caller hands you? Those are different problems. Take the hard case: an executor that accepts (address target, bytes calldata data) from the user, holds tokens, and must not book a trade that never happened. Solidity 0.8.24, mainnet EVM.

Core answer. A low-level call returns (bool success, bytes memory returndata). success == true means exactly one thing: the callee did not revert. It does not mean the target is a contract, that it returned what you expect, or that your balances moved. So the answer is a fixed sequence: reject non-contracts, bound the calldata, check the return size before decoding, and verify the state delta you actually care about. The bool is a liveness signal, not a correctness proof.

The sequence, and why each step exists.

  1. require(target.code.length > 0). A call to an EOA succeeds and returns empty data. extcodesize is 0 while a contract's constructor runs, so this rejects EOAs but a contract can still slip through during construction: treat it as a guard, not a proof.
  2. Bound the calldata: check the selector against an allowlist and the length against the expected ABI layout, so a user can't smuggle a different function into a trusted target.
  3. Check returndata.length before abi.decode. USDT and similar tokens return nothing on transfer; a naive abi.decode(ret, (bool)) reverts on them. Decode only when ret.length == 32.
  4. Verify the state delta. This is the check that catches a callee that returns true and does nothing.
SOLIDITY
// Solidity 0.8.24
function exec(address target, bytes calldata data, uint256 minOut)
    external returns (bytes memory)
{
    require(target.code.length > 0, "not a contract");
    uint256 before = IERC20(token).balanceOf(address(this));

    (bool ok, bytes memory ret) = target.call(data);
    require(ok, "call reverted");

    if (ret.length > 0) {
        require(ret.length == 32, "bad return size");
        require(abi.decode(ret, (bool)), "returned false");
    }

    uint256 delta = IERC20(token).balanceOf(address(this)) - before;
    require(delta >= minOut, "delta too small");
    return ret;
}

Trace: the malicious fallback. Attacker passes their own contract as target; its fallback returns abi.encode(true) and transfers nothing. minOut = 1, before = 1000.

  • code.length > 0 → true, it's a contract.
  • target.call(data) → fallback returns 32 bytes ending in 01, no revert → ok = true.
  • ret.length == 32 → true; abi.decode → true → passes.
  • delta = 1000 - 1000 = 0; require(0 >= 1) → reverts.

The bool and the return check both pass; only the delta check stops it. That is the whole argument for measuring state instead of trusting the return value.

Trade-offs. If the callee is a known, standard ERC-20, a high-level IERC20(token).transfer(...) is better: the compiler decodes the return, reverts bubble with a reason, and you write less. Reach for low-level call only when the target or calldata is untrusted or non-standard. If the integration only reads, use staticcall: it reverts if the callee attempts a state write, which is a free guard. Deciding criterion: trusted and standard-conforming → high-level; arbitrary → low-level with the full sequence; read-only → staticcall.

Failure modes and how you catch them. Gas griefing: call forwards 63/64 of remaining gas, so a callee can burn your budget. Cap gas explicitly or use pull payments (transfer/send only forward a 2300 stipend, which is why they're not a general fix). Reentrancy: a callee that calls back into you mid-execution. Checks-effects-interactions plus a guard. Forged revert data: don't bubble raw revert bytes to users; decode known selectors only. Proxy targets: the implementation can change between your check and your call, so pin a code hash or accept the trust boundary explicitly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Safely accept multiple token contracts into a vault.

Answer

The answer in 60-120 seconds

"Is the asset list curated, or can anyone list? I'll assume governance allowlists assets and stores a per-asset config, and that this is an ERC-4626-style vault whose shares are priced off what it holds.

On those assumptions: treat every ERC-20 as untrusted code and never credit the amount you asked to move - credit the balance delta you actually observed. Route all token calls through SafeERC20 so a missing return value or a false one cannot pass silently. Normalize decimals once at listing time inside an explicit accepted range. Anything that breaks the accounting - fee on transfer, rebase, blacklist, transfer hook - either gets a defined semantic in the vault or the asset is refused. Then prove it against malicious token mocks, not against USDC."

Mechanism, and where it goes wrong

Return values. ERC-20 transfer/transferFrom are declared to return bool, but USDT does not return anything, and some tokens return false instead of reverting. OpenZeppelin's SafeERC20 (Contracts 5.x) treats empty returndata as success and reverts on false, so a token that lies cannot silently pass.

Balance deltas. The reason a delta catches fee-on-transfer is that the token debits the sender the full amount and credits the recipient less. Reading balanceOf(address(this)) before and after the transfer and crediting the difference makes the vault's accounting match reality by construction. Cost: two extra external calls per transfer - cold-account access alone is 2,600 gas under EIP-2929, plus the token's own storage read.

SOLIDITY
// Solidity ^0.8.20, OpenZeppelin Contracts 5.x
using SafeERC20 for IERC20;

error BadDecimals(uint8 d);
error NothingReceived(uint256 requested, uint256 received);

function deposit(address token, uint256 amount) external nonReentrant returns (uint256 shares) {
    uint256 before = IERC20(token).balanceOf(address(this));
    IERC20(token).safeTransferFrom(msg.sender, address(this), amount); // reverts on false/lying return
    uint256 received = IERC20(token).balanceOf(address(this)) - before;
    if (received == 0) revert NothingReceived(amount, received);
    shares = received * scale[token] * totalShares / totalAssets; // credit the delta, scaled
    accounted[token] += received;
}

function register(address token) external onlyGovernance {
    uint8 d = IERC20Metadata(token).decimals(); // not part of ERC-20; can revert
    if (d > 18) revert BadDecimals(d);
    scale[token] = 10 ** (18 - d);
}

Decimals. decimals() is not in the ERC-20 interface; it is an optional convention some tokens omit, return as 0, or lie about. Normalize to one internal precision at listing time, with the bound stated: accept 0-18 and reject anything above, so 10 ** (18 - d) cannot overflow and every asset has a single scale.

assetdecimals()raw depositinternal credit (18 dec)scale
USDC61,000,0001e181e12
WBTC8100,000,0001e181e10
DAI181e181e181
fee-on-transfer token61,000,000 requested, 990,000 arrive0.99e181e12

That last row is the arithmetic that matters: at a share price of 1.0, the depositor gets 990 shares, not 1,000. Credit the requested 1,000 and the vault is 10 units short - roughly 1% off the share price - and the next depositor can buy shares cheap. This is also the invariant to fuzz: after any sequence of deposits and withdrawals, sum(accounted) <= token.balanceOf(vault) for every listed asset.

Rebasing and hooks. A rebasing token (stETH-style) changes balanceOf with no transfer, so any share price read from live balances drifts. Either hold the non-rebasing wrapper (wstETH, not stETH) or state that rebases are absorbed by share price and test exactly that invariant. Tokens with transfer hooks (ERC-777, ERC-1363) can reenter deposit mid-transfer, so accounting must be updated before the external call, nonReentrant must be on every entry point, and the mock used in tests must call back in.

Trade-offs and when to refuse an asset

  • Delta-tolerant vs strict equality. Crediting the delta supports fee-on-transfer tokens but accepts any shortfall. Requiring received == amount rejects fee tokens outright and is the simpler default for user-funded deposits. Choose by who eats the fee: with delta crediting the depositor eats it; with strict equality the deposit just reverts.
  • Allowlist vs permissionless listing. Allowlisting costs governance latency per asset but lets you configure scale, caps and wrapper choice up front. Permissionless listing needs per-asset deposit caps and a quarantine state so a bad token cannot touch existing shares.
  • Refuse when decimals() reverts or exceeds 18 with no tested path, the token returns false or lies about the transfer, balances move outside transfers and no wrapper exists, or the token's blacklist/pause could freeze the vault's own balance (USDC-style) - mitigate that last one with pull-based claims so one frozen asset cannot block every withdrawal.

Failure modes to detect, not just mention: under-credit from fees shows up as accounted < balanceOf going negative on the solvency invariant; reentrancy shows up as shares minted twice in a malicious-mock test; rebase drift shows up as a monitoring alert on balanceOf(vault) diverging from accounted outside deposit/withdraw blocks.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Review optimized unchecked arithmetic.

Answer

Pin the language first. In Rust, i32::unchecked_add is unsafe and documented as undefined behaviour on overflow. It is not wrapping arithmetic. wrapping_add is the modular two's-complement operation. So a review of optimized unchecked arithmetic is a proof obligation: every call must be dominated by a proof that the operands cannot overflow, and that proof must cover every reachable state, including future callers.

What unchecked buys and costs

unchecked_add tells LLVM it may assume no overflow. That can remove overflow checks, narrow operations, and vectorize hot loops. Normal + in Rust is checked in debug builds and wraps in release by default; -C overflow-checks=on forces checks in release. debug_assert! is compiled out when debug assertions are off, so it is a development aid, not a safety net. assert! always runs.

The cost is UB if the proof is wrong. Do not use unchecked when inputs are untrusted, when the proof depends on runtime data you cannot bound, when wrapping is the intended semantics, or when overflow is acceptable and should be explicit. Use wrapping_add for hashes, checksums and PRNGs; checked_add or overflowing_add for validation; saturating_add for counters.

Failure modes and detection

failurewhy it happensdetectionoperational cost
Incorrect loop boundfor i in 0..n with n > len; unchecked index or arithmeticdebug_assert!(i < len), Miri, fuzzOOB read/write, UB
Narrowing castx as u32 truncates, then unchecked_add assumes no overflowu32::try_from(x), clippy cast_possible_truncationsilent wrong result, later UB
Underflowunchecked_sub when a < bdebug_assert!(a >= b), property test with a < bUB, wrong result
Optimizer assumptionsunchecked_add lets LLVM assume no overflow; a violated assumption can delete checksMiri; assert! at the boundary; cargo test --release with overflow-checks=on will not catch uncheckedsecurity, miscompilation
Future caller changesproof is local, callers changeencapsulate in a safe function with assert!; #[deny(unsafe_op_in_unsafe_fn)]; #[forbid(unsafe_code)] in modulesregression
Proof omits reachable statesonly happy path testedproperty-based testing over the full domain, Miri, fuzzingUB in production

Worked check

Rust
fn midpoint(lo: u32, hi: u32) -> u32 {
    assert!(lo <= hi);
    let diff = hi - lo;          // safe: lo <= hi
    let half = diff / 2;
    // lo + half <= lo + (hi - lo) = hi <= u32::MAX
    unsafe { lo.unchecked_add(half) }
}

Trace:

  • midpoint(10, 20): assert 10 <= 20. diff = 10, half = 5. unchecked_add(10, 5) = 15. Return 15.
  • midpoint(0, u32::MAX): diff = 4294967295, half = 2147483647. unchecked_add(0, 2147483647) = 2147483647. Return 2147483647.
  • midpoint(u32::MAX, u32::MAX): diff = 0, half = 0. unchecked_add(4294967295, 0) = 4294967295. Return 4294967295.
  • midpoint(20, 10): assert fails, panic before unchecked. No UB.

The proof is the comment plus the assert!. The assert! is the boundary that keeps future callers from violating the unchecked region. If the assert is too expensive for the hot path, move it to the public entry point and keep the unchecked region private and small.

Review checklist

  1. State the language and version. Rust 1.80+ has unchecked_add.
  2. Reject unchecked_add if the intent is modular; require wrapping_add.
  3. Require a written proof for every unchecked call: operands, bounds, and why the bound holds for all reachable states.
  4. Require an assert! at the API boundary, not only debug_assert!.
  5. Run Miri on tests and fuzz zero, maximum, and boundary transitions.
  6. Check casts with try_from and clippy cast_possible_truncation.
  7. Keep the unchecked region minimal and private; forbid unsafe in surrounding modules.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Design share conversion without exploitable rounding.

Answer

What I'd say first

Assume an ERC-4626-style vault: totalAssets of an underlying token, totalSupply of shares, and two conversions. The whole design reduces to one rule: every conversion rounds in the vault's favor, and the direction is fixed per operation, not chosen per call site.

  • deposit/mint: shares = assets * totalSupply / totalAssets, round down
  • withdraw/redeem: assets = shares * totalAssets / totalSupply, round down

Rounding down on both sides means a user can never extract more value than they put in, and splitting one action into many can only lose them dust, never gain. That invariant is the thing to defend.

Why splitting matters: worked trace

Vault holds totalAssets = 1000, totalSupply = 3. Fair value per share = 333.33.

If withdraw rounds up (the bug): 1 share → 334 assets. Withdraw three times, one share each: 334 × 3 = 1002 assets paid out of a 1000-asset vault. The last withdrawal reverts or the vault is insolvent: 2 assets of value conjured from rounding. Withdraw all 3 shares at once: 3 × 1000 / 3 = 1000, correct. The exploit exists only because rounding favored the user; fix the direction and the split is harmless.

Arithmetic

Multiply first, in a 512-bit intermediate, then divide: OpenZeppelin's Math.mulDiv (Solidity 0.8.x) computes floor(x*y/d) without overflow. assets * totalSupply overflows uint256 well before the division would, so a naive a * b / c is wrong even when the final result fits.

Trade-offs

approachprotects againstcost
Round in vault's favorrounding/split extractionnone: it's the default rule
Virtual shares+assets (OZ _decimalsOffset, default 0)first-depositor donationdilutes price slightly; offset must be set > 0
Dead shares (Uniswap V2 MINIMUM_LIQUIDITY = 1000 wei to address(0))first-depositor donationpermanently locked value
Minimum depositzero-share depositsUX tax; doesn't stop donation

Deciding: if a trusted deployer seeds the vault with a large first deposit and deposits are permissioned, the inflation attack is moot and you can skip the offset. If anyone can deposit into an empty vault, set a nonzero _decimalsOffset: cheaper than burning dead shares and needs no extra token.

Failure modes to name

  • First-depositor/donation: attacker deposits 1 wei, donates a large amount directly to the vault, inflating share price so the next depositor mints 0 shares. Detect: totalAssets jumps with no Deposit event.
  • Zero-share deposit: require shares > 0, or the deposit silently donates.
  • Decimal mismatch: 6-decimal asset, 18-decimal shares. mulDiv handles it, but test the extremes.
  • Asymmetric rules: deposit rounds down but withdraw rounds up is exactly the exploit traced above.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Implement a failure-aware oracle read.

Answer

Assumptions I'd state up front: EVM chain, a Chainlink-style aggregator behind a proxy, one feed per market, and I own the consumer contract. I read latestRoundData(), never answer(): answer() returns the last stored value with no timestamp attached, so a stale round and a fresh one are byte-identical to the caller. That single fact is why the failure-aware read exists.

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

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData() external view returns (
        uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound
    );
}

contract PriceGuard {
    AggregatorV3Interface public immutable feed;       // the PROXY, not the aggregator
    AggregatorV3Interface public immutable sequencer;  // L2 uptime feed; address(0) on L1
    uint256 public immutable maxStaleness;             // seconds
    uint256 public immutable gracePeriod;              // seconds after sequencer recovery

    error Stale(uint256 updatedAt, uint256 nowTs);
    error NonPositive(int256 answer);
    error SequencerDown();
    error GraceNotElapsed(uint256 sinceUp);

    constructor(AggregatorV3Interface f, AggregatorV3Interface s, uint256 stale, uint256 grace) {
        feed = f; sequencer = s; maxStaleness = stale; gracePeriod = grace;
    }

    function read() public view returns (int256 price, uint8 dec) {
        if (address(sequencer) != address(0)) {
            (, int256 up, uint256 startedAt, , ) = sequencer.latestRoundData();
            if (up != 1) revert SequencerDown();
            if (block.timestamp - startedAt < gracePeriod) revert GraceNotElapsed(block.timestamp - startedAt);
        }
        (, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
        if (answer <= 0) revert NonPositive(answer);
        if (updatedAt == 0 || block.timestamp - updatedAt > maxStaleness) revert Stale(updatedAt, block.timestamp);
        return (answer, feed.decimals());
    }
}

Trace it. Arbitrum ETH/USD, maxStaleness = 3600 (the feed's documented 1-hour heartbeat), gracePeriod = 1800.

  1. block.timestamp = 1_700_000_100, sequencer feed returns up = 1, startedAt = 1_700_000_000. Delta is 100 < 1800 → GraceNotElapsed(100). The sequencer is back but prices haven't caught up; this is the case people skip.
  2. block.timestamp = 1_700_002_000. Delta 2000 ≥ 1800, pass. Feed returns answer = 241234567890, updatedAt = 1_700_001_800. Lag 200 ≤ 3600 → returns (241234567890, 8), i.e. $2,412.34567890.
  3. Same answer, updatedAt = 1_699_900_000. Lag 102000 > 3600 → Stale. The price is unchanged because nothing traded; the round is still old.
  4. answer = 0 or a negative sentinel → NonPositive.

Decimals. decimals() is per-feed: ETH/USD on Ethereum mainnet returns 8, others return 18. Normalize once at the boundary, uint256(answer) * 10 ** (18 - dec), and never hardcode 1e8.

Trade-offs. Revert is correct when the protocol cannot price risk without the feed: lending liquidations, perps, anything that mints against collateral. A fallback is correct when liveness outranks exactness, but only if it is not manipulable: a secondary oracle or last-known-good with a widening haircut. Pausing is wrong when the pause itself blocks liquidations on an already-underwater position: you have converted a price problem into bad debt. And a maxStaleness of 60s against a 1-hour heartbeat pauses constantly for no reason.

Failure modes and detection. Emit an event on every revert path and alert on revert rate; track block.timestamp - updatedAt as a metric so you see lag before it breaches. Pin the proxy address, not the aggregator: the aggregator changes on feed upgrades, the proxy does not. answeredInRound is deprecated on newer aggregators and equals roundId, so it is not a staleness signal; updatedAt is.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Choose a manipulation-resistant price for lending.

Answer

Core answer (first 60–120 seconds). I price collateral with a 30-minute TWAP of the asset's deepest pool, cross-checked against an independent oracle feed, and I take the more conservative of the two for collateral valuation. Concretely: TWAP window 30 minutes (150 blocks at 12s); reject any sample where the pool holds less than a floor of the quote asset (say $2M); reject if the feed's last update is older than 90 minutes; and cap total borrow against that collateral at 5% of the pool's quote-side depth. If the asset has a feed with a real independent node set and >$50M of combined CEX+DEX daily volume, I make the feed primary and keep the TWAP as a circuit breaker: if the two diverge by more than 5% for 3 consecutive blocks, pause new borrows and liquidations. Assumptions: single chain, 12s blocks, fungible ERC-20 collateral with a liquid pool, and per-block extractable value from the protocol bounded well below the manipulation cost below.

Why a TWAP resists manipulation. Spot price is one block's reserve ratio, so an attacker only has to distort it for the instant the contract samples it. A TWAP averages over the window, so the attacker must hold the deviation for the whole window while arbitrageurs trade against them every block. Cost scales with pool depth × window length.

Worked arithmetic (hypothetical pool): 5,000 ETH / 10,000,000 USDC, price 2,000, k = 5×10¹⁰. To push spot to 2,200 (+10%), the attacker buys until x′ = √(k/2200) = 4,767.3 ETH, i.e. 232.7 ETH for 488,060 USDC. One block later arbitrageurs sell back at 2,200 and pocket that spread, so a spot oracle is fooled for ~$488k. A 30-minute TWAP forces the attacker to re-establish the deviation after each arbitrage, so required capital scales roughly with the 150 blocks in the window: tens of millions here. If manipulation cost exceeds the value extractable from the protocol in that window, the TWAP holds.

Deviation bounds vs staleness. A feed with a 0.5% deviation threshold and 1-hour heartbeat updates on deviation in fast markets and hourly when quiet. Set staleness to heartbeat plus margin (90 minutes), not tighter: a 5-minute staleness check rejects a healthy feed in a quiet market and halts liquidations. Too loose and you accept a price from before a 20% move.

When not to use it. A TWAP is wrong for a thin pool (cheap to move) or fast-moving collateral where the 30-minute lag causes liquidations at stale prices. A feed is wrong for an unlisted asset or one whose node set is not independent. Deciding criterion: manipulation cost vs. extractable value, computed per asset.

failure modedetection
flash-loan spot movealert when |spot − TWAP|/TWAP > 5% for >3 blocks
stale fallbackmonitor last-update timestamp; alert past 90 min
shared sourceboth feeds resolve to the same pool → treat as one source
thin marketpool depth below floor → block new borrows
liquidation cascade>20% of debt within 5% of threshold → cap liquidations per block

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Test a protocol under flash-loan-scale capital.

Answer

Core answer (say this first)

Assume the protocol custodies user funds and prices them from an on-chain source. The test is not "does it handle flash loans": it is: give one actor unbounded capital and atomicity, then assert every protocol invariant after every call. The loan is only the funding primitive; the defect is whichever invariant the capital breaks.

Concretely: fork mainnet at a pinned block, deploy a handler that borrows, executes a fuzzed action, repays, and let an invariant fuzzer drive it. Assert invariants, not scenarios: a scenario test only finds the attack you already imagined.

Harness (Foundry, Solidity 0.8.24)

SOLIDITY
// forge test --fork-url $RPC --fork-block-number 21_000_000 --match-contract Invariants
contract Handler is Test {
    IPool  constant POOL = IPool(0x87870Bca3F3fD6335C3F4ce8392D69350B4fA4E2); // Aave V3 Pool
    IERC20 constant USDC = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48);
    Vault vault;

    function borrowAndAct(uint96 amt, uint8 action) external {
        uint256 amount = (uint256(amt) % 100_000_000e6) + 1e6; // 1 .. 100M USDC
        POOL.flashLoanSimple(address(this), address(USDC), amount, abi.encode(action), 0);
    }

    function executeOperation(address, uint256 amount, uint256 premium, address, bytes calldata params)
        external returns (bool)
    {
        uint8 action = abi.decode(params, (uint8));
        if (action == 0) vault.deposit(amount, address(this));
        else if (action == 1) USDC.transfer(address(vault), amount);   // donation
        else if (action == 2) vault.redeem(vault.balanceOf(address(this)), address(this), address(this));
        USDC.approve(address(POOL), amount + premium);
        return true;
    }
}

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

function invariant_roundTripBounded() public view {
    assertGe(vault.previewRedeem(vault.previewDeposit(1e6)), 1e6 - 1);
}
function invariant_neverClaimsMoreThanItHolds() public view {
    assertGe(USDC.balanceOf(address(vault)), vault.totalAssets());
}

Foundry calls every invariant_ function after every handler call, so a sequence that breaks one is caught at the call that breaks it.

Worked trace: donation / share inflation

Empty ERC-4626 vault, 1:1, no virtual offset.

stepactiontotalAssetstotalSupply
1attacker deposits 1 wei11
2attacker transfers 1,000,000e6 USDC straight to the vault1,000,000e6+11
3victim deposits 1,000,000e6 USDC → shares = 1,000,000e6·1/(1,000,000e6+1) = 02,000,000e6+11
4attacker redeems 1 share00

Attacker nets +1,000,000e6 USDC; the victim's deposit is gone. invariant_roundTripBounded fails at step 3 because previewDeposit(1e6) returns 0. The fix is OpenZeppelin's _decimalsOffset() (virtual shares): with offset 3 the attacker must donate ~1000× more to round the victim to zero.

Which layer to reach for

layerwhat it provesruntime
unitarithmetic edges you already thought ofms
fork test, pinned blockreal oracle, real liquidity, real token decimalsseconds
invariant fuzz (Foundry, Echidna, Medusa)no sequence of N calls breaks an invariantminutes
symbolic (Halmos, Certora)all inputs within boundsminutes–hours

Deciding criterion: a pure function of contract state → fuzz it; anything that reads an external price or pool depth → fork it, because a mock oracle cannot reproduce the manipulation; arithmetic inside one function → prove it. Fork tests are the only layer that sees the real oracle, but they pin a block and go stale; fuzzing explores sequences but is only as good as the handler and the invariants you wrote.

Failure modes to check before trusting a green run

  • Handler reverts on every call, so the fuzzer explores nothing. Foundry's fail_on_revert = false default hides this: assert a handler success counter.
  • Flash-loan fee ignored. Aave V3 charges a 5 bps premium, so a 100M USDC loan costs 50,000 USDC; an attack that nets less than that passes here but succeeds against a zero-fee Balancer V2 loan. Use the zero-fee lender to remove the confounder.
  • Fork pinned to a block where the oracle is stale or the pool is thin: the test passes for the wrong reason.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Protect a public transaction from ordering manipulation.

Answer

What I'd say first

Assume a public mempool on an EVM chain, a user submitting an AMM swap or a signed order, and an adversary who can reorder, insert, or censor transactions inside a block. You cannot stop reordering on a public chain, so the core answer is to bound the damage: the transaction carries user-specific terms (minimum output, deadline, nonce) that make any reordered execution revert instead of filling at a worse price, and then you pick a submission channel that shrinks the adversary's window.

Bounding the outcome

A swap with amountOutMinimum and deadline is a signed statement: execute only if I receive at least X by time T. A sandwich attacker has to push the price past X to profit, so the bound caps their take at the gap between fair price and X. Tighten X and you cut attacker profit but raise your own revert rate, and a reverted swap still costs gas. On Ethereum mainnet a revert burns the gas used up to the failure point, typically 30k–100k gas, so a bound that reverts 20% of the time is a real cost, not free safety.

Nonce: each account has a sequential nonce. A signed transaction with nonce N is includable exactly once; a copy replayed later fails because N is already consumed. That kills naive replay of a copied signed transaction, but not front-running of a fresh one.

Commit-reveal

Two phases. Commit: post keccak256(abi.encode(order, secret)). Reveal: post the order and secret; the contract checks the hash. Ordering can't be exploited because the content is hidden until the commit is mined. Cost: two transactions, so roughly double gas and at least one extra block (~12s on Ethereum) of latency, plus a liveness assumption, if the reveal never lands you need a timeout that voids the commit, or funds are stuck.

Protected submission

Send through a private relay instead of the public mempool. Flashbots Protect (rpc.flashbots.net) and MEV Blocker (rpc.mevblocker.io) forward the signed transaction straight to block builders, so it never sits in the public mempool for a searcher to front-run. What it does not do: guarantee inclusion, and it makes the relay a trusted party that can drop or delay your transaction.

Tradeoffs

MechanismBuys youCosts you
minOut + deadlineCaps attacker profit; reverts on bad executionRevert gas; missed fills when the bound is too tight
NonceBlocks replay of a copied signed txSequential, so one stuck nonce blocks every later tx
Commit-revealHides intent until committed2x gas, +1 block latency, needs a timeout
Private relayRemoves the public front-run windowRelay trust, no inclusion guarantee, possible censorship

Failure modes and how you'd see them

  • Sandwich: trace the block and see a buy immediately before and a sell immediately after your swap; monitor realized vs quoted price.
  • Censorship: the relay or builder never includes the tx; detect via a deadline timeout and fall back to public submission.
  • Stale quote: the price feed or quote is older than your tolerance; check its timestamp before signing.
  • Overly broad approval: an unlimited approve lets a compromised spender drain the balance; scan allowances and cap them.

The deciding criterion: if the adversary is a public searcher, bound + private relay is the cheap default; if the order itself is the secret, a large trade or an auction, commit-reveal is worth the extra block.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Design randomness for an on-chain allocation.

Answer

Core answer (first 90 seconds). Assume an EVM chain, N slots allocated among M entrants, real value at stake, and an adversary who can submit transactions and bribe a proposer. Use Chainlink VRF v2.5: freeze the entrant list, request one random word, and derive the allocation deterministically from that word. Do not use block.prevrandao, blockhash, or block.timestamp: they are public, and the proposer can re-roll the block to bias them. The VRF output is unpredictable to the oracle that produces it and verifiable on-chain, which is the property you actually need.

How the mechanism works. The consumer calls requestRandomWords on the VRF coordinator, which emits a request carrying a unique requestId and a seed derived from block data and the request itself. The oracle computes the VRF output over that seed with its secret key and submits fulfillRandomWords(requestId, words) back to the coordinator. The coordinator verifies the proof on-chain against the oracle's registered public key before calling your fulfillRandomWords. Two properties fall out of this: the oracle cannot choose the output without breaking the proof, and the coordinator tracks fulfillment per requestId, so a second callback for the same request reverts. That is what stops replay and duplicate fulfillment. Your consumer must also confirm msg.sender is the coordinator; VRFConsumerBaseV2Plus does this in rawFulfillRandomWords.

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

import {VRFConsumerBaseV2Plus} from "@chainlink/contracts/src/v0.8/vrf/dev/VRFConsumerBaseV2Plus.sol";
import {VRFV2PlusClient} from "@chainlink/contracts/src/v0.8/vrf/dev/libraries/VRFV2PlusClient.sol";

contract Allocation is VRFConsumerBaseV2Plus {
    uint256 public s_subscriptionId;
    bytes32 public s_keyHash;
    uint32 public s_callbackGasLimit = 200_000;
    uint16 public s_requestConfirmations = 3; // mainnet default, configurable

    uint256 public requestId;
    address[] public entrants;   // frozen before the request
    uint256 public seed;
    bool public drawn;

    constructor(uint256 subId, address coordinator, bytes32 keyHash)
        VRFConsumerBaseV2Plus(coordinator)
    { s_subscriptionId = subId; s_keyHash = keyHash; }

    function draw() external {
        require(!drawn, "already drawn");
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: s_keyHash,
                subId: s_subscriptionId,
                requestConfirmations: s_requestConfirmations,
                callbackGasLimit: s_callbackGasLimit,
                numWords: 1,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false}))
            }));
    }

    function fulfillRandomWords(uint256 _requestId, uint256[] memory words)
        internal override
    {
        require(_requestId == requestId, "stale request");
        require(!drawn, "already drawn");
        seed = words[0];
        drawn = true;
    }

    function winnerIndex() external view returns (uint256) {
        require(drawn, "not drawn");
        return seed % entrants.length;
    }
}

Worked trace. Five entrants, seed = 987654321. 987654321 % 5 = 1, so entrant index 1 wins. For weighted allocation with weights [50, 30, 20], total 100: 987654321 % 100 = 21; cumulative 50 → 21 < 50, so entrant 0 wins. Modulo bias here is ~2^-254 for N=5: negligible; for large N or weighted draws, use the full 256-bit word against cumulative weights rather than a small modulus.

Alternatives. Commit-reveal is cheap and oracle-free but the last revealer can bias by withholding, so it needs collateral and timeouts. An off-chain draw with an escrowed bond is fast but trusts the operator. VRF costs LINK or native and lands 2–3 blocks later; it is the wrong tool when you need sub-block latency or cannot fund a subscription.

Failure modes. Callback spoofing: mitigated by the coordinator check. Reorg: set requestConfirmations to your finality tolerance. Stale request: require requestId match. Reroll by retry: make draw one-shot; never let a failed draw be re-requested. Changing entrants: snapshot the list before the request. Gas exhaustion: keep the callback O(1) and set callbackGasLimit above worst case. Privileged cancellation: remove or timelock any owner reroll path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Replace an unbounded settlement loop.

Answer

Clarify and assume. The contract is a Solidity 0.8.24 payout vault on Ethereum mainnet (30M block gas limit, post-Cancun). It holds an ERC-20 pot and exposes settleAll():

SOLIDITY
for (uint256 i = 0; i < recipients.length; ++i)
    token.transfer(recipients[i], pot * shares[i] / totalWeight);

addRecipient is permissionless. "Replace" means: keep the same payout semantics, but make the gas of any single transaction independent of recipients.length.

Why it's unbounded. Work is O(n) where n is attacker-controlled. Adding one recipient costs the attacker one SSTORE (~22,100 gas, EIP-2929 cold). Each entry adds ~50k gas of work to the only path that moves funds: cold SLOAD of recipients[i] and shares[i] ≈ 4,200, a first-time ERC-20 transfer ≈ 50k, a Settled log ≈ 1.4k. At a 30M block gas limit that path reverts with out-of-gas at roughly 550–600 recipients, and because it is the only settlement path, the pot is frozen. Amplification is ~2.3x per entry: the attacker pays once, the protocol pays forever.

The replacement: bounded resumable batch with per-item isolation.

SOLIDITY
function settle(uint256 maxItems) external {
    uint256 n = recipients.length;
    uint256 i = cursor;
    uint256 end = i + maxItems > n ? n : i + maxItems;
    uint256 paid;
    for (; i < end; ++i) {
        address to = recipients[i];
        uint256 amount = pot * shares[i] / totalWeight;
        (bool ok, bytes memory ret) = address(token).call(
            abi.encodeCall(IERC20.transfer, (to, amount)));
        if (ok && (ret.length == 0 || abi.decode(ret, (bool)))) {
            paid += amount;
            emit Settled(i, to, amount);
        } else {
            emit Skipped(i, to);   // residue, retried out of band
        }
    }
    cursor = i;
    settledWeight += paid;
}

The caller picks maxItems; the loop is bounded by that parameter, not by the array. cursor makes it resumable and permissionless, so a stalled keeper can be replaced by anyone.

Trace. pot = 300e6 (300 USDC), totalWeight = 3, shares = [1,1,1], recipients = [alice, bob_blocked, carol], cursor = 0.

settle(2): n=3, i=0, end=2.

  • i=0: amount = 300e6*1/3 = 100e6; transfer to alice succeeds; paid = 100e6; Settled(0, alice, 100e6).
  • i=1: amount = 100e6; transfer to bob reverts (blocklisted); Skipped(1, bob).
  • cursor = 2, settledWeight = 100e6.

settle(2) again: i=2, end=3.

  • i=2: transfer to carol succeeds; paid = 100e6; Settled(2, carol, 100e6).
  • cursor = 3, settledWeight = 200e6.

Residue: index 1 unpaid, 100e6 still held. Detected by settledWeight (200e6) != pot (300e6) once cursor == recipients.length.

Choosing among alternatives.

approachright whenwrong when
Merkle pull claimrecipient set fixed at deploy; claimants can act; leaves publishableset changes after deploy; recipients must be paid without acting
per-account accumulatorentitlement derivable from on-chain balancestoken is transferable and you can't hook transfers → stale checkpoints
bounded resumable batchpush semantics required; set can grownobody keeps calling → partial state; needs an idempotency guard

Failure modes and detection.

failuredetection
duplicate payoutsettledWeight > pot invariant; assert in tests
skipped itemSettled + Skipped count vs recipients.length
one reverting recipientSkipped event; stuckCount metric
list mutated mid-flightassert recipients.length unchanged between batches
griefingcompare addRecipient cost to gas it adds to settle
proof data lostroot on-chain, leaves in event logs, not a frontend
gas schedule changere-run the gas snapshot on the fork; maxItems is a parameter, not a constant
abandoned partial statecursor / recipients.length metric; permissionless settle

Exactly-once, qualified. Exactly-once holds only per (recipient, epoch), and only because a settled flag makes the transfer idempotent: the token transfer itself is at-most-once. Any off-chain or cross-chain leg is at-least-once and needs a dedupe key. Don't claim exactly-once without that qualifier.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Design a permit-like signed operation.

Answer

First 90 seconds. I'd assume an EVM target, secp256k1 ECDSA, and that the goal is an off-chain signature that authorizes an on-chain state change without the signer paying gas. The design is EIP-712 typed data plus a per-signer nonce consumed in the same transaction that applies the effect. The signature itself never expires cryptographically, it's a number that stays valid forever, so everything that makes it single-use lives in contract state: the domain separator binds it to one chain and one contract, and the nonce binds it to one use.

Mechanism. EIP-712 hashes a domain separator and a struct hash, then signs keccak256("\x19\x01" || domainSeparator || structHash). The domain separator is keccak256(abi.encode(TYPEHASH, name, version, chainId, verifyingContract)). That is the replay binding: the same signature over the same struct produces a different digest on another chain (different chainId) or another contract (different verifyingContract), so ecrecover returns a different address and the check fails.

The nonce is the second binding. Read nonces[owner], fold it into the struct hash, and increment it before any external call. Two transactions in the same block both read nonce 7 and both verify, but the first increments to 8 and the second's check against stored state fails. Increment after the effect instead and both succeed: you have double-spent. Order matters.

SOLIDITY
// Solidity 0.8.24
bytes32 structHash = keccak256(abi.encode(
    PERMIT_TYPEHASH, owner, spender, value, nonces[owner], deadline));
bytes32 digest = keccak256(abi.encodePacked("\x19\x01", _domainSeparator(), structHash));
address signer = ecrecover(digest, v, r, s);
require(signer == owner && signer != address(0), "bad sig");
require(block.timestamp <= deadline, "expired");
nonces[owner] += 1;          // consume before effects

_domainSeparator() should cache the separator but rebuild it when block.chainid changes, otherwise a chain split leaves the cached separator pointing at the old chain.

Trade-offs. Single-use nonce is right when the authorization moves value or grants a role: anything where a second application is a bug. Repeatable authorization (no nonce, deadline only) suits a session key or a standing allowance, but then you need a revocation path, because the signature stays valid until the deadline no matter what. EIP-2612 permit is the minimal version: one nonce per owner, one spender, one value. Permit2 generalizes it: a single approval to the Permit2 contract, then per-transfer signed messages with their own nonces and deadlines: worth it when you would otherwise send an approval transaction per token.

designuse whencost
EIP-2612 permitone token, one spender, one valueone nonce per owner; no batching
Permit2many tokens, repeated transfersone-time approval; extra contract in the trust path
deadline-onlysession key, standing allowanceneeds explicit revocation

Failure modes, with detection.

  • Cross-chain replay: signature valid on a fork. Detect by asserting block.chainid in the domain separator; test by forking mainnet and replaying.
  • Cross-contract replay: two contracts share a domain. Detect by including verifyingContract; test by deploying two instances and replaying.
  • Nonce race: two mempool txs with the same nonce. Detect by incrementing before effects; test with two txs in one block.
  • Malleability: flipping s to n-s yields a second valid signature. EIP-2 already rejects high-s; enforce s <= secp256k1n/2 and reject v outside {27,28}.
  • Stale roles: signer was authorized at signing time, not at execution. Re-check authority at execution, not just the signature.
  • Contract wallets: ecrecover returns nothing useful for a smart-contract signer. Route through EIP-1271 isValidSignature.
  • Ambiguous encoding: two structs hash to the same digest. Use EIP-712 typed hashing, never abi.encodePacked of dynamic types.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

How do storage collisions occur in proxy-based upgradeable smart contracts, and how are they prevented?

Answer

In EVM proxy patterns (such as Transparent Upgradeable Proxies and UUPS), the proxy delegates execution to an implementation contract via delegatecall. Under delegatecall, the logic executes in the context of the proxy's address, reading and writing the proxy's storage trie directly. A storage collision occurs when two independent definitions resolve to the same raw storage slot index (0, 1, 2, ...), causing one variable to overwrite or misinterpret the bytes of another.

There are two primary forms of storage collision:

  1. Proxy vs. Implementation Collision: The proxy contract itself needs state (e.g., the implementation address and admin address). If declared as normal Solidity state variables starting at slot 0, they directly overlap with slot 0 and slot 1 of the implementation logic.
  2. V1 vs. V2 Implementation Collision: When upgrading from logic contract V1 to V2, inserting a new state variable before existing ones, reordering variables, changing an existing variable's type, or modifying inheritance order shifts the computed storage slots for all subsequent variables.

Prevention Strategies

1. EIP-1967 Pseudorandom Slots (Proxy vs. Logic)

Proxies prevent overlap with implementation state by placing proxy-specific pointers in fixed, pseudorandom 32-byte slots derived by hashing standardized strings and subtracting 1 (so the preimage is unknown and won't clash with dynamic array hashes).

SOLIDITY
// EIP-1967 implementation slot calculation
// bytes32(uint256(keccak256('eip1967.proxy.implementation')) - 1)
bytes32 private constant IMPLEMENTATION_SLOT =
    0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc;

function _getImplementation() internal view returns (address impl) {
    assembly {
        impl := sload(IMPLEMENTATION_SLOT)
    }
}

2. Append-Only Layouts & Storage Gaps (Implementation Upgrades)

In the logic contracts, existing variable declarations must remain immutable in their order and layout. Any new variables must be appended strictly at the end. In inherited base contracts, developer teams reserve fixed space via a storage gap array (uint256[50] private __gap;). When a base contract adds a variable later, it decrements the gap size by the number of slots consumed.

3. ERC-7201: Namespaced Storage Layout

Modern implementations use ERC-7201 namespaced storage. Instead of relying on sequential top-level slots starting at slot 0, structs are anchored to deterministic locations: keccak256(abi.encode(uint256(keccak256(id)) - 1)) & ~bytes32(uint256(0xff)).

SOLIDITY
// Example: ERC-7201 namespaced storage pattern
library VaultStorage {
    // keccak256(abi.encode(uint256(keccak256("example.vault.storage")) - 1)) & ~bytes32(uint256(0xff))
    bytes32 private constant VAULT_STORAGE_LOCATION =
        0x183492850f1f9ec6727299389f419c96fa9e0ab859846387083049b49b380300;

    struct Layout {
        uint256 totalDeposits;
        mapping(address => uint256) balances;
    }

    function layout() internal pure returns (Layout storage l) {
        bytes32 slot = VAULT_STORAGE_LOCATION;
        assembly {
            l.slot := slot
        }
    }
}

Layout Comparison

PatternMechanismProsPrimary Failure Mode
Sequential + Storage GapsRegular layout starting at slot 0; base contracts keep uint256[N] __gapDirect Solidity syntax; cheap gas readsForgetting to decrement gap size or reordering inheritance
ERC-7201 NamespacedStruct root anchored to custom hash formula via inline assemblyImmune to inheritance order shifts; clean modular boundariesRequires manual struct access patterns; slight gas overhead on base pointer derivation
EIP-1967Standardized slots for proxy infra (implementation, admin, beacon)Eliminates proxy-vs-implementation collisions entirelyLogic contract attempting to use assembly at EIP-1967 addresses

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Secure deployment and initialization of an upgradeable contract.

Answer

Assumptions: Solidity 0.8.x, OpenZeppelin Contracts v5, an upgradeable proxy, and a contract that holds value or permissions from block one.

Core answer. Deploy the implementation, call _disableInitializers() in its constructor, then create the proxy and run the initializer in the same transaction so no window exists where an uninitialized proxy is live. Before funding it, read the EIP-1967 slots and assert the owner and admin are what you expect.

Why the window exists. A proxy delegatecalls into the implementation, so the implementation's code runs against the proxy's storage. The implementation's constructor ran in the implementation's own storage, not the proxy's, so the proxy starts with every variable at its zero value, including _initialized. If initialize() is public and the proxy is deployed in one transaction and initialized in the next, anyone can call initialize() in between and become owner. That is the front-run takeover.

Two mechanisms close it:

  • Atomic init: new TransparentUpgradeableProxy(impl, admin, initCalldata) delegatecalls the initializer inside the proxy constructor, before the address is usable.
  • _disableInitializers() in the implementation constructor sets the implementation's own _initialized to type(uint64).max, so the implementation address, which is public and callable, cannot be initialized directly either.

Alternatives.

patternupgrade authoritypick whencost
UUPSlogic in implementation, _authorizeUpgradesingle instance, you own the upgrade patha bug in _authorizeUpgrade bricks upgrades; must _disableInitializers
TransparentProxyAdmin contract; admin cannot call impl functionsops team with a multisig, want separationextra ProxyAdmin deployment per proxy
Beaconone beacon, many proxiesmany identical instances (per-user vaults)one upgrade hits all; beacon is a single point

Deciding criterion: who holds upgrade rights, and how many instances. One instance you control → UUPS. Many instances → Beacon. Multisig ops team that does not want upgrade logic in the implementation → Transparent.

Failure modes and detection.

  • Front-run init: read owner() in the same script, immediately after proxy creation; if it is not your deployer, abort. Consequence: full control of the contract.
  • Reinitializer exposure: reinitializer(2) left callable after migration lets an attacker re-run it. Detect by asserting _initialized equals the expected version after every upgrade.
  • Inheritance-order omission: V2 is V1 but initialize never calls __Ownable_init → owner is address(0) and onlyOwner reverts forever. Detect with a post-deploy assertion on every role.
  • Wrong admin: Transparent admin set to an EOA cannot batch upgrades; set to the implementation address, the proxy reverts on every call. Detect by reading the admin slot.
  • Partial migration: a reinitializer writes new fields but does not backfill a mapping → reads return zero. Detect with a migration invariant test on forked mainnet state.

Verification.

SOLIDITY
// OpenZeppelin Contracts v5
contract ImplV1 is Initializable, UUPSUpgradeable, OwnableUpgradeable {
    /// @custom:oz-upgrades-unsafe-allow constructor
    constructor() { _disableInitializers(); }

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

    function _authorizeUpgrade(address) internal override onlyOwner {}
}
SOLIDITY
// deploy script: proxy creation and init in one tx
TransparentUpgradeableProxy proxy =
    new TransparentUpgradeableProxy(address(impl), admin, initCalldata);
require(OwnableUpgradeable(address(proxy)).owner() == expectedOwner);

EIP-1967 slots to read: implementation 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, admin 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103.

What changes the decision. If a factory creates the proxy and initializes it atomically, the front-run window is gone and you can drop the separate init step, but you still call _disableInitializers() on the implementation, because that address is public and callable.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Design roles for upgrade, pause, oracle, treasury, and routine operations.

Answer

Assumptions first: EVM protocol, OpenZeppelin Contracts v5, upgradeable proxy (UUPS or Transparent), Gnosis Safe multisigs as key holders, and a TimelockController as the on-chain delay. If you're on Solana or a non-upgradeable contract, the role graph collapses and this answer doesn't apply: say so before designing.

The role graph

Five roles, each held by a different authority, with the delay matched to how reversible the action is.

RoleHolderThresholdDelayPowers
UPGRADER_ROLETimelockController (48h)4-of-7 Safe proposes48hupgradeToAndCall
PAUSER_ROLE2-of-3 hot Safe2-of-3nonepause / unpause
ORACLE_ADMIN_ROLEkeeper EOA, 2-of-3 backup1none, boundedset feed address, heartbeat
TREASURY_ROLE3-of-5 Safe via 24h timelock3-of-524hwithdraw > 10 ETH
OPERATOR_ROLE2-of-3 ops Safe or bot2-of-3none, cappedset fee in [0, 5%]
SOLIDITY
// SPDX-License-Identifier: MIT
// OpenZeppelin Contracts v5.0, solc 0.8.24
import {AccessControlDefaultAdminRules} from
    "@openzeppelin/contracts/access/extensions/AccessControlDefaultAdminRules.sol";

contract Vault is AccessControlDefaultAdminRules {
    bytes32 public constant UPGRADER_ROLE     = keccak256("UPGRADER_ROLE");
    bytes32 public constant PAUSER_ROLE       = keccak256("PAUSER_ROLE");
    bytes32 public constant ORACLE_ADMIN_ROLE = keccak256("ORACLE_ADMIN_ROLE");
    bytes32 public constant TREASURY_ROLE     = keccak256("TREASURY_ROLE");
    bytes32 public constant OPERATOR_ROLE     = keccak256("OPERATOR_ROLE");

    bool public paused;

    constructor(address timelock, address pauserSafe, address keeper,
                address treasurySafe, address opsSafe)
        AccessControlDefaultAdminRules(3 days, timelock) // admin transfer delay; admin = timelock
    {
        _grantRole(UPGRADER_ROLE, timelock);
        _grantRole(PAUSER_ROLE, pauserSafe);
        _grantRole(ORACLE_ADMIN_ROLE, keeper);
        _grantRole(TREASURY_ROLE, treasurySafe);
        _grantRole(OPERATOR_ROLE, opsSafe);
    }

    function pause()   external onlyRole(PAUSER_ROLE) { paused = true;  }
    function unpause() external onlyRole(PAUSER_ROLE) { paused = false; }
}

Trace: one upgrade, one pause

Upgrade, TimelockController with minDelay = 172800 (48h), proposer = the 4-of-7 Safe, executor = address(0) (open), canceller = a separate guardian Safe:

  1. Safe collects 4 of 7 signatures and calls timelock.schedule(vault, 0, abi.encodeCall(Vault.upgradeToAndCall, (newImpl, initData)), bytes32(0), salt, 172800). Timelock stores readyAt = block.timestamp + 172800.
  2. 48h later anyone calls timelock.execute(...) with identical args. Timelock checks readyAt <= block.timestamp, then calls the vault. msg.sender at the vault is the timelock address, which holds UPGRADER_ROLE, so onlyRole passes.

Pause: the 2-of-3 Safe signs pause() and executes it directly against the vault. msg.sender is the Safe, which holds PAUSER_ROLE. paused = true in the same block: no timelock, because a pause you can't take during an exploit is worthless.

Trade-offs

48h is the right default above roughly $10M TVL: it gives monitors time to see the scheduled calldata and exit. Its cost is real: you cannot patch a live exploit by upgrade, so you lean on PAUSER_ROLE and accept that pause is a DoS vector if the hot key leaks. Below ~$1M TVL with a small team, 6–12h is defensible; the delay buys less than the operational friction costs. Widen OPERATOR_ROLE only when the parameter is bounded on-chain (fee capped at 5%), because a bound is what makes a no-delay role safe.

Failure modes

  • Default-admin recursion. DEFAULT_ADMIN_ROLE can grant itself and every other role. Never grant it to an EOA; hold it at the timelock and use AccessControlDefaultAdminRules so transfers take 3 days.
  • Role self-escalation. A role with grantRole on itself grows silently. Keep grant/revoke only on DEFAULT_ADMIN_ROLE.
  • Lost keys. Losing 1 of 7 signers is survivable; losing 4 bricks upgrades. Rotate owners through the Safe's own threshold and rehearse it on a fork.
  • Unsafe renunciation. Renouncing DEFAULT_ADMIN_ROLE before the replacement is confirmed permanently freezes role management. Confirm the new admin first, then renounce.
  • Alternate entry points. A second proxy, a legacy admin function, or an unguarded initializer bypasses the whole graph. Enumerate every external function that writes state and map it to a role.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Secure a modular contract that supports plugins.

Answer

Assume an EVM host contract, Solidity ^0.8.x, post-Cancun, that wants third-party plugins. The default safe answer is: do not delegatecall untrusted code. If you must, treat every plugin as hostile until proven otherwise: pin its code hash, give it a namespaced storage slot, and expose only the narrowest callable surface. The reason is that DELEGATECALL runs the plugin's bytecode with the host's address, balance, and storage, so a plugin can overwrite the host's owner slot, drain its balance via SELFDESTRUCT, or re-enter it.

Alternatives and when each fails

approachhow it worksfails when
address allowlistregistry maps plugin address to allowedplugin is a proxy or selfdestruct+recreate (pre-Cancun) changes code at the same address
code-hash pinningstore keccak256(plugin.code), check codehash before calllegitimate upgrade breaks; does not stop storage collision or selfdestruct
capability-scoped CALLplugin called via CALL, not DELEGATECALL, with a narrow interface and gas capplugin cannot extend host state; needs explicit data passing
DELEGATECALL + namespaced storageplugin shares storage but writes only to a pseudo-random slotplugin can still write any slot; requires audit or static analysis

Mechanism: why storage collisions happen

Solidity assigns state variables to slots sequentially from slot 0. A host with address owner at slot 0 and a plugin compiled independently with address owner at slot 0 will, under DELEGATECALL, both write to slot 0. The plugin's assignment overwrites the host's owner. Namespaced storage fixes this by placing the host's state at a slot derived from a string, e.g. EIP-7201: keccak256(abi.encode(uint256(keccak256("myapp.storage")) - 1)) & ~bytes32(uint256(0xff)). That slot is far from 0 and from other namespaces. EIP-1967 does the same for proxy implementation and admin slots.

How hash pinning defeats a malicious plugin

Registry stores bytes32 pinned = keccak256(plugin.code). Before DELEGATECALL: require(plugin.codehash == pinned, "code changed"). If the plugin's code is swapped (upgrade, selfdestruct+recreate), the hash mismatches and the call reverts. It does not stop the plugin from writing to host storage or calling SELFDESTRUCT, so pinning is necessary but not sufficient.

Failure modes and detection

  • Storage corruption: fuzz with Foundry or Echidna; assert host invariants after plugin calls.
  • Owner overwrite: access-control tests; check owner slot after every plugin call.
  • Asset theft: balance invariants; cap plugin gas (e.g., 100k) to limit damage.
  • Selector collision: Diamond (EIP-2535) maps bytes4 => address; reject duplicate selectors at diamondCut.
  • Implementation upgrade: hash mismatch reverts; governance must update the pinned hash via timelock.
  • SELFDESTRUCT: under DELEGATECALL it sends the host's balance to the target; post-Cancun EIP-6780 it no longer deletes the host unless created in the same tx, but the drain remains.
  • Governance compromise: multisig + timelock for registry changes.

Artefact: minimal hash-pinned, namespaced call

SOLIDITY
bytes32 constant SLOT = keccak256(abi.encode(uint256(keccak256("myapp.storage")) - 1)) & ~bytes32(uint256(0xff));
struct HostStorage { address owner; mapping(bytes4 => address) plugins; }
function hostStorage() internal pure returns (HostStorage storage s) {
    bytes32 slot = SLOT;
    assembly { s.slot := slot }
}
function callPlugin(bytes4 sel, bytes calldata data) external {
    address p = hostStorage().plugins[sel];
    require(p.codehash == pinnedHash[p], "unpinned");
    (bool ok,) = p.delegatecall(data);
    require(ok, "plugin failed");
}

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Define validation for a collateral configuration update.

Answer

Assumptions I'd state before answering: the config is admin-writable behind a role, the asset is already listed, and the price source is a Chainlink-style aggregator. If the config were immutable at deploy, most of this moves into the deploy script and the review target changes.

The 90-second answer. Validation is everything that must hold before the config write is committed, and it has to be enforced at the contract entry point, not in the UI. The config is the input to every health-factor computation that follows, so a bad write isn't a bug in one transaction: it silently reprices every open position until someone notices. The checks are: caller holds the config role, asset and feed are on allowlists, ltvBps < liqThresholdBps <= MAX, the feed is nonzero and its decimal scale is recorded, and the write emits a versioned event so the change is replayable and reversible.

SOLIDITY
// Solidity 0.8.20, OpenZeppelin AccessControl
uint16 private constant MAX_LIQ_THRESHOLD_BPS = 9_000;
uint256 public configVersion;

function setCollateralConfig(address asset, uint16 ltvBps, uint16 liqThresholdBps, address feed)
    external onlyRole(CONFIG_ROLE)
{
    require(assetAllowlist[asset], "asset");
    require(feedAllowlist[feed], "feed");
    require(ltvBps < liqThresholdBps && liqThresholdBps <= MAX_LIQ_THRESHOLD_BPS, "bounds");
    configs[asset] = Config(ltvBps, liqThresholdBps, feed);
    emit CollateralConfigUpdated(asset, ltvBps, liqThresholdBps, feed, ++configVersion);
}

Trace, with configVersion == 3 and USDC stored at 7500/8500:

  1. setCollateralConfig(USDC, 8000, 8500, usdcFeed): allowlists pass, 8000 < 8500 and 8500 <= 9000 pass. State written, event emitted with version 4.
  2. setCollateralConfig(USDC, 9000, 8500, usdcFeed): third require: 9000 < 8500 is false, revert "bounds". No state change, version stays 4.
  3. setCollateralConfig(USDC, 8000, 8500, attackerFeed): second require: feedAllowlist[attackerFeed] is false, revert "feed". Version stays 4.

Why each check exists. ltvBps < liqThresholdBps is the one that matters most: if the liquidation threshold sits at or below the LTV, a position is liquidatable the instant it opens, and the protocol eats the bad debt. The MAX bound stops a fat-fingered 9500 from making every position permanently unliquidatable. The feed allowlist is what stops a wrong-but-valid feed, ETH/USD wired to stETH, from mispricing the whole market. Decimals matter because Chainlink USD feeds report 8 decimals while USDC is 6 and WETH is 18; treating an 8-decimal answer as 18 is a 10^10 error, not a rounding error.

Trade-offs. On-chain versus off-chain: off-chain checks (a CI script, or simulating the multisig tx with eth_call against a fork) can iterate over every open position and answer "does this new threshold make anyone instantly liquidatable". An on-chain loop over positions is unbounded and unaffordable. But off-chain is advisory only, because anyone can call the contract directly and compose calls; the on-chain requires are the authoritative set, and they can only cover what's checkable in O(1). Strictness versus upgrade friction: a hardcoded MAX means a legitimate new asset with unusual parameters needs a contract upgrade, while a role-mutable bound is faster to ship but makes the role itself the entire security boundary. A timelock (48h is a common choice) gives users time to exit before a threshold drop lands, at the cost of slowing incident response when you actually want to tighten a bad config fast.

Failure modes and how I'd catch them. A feed swap to a wrong-but-allowlisted address shows up as a price that diverges from a second source: alert on a scheduled cross-check, not on the tx. A decimals mismatch shows up as a normalized price off by orders of magnitude; a unit test asserting the normalized value against a known reference catches it before deploy. Partial application is real off-chain, not on-chain: the EVM reverts the whole tx, but a batch script sending N separate txs can land half of them, so the version counter plus event replay is the reconciliation tool. A stale role, config role still held by an EOA that was rotated out, is caught by monitoring RoleGranted/RoleRevoked and alerting on the current holder set. A zero feed address returns a zero answer, which turns collateral value into zero or reverts on division; require(feed != address(0)) plus an answer > 0 check on read covers it.

What would change my answer: if the config were immutable per asset at deploy, the allowlist and role checks disappear and the review moves to the deploy script and its parameters; if positions were isolated per market, the cross-position invariant check becomes unnecessary and the on-chain bounds are sufficient on their own.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Define and test invariants for a tokenized vault.

Answer

Assume a standard ERC-4626 vault over an 18-decimal token, no fees, single asset, OpenZeppelin 5.x semantics. An invariant is a predicate that must hold after every state transition, not just at rest. I'd define four and test them with stateful fuzzing plus a differential model.

invariantassertionwhat breaks it
conservationasset.balanceOf(vault) + strategyValue >= totalAssets()stale strategy valuation
rounding directiondeposit/redeem round down, withdraw/mint round upa path that rounds in the user's favor
loss boundN operations lose < N wei totalsuperlinear rounding extraction
monotonic ratetotalAssets/totalSupply never falls except on a loss eventdonation / first-depositor dilution

Conservation. totalAssets() must equal what the vault can actually account for: idle balance plus strategy positions, minus recognized bad debt. If a strategy reports a stale value, this breaks before the loss is realized.

Rounding direction. ERC-4626 mandates rounding that favors the vault. Deposit 1 wei into a vault with totalSupply=3, totalAssets=2: shares = floor(1·3/2) = 1. Withdraw 1 wei: shares burned = ceil(1·3/2) = 2. The vault keeps the difference, so a user can never extract more than they put in.

Rounding loss bound. Each operation loses at most 1 wei of precision, so N operations lose at most N wei. Test it: run 10,000 random deposit/withdraw pairs and assert sum(assetsOut) <= sum(assetsIn) with a gap under 10,000 wei. A superlinear gap is a rounding-extraction bug.

Monotonic exchange rate. pricePerShare = totalAssets/totalSupply must be non-decreasing across deposits, withdrawals and transfers; it may only drop on an explicit loss event. That is what preserves fairness: a later depositor can't be diluted by an earlier one's donation.

Testing. Foundry stateful invariant tests with a handler contract that bounds inputs and tracks ghost variables; Echidna for corpus-driven property fuzzing; Certora for properties you need proved rather than sampled. The tradeoff: fuzzing finds shallow bugs in minutes but proves nothing; formal verification proves the property but costs days of spec writing and drifts when the contract changes. Differential testing against an independent Python model catches spec divergence, but the model is a second implementation that can itself be wrong: keep it small and derive it from the EIP, not from the Solidity.

Failure modes. The inflation attack: attacker deposits 1 wei (1 share), donates 1e18−1 directly, then a victim depositing 1e18−1 gets floor((1e18−1)·1/1e18) = 0 shares and loses everything. OpenZeppelin's _decimalsOffset() of 3 adds 1000 virtual shares, so the victim gets ~1000 shares and the attack costs 1000× more. Donation and first-depositor attacks, fee-on-transfer or rebasing tokens breaking the balance == totalAssets assumption, bad debt from a strategy, and pause deadlock (deposits paused but not withdrawals) are the ones I'd write explicit tests for.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Design emergency controls for a lending protocol.

Answer

Core answer (first 90 seconds)

Assume an upgradeable proxy, a 4-of-7 guardian multisig, and a governance timelock. The design is two tiers, not one.

Tier 1: freeze (the default emergency action). Blocks new supply and new borrow on a reserve. Leaves repay, withdraw, and liquidation open. The protocol stops taking on exposure while every existing user can still exit.

Tier 2: pause (nuclear). Blocks supply, borrow, repay, and withdraw. Leaves liquidation open. You reach for this only when the accounting itself is compromised and no state transition can be trusted.

Only the guardian can freeze or pause. Only timelocked governance can upgrade logic or change parameters. The guardian cannot move funds and cannot upgrade.

Mechanism

The guard is a require at the top of each external entry point, not a flag that halts the whole contract. That distinction matters: interest accrual and oracle reads must keep running so liquidations price correctly.

SOLIDITY
// Solidity ^0.8.20
contract LendingPool is Pausable {
    mapping(address => bool) public frozen;   // per-reserve

    modifier whenNotFrozen(address asset) {
        require(!frozen[asset], "RESERVE_FROZEN");
        _;
    }

    function supply(address asset, uint256 amt) external whenNotPaused whenNotFrozen(asset) { ... }
    function borrow(address asset, uint256 amt) external whenNotPaused whenNotFrozen(asset) { ... }
    function withdraw(address asset, uint256 amt) external whenNotPaused { ... }  // exits open on freeze
    function repay(address asset, uint256 amt) external { ... }                    // always open
    function liquidate(...) external { ... }                                       // always open
}

This mirrors Aave V3: validateSupply and validateBorrow check isFrozen and isPaused, while validateLiquidationCall checks neither. Compound's Timelock holds a 2-day delay before any governance action executes.

Trade-offs

  • Guard (modifier) vs circuit breaker (auto-trip on oracle deviation): a guard is deterministic and auditable but needs a human in the loop; a breaker reacts in one block but false-trips on a wick. Use the guard for governance-controlled risk, the breaker only for oracle staleness past a hard threshold.
  • Freeze vs pause: freeze preserves exits and reverses in seconds; pause is a hard stop that strands users if governance is slow to unpause.
  • Multisig vs timelock for the guardian: a timelock on pause defeats the purpose. You need sub-block response. A multisig on upgrade is too weak: 7 signers can drain the pool. Split the two roles.

Failure modes and detection

  • Guardian key compromise: a compromised guardian can freeze reserves (blocks new supply, no loss) or pause (blocks withdrawals). Detection: alert on every pause event, page on-call; 4-of-7 means four keys must fall.
  • Indefinite lockup: a pause with no unpause path. Detection: monitor time-since-pause and escalate to governance after a fixed window.
  • Blocking liquidations: gating liquidate behind whenNotPaused lets bad debt accrue. Detection: invariant test. After pause, a liquidation call must still succeed.
  • False alarm: a freeze during a normal oracle wick. Cost is borrowers can't draw, but no loss. Detection: track freeze frequency per reserve.
  • Race: an attacker front-runs the pause tx. Detection: mempool monitoring; mitigation is a private relay for the pause transaction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Threat-model a new collateralized lending contract.

Answer

Two assumptions up front, because they change the ranking: the contract sits behind an upgradeable proxy with a multisig-plus-timelock admin, and prices come from an external oracle. If either is false, the risk order moves.

Given those, the top three risks are the oracle, liquidation liveness, and privileged powers. A wrong or stale price is the only thing that turns a solvent book insolvent inside one block. If liquidators don't show up, bad debt is guaranteed no matter how clean the math is. Admin, governance and pause bypass every invariant you write. Rounding, callback tokens, fee-on-transfer tokens and congestion are all just ways to break one of those three or to break an accounting invariant.

Start with what can be lost or changed, by whom, and which property must always hold.

Asset or powerWho can touch itBoundaryInvariant
Collateral and debt balancesusers, liquidatorsdeposit / borrow / repay / liquidatesum of user debt equals totalDebt; no debt falls without a matching asset inflow
Oracle priceexternal feedprice readprice is fresh (age < heartbeat) and inside a sane band
Admin rolesmultisig + timelockproxy admin, role grantsno role change without the timelock delay
Pauseguardianpause / unpausepause never blocks repay or liquidate

Oracle choice is the decision that matters most, and it is a real trade-off:

SourceManipulation costFailure modeUse for
Chainlink push feed (ETH/USD mainnet is documented at 0.5% deviation, 1h heartbeat)corrupting N independent nodesgoes stale during congestion; feed deprecationprimary price
Uniswap V3 30-minute TWAPscales with liquidity × time; a flash loan can't move itlags a real gap-down, so liquidations fire latefallback and sanity band
Spot reserves (getReserves())one flash loansingle-block manipulationnever

The deciding criterion: compare the cost to move the price past a position's liquidation threshold against the profit from liquidating it. If cost < profit, that oracle is wrong for that market.

Here is why the oracle dominates, with hypothetical numbers. 100 ETH at $3,000 is $300k collateral; 80% LTV borrows $240k USDC. Liquidation threshold 82.5%, close factor 50% (Aave v3 and Compound both use 50%), liquidation bonus 5%. Price gaps 25% to $2,250 in one block.

  • Health factor = 225,000 × 0.825 / 240,000 = 0.77, so the position is liquidatable.
  • First liquidation repays $120k and seizes 120,000 × 1.05 / 2,250 = 56 ETH. Left: 44 ETH ($99k) against $120k debt, HF 0.68. Still underwater.
  • Clearing the full $240k needs 240,000 × 1.05 = $252k of collateral; only $225k exists. Bad debt ≈ 240,000 − 225,000/1.05 ≈ $25.7k, about 10.7% of the debt.

That is the number to defend: a 25% single-block move on an 80% LTV book produces roughly 10% bad debt even with a working liquidator.

Rounding direction is a security property, not a style choice. Solidity integer division truncates, so round in the protocol's favour on every path:

SOLIDITY
// Solidity 0.8.x
function sharesForDeposit(uint256 assets, uint256 totalAssets, uint256 totalShares)
    internal pure returns (uint256)
{
    return assets * totalShares / totalAssets;   // rounds down: user gets fewer shares
}

function assetsForDebt(uint256 debt, uint256 index)
    internal pure returns (uint256)
{
    return (debt * index + 1e18 - 1) / 1e18;     // rounds up: protocol never under-collects
}

Round debt up and collateral down. Round the other way and an attacker shaves value with repeated dust operations.

Failure modes, each with how you catch it:

FailureMechanismDetection
Stale oraclefeed stops updating during congestionrevert when block.timestamp - updatedAt > 2 × heartbeat; alert on age
Liquidation livenessbonus below gas + slippage, nobody liquidatesalert when HF < 1 for more than N blocks
Reentrancy via callbackERC-777 tokensReceived re-enters before state updateinvariant fuzz with a malicious token; checks-effects-interactions plus a guard
Share inflationfirst depositor donates to inflate share pricevirtual shares offset (OpenZeppelin _decimalsOffset); assert totalSupply > 0 after seeding
Governance captureflash-loaned voting powersnapshot at a past block, as Compound's getPriorVotes does

If I had one day, I would fix the oracle read and the pause scope first: a fresh, banded price and a pause that can stop borrows and deposits but never repay or liquidate. Those two close the paths that produce bad debt; the rest are hardening.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Create a smart-contract security test matrix.

Answer

Assumptions: EVM/Solidity repo on Foundry, contracts that hold value and make external calls, pre-audit. I'd build the matrix on two axes, threat class and test type, and choose the test type by what state the bug needs to exist, not by what's easy to write.

ThreatTest typeToolCatchesCost per run
Rounding, precision, off-by-oneUnit + boundaryforge testwrong result at 0, 1, type(uint256).maxms
Access control, role escalationUnit + fuzz on msg.senderFoundry fuzz, Echidnamissing modifier on one of N pathsseconds
Reentrancy, malicious callbacksStateful invariant + attacker contractFoundry invariant_, Echidnacallback re-entering mid-stateminutes
Solvency, accounting driftStateful invariantEchidna / Medusasum(balances) != totalSupply after arbitrary sequencesminutes–hours
Oracle / price manipulationDifferential + forkHalmos, Foundry forkmodel vs implementation divergenceseconds–minutes
Upgrade, storage layoutUnit + storage diffforge inspect, OZ upgrades pluginslot collision across versionsseconds
Live integrationForkvm.createSelectFork at a pinned blockwrong assumption about an external contractseconds/test, archive RPC

How the three that matter actually work.

Invariant fuzzing: you declare a property that must hold in every reachable state. invariant_solvent() { assertGe(token.balanceOf(address(pool)), totalDeposits); }. The fuzzer picks a random function from the target contract, random args, random sender, executes, re-checks the property after each call, and keeps a corpus of sequences that got closest. Foundry drives this with invariant_ functions plus targetContract(address) and [invariant] runs/depth/fail_on_revert; Echidna uses echidna_ functions returning bool with testLimit and seqLen. The generator is the weak point: if the target doesn't expose the admin role or the callback entry point, no sequence ever reaches the bug.

Differential: run the same call sequence against two implementations (Solidity vs a Python/TS model, or old vs new version) and assert equal outputs. This catches rounding and accounting drift that a single-implementation invariant can't see, because both sides are self-consistent.

Fork: vm.createSelectFork(rpcUrl, blockNumber) pins state. Pin the block number explicitly; an unpinned fork silently advances and your regression stops reproducing.

Trade-offs. Invariant fuzzing finds shallow multi-step bugs cheaply but proves nothing. Formal verification (Certora, Halmos) proves a property over all inputs, but you pay spec-writing time and only cover what you specify: a 20-line CVL rule can take an hour to get right. Fork tests are the only way to catch integration assumptions, but each needs an archive node and seconds of RPC; local deploys with mocks are fast and test your mock, not the protocol.

Failure modes. Weak generators (fuzzer never constructs the actor set); missing actors (privileged role absent from the target); wrong oracle (invariant asserts on a value the contract itself computes); stale fork; untested governance path; and coverage as proof: 100% line coverage with no invariant says nothing about multi-step state.

Curated: · Written: · Reviewed:

Difficulty: Hard