Skip to content
Tech Interview Prep
Technical interview guide

DeFi Primitives (AMMs, Lending, Liquidity Pools)

The core building blocks of decentralized finance: automated market makers, lending protocols, and the liquidity pools they're built on.

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

Scope: Uniswap v2 and v3 specifications; Aave borrowing and liquidation documentation reviewed 2026-09-04 (version-specific parameters must be checked at integration); Chainlink Data Feeds; ERC-4626; ERC-3156; OWASP SCSVS.

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

Explain and implement a constant-product swap quote.

Answer

Core answer (first 90 seconds). Assume a Uniswap V2-style pool: two tokens with reserves x and y, invariant x·y = k, a 0.3% fee taken from the input (997/1000), and integer reserves. A quote answers one of two questions: given Δx in, how much Δy out (exact-in), or given Δy out, how much Δx in (exact-out). Both fall out of solving the post-trade invariant.

Derivation. The fee is charged on the input, so effective input is Δx' = Δx·997/1000. After the swap the pool holds x + Δx' and y − Δy, and the invariant must still hold:

(x + Δx')(y − Δy) = x·y
Δy = y·Δx' / (x + Δx')

That is the whole quote. Spot price is y/x; execution price Δy/Δx is worse by the fee plus price impact, which grows with Δx/x. Inverting for exact-out gives Δx = x·Δy / ((y − Δy)·0.997), rounded up.

Implementation (Solidity ^0.8.20; 0.8 has built-in overflow checks, so no SafeMath).

SOLIDITY
library ConstantProduct {
    uint256 constant FEE_NUM = 997;
    uint256 constant FEE_DEN = 1000;

    // Exact-in: floor the output so the pool never pays out more than k allows.
    function getAmountOut(uint256 amountIn, uint256 reserveIn, uint256 reserveOut)
        internal pure returns (uint256 amountOut)
    {
        require(amountIn > 0, "INSUFFICIENT_INPUT");
        require(reserveIn > 0 && reserveOut > 0, "INSUFFICIENT_LIQUIDITY");
        uint256 inWithFee = amountIn * FEE_NUM;
        amountOut = (inWithFee * reserveOut) / (reserveIn * FEE_DEN + inWithFee);
    }

    // Exact-out: ceil the input so the user always pays at least the invariant cost.
    function getAmountIn(uint256 amountOut, uint256 reserveIn, uint256 reserveOut)
        internal pure returns (uint256 amountIn)
    {
        require(amountOut > 0, "INSUFFICIENT_OUTPUT");
        require(reserveIn > 0 && reserveOut > 0, "INSUFFICIENT_LIQUIDITY");
        require(amountOut < reserveOut, "INSUFFICIENT_LIQUIDITY");
        uint256 numerator = reserveIn * amountOut * FEE_DEN;
        uint256 denominator = (reserveOut - amountOut) * FEE_NUM;
        amountIn = numerator / denominator + 1;
    }
}

Worked trace. Reserves x = 10,000, y = 20,000,000; swap Δx = 100 in.

inWithFee  = 100 * 997            = 99,700
numerator  = 99,700 * 20,000,000  = 1,994,000,000,000
denominator= 10,000*1000 + 99,700 = 10,099,700
amountOut  = 1,994,000,000,000 / 10,099,700 = 197,431  (floor)

Spot is 20,000,000/10,000 = 2,000; execution is 197,431/100 = 1,974.31, a 1.28% hit. Running getAmountIn(197,431) returns 100 (the +1 rounds up), so the round trip is consistent.

Trade-offs. Exact-in floors the output (user receives ≤); exact-out ceils the input (user pays ≥). Pick by who should absorb the rounding dust. An on-chain quote is atomic and current but costs gas and can be front-run; an off-chain quote is cheap but stale. Constant product is always liquid across the curve; Uniswap V3 quotes depend on the tick range and in-range liquidity, not a single k. A TWAP resists manipulation but lags the true price.

Failure modes and detection.

  • Stale reserves: reserves move before the tx lands. Detect by comparing quote reserves to on-chain at execution and enforcing amountOutMin.
  • Fee mismatch: pool is a 0.05% or 1% tier, not 0.3%. Read the fee from the pool; never hardcode.
  • Rounding direction: floor on out, ceil on in. Fuzz getAmountIn(getAmountOut(x)) >= x.
  • Fee-on-transfer / rebasing tokens: received amount ≠ amountIn, breaking the invariant. Check the balance delta.
  • Sandwich: attacker moves price ahead of you. Bound slippage and set a deadline.
  • Insufficient liquidity: amountOut >= reserveOut reverts or divides by zero. require(amountOut < reserveOut).
  • Quote ≠ execution: a quote is a snapshot, not a guarantee. Enforce the bound on-chain.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-4

How do you calculate impermanent loss and determine under what conditions trading fee yields offset divergence loss for a liquidity provider?

Answer

Impermanent loss (divergence loss) measures the underperformance of an AMM liquidity position relative to holding the original underlying assets outside the pool. In a constant-product market maker ($xy = k$), price $P = y / x$. When relative price shifts by a factor $k_r = P_1 / P_0$, the pool automatically rebalances by selling appreciating assets for depreciating assets to maintain the invariant.

Mathematical Formulation

  1. Initial state ($t_0$): Reserves are $x_0, y_0$ with price $P_0 = y_0 / x_0$. Asset portfolio value $V_{hold} = x_0 P_0 + y_0 = 2 y_0$.
  2. New price state ($t_1$): Spot price changes to $P_1 = k_r P_0$. Invariant $x_1 y_1 = k = x_0 y_0$ yields new reserves: $$x_1 = \sqrt{\frac{k}{P_1}} = \frac{x_0}{\sqrt{k_r}}, \quad y_1 = \sqrt{k P_1} = y_0 \sqrt{k_r}$$
  3. Pool position value at $P_1$: $$V_{pool} = x_1 P_1 + y_1 = \frac{x_0}{\sqrt{k_r}} (k_r P_0) + y_0 \sqrt{k_r} = 2 y_0 \sqrt{k_r}$$
  4. Holding value at $P_1$: $$V_{hold} = x_0 P_1 + y_0 = x_0 (k_r P_0) + y_0 = y_0 (k_r + 1)$$
  5. Impermanent Loss ratio: $$IL(k_r) = \frac{V_{pool}}{V_{hold}} - 1 = \frac{2 \sqrt{k_r}}{1 + k_r} - 1$$

Worked Example

Assume $1\text{ ETH} = 2{,}000\text{ USDC}$. A provider deposits $10\text{ ETH}$ ($x_0$) and $20{,}000\text{ USDC}$ ($y_0$). Total value deposited is $40{,}000\text{ USDC}$.

ETH doubles to $4{,}000\text{ USDC}$ ($k_r = 2$):

  • $x_1 = 10 / \sqrt{2} \approx 7.071\text{ ETH}$
  • $y_1 = 20{,}000 \times \sqrt{2} \approx 28{,}284.27\text{ USDC}$
  • $V_{pool} = (7.071 \times 4{,}000) + 28{,}284.27 = 56{,}568.54\text{ USDC}$
  • $V_{hold} = (10 \times 4{,}000) + 20{,}000 = 60{,}000\text{ USDC}$
  • $IL = (56{,}568.54 / 60{,}000) - 1 \approx -5.72%$
  • Absolute divergence loss: $3{,}431.46\text{ USDC}$.

Break-Even Condition Against Fees

For net return to be non-negative relative to HODL, accumulated trading fee returns $R_{fee}$ must satisfy: $$(1 + R_{fee}) \cdot (1 + IL) \ge 1 \implies R_{fee} \ge \frac{1}{1 + IL} - 1 = \frac{1 + k_r}{2 \sqrt{k_r}} - 1$$

In a pool with fee tier $f$ (e.g., $0.30% = 0.003$) and total pool liquidity $L_{pool}$, if an LP owns share $s = L_{lp} / L_{pool}$ over time period $T$, accumulated fees are: $$Fees = s \cdot f \cdot Volume$$

The threshold volume required over period $T$ to neutralize divergence loss is: $$Volume_{break\text{-}even} = \frac{V_{pool} \left( \frac{1 + k_r}{2 \sqrt{k_r}} - 1 \right)}{f}$$

Price Multiplier ($k_r$)Impermanent LossBreak-Even Fee Yield Needed ($R_{fee}$)Break-Even Cumulative $V/L$ Ratio ($f = 0.3%$)
1.25x (+25%)-0.61%+0.61%~2.03x
1.50x (+50%)-2.02%+2.06%~6.87x
2.00x (+100%)-5.72%+6.07%~20.23x
3.00x (+200%)-13.40%+15.47%~51.57x
5.00x (+400%)-25.46%+34.16%~113.88x

Operational and Structural Boundaries

  1. Concentrated Liquidity (Uniswap v3): Divergence loss scales inversely with range width $[p_a, p_b]$. If price exits the range, loss caps at $100%$ of the outperforming asset, while fee accrual drops to zero immediately.
  2. Toxic Order Flow / LVR (Loss-Versus-Rebalancing): Arbitrageurs drain value on every external reference price shift before retail volume arrives. High volume driven exclusively by arbitrage generates fee yields strictly smaller than divergence losses.
  3. Mean-Reverting Pairs: Stablecoin or pegged pairs ($k_r \approx 1$) exhibit near-zero divergence loss, meaning even low fee yields ($0.01%$ to $0.05%$) outpace $IL$ unless a permanent depeg occurs.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

Mint and burn pool shares without diluting providers.

Answer

The 90-second answer. Assume a two-asset constant-product pool (Uniswap V2 style), 18-decimal tokens, and that "no dilution" means an existing LP's claim on reserves is unchanged by someone else's mint or burn. The rule is: price the deposit at the worse of the two implied prices, and round every division down.

Mint: shares = min(amount0 * totalSupply / reserve0, amount1 * totalSupply / reserve1). Burn: amount0 = shares * reserve0 / totalSupply, same for token1. The min is the whole trick: deposit lopsided and you get shares priced at the side you're shorting, and the excess you transferred stays in the pool for existing LPs. That's not a bug; it's the anti-dilution guarantee.

Worked mint. Pool holds 100 ETH / 200,000 USDC, totalSupply 10,000 LP. Alice deposits 1 ETH + 2,000 USDC. amount0 = 1e18 * 10,000 / 100e18 = 100. amount1 = 2,000e6 * 10,000 / 200,000e6 = 100. min = 100 LP. New totalSupply 10,100, reserves 101 ETH / 202,000 USDC. Alice's claim: 100/10,100 * 101 ETH = 1.0 ETH. Exactly what she put in, no dilution either way.

Now Alice deposits 1 ETH + 1,000 USDC instead. amount0 = 100, amount1 = 50, min = 50 LP. Both full amounts are transferred, so she gets 50 LP worth ~0.5 ETH while depositing ~1.5 ETH of value; the extra ~1 ETH accrues to existing LPs. That asymmetry is the mechanism working.

Burn. Alice burns her 50 LP: amount0 = 50 * 101 / 10,100 = 0.5 ETH, amount1 = 50 * 202,000 / 10,100 = 1,000 USDC. Integer division truncates, so she receives 0.5 ETH and 1,000 USDC and the dust stays in the pool. Rounding down on both mint and burn means the pool never pays out more than it owes.

First deposit. There's no totalSupply to divide by, so Uniswap V2 mints sqrt(amount0 * amount1) - MINIMUM_LIQUIDITY, with MINIMUM_LIQUIDITY = 1000 wei sent to address(0). First LP deposits 1 ETH (1e18) and 2,000 USDC (2e9): sqrt(1e18 * 2e9) = sqrt(2e27) ≈ 4.472e13, so the depositor gets ~44,721,359,689,995 LP and 1000 are locked forever. The lock's job isn't proportion: it's that totalSupply can never reach zero, so nobody can inflate the share price by donating into an empty pool.

Trade-offs. min() is right for a two-asset constant-product pool because it needs no oracle. If you want to accept lopsided deposits at fair value, you need an oracle price and a fee, the Balancer weighted-pool route, and that costs you an oracle dependency and a manipulation surface. ERC-4626 vaults use shares = assets * totalSupply / totalAssets, fine for a single asset but with its own inflation attack, mitigated by virtual shares/offset.

Failure modes and how you'd see them.

  • First-depositor inflation: attacker mints 1 wei, donates a large amount, next depositor's min() rounds to 0 shares. Detect: totalSupply tiny while reserves are large. Guard: MINIMUM_LIQUIDITY lock.
  • Donation: reserve jump with no Mint event. Detect by comparing reserves to the last event.
  • Fee-on-transfer tokens: the amount argument ≠ amount received. Guard: read reserves after the transfer (balance delta), never trust the argument.
  • Reentrancy: burn state before transferring assets, and use a reentrancy guard. Detect via Mint/Burn/Swap event ordering.
  • Stale reserves: read reserves after the last transfer in the same transaction.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Build safe swap transaction parameters.

Answer

Core answer (say this first).

A safe swap is three parameters and one refusal. You derive amountOutMinimum (or amountInMaximum) from a quote taken at the current block, set a deadline in seconds, and refuse to sign if either is missing or effectively unbounded. On Uniswap V3's SwapRouter that is ExactInputSingleParams{tokenIn, tokenOut, fee, recipient, deadline, amountIn, amountOutMinimum, sqrtPriceLimitX96}; on V2 it is swapExactTokensForTokens(amountIn, amountOutMin, path, to, deadline). The bound caps your on-chain loss; the deadline stops a transaction that sat in the mempool from filling against a market that no longer exists.

Choosing the numbers.

Slippage tolerance is a policy, not a constant. A working default: 5–10 bps for stable/stable, 30–50 bps for correlated pairs (ETH/stETH), 100–300 bps for volatile pairs. Anything above 500 bps on a size above roughly $10k should require an explicit confirmation, because a 5% bound on a $100k swap hands $5k to whoever can move the pool to just inside your limit.

Deadline is a unix timestamp in seconds, not a duration: block.timestamp + 30 is 30 seconds, 30 is 1970 and reverts. For a bot, 30–120 seconds; for a human in a wallet, 10–30 minutes is the usual range. Price impact is separate from slippage: warn above 1%, block above 5% unless the user confirms.

Failure modes, with the signal and the cost.

  • Sandwiching inside the bound. The attacker pushes the price to just inside amountOutMinimum, so you fill at the worst allowed price. Signal: realized execution price versus the mid-price at submission, and two transactions in the same block bracketing yours. Cost: the full width of your bound times notional.
  • Stale quote. Quote taken at block N, executed at N+5. Signal: quote age in blocks; compare quoted reserves to on-chain reserves at execution. Cost: revert (gas burned) or a fill worse than the UI showed.
  • Excessive tolerance. Signal: alert on any bound above your policy ceiling. Cost: value leaked to searchers on every fill.
  • Deadline confusion. Signal: a unit test asserting the deadline equals block.timestamp + delta, not delta. Cost: revert gas, or a fill minutes later against a moved market.
  • Fee-on-transfer or rebasing tokens. amountOutMinimum is computed on the nominal amount, but the pool receives less. Signal: balance delta before and after the transfer. Cost: revert or a shortfall the user eats.
  • Route change. A multi-hop path where an intermediate pool's liquidity moved. Signal: simulate the exact path against current state before signing. Cost: revert or a worse fill.
  • Censorship. The bound does not guarantee inclusion; a builder can drop your transaction. Signal: transaction not mined within the deadline. Cost: missed execution, not loss.
  • Failed-transaction gas. A revert still costs gas. Signal: gas used on revert in simulation. Cost: the gas, plus the opportunity cost of the missed swap.

Trade-offs and alternatives.

Tighter bound, more reverts, less MEV leakage; looser bound, more fills, more leakage. The deciding criteria are size relative to pool depth, how latency-sensitive the trade is, and whether a human is present to re-sign. If leakage matters more than inclusion certainty, route through a private relay (Flashbots Protect) or a batch auction (CoW Swap, UniswapX) where solvers compete and surplus goes back to the user. If you need a guaranteed price now, an RFQ from a market maker (0x) trades surplus for certainty. A limit order or TWAP is the right tool when the user is not in a hurry.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

Reduce sandwich exposure for a trading interface.

Answer

Assume Ethereum mainnet, a web interface that sets default slippage and gas, and a user wallet that signs transactions. The interface controls the RPC endpoint and routing.

The core answer: remove the public mempool signal and cap the attacker's profit. Submit through a private relay like Flashbots Protect or MEV Blocker, set slippage to the tightest value that still fills, and batch or split orders when they are predictable.

A sandwich attack needs to see your pending transaction before it lands. In the public mempool, a searcher sees your swap, buys the same asset ahead of you, lets your trade push the price up, then sells. Their profit is bounded by your slippage tolerance: if you allow 1%, they can take up to 1% minus gas. Private submission sends the signed transaction directly to block builders (e.g., Flashbots, Titan, Beaver, rsync) without broadcasting to the public mempool. The searcher never sees it, so they cannot front-run. Flashbots Protect is an RPC endpoint (https://rpc.flashbots.net) that routes to Flashbots builders. MEV Blocker (https://rpc.mevblocker.io) routes to a set of builders and returns a rebate for some MEV. Both add latency: typically one to two blocks, because builders include private transactions at the end of their block-building process.

The cost is trust and liveness. You now depend on the relay to include your transaction and not leak it. If the relay censors or goes down, your transaction may not land. MEV Blocker has a fallback to public mempool after a timeout, which reintroduces sandwich risk. Tight slippage reduces attacker profit but increases revert risk: on a liquid pair like ETH/USDC, 0.1% is often enough; on a long-tail token, 0.5% or 1% may be needed to avoid reverts. Batching multiple trades into one transaction or using a batch auction (e.g., CoW Swap) makes individual trades less predictable, but adds latency and complexity. On-chain limit orders avoid the mempool entirely but may not fill immediately.

When not to use private relays: if you need immediate execution and the trade is small relative to pool liquidity, the gas cost of a sandwich may exceed the profit, so public submission with tight slippage is acceptable. On L2s with a private sequencer (e.g., Arbitrum, Optimism), the mempool is not public, so sandwich risk is lower; private relays are unnecessary.

Detect relay censorship by monitoring inclusion time; if a transaction is not included within two blocks, fall back. Detect stale private quotes by comparing execution price to a fresh oracle. Revert gas is a cost: each failed transaction still costs gas. Fragmented routes across multiple DEXs can be sandwiched on each leg; use an aggregator that splits optimally. Never claim MEV elimination: private relays reduce but do not eliminate, because builders can still reorder within their own block.

OptionMechanismLatencyTrust assumptionWhen to use
Flashbots ProtectRPC to Flashbots builders1-2 blocksFlashbots does not leakDefault for mainnet swaps
MEV BlockerRPC to multiple builders, rebate1-2 blocksBuilders do not leakWhen you want rebate
Public mempool + tight slippageBroadcast to all0 blocksNoneSmall trades, L2s with private sequencer
Batch auction (CoW Swap)Solver competition30s-2minSolvers do not front-runNon-urgent trades

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Estimate safe execution for a large AMM order.

Answer

Core answer. Assume a Uniswap-v2-style constant-product pool, 0.3% fee, ETH/USDC with 10,000 ETH and 20,000,000 USDC (spot 2,000). For a 100 ETH sell the rule of thumb is: total slippage ≈ fee + (size / input reserve) = 0.3% + 100/10,000 ≈ 1.3%. So expect ~197,400 USDC out, not 200,000, and set minOut about 1% below the simulated fill (~195,500) rather than at spot. The number that decides safety is size relative to the reserve you're draining, not the dollar notional.

The arithmetic. Constant product x·y = k, fee taken off the input.

in' = 100 × 0.997 = 99.7 ETH
x'  = 10,000 + 99.7 = 10,099.7
y'  = k / x' = 200,000,000,000 / 10,099.7 = 19,802,568
out = 20,000,000 − 19,802,568 = 197,432 USDC

Against 200,000 of spot value that is 1.28% total: 0.3% fee, ~0.98% impact. Impact grows with size/reserve: 500 ETH into the same pool gives in' = 498.5, x' = 10,498.5, y' = 19,050,341, out = 949,660, i.e. 5.03% total and ~4.73% impact. Five times the size, roughly five times the impact.

Splitting. Within one pool, splitting is path-independent: two 50 ETH sells return 99,206 + 98,226 = 197,432, identical to the single 100 ETH sell. Splitting only pays across venues or when other flow moves price between legs. Across two identical pools, 50 ETH each returns 2 × 99,206 = 198,411: 979 USDC (0.49%) better. Deciding criterion: extra gas per hop versus impact saved. An extra mainnet swap is ~150k gas; at 20 gwei and $3,000 ETH that is ~$9, so the split wins here. If the second venue is arbitraged to the first, the 979 USDC evaporates and you paid gas for nothing: reject the split.

Failure modes and detection.

  • Sandwiching: an attacker front-runs your visible tx. Detect by comparing realized price to the quote at submission block; slippage beyond your simulated impact by more than a few bps means you were sandwiched. Mitigate with private submission (Flashbots) and tight minOut.
  • Stale quote: quoted at block N, filled at N+3. Re-read reserves at execution and revert if they moved past tolerance.
  • Insufficient depth: simulate against current reserves; if impact exceeds your cap (say 2%), the pool is too thin. Route elsewhere or split.
  • Fee-tier or dynamic-fee change: read the fee from the pool at execution; never hardcode 0.3%.
  • Partial intent: a multi-tx split where leg 2 reverts leaves you half-filled. Use an atomic router or track and unwind.
  • Route correlation: two "independent" pools sharing LPs or arbitraged together give no split benefit. Check price correlation before trusting the second venue.

What I'd encode. maxIn on the input token, minOut from the simulated fill minus tolerance, a deadline, and a router that reverts atomically. Then verify with a fork simulation against current state before signing.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Walk me through how you'd quote a 100k USDC to USDT swap against a Curve-style stableswap pool, and why the slippage is so much lower than the same trade on a constant-product pool.

Answer

A stableswap quote is not a price lookup. You solve the pool's invariant for the output balance, holding D fixed across the swap.

The invariant blends constant-sum and constant-product behaviour:

Ann*(x + y) + D = Ann*D + D^3/(4xy),   Ann = A*n

A is the amplification coefficient, n the number of coins. At perfect balance D = x + y; otherwise D is solved by Newton from the current balances and then held constant for the swap. To quote dx of coin x: set x' = x + dx, solve the same equation for y', and the output is y - y'.

python

Python 3.11, n = 2, integer arithmetic, round the output down.

def get_D(x, y, Ann, n=2): S = x + y D = S for _ in range(255): D_P = D * D // (x * n) * D // (y * n) D_prev = D D = (Ann * S + D_P * n) * D // ((Ann - 1) * D + (n + 1) * D_P) if abs(D - D_prev) <= 1: return D raise ValueError('D did not converge')

def get_y(x_new, D, Ann, n=2): c = D * D // (x_new * n) * D // (Ann * n) # D^3 / (4Annx_new) b = x_new + D // Ann y = D for _ in range(255): y_prev = y y = (y * y + c) // (2 * y + b - D) if abs(y - y_prev) <= 1: return y raise ValueError('y did not converge')

Worked quote, USDC/USDT, x = y = 1,000,000, A = 100 so Ann = 200. D = 2,000,000 satisfies the invariant at balance (both sides 402,000,000). Swap in dx = 100,000, so x' = 1,100,000:

200*(1,100,000 + y) + 2,000,000 = 200*2,000,000 + 8e18/(4*1,100,000*y)
200y - 178,000,000 = 1.8181818e12/y
y^2 - 890,000y - 9.090909e9 = 0
y' = (890,000 + sqrt(890,000^2 + 4*9.090909e9))/2 = 900,100

Two roots, +900,100 and -10,100; only the positive one is a balance. Check it: LHS = 2002,000,100 + 2,000,000 = 402,020,000, RHS = 400,000,000 + 8e18/3,960,440,000 = 402,019,978, agreeing to 22 wei. Output = 1,000,000 - 900,100 = 99,900 USDT, average price 0.9990, 10 bps. The same 100,000 into an xy = 1e12 pool returns 90,909, 909 bps.

dx instableswap outavg pricex*y=k outavg price
100,00099,9000.9990 (10 bps)90,9090.9091 (909 bps)
200,000199,5890.99795 (21 bps)166,6670.8333 (1667 bps)
500,000496,7530.99351 (65 bps)333,3330.6667 (3333 bps)
900,000869,6290.96625 (338 bps)473,6840.4737 (5263 bps)

The marginal price comes from implicit differentiation: p = (Ann + D^3/(4x^2 y)) / (Ann + D^3/(4x y^2)). At balance the constant-product term is exactly 2 whatever the pool size, so A = 100 buys a 100:1 ratio of amplification to curvature at the peg. That is why the first 10% of the pool costs 10 bps instead of 909.

Trade-offs. High A flattens the curve near the peg but lets the pool be drained to near-zero on one side, and LPs wear the loss when a coin depegs. The flat region is narrower than the crossover suggests: the constant-product term equals Ann only at x^2 y = D^3/(4Ann), which here is x = 70,900, y = 1,990,000, a 93% imbalance, where the marginal price is already 1.93. Deviation grows with imbalance:

imbalancemarginal price
10%1.0020 (20 bps)
20%1.0043 (43 bps)
30%1.0072 (72 bps)
40%1.0112 (112 bps)

A = 0 is exactly constant product. The invariant has no concept of a peg: if USDT trades at 0.97 it quotes along the curve as if nothing happened, so a stableswap quote is only meaningful while the coins are actually worth the same.

Failure modes. Decimals: Curve normalises balances to a common precision (1e18 or 1e30) before the invariant while get_dy takes raw amounts; mixing the two silently misprices the quote. Fee: read it from the pool rather than assuming it, Curve stable pools have run 1-4 bps, and apply it after the invariant. Ramping A: ramp_A moves A over days, so a quote built with today's A is wrong at execution; read future_A and future_A_time. Stale balances: an off-chain quote executed a block later is a sandwich target, so take minAmountOut from a fresh eth_call. Integer Newton converges to within 1 wei in at most 255 iterations or the pool reverts, so round the output down. In practice, do not reimplement this to execute: eth_call get_dy at the target block (get_dy_underlying for lending pools) and use the invariant to reason about slippage and to sanity-check the result.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

How does concentrated liquidity in an AMM alter impermanent loss and fee dynamics compared to a standard constant product pool?

Answer

In Uniswap v2, liquidity spans $P \in (0, \infty)$ under $x \cdot y = k$. In Uniswap v3, liquidity providers (LPs) supply tokens only within a finite interval $[p_a, p_b]$. The pool invariant inside the range is governed by virtual reserves: $$(x + x_v)(y + y_v) = L^2$$ where $x_v = \frac{L}{\sqrt{p_b}}$ and $y_v = L \sqrt{p_a}$. Real balances held by the position at price $P \in [p_a, p_b]$ are: $$x = L \left(\frac{1}{\sqrt{P}} - \frac{1}{\sqrt{p_b}}\right), \quad y = L (\sqrt{P} - \sqrt{p_a})$$

1. Capital Efficiency and Virtual Depth

To supply liquidity depth $L$ in v2, an LP must deposit $V_{v2} = 2L\sqrt{P}$. In concentrated liquidity, the LP only deposits real reserves $x$ and $y$. Evaluating total position value $V(P) = xP + y$: $$V(P) = L \left(2\sqrt{P} - \frac{P}{\sqrt{p_b}} - \sqrt{p_a}\right)$$ Because the LP commits less capital for the same liquidity parameter $L$, their capital efficiency is magnified. At range boundaries, real balances of one asset hit exactly zero: if $P \le p_a$, $y = 0$ and the position is 100% token $x$; if $P \ge p_b$, $x = 0$ and the position is 100% token $y$.

2. Fee Dynamics

  • Accrual outside the invariant: In v2, fees compound directly into pool reserves $k$. In v3, fees do not compound into $L$; they are tracked outside the invariant via global fee growth variables ($feeGrowthGlobal0$, $feeGrowthGlobal1$) per unit of liquidity $L$.
  • Yield amplification within range: When $P \in [p_a, p_b]$, the position earns fees proportional to $L_{pos} / L_{pool}$. Because $L$ is produced using less principal, fee APR scales directly with the reduced capital denominator.
  • Binary earning state: When $P$ drops below $p_a$ or rises above $p_b$, the position becomes inactive ($L_{active} = 0$). Fee generation drops immediately to 0 until the market price re-enters the interval.

3. Impermanent Loss Dynamics and Acceleration

Impermanent loss is calculated as percentage divergence from a HODL baseline: $\text{IL} = \frac{V_{LP}(P) - V_{hold}(P)}{V_{hold}(P)}$. In concentrated liquidity, IL is magnified because the real capital denominator is smaller than in v2 for the same change in token balances.

AttributeUniswap v2 ($0, \infty$)Uniswap v3 ($[p_a, p_b]$)
Invariant$x \cdot y = k$$(x + L/\sqrt{p_b})(y + L\sqrt{p_a}) = L^2$
Terminal StateAsymptotically approaches 0 as $P \to 0$ or $\infty$Exactly 100% token $x$ at $P \le p_a$; 100% token $y$ at $P \ge p_b$
Fee AccountingAuto-compounds into pool $k$Uncollected fees tracked per tick outside $L$
IL SensitivityStandard curve: $2\frac{\sqrt{r}}{1+r} - 1$Amplified divergence relative to initial capital committed

Worked Example: Price Move to Lower Bound

Let entry price $P_0 = 1000$ with range $[p_a, p_b] = [900, 1111.11]$.

  • $\sqrt{P_0} \approx 31.62278$
  • $\sqrt{p_a} = 30$
  • $\sqrt{p_b} \approx 33.33333$

Initial balances per unit $L$:

  • $x_0 = \frac{1}{31.62278} - \frac{1}{33.33333} \approx 0.031623 - 0.030000 = 0.001623$
  • $y_0 = 31.62278 - 30 = 1.62278$
  • Initial capital committed: $V_0 = x_0 P_0 + y_0 = (0.001623 \times 1000) + 1.62278 = 3.24556$

Now assume price moves to the lower boundary $P_1 = 900$ ($\sqrt{P_1} = 30$):

  • Concentrated Position Value ($V_1$): At $P_1 = 900$, $y_1 = 0$. $x_1 = \frac{1}{30} - \frac{1}{33.33333} = 0.033333 - 0.030000 = 0.003333$. $$V_1 = x_1 \times P_1 = 0.003333 \times 900 = 3.00000$$
  • HODL Value ($V_{hold}$): Holding the initial basket at $P_1 = 900$: $$V_{hold} = x_0 P_1 + y_0 = (0.001623 \times 900) + 1.62278 = 1.46070 + 1.62278 = 3.08348$$
  • Concentrated IL: $$\text{IL}_{v3} = \frac{3.00000 - 3.08348}{3.08348} = \frac{-0.08348}{3.08348} \approx -2.707%$$
  • Uniswap v2 IL comparison ($r = 900/1000 = 0.9$): $$\text{IL}_{v2} = \frac{2\sqrt{0.9}}{1 + 0.9} - 1 = \frac{2(0.948683)}{1.9} - 1 \approx -0.1386%$$

Here, impermanent loss is amplified by $\frac{-2.707%}{-0.1386%} \approx 19.53\times$. The capital efficiency multiplier ($1 / (1 - \sqrt{p_a/p_b}) = 10\times$) does not equal the IL amplification factor because IL measures the divergence against a smaller, non-infinite real capital baseline.

Failure Modes & Trade-offs

  1. Directional Runaway / Skewed Inventory: If the price trends outside $[p_a, p_b]$, the LP stops earning fees entirely while holding 100% of the asset that declined in relative value, suffering maximum divergence loss.
  2. Rebalancing Drag & Gas Friction: Active management requires withdrawing liquidity, re-centering ticks, and redepositing. On L1 Ethereum, contract invocations crossing multiple initialized ticks consume substantial gas (e.g., $100\text{k}+\text{ gas}$), which can easily erase fee earnings on volatile pairs.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Select and operate concentrated-liquidity ranges.

Answer

Core. I need the pair, the pool, the fee tier, and how often I can actually touch the position. Assume ETH/USDC, 0.05% tier (tick spacing 10), entry at $3,000, and at most one rebalance a day. The decision is: set the range width from the volatility I expect over the rebalance horizon, then check that fee income over that horizon beats divergence loss plus rebalance cost. If it doesn't, widen the range or don't LP.

Selecting the range. Price is indexed by tick, p = 1.0001^tick, so 1% ≈ 100 ticks. Tick spacing is fixed per tier: 1 (0.01%), 10 (0.05%), 60 (0.30%), 200 (1.00%), and it caps how tight you can go: a 0.30% pool can't express anything narrower than 60 ticks, ~0.6%.

Worked: at $3,000 the current tick is ln(3000)/ln(1.0001) ≈ 80,068. A ±1% range is ticks 79,968 to 80,168: 200 ticks wide. At spacing 10 I round to 79,970 and 80,170, i.e. $2,970.8 to $3,030.9.

Narrower buys capital efficiency: a symmetric range p/1.01 to 1.01p gives 1/(1 − (p_a/p_b)^(1/4)) ≈ 200× the depth of a full-range position for the same capital. That's the point and the risk: divergence loss scales by the same factor.

Operating. Fees aren't stored per position. The pool tracks feeGrowthGlobal per unit of liquidity; a position's claim is L × (feeGrowthInside − feeGrowthInsideLast) / 2^128, where feeGrowthInside = feeGrowthGlobal − feeGrowthBelow(tickLower) − feeGrowthAbove(tickUpper). It only advances while the current tick is inside your range.

Trace: pool liquidity 1,000,000, our position L = 10,000 (1%). A $1,000 swap at 0.05% pays $0.50, so ΔfeeGrowthGlobal = 0.50/1,000,000 = 5.0e-7 (stored as 5.0e-7 × 2^128 ≈ 1.70e32). A second $4,000 swap pays $2.00 → cumulative 2.5e-6. Our claim: 10,000 × 2.5e-6 = $0.025. Now a $10,000 swap pays $5.00, but the tick crosses out of our range after only $1.00 of it accrued inside; feeGrowthInside stops at 3.5e-6 and our claim is $0.035. The other $4.00 went to positions the price moved into. From here accrual is frozen: we're 100% in the token that got cheap and earning nothing.

Trade-offs. Tight: more fee share, but you exit more often, pay more gas, and take more divergence loss and adverse selection. You're systematically selling the token that's running. Wide: less management, lower yield. Concentrated liquidity isn't worth it when volume is thin, gas is high, or you can't watch the tick; full-range or just holding is the honest alternative.

The arithmetic that decides it. Divergence loss at the range edge ≈ half-width/4. For ±1% that's ~0.25% of position value per 1% move (full-range is ~0.0012%, the 200× again).

Item, $10k position, ±1%, daily rebalanceValue
Divergence loss if price moves 1%0.25% × $10,000 = $25
Gas, 200k round trip @ 20 gwei, ETH $3,000$12
Break-even fee income/day$37 → 135% APR
Same on Base @ 0.05 gweigas $0.03 → break-even $25/day → 91% APR

And the range gets breached often: ETH at 60% annualized vol has daily σ ≈ 60%/√365 ≈ 3.1%, so ±1% is ±0.32σ. Under a zero-drift normal model the position stays in range only ~25% of days. Gas is not the binding constraint; divergence loss is. That's why I'd widen to ±5% or more unless fee APR is genuinely triple-digit.

Failure modes and detection. Out-of-range inactivity: tick outside bounds, fees flat at zero. Adverse selection / LVR: position PnL trails a rebalancing benchmark. Gas-heavy churn: rebalance count × gas exceeds fees collected. Divergence loss: amplified ~200× at ±1%. Tick/bound mistakes: off-by-one against tick spacing. If a vault or manager runs it, contract or key compromise, bounded by position size.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

How would you implement multi-hop swap routing across several AMM pools, and how do you choose the path?

Answer

Assume Uniswap v2-style constant-product pools (x·y=k, 0.3% fee) and a router that executes a fixed path. The core answer: model tokens as nodes and pools as edges, quote each candidate path with getAmountsOut, pick the path (or split) that maximises final output net of gas, then execute with a slippage bound.

Mechanism. Each hop's output is amountOut = (reserveOut · amountIn · 997) / (reserveIn · 1000 + amountIn · 997). That function is concave in amountIn, so the best route is not always the shortest: a direct thin pool can be worse than two hops through deep pools. Enumerate simple paths up to maxHops (3-4 in practice), quote each, compare. For split routing across two paths, solve for the input split where marginal output per wei is equal: a small convex problem, usually 1-D bisection.

Worked trace. 10 WETH. Direct WETH/WBTC pool holds 200 WETH / 6 WBTC; multi-hop WETH→USDC→DAI→WBTC.

  • Direct: amountInWithFee = 9,970; out = 6·9,970/(200,000+9,970) = 0.2849 WBTC.
  • Hop 1 WETH/USDC (1,000 WETH, 2,000,000 USDC): out = 2,000,000·9,970/(1,000,000+9,970) = 19,743.16 USDC.
  • Hop 2 USDC/DAI (1,000,000 / 1,000,000): amountInWithFee = 19,743.16·997 = 19,683,930.52; out = 1,000,000·19,683,930.52/(1,000,000,000+19,683,930.52) = 19,303.95 DAI.
  • Hop 3 DAI/WBTC (500,000 DAI, 10 WBTC): amountInWithFee = 19,303.95·997 = 19,246,038.15; out = 10·19,246,038.15/(500,000,000+19,246,038.15) = 0.3707 WBTC.

Multi-hop wins by ~30%, so the router must not default to the direct pair.

routehopsoutput (WBTC)gas
direct WETH/WBTC10.2849~110k
WETH→USDC→DAI→WBTC30.3707~330k

Code. Off-chain quoting in TypeScript:

TypeScript
const paths = enumeratePaths(tokenIn, tokenOut, graph, 3);
const quotes = await Promise.all(paths.map(p => router.getAmountsOut(amountIn, p)));
const best = quotes.reduce((a, b) => a.at(-1)! > b.at(-1)! ? a : b);

On-chain execution is the v2 router loop: getAmountsOut, require(final >= amountOutMin), transfer to the first pair, then _swap walks the path, each pair sending its output to the next.

Trade-offs. Off-chain quoting is cheap and can consider hundreds of paths, but reserves move between quote and execution; the on-chain amountOutMin is the only real protection. On-chain quoting is trustless but costs gas per candidate. Cap maxHops: each hop adds ~70-100k gas, so at 30 gwei and $3,000 ETH a 4th hop costs ~$9-12. Only worth it if it improves output by more than that.

Failure modes. (1) Quote-execution gap: a sandwich or a large trade in the same block moves reserves; detect by logging realized vs. quoted output and alerting when realized < 0.99·quoted. (2) Fee-on-transfer or rebasing tokens break the invariant mid-route: getAmountsOut assumes exact transfers, so the last hop reverts or under-delivers. (3) Stale graph: a pool drained or paused since the last index; prune by reserve threshold and re-quote per block. (4) Path through a honeypot token that blocks sells. (5) Silent rounding on low-decimal tokens (e.g., WBTC 8 decimals) can make a hop output zero.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Model supplier accounting in a pooled lending market.

Answer

I'd model supplier claims as shares against a pool, not as a fixed balance. The pool has one global accumulator, either an index or an exchange rate, and each supplier holds a scaled balance or share count. Interest paid by borrowers increases the accumulator, so every supplier's claim grows without touching their stored balance.

Concretely, index model: index starts at 1.00. Supplier deposits 10,000 USDC. Scaled balance = 10,000 / 1.00 = 10,000. Borrowers pay 100 USDC interest. Index becomes 1.01. Claim = 10,000 × 1.01 = 10,100. If they withdraw 5,050, burn 5,050 / 1.01 = 5,000 scaled. Remaining claim = 5,000 × 1.01 = 5,050. Ignore rounding and reserves for the trace.

The critical ordering is accrue before any state change. If the index is stale at 1.00 but the true value is 1.01, a new deposit of 10,000 gets 10,000 scaled instead of 9,900.99. When the index updates, they instantly own 10,100: capturing 100 that belonged to existing suppliers. So every deposit, withdraw, borrow, repay, and liquidation calls accrue first.

Index vs share conversion. Index: one global index, per-user scaled balances. Aave uses a liquidity index in ray (1e27). Share conversion: per-user shares, global exchange rate. Compound uses cTokens and an exchangeRate. Both are monotonic under positive interest; a loss event can reduce the accumulator. Index is cheaper to accrue globally; share conversion is natural if you already have an ERC-20 share token. Deciding criteria: if you need to support rebasing or fee-on-transfer tokens, neither works directly. You must wrap or measure balance deltas. If you compute exchange rate from raw token balance, you're open to donation inflation; track internal cash instead.

Reconciliation: cash + debt - reserves - bad debt = supplier claims. Cash is idle liquidity. Debt is outstanding principal plus accrued interest. Reserves are the protocol's cut. Bad debt is unrecoverable borrows. If claims exceed that, you're insolvent. Expose withdrawal liquidity separately: available liquidity is idle cash; accounting value is cash + debt. A supplier can have a 10,100 claim but only 2,000 cash available, so they can't all withdraw.

Failure modes I'd test: bad debt. Reconcile and see claims > assets; socialize by reducing the index or drawing reserves. Stale accrual: compare index to elapsed-time interest; dilution. Utilization spike: available liquidity / total claims; if 100%, withdrawals queue. Run dynamics: simulate first-mover advantage; last suppliers stuck. Fee-on-transfer: compare balanceOf before/after; accounting mismatch. Oracle failure: deviation check; bad debt. Upgrade: storage diff and fork tests. Rounding: scaled balances are integers; round in favor of the pool and fuzz the invariant sum(scaled) × index <= cash + debt - reserves - bad debt.

So the model is: shares plus a monotonic accumulator, accrue first, reconcile cash + debt - reserves - bad debt to claims, and show liquidity separately from accounting value. The claim is not a demand deposit: it's exposed to borrower default, oracle error, and protocol risk.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Verify index-based debt accounting.

Answer

Assumptions I'd state first. "Index-based debt accounting" means a pool where each reserve carries a borrow index and each account stores a scaled debt. I'll assume Aave V3-style math (RAY = 1e27) and flag where Compound III (WAD = 1e18) differs. Verifying it means proving invariants hold under arbitrary call sequences, not reading the code and agreeing with it.

Core answer. Four invariants, one reference implementation, three test layers.

  1. borrowIndex is monotonic non-decreasing.
  2. debt_i = scaledDebt_i * borrowIndex / RAY, and scaledDebt_i changes only on borrow, repay or liquidation: never on accrual.
  3. totalBorrows == Σ scaledDebt_i * borrowIndex / RAY, up to one wei of dust per account.
  4. Rounding never favours the borrower: Σ debt_i >= totalBorrows after every call.

Test layers: differential-fuzz the accrual function against a high-precision reference; invariant-fuzz the pool with random call sequences; fork-test against a pinned mainnet block.

Why it works. Accrual is O(1) per reserve per block instead of O(n) per borrower. Aave V3's MathUtils.calculateCompoundedInterest is a third-order Taylor expansion of (1 + ratePerSecond)^elapsed:

SOLIDITY
// RAY = 1e27; rate is the APR in RAY, exp is elapsed seconds
uint256 ratePerSecond = rate / SECONDS_PER_YEAR;
uint256 basePowerTwo   = ratePerSecond.rayMul(ratePerSecond);
uint256 basePowerThree = basePowerTwo.rayMul(ratePerSecond);
return RAY + ratePerSecond * exp
     + exp * (exp - 1) * basePowerTwo / 2
     + exp * (exp - 1) * (exp - 2) * basePowerThree / 6;

Trace at 5% APR over one year (exp = 31,536,000): ratePerSecond = 1.5855e18; linear term 5.0000e25 (+0.05); second term 1.2500e24 (+0.00125); third term 2.0833e22 (+0.0000208). Index = 1.0512708e27. Continuous compounding gives e^0.05 = 1.0512711: the dropped fourth-order term is ~2.6e-7 relative, which is why the truncation is safe at realistic rates.

Trade-off. Compound III instead accrues simple interest per call: simpleInterestFactor = borrowRate * timeElapsed, then borrowIndex += simpleInterestFactor * borrowIndex / 1e18. That is two mulDivs instead of three rayMuls, but it is path-dependent: a reserve untouched for a year charges 5.000%, not 5.127%. Aave's Taylor form is path-independent and costs ~1 extra rayMul per accrual. Pick simple-per-accrual only if you can guarantee frequent touches; otherwise the effective rate drifts with usage.

Failure modes and how to catch them.

FailureTriggerDetection
Stale index readLiquidation or getUserAccountData runs before accrueInterestAssert borrowIndex after every state-changing call equals the reference implementation at that timestamp
Rounding leakDebt rounds down on repayFuzz 1e5 borrow/repay cycles; assert totalBorrows never decreases relative to Σ debt_i
Timestamp jumpSequencer posts a batch with a far-future timestamp; one accrual compounds a huge expMock block.timestamp forward by 30 days; assert index matches reference and no revert
Zero utilizationtotalBorrows == 0 in the utilization divisionUnit test: utilization returns 0, no divide-by-zero
Scale mismatch on upgradeProxy upgrade changes index scale (1e18 → 1e27) or initial indexStorage-layout diff plus a migration test reading a pre-upgrade scaled balance and asserting derived debt is unchanged

Overflow is a distant risk, not the binding one: with RAY = 1e27, scaledDebt * index for a 1e30-token debt is ~1e57, twenty orders below 2^256 ≈ 1.16e77. The real bound is the rate model's per-second rate and the elapsed-time cap.

Off-chain cross-check. Recompute the index from the rate model and compare against getReserveNormalizedVariableDebt on a pinned block; a mismatch means the on-chain accrual and the indexer disagree, which is the cheapest early warning you get.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Review a kinked utilization rate model.

Answer

First I'd pin down scope: which reserve, which chain, and whether this is a governance parameter review or a post-incident review. I'll assume an Aave V3-style two-slope model on a USDC reserve. The parameters are governance-set and get retuned, so I'd read them off the live interest rate strategy contract rather than trust a doc: the numbers below are illustrative of the shape, not a claim about today's mainnet values.

The kink exists because the pool has to stay withdrawable. Below the optimal utilization the curve is a gentle supply incentive; above it, the same curve becomes a scarcity price. The formula is piecewise linear:

R(U) = base + slope1 * U/U_opt, for U <= U_opt R(U) = base + slope1 + slope2 * (U - U_opt)/(1 - U_opt), for U > U_opt

Take base 0, slope1 5%, slope2 60%, U_opt 0.90. Tracing it:

utilizationrate
0.805% * 0.80/0.90 = 4.44%
0.90 (kink)5%
0.955% + 60% * 0.05/0.10 = 35%
1.005% + 60% * 0.10/0.10 = 65%

Below the kink the slope is 5%/0.90 = 5.6% per unit of utilization. Above it, 60%/0.10 = 600% per unit: about 108x steeper. That steepness is the design: a piecewise-linear stand-in for a convex cost of liquidity.

Worth contrasting with Compound's parameterization, because the same shape is expressed differently. Compound's cUSDC model is R(U) = base + multiplier * U below the kink, and R(U) = base + multiplier * kink + jump * (U - kink) above it. With base 0, multiplier 5%, jump 109%, kink 0.90: U=0.95 gives 4.5% + 109% * 0.05 = 9.95%, and U=1.00 gives 4.5% + 109% * 0.10 = 15.4%. The jump multiplier there is the slope of the excess, not the rate at U=1, so a 109% jump is far gentler than Aave's 60% slope2. Reading one as the other is a classic review miss.

Then four things to check: continuity at the kink, the reserve factor, the bounds, and the failure modes.

Continuity: the rate at U_opt from the first slope must equal the rate at U_opt from the second. If governance moves U_opt to 0.80 without recomputing slope1, borrowers get a step change for a one-wei utilization move. Test: assert R(U_opt) equals R(U_opt + 1 wei) within rounding.

Reserve factor: borrowers pay the borrow rate; suppliers get borrowRate * U * (1 - reserveFactor). At U = 0.90, a 5% borrow rate and a 10% reserve factor give suppliers 4.05%. Raise the reserve factor to 50% and they get 2.25%: the supply incentive the kink was supposed to create is halved.

Bounds: utilization must be clamped to [0, 1]. If interest accrues into total borrows without a matching increase in cash, or a repayment is double-counted, U can exceed 1e18 and slope2 extrapolates. Assert U <= 1 in the strategy.

Failure modes, with detection. Near-full utilization: at U = 0.99 there's 1% cash, so a single large supplier can't exit. Monitor available liquidity against the largest supplier balance, not just the rate. Stale accrual: the rate is computed on last-accrued state, so a borrow in the same block as a large withdrawal can push U past the kink and the next accrual charges the high rate for the whole elapsed window. Compare last-accrual timestamp to block timestamp. Atomic manipulation: flash-supply to push U below the kink, borrow cheap, repay. The rate should only move on accrual, not within a transaction. Supplier run: high rates don't help if there's no cash. Insolvency despite high rates: if collateral falls faster than interest accrues, the high borrow rate is irrelevant and you get bad debt. Watch the health-factor distribution, not the rate.

When is a kinked curve the wrong choice? If utilization is structurally pinned near 100% (one looping borrower, no natural suppliers) the kink just charges a high rate nobody responds to. Then you want a fixed-rate term market (Notional, Pendle) or an adaptive curve that retunes from observed elasticity (Morpho's IRM). If supply is highly elastic and demand is flat, a single-slope linear curve is simpler and has one fewer parameter to misconfigure. The deciding question: does the borrower set actually respond to price within a block or two? If yes, kinked. If no, the kink is decoration.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Implement liquidation accounting correctly.

Answer

What I'd say first

Liquidation accounting is one invariant: after the call, the borrower's health factor is higher than before, and the protocol holds at least as much value as it did. Close factor, bonus, protocol fee and rounding all exist to keep that true.

Health factor is risk-adjusted collateral over debt:

HF = Σ(collateral_i × price_i × liqThreshold_i) / Σ(debt_j × price_j)

Liquidatable when HF < 1. On Aave V3's Ethereum market ETH carries an 80% LTV, an 82.5% liquidation threshold and a 5% bonus; Compound V2 uses a flat 50% close factor and an 8% incentive.

The accounting

SOLIDITY
// Solidity 0.8.20. Prices share one 8-decimal scale (Chainlink);
// debt and collateral amounts stay in their own token decimals.
uint256 constant CLOSE_FACTOR_BPS = 5_000;   // 50%
uint256 constant FULL_CLOSE_HF    = 0.95e18; // below this, close factor is 100%
uint256 constant BONUS_BPS        = 10_500;  // 5% on ETH
uint256 constant PROTOCOL_FEE_BPS = 1_000;   // 10% of the bonus

function liquidate(address user, uint256 debtToCover) external nonReentrant {
    accrueInterest();                        // debt is current before anything is priced
    uint256 hfBefore = healthFactor(user);
    require(hfBefore < 1e18, "not liquidatable");

    uint256 maxRepay = hfBefore < FULL_CLOSE_HF
        ? debt[user]
        : debt[user] * CLOSE_FACTOR_BPS / 10_000;
    if (debtToCover > maxRepay) debtToCover = maxRepay;

    uint256 seizeValueDebt   = debtToCover * BONUS_BPS / 10_000;      // debt units
    uint256 collateralSeized = seizeValueDebt * priceDebt / priceCollateral; // truncates
    uint256 protocolFee      = (seizeValueDebt - debtToCover) * PROTOCOL_FEE_BPS
                               / 10_000 * priceDebt / priceCollateral;

    debt[user] -= debtToCover;
    collateral[user] -= collateralSeized;    // reverts if the position is short
    collateral[treasury] += protocolFee;

    debtToken.transferFrom(msg.sender, address(this), debtToCover);
    collateralToken.transfer(msg.sender, collateralSeized - protocolFee);

    require(healthFactor(user) > hfBefore, "HF must improve");
}

Rounding direction is not cosmetic. seizeValueDebt * priceDebt / priceCollateral truncates, so the borrower keeps the sub-wei remainder and the protocol never hands out more value than it took in. Rounding the other way lets a liquidator drain a wei per call, and on a 6-decimal debt token against 18-decimal collateral the error is 1e12 times larger.

Worked trace: 10 ETH collateral, 6,000 USDC debt, ETH falls to $700:

stepvalue
collateral value10 × $700 = $7,000
borrowing power$7,000 × 0.825 = $5,775
HF before5,775 / 6,000 = 0.9625
max repay6,000 × 50% = 3,000 USDC
seize value3,000 × 1.05 = $3,150
collateral seized3,150 / 700 = 4.5 ETH
bonus / protocol fee$150 → 10% = $15 = 0.02142857 ETH
liquidator receives4.47857143 ETH
HF after(5.5 × 700 × 0.825) / 3,000 = 1.0588

Trade-offs

A 50% close factor spreads the hit across several liquidators and avoids wiping a borrower who is barely under; Aave V3 switches to 100% below HF 0.95 because a position that far gone needs clearing in one call or it becomes protocol bad debt. Compound V2 is flat 50% and accepts the slower unwind.

Fixed bonus versus Dutch auction: a fixed 5–10% is cheap to compute and predictable, but in a fast crash it can fall below gas plus slippage and nobody liquidates. MakerDAO's Dutch auction starts at a high penalty and decays, extracting more value at the cost of latency and a keeper bot. The protocol fee is the same lever from the other side: Aave V3's default 10% cut of the bonus funds the treasury and shrinks the keeper's margin.

Failure modes and how you catch them

  • Stale price. Chainlink's ETH/USD mainnet feed has a 1-hour heartbeat and a 0.5% deviation trigger. Revert when updatedAt is older than the heartbeat; alert on oracle age. A stale price during a crash lets a liquidator seize collateral at yesterday's value.
  • Wrong decimals. USDC is 6, ETH 18, Chainlink 8. Mixing them scales silently by 1e12. Test with 6- and 8-decimal tokens and assert the seized amount is within 1 wei of the closed form.
  • Over-liquidation. Close factor unenforced, or the seize amount computed from pre-accrual debt. The HF_after > HF_before post-condition catches both; fuzz the close factor.
  • Dust. At 30 gwei and 200k gas a liquidation costs ~0.006 ETH, about $12 at $2,000. A $50 position on a 5% bonus pays $2.50. Skip positions below a minimum debt.
  • Reentrancy. The liquidator is a contract and the ERC-20 transfer can call back. Checks-effects-interactions plus nonReentrant.
  • Transfer-fee tokens. Measure the balance delta, never the transfer argument.
  • Congestion. Gas spikes make marginal liquidations unprofitable exactly when they are needed. Track liquidatable debt against liquidated debt as the leading indicator.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Calibrate liquidation incentive and close behavior.

Answer

Core answer

Assume an overcollateralized pool (Aave V3 / Compound V2 style). Health factor HF = Σ(collateral_i × LT_i) / Σ(debt_j); a position is liquidatable when HF < 1. Two knobs decide whether liquidation actually happens: the liquidation bonus B (extra collateral the keeper seizes on top of the debt repaid) and the close factor C (fraction of debt repayable in one call).

The rule I'd defend: B must make the keeper's expected profit positive after gas, slippage, oracle lag and competition, with margin; C must be small enough that one liquidation doesn't move the collateral price enough to push other positions under HF 1.

Sizing the bonus

Keeper EV per call ≈ C·D·B − gas − s·C·D·(1+B), where D is debt and s is slippage on the seized collateral. Solving for B:

B > gas/(C·D) + s·(1+B) → roughly B > gas/(C·D) + s + margin.

Worked example (hypothetical figures): $100k debt, $105k collateral, HF 0.98, WETH collateral. Aave V3's close factor here is 50% (HF ≥ 0.95), so C·D = $50k. With B = 5%: keeper repays $50k, seizes $52.5k → gross $2.5k. Gas: 300k gas at 50 gwei = 0.015 ETH ≈ $50 at $3,300/ETH. Slippage 0.5% on $52.5k = $262. Net ≈ $2.2k. Profitable.

Same bonus on a $500 debt: C·D = $250, gross bonus $12.50, gas $50 → keeper loses $37.50. Minimum viable debt is roughly gas/(C·B) = $50/(0.5 × 0.05) ≈ $2,000. Below that, dust never gets cleared and bad debt accrues.

Choosing the close factor

Compound V2 fixes C = 0.5. Aave V3 uses 50% while 0.95 ≤ HF < 1 and 100% once HF < 0.95. The reasoning: a position barely under water gets a partial close so the collateral sale is small and the borrower keeps most of their position; a deeply underwater position is cleared in one call so keepers don't spend gas on repeated partial liquidations that leave it still insolvent.

The trade-off: large C clears bad debt fast but dumps collateral into the market, if the seized amount is a meaningful fraction of DEX depth, the price impact pushes other borrowers under HF 1 (a cascade). Small C limits impact but leaves the position liquidatable again next block, and if keepers don't return, bad debt grows.

Failure modes and detection

  • Dust: positions where EV < 0. Detect by simulating keeper EV across all liquidatable positions; track the share with negative EV.
  • Bonus front-running: keepers bid gas up until the bonus is captured by builders. Detect by tracking gas paid as a fraction of bonus seized; if it approaches 1, the bonus is too low relative to congestion.
  • Cascades: liquidation volume vs DEX depth. Detect by monitoring seized collateral as a percentage of pool depth per block.
  • Stale oracle: liquidation triggered on a price that no longer holds. Detect with oracle heartbeat and deviation checks against a second source.
  • Parameter cliff: HF 0.949 vs 0.951 flips close factor 50% → 100%. Detect by looking at the distribution of close sizes; a spike at the threshold means borrowers get surprised.

When the calibration is wrong

If keepers consistently leave liquidatable positions untouched, B is too low or C too small. If borrowers are wiped out on a 1% dip, B is too high or C too large. If liquidations cluster and push unrelated positions under HF 1, C is too large for that collateral's depth.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Design a Dutch auction liquidation mechanism for an undercollateralized lending position. Walk me through the price curve, the parameters you'd pick, and how it fails.

Answer

Clarify and assume. The auction sells a fixed lot of collateral to repay a fixed tab of debt. Price is anchored to an oracle and decays over time. I'd run it per collateral with the oracle being a TWAP, not spot. This is the family MakerDAO's Clipper popularised; the parameters below are mine, not a copy of theirs.

Mechanism. At liquidation, seize lot collateral and freeze tab debt. Price per collateral unit:

p(t) = (tab/lot) * m(t)
m(t) = max(floor, buf - (buf - floor) * t / tail)

A keeper sends amt of the debt asset and receives min(lot_remaining, amt / p(t)) collateral. A take reduces lot and tab proportionally, so tab/lot is invariant across takes and the curve does not move under the keeper's feet. When tab hits zero the auction closes and leftover collateral returns to the borrower. When the remaining lot falls below resetFrac * lot_0, the auction restarts with a fresh clock at top = buf * tab/lot on current values, so the tail is not dumped at the floor price. If the lot is exhausted with tab remaining, the remainder is bad debt against the reserve.

Why decay instead of a fixed bonus. A fixed bonus is one number that has to be right for every collateral and every market. Too low and nobody bids the illiquid tail; too high and keepers extract rent from every borrower. The decay makes the bonus a function of how long the position has been open, which is the cost the protocol is actually paying.

paramvaluecontrolsfailure if wrong
buf1.05starting multiplier over tab/lottoo high: no early bids, takes cluster at the floor
tail1800 stime to reach the floortoo long: interest accrues, price drifts, bad debt
floor0.85terminal multiplier, i.e. max discounttoo low: protocol gives away value; too high: illiquid collateral never clears
resetFrac0.20remaining-lot fraction that triggers a restarttoo high: restarts churn; too low: tail sells at the floor
min lot>= 20x gas costkeeper profitability floorsmall lots never get bid

Worked trace. 10 ETH lot, 12,000 DAI tab, oracle $1,300/ETH, so tab/lot = 1,200. buf 1.05 gives p(0) = 1,260; floor 0.85 gives p(1800) = 1,020. Slope = 240/1800 = 0.1333 DAI per ETH per second.

t (s)p(t)discount vs oracleETH for 6,000 DAIoracle valuegross profit
01,260.003.1%4.7626,190190
6001,180.009.2%5.0856,610610
12001,100.0015.4%5.4557,0911,091
18001,020.0021.5%5.8827,6471,647

A take plus a swap is roughly 250k gas; at 20 gwei and $3,300/ETH that is 0.005 ETH, about $16.50. A keeper taking D = 6,000 DAI at oracle O = 1,300 with sale slippage s and gas G = 16.50 needs p <= DO(1-s)/(D+G) = 1,296.4*(1-s):

slippage smax pricebreak-even t
01,2960 s: start price 1,260 already clears
5%1,232~213 s
10%1,167~699 s
15%1,102~1,186 s
20%1,037~1,672 s
25%972never: below the 1,020 floor

A liquid collateral clears in the first block; a long-tail token with 20% sale slippage waits ~28 minutes, and at 25% the auction never clears at all. That last row is what you tune floor against.

Failure modes and how I would see them.

  • No bids at all: illiquid or blacklisted collateral, or an oracle above the real market. Detect with p95 time-to-first-bid, restart count, bad debt per auction.
  • Oracle manipulation at auction start: p(t) is anchored to the oracle, so pushing the feed up raises the start price and suppresses bids; the attacker buys at the floor after the feed reverts. Compare the auction oracle against a secondary source at start, and use a TWAP rather than spot.
  • Floor clustering: if more than 80% of takes land in the last 10% of the window, buf is too high and the protocol pays the maximum discount on every liquidation.
  • Restart griefing: anyone can restart an expired auction, so a griefer resets the clock repeatedly. Cap restarts per position and alert on the count.
  • Reentrancy on take: the collateral token may have hooks. Take payment first, use a pull pattern, make no arbitrary calls.

When not to use it. Deep, liquid collateral with many keepers. A fixed bonus clears in one block there, and the auction only adds latency and interest accrual. Dutch auctions earn their complexity on the long tail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Set collateral risk parameters for a new asset.

Answer

First I'd clarify: is this a new collateral on an existing pool, or a new isolated market? What's the asset's liquidity, volatility, and oracle? I'll assume a mid-cap volatile token: $50M daily DEX volume, 90% annualized realized vol, Chainlink oracle with 1-hour heartbeat and 0.5% deviation threshold, on an Aave v3-style pool. My recommendation: LTV 55%, liquidation threshold 65%, liquidation bonus 10%, supply cap $20M, borrow cap $10M, isolation mode debt ceiling $5M, reserve factor 20%, liquidation protocol fee 10%.

The mechanism: LTV caps new borrowing. Liquidation threshold is the health-factor line where liquidators can repay debt and seize collateral. The gap between them, 10 points here, is the buffer that absorbs price drop before liquidation. With LTV 55% and LT 65%, a borrower at max LTV gets liquidated after a drop of 1 - 0.55/0.65 = 15.4%. That's the arithmetic: debt = 0.55P, collateral value = P', liquidation when 0.55P > 0.65P', so P' < 0.846P. The bonus exists because liquidators take inventory risk, pay gas, and cross slippage. If the bonus is too low, nobody liquidates and bad debt accrues. Caps limit protocol exposure per asset and per market. Isolation mode prevents a new asset from being used to borrow other assets, containing contagion.

ParameterValueWhy
LTV55%Capital efficiency vs buffer; 90% vol asset
Liquidation threshold65%10-point buffer; liquidation after ~15% drop
Liquidation bonus10%Covers gas, slippage, inventory risk
Supply cap$20M40% of daily volume; limits exit liquidity risk
Borrow cap$10MHalf of supply cap; limits debt concentration
Isolation debt ceiling$5MCaps total borrows against this asset
Reserve factor20%Protocol revenue vs borrower cost
Liquidation protocol fee10%Protocol share of bonus

On Compound v3 the same knobs are collateral factor, liquidation factor, and liquidation discount; on MakerDAO it's liquidation ratio and penalty. The logic is identical.

Tradeoffs: A higher LTV, say 75%, is justified for a stablecoin with deep liquidity, a robust oracle, and low vol. It increases capital efficiency but shrinks the buffer to 5 points, so a 6% depeg triggers liquidations. A lower LTV, say 40%, is for a long-tail asset with thin liquidity or a manipulable oracle. The cost is capital inefficiency; borrowers leave for better terms. I'd start conservative and raise after observing live liquidations.

Failure modes and detection: Oracle lag during gap moves. Monitor oracle price vs CEX mid, alert if deviation > 1% for > 5 minutes. Thin exit liquidity: track DEX depth at 2% slippage; if it drops below $5M, lower caps. Correlated collateral and debt, if the asset is a LST and debt is ETH, a staking crisis hits both; monitor correlation of returns. Governance delay: parameter changes take days; keep a manual pause guardian. Bridge risk, if the asset is bridged, monitor bridge TVL and withdrawal delays. False historical stability: backtest includes only calm periods; stress test with 2018/2022 drawdowns. Operational cost: a $10k liquidation with 10% bonus yields $1k; 3% slippage costs $300, gas $5, net $695. If net < $100, liquidators stop.

I'd stage: launch with caps at 25% of target, monitor for two weeks. Raise caps if liquidation profitability > 5% and oracle deviation < 0.5%. Lower LTV if health factor distribution shows > 20% of debt within 5 points of liquidation.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Assess a stablecoin used as protocol collateral.

Answer

First 60 seconds. This is a credit and liquidity question, not a price question: if the protocol has to liquidate this collateral in a stress event, can it get par, and who can stop it? I'd score four axes: redemption certainty, reserve quality, control/censorship, and oracle plus exit liquidity, then set the haircut and cap from the worst axis. A coin that redeems T+0 at par into cash and ≤90-day T-bills at a regulated custodian, with monthly attestations and disclosed freeze powers, gets a 2–5% haircut and a 20% cap. One backed by loans, perps, or other stablecoins gets 20–50%, or zero.

Par is a legal claim on the issuer, not a property of the token. If the issuer can freeze, the protocol's collateral can be frozen. If the reserve is short-dated government debt, a run is a liquidity event; if it is long-dated or reflexive, a run is a solvency event. Market price only tells you what arbitrageurs will pay right now: it does not tell you what the issuer will redeem. USDC: cash and short-dated T-bills, monthly attestations, freezeable, deep liquidity. DAI: overcollateralized crypto plus RWA, governance-controlled, reflexive if ETH drops. USDe: delta-neutral basis trade, funding-rate and exchange-custody risk. The deciding criteria are: can you redeem at par same day, and who can veto?

Scoring the axes.

AxisWhat I checkPassFail → action
RedemptionT+0 par ≤$1M, T+1 above, regulated custodianpar, same daygated or discretionary → 20–50% haircut
Reservesshare in cash + ≤90d T-bills≥80%loans, perps, other stables → 20–50% or zero
Controlfreeze/pause powers disclosed; protocol can exitdisclosedundisclosed freeze → zero
Oracle + exitTWAP length vs 2% book depth30-min TWAP, depth ≥ position1-hour TWAP, thin book → cap the position

Worked trace: Stablecoin X (hypothetical). Reserves 60% T-bills, 25% USDC, 15% secured loans; quarterly attestations; issuer can freeze; T+0 redemption under $1M, T+1 above; 90% of supply on one chain; top-10 holders 40%. Worst axis is reserves (40% non-cash) plus gated redemption above $1M, so: haircut 80%, cap 5% of protocol collateral.

Position: $5M notional of X.

  • Effective collateral = $5M × (1 − 0.80) = $1.00M
  • Max borrow at 70% LTV = $1.00M × 0.70 = $700k
  • Liquidation triggers when $5M × P × 0.20 = $700k → P = $0.70, a 30% depeg
  • At liquidation the protocol sells $5M notional. The deepest venue holds $800k within 2% of mid: 6× too thin. Assume the sale realizes an average of $0.55 (hypothetical): proceeds $2.75M.
HaircutMax borrow (70% LTV)Liquidation proceedsBad debt
5% (treat as USDC)$3.325M$2.75M$575k
80%$700k$2.75M$0

The trigger price is $0.70 either way: the haircut does not move the trigger, it caps the debt sitting behind it. That is the whole point of the haircut.

Failure modes and detection. Depeg: DEX mid below $0.995 for more than 10 minutes while redemption is open. Run: redemption queue exceeds 5% of supply in 24 hours (on $2B supply, $100M). Maturity mismatch: weighted average maturity above 90 days against daily redemption. Frozen reserves: issuer blacklists an address or pauses mint/redeem. Reflexive collateral: a drop in X's own price triggers liquidations that sell X. Bridge representation: wrapped X trades at a discount because the bridge is paused. Oracle lag: protocol oracle on a 1-hour TWAP while the market moves 5% in 5 minutes. Governance capture: a single multisig can upgrade minting. Thin exit: 2% depth under $1M on the primary DEX.

In production I'd monitor attestation age, redemption queue, DEX depth, oracle deviation, and governance timelock, and set the haircut and cap from those inputs. Hard triggers to zero: attestation older than 60 days, redemption gated, or more than 20% of reserves in other stablecoins. When one fires, pause new collateral and liquidate into the deepest venue.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Choose a TWAP window for collateral pricing.

Answer

Core answer (first 90 seconds)

Clarify three things before naming a window: what the collateral is, how deep the pool is, and whether liquidation is atomic or delayed. Those decide it.

My default: 30 minutes for a major-pair collateral (ETH/USDC, WBTC/USDC) on a pool with at least $50M of in-range liquidity and liquidation that can execute within one block. Move to 1 hour if the pool is thinner than 10× the protocol's largest single position, or if the asset is volatile and LTV is above 65%. Drop to 10 minutes only for stablecoin/stablecoin pairs with $200M+ depth and a delayed liquidation auction. Never go below 10 minutes for anything that backs debt.

Why 30 minutes, mechanically

Uniswap V3's oracle stores cumulative tick values in a ring buffer. observe([1800, 0]) returns two cumulative ticks; the TWAP tick is (cum[1] - cum[0]) / 1800, and price is 1.0001^tick. Because the average is taken on ticks, the result is the geometric mean of the instantaneous prices over the window, not the arithmetic mean.

The buffer holds at most one observation per block. On Ethereum mainnet at ~12s blocks, a 30-minute window needs at least 1800/12 = 150 slots; set observationCardinalityNext to ~225 for headroom against missed blocks and sparse swaps. The pool default is observationCardinality = 1, and with cardinality 1 any observe call with secondsAgo > 0 reverts with OLD. Growing the buffer is two-step: increaseObservationCardinalityNext sets the target, and the next swap writes the new slots. So the window you pick is a hard constraint on the cardinality you must pay to initialize.

SOLIDITY
// Uniswap V3, @uniswap/v3-core 1.0.0
uint32 constant WINDOW = 1800; // 30 minutes

function twapTick(address pool) internal view returns (int24) {
    uint32[] memory ago = new uint32[](2);
    ago[0] = WINDOW;
    ago[1] = 0;
    (int56[] memory cum, ) = IUniswapV3Pool(pool).observe(ago);
    int56 delta = cum[1] - cum[0];
    return int24(delta / int56(uint56(WINDOW)));
}

Why the window buys security

To move a W-second TWAP by Δ, an attacker who holds spot displaced by Δ for the full window gets a Δ TWAP move; holding for half the window needs 2Δ spot displacement. So the attacker trades slippage cost against arbitrage bleed. For a fixed target TWAP displacement, total cost grows roughly linearly with W: the arbitrage bleed scales with holding time, and the required spot displacement falls only as 1/d. Doubling 15 → 30 minutes roughly doubles attack cost on a pool of fixed depth.

When a shorter window wins

If liquidation is not atomic (a 24-hour auction, a keeper with a delay) the attacker cannot realise the profit before the position is closed, so 10 minutes is enough. Same if LTV is 50% and the pool is 100× the largest position. The window is insurance against atomic extraction; with no atomic extraction you are paying cardinality gas for nothing.

Failure modes and how you catch them

failuredetectioncost
cardinality < window/12fork-test observe at the exact window; alert on observationCardinalityOLD revert, liquidations blocked
stale TWAP in a crashmonitor |TWAP − spot|/spot; halt borrows above 5% for 10 minbad debt accrues while spot and TWAP diverge
prolonged manipulationcompare against a second venue; watch pool TVL vs exposurebounded by window × depth, but a funded attacker can hold 30 min
thin poolpool TVL / largest position < 10window is irrelevant; attacker just buys the pool
token0/token1 flippedunit test the TWAP against a pinned reference pricecollateral valued at 1/3000 instead of 3000
correlated marketscheck whether one pool prices both assetsoracle risk is not diversified

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Build an oracle adapter with explicit failure behavior.

Answer

What I'd say first

Assume an EVM L2 (Arbitrum), one collateral market, Chainlink push feeds, Solidity 0.8.20. The adapter is a stateless read path: it pins the feed address, expected decimals and expected description at construction, validates every round on read, and reverts on anything invalid instead of returning a number. The consumer, not the adapter, decides whether a revert means pause or fallback. That split is the whole design: the adapter's job is to never hand out a number it can't defend.

The mechanism

Chainlink's latestRoundData() returns (roundId, answer, startedAt, updatedAt, answeredInRound). Four things can be wrong with a decodable answer: the round is incomplete (answeredInRound < roundId), it's stale (block.timestamp - updatedAt exceeds the feed's heartbeat), it's non-positive, or it's outside sane bounds. ETH/USD on Ethereum mainnet publishes on a 0.5% deviation threshold with a 1-hour heartbeat, so maxStaleness of 3600s is the right default there; on an L2 you set it from the feed's own heartbeat, not from a guess.

SOLIDITY
pragma solidity 0.8.20;

interface AggregatorV3Interface {
    function decimals() external view returns (uint8);
    function latestRoundData() external view returns (uint80, int256, uint256, uint256, uint80);
}

contract PriceAdapter {
    AggregatorV3Interface public immutable feed;
    uint8 public immutable feedDecimals;
    uint256 public immutable maxStaleness;
    int256 public immutable minAnswer;
    int256 public immutable maxAnswer;

    error Stale(uint256 updatedAt, uint256 nowTs);
    error IncompleteRound(uint80 roundId, uint80 answeredInRound);
    error OutOfBounds(int256 answer);
    error NonPositive(int256 answer);

    constructor(address f, uint256 staleness, int256 lo, int256 hi) {
        feed = AggregatorV3Interface(f);
        feedDecimals = AggregatorV3Interface(f).decimals();
        maxStaleness = staleness;
        minAnswer = lo;
        maxAnswer = hi;
    }

    function read() public view returns (int256 price, uint8 decimals) {
        (uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) =
            feed.latestRoundData();
        if (answeredInRound < roundId) revert IncompleteRound(roundId, answeredInRound);
        if (updatedAt == 0 || block.timestamp - updatedAt > maxStaleness)
            revert Stale(updatedAt, block.timestamp);
        if (answer <= 0) revert NonPositive(answer);
        if (answer < minAnswer || answer > maxAnswer) revert OutOfBounds(answer);
        return (answer, feedDecimals);
    }
}

Trace

ETH/USD, maxStaleness = 3600. block.timestamp = 1_700_000_000, updatedAt = 1_699_996_000. Age = 4000 > 3600 → revert Stale(1699996000, 1700000000). Now roundId = 101, answeredInRound = 100 → revert IncompleteRound(101, 100). A healthy round: answer = 2_000_00000000 (8 decimals) = $2000; scaling to 18 decimals is answer * 1e10.

Trade-offs

Revert vs return-last-good vs pause. Revert is honest but a permanently stale feed halts the market: that's a governance problem, not a code one, so you need a timelocked feed-swap path. Return-last-good hides staleness and is how people get liquidated on a price that no longer exists. Pause is the middle: bounded, reversible, but it needs an explicit unpause owner. Deviation checks against a second feed are worth it only when the two feeds are genuinely independent; two feeds from the same provider are correlated and the check buys nothing.

Failure modes and detection

  • Staleness: age > heartbeat; expose age() in a health view and alert on it.
  • Wrong feed or orientation: pin the description hash at construction; min/max bounds catch an inverted pair.
  • Decimals: pin at construction; re-check feed.decimals() on read if the feed is upgradeable.
  • Sequencer outage (L2): read the Chainlink L2 Sequencer Uptime Feed and require a grace period after it reports back up. Chainlink's own example uses one hour.
  • Correlated sources: compare against a second independent feed, not a sibling.
  • Fallback manipulation: bound and rate-limit any fallback.
  • Governance change: timelock feed swaps.
  • Permanent DoS: the revert path itself; mitigate with the timelocked swap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Plan for lending-market insolvency.

Answer

Core answer (first 90 seconds)

Assume an overcollateralized pooled market, Aave v3 or Compound v3 style, where suppliers hold a claim on the pool and borrowers post volatile collateral. Insolvency means realizable assets fall below supplier claims. The plan runs in four phases, in this order: detect, contain, allocate, recover. You cannot skip to allocate; by the time you are allocating, the size of the loss is already fixed.

Detect: watch the health-factor distribution, not the average. The number that matters is what fraction of debt sits within 10% of HF 1.0, plus the DEX depth of each collateral. If 20% of debt is liquidatable and the collateral's deepest pool holds $2M, you have a problem before any price move.

Contain: freeze the reserve (Aave's Frozen state blocks deposits and borrows but still allows repay and liquidate), push the close factor to 100%, raise the liquidation penalty. Speed beats fairness here.

Allocate: the waterfall is borrower collateral → protocol treasury → backstop module → suppliers pro-rata → governance token dilution.

Recover: bad-debt auction or recapitalization, then wind down.

How a shortfall reaches depositors

Worked example, labelled assumptions: 13M USDC supplied. Borrower posts 10,000 ETH at $2,000 = $20M, liquidation threshold 82.5% (Aave v3's WETH setting), borrows 13M USDC. HF = 16.5/13 = 1.27.

ETH falls to $1,500: weighted collateral 12.375M, HF 0.95. Liquidatable, and under 0.95 the close factor is 100%. ETH then gaps to $1,000 before a keeper lands: collateral $10M, HF 0.63. With a 5% liquidation penalty, a liquidator repays at most 10M/1.05 = 9.52M and takes all 10M of ETH. Debt left: 3.48M, collateral zero. The pool now holds 9.52M against 13M of supplier claims: a 26.7% haircut, socialized pro-rata.

Note what set the loss: the gap between oracle price and the price a liquidator could actually realize, not the liquidation threshold. The threshold only decided when liquidation started.

Trade-offs

Backstop versus socialize. Aave's Safety Module is stkAAVE with a 30-day cooldown and up to 30% slashing: fine for a bounded loss while AAVE is liquid and uncorrelated. It is the wrong tool when the failure is reflexive: if the crash that caused the bad debt also craters AAVE, you are selling the backstop into the same hole. MakerDAO on 12 March 2020 is the canonical case: ETH fell about 43% in a day, 1,462 auctions cleared with zero bids, roughly $8M of bad debt, and MKR had to be minted through debt auctions. Socialized loss is right for small, bounded shortfalls and wrong once it exceeds a few percent of deposits, because that is where suppliers run, and the run is what converts a shortfall into insolvency.

Failure modes and detection

  • Oracle error: compare the primary oracle against a fallback and a DEX TWAP; alert on divergence above 2% sustained.
  • Keeper failure: track time since last successful liquidation per reserve. Black Thursday was a gas spike, not a price problem.
  • Inaccessible collateral: collateral on an L2 cannot be seized on L1; watch bridge withdrawal queue depth and finality lag.
  • Governance delay: timelocks run 1–2 days (Compound's Governor Bravo is 2). If time-to-insolvency is shorter than time-to-parameter-change, your controls do not exist. Measure both.
  • Concealed deficit: reconcile totalBorrows against actually repayable debt; flag any position with HF < 1 that no liquidator has touched in 24 hours.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Secure a tokenized vault's initial deposits.

Answer

Core answer. A vault's share price is undefined until the first deposit sets it. In ERC-4626, convertToShares(assets) = assets * totalSupply / totalAssets. On an empty vault both are zero, so whoever deposits first defines the price, and an attacker can move that price before a victim arrives. The fix is to make the empty-vault conversion non-degenerate: OpenZeppelin's _decimalsOffset() adds virtual shares plus one virtual asset, or you mint dead shares to address(0) on the first deposit. Then enforce a minSharesOut on every deposit so a victim reverts instead of silently receiving zero shares.

Why the attack works. The attacker never calls deposit for the inflation step: they transfer tokens straight to the vault, which raises totalAssets without minting shares:

  1. Attacker deposits 1 wei → 1 share. totalSupply = 1, totalAssets = 1.
  2. Attacker transfers 1e18 tokens directly to the vault (a donation, no Deposit event). totalAssets = 1e18 + 1, totalSupply = 1.
  3. Victim calls deposit(1e18 - 1). Shares = floor((1e18 - 1) * 1 / (1e18 + 1)) = 0. The victim receives nothing.
  4. Attacker redeems 1 share → 2e18. Spent 1e18 + 1, gained 2e18.

The donation is the whole trick: it inflates the denominator so the victim's deposit rounds to zero, and those assets are absorbed into the attacker's single share.

Mitigation. OpenZeppelin's virtual offset:

SOLIDITY
// OpenZeppelin ERC4626, Solidity ^0.8.20
function _convertToShares(uint256 assets, Math.Rounding rounding)
    internal view override returns (uint256)
{
    return assets.mulDiv(
        totalSupply() + 10 ** _decimalsOffset(),
        totalAssets() + 1,
        rounding
    );
}

With _decimalsOffset() = 3, the vault starts with 1000 virtual shares and 1 virtual asset. To force a victim's deposit to zero shares the attacker must now donate roughly 1000x the victim's deposit instead of 1x. Each +1 on the offset multiplies the attacker's cost by 10.

Trade-offs.

mitigationcostwhen to use
virtual shares (_decimalsOffset)share price scaled by 10**offset; small deposits round to 0 shares soonerdefault choice, locks no value
dead shares (mint MINIMUM_LIQUIDITY to address(0))permanently locks that asset amountwhen you want an explicit bootstrap and no offset math
minSharesOut onlyreverts the victim, does not stop the attackalways, as a second layer

Failure modes and detection.

  • Zero-share deposit: previewDeposit(x) returns 0 for x > 0. Assert in a unit test; revert via minSharesOut.
  • Donation: totalAssets() rises with no Deposit event. Alert on that delta.
  • Fee-on-transfer or rebase token: the vault credits assets but its balance delta is smaller or drifts. Assert token.balanceOf(vault) delta equals assets after deposit.
  • Rounding extraction: repeated deposit/withdraw cycles drain dust. Fuzz test asserting vault balance never decreases.
  • Stale preview: previewDeposit is a view, not a promise. Always pass minSharesOut.
  • Withdrawal illiquidity: redeem reverts when strategy funds are locked. Check maxWithdraw before promising liquidity.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Implement an ERC-3156-compatible flash lender.

Answer

Core answer. Assume the lender already holds the token it lends and the token is a plain ERC-20 (no rebasing, no fee-on-transfer). ERC-3156 fixes three functions on the lender (maxFlashLoan, flashFee, flashLoan) and one on the borrower, onFlashLoan, which must return the magic value keccak256("ERC3156FlashBorrower.onFlashLoan") (0x23e30c8b). The flow is: check the token is supported and the amount is available, transfer amount to the receiver, call onFlashLoan with msg.sender as initiator, require the magic value back, then pull amount + fee from the receiver with transferFrom. If any step fails the whole transaction reverts, so the loan is atomic by construction. The spec leaves the fee formula to the lender; the common convention is basis points, e.g. 9 bps = 0.09% (Aave V2's rate).

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

interface IERC20 {
    function transfer(address to, uint256 amount) external returns (bool);
    function transferFrom(address from, address to, uint256 amount) external returns (bool);
    function balanceOf(address account) external view returns (uint256);
}

interface IERC3156FlashBorrower {
    function onFlashLoan(address initiator, address token, uint256 amount,
        uint256 fee, bytes calldata data) external returns (bytes32);
}

contract FlashLender {
    bytes32 private constant CALLBACK_SUCCESS =
        keccak256("ERC3156FlashBorrower.onFlashLoan"); // 0x23e30c8b
    uint256 private constant BPS = 10_000;
    uint256 public feeBps = 9; // 0.09%
    mapping(address => bool) public supported;
    uint256 private locked = 1;

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

    function maxFlashLoan(address token) external view returns (uint256) {
        return supported[token] ? IERC20(token).balanceOf(address(this)) : 0;
    }

    function flashFee(address token, uint256 amount) public view returns (uint256) {
        require(supported[token], "unsupported");
        return (amount * feeBps) / BPS;
    }

    function flashLoan(IERC3156FlashBorrower receiver, address token,
        uint256 amount, bytes calldata data) external nonReentrant returns (bool) {
        require(supported[token], "unsupported");
        uint256 fee = flashFee(token, amount);
        uint256 before = IERC20(token).balanceOf(address(this));
        require(amount <= before, "insufficient liquidity");

        require(IERC20(token).transfer(address(receiver), amount), "transfer failed");
        require(receiver.onFlashLoan(msg.sender, token, amount, fee, data)
            == CALLBACK_SUCCESS, "callback rejected");
        require(IERC20(token).transferFrom(address(receiver), address(this),
            amount + fee), "repay failed");
        require(IERC20(token).balanceOf(address(this)) >= before + fee, "balance short");
        return true;
    }
}

Trace. Token balance 5,000,000; amount 1,000,000; feeBps 9.

steplender balancereceiver balance
before captured5,000,0000
transfer to receiver4,000,0001,000,000
onFlashLoan runs, receiver approves 1,000,9004,000,0001,000,000
transferFrom pulls 1,000,9005,000,9000
check 5,000,900 >= 5,000,000 + 900pass—

Fee is 900 units = 0.09% of 1,000,000.

Trade-offs. ERC-3156 mandates pull repayment: the receiver must approve the lender for amount + fee before the callback returns. Balancer V2 uses push, the borrower sends funds back to the Vault itself and the Vault verifies, which avoids the approval but puts the amount check on the borrower. Pull is safer because the lender controls the exact figure and timing. A wrapper that bundles several loans or auto-repays from a router adds convenience but hides the approval step; keep the raw flashLoan as the primitive. Don't build one if you can't guarantee atomic repayment, if the token rebases (your before + fee check breaks), or if exposing flash liquidity to your own oracle creates a manipulation surface.

Failure modes.

failuremechanismdetection
wrong callback selectorreceiver returns a different bytes32require(... == CALLBACK_SUCCESS) reverts
initiator confusionattacker calls flashLoan with receiver = victim; victim's hook runs with attacker datareceiver must check initiator == msg.sender or a whitelist
malicious tokentoken re-enters or returns true without moving fundsnonReentrant + final balance check
approval failurereceiver never approved amount + feetransferFrom reverts
fee rounding(amount * feeBps) / BPS truncates; amount 100 at 9 bps gives fee 0round up: (amount * feeBps + BPS - 1) / BPS
reentrancyreceiver re-enters flashLoan mid-callbacknonReentrant guard
liquidity over-promisemaxFlashLoan returns full balance you also need elsewherereserve a floor
receiver trusts any lenderreceiver's hook runs for an unknown callerreceiver checks msg.sender is a known lender

What would change the design: a fee-on-transfer or rebasing token forces you to measure deltas rather than trust amount, and a multi-token lender needs per-token liquidity accounting instead of a single balance read.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Make a protocol invariant robust to atomic capital.

Answer

Core answer. Assume "atomic capital" means capital borrowed and repaid inside one transaction: a flash loan, or the attacker's own funds used the same way. The attacker's balance sheet stops constraining them, so the invariant you must defend is not "collateral ≥ debt for honest users over time" but "collateral ≥ debt for every state reachable before the transaction ends." Two things break that. First, reading a live balance (token.balanceOf(market), pair.getReserves()) as if it were accounting state. Second, reading a price from a market the attacker can trade against in the same transaction. Fix both: keep accounting in storage the attacker cannot move by transferring tokens, and price from a source whose cost to move exceeds the profit.

Why it breaks. A lending market with collateralValue = balanceOf(market) * spotPrice and a 75% LTV, priced off a Uniswap v2 pair. Illustrative round numbers:

  1. Pool holds 1,000,000 USDC / 500 WETH → spot 2,000 USDC/WETH.
  2. Flash-loan 2,000,000 USDC (Aave v3 charges 5 bps → 1,000 USDC).
  3. Swap 1,500,000 USDC in → ~300 WETH out; reserves become ~2,500,000 / 200 → spot ~12,500 USDC/WETH, 6.2×.
  4. Deposit 100 WETH as collateral → valued at 1,250,000; borrow 75% = 937,500 USDC.
  5. Swap the 300 WETH back → ~1,490,000 USDC.
  6. Repay 2,001,000. Net ≈ 926,500 USDC; the market holds 100 WETH (~200,000 at the true price) against 937,500 debt → ~737,500 bad debt.

The invariant held at every step. The price was the lie.

Mitigations, and when each is wrong.

MitigationDeciding criterionWrong when
Internal accounting instead of balanceOfinvariant must not reflect unsolicited transfersrebasing or fee-on-transfer tokens, or rewards airdropped to the contract, where balanceOf is the only truth
Uniswap v3 TWAP, 30 min via observe()cost to move the pool across the window > extractable profitasset is thin, window is shorter than the manipulation, or you need sub-minute freshness
Chainlink push feed via latestRoundData()a liquid market with a published feed existsno feed; heartbeat (1 h on many mainnet feeds) is too stale; the feed's own market is thin
Per-block caps / rate limitsbound loss per block below attack costcap sits above extractable value, or the attacker splits across blocks
Timelock / governance delaythe legitimate action is not atomicliquidations and arbitrage must settle atomically
SOLIDITY
// vulnerable: live balance is attacker-movable
return token.balanceOf(address(this)) * oracle.price();
// robust: storage the attacker cannot move by transferring
return accountedDeposits[msg.sender] * oracle.price();

Failure modes and detection. Spot-price manipulation: compare the protocol's price to a Chainlink/TWAP reference each block, alert on >5% divergence. Donation inflation: a Foundry invariant asserting token.balanceOf(market) == internalCash after every handler call. Same-block governance: require block.number >= snapshotBlock + delay in the execution path. Bad debt from liquidation loops: track totalBorrows against collateral valued at the conservative price, alert when the ratio exceeds 1.

Testing. A Foundry stateful invariant test whose handler can flash-loan, donate, and swap within one call, run 10k+ times. If the handler cannot compose those three, the test cannot see the attack.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Map transitive risk for a yield strategy.

Answer

What I'd say first

Transitive risk is exposure that reaches your position through a dependency you never signed up for. You hold vault shares; the vault holds a lending-market position; the market prices collateral with an oracle; liquidations route through an AMM; the shares are bridged. One position, five failure domains. The mapping job is to find the shortest path from any single failure to your NAV, then decide whether you can cut it.

Assumptions I'd state up front: a USDC-denominated vault, single-chain custody with a lock-and-mint bridge for a wrapped share on a second chain, and I control none of the underlying protocols' admin keys.

Worked chain (hypothetical numbers, real shape)

Vault TVL $50M. $20M sits in lending market M. M's collateral book is 40% stETH ($8M) and 60% USDC, 80% max LTV, priced by a Chainlink stETH/ETH feed.

Hop 1: stETH trades 8% below ETH on the secondary market. The feed is a TWAP, so it lags; the position's health factor falls from 1.15 to 0.98 and becomes liquidatable.

Hop 2: the liquidator swaps $8M of stETH through the Curve stETH/ETH pool, which has $12M of depth. Assume the sale clears at 92 cents on the dollar: the position closes, but roughly $640k of debt is unrecoverable and socialized across the market.

Hop 3: M pauses withdrawals while it absorbs the shortfall. The vault can't redeem, so the bridged share on chain B, worth only redemption, trades at a discount, and the bridge's locked TVL no longer matches minted supply.

Three hops, one trigger. Draw that before writing any cap.

Trade-offs

Three credible responses, and they fail differently.

Per-hop exposure caps (no more than 20% of TVL in one lending market, 10% in one bridge) are cheap and legible. They're blunt: they cap the wrong thing when two dependencies fail together, which is exactly the correlated case.

Full dependency inventory with per-edge limits is precise but slow to maintain and blind to dependencies you didn't know existed: the oracle upgrade nobody announced.

Circuit breakers that unwind on a signal (oracle deviation above 2% against a secondary feed, pool 2% depth below $5M) are fast but fire on noise, and can themselves trap you when the unwind venue is the venue that's broken.

Deciding criteria: can I exit in one block without touching the failing venue? Is this dependency correlated with my others? Do I hold the pause key? If the first answer is no and the third is no, reject the strategy: that's the case where you're a passenger.

Failure modes and what you watch

  • Oracle lag or manipulation: detect as divergence between the primary feed and a secondary source past your threshold; cost is mispriced liquidations.
  • Liquidity evaporation: detect as 2% depth on the exit pool; cost is slippage that turns a liquidation into bad debt.
  • Bridge halt: detect as minted supply diverging from locked TVL, or a growing withdrawal queue; cost is a share that can't be redeemed.
  • Admin pause or upgrade: detect as a timelock or proxy-admin event; cost is exit blocked exactly when you need it.
  • Recursive collateral: detect as a token used as collateral in a market that also prices it; cost is a circular mark.

Ordering: pause deposits first, unwind the liquid leg, then the illiquid leg, and never pause withdrawals before the unwind is done. That converts a market problem into a run.

Curated: · Written: · Reviewed:

Difficulty: Hard