- Home
- Prep by Job Role
- Blockchain Developer
- Top 100 Q&A
Top 100 Blockchain Developer Interview Questions and Answers
The questions most likely to come up in your Blockchain Developer interview, ranked by likelihood, with senior-level answers that cover what the interviewer is listening for.
Curated: · Written: · Reviewed:
Q&A-8Someone says "wait one block." On Ethereum PoS, what times are you actually talking about, and which clock does finality use?
When someone says "wait one block" on Ethereum PoS, the defensible reading is "wait for the next proposal opportunity", and that is 12 seconds. Slots run on a fixed 12-second grid and a block is an optional occupant of a slot, so if the next slot is skipped you wait 12 more seconds for the one after it. "One block" is 12 s times the number of slots until a block appears, not a fixed duration.
Finality does not run on that clock. It runs on the epoch clock: 32 slots, 6.4 minutes, with Casper FFG checkpoints taken at epoch boundaries. A block is finalized only when the epoch that contains it is finalized, and finalization advances one epoch at a time. The finalized checkpoint trails the head by 2 epochs normally, 3 when a checkpoint has to be re-justified. In wall-clock that is about 12.8 minutes from inclusion, or up to 19.2 minutes in the slow case. Adding blocks does not shorten any of it.
The clocks, and what each is the right measure for
| Clock | Unit | Read it from | Right for |
|---|---|---|---|
| Slot | 12 s | beacon head slot (/eth/v1/beacon/headers/head), or execution block timestamp = genesis_time + 12 * slot | reorg budgets, retry timing, "did my tx land". Not settlement: a 1-slot reorg is routine |
| Justified checkpoint | 1 epoch = 6.4 min | current_justified / previous_justified in /eth/v1/beacon/states/head/finality_checkpoints, or the execution safe block tag | an answer faster than finality with bounded residual risk: balances shown to users, internal accounting, a path you can roll back. Still replaceable |
| Finalized checkpoint | one finalization event per epoch | finalized from the same endpoint, or the execution finalized block tag | anything irreversible: exchange credit, bridge release, liquidation. Cost is the ~13 min latency |
| Wall clock / block count | seconds or blocks | local clock, eth_getBlockByNumber height | timeouts, SLAs, alerting. Never a safety boundary |
Arithmetic
1 slot = 12 s. 1 epoch = 32 slots = 384 s = 6.4 min. Normal finality = 2 epochs from inclusion = 64 slots = 768 s = 12.8 min. Checkpoint re-justified = 3 epochs = 96 slots = 1152 s = 19.2 min.
Where counting blocks breaks
A deposit service waits 32 blocks. On a clean stretch that is 32 slots, 384 s. If 8 of those slots were empty, the same 32 blocks span 40 slots, 480 s, which is 96 s more, and the counter shows no difference. Nothing bounds that error, because missed slots are unbounded over a long window. A finalized-checkpoint check has no block count in it at all, so the same 8 misses change nothing. The mirror-image mistake: treating "32 blocks" as "6.4 minutes of safety" makes a variable look like a constant.
Picking one
Settle irreversible value on the finalized checkpoint and only on it. Use the justified checkpoint when you need an answer in about 6.4 minutes and can carry a revert path. Use the slot clock for everything about inclusion and reorgs: compare your deposit block's number against the block returned for the finalized tag instead of counting confirmations of your own. Use wall time for the things that are actually about time.
Failure mode on the finality clock itself: finality stops advancing when more than a third of the stake stops attesting, and resumes after the inactivity leak (mainnet spec constant MIN_EPOCHS_TO_INACTIVITY_PENALTY = 4 epochs) plus participation recovery. Code that blocks until finalized with no timeout hangs there, so bound it and alert when the finalized epoch has not advanced for several epochs.
Curated: · Written: · Reviewed:
Q&A-10The block number has not incremented for 36 seconds. Has the chain halted, and how should a keeper treat the gap?
Short answer: no. A 36-second gap is three missed slots at 12s each. The slot clock kept ticking and fork choice kept running; the execution block number didn't move because no proposer published a block. A halt looks different: no new head for many slots, and, the decisive signal, no new finalized checkpoint.
Why the block number stalls without a halt
Post-merge, an execution block exists only if the beacon proposer assigned to that slot publishes one. If that proposer is offline, or its block arrives too late to be seen, the slot is empty. Empty slots are routine on mainnet; three in a row is uncommon but well inside normal variance. The beacon slot clock is wall-clock driven and independent of block production, so slot advances every 12s whether or not a block appears.
Finality is a third, slower clock. Casper FFG finalizes a checkpoint every epoch (32 slots, 6.4 min), and a checkpoint is finalized two epochs later: 64 slots, 12.8 min. So a 36s gap is nowhere near the finality horizon.
What a real halt looks like
Not a 36s gap. Look for: head slot lagging wall clock by many slots across several independent beacon nodes; no new finalized epoch for more than 2 epochs (>12.8 min); execution clients importing nothing. If finality stalls for 4 epochs, the inactivity leak starts draining non-participating validators: that is the protocol's own recovery path, not something a keeper triggers.
How a keeper should treat the gap
- Key on slot or block timestamp, never on "block number changed." A block number bump is an output, not a clock.
- Make every action idempotent. Dedupe on a stable key (
(block_hash, log_index)for an event, or the target's id for a liquidation) so a re-poll cannot double-fire. - Process all blocks since your last checkpoint, in order, not just the newest. Two blocks can land inside one poll interval.
- Pick a confirmation depth deliberately. The
finalizedJSON-RPC block tag is reorg-proof but 12.8 min behind;safeis roughly one epoch. A liquidation keeper usually acts onlatest/safeand handles reorgs explicitly, because waiting for finality loses the race.
Worked example (hypothetical)
A keeper that re-scans a trailing window each poll and acts on every match, with no dedupe:
t=0s head=N scan [N-5 .. N] -> act on event in N
t=12s head=N scan [N-5 .. N] -> act on event in N (again)
t=24s head=N scan [N-5 .. N] -> act on event in N (again)
t=36s head=N+2 scan [N-3 .. N+2] -> act on event in N (again)
The same event fires four times. The mirror-image bug: a keeper that only inspects the head block sees N+2 at t=36s and misses the event that landed in N+1. Both are fixed by the idempotency key plus ordered replay from the last checkpoint, not by sleeping longer.
Detection
Alert on a window, not a single gap: e.g. ≥8 empty slots in 10 minutes, or time_since_last_finalized_epoch > 2 epochs. A lone 36s pause should page nobody.
One caveat: on a chain with fixed block times and no empty slots, most L2s, a 36s gap means something else entirely, and the sequencer is the first thing to check.
Curated: · Written: · Reviewed:
Q&A-1A transfer shows status success at the latest head. Why is that not Ethereum settlement, and which Gasper checkpoint actually is?
The first thing I would pin down about inclusion versus Gasper finality is which confirmation tier actually changes the decision.
Ethereum under Gasper separates fork-choice inclusion from Casper FFG finality: a block can be the LMD-GHOST head and still be replaced; only a supermajority-justified then finalized checkpoint is economically irreversible under the slashable-vote rules.
Concretely, fetch the receipt by transaction hash (it has no block tag). Treat inclusion as "the receipt's block is on the current head," and settle only when that block is an ancestor of the current finalized checkpoint, not when receipt.blockHash equals the checkpoint hash. Quote slot=12s; typical tx finality is closer to 2.5 epochs (~16 min) because a mid-epoch inclusion waits for a later checkpoint.
The reason for that specificity is a failure I have seen: An exchange credited 840 ETH after 1 confirmation at slot 9_102_441; a 7-block reorg dropped the deposit and the desk paid out $2.1M before the covering finalized checkpoint arrived ~16 minutes later.
Same tx, three eth_getBlockByNumber tags.
| Tag | Slot | Meaning | Reorgable? |
|---|---|---|---|
| latest | 9102448 | LMD-GHOST head | yes, even 7 blocks |
| safe | 9102416 | justified / reorg-safe under honesty | not FFG-final |
| finalized | 9102384 | Casper FFG checkpoint | not under honest 2/3 |
I would not consider it settled without evidence: Log the receipt's blockHash and the consensus client's finalized block; settle only if the receipt block is canonical and at or below that finalized ancestor.
Inclusion is a vote of the current head; finality is a 2/3 FFG checkpoint.
Curated: · Written: · Reviewed:
Q&A-3If two blocks compete at the same height, what does LMD-GHOST actually pick, and why is that not the same as an FFG vote?
The 90-second answer. LMD-GHOST picks the child whose subtree holds the greatest latest-message attestation weight, plus a proposer boost for the current slot's timely block. An FFG vote is a different object: a (source, target) checkpoint pair counted toward a 2/3 justification threshold. The head can flip every slot; a finalized checkpoint cannot be reverted without slashing a third of the stake. Head selection is the liveness mechanism, FFG is the safety mechanism: they read the same attestations and answer different questions. If you treat a head as settled, you have confused the two.
Why the head is not an FFG vote. Each attestation carries both an LMD vote (a beacon block root) and an FFG vote (source/target checkpoints). Fork choice keeps only the latest LMD vote per validator: a newer attestation overwrites the old one, so weight moves as validators re-attest. FFG votes accumulate across an epoch and are not overwritten within it; they are counted against 2/3 thresholds. So "8.5M ETH behind this block" is a snapshot of latest messages, not a commitment. The two signals also have different latencies:
| Signal | What it takes | Latency | Reversible? |
|---|---|---|---|
| Head (LMD-GHOST) | greatest latest-message weight + boost | ~1 slot (12s) | yes, every slot |
| Justified checkpoint | 2/3 of total stake FFG votes | ~1 epoch (6.4 min) | in theory, at 1/3 slashing |
| Finalized checkpoint | justified + next epoch justified | ~2 epochs (12.8 min) | no, without 1/3 slashing |
The boost is a deliberate trade, not a detail. The current spec gives the slot's timely proposer a boost of 40% of that slot's committee weight. With ~34M ETH staked, that is 34e6 / 32 × 0.4 ≈ 425k ETH: enough for a block with less attestation weight to win the slot. That trades weight fidelity for reorg resistance; shallow reorgs dropped sharply after it landed. If you build on head, you accept that a minority-weight block can be head for one slot. The alternative (no boost, pure heaviest-subtree) is more faithful to weight but reorgs more. The research direction (single-slot finality) exists precisely to collapse this gap.
Worked example (hypothetical numbers). Two children at the same height:
| Child root | Attestation weight | Proposer boost | Head? |
|---|---|---|---|
| 0xaa… | 8.2e6 ETH | 0 | no |
| 0xbb… | 8.1e6 ETH | 0.4e6 | yes |
| 0xaa…, 3 slots later | 8.5e6 ETH | 0 | yes (flip) |
A market maker quoting on head 18,440,102 had 410 ETH of fills land on the branch that got discarded three slots later; the book was −$740k for 11 minutes. That is the cost of pricing head as final.
Deciding criteria and how to hedge. The criterion is value at risk against latency budget. If settlement is irreversible and you can wait 12.8 minutes, settle on finalized. If you need sub-second, you are exposed and must price it: cap exposure per slot, re-price on flip, and use the justified checkpoint as a "safe" head. Op-stack does exactly this, tracking L1 safe (justified) and finalized heads and only finalizing withdrawals on the latter. Exchanges credit deposits at finalized for the same reason.
Detection. Dump fork-choice weight per child root at slot n and n+1. A flip without an FFG change is expected, not a bug. The real alarm is justification stalling for more than a couple of epochs: that is a deep-reorg signal, not a normal head flip. Fork choice names a live head; it does not freeze history.
Curated: · Written: · Reviewed:
Q&A-9Why is 2/3 of stake the number that matters for Casper FFG, and what happens if you design around 51% like a hash-rate story?
FFG finalizes a checkpoint when validators holding at least two-thirds of total effective balance vote for it. The threshold exists to make double-finality attributable: two conflicting finalized checkpoints must share at least one-third of stake, and that overlap is slashable. A 51% coalition can reorg the head under LMD-GHOST; it cannot finalize two histories without losing a third of its own stake.
The arithmetic is the whole argument. Let N be total effective balance. Two sets each ≥ 2N/3 overlap by at least 2N/3 + 2N/3 − N = N/3. So any double-finality proves ≥ N/3 of stake signed both checkpoints: attributable, slashable, and large enough to deter. Drop the threshold to 51% and the guaranteed overlap falls to 2N/100: a double-finality would only prove 2% misbehaved, and an attacker keeps 98% of its stake. That is why 51% is a head-influence number, not a settlement number.
When is a 51%-style design the right call? When you want liveness-first and can tolerate reorgs: PoW longest-chain, or any chain where settlement is probabilistic and downstream systems wait for confirmations. You accept that a majority can rewrite recent history in exchange for never stalling on finality. A finality gadget like FFG is right when something downstream needs irreversibility (a bridge, an exchange credit, a light client) and you are willing to pay for it with a liveness dependency: if fewer than 2/3 vote, finality stops even though blocks keep being produced.
Concrete failure modes. First, ≥1/3 offline or censored: no new finalized checkpoint, but the chain still produces blocks. A liveness failure, not a safety one. Detect it by watching the finalized epoch stop advancing. Second, ≥1/3 Byzantine can block finality indefinitely; that is the same liveness attack, and nothing is slashed unless they double-vote. Third, ≥1/3 double-votes: safety would break, but the evidence is on-chain and the stake is slashed, which is exactly what the 2/3 threshold is buying.
| Threshold | Guaranteed overlap on double-finality | What it buys |
|---|---|---|
| 51% | 2% of stake | head reorgs only |
| 2/3 | 1/3 of stake | slashable double-finality |
To check a finality claim, read the finalized checkpoint root and confirm the attesting effective balance on that root is ≥ 2/3 of total effective balance.
Curated: · Written: · Reviewed:
Q&A-2Why does Casper FFG need a justified checkpoint and then a later supermajority on its child before you call a deposit final?
Casper FFG finalizes in two phases because a single supermajority vote proves only that a majority agrees right now; it cannot prove that a conflicting majority could never form. The second phase, a supermajority link from the justified checkpoint to a descendant, is what turns conflicting finalization into a provable, slashable offense. That property is accountable safety, and it is the whole reason the two-step structure exists.
The mechanism. A justification is a supermajority link: ≥2/3 of total effective balance signs an attestation with source checkpoint s and target checkpoint t, where s is already justified. Genesis is justified by definition. A checkpoint c is finalized when c is justified and there is a supermajority link from c to its child checkpoint. So finalization is two consecutive justified epochs.
The safety argument is an intersection argument. Any two quorums of ≥2/3 overlap in ≥1/3 of stake. If two conflicting checkpoints were both finalized, the validators in that ≥1/3 overlap must have signed links that conflict: either two different targets in the same epoch (double vote) or nested sources and targets (surround vote). Both are slashing conditions. Two conflicting finalized checkpoints therefore cannot coexist unless ≥1/3 of stake is slashable. Safety holds under the standard assumption that <1/3 of stake is Byzantine.
Why one phase is not enough. A single link gives you one quorum. From one quorum you cannot derive a slashable intersection, and you cannot anchor the vote to a previously agreed checkpoint. Requiring the second link's source to be justified forces the second quorum to be built on top of the first, which is exactly what creates the overlap. Justification is a promise; finalization is the proof that the promise is backed by a slashable bond.
Worked trace (100 validators, 2/3 threshold = 67):
| Step | Link | Votes | Result |
|---|---|---|---|
| 1 | 99 → 100 | 70 | epoch 100 justified |
| 2 | 100 → 101 | 68 | epoch 101 justified; epoch 100 finalized |
| 3 | conflicting 99 → 100′ | 67 | epoch 100′ justified |
| 4 | 100′ → 101′ | 67 | epoch 100′ finalized |
Steps 1 and 3 overlap in at least 70 + 67 − 100 = 37 validators who signed two different targets in epoch 100: a double vote. Those 37 are slashable, so step 4 cannot happen without burning ≥1/3 of stake. That is the guarantee the two-phase rule buys.
Trade-offs and alternatives. Tendermint and HotStuff finalize in a single round using a lock-and-precommit, giving immediate finality, but they require near-full validator participation and couple finality tightly to the fork-choice rule. FFG is an overlay on LMD-GHOST, so it tolerates partial participation and network partitions between checkpoints; the price is ~2 epochs of latency (about 12.8 minutes on Ethereum at 32 slots × 12 s). GRANDPA (Polkadot) uses the same accountable-safety argument but finalizes many blocks per round. If you need sub-second finality, FFG's two-epoch latency is the wrong tool; a single-round BFT protocol is the right one, at the cost of higher communication overhead.
Failure modes. Liveness, not safety, is what breaks in practice: if <2/3 of stake attests, justification stalls and finality halts. Ethereum mainnet lost finality for roughly 25 minutes in May 2023 when a Prysm attestation-processing bug dropped participation below the threshold: no conflicting checkpoint finalized, which is the safety property working as designed. Detect it by watching the justified-epoch counter stop advancing; recover by fixing the client and letting participation climb back over 2/3.
What to check before paying against a deposit. Resolve the finalized checkpoint to its execution block and prove the deposit's block is an ancestor. Comparing floor(depositSlot / 32) to finalized_checkpoint.epoch is unsafe: a checkpoint covers the start of its epoch, not every later block in it.
Curated: · Written: · Reviewed:
Q&A-5Beacon APIs expose safe and finalized. When is safe still the wrong tag for a withdrawal, and what is it for?
I would treat safe head versus finalized checkpoint as a state machine over pending, included, and finalized, not as a single RPC result.
The execution API's safe tag is the most recent block considered reorg-safe under honest-majority and synchrony assumptions, typically the justified checkpoint; it is not Casper FFG finality. Withdrawals and mint/burn still use finalized unless the product explicitly eats remaining reorg risk.
Concretely, map JSON-RPC tags: latest → raw head, safe → justified / reorg-safe under those assumptions, finalized → FFG checkpoint. For custody, fetch the receipt by hash and require its block to be an ancestor of the current finalized block: equality with the checkpoint hash is the wrong test.
The reason for that specificity is a failure I have seen: A custodian paid 3_200 USDC on safe at slot 11_004_088, treating it as settlement; 4 minutes later the justified view moved and the USDC had already left the hot wallet.
Tags at one query time.
| Tag | Block | Age | Use |
|---|---|---|---|
| latest | 19001010 | 0s | mempool UX |
| safe | 19000978 | ~epoch-scale | low-value display |
| finalized | 18999946 | ~2–3 epochs | withdrawals |
I would not consider it settled without evidence: Side-by-side logs of safe.hash and finalized.hash for 2 hours; any payout whose hash only ever matched safe is a policy bug.
Safe is a better head, not a finalized checkpoint.
Curated: · Written: · Reviewed:
Q&A-4A product owner wants "6 confirmations like Bitcoin." What do you actually encode on Ethereum PoS, and where does that policy fail?
On Ethereum PoS there is no "6 confirmations" primitive to encode. Confirmation depth is an application-level risk budget on reorg probability, not a protocol guarantee. High-value settlement waits for Casper FFG finality; low-value UX uses a documented N-slot head lag and accepts that the head can reorg.
Mechanism: Gasper is LMD GHOST fork choice plus Casper FFG. A checkpoint is justified after one epoch of attestations (32 slots, 6.4 min) and finalized after a second, so finality lands about 12.8 min (two epochs) after inclusion. Reverting a finalized checkpoint requires ≥1/3 of staked ETH to be slashed: that is the settlement tier. Before finality the head is only probabilistically stable: depth-1 and depth-2 reorgs occur on mainnet, deeper ones are rare but not impossible.
Pick N from a loss table, not from a Bitcoin habit:
| Value | Policy | Wait | Residual risk |
|---|---|---|---|
| <$50 | 2 slots | 24s | small reorg |
| <$5k | 12 slots | 2.4 min | uncommon |
| ≥$50k | finalized | ~12.8 min (2 epochs) | needs 1/3 stake slashed |
Implementation: subscribe to newHeads, rewind N blocks, and treat N as "probably safe," never as "cannot reorg."
Worked example (hypothetical): a checkout used 6 blocks (72s) for a $180k NFT mint. A 9-block reorg at slot 7,881,200 unminted the token after the warehouse shipped: $180k of inventory gone. The 6-block policy was a UX delay applied to a settlement decision.
To verify the policy holds, run a reorg drill in staging: rewind 12 then 64 slots and assert the credit table matches finalized receipts only.
Six blocks is a UX delay; finalized is the settlement tier.
Curated: · Written: · Reviewed:
Q&A-6Your indexer is at height H when the node reports a reorg back to H-8. What must you undo, and what must stay?
In 60 seconds. A reorg back to H-8 means the node's canonical chain now diverges at H-8: blocks H-7 through H are no longer canonical. Undo every derived row those 8 blocks produced: logs, receipts, transfers, balance deltas, aggregates, caches, and any "latest" pointer, and keep everything at or below H-8 plus the raw blocks you replay from. H-8 is the boundary; nothing above it is trustworthy until you re-verify it against the node.
Finding the boundary. Don't trust the depth the node reports; walk it. Compare your stored hash for each height against the node's hash, descending until they match.
def rewind(cursor, node, store):
n = cursor.number # last block we applied
while n >= 0:
if store.hash_at(n) == node.hash_at(n):
return n # common ancestor
store.delete_block(n) # logs, transfers, balance deltas, aggregates
n -= 1
raise ReorgTooDeep()
Trace with H=1008, common ancestor 1000:
| Height | Stored | Node | Action |
|---|---|---|---|
| 1008 | 0xaa8 | 0xbb8 | delete |
| 1007 | 0xaa7 | 0xbb7 | delete |
| … | … | … | delete |
| 1001 | 0xaa1 | 0xbb1 | delete |
| 1000 | 0xaa0 | 0xaa0 | keep: stop |
Eight deletes, then replay 1001–1008 against the new hashes.
What must go. Anything computed from those blocks: logs and receipts, token/NFT transfers, internal transfers, balance and nonce deltas, running aggregates (volume, TVL, active addresses), materialized views, search-index entries, and cached head state. Delete by block hash, not just by number: the new chain reuses the same heights with different contents, so a number-only delete followed by an append is exactly how you double-count.
What must stay. Every row at height ≤ 1000 on the canonical path, the raw blocks and transactions you replay from, and finalized state. On Ethereum PoS finality is two epochs: 64 slots × 12 s ≈ 12.8 minutes, so an 8-block reorg (~96 s) never touches finalized data. If a reorg ever crosses the finalized checkpoint, stop and alert: that's a consensus failure, not a routine rewind.
Failure modes.
- Append-only indexer: replays the new branch on top of the old, double-crediting. Detect by asserting row counts and a unique key on (blockHash, txIndex, logIndex) or (txHash, logIndex).
- Non-idempotent writes: replay must upsert, not insert.
- Running counters: you can't fix a balance by deleting a row if it was incremented in place. Recompute from remaining rows or store per-block deltas.
- Side effects already emitted: webhooks, alerts, emails can't be un-sent. Delay them until finality, or emit compensating events.
- Stale caches and views: invalidate them in the same transaction as the delete.
- Provider disagreement: if two nodes report different heads, quorum before rewinding.
Verification. A fixture that feeds an 8-block fork, then the canonical chain, and asserts derived balances equal eth_call at the new head: plus a check that no (txHash, logIndex) appears twice. That's the test that catches the append bug before users do.
Curated: · Written: · Reviewed:
Q&A-7A minority of validators cannot see the majority for hours. What does the inactivity leak do, and how does that change your finality wait?
I would settle inactivity leak under partition against a counter-example first, so the clever opcode has to survive it.
If FFG cannot gather 2/3, Gasper leaks inactive validators' balances until the online set again exceeds 2/3, restoring finality liveness. A prolonged partition can in the limit let both sides leak the other and finalize conflicting histories, after which social recovery is the remaining safety valve.
Concretely, during a leak, do not treat "we have not finalized in 2 epochs" as a bug in your app; lengthen settlement to "first finalized after leak ends" and halt mint/burn. Track currentEpoch - finalizedEpoch as a gauge.
The reason for that specificity is a failure I have seen: During a 3.1-hour leak on a test fork, a vault kept releasing after 12.8 minutes of wall time; $640k left on a non-finalized head that later lost 22% of its attestations.
Lag gauge during a leak.
| t | finalized lag (epochs) | Policy |
|---|---|---|
| 0 | 2 | normal ~12.8 min |
| 40 min | 8 | freeze payouts |
| 3.1 h | 29 | still freeze |
| after leak | 2 | resume |
I would not consider it settled without evidence: Alert when finalized lag > 5 epochs (~32 min) and freeze settlement until lag returns to 2.
The leak buys finality later by burning inactive weight; it does not let you skip FFG now.
Curated: · Written: · Reviewed:
Q&A-11A founder asks whether Ethereum finality is "mathematically impossible to reverse." What do you say, with numbers?
First two minutes
No. Ethereum finality is economically infeasible to reverse, not mathematically impossible, and if the founder is pricing risk on "mathematically impossible", they are pricing the wrong thing.
Gasper finality is a vote count, not a proof. A checkpoint is justified when two-thirds of staked ETH attests for it, then finalized one epoch later once the next checkpoint is justified: two epochs of 32 slots at 12 seconds each, about 12.8 minutes from block to final. The property the protocol actually gives you is accountability: two conflicting checkpoints cannot both be finalized unless at least a third of all staked ETH signed both, and that overlapping third is provably slashable from the published attestations alone. Nothing here rules the event out the way a preimage rules out forging a hash. Clients enforce the rule, and clients can be changed.
Blunt version for the founder: "reversing a finalized checkpoint means burning at least a third of all staked ETH, or coordinating a social fork. Pick which one you are afraid of."
The arithmetic
Assume 32,000,000 ETH staked at $3,000 per ETH; substitute live values.
| Quantity | Value |
|---|---|
| Total staked | 32,000,000 ETH (~$96B) |
| Attestation weight needed to finalize | 2/3 = 21,330,000 ETH (~$64B) |
| Overlap that must be slashable to finalize two conflicting checkpoints | 1/3 = 10,670,000 ETH (~$32B) |
| Base slashing penalty | effective balance / 32 = 1 ETH per 32 ETH validator |
| Correlation penalty in a mass event | scales toward the full effective balance, over an 8,192-epoch (~36 day) window |
| A $5M deposit | 0.016% of that $32B; the attacker burns roughly 6,400x it |
How a reversal would actually have to go
- Epoch N: 2/3 of stake attests to checkpoint A, so A is justified. Epoch N+1 attests to a descendant, so A is finalized.
- To replace A, an attacker publishes a conflicting checkpoint B at the same height and collects 2/3 of stake on it. Every validator signing both A and B has double-voted; validators attesting across the two branches add surround votes.
- The two 2/3 quorums overlap by at least 1/3 of total stake, derivable from the published attestations with no court and no governance vote. The protocol slashes that overlap: the 1 ETH base per 32 ETH validator, plus a correlation penalty that for a slashing this large drives balances to zero. Slashed ETH is burned, not redistributed.
- The attacker's validators are then ejected through the exit queue, which drains 1/65536 of the active set per epoch. If the cause was a client bug instead, the remedy is a coordinated client release or a user-activated soft fork: a human decision, not a protocol rule.
Failure modes, and how you see them
- Liveness, not safety: a third of stake offline or refusing to attest halts finality and nothing else. Watch the finalized epoch stall while the head keeps advancing: GET /eth/v1/beacon/states/head/finality_checkpoints on the beacon API, or the execution-layer "finalized" block tag. Alert at 3-4 epochs of lag (~25 minutes). Ethereum lost finality for about 25 minutes in May 2023 to a client bug; nothing was reversed.
- Safety: a mass slashing (1/3 or more) is the on-chain fingerprint of two conflicting quorums. It shows up as a spike in slashed validators and a drop in total stake, not as a silent event.
- Social fork: if finality breaks under you, recovery is a coordinated choice by client teams, staking pools and exchanges about which branch to follow. That takes hours to days, and withdrawals are frozen meanwhile.
- Wrong lever: "justified" is one epoch (~6.4 minutes) and is not final. Crediting deposits on justified, or on exchange confirmations alone, credits a checkpoint that can still be replaced without any slashing.
What to tell the founder
"Finalized" means reverting it costs someone a third of all staked ETH, about $32B at current prices, and the protocol burns it. It does not mean impossible. Credit deposits on finalized, not justified; hold a reserve or insurance against the tail where finality stalls and you must pick a branch or freeze withdrawals; and put the assumption in the risk memo as "reversal implies at least 1/3 of stake slashable, or a user-activated fork".
Curated: · Written: · Reviewed:
Q&A-92During a network partition, Gasper stops finalizing rather than finalizing two heads. Which CAP corner is that, and when would a product pick the other?
Core answer (say this first). Assume we mean Ethereum's Gasper, Casper FFG for finality plus LMD-GHOST for the head, under a partition that splits the validator set. The finalized checkpoint is the CP corner: it gives up availability of finality rather than risk two conflicting finalized checkpoints. The head that LMD-GHOST returns stays available and is AP-ish: it keeps advancing on each side and can be reorged. So the accurate framing is that one protocol exposes both corners at once, and the product picks which one its action depends on. (CAP's C is linearizability of a register; finality is a stronger, irreversible commitment, so this is a defensible analogy, not a literal CAP theorem instance.)
Why finality stalls. Casper FFG finalizes a checkpoint only after two consecutive epochs are justified, and justification needs attestations from at least two-thirds of total staked ETH. An epoch is 32 slots × 12 s = 6.4 min, so under normal conditions finality trails the head by about two epochs, roughly 12.8 min. Cut the network so neither side holds two-thirds and neither side can justify: finality stops, and it stays stopped until the partition heals and two-thirds attest again. That stall is unbounded, not a fixed 12.8 min. Safety holds because two conflicting checkpoints cannot both be finalized without at least one-third of stake being slashed; the protocol would rather halt finality than pay that.
When a product picks the other corner. Pick the head (availability) when the action is cheap to reverse and the cost of stalling exceeds the expected cost of a reorg. Pick finalized (safety) when the action is irreversible or settles value. Deciding criteria, in order: (1) can the effect be clawed back or compensated? (2) value at risk per minute of stall; (3) probability the head you acted on gets reorged out.
Worked example (hypothetical, labelled as such). A partition splits stake 55/45. Neither side reaches 66.7%, so both stall finality and both advance a head. A game that credits on the head credits on both sides; on heal one head is reorged out and those credits are invalid. The same partition at 70/30: the 70% side justifies and finalizes, and the 30% side's head-only credits are unwound when it reorgs onto the finalized chain.
| Partition split | Finality | Head | Safe to settle value? |
|---|---|---|---|
| 55/45 | stalls on both sides | advances on both | no |
| 70/30 | 70% side finalizes | advances on both | only on the finalized side |
| healed | resumes in ~2 epochs | collapses to one head | yes, after finality |
Failure modes and detection. Following the head during a partition produces duplicate credits on both sides; detect it by two divergent heads or state roots, or by finalized-epoch lag exceeding two epochs (~13 min). Waiting on finality produces an unbounded stall; detect it by the finalized checkpoint not advancing while the head does, and respond by pausing withdrawals and queueing, or by falling back to a head-based rule with an explicit risk cap. Monitor the gap between finalized epoch and head epoch, plus attestation participation.
Curated: · Written: · Reviewed:
Q&A-13What does a valid secp256k1 signature on an Ethereum transaction actually prove, and what does it not prove?
What it proves. A valid secp256k1 signature proves two things and only two: the signer knew the private key d whose public key Q hashes to the recovered address, and they signed the exact hash z of the signing payload. The RLP-encoded fields for a legacy tx, or the typed envelope (EIP-1559/2930/4844) for newer ones. Nothing about intent, key custody, or finality follows from it.
Mechanism. ECDSA signing picks a nonce k, computes R = k·G, r = R.x mod n, s = k⁻¹(z + r·d) mod n. Ethereum doesn't verify against a known pubkey; it recovers one: Q = r⁻¹(s·R − z·G), with v selecting the candidate R (y-parity, plus the rare r ≥ n case). The address is keccak256(Q)[12:]. The binding is entirely to z: flip one byte of the payload, z changes, and the recovered Q is a different, effectively random address. That is why calldata substitution is detectable: the substituted tx has a different z, so ecrecover yields an address that won't match the signer.
What it does not prove.
- Intent. The signer authorized bytes, not a screen. Blind signing, a hardware wallet showing a hash it can't decode, produces a perfectly valid signature over a
transferFromthe user never read. - Key custody. A stolen or leaked key signs identically to the owner's.
- Finality. Validity is orthogonal to inclusion, ordering, and reorgs.
- That the address is an EOA. EIP-1271 contracts validate via
isValidSignature;ecrecoverreturning an address doesn't mean a key signed.
Decision points.
- Recovery vs verify: recovery is why the sender is derivable from
(r,s,v)alone; standard ECDSA verify needsQup front. - EIP-155 chainId: without it in the payload, the same signature replays on a forked or sibling chain. With it,
zdiffers per chain. - EIP-2 low-s:
s ≤ n/2kills malleability. Without it,(r, n−s)is also valid, giving a second tx hash for one signature. - EIP-712: the domain separator binds chainId and verifying contract, so a signature for one contract can't be replayed against another.
| Proves | Does not prove |
|---|---|
Knowledge of d for the recovered address | The signer understood the payload |
The exact z was signed | The key is uncompromised |
| Sender = recovered address | Inclusion, ordering, finality |
| — | That the address is an EOA (EIP-1271) |
Failure modes and detection.
- Blind signing: valid signature over unintended calldata. Detect by independently serializing the tx and byte-comparing hashes; require the signer to display decoded fields.
- Malleability: two valid signatures, two hashes. Detect by enforcing low-s.
- Cross-chain replay: same signature valid on two chains. Detect by requiring chainId in the payload.
- Wrong-bytes verification: a verifier that hashes a client-supplied blob instead of the canonical serialization recovers a matching address for the blob while the broadcast tx differs. Detect by re-serializing locally and comparing.
A signature binds bytes to a key. Everything else (intent, custody, finality) is a separate control.
Curated: · Written: · Reviewed:
Q&A-14How is an Ethereum address computed from a public key, and why is a 20-byte truncation not a checksum of the key?
An Ethereum EOA address is the last 20 bytes of the Keccak-256 hash of the 64-byte uncompressed public key, with the 0x04 prefix removed. In the Yellow Paper: address = keccak256(pubkey[1:])[12:]. The public key is the 64-byte concatenation of the X and Y coordinates on secp256k1. The hash is Keccak-256, not NIST SHA3-256. The 20-byte truncation is not a checksum because it doesn't verify the key; it's a lossy identifier. A checksum adds redundancy to detect errors; truncation removes information. The address is not a commitment to the public key: you can't recover the key from the address, and you can't verify a key against an address without the key. The security property is collision resistance: a generic collision takes about 2^80 work (birthday bound on 160 bits), and a preimage for a specific address takes about 2^160. That's infeasible, but it's not authentication. Authentication comes from ECDSA signatures.
Here's the pipeline in code, checked against eth-keys 0.4.0 and eth-utils 2.2.0:
from eth_keys import keys
from eth_utils import keccak, to_checksum_address
priv = keys.PrivateKey(bytes.fromhex('46'*32))
pub = priv.public_key
pub_bytes = pub.to_bytes() # 64 bytes, no 0x04 prefix
addr_bytes = keccak(pub_bytes)[12:] # last 20 bytes
print(addr_bytes.hex())
# 9d8a62f656a8d1615c1294fd71e9cfb3e4855a4f
print(to_checksum_address(addr_bytes))
# 0x9d8A62f656a8d1615C1294fd71e9CFb3E4855A4F
The table:
| Step | Bytes | Note |
|---|---|---|
| uncompressed XY | 64 | drop 0x04 |
| keccak256 | 32 | |
| address | last 20 | [12:32] |
| fixed-address preimage work | ~2^160 | generic collision ~2^80 |
EIP-55 is a design choice, not a protocol requirement. It encodes a checksum in the mixed-case hex representation: hash the lowercase hex address (without 0x) with Keccak-256, and capitalize hex letters where the corresponding nibble of the hash is >= 8. This detects typos in the address string. The alternatives: full public key as address (64 bytes) would avoid truncation collisions but cost more storage and calldata; Bech32 (Bitcoin, Cosmos) uses a dedicated checksum and is case-insensitive, but requires a new address format. Ethereum kept 20-byte hex for backward compatibility and added EIP-55 as an optional display checksum. It is not enforced by the protocol; wallets and block explorers must implement it. If you accept all-lowercase addresses, you lose typo detection. If you accept mixed-case, you must validate the checksum.
Failure modes: hashing the 33-byte compressed key instead of the 64-byte uncompressed key yields a different address; using SHA3-256 instead of Keccak-256 yields a different address; forgetting to drop the 0x04 prefix yields a different address. Address poisoning: an attacker sends a tiny amount from an address with the same first and last few hex characters, hoping you copy it from history. EIP-55 doesn't help if you copy from history. Hardware wallets display the address and verify it on-device, which is the real defense.
The 20-byte truncation is not a checksum of the key. It's a short, collision-resistant identifier. The checksum you see in EIP-55 is on the hex string, not on the key.
Curated: · Written: · Reviewed:
Q&A-15A user pastes a mixed-case address. What does EIP-55 actually detect, and what can it not catch?
The 90-second version
EIP-55 is a typo detector, not an identity check. It folds bits of keccak256(address) into the letter case of the address string, so a validator answers exactly one question: does this string's case pattern match the hash of its own lowercase form? It never answers "is this the address you meant?" A green tick on an explorer means the string is well-formed, not that the destination is right.
Mechanism
Take the 40 lowercase hex characters, no 0x. Hash those 40 ASCII bytes with Keccak-256. Walk the 40 positions: if the character is a letter a–f, uppercase it when the i-th hex digit of the hash is ≥ 8; leave it lowercase otherwise. Digits 0–9 are never touched, so they carry no check information at all.
# Python 3.9+, eth-hash[pycryptodome]
from eth_hash.auto import keccak
def to_checksum(addr: str) -> str:
body = addr.lower().removeprefix("0x")
h = keccak(body.encode("ascii")).hex()
return "0x" + "".join(
c.upper() if c in "abcdef" and int(h[i], 16) >= 8 else c
for i, c in enumerate(body)
)
to_checksum("0x5aaeb6053f3e94c9b9a09f33669435e7ef1beaed")
# '0x5aAeb6053F3E94C9b9A09f33669435E7Ef1BeAed' (EIP-55 test vector)
Use Keccak-256, not NIST SHA3-256. hashlib.sha3_256 uses different padding and produces a different digest, so every checksum you generate will fail against every other tool.
What it catches
Any single-character edit changes the hash, which re-randomises the case of every letter in the string. The edited string survives only if all L letter positions happen to land on the right case, which is 2^-L. A typical address has ~15 letters (40 positions × 6/16), so a random one-character typo slips through about 1 time in 32,768. That is the entire guarantee.
| Letters in the address (L) | Chance a random 1-char typo passes |
|---|---|
| 0 | 1: never detected |
| 5 | 1 in 32 |
| 15 (typical) | 1 in 32,768 |
| 30 | 1 in ~1.07 billion |
What it cannot catch
- All-lowercase or all-uppercase input. No case pattern, no check. Most JSON-RPC responses, explorer copy buttons and many wallets hand you lowercase, and every mainstream library accepts it. This is the common case, not the edge case.
- Addresses with few letters. The guarantee is 2^-L, not 2^-15.
0x0000000000000000000000000000000000000000has zero letters, so a digit-to-digit typo there is never detected. A 5-letter address is caught only 31 times in 32. - A typo that happens to checksum. 1 in ~32,768 on average, and an attacker can grind for it deliberately: producing a validly-checksummed lookalike costs nothing.
- Intent, ownership, or chain. A valid checksum says nothing about whether the address is the recipient you meant, whether it is an EOA or a contract, or which EVM chain it is on. The same address is valid on every chain; EIP-1191 exists precisely because some chains wanted the chain ID folded in.
- Clipboard and UI substitution. Malware that swaps the whole address for another validly-checksummed one passes every check. So does a lookalike sharing the first and last four characters.
The failure mode to name
A support flow that reports "checksum passed" as reassurance. The concrete version: a lookalike contract differing in three hex characters, ground until it checksums, pasted by a user who saw a tick. The control that would have stopped it is an allowlist on the destination, not the checksum.
What to actually do
- Validate the checksum on any mixed-case input and reject on mismatch; treat all-one-case input as unverified rather than valid.
- Compare against a stored allowlist above a threshold you choose, and show the full address plus first/last four characters for out-of-band confirmation.
- Unit-test the boundary: one flipped character in a mixed-case address must raise.
Checksums catch sloppy typing. They do not name the intended recipient.
Curated: · Written: · Reviewed:
Q&A-16Why can a signed Ethereum transaction from chain 1 be worthless on chain 137, and what field makes that true?
The 90-second version
chainId. It sits inside the bytes the signature covers, so the signature commits to it, and a node on chain 137 compares the transaction's declared chain ID against its own before it touches state. Mismatch, reject. You cannot relabel the transaction chainId = 137 and keep the signature, because that changes the signing hash and the recovered sender.
Where the field actually lives
| Tx type | Envelope | chainId location | Signing hash |
|---|---|---|---|
| Legacy, pre-EIP-155 | none | absent | keccak(rlp([nonce, gasPrice, gasLimit, to, value, data])) |
| Legacy, EIP-155 | none | encoded in v | keccak(rlp([nonce, gasPrice, gasLimit, to, value, data, chainId, 0, 0])) |
| 0x01 EIP-2930 | 0x01 | payload field 0 | keccak(0x01 ‖ rlp([chainId, nonce, gasPrice, gasLimit, to, value, data, accessList])) |
| 0x02 EIP-1559 | 0x02 | payload field 0 | keccak(0x02 ‖ rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList])) |
| 0x03 EIP-4844 | 0x03 | payload field 0 | keccak(0x03 ‖ rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList, maxFeePerBlobGas, blobVersionedHashes])) |
| 0x04 EIP-7702 | 0x04 | payload field 0 | keccak(0x04 ‖ rlp([chainId, nonce, maxPriorityFeePerGas, maxFeePerGas, gasLimit, to, value, data, accessList, authorizationList])) |
For legacy EIP-155, v = chainId * 2 + 35 + yParity, so chainId 1 gives v ∈ {37, 38} and chainId 137 gives v ∈ {309, 310}. The chain ID is recoverable from v alone: (v - 35) / 2.
The trace
A legacy transaction signed for chainId 1, v = 37. A node on chain 137 receives the raw bytes:
tx.ChainId()=(37 - 35) / 2= 1.- The node builds its signer with chainId 137.
1 != 137→ geth's signer returnsErrInvalidChainId.- The txpool rejects it during sender recovery, before nonce and balance checks. The nonce stays free on 137.
What did not happen: ecrecover did not fail. Verify that same signature with chainId 1 and it recovers the correct sender. The rejection is a chain-ID check, not a broken signature. That distinction matters, because it tells you where the protection actually comes from: the field is bound by the signature, so an attacker cannot rewrite it, and the node refuses anything whose declared chain ID is not its own.
Failure modes
- Pre-EIP-155 legacy (
v ∈ {27, 28}). No chainId in the signing hash, so the same signature recovers the same sender on every chain. Geth's txpool rejects unprotected transactions by default since v1.10;--rpc.allow-unprotected-txsopts back in. Any chain that accepts them is replayable. - A fork that kept
chainId = 1. EIP-155 cannot help: the check passes because the IDs match. That is an ops failure, not a protocol one. If you fork mainnet state for a testnet, change the chain ID before anyone signs. - A signer that omits chainId. You get a pre-155 transaction with
v ∈ {27, 28}and no replay protection. Assert the chain ID at the signing call site, not at the RPC. - Assuming the same contract address means the same chain. Addresses repeat across chains; the chain ID is the only thing separating them.
What I check in review
- Every signing path sets
chainIdexplicitly; no hand-rolled signing hashes. - Production mainnet transactions never carry
v ∈ {27, 28}. - The chain ID is asserted against the target node's
eth_chainIdbefore broadcast, not just at signing time.
Curated: · Written: · Reviewed:
Q&A-17Ethereum rejects high-s signatures. What attack does that close, and what still remains?
Core answer
EIP-2, active from Homestead (block 1,150,000, March 2016), rejects any transaction whose ECDSA s-value is greater than secp256k1n/2. It closes third-party transaction-hash malleability.
ECDSA over secp256k1 has a structural property: if (r, s) verifies against a message hash and public key, then (r, n − s) also verifies, with the recovery parity flipped. Before EIP-2, anyone watching the mempool could take your pending transaction, swap s for n − s, flip v, and rebroadcast. The result has a different hash but the same sender, nonce, value and calldata: identical effect, different identity. Any system that keys on tx hash (a relayer's processed set, a bridge credit, a wallet dedupe) now sees two transactions where the signer sent one.
What remains is that low-s makes the hash a function of the signer's signature, not of the signer's intent. The signer can still produce two valid transactions with the same nonce and different hashes, and anyone can replace a pending transaction with a same-nonce, higher-fee one. Tx hash is still not an idempotency key; (sender, nonce) is, and only finality makes it safe. The rule is also scoped to transaction validation: the ecrecover precompile still accepts high s, deliberately.
Mechanism and the canonical form
N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
HALF_N = N // 2 # 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0
def canonical(r, s, y_parity):
"""Low-s twin of an ECDSA signature. Ethereum rejects; it does not fix for you."""
if s > HALF_N:
return r, N - s, y_parity ^ 1
return r, s, y_parity
Trace with s = N − 1: canonical returns (r, 1, flipped parity). Both (r, N−1) and (r, 1) verify against the same public key and message hash. A post-Homestead node accepts only (r, 1); a pre-Homestead node, or a contract calling ecrecover, accepts both.
| s | Accepted by tx validation (post-EIP-2) |
|---|---|
| 1 | yes |
| floor(n/2) = 0x7FFF…20A0 | yes: the bound is inclusive |
| floor(n/2) + 1 | no |
| n − 1 | no: the twin of s = 1 |
| n | invalid; s must lie in [1, n−1] |
The same check applies to every transaction type, legacy and typed.
What still remains
- Signer-side duplicates. Same nonce, different hash: re-signing with a different k, or changing any signed field. Nonce uniqueness is enforced; hash uniqueness is not.
- Replacement. An observer can submit the same nonce with a higher fee and take the slot. The hash you saw may never be included.
- ecrecover. EIP-2's rationale leaves the precompile accepting high s on purpose, for verifying old Bitcoin signatures. Contracts must enforce s ≤ n/2 and v ∈ {27, 28} themselves; OpenZeppelin's ECDSA library does this against the _HALF_ORDER constant above.
- Off-chain signatures. EIP-712 and personal_sign are not consensus-validated; the verifier owns the check.
- Cross-chain replay. Low-s says nothing about replaying a signed transaction on a forked chain: that is EIP-155 chain id.
Failure mode and detection
The failure is an indexer or bridge whose unique key is tx hash. Detect it by fuzzing s' = n − s against a node and asserting rejection, and by monitoring for two included transactions sharing (sender, nonce) with different hashes. Constructed example: a relayer that credits on first-seen tx hash and verifies signatures with a high-s-accepting path credits twice for one signed transfer; the second credit is the twin. The fix is the key, not the signature check.
Curated: · Written: · Reviewed:
Q&A-18Your contract uses ecrecover to auth a voucher. Which return values must you reject, and why is 0x0 a trap?
ecrecover(hash, v, r, s) is the precompile at 0x01. It never reverts. Every failure path returns address(0). So there are two things to reject: the return value address(0), and the inputs that produce it.
Reject, in this order:
v != 27 && v != 28: the precompile accepts only these two.0/1(the raw recovery id some libraries emit) returnsaddress(0).r == 0 || r >= ns == 0 || s >= ns > n/2, not becauseecrecoverfails (it doesn't; it returns a valid address), but because(r, s)and(r, n - s)recover the same signer. If replay protection keys on the signature bytes, both encodings pass.recovered == address(0)recovered != expectedSigner
n is the secp256k1 group order, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141.
Why 0x0 is the trap
address(0) is overloaded. It is the failure sentinel and the default value of every address-typed storage slot and mapping entry in the EVM. That collision is what makes it dangerous:
require(ecrecover(...) == owner)whereownerwas never set (or is a mapping default) authorizes any malformed signature.require(recovered != address(0))alone proves only that some well-formed signature exists, not that it is yours. It is a necessary check, never a sufficient one.- If the recovered address is used as a key into an allowance mapping,
address(0)is a shared bucket every forged signature lands in. - If the recovered address is the mint or transfer recipient, funds go to
0x0and are unrecoverable.
Guard
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
uint256 constant N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141;
uint256 constant HALF_N = 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0;
function recoverStrict(bytes32 h, uint8 v, bytes32 r, bytes32 s)
internal pure returns (address)
{
require(v == 27 || v == 28, "v");
uint256 rr = uint256(r);
uint256 ss = uint256(s);
require(rr != 0 && rr < N, "r");
require(ss != 0 && ss <= HALF_N, "s"); // low-s only
address a = ecrecover(h, v, r, s);
require(a != address(0), "zero");
return a;
}
Caller: require(recoverStrict(digest, v, r, s) == signer, "signer");, with signer set in the constructor behind require(signer != address(0)).
What each input does
| input | ecrecover returns | rejected at |
|---|---|---|
v = 0, valid r,s | address(0) | v check |
v = 27, r = 0 | address(0) | r check |
v = 27, s = 0 | address(0) | s check |
v = 27, s = n | address(0) | s check |
v = 27, s = n/2 + 1 | valid address | s check (malleability) |
valid (v,r,s), wrong key | some address ≠ 0 | signer equality |
Row 5 is the one people miss: the precompile does not enforce EIP-2 low-s. That rule applies to transaction signatures, not to ecrecover.
Failure modes and how to catch them
- High-s replay. Same signer, two encodings. Fuzz
sandn - sagainst your replay map; both must fail to redeem. - Cross-chain replay. Same deployer and nonce gives the same contract address on two chains. If the digest omits
block.chainid, one voucher redeems on both. Putaddress(this)andblock.chainidin the digest, or use an EIP-712 domain separator. - Cross-contract replay. Digest omits
address(this); a voucher for contract A redeems on B. - Smart-contract wallets. A Safe's EIP-1271 signature makes
ecrecoverreturnaddress(0), so a strict guard rejects a legitimate signer. Use OpenZeppelinSignatureChecker.isValidSignatureNow, which falls back toisValidSignaturefor contract accounts.
Alternatives
ECDSA.recover from OpenZeppelin runs the whole list: it rejects v ∉ {27,28}, rejects s > n/2, and reverts with ECDSAInvalidSignature on malformed input or a zero recovery. It still does not know who the signer should be: you compare the returned address against your stored signer yourself.
One more input trap: ecrecover takes a 32-byte digest. If you sign off-chain with personal_sign, the digest is keccak256("\x19Ethereum Signed Message:\n32" || innerHash). Passing the inner hash recovers a different address: usually non-zero, so the != address(0) check passes and the signer comparison fails, which reads as a signing bug rather than a guard bug.
Curated: · Written: · Reviewed:
Q&A-19A mobile wallet stores a 12-word mnemonic in app storage. What is the actual secret, and how do account indexes change the address?
Assume a standard BIP-39/BIP-32/BIP-44 wallet, no passphrase unless one is set. Under those assumptions the 12 words are an encoding, not the secret. They carry 128 bits of entropy plus a 4-bit checksum; the secret is the 512-bit seed produced by PBKDF2-HMAC-SHA512 over the words: 2048 iterations, salt "mnemonic" + passphrase. Set a passphrase and the same words derive a different, empty wallet; that is the whole point of the 25th word. Everything downstream is a one-way function of that seed, so whoever holds the seed (or the words plus passphrase) holds every account at every index, permanently.
Index i does not transform an address, it selects a different child key. BIP-32 turns the seed into a master private key and chain code, then each path segment is an HMAC-SHA512 step. Ethereum wallets use m/44'/60'/0'/0/i: the first three segments are hardened (coin type 60 is ETH), the last two are not, which is why an xpub at m/44'/60'/0'/0 can enumerate every receiving address without any private key. Address i is keccak256 of the secp256k1 public key for child i, last 20 bytes. Different i, unrelated key, unrelated address.
words + passphrase
PBKDF2-HMAC-SHA512(2048 iters, salt="mnemonic"+passphrase) -> 512-bit seed
HMAC-SHA512(key="Bitcoin seed", seed) -> master priv + chain code
CKDpriv 44' -> 60' -> 0' -> 0 -> i -> privkey_i
secp256k1(privkey_i) -> pubkey_i
keccak256(pubkey_i)[12:] -> address_i
Wallets scan i = 0..19 (the BIP-44 gap limit of 20) to find used accounts, which is why restoring a seed surfaces your history rather than just account 0.
Storage is where the real decision sits, and the options trade hardware backing against recoverability:
| Where the seed lives | What protects it | Pick it when | Fails when |
|---|---|---|---|
| Hardware-backed keystore (Android Keystore/StrongBox; iOS Keychain holding a Secure-Enclave wrapping key) | Key material stays in the TEE/SE; unlock gated by biometrics or device credential | The device has a TEE/SE and you sign on-device | iOS SE only holds P-256, so you wrap the secp256k1 seed with an SE key rather than storing it directly; factory reset or device migration loses it unless you have a separate recovery path |
| OS keystore, software-backed (Android Keystore, iOS Keychain without SE) | Encrypted at rest under the device credential | No TEE, or you need an exportable backup | Rooted/jailbroken device, or Android auto-backup lifting the file off the device |
| App-encrypted prefs (AES-GCM under a passphrase-derived key) | Only your own KDF | You must restore on a new device with no OS backup | Weak passphrase, memory scrape, rooted device |
Deciding criteria, in order: does the device have a TEE/SE, must the user restore on a new phone, and do you sign on-device at all. If the answer to the last is no, a custodial or MPC design removes the seed from the device entirely and beats every row above.
Concrete failure modes and how you catch them: a crash reporter or analytics SDK serialising app state ships the seed string. Catch it with a secret-scanning CI rule plus a runtime log scrubber, not a policy. Android auto-backup includes shared_prefs by default: set android:allowBackup="false" or exclude the file. A screenshot of the recovery-phrase screen: set FLAG_SECURE. A seed held in a plain String survives in the heap after use: hold it in a byte array you zero, and accept that this only narrows the window.
The words are the key to every index; the path only names which child. Store the seed where it cannot be read back, and treat any log line containing it as a breach.
Curated: · Written: · Reviewed:
Q&A-20Why sign EIP-712 structs instead of a raw keccak of concatenated fields, and what must the domain separator include?
What a strong candidate says first
Sign the EIP-712 digest, not keccak256(abi.encode(...)) of the fields, because the signature has to be bound to where it is valid, not just what it says. EIP-712 wraps the struct hash in a domain separator behind a \x19\x01 prefix:
digest = keccak256(0x1901 ‖ domainSeparator ‖ structHash)
structHash = keccak256(typeHash ‖ abi.encode(field1, field2, ...))
typeHash = keccak256("Transfer(address to,uint256 amount)")
The \x19 prefix makes the payload un-parseable as an RLP transaction, so a signature can never be replayed as a transaction. The domain separator is what stops replay across chains and contracts.
What the domain separator must include
bytes32 domainSeparator = keccak256(abi.encode(
keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"),
keccak256(bytes("Marketplace")),
keccak256(bytes("1")),
block.chainid,
address(this)
));
The type string must list exactly the fields you encode, in the same order. name, version and salt are optional; chainId and verifyingContract are the two that carry replay protection.
| Field | Example | Replay it stops |
|---|---|---|
| chainId | 1 | same contract address on another chain |
| verifyingContract | 0x7a25… | a clone or fork of the contract |
| version | "1" | a v2 with the same struct types |
| name | "Marketplace" | a different app reusing your types |
Alternatives, and when plain hashing is fine
- EIP-191
personal_sign("\x19Ethereum Signed Message:\n" + len + msg): no chainId, no contract. Fine for off-chain auth where the server is the only verifier and the message carries a nonce: a login challenge, say. Wrong for anything a contract acts on, because it replays on every chain and every contract that accepts it. - Hand-rolled domain hash:
keccak256(abi.encode(chainId, address(this), nonce, ...))gives the same replay protection. You lose the standard: wallets can't render it,eth_signTypedData_v4tooling doesn't apply, and a reviewer can't diff the type string against the struct. - Plain
keccak256of concatenated fields: acceptable only when the signature never crosses a trust boundary. A merkle leaf, or an off-chain message with a nonce and a single verifier. The moment a contract verifies it, you need the domain.
The cost of EIP-712 is wallet UX and plumbing: the dapp ships the full typed-data JSON, the wallet must support eth_signTypedData_v4, and users see structured fields instead of a hex blob. That's the point, but it is more to get wrong.
Failure mode: stale cached separator
Caching domainSeparator in an immutable at deploy is common and wrong across a fork or a CREATE2 redeploy to a new chain: block.chainid changes, the cached value doesn't, and signatures made for the new chain fail, or old-chain signatures verify. Compute it at runtime, or invalidate on chainid change. EIP-5267 exposes it via eip712Domain() so verifiers can read it.
How to check it
Change verifyingContract by one byte and assert ecrecover returns a different address; sign the same struct with chainId 1 and 5 and assert the digests differ. That is the whole test.
Curated: · Written: · Reviewed:
Q&A-21A user signed a permit for token A. Why must token B reject that signature even if the owner address matches?
The 90-second answer
A permit signature commits to a digest, and the digest commits to the verifying contract. Token B recomputes the digest with its own address in the domain, gets different bytes, and ecrecover over those bytes returns an address that is not owner (barring a negligible-probability collision). B's check recovered == owner fails and it reverts. The owner argument matching is irrelevant: the signature never authorized anything for B.
Two pieces of per-contract state make that true:
DOMAIN_SEPARATORincludesverifyingContract = address(this)andchainId.nonces[owner]lives in each token's own storage.
So a permit for A is not a receipt you can present at B.
Mechanism
EIP-712 digest: keccak256("\x19\x01" || domainSeparator || hashStruct(Permit)), where domainSeparator = keccak256(abi.encode(TYPE_HASH, keccak256(bytes(name)), keccak256(bytes(version)), chainId, verifyingContract, salt)).
EIP-2612 permit message: owner, spender, value, nonce, deadline. Change any field, including verifyingContract, and the digest changes, so the recovered signer changes.
Alternatives, and when each applies
| Scoping mechanism | What binds the signature | Use when |
|---|---|---|
| Per-contract domain (EIP-2612) | verifyingContract + chainId | Standard token approvals; wallet support is universal |
Domain salt | Extra bytes32 inside the domain | One contract hosts several signing contexts, or a factory wants distinct domains without new addresses |
| Permit2 (one canonical contract) | Single domain; every token approved to it; nonce is a bitmap | Many tokens, one approval tx, batch transfers, out-of-order nonces |
| Off-chain nonce registry | Relayer marks the digest used | Gasless relayers where the on-chain check is too expensive and a trusted relayer is acceptable |
| ERC-1271 | isValidSignature call to the wallet | Smart-contract wallets and multisigs: no ecrecover |
Criteria: if you own the token and want zero extra infrastructure, EIP-2612. If you want one approval covering every token, Permit2. If the signer is a contract, ERC-1271. Off-chain nonces only when the on-chain path is unaffordable and the trust assumption is tolerable.
Failure modes
- Clones sharing a domain. A factory that hardcodes the separator, or a proxy whose implementation caches it, gives two addresses the same
verifyingContractbytes. Then the digest matches and B accepts. Detect: asserta.DOMAIN_SEPARATOR() != b.DOMAIN_SEPARATOR()in a test, and checkchainIdis read live rather than baked in at deploy (a fork replays otherwise). - Nonce bumped after the external effect. Reentrancy lets the same digest be spent twice. Detect: a test that re-enters
permitfrom the spender's hook. - Unbounded
deadline. A signature withdeadline = type(uint256).maxis valid forever. Detect: assertpermitreverts after the deadline passes. ecrecoverreturningaddress(0)on a malformed signature. Code that treats zero as "no signature" and skips the nonce bump is exploitable.
Worked check (Foundry, Solidity 0.8.24, OpenZeppelin 5.x)
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {Test} from "forge-std/Test.sol";
import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol";
import {ERC20Permit} from "@openzeppelin/contracts/token/ERC20/extensions/ERC20Permit.sol";
contract Token is ERC20, ERC20Permit {
constructor(string memory n) ERC20(n, "T") ERC20Permit(n) {}
}
contract CrossContractReplay is Test {
bytes32 constant PERMIT_TYPEHASH =
keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)");
Token a = new Token("A");
Token b = new Token("B");
uint256 pk = 0xA11CE;
address owner = vm.addr(pk);
address spender = address(0xBEEF);
function test_permitForAIsRejectedByB() public {
assertTrue(a.DOMAIN_SEPARATOR() != b.DOMAIN_SEPARATOR());
uint256 deadline = block.timestamp + 1 hours;
bytes32 digestA = keccak256(
abi.encodePacked(
"\x19\x01",
a.DOMAIN_SEPARATOR(),
keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, 1e18, a.nonces(owner), deadline))
)
);
(uint8 v, bytes32 r, bytes32 s) = vm.sign(pk, digestA);
a.permit(owner, spender, 1e18, deadline, v, r, s);
assertEq(a.nonces(owner), 1);
assertEq(a.allowance(owner, spender), 1e18);
vm.expectRevert(); // ERC2612InvalidSigner(recovered, owner)
b.permit(owner, spender, 1e18, deadline, v, r, s);
assertEq(b.nonces(owner), 0);
}
}
Trace:
a.DOMAIN_SEPARATOR()=keccak256(abi.encode(TYPE_HASH, keccak256("A"), keccak256("1"), 31337, address(a), 0)). B's differs only in the address field, so the two 32-byte values differ.vm.sign(pk, digestA)yields(v, r, s)that recover toownerfordigestA.a.permit(...)recomputesdigestA,ecrecoverreturnsowner,nonces[owner] == 0matches, deadline holds, so allowance becomes1e18andnonces[owner]becomes1.b.permit(...)recomputesdigestB,ecrecover(digestB, v, r, s)returns an address that is notowner, so it reverts withERC2612InvalidSigner. B'snonces[owner]is still0.
Step 4 is the point: B's nonce was never what stopped it. The domain was. The revert selector depends on the OpenZeppelin version; the assertion that matters is that B's nonce is untouched.
Curated: · Written: · Reviewed:
Q&A-23Why is if (tx.origin == owner) a phishing primitive, and what should authorize instead?
60 seconds
tx.origin is the EOA that signed the transaction, and it holds the same value in every frame. msg.sender is the caller of the current frame. require(tx.origin == owner) asks "did the owner sign this transaction?" rather than "is the owner calling me now?", so every contract the owner calls during that transaction borrows the owner's authority. Authorize with msg.sender. The safest rule for tx.origin is to leave it out of anything security-relevant.
The primitive
The attacker needs no key. The owner signs one transaction to an attacker-controlled contract - a fake mint, a "claim", anything the wallet previews as harmless - and that contract calls the vault from inside the same transaction.
// Solidity 0.8.24
contract Vault {
address public owner;
function withdraw(address to, uint256 amount) external {
require(tx.origin == owner, "not owner"); // the bug
(bool ok, ) = to.call{value: amount}("");
require(ok, "send failed");
}
}
contract Claim { // attacker-controlled
Vault immutable vault;
constructor(Vault v) { vault = v; }
receive() external payable {}
function claim() external { // what the phishing page asks the owner to sign
vault.withdraw(address(this), 62 ether);
}
function sweep() external { // separate tx, sent by the attacker EOA
(bool ok, ) = payable(msg.sender).call{value: address(this).balance}("");
require(ok, "sweep failed");
}
}
Amounts are hypothetical; suppose the vault holds 62 ETH. Frame by frame:
| # | Frame | msg.sender | tx.origin | tx.origin == owner |
|---|---|---|---|---|
| 1 | Claim.claim(), called by the owner | owner EOA | owner EOA | true, but unused |
| 2 | Vault.withdraw(), called by Claim | Claim | owner EOA | true - 62 ETH leaves the vault |
| 3 | Claim.sweep(), a later tx | attacker EOA | attacker EOA | n/a |
Frame 2 is the entire attack. The vault sees the owner as the origin, so the require passes even though its direct caller is the attacker's contract. Frame 1 does not have to touch the vault at all: any call the owner makes into the attacker's contract starts the chain.
What to authorize instead
| Caller you want to admit | Check |
|---|---|
| EOA owner | require(msg.sender == owner) |
| Safe / multisig wallet | msg.sender == wallet - the wallet is a contract and calls the target directly |
| Smart account on ERC-4337 | during validateUserOp the caller is the EntryPoint; during execution the account calls you, so msg.sender is the account address |
| Off-chain signed approval | verify the signature over (chain id, contract, nonce, params), and for contract signers use ERC-1271 isValidSignature |
| Gasless relayer (EIP-2771) | accept the appended sender only when msg.sender == trustedForwarder; otherwise recover the signer from the payload yourself |
The other misuse is tx.origin == msg.sender as a "reject contract callers" filter. An ERC-4337 account is a contract, so the filter locks out every smart-wallet user; with a relayer you see the relayer's EOA instead of the user's.
Failure modes, and how I would catch them
tx.originin an auth check: any contract the owner interacts with can drain the vault. This is catchable statically - Solidity's documentation advises against usingtx.originfor authorization, and Slither ships atx-origindetector. I would also add a CI grep that fails the build ontx.originoutside comments.tx.origin == msg.senderas a contract filter: it fails closed for 4337 accounts. The symptom is a revert that only smart-wallet users hit; reproduce it with a fork test that calls the function through a one-line helper contract instead of from an EOA.- Neither check defends against the phishing page. A plain ERC-20
approvedrain never touchestx.origin; all the vault controls is whether it hands over authority it never meant to give.
The answer: msg.sender for authorization, ERC-1271 or account-aware handling for contract signers, and tx.origin nowhere.
Curated: · Written: · Reviewed:
Q&A-24A sequencer signs 2_000 batches a day. Where should the private key live, and what policy sits around it?
Short answer: the key lives in a non-exportable HSM or a cloud KMS asymmetric key, behind a signer service that enforces a policy on every payload. The sequencer host never holds key material. And the key that sequences is not the key that pauses or upgrades.
Why the box is chosen by blast radius, not throughput
2,000 batches/day is 0.023 TPS: one signature every 43 seconds. Even a 10x burst is 0.23 TPS. A network-attached signer adds single-digit to tens of milliseconds per call; that is noise against a 43-second budget. So latency does not force a local key, and "we need it on the host for speed" is not a real argument at this rate. What forces the design is what a stolen key can do.
A sequencer key can only post batches to one inbox contract. That is a bounded blast radius: an attacker can post garbage batches, which the verifier rejects, and the worst case is a stalled chain. An upgrade key can replace the verifier. Those are different risk classes and must not share custody.
Custody and policy
| Role | Signs/day | Custody | Constraint |
|---|---|---|---|
| batch signer | ~2,000 | HSM (FIPS 140-3 L3) or cloud KMS, non-exportable | target + selector allowlist, value == 0, rate cap |
| pause | 0–2 | 3-of-5 multisig, keys on hardware wallets | no timelock; must be fast |
| upgrade | 0–1 | 4-of-7 multisig + 48h timelock | timelock is the real control |
AWS KMS (ECC_SECG_P256K1) and GCP KMS (EC_SIGN_SECP256K1_SHA256) both sign secp256k1; confirm the key spec and region before committing. A local HSM removes the network dependency and the vendor-trust question at the cost of your own HA and firmware patching.
The signer service is where the policy actually lives
# signer service, Python 3.12 — runs next to the key, not on the sequencer host
ALLOWED_TARGETS = {"0x<batchInbox>"}
ALLOWED_SELECTORS = {"0x<commitBatch>"}
def may_sign(tx) -> bool:
if tx.to not in ALLOWED_TARGETS: return False
if tx.selector not in ALLOWED_SELECTORS: return False
if tx.value != 0: return False
if tx.gas > 500_000: return False
if not monotonic_nonce(tx): return False
return True
The sequencer sends an unsigned payload; the signer validates, signs, and appends {payload_hash, decision, timestamp} to an append-only log. The key is never exported, so a compromised sequencer host yields at most the ability to request signatures the policy already permits.
Failure modes and how you see them
- Key on the sequencer host (env var, config file, or a KMS-encrypted blob the host can decrypt): one RCE is a full key compromise. Detect by asserting the key is non-exportable and that no process outside the signer can call the signing API.
- Allowlist drift: a governance change moves the inbox and someone widens the allowlist to
*. Detect with a diff alert on the policy file and a canary sign that must fail. - Sign-rate anomaly: a replay or a runaway loop. Alert at 2x the trailing 7-day baseline; the daily cap is the hard stop.
- Rotation that breaks the chain: rotating the sequencer key requires an on-chain governance tx to authorize the new signer, so the rotation cadence is bounded by governance latency, not by a calendar. 90 days is a reasonable default; a personnel change is a trigger regardless.
Alternatives and when not to use them
Threshold signing (2-of-3 across independent signer nodes, no single key) removes the single point of compromise but adds coordination latency and a much harder key-ceremony story. For a 0.023 TPS sequencer the HSM/KMS path is simpler and sufficient. Do not add a fallback hot key for KMS outages: a stalled sequencer that queues batches is recoverable; a fallback key is the incident.
Curated: · Written: · Reviewed:
Q&A-32When does uint256 a + b revert in Solidity 0.8, and when can it still wrap?
Core answer. In Solidity 0.8.x, a + b on two uint256 values reverts when the mathematical sum exceeds type(uint256).max (2^256 − 1). The revert is a Panic(0x11), arithmetic overflow/underflow, not a require string. It still wraps in three places: inside an unchecked { } block, through an explicit narrowing cast such as uint8(x), and inside inline assembly (add(a, b)), which never had checks.
Why it behaves that way. 0.8.0 made the compiler emit overflow checks around +, -, * and unary - for every integer type. unchecked suppresses exactly those checks for the statements it encloses. Casts are a separate mechanism: converting uint256 to uint8 is defined as keeping the low 8 bits, so it truncates instead of reverting. The compiler inserts no range check on an explicit conversion.
// Solidity 0.8.x
uint256 x = type(uint256).max; // 2**256 - 1
x + 1; // reverts: Panic(0x11)
unchecked { x + 1; } // 0
unchecked { x / 0; } // still reverts: Panic(0x12)
uint8(uint256(300)); // 44 (300 = 1*256 + 44)
uint8(uint256(256)); // 0
uint8(uint256(255)); // 255
| Expression | 0.8 default | inside unchecked |
|---|---|---|
a + b > max | revert Panic(0x11) | wraps mod 2^256 |
a - b < 0 | revert Panic(0x11) | wraps mod 2^256 |
a * b > max | revert Panic(0x11) | wraps mod 2^256 |
a / 0 | revert Panic(0x12) | revert Panic(0x12) |
Failure modes and how to catch them.
- Raw downcast truncation. A value held in
uint256and cast touint8silently wraps at 256: a fee of 300 becomes 44. Fuzz the boundaries (255, 256, 257) or use OpenZeppelinSafeCast.toUint8, which reverts when the value exceeds 255. uncheckedwith an unproven bound. It is safe only when you can prove the bound, e.g. a loop counter bounded byarray.length. If the bound depends on external input, the wrap is a bug, not an optimisation.- Inline assembly.
assembly { r := add(a, b) }wraps with no panic; the compiler cannot check it. uncheckedis not a blanket off-switch. Division by zero (Panic(0x12)) and array out-of-bounds (Panic(0x32)) still revert inside it.- Pragma, not compiler. A file declaring
pragma solidity ^0.7.0compiles with 0.7.x, where+wraps silently. The pragma decides the semantics, not the compiler binary you happen to invoke.
So the default is checked; unchecked, narrowing casts and assembly are the remaining doors through which a uint256 addition can still wrap.
Curated: · Written: · Reviewed:
Q&A-34Why can uint256 x = 256; uint8(x) equal 0 in 0.8 without a revert, and what helper do you use instead?
The 60-second answer
Solidity 0.8's overflow checks are attached to arithmetic operators (+, -, *, **, unary -, ++, --) not to explicit type conversions. uint8(x) on a runtime uint256 is a truncating cast: it keeps the low 8 bits, i.e. x mod 256. 256 mod 256 == 0, so you get 0 and no revert. The compiler emits no range check for the cast.
The helper is OpenZeppelin's SafeCast: x.toUint8() reverts when x > 255. Without the dependency, require(x <= type(uint8).max) immediately before the cast is equivalent.
What 0.8 checks, and what it does not
Checked: the arithmetic operators above, and unchecked { } switches them off. Not checked: explicit conversions (uint8(x), int128(y), address(z)), and inline assembly (and(x, 0xff) truncates just as silently). unchecked is irrelevant to casts: they truncate either way.
The literal case is different from the runtime case. uint8(256) written with a constant is a compile error since 0.8.0: the compiler folds the constant, sees it does not fit, and rejects it. The dangerous case is exactly the one in the question: a value the compiler cannot see, arriving from storage, calldata, or an oracle. Values that arrive as an external uint8 parameter are range-checked by the ABI decoder, so the exposure is internal casts from wider types.
Code
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
import {SafeCast} from "@openzeppelin/contracts/utils/math/SafeCast.sol";
contract Narrow {
using SafeCast for uint256;
function truncating(uint256 x) external pure returns (uint8) {
return uint8(x); // x mod 256, never reverts
}
function checked(uint256 x) external pure returns (uint8) {
return x.toUint8(); // reverts if x > 255
}
function manual(uint256 x) external pure returns (uint8) {
require(x <= type(uint8).max, "narrow: overflow");
return uint8(x);
}
}
Foundry test pinning both behaviours:
function testTruncates() public {
assertEq(narrow.truncating(255), 255);
assertEq(narrow.truncating(256), 0);
assertEq(narrow.truncating(511), 255);
}
function testCheckedReverts() public {
vm.expectRevert(
abi.encodeWithSignature("SafeCastOverflowedUintDowncast(uint8,uint256)", uint8(8), uint256(256))
);
narrow.checked(256);
}
OpenZeppelin Contracts 5.x raises the custom error SafeCastOverflowedUintDowncast(uint8 bits, uint256 value); 4.x reverted with the string SafeCast: value doesn't fit in 8 bits.
Expression (x = uint256(256)) | Result |
|---|---|
uint8(x) | 0 |
uint8(255) | 255 |
uint8(511) | 255 |
SafeCast.toUint8(x) | revert |
uint8(256) (literal) | compile error |
When narrowing is worth it
uint8 does not save gas in memory or on the stack: every value occupies a full 32-byte slot regardless of declared width. Narrowing pays off in storage packing (four uint64 fields share one 32-byte slot) and in ABI/interface compatibility. SafeCast costs one comparison and a revert branch; in a hot loop, hoist the check out of the loop or keep the wider type.
Failure modes
Truncation bites wherever a value can exceed the bound: oracle answers (int256), token amounts, timestamps, sqrtPriceX96 (uint160). Worked arithmetic for an 18-decimal token cast to uint64: 2^64 - 1 wei is 18.4467 tokens, so a 20-token balance (2e19 wei) becomes 2e19 - 2^64 = 1553255926290448384 wei, or 1.5533 tokens. 92% of the balance gone, no revert, no event.
Detection: fuzz the full uint256 range and assert the checked path reverts for x > 255; grep the codebase for raw downcasts (uint8(, uint128() and require each one to be justified; add an invariant that the sum of balances equals totalSupply so a truncated credit shows up as a broken invariant rather than a silent loss.
Curated: · Written: · Reviewed:
Q&A-33A loop does i++ to n where n is calldata length. Where is unchecked justified, and what number still needs a check?
The 60-second answer. unchecked is justified on the loop counter increment, and only there. The number that still needs a check is n (not as a counter bound, but wherever you use it to index or size something else) plus every accumulator the loop touches.
Why the counter is safe. Solidity 0.8.0+ reverts on overflow by default; unchecked { ++i; } removes that check. Here it is provably redundant. At the moment ++i runs, the loop guard i < n just held, so i <= n - 1. n is a uint256, so n <= 2^256 - 1, hence i <= 2^256 - 2 and i + 1 <= 2^256 - 1 = type(uint256).max. The increment cannot wrap. The safety comes from the guard, not from n being small in practice: n can be 2^256 - 1 and the argument still holds.
// Solidity 0.8.x
function sum(uint256[] calldata xs) external pure returns (uint256 total) {
uint256 n = xs.length;
for (uint256 i; i < n;) {
total += xs[i]; // checked: user-supplied values
unchecked { ++i; } // safe: guard proved i < n
}
}
Trace with xs = [1, 2, 3], n = 3: i=0 -> total=1, ++i->1; i=1 -> total=3, ++i->2; i=2 -> total=6, ++i->3; i=3, 3 < 3 false, exit. Returns 6. At each ++i, i <= 2, so i+1 <= 3.
What still needs a check.
total += xs[i]: a sum of user input. Leave it checked; it can overflow and revert, which is the correct behavior.nas an index bound.xs.lengthis safe forxs, but if the body indexes a different array, a fixed-sizeuint256[10]or a storage array, you must checkn <= thatArray.lengthyourself. Calldata length proves nothing about another container.nas a size. If you use it to allocate memory or drive a nested loop, that is a gas/DoS surface, not an overflow one.
Failure modes. Wrapping the whole function in unchecked to save gas removes the check on total and on any balance + amount; an overflow then wraps silently instead of reverting, and downstream accounting is wrong with no revert to catch it. Detection: a fuzzer or invariant test that feeds type(uint256).max values and asserts a revert; a gas snapshot showing the loop-only saving is small (tens of gas per iteration) versus the risk.
Assumptions. Solidity 0.8.0+ (checked arithmetic default, unchecked introduced there). On 0.7.x you would use SafeMath and the question does not arise.
Curated: · Written: · Reviewed:
Q&A-26Where does mapping(address => uint256) balances[user] live, and why is slot 0 of the contract not the answer?
Direct answer. balances is declared at some slot p in the contract's storage layout, but that slot holds no balances. The balance for a given user sits at keccak256(h(user) ‖ p): a 32-byte slot derived from the key and the declaration slot. Slot 0 is not the answer for two independent reasons: it is only the declaration slot if balances happens to be the first state variable, and even then slot 0 itself is empty. Reading it returns zero, not a balance.
Assumptions. Solidity ≥0.8, no proxy, no assembly writing to arbitrary slots. user is an address, a value type, so it is left-padded to 32 bytes before hashing.
Mechanism. The compiler assigns each state variable a slot in declaration order, base contracts first. A mapping declaration consumes exactly one full slot and is never packed with neighbours. That slot is never written: it is a marker, not storage. The value for key k lives at keccak256(h(k) ‖ p), where h left-pads value types to 32 bytes and leaves dynamic types (string, bytes) unpadded. Nested mappings hash again: keccak256(h(k2) ‖ keccak256(h(k1) ‖ p)).
So for balances at slot 3 and user 0xabc…:
slot = keccak256(abi.encode(user, uint256(3)))
That is a 32-byte number, almost certainly not 0, 1, 2 or 3. It is also not enumerable: there is no list of keys, so you cannot walk storage to sum balances.
Why slot 0 specifically is wrong. Two reasons, and interviewers usually want both:
- Layout is declaration-order dependent. If
owneris declared beforebalances,balancesis at slot 1, not 0. Inheritance shifts it further. - Even when
balancesis the first variable, slot 0 is the declaration slot, and it is empty.vm.load(addr, 0)returns 0. The balance is at the hash.
Alternatives and when to pick them.
- Read via the public getter
balances(user): correct, cheap, and the only option from another contract. Use it unless you are debugging layout. cast storage <addr> <slot>orforge inspect <C> storage-layout: for verifying the layout and reading raw slots. Use when the getter is missing or you suspect a proxy collision.EnumerableSetor an array of keys, if you need to iterate or sum. Costs an extra slot per key and gas on every write; only worth it if iteration is a real requirement.- A separate accounting contract: isolates balances from upgradeable layout risk.
Failure modes and detection.
- Zeroing the declaration slot to "clear balances" does nothing: the per-user slots stay. Detect by reading a known user's hashed slot before and after.
- Assuming
address(this).balanceequals the sum of the mapping: it does not; ETH balance and token accounting are separate. - Proxy storage collisions: a mapping's hashed slots can in principle land on a slot an upgrade uses. EIP-1967 avoids this by putting implementation and admin slots at pseudo-random positions.
How I'd verify. Compute the slot off-chain, then assert it in Foundry:
bytes32 slot = keccak256(abi.encode(user, uint256(3)));
assertEq(uint256(vm.load(address(c), slot)), 1e18);
Curated: · Written: · Reviewed:
Q&A-27A function takes bytes calldata payload. When do you copy to memory, and what is the gas mistake of always using storage?
The 90-second answer
bytes calldata payload is read-only input living in the transaction's input data. You never pay to receive it: reading a word is 3 gas (CALLDATALOAD). Copy to memory only when you must mutate the bytes or hand them to something that requires a memory argument (abi.decode, string.concat, most library calls). Write to storage only when the data must survive the transaction. The mistake is treating storage as a scratchpad: a 1 kB payload costs ~660,000 gas to persist versus ~200 gas to copy to memory.
Why the three locations cost what they do
- calldata: ABI-encoded in the tx input.
CALLDATALOADis 3 gas/word;CALLDATACOPYis 3 gas/word plus memory expansion. No copy unless you ask for one. - memory: a byte array expanded in 32-byte words; cost is
3*words + words²/512, cheap until you are into thousands of words. - storage:
SSTOREis 20,000 gas for a fresh nonzero slot, 2,900 gas to overwrite an existing nonzero slot (warm, EIP-2929). Abytesvalue also carries a length slot.
Worked example: 1,024-byte payload
1,024 bytes = 32 words.
| Location | Work | Gas |
|---|---|---|
| calldata | read in place | 0 copy |
| memory | CALLDATACOPY 32 words (96) + expansion (98) | ~200 |
| storage | 32 data slots + 1 length slot, all fresh | 33 × 20,000 = 660,000 |
Persisting is ~3,400× the memory copy. It is also a hard ceiling, not just a cost: mainnet's block gas limit is ~30M, so a 128 kB blob (4,096 slots ≈ 82M gas) cannot be written in a single transaction at all.
Code
pragma solidity 0.8.24;
contract Payload {
bytes public stored;
// No copy: calldata read in place.
function length(bytes calldata payload) external pure returns (uint256) {
return payload.length;
}
// One copy: mutation needs memory.
function zeroFirstByte(bytes calldata payload) external pure returns (bytes memory) {
bytes memory m = payload; // CALLDATACOPY
m[0] = 0x00;
return m;
}
// Persistent: one SSTORE per word + the length slot.
function persist(bytes calldata payload) external {
stored = payload;
}
}
When storage is right
When the value must outlive the call: a config, a commitment, a root. Then store a 32-byte keccak256(payload) commitment (one slot, 20,000 gas) instead of the raw blob, and keep the blob off-chain. That is the standard pattern for proofs and large payloads.
Failure mode and detection
The failure is a bytes storage write inside a function that only needs the data for the duration of the call: often added "for debugging" or "to be safe". It shows up as a gas spike proportional to payload size. Detect it with forge snapshot before/after changing the location keyword, or by reading the call trace for SSTORE opcodes where you expected none. On a 1 kB payload the delta is ~660k gas per call.
Passing calldata through
Internal functions can take calldata parameters (Solidity 0.6.9+), so you can thread the payload through helpers without copying. The copy is forced only by mutation or by a memory-typed API.
Curated: · Written: · Reviewed:
Q&A-25Two uint128s sit in one slot. What do you pack for, and what breaks if a later upgrade inserts a uint256 in between?
What you pack for
Gas, and only gas. The EVM charges per 32-byte slot, not per byte, so two uint128s in one slot means a fresh slot costs one zero→nonzero SSTORE (20,000 gas, 22,100 if the slot is cold under EIP-2929) instead of two, and reading both costs one SLOAD (2,100 cold, 100 warm) instead of two. Packing saves nothing on storage size unless it removes a whole slot.
The price is that the layout becomes an ABI. Solidity assigns slots in declaration order and packs greedily: a variable goes in the current slot if it fits in the remaining bytes, otherwise it starts a new one. Insert a uint256 between the two uint128s in an upgrade and everything after it shifts.
The trace
// V1
uint128 a; // slot 0, bytes 0..15
uint128 b; // slot 0, bytes 16..31
address owner; // slot 1, bytes 0..19
uint256 total; // slot 2
// V2 — fee inserted between a and b
uint128 a; // slot 0, bytes 0..15
uint256 fee; // slot 1 — 32 bytes don't fit in slot 0's remaining 16
uint128 b; // slot 2, bytes 0..15
address owner; // slot 3 — 20 bytes don't fit after b
uint256 total; // slot 4
Against V1's existing storage, V2 reads:
| Name | V1 slot | V2 slot | Value V2 sees |
|---|---|---|---|
a | 0 low | 0 low | correct |
b | 0 high | 2 low | 0: slot 2 was never written |
owner | 1 | 3 | address(0): slot 3 was never written |
total | 2 | 4 | 0 |
fee | — | 1 | the old owner address, reinterpreted as a uint256 |
No revert, no compiler warning. owner is now address(0), so every onlyOwner check passes for anyone; b reads as zero; and fee is whatever the old owner address was. The insert doesn't have to be a uint256 either: dropping a uint64 between two uint128s leaves 24 bytes used, so b still moves to the next slot.
What to do instead
- Append only. Never reorder, never widen or narrow a type, never insert.
- Reserve a gap:
uint256[50] __gap;as the last variable of each upgradeable base contract, shrunk by the number of slots each new variable consumes. - Or drop inheritance-order fragility: ERC-7201 namespaced storage,
keccak256(abi.encode(uint256(keccak256("myapp.main")) - 1)) & ~bytes32(uint256(0xff)), which is what OpenZeppelin Contracts v5 uses. - Keep proxy bookkeeping out of the packed region: EIP-1967 stores the implementation at
bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1). - Catch it in CI: diff the
storageLayoutJSON (forge inspect V2 storageLayout,solc --storage-layout, or the OpenZeppelin Upgrades plugin'supgradeProxycheck) and fail the build on any slot or offset change for an existing name.
When packing isn't worth it
If the two fields are written in different transactions, packing saves nothing on writes: you pay a full SSTORE for whichever one you touch. It only pays when they're read or written together. It also costs a few gas of masking (AND/SHR, 3 gas each) and a little bytecode. Uniswap V3's pool slot0 is the canonical case for packing: uint160 sqrtPriceX96, int24 tick, three uint16 counters, a uint8 and a bool. 248 bits in one slot, read together on every swap.
Curated: · Written: · Reviewed:
Q&A-28What stays the same under delegatecall, what changes, and why is that the proxy primitive?
What stays, what changes
delegatecall runs the callee's code inside the caller's context. Everything that answers "where am I" comes from the caller, not the callee:
| code executed | storage and address(this) | msg.sender | |
|---|---|---|---|
call | callee | callee | caller |
delegatecall | callee | caller | original caller |
staticcall | callee | callee, read-only | caller |
So under delegatecall the code changes and nothing else does: storage, address(this), balance and msg.sender are all the caller's. delegatecall has no value operand, so msg.value is inherited from the calling frame rather than sent: you cannot forward ETH with it.
That split is exactly what a proxy needs. The proxy holds the state and the address users trust; the implementation holds the logic. Upgrading means pointing the proxy at new code, and the state survives because it was never in the implementation to begin with.
The failure mode that defines the pattern
Naive layout:
contract Proxy {
address implementation; // slot 0
address admin; // slot 1
fallback() external payable {
(bool ok,) = implementation.delegatecall(msg.data);
require(ok);
}
}
contract Impl {
address owner; // slot 0
uint256 total; // slot 1
function initialize(address o) external { owner = o; }
}
Trace initialize(alice) through the proxy. The proxy delegatecalls, so owner = o compiles to SSTORE 0, alice, and slot 0 of the proxy is implementation. The pointer is now alice. The next user call delegatecalls into an address with no code, which returns success with empty returndata, so require(ok) passes and the proxy answers every call with nothing. Silent, total, and only recoverable through an upgrade path that does not go through the fallback.
EIP-1967 fixes this by putting proxy bookkeeping at slots derived from keccak256("eip1967.proxy.implementation") - 1, which no compiler will assign to a normal state variable.
The 2017 Parity multisig freeze came from the other direction: the library contract was callable directly, an attacker took ownership of it and called selfdestruct, and every wallet that delegatecalled into it was left with no code.
Which proxy, and when not to
- Transparent proxy: admin calls hit the proxy's own functions, everyone else is delegated. Simple, but every user call pays an extra SLOAD to check the caller, and the admin cannot use the dApp.
- UUPS: upgrade logic lives in the implementation. Cheaper per call, but an implementation that ships without
upgradeTobricks the proxy permanently. - Beacon: many proxies read the implementation from one beacon contract, so one transaction upgrades a whole fleet.
- Minimal clone (EIP-1167): ~45 bytes of runtime, immutable implementation. Deploy cost dominates; upgradeability is not the point.
- Diamond (EIP-2535): selector-routed facets, for when the interface has to grow past the 24 KB contract size limit.
Deciding criteria, in order: do you need upgradeability at all? If not, deploy immutable: it is cheaper and deletes an entire class of attack. If yes: one instance or many (beacon, clone), does the admin need to use the app (UUPS over transparent), and will the interface grow (diamond).
Do not reach for delegatecall when the callee is untrusted: it gets write access to your storage and can move your balance. Do not use it for pure computation: an internal library function is inlined, and an external one reached by call cannot touch your slots. And do not use it to "save gas" on a contract that never upgrades.
Curated: · Written: · Reviewed:
Q&A-29A transparent proxy stores the implementation at a random slot. Why did the first Solidity member still destroy a fork of it?
Two things in that question need pinning down first, because the answer turns on them.
EIP-1967 slots aren't random. The implementation pointer lives at keccak256("eip1967.proxy.implementation") - 1 = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc, and the admin at keccak256("eip1967.proxy.admin") - 1 = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103. Deterministic, reproducible, just far from slot 0 and unlikely to collide with app state. "First Solidity member" is the first state variable Solidity assigns, which is slot 0.
So the answer is: the pseudo-random slot protects the pointer. It does nothing for slot 0. Under delegatecall the implementation's code runs against the proxy's storage, and both contracts number their variables from 0. A fork that adds any state variable to the proxy (an admin, a reentrancy guard, a uint256 _status) puts it at slot 0, directly on top of the implementation's first variable. The fork's own first member is what collides.
Mechanism: Solidity assigns state variables to slots in declaration order starting at 0, packing where it can. delegatecall doesn't switch storage context: the callee reads and writes the caller's slots. OpenZeppelin's transparent proxy declares zero state variables for exactly this reason; impl, admin and beacon all live in EIP-1967 slots written in assembly. The moment a fork adds a normal variable, it reintroduces slot 0.
Worked trace. Forked proxy:
contract ForkedProxy {
address public admin; // slot 0 — the mistake
// impl pointer at the EIP-1967 slot, written in assembly
}
contract TokenV1 {
uint256 public totalSupply; // slot 0
mapping(address => uint256) balanceOf; // slot 1
}
| Step | Write | Slot 0 | admin reads as |
|---|---|---|---|
| deploy | proxy ctor: admin = 0x1111…1111 | 0x0000…1111 | 0x1111…1111 |
initialize() | impl: totalSupply = 1_000_000e18 | 0x0000…d3c21bcecceda1000000 | 0x0000…d3c21bcecceda1000000 |
upgradeTo(v2) | onlyAdmin check | unchanged | reverts: caller isn't admin |
The first initialize overwrote admin with the token supply. Nobody controls 0x00000000000000000000D3C21BCECCEDA1000000, so upgradeTo is dead and the fork is bricked on V1. If the implementation instead has a public function that writes slot 0 to an attacker-chosen value, the attacker becomes admin and upgrades to a malicious implementation: the takeover variant of the same bug.
Alternatives, and when each is right. A transparent proxy keeps the admin address from falling through to the implementation, at the cost of an admin check on every call; simple to reason about. UUPS (EIP-1822) moves upgrade logic into the implementation, so calls are cheaper and the proxy is smaller, but you must implement _authorizeUpgrade and you can brick by upgrading to an implementation that lacks upgradeTo. Minimal clones (EIP-1167) are a 45-byte proxy with no storage of its own, so this collision is impossible, but they're immutable. A beacon shares one implementation pointer across many proxies, which pays off when you have thousands of instances. Diamonds (EIP-2535) split logic across facets and add the most moving parts. A custom slot scheme for the pointer is essentially never justified; use EIP-1967. If you genuinely need proxy-level state, put it in a namespaced slot too, ERC-7201 derives one as keccak256(abi.encode(uint256(keccak256("erc7201:…")) - 1)) & ~0xff, never slot 0.
Detection: forge inspect ForkedProxy storage-layout should show zero variables; the OpenZeppelin upgrades plugin's validateUpgrade diffs layouts across versions; base contracts reserve uint256[50] __gap; and a fork test should assert admin is unchanged after the implementation writes its first variable.
The random slot was never the protection. Slot 0 was the exposure, and the fork's first variable is what landed on it.
Curated: · Written: · Reviewed:
Q&A-31Why does a proxy's implementation constructor not initialize the proxy's storage, and what race exists on initialize?
I would settle proxy constructors versus initializers against a counter-example first, so the clever opcode has to survive it.
Constructors run in the implementation's own context at deploy; the proxy's storage is still zeros. initialize() must be called via the proxy, once, with an initializer modifier.
Concretely, disable initializers in the impl constructor (_disableInitializers). Call initialize in the same tx as proxy deploy (or use a factory). Uninitialized proxies are takeovers: anyone becomes owner.
The reason for that specificity is a failure I have seen: A team deployed proxy then initialized 40 minutes later; an attacker initialized first as owner and swept 900 ETH of seed liquidity.
Same 40-minute gap.
| t | Proxy storage owner | Who |
|---|---|---|
| 0 min | 0x0 | uninitialized |
| 12 min | attacker | initialize() |
| 40 min | team tx reverts | too late |
I would not consider it settled without evidence: Trace the deploy tx: proxy bytecode, then delegatecall initialize in the same transaction; a separate tx is a bug.
Constructor writes the impl; initialize writes the proxy; do both atomically.
Curated: · Written: · Reviewed:
Q&A-30When do you pick UUPS over a transparent proxy, and what extra function must the implementation keep?
Pick UUPS when you deploy many proxies and control every implementation that will ever sit behind them; pick transparent when the upgrade path must survive a bad implementation.
UUPS moves the upgrade logic into the implementation, so the proxy is a thin ERC-1967 shell: cheap to deploy, and user calls pay nothing extra. Transparent keeps the upgrade logic in the proxy and routes admin calls to the proxy's own admin functions instead of delegating them, which costs an admin-slot check on every user call but means the proxy can always be upgraded even if the current implementation is broken.
Mechanism. Both delegate user calls to the implementation with delegatecall. Transparent additionally reads the ERC-1967 admin slot on every call to decide whether the caller is the admin; that SLOAD is roughly 2,100 gas cold and 100 warm, paid by every user call. UUPS skips it. The trade is deployment cost: the transparent proxy carries the upgrade code, so each proxy you deploy is larger; UUPS puts that code in the implementation, which you deploy once and point many proxies at.
The extra function. A UUPS implementation must keep upgradeToAndCall(address, bytes), inherited from UUPSUpgradeable, plus the _authorizeUpgrade(address) override that gates it, and proxiableUUID(), which returns the ERC-1967 implementation slot. In OpenZeppelin Contracts 5.x, upgradeTo was removed; upgradeToAndCall is the only upgrade entry point.
// OpenZeppelin Contracts 5.x, Solidity ^0.8.20
contract ImplV1 is Initializable, UUPSUpgradeable, OwnableUpgradeable {
constructor() { _disableInitializers(); }
function initialize(address owner_) external initializer {
__Ownable_init(owner_);
}
function _authorizeUpgrade(address newImpl) internal override onlyOwner {}
}
Trace of upgradeToAndCall(newImpl, "") on the proxy. The proxy delegatecalls into the implementation, which runs _authorizeUpgrade(newImpl), reverts unless onlyOwner passes, then ERC1967Utils.upgradeToAndCall staticcalls proxiableUUID() on newImpl and compares the result to the implementation slot. A mismatch, or a newImpl with no such function, reverts the whole transaction and the slot is never written. Only after the check passes does it write the new implementation address and delegatecall the init data.
Failure mode. Upgrade to an implementation that does not inherit UUPSUpgradeable, or whose _authorizeUpgrade reverts for every caller, and the proxy has no upgrade entry point left. State and funds are still there, but no future bug can be patched. This failure is unique to UUPS: transparent's upgrade logic lives in the proxy, so a bad implementation is recoverable.
Detection. Two tests. A positive one: upgradeToAndCall to a UUPS-compatible implementation changes the ERC-1967 implementation slot. A negative one: upgrading to a contract without proxiableUUID reverts with ERC1967InvalidImplementation and leaves the slot unchanged. Add a third asserting _authorizeUpgrade reverts for a non-owner.
| Pattern | Upgrade logic lives in | Per-user-call overhead | Bad implementation |
|---|---|---|---|
| transparent | proxy (+ ProxyAdmin) | admin-slot SLOAD (~2,100 gas cold) | recoverable; proxy still upgrades |
| UUPS | implementation | none | proxy can be frozen |
When not to use UUPS. If you cannot guarantee every future implementation inherits UUPSUpgradeable (several teams shipping implementations, or handing the proxy to a new codebase) transparent's proxy-resident upgrade path is the safer default. Same if you need the admin address to be unable to reach implementation functions, which transparent's admin routing gives you and UUPS does not.
Curated: · Written: · Reviewed:
Q&A-101Your V2 implementation inserts a new variable at the top of the inheritance chain. Walk me through what breaks in the proxy's storage, how a storage gap or ERC-7201 namespaced layout prevents it, and why an uninitialized implementation is a takeover risk.
Assume an upgradeable proxy: EIP-1967 implementation slot, Solidity 0.8.x, OpenZeppelin Upgrades. The proxy's storage is the implementation's storage: delegatecall runs the implementation's code against the proxy's slots. Three separate failure modes, one fix each.
1. Layout collision. The proxy has no layout of its own; it inherits whatever the implementation declares. If V2 inserts a variable before existing ones, or changes inheritance linearization, every slot after the insertion point is reinterpreted.
V1:
contract V1 {
address owner; // slot 0
uint256 totalSupply; // slot 1
mapping(address => uint256) balances; // slot 2 (seed)
}
V2 (bad: inserted version at the top):
contract V2 {
uint256 version; // slot 0 <-- new
address owner; // slot 1
uint256 totalSupply; // slot 2
mapping(address => uint256) balances; // slot 3 (seed)
}
After upgrade, owner reads slot 1, which held totalSupply = 1_000_000e18. That is a non-zero address the attacker does not control, so onlyOwner calls revert: the protocol is bricked. balances[user] now reads keccak256(user . 3) instead of keccak256(user . 2), so every balance reads zero. If the reinterpreted slot is attacker-writable: e.g. V2 inserts a mapping the attacker can write at the slot that used to hold owner: the collision escalates to a takeover.
2. Storage gap. Base contracts reserve slots so a new variable in the base consumes a gap slot instead of shifting derived storage:
contract Base {
uint256 public totalSupply;
uint256[50] private __gap; // reserve 50 slots
}
When Base adds uint256 public fee, it shrinks __gap to uint256[49]. Derived contracts' storage does not move. The arithmetic is exact: the gap must be reduced by the number of slots the new variable occupies, and a uint256 occupies one slot while a mapping or dynamic array occupies one seed slot. Forgetting to shrink the gap is the bug the compiler will not catch.
3. ERC-7201 namespaced storage. Instead of relying on declaration order, each contract's storage lives at a fixed, namespaced slot:
// keccak256(abi.encode(uint256(keccak256("erc7201:myapp.storage.Main")) - 1)) & ~bytes32(uint256(0xff))
bytes32 constant MAIN_STORAGE = 0x...;
struct MainStorage { address owner; uint256 totalSupply; mapping(address => uint256) balances; }
function _main() internal pure returns (MainStorage storage $) {
assembly { $.slot := MAIN_STORAGE }
}
Two contracts cannot collide because their slots are derived from distinct strings, and adding a variable to the struct does not move any other contract's storage. This is what OpenZeppelin 5.x uses for its own upgradeable contracts.
4. Uninitialized implementation. The implementation contract is deployed and left with initialized = false. Anyone can call initialize() on it directly, not through the proxy, become its owner, and then call any onlyOwner function that does selfdestruct or delegatecall. Pre-Cancun, selfdestruct removed the implementation's code and bricked every proxy pointing at it; that is the Parity wallet failure. Post-EIP-6780 (Cancun), selfdestruct only sends the balance and leaves the code, so the bricking risk is reduced, but the attacker can still drain any ETH held by the implementation and can grief any registry that treats the implementation as a live contract. The fix is one line in the implementation's constructor:
constructor() { _disableInitializers(); }
OpenZeppelin Initializable v4.6+ sets _initialized = type(uint8).max so initialize reverts on the implementation while the proxy's own storage is untouched.
Detection. forge inspect V2 storage-layout and diff against V1; the OZ Upgrades plugin's validateUpgrade fails on an unsafe layout change. A test that calls initialize() on the implementation directly and expects a revert catches the uninitialized case. Storage gaps are checked by asserting the gap size shrinks by exactly the slots added.
Curated: · Written: · Reviewed: —
Q&A-22What inputs determine a CREATE2 address, and why is "the address of the contract after it upgrades" the wrong answer?
The 90-second answer
A CREATE2 address is a pure function of four inputs, all fixed before any bytecode runs: the constant 0xff, the deploying address (the factory), a 32-byte salt, and keccak256(init_code). Nothing about the contract's later behaviour (storage, admin, implementation, or runtime bytecode) feeds into it.
"The address of the contract after it upgrades" is wrong because an upgrade does not change the address. In a proxy pattern the proxy is deployed once at a fixed address; upgrading means writing a new implementation address into the proxy's storage slot (EIP-1967) and letting delegatecall route to it. The proxy's address is unchanged, and the implementation lives at a different address entirely. The address was already determined at deploy time, before the constructor ran.
Mechanism
address = keccak256(0xff ++ deployer ++ salt ++ keccak256(init_code))[12:]
| Input | Bytes | Notes |
|---|---|---|
0xff | 1 | domain separator; keeps CREATE2 from colliding with CREATE, which hashes RLP(deployer, nonce) |
deployer | 20 | the contract executing the CREATE2 opcode |
salt | 32 | caller-chosen |
keccak256(init_code) | 32 | init_code is the creation bytecode with constructor arguments appended |
| result | last 20 of the keccak |
The hash is taken over init_code before execution. That is the whole point: constructor arguments change the address (they are part of init_code), but the runtime code the constructor returns does not, because it does not exist yet when the address is computed.
Why the upgrade answer is a category error
Deploy a proxy via CREATE2 at address A. Upgrade it: A's storage slot now points at implementation B. A is still A: same four inputs, same hash. B is a separate contract at a separate address, deployed by a normal CREATE. So "the address after it upgrades" conflates the proxy's address with the implementation's code; the address is fixed at deployment and never moves.
CREATE vs CREATE2
CREATE derives the address from the deployer's nonce, so the same factory produces different addresses on different chains and after any intervening deployment. CREATE2 is nonce-independent: the same (deployer, salt, init_code) yields the same address on every chain. That is what makes counterfactual addresses work (deterministic wallets, L2 bridges, state channels) you can commit to an address and fund it before the contract exists.
The cost: a given (deployer, salt, init_code) can be deployed only once; a second attempt reverts on the address collision. And anyone who knows the salt and init_code can deploy to the predicted address first. They would deploy the same contract, so this is only a problem if your init_code is malleable or you assumed you alone would deploy.
Failure mode
Hashing runtime bytecode instead of init_code produces a wrong prediction. Detect it by computing the address off-chain from the exact init_code bytes you pass to the factory and comparing against address(new C{salt: s}()).
Redeploy caveat
EIP-6780 (Cancun, live on mainnet since March 2024) changed SELFDESTRUCT: it no longer deletes code unless it runs in the same transaction as creation. So "deploy again to the same address after selfdestruct" is not a design you can rely on.
Curated: · Written: · Reviewed:
Q&A-55When do you use CREATE (nonce-based) versus CREATE2 (salt-based), and what address prediction fails if you pick wrong?
Use CREATE2 when the address has to be known before the contract exists: counterfactual wallets, pre-funded addresses, same-address-across-chains deployments, factory pairs. Use CREATE when nobody needs to predict the address: it is the default, it costs a little less, and its address depends on the deployer's nonce, so a destroyed contract cannot be resurrected at the same address.
Mechanism
// CREATE: address depends on deployer + nonce
address a = address(uint160(uint256(keccak256(
abi.encodePacked(bytes1(0xd6), bytes1(0x94), deployer, nonce)
))));
// CREATE2: address depends on deployer + salt + keccak(initcode)
address b = address(uint160(uint256(keccak256(
abi.encodePacked(bytes1(0xff), deployer, salt, keccak256(initcode))
))));
Both opcodes increment the deployer's nonce; only CREATE's address reads it. CREATE2's address is fixed the moment the initcode is fixed, and constructor arguments are appended to the initcode, so changing an argument or the compiler version moves the address.
Trade-offs
| CREATE | CREATE2 | |
|---|---|---|
| Address known before deploy | no | yes |
| Extra gas | — | 6 gas per 32-byte word of initcode (EIP-1014) |
| Address depends on | deployer nonce | salt + initcode hash |
| Redeploy after selfdestruct | new address | same address, if the salt is reused |
| Can pre-fund the address | no | yes |
The gas delta is small: a 1 KB initcode costs 32 words × 6 = 192 gas more, a 24 KB initcode 4,608 gas. That is not the reason to pick one; the address property is.
Failure modes
Nonce drift with CREATE. A deployer key used on several chains has an independent nonce per chain, and any mined transaction, including one that reverts, consumes a nonce. A "same address everywhere" plan built on CREATE breaks the first time one chain's nonce differs by one:
| Chain | deployer nonce | CREATE address |
|---|---|---|
| 1 | 4 | 0x…a1 |
| 10 | 5 (one reverted tx) | 0x…b7 |
| CREATE2, salt=0x01, same initcode | any | 0x…c3 on both |
Salt collision. CREATE2 reverts if the target address already has code. A factory that reuses a salt without tracking it bricks that deployment path.
Metamorphic redeploy. Same salt plus same initcode gives the same address, but the runtime code can differ if the initcode is not self-contained: for example it copies runtime code from an external contract the attacker controls. On Ethereum mainnet, EIP-6780 (Dencun, March 2024) means SELFDESTRUCT no longer deletes code unless the contract was created in the same transaction, which closes the classic version of this. On EVM chains that have not adopted EIP-6780 it is still open. If a contract must be destroyable and redeployable, CREATE's nonce-derived address avoids the whole class.
Initcode coupling. CREATE2 addresses are only as stable as the initcode hash. A counterfactual address computed against one compiler version is wrong after an upgrade that changes the bytecode.
When CREATE is the right call
One-off contracts, contracts whose address nobody needs to predict, and anything that must be destroyable without leaving a reusable address behind. Reach for CREATE2 only when something outside the chain (a user's counterfactual wallet, a cross-chain config, a pre-funded address) has to name the address before it exists.
Curated: · Written: · Reviewed:
Q&A-35Who receives the base fee after London, who receives the priority fee, and what is the user's maxFeePerGas cap?
Direct answer. After London (EIP-1559, block 12,965,000, 5 Aug 2021) the base fee is burned: it leaves ETH supply and no account receives it. The priority fee (tip) goes to the block proposer, paid to the feeRecipient address the proposer sets for that block. The user's cap is maxFeePerGas, a per-gas ceiling; the price actually paid is min(maxFeePerGas, baseFee + maxPriorityFeePerGas).
Mechanism. Per gas:
effectiveGasPrice = min(maxFeePerGas, baseFee + maxPriorityFeePerGas)effectiveTip = effectiveGasPrice - baseFee = min(maxPriorityFeePerGas, maxFeePerGas - baseFee)- Proposer receives
effectiveTip * gasUsed; the protocol burnsbaseFee * gasUsed; the user is refunded(maxFeePerGas - effectiveGasPrice) * gasUsed.
A tx is only includable when maxFeePerGas >= baseFee. maxFeePerGas is per gas, so the worst-case total is maxFeePerGas * gasLimit.
Worked example: gasUsed = 21,000, baseFee = 30 gwei, maxPriorityFeePerGas = 2 gwei, maxFeePerGas = 40 gwei.
| Component | Computation | ETH |
|---|---|---|
| Burned | 21,000 × 30 gwei | 0.000630 |
| Proposer tip | 21,000 × 2 gwei | 0.000042 |
| User's cap | 21,000 × 40 gwei | 0.000840 |
| Refund | 21,000 × (40−32) gwei | 0.000168 |
| Actually paid | 21,000 × 32 gwei | 0.000672 |
Check: 0.000630 + 0.000042 = 0.000672, and 0.000840 − 0.000672 = 0.000168.
def effective_gas_price(base_fee, max_priority_fee, max_fee):
return min(max_fee, base_fee + max_priority_fee)
def tip(base_fee, max_priority_fee, max_fee):
return effective_gas_price(base_fee, max_priority_fee, max_fee) - base_fee
effective_gas_price(30, 2, 40) # 32
tip(30, 2, 40) # 2
Choosing maxFeePerGas. The base fee can rise up to 12.5% per block while blocks stay full. Headroom of 2× the current base fee survives ~6 consecutive full blocks before your tx becomes unincludable; 3× survives ~9. Too low and the tx sits in the mempool until the base fee falls below your cap: it is not dropped, just not mined. Setting it high costs nothing extra while the base fee is low, because you pay baseFee + tip, not maxFeePerGas; the exposure is only that a base-fee spike makes you pay more than you expected.
Choosing the tip. The tip is the only lever a proposer has to prefer your tx, since the base fee is burned regardless. Calm blocks clear at 1–2 gwei; NFT mints and liquidation cascades push tips to 50–500 gwei. A tip above maxFeePerGas - baseFee is silently capped to that difference, so a large tip with a tight maxFeePerGas does nothing.
Failure modes.
- Forwarding
baseFee * gasUsedto the proposer. A gas-station contract that kept the legacycoinbase.transfer(gasPrice * gasUsed)model overpays proposers by the base-fee share. On an 8.4M gas/day flow at 30 gwei base fee that is 0.252 ETH/day burned: 7.6 ETH over 30 days: sent to proposers by mistake. Detect it by comparing the fee-recipient balance delta per block againstsum(effectiveTip * gasUsed); the base fee must not appear in that delta. - Setting
maxFeePerGasbelow the current base fee. The tx is rejected at submission or stuck until the base fee drops; checketh_maxPriorityFeePerGasand recent base fees before signing. - Treating
maxFeePerGasas a total. It is per gas; multiply bygasLimitfor the worst case.
Curated: · Written: · Reviewed:
Q&A-36A tx with maxFeePerGas = 20 gwei sits pending while base fee is 25 gwei. Why will it never land, and how do you replace it?
The short version. The transaction is invalid for any block whose base fee is at or above its fee cap, so no tip can rescue it. Replace it with a transaction on the same nonce whose maxFeePerGas and maxPriorityFeePerGas are both higher: in geth, at least 10% higher on each.
Why it can't land. EIP-1559 makes maxFeePerGas a hard ceiling on what the sender will pay per gas, and the block's base fee is burned. A block may only include the transaction if maxFeePerGas >= baseFeePerGas. At base 25 and cap 20 that condition fails, and the priority fee is irrelevant: the effective tip is min(maxPriorityFeePerGas, maxFeePerGas - baseFeePerGas), which is negative here. The transaction sits in mempools, not in a block. It becomes includable the moment the base fee drops below 20 gwei: it is not permanently dead, just dead at this base fee.
Replacing it. Same nonce, higher fees. Geth's default --txpool.pricebump is 10%, and for a 1559 transaction it applies to both fields: bump only the tip and you get replacement transaction underpriced. Other clients have their own defaults, so check yours.
Size the bump for where the base fee is going, not for the 10% floor. Base fee moves at most ±12.5% per block. If base is 25 and blocks stay full, three blocks later it is 25 × 1.125³ ≈ 35.6 gwei. Add a 2 gwei tip and you want a cap near 38 gwei; 45 leaves headroom. A 10% bump to 22 gwei is accepted by the pool and still never mined.
| Tx | nonce | maxFee | base | outcome |
|---|---|---|---|---|
| A | 17 | 20 | 25 | invalid, sits in pool |
| B | 17 | 45 | 25 | replaces A, mines |
| C | 18 | 45 | 25 | waits: nonce 17 must clear first |
The alternatives, and when replacement is the wrong move.
- Wait it out. Base fee falls when blocks come in under target. From 25 gwei, two consecutive empty blocks give 25 × 0.875² ≈ 19.1 gwei, and the transaction becomes valid with a 0.9 gwei tip. Fine if the transaction is not urgent and demand is genuinely falling, but you are betting on other people's blocks, and if the spike persists you have lost the time for nothing.
- Cancel instead. Same nonce, 0-value self-transfer, same bump rules. Costs one gas payment but frees the nonce immediately and guarantees the original never executes. This is the right call when the original is a stale swap or an approval you no longer want.
- Don't replace at all if it is already gone. Nodes evict pooled transactions whose fee cap is far below the current base fee when the pool is under pressure. Check
eth_getTransactionByHashfirst; if it returns null there is nothing to replace, and you can simply send fresh at nonce 17.
Failure modes to watch. A replacement that bumps only one field is rejected outright. A replacement sent to a node that never held the original still works, but if the original is live in other pools you are in a fee race: the higher cap wins, so make the bump decisive rather than exactly 10%. And while nonce 17 is stuck, everything at 18 and up queues behind it; eth_getTransactionCount(addr, "pending") shows the gap, and those later transactions cannot mine until 17 clears.
Curated: · Written: · Reviewed:
Q&A-37Is blob gas the same market as EIP-1559 execution gas, and who pays the blob base fee?
Core answer (first 90 seconds). No. Blob gas and execution gas are two independent fee markets with two independent base fees, and both are burned. A blob-carrying transaction pays execution gas for the transaction itself (baseFee + priority fee) plus blobGasUsed × blobBaseFee. The blob base fee is paid by the transaction sender and burned; the proposer earns only the priority fee on execution gas, never a tip on blob gas. Blob gas is also not calldata: the EVM cannot read it (BLOBHASH returns only the versioned hash), and the sidecars are pruned after 4096 epochs, about 18 days.
Mechanism. Execution base fee comes from the parent block's gas used relative to its target. Blob base fee comes from excess_blob_gas, a running total of blob gas used above target, through fake_exponential:
blobBaseFee = fake_exponential(MIN_BLOB_GASPRICE, excess_blob_gas, BLOB_BASE_FEE_UPDATE_FRACTION)
At Cancun, MIN_BLOB_GASPRICE = 1 wei and BLOB_BASE_FEE_UPDATE_FRACTION = 3,338,477. The update fraction is a fork-dependent constant and has been changed by later forks. One blob is 131,072 blob gas (128 KiB usable). After BPO2, the second blob-parameter-only fork following Fusaka, mainnet targets 14 blobs per block with a 21-blob cap; clients carry these as configuration. Because the two base fees are driven by different state, they move independently: a quiet execution market can sit next to a spiking blob market.
Trade-offs: when blob DA is worth it. The question is not "are blobs cheaper" but which DA guarantee the rollup needs.
- Blobs: cheapest L1 DA per byte, secured by Ethereum consensus, but not EVM-readable and pruned after ~18 days. Right when the rollup derives state off-chain and needs L1 only for ordering and short-term DA.
- Calldata: 16 gas per nonzero byte, 4 per zero byte, permanent and EVM-readable. Right when an L1 contract must read the data (on-chain fraud proofs) or it must persist indefinitely.
- Off-chain DA (Celestia, EigenDA, validium): cheaper still, but adds a trust assumption outside Ethereum consensus. Right when the rollup's security model already accepts that committee, or cost dominates.
Deciding criteria: cost per byte, DA guarantee (L1 consensus vs external), EVM accessibility, retention window, and whether the proof system can verify KZG commitments on L1.
Failure modes. A batcher that budgets DA using execution base fee as a proxy underbids when the blob market spikes on its own. Detect it by monitoring excess_blob_gas and the derived blobBaseFee from the block header; alert when blobBaseFee exceeds a threshold such as 10× the 30-day median. Second: a fraud proof that needs blob data older than ~18 days cannot fetch it from L1. The rollup needs another DA source or a proof window shorter than the retention period.
Artefacts.
| Market | Measure | Burned? | Paid to |
|---|---|---|---|
| execution | baseFee × gasUsed | yes | burned |
| blob | blobBaseFee × blobGasUsed | yes | burned |
| priority tip | priorityFee × gasUsed | no | proposer |
Arithmetic trace with Cancun constants (integer results from the EIP-4844 fake_exponential):
- excess_blob_gas = 0 → blobBaseFee = 1 wei
- excess_blob_gas = 3,338,477 (one update fraction) → 2 wei
- excess_blob_gas = 6,676,954 (two update fractions) → 7 wei
The real-valued exponential would give e¹ ≈ 2.718 and e² ≈ 7.389; the integer routine floors. Burned in every case.
Hypothetical: a rollup budgeted DA as calldata at 4.2 gwei-equivalent and underpaid blob fees 8× during a 3-hour blob spike; 2,400 batches missed their target slot.
Self-assessment.
Key points a strong answer hits. (1) Two separate markets, two separate base fees, no shared price. (2) Both burned; the proposer gets no blob tip. (3) Blob base fee is a function of excess_blob_gas, not of execution base fee. (4) Blob data is not EVM-readable and is pruned at 4096 epochs. (5) The practical consequence: DA budgeting and monitoring must track the blob market on its own.
What interviewers look for. Whether you separate the two markets cleanly; whether you know the fee is burned and who pays it; whether you can name the retention window and EVM inaccessibility as the two properties that decide blob vs calldata; and whether you can reason about when off-chain DA is the right call rather than defaulting to "blobs are cheap".
Weak-answer patterns. "Blobs are just cheaper calldata": misses inaccessibility and pruning. Saying the proposer earns the blob fee. Deriving blob base fee from execution base fee. Claiming blob data is available forever. Quoting a blob price without saying it is per blob gas and fork-dependent.
Likely follow-ups. What happens to blob base fee when a block uses fewer blobs than target? (excess_blob_gas falls, fee decays toward 1 wei.) How does a rollup prove a blob was included? (KZG point-evaluation precompile at 0x0a, versioned hash from BLOBHASH.) Why is the update fraction a fork-dependent constant? What does 128 KiB cost as a blob vs as calldata at a given base fee?
Curated: · Written: · Reviewed:
Q&A-39Why can nonce 5 be pending on Ethereum and confirmed on an L2 for the same address, and how do you replace a stuck tx?
Short answer: the nonce is part of each chain's account state, not a property of the address. Ethereum mainnet and an L2 are separate state machines with separate mempools, so one key has two independent counters. Nonce 5 pending on mainnet says nothing about nonce 5 on Arbitrum: that chain might be at 42 and idle. To unstick a transaction you re-send from the same address, on the same chain, with the same nonce and a higher fee.
Why the counters diverge. An L2 sequencer accepts and confirms in seconds; the L1 mempool can hold a transaction for hours when its maxFeePerGas sits below the base fee. The explorer tick is per chain, so a green tick on Arbitrum and a pending nonce 5 on mainnet are both correct at the same time. Read eth_getTransactionCount(addr, "pending") on the RPC of the chain you actually care about: that returns the next nonce including queued transactions.
| Chain | latest | pending | State |
|---|---|---|---|
| Ethereum mainnet (1) | 5 | 6 | nonce 5 stuck, fee under base fee |
| Arbitrum One (42161) | 42 | 42 | nothing queued |
Replacement mechanics. Same address, same chain, same nonce, higher fee. Geth's default --txpool.pricebump is 10%, applied to both maxPriorityFeePerGas and maxFeePerGas for EIP-1559 transactions; bump only one and you get replacement transaction underpriced. A cancel is the same operation with a 0-value self-send. Whichever of the original and the replacement gets mined first consumes the nonce; the loser is rejected as nonce too low.
Trade-offs. Three real options:
- Speed up: same nonce, same calldata, higher fee. Keeps the original intent.
- Cancel: same nonce, 0 ETH to yourself, higher fee. Use when you no longer want the original to land.
- Wait, if
maxFeePerGasis above the base fee, the transaction mines when base fee drops. Cheapest, but a stuck nonce 5 blocks nonces 6, 7, … from that account on that chain, so anything you send afterwards queues behind it.
Replacement is the wrong move when eth_getTransactionReceipt already returns a receipt: the transaction is mined, and a replacement is rejected as nonce too low. It is also wrong on the other chain: sending on Polygon does not touch mainnet nonce 5. And if the account is a smart contract account (ERC-4337), the nonce is a 2D (key, sequence) value and the replacement rules differ.
Failure modes. A nonce gap stalls every later transaction from that account on that chain until it is filled. Geth evicts underpriced transactions after its default --txpool.lifetime of 3 hours, so the transaction can vanish from your node while still sitting in other nodes' mempools: it can still mine later, which is why you replace rather than assume it is gone. And a replacement sent on the wrong chain burns fee and changes nothing: a user told to "send 0 ETH to yourself to unstick" on Polygon spent real money while mainnet nonce 5 sat untouched for hours.
Worked example. Original: nonce 5, maxFeePerGas 30 gwei, maxPriorityFeePerGas 1.5 gwei. A valid replacement needs at least 33 gwei and 1.65 gwei (10% on both). Send 0 ETH to yourself at nonce 5 with 40 gwei / 2 gwei; if the original is still unmined, the replacement takes the nonce and the original becomes invalid. Confirm with eth_getTransactionReceipt on the same chain.
Curated: · Written: · Reviewed:
Q&A-40Why did address.transfer and send use a 2300 stipend, and why is that the wrong withdrawal pattern now?
The short answer. transfer and send forward exactly 2,300 gas to the recipient. That number was a reentrancy guard: 2,300 is enough to emit an event (LOG1 with one topic costs 750) but not enough to write storage (SSTORE is 20,000 for a fresh slot) or to make a nested call that could reenter. The guard was a bet that gas costs would never move. They moved twice, and the bet now breaks legitimate receivers.
Mechanism. transfer and send are the same call with different failure handling: send returns false on failure, transfer reverts. Both hardcode the stipend. A plain call{value: x}("") forwards the remaining gas minus 1/64 (the EIP-150 63/64 rule), so the receiver can do real work.
Why it broke. Two hard forks raised the cost of the operations a fallback typically does:
- EIP-150 (Tangerine Whistle, Oct 2016) raised CALL from 40 to 700 and SLOAD from 50 to 200.
- EIP-1884 (Istanbul, Dec 2019) raised SLOAD from 200 to 800 and BALANCE from 400 to 700.
- EIP-2929 (Berlin, Apr 2021) made a cold SLOAD 2,100.
A fallback that did three SLOADs cost 600 gas before Istanbul (fine under 2,300) and 2,400 after. Same contract, same code, now unpayable by transfer.
The pattern now. Pull payments: the contract credits a balance, the recipient calls withdraw(), and the contract sends with call{value:}. Checks-effects-interactions plus a reentrancy guard, not the stipend, is what stops reentrancy.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
contract Payout {
mapping(address => uint256) public owed;
uint256 private locked = 1;
modifier nonReentrant() {
require(locked == 1, "reentrant");
locked = 2;
_;
locked = 1;
}
function withdraw() external nonReentrant {
uint256 amt = owed[msg.sender];
require(amt != 0, "nothing owed");
owed[msg.sender] = 0; // effect before interaction
(bool ok, ) = payable(msg.sender).call{value: amt}("");
require(ok, "send failed");
}
}
Worked trace. A receiver whose receive() does one SSTORE (a deposit counter):
transfer: forwards 2,300. SSTORE 0→nonzero needs 20,000. Out of gas, the whole payout reverts.call{value:}: forwards remaining − 1/64. SSTORE succeeds, the receiver's counter increments,ok == true.
| Operation | Gas | Source |
|---|---|---|
| LOG1, 1 topic, 0 data | 750 | 375 + 375 |
| SSTORE 0→nonzero | 20,000 | |
| SSTORE nonzero→nonzero | 5,000 | |
| SLOAD (post-Istanbul) | 800 | EIP-1884 |
transfer/send forwarded | 2,300 | fixed |
call forwarded | remaining − 1/64 | EIP-150 |
Failure modes. The one that bites in production is a receiver that is itself a contract (a multisig, a contract wallet, a staking pool) whose fallback does more than 2,300 gas. The payout reverts and the funds sit in the sender until it is migrated. Detect it before shipping: a test that pays a receiver whose receive() writes storage, and a reentrancy test that the lock holds when the receiver calls back into withdraw().
What not to do. Do not keep transfer on the belief that the stipend is a safety feature; it is a fixed budget that no longer covers a normal fallback. Do not drop the reentrancy guard because call forwards everything: the guard is the protection now.
Curated: · Written: · Reviewed:
Q&A-41When does receive() run versus fallback(), and what happens if you only write fallback and someone sends empty calldata with ETH?
The dispatch rule. Solidity's generated dispatcher checks calldata length first, then the selector.
- Calldata is empty (0 bytes):
receive()runs if it exists. If there is noreceive(),fallback()runs if it exists and is payable. If neither, the call reverts. - Calldata is non-empty: the dispatcher matches the first 4 bytes against the function selectors. No match →
fallback(). Iffallback()is missing, or the call carriesmsg.value > 0and the target (includingfallback) is not payable, the call reverts.
The length check comes before any value check, so empty calldata routes to receive() even when msg.value == 0. receive() is not "the ETH function"; it is "the empty-calldata function."
Only a fallback, empty calldata + ETH. If the fallback is payable, it runs: msg.data.length == 0, msg.sig == 0x00000000, msg.value is the ETH, and the ETH is accepted. If the fallback is not payable, the call reverts and the ETH never lands: a non-payable fallback reverts on any call carrying value, empty calldata included.
| calldata | msg.value | receive()? | fallback()? | outcome |
|---|---|---|---|---|
| empty | > 0 | yes | — | receive() |
| empty | > 0 | no | payable | fallback() |
| empty | > 0 | no | non-payable | revert |
| empty | > 0 | no | none | revert |
| empty | 0 | yes | — | receive() |
| empty | 0 | no | any | fallback() |
| 4-byte, no match | 0 | — | any | fallback() |
| 4-byte, no match | > 0 | — | payable | fallback() |
| 4-byte, no match | > 0 | — | non-payable | revert |
| 4-byte, no match | any | — | none | revert |
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
contract Sink {
event Got(uint256 value, uint256 dataLen, bytes4 sig);
receive() external payable { emit Got(msg.value, msg.data.length, msg.sig); }
fallback() external payable { emit Got(msg.value, msg.data.length, msg.sig); }
}
Traced against solc 0.8.24:
sink.call{value: 1 ether}("")→ 0 bytes →receive()→Got(1000000000000000000, 0, 0x00000000).sink.call("")→ 0 bytes, 0 value →receive()→Got(0, 0, 0x00000000).sink.call(hex"deadbeef")→ 4 bytes, no match →fallback()→Got(0, 4, 0xdeadbeef).sink.call{value: 1 ether}(hex"deadbeef")→fallback()→Got(1000000000000000000, 4, 0xdeadbeef).
Trade-offs. receive() + fallback() is the clearest split: plain transfers take a path that cannot accidentally run selector logic, unknown selectors take another. A single payable fallback() (the pre-0.6 style, e.g. WETH9's function() public payable { deposit(); }) is fine when both cases do the same thing, but you must branch on msg.data.length == 0 when they differ, and any abi.decode(msg.data[0:4], ...) reverts on empty data. Upgradeable proxies (OpenZeppelin TransparentUpgradeableProxy, UUPS) put delegatecall in fallback() and forward raw calldata, so empty calldata + ETH delegatecalls into the implementation's receive()/fallback() in the proxy's storage context: a proxy that must hold ETH needs its fallback() payable or its own receive(). Deciding criteria: accept plain ETH → receive() (or payable fallback); need a catch-all for unknown selectors → fallback(); need to tell the two apart → receive() or branch on msg.data.length.
Failure modes. A non-payable fallback plus ETH reverts, so the sender's transfer/send fails with no state change. A selector-decoding fallback on empty data sees msg.sig == 0x00000000 and reverts on the msg.data[0:4] slice: visible as reverts on plain transfers only. .transfer()/.send() forward a 2300-gas stipend, so a receive() that writes storage or emits a data-carrying event can exceed it and revert the transfer; use call{value:} and check the return, or keep the receive path to a bare emit. And receive/fallback are external entry points: a payable fallback that forwards ETH or calls out before updating state is reentrant.
Curated: · Written: · Reviewed:
Q&A-42Order a withdraw that updates a balance and then calls the user. Where does the external call sit, and why?
Answer
State first, call last. In a withdraw that debits a balance and then pays the user, the external call is the final statement: after every storage write it depends on. That ordering is checks-effects-interactions (CEI): validate inputs, apply all state changes, then hand control to the outside world.
// Solidity 0.8.x
mapping(address => uint256) public balances;
function withdraw() external {
uint256 amount = balances[msg.sender]; // check
balances[msg.sender] = 0; // effect
(bool ok, ) = msg.sender.call{value: amount}(""); // interaction
require(ok, "eth transfer failed");
}
Trace the reentrancy: an attacker contract with 1 ETH deposited calls withdraw(). The effect zeroes balances[attacker] before the call. The call enters the attacker's receive(), which calls withdraw() again. On the re-entry, amount = balances[attacker] reads 0, so it sends 0 and returns. The attacker leaves with 1 ETH, not 2. Reverse the two lines, call before the write, and the re-entry reads the still-1-ETH balance and drains it.
Why the call must be last: call forwards all remaining gas, so the callee can run arbitrary code, including calling back into this contract. The 2300-gas stipend of transfer/send is not a fix: it breaks under gas repricing (EIP-1884 raised SLOAD to 800) and never protected state that was already stale.
Failure modes to name:
- Token hooks. ERC-777
tokensToSend/tokensReceivedand ERC-721onERC721Receivedare interactions. Any function that moves such a token and updates accounting must apply CEI around the transfer, not only around ETH sends. - Cross-function reentrancy. The callback re-enters a different function that reads the same balance. CEI per-function is not enough; the invariant is "no external call while any shared state is mid-update."
- Read-only reentrancy. A
viewfunction called during the callback returns the half-updated state, and integrators that price off it get a wrong number. This is why some protocols add a reentrancy guard that also blocks view functions.
A nonReentrant modifier is defense in depth, not a substitute for ordering: it costs an SSTORE and does not fix read-only reentrancy on its own.
One detail worth flagging: require(ok) reverts the whole withdrawal when the recipient's receive() reverts or runs out of gas. For a self-withdrawal that is harmless, but if the protocol pushes ETH to third parties or batches payouts, a reverting recipient becomes a denial-of-service. Prefer not reverting, leave the balance for a retry, or use a pull pattern where users claim funds themselves.
Detection: a Foundry test with an attacker contract that re-enters, plus an invariant test asserting total balances never exceed the contract's ETH. Slither's reentrancy detector catches the obvious ordering; it will not catch cross-function or read-only cases.
Curated: · Written: · Reviewed:
Q&A-51A function loops over recipients and does call{value: amounts[i]}. Why can summing amounts and checking == msg.value still fail, and what is the double-spend?
This is a place where an explorer green tick and a correct handling of msg.value in a loop are not the same event.
msg.value is constant for one call frame; a nested callback sees only ETH attached to that new call, not the outer msg.value. The double-spend is leftover credit or a remaining-value variable that is not zeroed before the external call.
Concretely, load msg.value into local remaining; subtract each send before the call; require remaining==0 at end; reentrancy lock. Do not re-read msg.value after a callback as if it were new money, and do not pay from a stored credit that is still nonzero.
The reason for that specificity is a failure I have seen: A splitter stored credit = msg.value, paid from credit, then reentered before credit was zeroed, paying 3× the 10 ETH sent ($90k) from the contract's idle balance.
10 ETH, three recipients.
| i | send | remaining |
|---|---|---|
| 0 | 2 | 8 |
| 1 | 3 | 5 |
| 2 | 5 | 0 |
| reenter | 10 again | bug if unlocked |
I would not consider it settled without evidence: Attacker receive() calls split again; balances must not go down by more than the original msg.value.
msg.value does not teleport into the callback; leftover credit does.
Curated: · Written: · Reviewed:
Q&A-43The token is ERC-777 or has a transfer hook. Why is a reentrancy lock on your only "withdraw" function not enough?
A lock on withdraw only stops reentrant withdraw calls. The hook fires on every transfer, so the attacker reenters a different, unlocked function (deposit, claim, harvest, redeem) that reads the vault's accounting while the in-flight transfer has left it stale. The lock protects one function; the invariant it is meant to protect spans all of them.
Mechanism
ERC-777 calls tokensToSend on the sender before balances move, and tokensReceived on the recipient after. ERC-20 has no such callback: that absence is the whole point of ERC-777. ERC-721/1155 have onERC721Received / onERC1155Received, which fire on the recipient after the transfer, so they are a weaker vector than tokensToSend.
So when your vault calls token.transferFrom(attacker, vault, amount) inside deposit, the attacker's tokensToSend runs while:
- the attacker still holds the tokens (their balance is not yet debited), and
- the vault's
balanceOfis stale-low (the incoming tokens are not yet credited).
Any unlocked function that prices off balanceOf(vault) now sees the wrong number. nonReentrant on withdraw does nothing, because the attacker never calls withdraw.
Worked example (hypothetical numbers)
Vault has withdraw locked and redeem unlocked: same payout logic, one modifier missing:
function deposit(uint256 amount) external {
shares[msg.sender] += amount; // credit first
token.transferFrom(msg.sender, address(this), amount);
}
function withdraw(uint256 amount) external nonReentrant {
shares[msg.sender] -= amount;
token.transfer(msg.sender, amount);
}
function redeem(uint256 shares_) external { // unlocked
uint256 assets = shares_ * token.balanceOf(address(this)) / totalSupply();
shares[msg.sender] -= shares_;
token.transfer(msg.sender, assets);
}
State: vault holds 1000 tokens, totalSupply 1000 (one honest depositor). Attacker holds 1000 tokens, 0 shares.
- Attacker calls
deposit(1000).shares[attacker] = 1000,totalSupply = 2000. transferFromfirestokensToSendon the attacker. Vault balance is still 1000.- Hook calls
redeem(1000):assets = 1000 * 1000 / 2000 = 500. Shares burned,totalSupply = 1000, vault pays 500 → balance 500. - Hook returns;
transferFromcompletes → vault balance 1500.
Final: vault 1500, totalSupply 1000. Attacker paid 1000, received 500, holds 0 shares: a 500 loss here. Flip the direction and the attacker wins: if the unlocked function is a payout that reads balanceOf as the numerator (a swap-style out = amountIn * reserveOut / balanceOf(this)), the stale-low balance inflates the payout, and the attacker extracts the difference from the pool. This is the shape of the April 2020 imBTC/Uniswap V1 drain.
Trade-offs
| Mitigation | Cost | When it applies |
|---|---|---|
nonReentrant on every state-changing entry | ~2.9k–5k gas per call (two SSTOREs) | You must support ERC-777 and can't restructure |
| CEI: compute, then transfer, then write | No gas overhead | You control the function order |
Snapshot balanceOf before the transfer | One SLOAD | Pricing reads a live balance |
| Reject ERC-777 / use ERC-20 only | Loses composability; some tokens are ERC-777-only | You choose the token |
A single global lock is cheaper than per-function modifiers and closes the whole class. CEI is free but only works if no function reads a live balance mid-transfer.
Failure modes and detection
- Cross-function reentrancy (the example above): detected by an invariant test that runs a malicious ERC-777 mock whose
tokensToSendreenters every unlocked entry point. The suite must fail on the unlocked path. - Stale-balance pricing: detected by asserting
balanceOf(vault)is unchanged across the hook, or by fuzzing share price within a single transaction. - Production signal: a share price that moves more than a few percent inside one tx, or a
Transferlog where the vault is both sender and recipient in the same call frame.
The hook is another public function you did not write. Lock it or don't read live balances.
Curated: · Written: · Reviewed:
Q&A-44A view function reports virtual price from a pool that is mid-callback. How does a "read-only" reentrancy steal funds?
Core answer
Read-only reentrancy doesn't steal from the pool. It steals from whoever trusts the pool's view function while the pool is mid-callback. The attacker never reenters the pool; they reenter a consumer (a lending market, a vault, an oracle) that calls get_virtual_price() or pricePerShare() and treats the number as ground truth.
Assumptions that make it work: the pool exposes a view derived from stored balances and LP total supply; the pool makes an external call (native ETH transfer, ERC777/ERC677 hook, flash-loan callback) before it finishes writing those balances; and a third-party protocol reads that view without a reentrancy check of its own.
Mechanism
The view is a pure function of state that is briefly inconsistent. During the callback, balances and total supply are half-updated, so the view returns a value that exists at no block boundary. The consumer prices collateral or mints shares off it, and the loss lands in the consumer when the pool settles.
Worked trace (hypothetical numbers)
Pool: 1,000 ETH / 1,000,000 USDC, LP supply 1,000,000, virtual price 1.00. Attacker holds 500,000 LP and calls remove_liquidity. In pools that burn LP or send ETH before writing balances, the view reads the transient state:
| Step | LP supply | Pool balances | virtualPrice |
|---|---|---|---|
| before | 1,000,000 | 1,000 ETH / 1,000,000 USDC | 1.00 |
| LP burned, ETH sent, balances not yet written | 500,000 | 1,000 ETH / 1,000,000 USDC | ~2.00 |
| attacker borrows against remaining LP at 2.00 | 500,000 | — | 2.00 |
| pool settles | 500,000 | 500 ETH / 500,000 USDC | 1.00 |
get_virtual_price is the pool invariant divided by LP supply, so halving supply while balances lag roughly doubles it. The loan was sized against 2.00 and is now backed by collateral worth 1.00: a 2x shortfall. The attacker keeps the borrowed assets; the pool itself is untouched.
Mitigations and what they cost
| Fix | Cost | Use when |
|---|---|---|
| Checks-effects-interactions: write balances before the external call | ~free, but sometimes impossible when the call's return feeds the update | you own the pool |
| Reentrancy guard on the view (revert if entered) | ~2,100 gas per read (one SLOAD); breaks legitimate on-chain readers that call the view inside a callback | you own the pool and can't reorder |
| Consumer-side: don't trust a spot view. Use a TWAP or cross-check balances and totalSupply directly | latency (a TWAP lags the real price), more code | you're the consumer and can't change the pool |
The guard is the cheapest pool-side fix, but it only protects that pool; a consumer reading a different pool's view is still exposed, which is why the consumer-side fix is the one that generalizes.
Detection
Fork test: enter the callback, eth_call the view, assert it either reverts or equals the post-state. Never the mid-state.
// inside the attacker's receive hook, on a fork
uint256 mid = pool.get_virtual_price();
// assert mid == postStatePrice, not the transient spike
A view is a weapon when it answers during someone else's callback.
Curated: · Written: · Reviewed:
Q&A-45Alice sets allowance from 100 to 50. How does Bob steal 150, and what API replaces approve-to-new-value?
Assumptions first. Standard ERC-20, allowance[Alice][Bob] is currently 100, Bob is an approved spender, and Alice's fix is a plain approve(Bob, 50) transaction. No permit, no allowance-consuming contract in the middle.
The short answer. Bob front-runs Alice's approve. He sees it in the mempool, pays a higher gas price, and gets transferFrom(Alice, Bob, 100) mined first. That drops the allowance to 0 and moves 100 tokens. Alice's approve then lands and writes 50. Bob spends that too. 100 + 50 = 150.
The trace.
| # | What lands | allowance[Alice][Bob] | Bob's balance |
|---|---|---|---|
| 0 | start | 100 | 0 |
| 1 | Bob's transferFrom(Alice, Bob, 100) | 0 | 100 |
| 2 | Alice's approve(Bob, 50) | 50 | 100 |
| 3 | Bob's transferFrom(Alice, Bob, 50) | 0 | 150 |
Step 1 is the whole trick. approve writes an absolute value, so Alice's transaction at step 2 does not undo Bob's spend: it just sets a fresh 50 on top of an allowance Bob already emptied. If Alice's approve had landed first, Bob could only take 50.
What API replaces approve-to-new-value. OpenZeppelin's increaseAllowance/decreaseAllowance (ERC20, v4.x) were the usual answer. decreaseAllowance(50) subtracts from the live value, so if Bob already took the 100 it reverts on underflow instead of silently granting 50: a safe failure. But OpenZeppelin removed both in Contracts v5.0.0, so on a current v5 codebase they are not available.
And approve(0) then approve(50) does not fix the race either. Bob front-runs the approve(0) with the same transferFrom(100), the zero-approve is a no-op, the 50 lands, Bob takes 50. Still 150. That two-step pattern exists to satisfy tokens like USDT that revert on a non-zero-to-non-zero approve; it is not a race fix.
The actual fix is architectural. Don't leave a standing allowance that a later absolute write can re-arm. Two workable shapes:
- Pull payments with EIP-2612
permit: the user signs a permit with a nonce and deadline, and your contract consumes it atomically withtransferFromin the same transaction (a multicall orpermitAndCall-style entrypoint). The permit still sets an absolute value, so a permit left pending in the mempool has the same race: atomicity is what removes the window, not the signature. - Per-payment EIP-712 signed intent verified by your contract, with no allowance at all.
Detection. Fork-test it: on an Anvil or Hardhat fork, broadcast approve(50) and a front-running transferFrom(100) in the same block and assert final balances. In production, watch for a spender pulling the old allowance in the block before an allowance-decrease lands. A confirmed approve receipt tells you the slot changed; it does not tell you the spender didn't already drain the old value.
Curated: · Written: · Reviewed:
Q&A-46Does permit move tokens, what does it consume, and how is it different from a transfer signed off-chain?
I would answer EIP-2612 permit by separating what consensus agreed from what an oracle or a bridge merely claimed.
permit is an EIP-712 signature that sets allowance and increments the owner's permit nonce; it does not transfer: a later transferFrom moves tokens, unlike a signed transfer typed data.
Concretely, inputs are owner, spender, value, deadline, v,r,s; check deadline, nonce, and domain (chainId, token), then _approve. A relayer must permit then transferFrom in the same transaction; a later standalone permit still races like approve.
The reason for that specificity is a failure I have seen: A dapp treated permit as payment and marked an invoice paid before transferFrom; 1_200 invoices ($84k) closed with allowance set and 0 moved.
Two calls.
| Call | nonce | allowance | owner balance |
|---|---|---|---|
| before | 4 | 0 | 1000 |
| permit(500) | 5 | 500 | 1000 |
| transferFrom 500 | 5 | 0 | 500 |
I would not consider it settled without evidence: After permit, balanceOf(owner) unchanged; nonce+1; allowance==value. Then transferFrom changes balances.
Permit writes allowance and nonce; cash is still transferFrom.
Curated: · Written: · Reviewed:
Q&A-61How does Permit2 differ from EIP-2612 permit, and what does an expiration of 0 mean?
The 90-second answer
Both Permit2 and EIP-2612 move a token approval off-chain into a signature, but they store the allowance in different places and treat expiry differently.
EIP-2612 is token-native: the token itself implements permit(...), and the signature writes an allowance on that token. Its deadline bounds only the signature: once the allowance is written it has no expiry of its own; it persists until spent or overwritten.
Permit2 is a standalone contract (canonical deployment 0x000000000022D473030F116dDEE9F6B43aC78BA3) that tokens are approved to once. Permits are then signed per spender. In its AllowanceTransfer flow, Permit2 separates two timestamps: sigDeadline (when the signature must be submitted by) and expiration (how long the resulting allowance lives). And the answer to the second half: expiration = 0 means the allowance never expires. It is the "no expiry" sentinel, not "already expired."
Mechanism
EIP-2612: permit(owner, spender, value, deadline, v, r, s). The token checks block.timestamp <= deadline, verifies the signature against nonces[owner], then does _approve(owner, spender, value) and increments the nonce. The allowance is a plain uint256 with no time component.
Permit2 AllowanceTransfer: permit(owner, PermitSingle, signature). PermitSingle carries sigDeadline plus PermitDetails{ token, amount, expiration, nonce }. The contract checks the signature deadline, then stores (amount, expiration, nonce) in allowance[owner][token][spender]. Later transferFrom reads that struct and checks:
// Permit2 AllowanceTransfer, simplified
if (block.timestamp > allowed.expiration && allowed.expiration != 0)
revert AllowanceExpired(allowed.expiration);
The != 0 is the whole point: 0 disables the expiry check.
Comparison
| EIP-2612 | Permit2 (AllowanceTransfer) | |
|---|---|---|
| Where allowance lives | token contract | Permit2 contract |
| Nonce lives | token (nonces[owner]) | Permit2 (allowance[owner][token][spender].nonce) |
| Signature bound | deadline | sigDeadline |
| Allowance expiry | none: persists until changed | expiration; 0 = never expires |
| Approvals needed | one per token per spender | one approve to Permit2 per token, then per-spender signatures |
Failure modes
- Treating
expiration = 0as "expired" or as a short-lived allowance: it is the opposite: a permanent allowance. A dapp that signsexpiration = 0for convenience has granted an allowance that survives until the user revokes it. Detection: readallowance(owner, token, spender)and inspect the returnedexpiration; 0 means unbounded. - Confusing
sigDeadlinewithexpiration. A shortsigDeadlinedoes not shorten the allowance. If you want the allowance to lapse, setexpirationexplicitly. - Revocation: bump the nonce (invalidates outstanding signatures) or set the allowance to zero.
When to use which
Use EIP-2612 when the token supports it and you want a single, token-native approval with no extra contract in the path. Use Permit2 when you need one approval to cover many tokens or spenders, batched transfers, or a signature not tied to a token's own implementation: at the cost of an extra contract in the trust path and the expiration = 0 footgun.
Curated: · Written: · Reviewed:
Q&A-47When is approve(type(uint256).max) defensible, and what incident number makes it indefensible?
Defensible when the spender's code cannot change and you would hand it the balance anyway. The clean case: approve(PERMIT2, type(uint256).max) once, then sign a permit per transfer carrying an exact amount and a deadline. Permit2 (0x000000000022D473030F116dDEE9F6B43aC78BA3) is a non-upgradeable singleton; its only power is to move tokens you signed for. Same logic for Uniswap V2 Router02 (0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D): immutable, no admin, no upgrade path.
Indefensible the moment the spender can change behaviour after you approve. The incident that settles it is Hedgey Finance, 19 April 2024: users had approved a legitimate, audited contract for its normal use; a missing check in the campaign-creation path let an attacker pull tokens from every address with an outstanding allowance. ~$44.7M across Ethereum and Arbitrum, no upgrade required: the bug was in the code users had already approved. LI.FI, 16 July 2024, ~$11.6M, same shape: an arbitrary external call in the bridge contract drained wallets that had approved it. BadgerDAO, 2 December 2021, ~$120M, is the other variant: a script injected into the front-end got users to sign approvals to an attacker's contract.
So the rule: max is defensible for immutable, admin-less code you have read; indefensible for anything with an upgrade path, an owner, or a front-end that can ask you to approve something else.
The gas argument is worth about $1.74
A fresh approve (0 → nonzero) is ~46,000 gas: 21,000 base + 2,100 cold slot + 20,000 SSTORE_SET + calldata and event. Re-approving an existing nonzero allowance is ~29,000 gas (SSTORE_RESET is 2,900 post-EIP-2929). So max saves ~29,000 gas per re-approval you skip. At 20 gwei and $3,000 ETH that is 0.00058 ETH ≈ $1.74. You are trading the whole balance for under two dollars.
Spender classes
| Spender | Max approve | Why |
|---|---|---|
| Immutable, no admin (Permit2, Uniswap V2 Router02) | Yes | Code cannot change; worst case is the bug it shipped with |
| Upgradeable proxy or contract with an owner | No: exact amount or Permit2 | A later implementation can add a sweep |
| EOA | Never | No code to audit; key compromise is the balance |
| Contract you have not read | No | You are approving code, not a brand |
The approve race
approve sets an absolute value, so changing N → M can be front-run: the spender spends N, your tx lands, they spend M. Reset to zero first, use increaseAllowance/decreaseAllowance (OpenZeppelin, non-standard), or sign a permit. EIP-2612 permit(owner, spender, value, deadline, v, r, s) does the same at the token level: a signed approval with an exact value and a deadline, no gas from the owner.
// Solidity 0.8.x
token.approve(spender, 0); // clear first
token.approve(spender, exact); // then set the new value
// Permit2: approve once, sign per transfer
token.approve(address(PERMIT2), type(uint256).max);
permit2.permit(owner, permitSingle, signature); // amount + expiration + deadline
permit2.transferFrom(owner, recipient, uint160(amount), token);
Failure modes to name
- Upgradeable spender: a proxy upgrade adds a function that transfers from any address with an allowance. Detected by watching the proxy's implementation address (
Upgradedevents) and by approval checkers such as revoke.finance or Etherscan's token-approval view. - Front-end compromise: the contract is fine, the page is not. Detected by comparing the spender address in the wallet prompt against the one you expect.
- Stale allowance: you approved once for a one-off, forgot, and the contract later grew a bug. Detected by periodic
allowance(owner, spender)reads; revoke anything you cannot justify.
Revoke cadence: tie it to the spender's change events, not a fixed calendar. Revoke when the proxy upgrades or the protocol announces a migration. A 90-day sweep is a reasonable default if you want a number, but the trigger should be the upgrade, not the date.
Curated: · Written: · Reviewed:
Q&A-56transferFrom decreases allowance except when it is max. Why do fee-on-transfer tokens still break a naive amount-out check?
Core answer
Assume a standard ERC-20, a router that pulls tokens with transferFrom, and a reserve it credits by the amount argument. Allowance and delivery are different quantities, and the max-uint rule is exactly why you cannot use one to infer the other.
transferFrom decrements the allowance by the amount argument, or, under the max-uint convention, not at all. The fee is taken inside the token's own transfer logic: sender balance -= amount, recipient balance += amount - fee, and the fee is burned or routed to a treasury. So the recipient's balance grows by amount - fee while the allowance moves by amount (or zero). A router that does reserves += amount credits tokens that never arrived.
The max-uint exemption is what kills the allowance as a fallback oracle. With infinite approval the allowance does not change, so it carries no information about what was delivered. With finite approval it changes by the requested amount, not the delivered amount. Either way the only reliable measure is the recipient's balance delta.
Where the fee is taken
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
contract Router {
IERC20 public immutable token;
uint256 public reserves;
function swapIn(uint256 amountIn) external {
uint256 before = token.balanceOf(address(this));
token.transferFrom(msg.sender, address(this), amountIn);
uint256 received = token.balanceOf(address(this)) - before;
reserves += received; // not amountIn
}
}
Trace with amountIn = 1000, a 1% fee, and contract balance 5000 before the call:
- allowance check: finite 1000 -> allowance 0;
type(uint256).max-> unchanged - sender balance
-= 1000 - fee 10 burned
- contract balance 5990
received = 990
| Approval | allowance delta | balance delta (1% fee, amount 1000) |
|---|---|---|
| finite 1000 | -1000 | +990 |
type(uint256).max | 0 | +990 |
The allowance column is wrong in both rows as a measure of what moved.
Trade-offs
- Balance-delta costs an extra
balanceOf(cold SLOAD ~2100 gas, warm ~100). On a swap that is noise; in a hot loop it adds up. - Balance-delta is wrong for rebasing tokens, where
balanceOfchanges without a transfer. There you wantsync()-style accounting: re-read balances and set reserves to the actual values, as Uniswap V2'ssync()does. - Uniswap V2 ships a separate router path,
swapExactTokensForTokensSupportingFeeOnTransferTokens, that does the balance-delta check; the plain path assumesamount == received. Choose per token, not globally. - Some fee-on-transfer tokens take the fee on the sender side only, some on both; balance-delta handles both because it measures the recipient.
- USDT-class tokens return no boolean from
transferFrom; wrap with SafeERC20 so a silent failure does not read as success.
Failure modes
Naive credit lets reserves drift above real balances. An arbitrageur swaps against the inflated reserve and extracts the difference, and the leak compounds per swap. Detect it with an invariant test asserting reserves == token.balanceOf(pair) after every swap, plus a fork test against a 1% fee mock.
Curated: · Written: · Reviewed:
Q&A-57Why does safeTransferFrom call onERC721Received, and how is that a reentrancy door a marketplace must lock?
What a strong candidate says first
safeTransferFrom calls onERC721Received on the recipient when the recipient is a contract, because EIP-721 requires it: a plain transferFrom can send a token to a contract that has no way to move it out, permanently bricking it. The hook is the recipient's chance to accept or reject.
The reentrancy door is that this hook is an external call to attacker-controlled code that runs in the middle of your buy. If your marketplace writes its listing state after the transfer, the hook can call back into buy while the listing still looks active. The fix is checks-effects-interactions: clear the listing before the external call, and add a nonReentrant guard as a second lock.
The mechanism
EIP-721 defines the callback signature and the required return value:
function onERC721Received(
address operator,
address from,
uint256 tokenId,
bytes calldata data
) external returns (bytes4);
A compliant safeTransferFrom reverts unless the recipient returns 0x150b7a02 (the selector onERC721Received(address,address,uint256,bytes)). OpenZeppelin's _safeTransfer does the token state update first, then the check:
function _safeTransfer(address from, address to, uint256 tokenId, bytes memory data) internal {
_transfer(from, to, tokenId); // ownerOf/balances updated here
require(_checkOnERC721Received(from, to, tokenId, data), "ERC721: transfer to non ERC721Receiver implementer");
}
So when your hook runs, the token has already moved. That matters: a reentrant buy on the same listing will usually revert on the token transfer itself, because the seller no longer owns the token. The exploitable surface is your marketplace's own accounting (payouts, credits, refunds, or state another function reads) which is not idempotent.
A worked exploit
Marketplace that pays the seller after the transfer, and credits a withdrawable balance:
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
contract Market {
struct Listing { address seller; uint256 price; bool active; }
mapping(uint256 => Listing) public listings;
mapping(address => uint256) public owed;
IERC721 public nft;
function buy(uint256 id) external payable {
Listing storage l = listings[id];
require(l.active, "inactive");
require(msg.value == l.price, "price");
nft.safeTransferFrom(l.seller, msg.sender, id); // hook fires on msg.sender
l.active = false; // effect AFTER interaction
owed[l.seller] += msg.value;
}
function withdraw() external {
uint256 amt = owed[msg.sender];
owed[msg.sender] = 0;
(bool ok,) = msg.sender.call{value: amt}("");
require(ok, "withdraw failed");
}
}
Attacker is the seller and the buyer is the attacker's contract. Trace:
- Attacker lists token
1at 1 ETH, then callsbuy(1)with 1 ETH. safeTransferFrommoves token1to the attacker's contract and callsonERC721Received.- Inside the hook, the attacker reenters
buy(1).l.activeis stilltrue, so therequirepasses. The token transfer reverts here, the seller no longer owns token1, so this particular reentry fails.
That is the honest limit of the naive double-buy. The door is still real, and it opens on the accounting: if the marketplace credits owed before the transfer, or pays a referral/refund after it, the reentrant call can double-credit. The lock is the same either way.
The lock
function buy(uint256 id) external payable nonReentrant {
Listing storage l = listings[id];
require(l.active, "inactive");
require(msg.value == l.price, "price");
l.active = false; // effects first
nft.safeTransferFrom(l.seller, msg.sender, id); // interaction last
owed[l.seller] += msg.value;
}
nonReentrant (OpenZeppelin ReentrancyGuard) sets a flag on entry and clears it on exit; any reentrant call reverts with ReentrancyGuard: reentrant call. Clearing l.active first makes the reentrant buy fail the require even without the guard.
Failure modes and follow-ups
transferFrominstead ofsafeTransferFrom: no hook, no reentrancy, but tokens sent to contracts that cannot handle them are stuck. That is a different bug, not a fix.- Guard only on
buy: ifwithdraw,cancel, oracceptOfferalso move tokens or ETH, they need the guard too. - Detecting it: a reentrant call shows up as a nested
buy/withdrawframe in the trace, or as aReentrancyGuard: reentrant callrevert in a fork test. Write the malicious receiver as a test contract and assert the second call reverts.
One line to remember: the safe in safeTransferFrom protects the token, not your listing state.
Curated: · Written: · Reviewed:
Q&A-58A batch transfer of 20 ids in one tx: what must you check that a single safeTransfer does not, and where do rounding and callbacks hide?
Assumptions. "20 ids in one tx" is ERC-1155 safeBatchTransferFrom. ERC-721 has no batch in the standard and ERC-20 has no ids, so the batch-versus-single contrast only exists in 1155. I'll assume OpenZeppelin 5.x semantics and a contract receiver.
What the batch forces you to check that a single transfer does not.
Parallel-array length. Single takes one id and one amount. Batch takes ids[] and amounts[], and they must be the same length; OZ reverts with ERC1155: ids and amounts length mismatch. A hand-rolled loop without that check reads zero for the missing entries: you move 20 ids while charging for 19, or the reverse.
One callback, not twenty. Single fires onERC1155Received per call. Batch fires onERC1155BatchReceived once, after every balance has moved. A receiver that only implements the single hook fails the ERC-165 check and reverts the whole batch. The hook must return 0xbc197c81; the receiver advertises 0x4e2312e0.
Rounding lives in your amounts[], not in the token. 1155 amounts are raw uint256; the token never rounds. Rounding appears when you derive the array from a total: splitting a pot, applying per-id fees, or converting a fungible amount into per-id units. Integer division truncates per id, so the parts stop summing to the whole.
// Solidity ^0.8.20 — deriving per-id amounts from a total
function split(uint256 total, uint256[] calldata weights)
public pure returns (uint256[] memory amounts)
{
uint256 sum;
for (uint256 i; i < weights.length; ++i) sum += weights[i];
amounts = new uint256[](weights.length);
for (uint256 i; i < weights.length; ++i)
amounts[i] = total * weights[i] / sum; // truncates each id
}
Trace total = 100, weights = [1,1,1]: sum = 3, each 100*1/3 = 33, so amounts = [33,33,33] and the batch moves 99 of 100. The caller's ledger still says 100. Fix it by giving the last id total - runningSum, or carrying the remainder explicitly.
Batch versus a loop of safeTransferFrom.
one safeBatchTransferFrom | 20 × safeTransferFrom | |
|---|---|---|
| intrinsic gas | 21,000 once | 21,000 × 20 = 420,000 |
| events | one TransferBatch | 20 TransferSingle |
| receiver calls | one batch hook | 20 single hooks |
| failure scope | any bad id reverts all 20 | per call; partial progress possible |
| receiver compat | needs the batch hook | works with single-hook receivers |
The gas gap is mostly the 19 extra 21,000-gas transaction envelopes plus 19 extra logs; the per-id storage writes are the same either way. Measure on your target chain before quoting a number.
Failure modes and what changes the decision. Reentrancy: OZ updates balances before the batch hook, so a reentrant call sees post-transfer state. If you call the hook before updating balances, a reentrant safeBatchTransferFrom sees stale balances and can double-spend: guard it and test by reentering from the hook. Empty batch: zero-length arrays pass the length check (0 == 0), the loop does nothing, and OZ still runs the acceptance check when to is a contract; guard ids.length > 0 if your accounting assumes at least one id.
Loop instead of batch when the receiver is a contract you don't control that only implements the single hook, when ids carry per-id business rules, or when you need per-id failure isolation. Otherwise batch.
Curated: · Written: · Reviewed:
Q&A-60A token rebases every 8 hours. Why is storing amount at deposit time the wrong collateral accounting?
The 90-second answer
Storing amount at deposit time records a snapshot of a quantity the token itself keeps changing. A rebasing token's balanceOf is derived from a share balance times a rate (stETH-style) or from an elastic supply (AMPL-style), and it moves on every rebase without any call from your contract. Your stored number is a cache with no invalidation path: it drifts from the truth on the first rebase and never catches up. The fix is to store the token's own invariant unit: shares for tokens that expose one, or a re-read of balanceOf at every accounting touchpoint for tokens that don't, and convert to an amount only at the moment you need one.
Why the snapshot drifts
Two independent things break it:
- The rebase changes
balanceOfwith noTransferto or from your vault. AMPL-style elastic supply emits nothing on rebase; stETH-style tokens expose a share balance you can read directly. Either way, nothing calls your deposit function. - Your accounting only updates on deposit, withdraw, borrow and liquidate. Between those events the stored number is frozen while the real balance moves.
Worked trace
Borrower deposits 1,000,000 units of a rebasing token, borrows 600,000 USDC. Liquidation threshold 75%. Three consecutive −10% rebases:
| Event | balanceOf | vault stored | protocol LTV | true LTV |
|---|---|---|---|---|
| deposit | 1,000,000 | 1,000,000 | 60.0% | 60.0% |
| rebase −10% | 900,000 | 1,000,000 | 60.0% | 66.7% |
| rebase −10% | 810,000 | 1,000,000 | 60.0% | 74.1% |
| rebase −10% | 729,000 | 1,000,000 | 60.0% | 82.3% |
At the third rebase the position is past the 75% threshold and liquidatable, but the protocol still reads 60% and never acts. The bad debt accrues silently. The same table with positive rebases runs the other way: stored collateral under-counts, so borrowers get blocked and liquidated when they are actually healthy.
The fix
- Tokens with a share balance (stETH, cToken/aToken style): store
shares, notamount. Shares are invariant across rebases; convert withamount = shares * rateat read time. Round collateral down and debt up. - Tokens with no share concept (AMPL): nothing invariant exists to store. Either wrap into a non-rebasing wrapper before it enters the vault, or treat the stored number as a cache and re-read
balanceOfon every path that touches collateral: deposit, withdraw, borrow, liquidate, and every health check. A cache with a freshness bound is workable; a cache with no invalidation is not. - Debt side: if debt is denominated in the same rebasing token, both sides scale and the ratio is invariant, but only if you scale both. Mixing rebasing collateral with a static debt unit is where the LTV breaks.
Failure modes and detection
- Negative rebase: stored > actual, protocol over-lends, bad debt at liquidation. Positive rebase: stored < actual, unnecessary liquidations and blocked withdrawals. Both are caught by one invariant job asserting
stored == balanceOf(orstored == sharesToAmount(shares)) every block, alerting on any nonzero delta. - Transfer-only indexers: subgraphs and risk dashboards miss the rebase entirely and report a supply that never existed. Cross-check indexer totals against
totalSupply(). - Rounding: share-to-amount conversion must round in the protocol's favour; a 1-wei-per-position drift compounds across positions.
Storing amount is correct only when the amount is genuinely invariant: a non-rebasing token, or a wrapper like wstETH that fixes the rate. There the snapshot is the truth; everywhere else it is a stale cache.
Curated: · Written: · Reviewed:
Q&A-62USDC is 6 decimals, WETH is 18, a feed is 8. Where do you scale, and what is a 10^12 bug worth?
Scale at the boundary where the number first enters arithmetic, and carry the exponent explicitly. The rule is one line: when you multiply an amount by a price, divide by 10^(decAmount + decPrice − decOut). Get that exponent wrong and you are off by a power of ten, and between USDC (6) and WETH (18) that power is 10^12.
What a 10^12 bug is worth: it is the ratio 10^(18−6). Treat 1 USDC, 1e6 raw units, as if it were 18-decimal and it reads as 1e-12 USDC, a $1 asset valued at $0.000000000001. Scale that up. A $1,000,000 USDC balance is 1e12 raw units; divided by 1e18 it reads as 1e-6 USDC, one millionth of a dollar. Every dollar of mis-scaled notional is off by a factor of a trillion, in whichever direction the exponent error points.
Where the exponent lands
Derive it once. Real value = (a / 10^decA) × (p / 10^decP). To store that value with decV decimals, multiply by 10^decV:
v = a × p × 10^decV / 10^(decA+decP) = a × p / 10^(decA+decP−decV)
So v = mulDiv(a, p, 10**(decA + decP - decV)).
Check it against the two tokens, output in 8 decimals (decV = 8):
| amount a | decA | price p | decP | divisor 10^(decA+decP−8) | v | reads as |
|---|---|---|---|---|---|---|
| 1e18 (1 WETH) | 18 | 3e11 ($3000, 8dp) | 8 | 1e18 | 3e11 | $3000 |
| 1e6 (1 USDC) | 6 | 1e8 ($1, 8dp) | 8 | 1e6 | 1e8 | $1 |
Both correct. The only thing that changed between the rows is decA, and it changed the divisor by 10^12.
The two options, and when each is wrong
Normalize to 18-decimal fixed point at the boundary: amount18 = amount × 10^(18−decA), then all downstream math is 18-dec. One exponent, hard to get wrong later. This breaks when a token has more than 18 decimals, because you truncate, and it overflows sooner: two 18-dec values multiplied are 1e36, and a chain of them can exceed uint256.
Carry the exponent in mulDiv: no intermediate scaling, full precision, one rounding at the end. The trap here is decA + decP < decV. The exponent goes negative, and code that always divides silently truncates to zero. A 6-dec token with a 6-dec feed and 18-dec output gives 10^(6+6−18) = 10^-6, and integer division returns 0.
Failure modes and detection
- Feed decimals ≠ token decimals. Chainlink USD feeds are 8 decimals; assuming 18 is a 10^10 error on its own.
- "ERC-20 is 18 decimals" is false for USDC (6) and WBTC (8). A table that hardcodes 18 breaks on both.
- Detection: an invariant test per token. 1 whole token at a $1 feed must equal exactly 10^decV. A property test that two positions of equal dollar value produce equal internal values catches a 10^12 jump immediately.
- Operational cost: if USDC collateral reads as 1e-12, a $1M position looks like dust, so borrowing is blocked or, on the debt side, healthy positions become liquidatable. The health factor is off by 10^12, so any position with debt above ~1e-6 is instantly seizable.
Curated: · Written: · Reviewed:
Q&A-63tokenURI returns ipfs://Qm… today. What can an upgradeable URI still do tomorrow, and how do you freeze it?
Core answer (say this first). Nothing in ERC-721's metadata extension makes tokenURI stable. OpenZeppelin 5.x implements it as string.concat(_baseURI(), tokenId.toString()), and _baseURI() returns a storage string an owner-only setter can rewrite at any time. So an upgradeable URI can do tomorrow whatever the admin key can do: swap the base to a new CID, flip a revealed flag, or point at a gateway that no longer serves the file. Freezing means deleting that capability, not adding one.
How the slot becomes immutable. Three real options, in increasing strength:
- Immutable base set in the constructor. No setter exists, so no admin can change it. Cheapest and strongest, but you cannot reveal later.
- One-way freeze flag.
setBaseURIrequires!frozen;freeze()sets it. This is a custom function, no ERC definesfreezeURI(), so it lives in your own ABI and should emit an event. - Per-token content hash. Store the CID, or a
bytes32sha2-256 digest (32 bytes), per token;tokenURIderives the string from it. Freezing is per token, so you can reveal in batches.
// SPDX-License-Identifier: MIT
pragma solidity ^0.8.24;
import {ERC721} from "@openzeppelin/contracts/token/ERC721/ERC721.sol";
import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol";
contract FreezableURI is ERC721, Ownable {
string private _base;
bool public frozen;
event BatchMetadataUpdate(uint256 _fromTokenId, uint256 _toTokenId); // ERC-4906
constructor(string memory base_) ERC721("C", "C") Ownable(msg.sender) {
_base = base_;
}
function setBaseURI(string calldata base_) external onlyOwner {
require(!frozen, "frozen");
_base = base_;
emit BatchMetadataUpdate(0, type(uint256).max);
}
function freeze() external onlyOwner { frozen = true; }
function _baseURI() internal view override returns (string memory) { return _base; }
}
Trace: with _base = "ipfs://QmOld/", tokenURI(7) returns ipfs://QmOld/7. After freeze(), setBaseURI("ipfs://QmNew/") reverts with "frozen", and tokenURI(7) still returns ipfs://QmOld/7. Emitting ERC-4906's BatchMetadataUpdate is what tells marketplaces to re-fetch; without it they keep serving cached JSON.
On-chain CID vs IPFS pinning. Storing the CID string on-chain is fine and costs one SSTORE (~20,000 gas for a fresh slot, ~2,900 to rewrite an existing one). Pinning is not an on-chain operation: it is a pinning service or your own IPFS node keeping the bytes. A frozen CID commits to the content, but if nobody pins, it resolves to nothing. Freeze the CID and keep the pinning arrangement alive.
When not to freeze. Reveal collections must stay mutable until reveal; freezing at deploy breaks the drop. Collections with a broken CID or a dead gateway need a fix path. The deciding question is whether you have promised rarity before the metadata is final, if yes, freeze; if you still owe a reveal or a correction, keep the setter and disclose it.
The failure mode that matters. On a UUPS or Transparent proxy the flag lives in proxy storage, so an upgrade can ship a new implementation with a fresh setter. A freeze flag is only as strong as the upgrade admin. To make it real, renounce upgrade rights (set the proxy admin to address(0)) or deploy non-upgradeable.
How to verify. Test that setBaseURI reverts after freeze(), that tokenURI is unchanged, and that the CID in the marketplace listing equals the frozen one.
Curated: · Written: · Reviewed:
Q&A-48Which fields of latestRoundData must you check before using answer as a price, and what happens if you only require answer > 0?
The 60-second answer. latestRoundData() returns five fields: roundId, answer, startedAt, updatedAt, answeredInRound. Before treating answer as a price you need three of them, plus two things outside the call:
updatedAt != 0andblock.timestamp - updatedAt <= maxAge, wheremaxAgeis the feed's documented heartbeat plus a small buffer.answer > 0, or, for feeds that can legitimately print negative (spread and rate feeds), a sane min/max band.roundId != 0. On pre-OCR feeds alsoansweredInRound >= roundId; on current OCR feedsansweredInRoundis deprecated and is not a freshness check.feed.decimals()matches what your arithmetic assumes.- On an L2, the sequencer uptime feed says the sequencer is up and you are past the post-recovery grace period.
startedAt is essentially never checked.
// SPDX-License-Identifier: MIT
pragma solidity 0.8.24;
interface AggregatorV3Interface {
function latestRoundData() external view
returns (uint80 roundId, int256 answer, uint256 startedAt,
uint256 updatedAt, uint80 answeredInRound);
function decimals() external view returns (uint8);
}
contract PriceGuard {
AggregatorV3Interface public immutable feed;
uint256 public immutable maxAge; // heartbeat + buffer, e.g. 3600 + 300
uint8 public immutable feedDecimals;
error BadRound(uint80 roundId);
error BadAnswer(int256 answer);
error Stale(uint256 updatedAt);
constructor(AggregatorV3Interface f, uint256 maxAge_, uint8 dec) {
feed = f; maxAge = maxAge_; feedDecimals = dec;
}
function read() public view returns (int256) {
(uint80 roundId, int256 answer, , uint256 updatedAt, ) = feed.latestRoundData();
if (roundId == 0 || updatedAt == 0) revert BadRound(roundId);
if (answer <= 0) revert BadAnswer(answer);
if (block.timestamp - updatedAt > maxAge) revert Stale(updatedAt);
return answer;
}
}
| Field | What it tells you | Check |
|---|---|---|
roundId | round index | != 0; on pre-OCR feeds answeredInRound >= roundId |
answer | the price | > 0, or inside a sane min/max band |
startedAt | round start | not used |
updatedAt | last update time | != 0 and block.timestamp - updatedAt <= maxAge |
answeredInRound | round the answer was computed in | deprecated on OCR feeds; never a substitute for updatedAt |
Where the trade-offs are. maxAge is the real decision. ETH/USD on Ethereum mainnet has a 1-hour heartbeat and a 0.5% deviation threshold, so a calm weekend can go a full hour without an update. Set maxAge tighter than the heartbeat and you revert on a healthy feed; set it looser and a genuinely stale price passes. Heartbeat plus a few minutes of buffer is the usual compromise: with a 3,600s heartbeat and a 300s buffer, an update 3,899s old is accepted and 3,901s reverts, so the worst case you accept is a price up to ~65 minutes old. Reverting on stale data halts liquidations and lets bad debt build; accepting stale data liquidates at the wrong price. A middle path is a fallback oracle (a TWAP or a second feed) or pausing new borrows while still allowing repayments. getRoundData(roundId) re-reads the same round to confirm it is complete and its updatedAt matches: an extra call, worth it in a liquidation path. On Arbitrum or Optimism the feed freezes while the sequencer is down, so updatedAt goes stale while answer stays positive; Chainlink's docs recommend checking the sequencer uptime feed and waiting a grace period (their example uses 30 minutes) after recovery, because the first rounds after restart can still be old.
What answer > 0 alone misses. A lending market on an L2 that checked only answer > 0: the sequencer goes down for 61 minutes, ETH/USD's updatedAt is 3,700s old (past the 3,600s heartbeat) and answer still reads the last price. The market keeps accepting deposits and liquidating against a price over an hour old. answer > 0 is a liveness check on the number, not on the round. It also misses a wrong feed address returning a positive price for a different asset, and an 8-decimal answer scaled as 18-decimal, which is a 10^10 error.
Curated: · Written: · Reviewed:
Q&A-49Your feed heartbeats every 3_600 seconds or 0.5% deviation. How do you combine that with a circuit breaker on a 20% jump?
Assumptions I'd state up front: one oracle feed driving a liquidation engine; heartbeat 3600s means it publishes at least hourly, and the 0.5% deviation trigger means it publishes sooner whenever price moves 0.5% from the last published value. I can pause liquidations but not revert trades, and I have a fallback source to switch to.
The two gates answer different questions and run in order on every price.
| Gate | Question | Bound | On fail |
|---|---|---|---|
| Staleness | Is this price fresh? | age ≤ 3600s + 300s grace | stop liquidating, use fallback |
| Jump (fast) | Did one update move too far? | |p − p_prev| / p_prev ≤ 20% | pause liquidations, confirm |
| Jump (slow) | Did the window move too far? | |p − p_ref| / p_ref ≤ 20%, window ≥ 3600s | pause liquidations, confirm |
The combination is the point. The heartbeat is what makes the jump gate well-defined: because the feed publishes on a 0.5% deviation, price cannot drift more than 0.5% during a silent window, if it had, the feed would have published. So a 20% move can never hide inside the 3600s heartbeat; it always arrives as an update, and the jump gate will see it. The staleness gate must run first, because computing a jump from a price older than the heartbeat is meaningless: you'd be comparing a stale price to a fresh one and calling the difference a jump.
The reference matters. Comparing to the immediately previous update catches a single bad print or a gap, but a real move arriving as forty consecutive 0.5% updates never shows a 20% single-step delta. So I use two references: consecutive-update delta for the fast trip, and a window at least as long as the heartbeat for the slow trip. Both pause; neither reverts.
Trade-offs. A tight breaker (low threshold, short window) pauses on real moves and blocks liquidations, letting bad debt accrue. A loose one liquidates on a bad print and socializes the loss. Alternatives to a single-feed delta: a TWAP reference (robust to one bad print, but lags and is itself manipulable over the window), or a median across two or three independent feeds (best signal, needs a second source). I'd take the median if I have it, TWAP otherwise.
Failure modes and detection:
- Stale feed tripping the breaker: age > heartbeat suppresses the jump gate. Detect via updatedAt lag.
- Bad print: one update 20% off, next update back. Detect: the next update reverts; auto-reset the breaker.
- Real gap (weekend, thin liquidity): the jump persists across updates. Detect: it doesn't revert; confirm with the fallback before resuming.
- Heartbeat masking: a jump window shorter than 3600s misses a move that accumulated across several updates. Keep window ≥ heartbeat.
Gate logic:
HEARTBEAT, GRACE, JUMP, WINDOW = 3600, 300, 0.20, 3600
def gate(now, updated_at, price, prev_price, ref_price):
if now - updated_at > HEARTBEAT + GRACE:
return "STALE" # stop liquidating, use fallback
if prev_price and abs(price - prev_price) / prev_price > JUMP:
return "PAUSE_FAST" # single-update jump: pause, confirm
if ref_price and abs(price - ref_price) / ref_price > JUMP:
return "PAUSE_SLOW" # window >= heartbeat: pause, confirm
return "OK"
Trace: feed silent 3600s, last price 100.00. Update arrives at t=3600 with 100.40 (0.4% move, published by heartbeat). prev delta 0.4% → OK; ref delta 0.4% → OK. Then a gap: next update 121.00. prev delta 20.5% → PAUSE_FAST; ref delta 21.0% → PAUSE_SLOW. Breaker trips, liquidations pause, fallback queried. If the fallback agrees near 121, resume; if it says 100.5, it was a bad print and the breaker resets.
Curated: · Written: · Reviewed:
Q&A-74A USDC/USD feed prints $0.87 for 25 minutes. Do you liquidate ETH-USDC vaults on that print, and what alternative bound do you use?
No: don't liquidate on that print, and in an ETH-collateral / USDC-debt vault the print can't make a healthy position liquidatable anyway.
Assumption first: the vault holds ETH as collateral and owes USDC. Health factor is (ETH qty × ETH/USD × LLTV) / (USDC debt × USDC/USD). A USDC depeg shrinks the denominator, so it raises the health factor. The print makes borrowers safer, not seizable.
Worked example: 10 ETH at $2,000, 80% LLTV, 12,000 USDC debt:
| USDC price | Debt value | Health factor |
|---|---|---|
| $1.00 | $12,000 | 16,000 / 12,000 = 1.33 |
| $0.87 | $10,440 | 16,000 / 10,440 = 1.53 |
The print moves you away from liquidation. So the answer to "do you liquidate" is no, and the reason is mechanical, not policy.
The alternative bound. Clamp asymmetrically: value USDC debt at par ($1), never let a depegged feed shrink what a borrower owes, and value any USDC collateral at min(feed, $1). A depeg can then only ever reduce USDC collateral value, never reduce USDC debt. Gate any liquidation on a corroborated price (a second oracle plus a CEX mid or DEX TWAP), not a single 25-minute print.
Why the print is suspect. Chainlink's USDC/USD feed on Ethereum updates on a 0.25% deviation threshold with a 24-hour heartbeat, so a 5% move is ~20× the normal trigger: a real dislocation or a bad round, not noise. And real depegs persist: USDC traded near $0.87 on 11 March 2023 after Circle disclosed $3.3B of reserves at SVB, and stayed off-peg for roughly 48 hours until the backstop. A 25-minute print is far shorter than any real depeg, which points to one bad reporter or a thin venue, a single Curve 3pool or CEX mid, rather than a market-wide repricing.
The trade-off. Pause liquidations and a genuine depeg lets bad debt accrue: positions that should close stay open, and if USDC never recovers the protocol eats the loss. Don't pause and a bad print seizes ETH from healthy borrowers: the March 2023 failure mode, where venues that marked USDC at the print liquidated positions that were fine an hour later. The asymmetry decides it: a bad print is recoverable, a cascade of wrongful liquidations is not.
Detection and cost. Alert when the primary feed diverges from a second source by more than a few percent, and track staleness against the heartbeat. Put the breaker in the oracle adapter, not in governance: a multisig pause takes minutes to hours, and a 25-minute print is over before a vote lands.
The opposite failure. If USDC is collateral, refusing to mark it down lets borrowers abandon undercollateralized positions. That's why the clamp is asymmetric: debt at par, collateral at min(feed, $1). You never under-liquidate a genuine USDC-collateral depeg, and you never liquidate an ETH-USDC vault on a bad print.
Curated: · Written: · Reviewed:
Q&A-50A vault mints shares = assets * totalSupply / totalAssets. Who should round in whose favor, and what is the first-deposit trap?
The rule: every rounding goes in the vault's favor. For a vault with totalSupply S and totalAssets A:
| Call | Computes | Round | Effect |
|---|---|---|---|
deposit(assets) | shares = assets·S/A | down | user gets fewer shares |
mint(shares) | assets = shares·A/S | up | user pays more assets |
withdraw(assets) | shares = assets·S/A | up | user burns more shares |
redeem(shares) | assets = shares·A/S | down | user receives fewer assets |
This is exactly what ERC-4626 mandates, and the reason is composability. If any single operation rounded in the user's favor, an attacker could split one deposit into many small ones (or one redeem into many) and harvest the rounding remainder on each call. Rounding toward the vault means the error accrues to the pool, never to a caller, so no sequence of calls is profitable.
In Solidity, use mulDiv with an explicit rounding argument: OpenZeppelin Math.mulDiv(x, y, d, Math.Rounding.Floor|Ceil), or Solmate FixedPointMathLib.mulDivDown/mulDivUp. Plain a * b / c truncates and silently rounds down in every case, which is wrong for mint and withdraw.
The first-deposit trap. When S == 0 the share price is undefined; the vault special-cases it to 1:1, which lets the first depositor set the price. The attack:
- Attacker deposits 1 wei → 1 share.
A = 1,S = 1. - Attacker transfers 1e18 wei of the asset straight to the vault: a donation, no mint.
A = 1e18+1,S = 1. - Victim deposits 1e18.
shares = floor(1e18 · 1 / (1e18+1)) = 0. Victim gets nothing.A = 2e18+1,S = 1. - Attacker redeems 1 share →
1 · (2e18+1) / 1 = 2e18+1assets. Spent1e18+1, took2e18+1; the victim's 1e18 is now the attacker's.
The victim's deposit is the profit. The donation is not lost: it comes back on redeem.
Mitigations, and what they actually buy you.
- Virtual shares/assets (OpenZeppelin ERC4626).
_convertToSharesusesassets · (S + 10^offset) / (A + 1). With the default offset 0 that is 1 virtual share and 1 virtual asset. To zero out a victim depositingA, the attacker must now donate more than2A: the attack costs more than it steals. Raising the offset to 3 makes the required donation ~1000A. Override_decimalsOffset()when the asset has few decimals or low unit value. - Dead shares. Burn a fixed minimum on the first deposit (Uniswap V2 burns 1000 wei of LP) so
Scan never be 1. The attacker then has to donate proportionally more to move the price. - Seed the vault. Deposit a known amount yourself before it is public, so
Sis never 0 when a user arrives.
How I'd verify it. Not with a single unit test. A stateful fuzz/invariant test over random sequences of deposit, mint, withdraw, redeem and direct transfers, asserting: (a) no account ever ends with more assets than it put in, and (b) a victim depositing X right after any attacker action receives shares redeemable for at least X − 1 wei. That catches both the inflation attack and any rounding direction you got backwards.
When this matters less. If the vault asset is rebasing or fee-on-transfer, the donation vector changes and you handle balance drift separately, but the rounding rule is unchanged.
Curated: · Written: · Reviewed:
Q&A-59ERC-4626 has convertToShares and previewDeposit. Which is the idealized average-rate conversion, which quotes the deposit path, and why can they differ?
Core answer (say this first).
convertToShares is the idealized conversion: it maps assets to shares using the vault's virtual totalAssets/totalSupply ratio, ignores fees, and rounds down. EIP-4626 defines it to be caller- and time-independent: the same inputs give the same answer regardless of who calls or when.
previewDeposit quotes the deposit path. It runs against live vault state and the vault's fee configuration, and per EIP-4626 it "MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit call in the same transaction." That makes it the number to use as a slippage bound. deposit returns the shares actually minted, which is the ground truth.
They differ because fees and live state enter previewDeposit but not convertToShares, and because both round down but on different quantities.
Mechanism.
EIP-4626 pins the semantics:
convertToShares(assets): "MUST NOT show any variations depending on the caller" and "MUST round down towards 0." It is a pure function of the vault's accounting ratio.previewDeposit(assets): "MUST return as close to and no more than the exact amount of Vault shares that would be minted in a deposit call in the same transaction." It must account for deposit fees and any other live condition.deposit(assets, receiver): "MUST return the amount of shares minted."
So the three form a chain of decreasing idealization: idealized ratio → quoted deposit → realized mint.
Worked example. Vault with totalAssets = 1,000,000e18, totalSupply = 1,000,000e18 (1:1), deposit fee 10 bps (0.1%). Deposit 1000e18 assets.
- fee = 1000e18 * 0.001 = 1e18; net assets = 999e18
convertToShares(1000e18)= 1000e18 * 1,000,000e18 / 1,000,000e18 = 1000e18previewDeposit(1000e18)= 999e18depositreturns 999e18
| Call | Result |
|---|---|
convertToShares(1000e18) | 1000e18 |
previewDeposit(1000e18) | 999e18 |
deposit(...) returns | 999e18 |
minOut = convertToShares | revert (needs 1000e18, mints 999e18) |
Trade-offs / when to use which.
- Use
previewDepositfor UI quotes and forminSharesOuton deposit. It is the tightest bound the spec guarantees won't over-promise. - Use
convertToSharesfor accounting, share-price display, and internal math where you want a fee-free ratio. Do not use it as a slippage bound: on any vault with a deposit fee or live-state-dependent pricing it over-quotes and reverts honest deposits. - Caveat:
previewDepositis a quote, not a guarantee. State can change between preview and deposit (another tx in the same block, a donation), so the realized mint can be lower. That is whydeposit's return value is the ground truth and why you compare it tominSharesOutafter the call. - Rounding: both round down, so
previewDepositcan under-report by up to 1 wei; that is safe for a min-out bound but means preview and actual can differ by 1 wei even with no fee.
Failure modes.
- Fee-on-deposit vault plus
minOut = convertToShares→ every deposit reverts. - Inflation/donation attack: first depositor donates to inflate share price;
convertToShareson a tiny deposit rounds to 0. Mitigate with a virtual shares/assets offset or dead shares. - Stale preview: preview in one block, deposit in the next, price moved → realized shares below
minOut→ revert.
Curated: · Written: · Reviewed:
Q&A-64A Uniswap v2 pair takes 0.3% on the input. When is x*y=k true, and which k do you compare?
Core answer (first 90 seconds)
x*y=k is true on the reserves after the swap, and it holds because the fee is left in the pool. The pair enforces that the product of the two reserve balances never decreases across a swap. So the k you compare is the product of the current reserves before the swap against the product after: k_after ≥ k_before. There is no fixed constant k you check against: k is a moving quantity that ratchets up by the fee.
The 0.3% is charged on the input, not the output. The pair computes amountInWithFee = amountIn * 997, then amountOut = (amountInWithFee * reserveOut) / (reserveIn * 1000 + amountInWithFee). The full amountIn, fee included, is added to reserveIn; only amountOut is removed from reserveOut. That asymmetry is exactly what makes k grow.
Worked example
Pool 100/100, swap in 1.
amountInWithFee = 997. amountOut = 997100 / (1001000 + 997) = 99700 / 100997 = 0.98716. newX = 101, newY = 100 − 0.98716 = 99.01284, k_after = 101 * 99.01284 = 10000.30.
| model | out | k_after |
|---|---|---|
| no fee | 0.99010 | 10000.00 |
| 997/1000 | 0.98716 | 10000.30 |
Without the fee, k is exactly conserved at 10000. With the fee, k rises by about 0.30: the fee stays in the pool.
Alternatives and when they apply
- Compare k_after to k_before (correct for v2). This is a conservation check: it guarantees a single swap cannot drain the pool.
- Compare to a stored constant k0. Wrong for v2, because k is not constant: it only looks constant in the no-fee idealization. Asserting k == k0 rejects every legitimate swap.
- Constant-sum / stableswap (Curve). A different invariant, x+y held near constant in the balanced region, used when assets should trade near 1:1. Constant product is the right choice when you want price to move with inventory and neither side to be fully depleted.
- Spot vs TWAP. reserveOut/reserveIn is the instantaneous price and is manipulable within a block; a TWAP over N blocks is the alternative when you need a manipulation-resistant price. The invariant says nothing about price: it is a reserve-conservation rule.
Failure modes
- Dropping the 997 factor: you compute amountOut as if there were no fee, overpay the output, and k_after drops below k_before. An arbitrageur can then extract value. Detect it by asserting k_after ≥ k_before after every swap, in tests and on-chain.
- Comparing k to a fixed constant: rejects valid swaps.
- Treating spot price as an oracle: flash-loan manipulation moves it within one block.
How to check
Assert k_after ≥ k_before after every swap. That single assertion catches the missing-fee bug, because the fee is the only reason k is allowed to grow.
Curated: · Written: · Reviewed:
Q&A-65Why is token.balanceOf(pair)/balanceOf(other) not an oracle, even inside the same block as your borrow?
Core answer. balanceOf(pair) is not the pool's price. It is the pool's ERC-20 balance, and any holder of that token can change it with a plain transfer. getReserves() is the cached reserve, which only moves on swap, mint, burn, or sync. So balanceOf(pair)/balanceOf(other) can be moved without a swap, without a flash loan, and inside the same transaction as your borrow. "Same block" buys you nothing: the manipulation is atomic with your read, so it is already in place when you look.
Mechanism. A v2 pair stores reserve0 and reserve1. balanceOf(pair) and the reserve are equal only while nobody has sent tokens directly. A direct transfer of token0 to the pair raises balanceOf(pair) for token0 and leaves reserves and k untouched. If other is the pair's other token, the ratio jumps; if other is any token outside the pair, the ratio is meaningless to begin with. Either way it is not the price.
Worked example, a 1000 USDC / 1 WETH pool at 1000 USDC per WETH:
| step | balanceOf(pair) USDC | reserve0 USDC | ratio | k |
|---|---|---|---|---|
| start | 1000 | 1000 | 1000 | 1000 |
| attacker transfers 1000 USDC to pair | 2000 | 1000 | 2000 | 1000 |
| your borrow reads the ratio | 2000 | 1000 | 2000 | 1000 |
attacker calls skim() | 1000 | 1000 | 1000 | 1000 |
The attacker's cost is gas. Uniswap v2's skim(to) transfers balance - reserve to the caller, so the donated 1000 USDC comes straight back after your borrow. The donation is a loan to the pool, not a loss.
Same block is the wrong defence. The attacker does not need a prior block. transfer to the pair, call your borrow, then skim: one transaction, one block, and your read sees the inflated balance because the transfer executed earlier in the same call stack. Atomicity is the attacker's tool here, not yours. A same-block check only helps if you also prove the balance equals the reserve at the moment you read it.
Why a TWAP survives this. v2's cumulative price is derived from reserves, updated on swap, mint, burn, and sync. A bare transfer never touches it, so a 30-minute TWAP is unaffected by a donation. The attacker can call sync() to fold the donation into reserves and move the TWAP, but sync() makes the donation real, skim() can no longer recover it, so the attack now costs the full donated amount for the window it is held. That is the difference between free and expensive.
Detection. Never price from balanceOf(pair). If you must read balances, assert they match reserves and revert on mismatch:
// Uniswap v2 pair, Solidity 0.8.x
(uint112 r0, uint112 r1, ) = pair.getReserves();
uint256 b0 = token0.balanceOf(address(pair));
uint256 b1 = token1.balanceOf(address(pair));
require(b0 == r0 && b1 == r1, "balance/reserve desync");
That check catches the donation, but it is a guard, not a price. For collateral, use a windowed TWAP over at least 30 minutes, a Chainlink feed with a staleness bound, or both with a deviation cap. The ratio of two balances is a number an attacker can write; a reserve-derived TWAP is one they have to hold.
Curated: · Written: · Reviewed:
Q&A-66Uniswap v2 cumulative prices can build a TWAP. Why is a 1-block TWAP useless, and what window do you pick for a $5M pool?
Assumptions first: mainnet, 12-second blocks, a $5M pool of real liquidity, and the TWAP feeds something that pays out on a wrong price (lending collateral, options settlement). On an L2 with 2s blocks, every block count below scales by six.
The direct answer: a 1-block TWAP is useless because it is not an average at all. It is the previous block's closing price. Uniswap v2's accumulator updates at most once per block and records the price before the current operation, so a one-block window returns exactly one price sample. It is spot with a rounding step, and a single swap in the prior block sets it.
Mechanism. The pair stores price0CumulativeLast and price1CumulativeLast. On every swap, mint or burn, _update() runs first:
uint32 timeElapsed = blockTimestamp - blockTimestampLast;
if (timeElapsed > 0 && _reserve0 != 0 && _reserve1 != 0) {
price0CumulativeLast += uint(UQ112x112.encode(_reserve1).uqdiv(_reserve0)) * timeElapsed;
}
The price added is reserve1/reserve0 before the swap: the price that held since the last update. So the cumulative is ∫price dt sampled at block boundaries. A TWAP over window W is (cum(T) - cum(T-W)) / W. With W = 12s and one update in that interval, the difference is price × 12s, and dividing by 12s gives back that single price. No smoothing happened. The accumulator's resolution is one block, so any window shorter than two blocks carries at most one sample.
Two consequences. An attacker who moves the price in block N and is read in block N+1 gets the manipulated price. And if no swap occurs in the window, the cumulative does not change and the TWAP is 0: a quiet pool returns zero, not a stale price.
Window for a $5M pool. The cost to move a W-second TWAP by δ is the capital needed to hold the skew for the whole window, because the TWAP is time-weighted: a skew held for half the window moves it half as far. On a 50/50 $5M pool (x = y = $2.5M), moving the price 10% needs Δx = x(1 − 1/√1.1) ≈ $116k swapped in; doubling it needs x(1 − 1/√2) ≈ $732k. Those are entry costs. The attacker then has to defend the skew for the window against arbitrageurs, and every block they fail, the price reverts.
1800s (30 min, 150 mainnet blocks) is the usual default for a pool this size: the attacker must hold and defend a six-figure skew across 150 consecutive blocks, and the arbitrage profit available to anyone who corrects a 10% mispricing on $5M is large enough that defending it for 30 minutes costs more than most manipulations pay. 30 minutes also tracks a real move within a few percent, so it does not lag a genuine crash the way a 24-hour window would.
Deciding criteria, in order: (1) cost to manipulate exceeds the maximum profit from a wrong price; (2) window short enough that a real price move shows up before it matters; (3) enough swaps in the window that the TWAP is not zero or stale. For a $5M pool, 1800s satisfies all three. A $50M pool can use 600s; a $500k pool needs hours or a different oracle.
Failure modes. Zero or stale TWAP on a quiet pair: detect by checking the cumulative actually changed. Single-block manipulation of the first block after a long quiet period. And the v2 accumulator stores no history: you must snapshot priceCumulativeLast at the start of your window yourself, in your own contract or off-chain, or you have no window at all.
Curated: · Written: · Reviewed:
Q&A-67A v3 position is in range only between ticks 200000 and 200200. What is the price of that position outside the range, and why do v2-style x*y formulas fail?
Core answer (first 90 seconds)
Ticks are prices, not indices: p = 1.0001^tick. So the range is p_lower = 1.0001^200000 ≈ 4.847×10⁸ and p_upper = 1.0001^200200 ≈ 4.945×10⁸ token1 per token0: a 200-tick, ~2.0% band.
Outside that band the position is single-sided, and the amount is fixed by L and the two boundary ticks:
- price ≤ p_lower: 100% token0, amount0 = L(1/√p_lower − 1/√p_upper)
- price ≥ p_upper: 100% token1, amount1 = L(√p_upper − √p_lower)
With √p_lower ≈ 22015 and √p_upper ≈ 22237, that is amount0 ≈ 4.52×10⁻⁷·L and amount1 ≈ 221.2·L. For L = 10¹⁸: ≈ 4.52×10¹¹ token0 (451.8 at 18 decimals) below the range, ≈ 2.21×10²⁰ token1 (221.2) above it. Below the range the token1-value is amount0 × p and still moves with price; above it the value is the constant amount1. At the boundaries the value is continuous: it just stops changing once price clears p_upper.
Why x·y fails
v2's x·y = k is an invariant on actual reserves, and price = y/x. v3 replaces it with
(x + L/√p_upper)(y + L√p_lower) = L²
The terms L/√p and L√p are virtual reserves; their product is L² at every price. Actual reserves x, y are what remains after the virtual part is subtracted, and they satisfy a constant-product relation only loosely. Out of range one actual reserve is exactly 0, so x·y = 0: the formula returns nothing. And y/x is 0 or ∞, so the v2 price-from-reserves step is undefined. In v3 the price is set by the tick (√P in slot0); reserves are derived from L and the range, not the other way round.
Trade-offs, which valuation to use
| Method | Value | When |
|---|---|---|
| Current tick (slot0.sqrtPriceX96) | Instantaneous mark | Swap quotes, UI; slot0 is spot and flash-loan manipulable within a block |
| Boundary tick | Conservative: p_lower below range, p_upper above | Liquidation thresholds, collateral haircuts |
| TWAP via observe() | Manipulation-resistant, lagged | Oracle-style valuation, not a live quote |
Failure mode
Treating a v3 NFT as v2 reserves: an out-of-range position gets counted as 50/50. Detect it by computing amount0/amount1 from L and the ticks and comparing against the pool's actual token balances, if the position is out of range, one side must be 0.
Curated: · Written: · Reviewed:
Q&A-68LTV is 75% and liquidation threshold is 80%. What can a user borrow on $10_000 collateral, and when does liquidation start?
Assume one collateral asset, no accrued interest yet, and a stable oracle price. Max borrow = LTV × collateral = 0.75 × $10,000 = $7,500. Liquidation begins when debt exceeds the liquidation threshold times collateral value: 0.80 × $10,000 = $8,000. Health factor = (collateral × LT) / debt, and the position is liquidatable when HF < 1.
So the user draws $7,500 and has $500 of headroom before the seizure line. That $500 is the entire reason the two numbers exist: LTV caps new borrows, LT is where a keeper can act, and the gap between them absorbs price moves and interest before anyone gets liquidated.
Two ways to walk from $7,500 of debt to $8,000:
- Interest. $500 on $7,500 is 6.67% of principal. At a 5% variable APR with no repayment, that is roughly 16 months.
- Price. Collateral must fall to 7500 / 0.8 = $9,375, a 6.25% drop from $10,000.
| Debt | HF = 8000 / debt | Liquidatable? |
|---|---|---|
| 7,500 | 1.067 | no |
| 7,900 | 1.013 | no |
| 8,000 | 1.000 | at the line: Aave requires HF < 1, so not yet |
| 8,100 | 0.988 | yes |
Tight gap vs wide gap. A tight gap, LT only a point or two above LTV, gives borrowers more leverage per dollar of collateral but leaves almost no room for oracle lag or a fast candle. A wide gap is safer for the protocol and caps capital efficiency. Compound v2 used a single collateral factor for both the borrow limit and the liquidation line, so a max borrow sat at HF = 1 by construction. Aave v3 splits the two parameters precisely so a max borrow starts above 1. The deciding criteria: collateral volatility (a 6.25% intraday move is routine for a mid-cap token, rare for ETH), oracle update cadence and deviation threshold, and how deep the liquidation market is, if keepers cannot clear a position in one block, run a wider gap. Stablecoin collateral can carry a tight gap; long-tail collateral should not.
Failure modes.
- LTV set equal to LT. A max borrow is instantly liquidatable on any downward tick or interest accrual. Detect it by histogramming HF across open positions; a cluster at 1.0 is the signal.
- Interest drift. Variable-rate debt rises with no user action, so a position at HF 1.067 crosses 1.0 in months at high rates, not years.
- Oracle. A stale or manipulated price moves collateral value and HF together; a 6.25% deviation is enough to liquidate a max-borrow position.
Keepers repay the debt and seize collateral plus a liquidation bonus, so the borrower loses more than the $500 gap suggests.
Curated: · Written: · Reviewed:
Q&A-69A keeper liquidates $100 of debt at a 5% bonus and 50% close factor. How much collateral leaves, and why does a 100% close factor cascade?
$50 of debt is repaid and $52.50 of collateral leaves the position.
The keeper can only repay min(debt × closeFactor, repayAmount). With $100 of debt and a 50% close factor, the repayment is capped at $50 even if the keeper offers more. The bonus is paid out of the borrower's collateral, so the seized amount is repay × (1 + bonus) in USD terms: 50 × 1.05 = $52.50. The position keeps $50 of debt and loses $52.50 of collateral; the keeper's gross profit is the $2.50 bonus, minus gas and the slippage from selling the seized collateral. Two preconditions gate the whole thing: the position must be liquidatable (health factor < 1), and the keeper must be willing to front the repay amount.
Why a 100% close factor cascades
Close factor is the throttle on how much of a position one transaction can take. At 50%, a liquidation leaves the borrower healthier than it found them. At 100%, one transaction can wipe the position entirely, and that is what turns a single liquidation into a cascade.
Work the arithmetic. Take a position with $115 of collateral, an 85% liquidation threshold, and $100 of debt. Health factor = 115 × 0.85 / 100 = 0.9775, so it is liquidatable.
| Close factor | Repay | Collateral seized | HF after |
|---|---|---|---|
| 50% | $50 | $52.50 | 1.0625 |
| 100% | $100 | $105 | position closed |
At 50% close the position is out of liquidation range after one transaction: remaining collateral $62.50, remaining debt $50, HF = 62.50 × 0.85 / 50 = 1.0625. At 100% close the position is gone in one transaction and the keeper holds $105 of collateral to sell.
The general form makes the difference explicit. After repaying a fraction f of the debt and seizing f × D × (1 + bonus) of collateral, HF' = [HF − f(1 + bonus)t] / (1 − f), where t is the liquidation threshold. Plug in f = 0.5, bonus = 0.05, t = 0.85, HF = 0.9775: [0.9775 − 0.44625] / 0.5 = 1.0625. With f < 1, HF' exceeds 1 whenever HF > f(1 + bonus)t: for these parameters that threshold is 0.446, so any liquidatable position recovers. At f = 1 the expression divides by zero: there is no debt left, so there is no recovery, only a closed position.
That is the cascade. The keeper sells the $105 of seized collateral. If that market is thin, the sale pushes its price down. Every other borrower holding it sees collateral value fall, so their health factor falls too. Positions sitting at 1.00–1.05 cross below 1, become liquidatable, and with a 100% close factor each is fully wiped in a single transaction: producing more seized collateral to sell. Liquidation drives the price down, which drives more liquidation. A 50% close factor breaks the loop because each liquidation leaves the position above HF 1: the keeper cannot extract the whole book in one swing, and the borrower keeps collateral that keeps them solvent.
Two failure modes follow. First, with 100% close the keeper seizes 1.05 × D of collateral; if the position holds less than that, the shortfall becomes protocol bad debt, and the borrower has no collateral left and no reason to repay. Second, a 100% close factor removes any partial-recovery path, so a borrower who would have topped up after a 50% liquidation instead loses everything.
Detection: measure the price impact of one liquidation against the collateral's market depth, count positions within a few percent of HF 1, and check whether the close factor is 100% with a large bonus. If liquidating a marginal position leaves HF below 1, the parameters permit a cascade.
Curated: · Written: · Reviewed:
Q&A-70A flash loan of 1_000_000 USDC must be repaid in the same transaction. What can the borrower do in the middle, and what can they not roll past the tx end?
The 90-second answer
Pin down the pool and the premium first. Aave V3 charges 0.05% (5 bps) on the borrowed amount as of V3.1; it was 0.09% before that. On 1,000,000 USDC that is 500 USDC of premium (900 at the old rate), so 1,000,500 USDC has to be back in the pool before the transaction ends.
Atomicity is not a lock the EVM hands you. The pool sends you the 1,000,000, calls executeOperation on your contract, and after you return true it pulls amount + premium back with transferFrom. If the balance or the approval is not there, that transfer reverts and every state change in the transaction unwinds, including whatever you did with the money.
In the middle you can do anything 1,000,000 USDC of capital that exists for one transaction buys: arbitrage across venues, liquidate an underwater borrower, swap collateral, move an AMM spot price, buy governance tokens and vote, or drain a second protocol that trusts a balance it can read. What cannot survive the end of the transaction is the debt, and any state that only holds because you still have the tokens.
How the check actually works
// Aave V3 pool, Solidity 0.8.20
function executeOperation(
address asset,
uint256 amount, // 1_000_000e6
uint256 premium, // 500e6 at 5 bps
address, // initiator
bytes calldata
) external returns (bool) {
require(msg.sender == POOL, "not pool");
// spend `amount` here: arb, liquidate, vote, drain
IERC20(asset).approve(POOL, amount + premium);
return true; // pool then pulls amount + premium
}
| Point in the tx | Pool's USDC | Your obligation |
|---|---|---|
| before | B | 0 |
| pool sends 1,000,000 | B − 1,000,000 | 1,000,000 |
| callback runs | B − 1,000,000 | 1,000,000 |
| pool pulls 1,000,500 | B + 500 | 0 |
| pull fails | revert → B | revert |
If your arbitrage only produced 1,000,300, the pull fails, the tx reverts, and you do not keep the 300. That is the whole guarantee.
What cannot roll past the tx end
- The debt. No partial repayment, no extension, no settling next block. Aave V3 requires repayment in the same asset.
- Token balances. Any USDC you still hold at the end came from somewhere else; the borrowed 1,000,000 is gone.
- Prices that only moved because of your trade. If an oracle reads a spot pool you just pushed, the price reverts with the tx. A TWAP over a window longer than one block dilutes it.
- Governance weight read at execution time. A snapshot taken at a later block sees your normal balance.
- Any position that needs the capital to still be there. It has to be funded by something else before the callback returns.
The nuance: the loan does not persist, but a self-funding position opened with it does. Flash-borrow 1,000,000, deposit it as collateral, borrow 800,000 against it, repay the flash loan. The flash loan is gone; the 800,000 debt is not.
Failure modes and how to detect them
- Quorum or vote weight from
balanceOfat execution time. The April 2022 Beanstalk exploit flash-borrowed roughly $1B, converted it to Stalk, and passed an emergency proposal that drained about $182M. Test: does the weight come fromgetPastVotes/ERC20Snapshotat a prior block, or from the current balance? - Spot-price oracle. Test: can one transaction move the pool the price is read from, and is the TWAP window longer than a block?
- Balance-as-deposit accounting (ERC-4626 style). Test: does share price use
totalAssets()= token balance? A flash deposit then inflates it. - Liquidation. A flash loan removes the capital requirement, so your liquidation bonus is anyone's budget. Test: can a contract with zero capital liquidate a healthy-looking position in one tx?
The test I would write first: flash-borrow the governance token, vote, repay, and assert the proposal still fails.
Curated: · Written: · Reviewed:
Q&A-71A user swaps 50 ETH with 0.5% slippage on a $2M pool. How does a sandwich work, and which number actually protects them?
The 60-second answer
A sandwich is two trades wrapped around yours: a searcher front-runs your swap to push the price against you, lets your swap fill at the worse price, then unwinds at a profit. Your swap's only on-chain protection is minAmountOut: the slippage setting. The deadline stops stale inclusion; private orderflow hides you from the mempool. Neither bounds the price you accept.
Then check the numbers, because they decide the answer. 50 ETH into a $2M pool is not a 0.5% trade. Assume a 50/50 pool at ETH = $2,000: reserves are 500 ETH and 1,000,000 USDC. Selling 50 ETH moves the ETH reserve to 550, so the constant-product output is 1,000,000 − (500 × 1,000,000)/550 = 90,909 USDC against a spot value of 100,000: a 9.09% price impact. A 0.5% minAmountOut is 99,500 USDC. The honest fill is already below it, so the swap reverts. No sandwich lands, because there is nothing to sandwich.
So the number that protects is minAmountOut, and here it is set so tight the trade fails rather than fills.
How the sandwich works
You are selling ETH, so your swap adds ETH to the pool and pushes the ETH price down. A searcher profits by selling ETH ahead of you (pushing it down further), letting your larger sell clear at the depressed price, then buying ETH back cheap. The pool is a constant product x·y = k; every trade moves the price along that curve, and the searcher's two trades straddle yours to capture the difference. The victim's fill is worse than the honest fill by exactly the price move the searcher caused.
Worked trace (assume a loose 10% minOut so the swap can fill; 0.3% fee ignored for clarity)
| Step | Pool ETH | Pool USDC | Result |
|---|---|---|---|
| Start | 500 | 1,000,000 | k = 5×10⁸ |
| Searcher front-run: sell 10 ETH | 510 | 980,392 | searcher gets 19,608 USDC |
| Victim: sell 50 ETH | 560 | 892,857 | victim gets 87,535 USDC (3.7% below the honest 90,909) |
| Searcher back-run: buy with 19,608 USDC | 547.96 | 912,465 | searcher gets 12.04 ETH |
Searcher net: +2.04 ETH ≈ $4,080, minus gas. The victim's loss is the searcher's gain plus the pool's fee. With the question's real 0.5% minOut, the victim's row reverts at 87,535 < 99,500 and the whole sequence is moot.
What to actually do
- Set
minAmountOutfrom a fresh quote minus a few bps of expected impact, not a default. For a 50 ETH sell here, the honest impact is ~9%, so the tolerance has to be sized to the trade, not to a habit. - If the trade is more than ~1% of the pool, split it across blocks or route through private orderflow so it never appears in the public mempool.
- The deadline bounds staleness only. It does not bound price.
Failure modes
- Tolerance too tight: the swap reverts. Detect via failed tx / no fill; the user pays gas and gets nothing.
- Tolerance too loose: extraction. Detect by simulating the sandwich around the exact calldata, if searcher profit exceeds gas, tighten
minAmountOutor split. - Stale inclusion: a pending tx sits in the mempool and gets sandwiched at a later block. The deadline caps how long that window stays open.
Curated: · Written: · Reviewed:
Q&A-72Aave-style indexes use 1e27 (ray). Why do you never multiply two token amounts in ray without dividing, and what does index=1.04e27 mean?
Ray is a fixed-point scale, not an amount. 1e27 is "1.0". So index = 1.04e27 reads as 1.04: the index has grown 4% since it was initialised to 1e27, and a scaled balance of 1000e18 now redeems 1040e18 tokens. Multiplying two ray-scaled values produces a number at 1e54 scale: no unit, no meaning. You divide by RAY to get back to token units.
Why the divide is structural. Aave stores supply and debt as scaled balances: scaledBalance = amount / index. The index is monotonic non-decreasing, so a scaled balance stays put while the underlying amount grows. Every read back is amount = scaledBalance * index / RAY. Drop the /RAY and you have multiplied a token amount by 1e27; the result is 1e27 times too large. That is the entire bug class.
The arithmetic.
| scaledBalance | liquidityIndex | scaled * index | / RAY (assets) | no divide |
|---|---|---|---|---|
| 1000e18 | 1e27 | 1e48 | 1000e18 | 1e48 |
| 1000e18 | 1.04e27 | 1.04e48 | 1040e18 | 1.04e48 |
The last column is the fourth column times 1e27. Nothing reverts; the value is just wrong.
Overflow sets the rule "one ray factor per product". uint256 tops out at ~1.16e77. A scaled balance for a 1e12-token reserve is ~1e30; times one ray index that is 1e57 and fits. Multiply by a second ray factor and you are at 1e84 and the arithmetic wraps or reverts. So: at most one ray factor in any product, and divide immediately after.
mulDiv vs plain division.
| form | overflow | rounding | use when |
|---|---|---|---|
a * b / RAY | reverts if a*b > 2^256-1 | floor | you can prove a*b fits |
Math.mulDiv(a, b, RAY) | 512-bit intermediate; reverts only if the result doesn't fit | floor | inputs are unbounded or user-supplied |
WadRayMath.rayMul(a, b) | assembly mul wraps silently | half-up | hot path, a*b provably bounded |
rayMul is the cheap one and the dangerous one: the assembly mul does not revert on overflow, so the precondition a <= (type(uint256).max - HALF_RAY) / b is on you. mulDiv pays for a 512-bit intermediate and is safe for arbitrary inputs. Both run once per user action, so the gas difference is not the bottleneck: pick mulDiv unless you have a bound you can point at.
// Aave V3 WadRayMath, ray = 1e27
function rayMul(uint256 a, uint256 b) internal pure returns (uint256 c) {
if (a == 0 || b == 0) return 0;
assembly {
c := mul(a, b)
c := add(div(c, RAY), gt(mod(c, RAY), HALF_RAY)) // half-up
}
}
Failure mode. The repay path is where this bites, because it inverts the formula: scaledBurn = amount * RAY / index. Take a user repaying 1040e18 against index = 1.04e27; the correct burn is 1000e18 scaled. If the divide is dropped, the contract computes 1040e18 * 1.04e27 ≈ 1.08e48 scaled units. Under Solidity 0.8 checked arithmetic the subsequent subtraction reverts and the bug is loud. It goes quiet when the product is stored rather than subtracted: written into a user's scaled balance, it credits a position 1e27 times too large, and that user can withdraw the reserve. Detection: assert scaledBalance * index / RAY round-trips to the stored amount, and fuzz the conversion with index at both 1e27 and large values.
Curated: · Written: · Reviewed:
Q&A-73A rate model is 0–80% utilization at slope1, then a steep slope2. Why is 90% utilization not "slightly more" than 80%, and who gets liquidated?
Direct answer. Utilization is borrowed/supplied, and a kink model prices the marginal unit of liquidity, not the average. Below the kink the marginal price is slope1; above it, slope2. So 80%→90% is not ten points of the same curve: it is ten points priced at slope2, and those ten points cost more than the first eighty combined. The borrowers who get liquidated are the ones whose health factor was already near 1 on the asset whose borrow rate spiked: the rate does not create the liquidation, it accelerates the clock on positions the price move had already put at the edge.
The arithmetic. Take a labelled hypothetical: base 0%, slope1 5%, slope2 60%, kink 80% (round numbers, not a specific deployment).
APR(u) = base + slope1·min(u, kink) + slope2·max(0, u − kink)
| u | borrow APR | APR added by the next 1% of u |
|---|---|---|
| 79% | 3.95% | 0.05% |
| 80% | 4.00% | 0.60% |
| 90% | 10.0% | 0.60% |
| 95% | 13.0% | 0.60% |
| 100% | 16.0% | — |
The whole 0→80% range adds 4.00% APR. The 80→90% range adds 6.00%. The marginal price of utilization is 12x higher above the kink, which is the entire point of the kink.
Why the curve has to bend there. u = borrowed/supplied. The idle fraction (1−u) is the only liquidity that can service withdrawals and liquidations without touching outstanding loans. At u=80% there is 20% of supply sitting idle; at 90% there is 10%; at 100% there is none and suppliers cannot withdraw at all. The rate is the auction price for that shrinking buffer: it has to rise steeply enough to (a) pull new deposits in and (b) push marginal borrowers to repay, before the buffer hits zero. A linear curve cannot do both: it either pays suppliers too little at 90% or charges borrowers too much at 50%.
Who gets liquidated. HF = Σ(collateral·LT)/Σ(debt). A rate spike does not move collateral or principal; it moves how fast debt compounds. At 4% APR debt grows 0.011%/day; at 14% it grows 0.038%/day. A position at HF 1.001 reaches HF 1 in about 9 days at 4% and about 2.6 days at 14%: the spike cuts the runway by roughly 3.5x. So the liquidated set is: borrowers already at the margin, on the debt asset whose rate spiked, and disproportionately recursive positions where the same asset is both collateral and debt. Leverage multiplies both the debt growth and the collateral's sensitivity to the unwind. Keepers watch utilization because a rate spike is a leading indicator of the liquidity crunch and price move that will actually push HF below 1.
Trade-offs. Kink placement: a lower kink (say 60%) buys a bigger buffer but leaves supplier capital idle and cheap; a higher kink (90%) is capital-efficient but the buffer is thin exactly when it matters. slope2 magnitude: too steep and a two-point utilization move is a rate shock that makes borrowers flee and destabilizes the pool; too shallow and it cannot attract supply fast enough to stop u reaching 100%. Reserve factor: it takes a cut of borrower interest before it reaches suppliers, so a high reserve factor weakens the very supply-attracting feedback slope2 depends on. The two parameters have to be tuned together.
Failure modes. u→100%: withdrawals revert, and a liquidation that needs to move collateral can stall if the debt asset is fully borrowed. Rate spike without a price move: borrowers unwind voluntarily, which is a slow bleed, not a liquidation cascade. Do not confuse the two. And a kink model tuned on one asset's flow history misprices a different asset's withdrawal profile; the kink is a policy choice, not a constant.
Curated: · Written: · Reviewed:
Q&A-75A 400 ETH swap hits the public mempool. What extra cost do you expect versus an MEV-Share/private relay path, and what do you not get?
The 60-second answer
Assume a 400 ETH swap (~$1.2M at $3k/ETH) into a pool holding ~10,000 ETH on the ETH side, so the trade is ~4% of the reserve. On the public mempool I'd expect to lose roughly my own price impact to a sandwich: order $40–60k. Through a private relay or MEV-Share I'd expect to pay a priority fee to the builder, order 0.1–0.5 ETH ($300–1,500), and lose little or nothing to a sandwich. What I don't get on the private path: a guarantee of inclusion, and any guarantee the builder set won't do the same thing. Figures here are illustrative; the shape is what matters.
Why the public path costs that
A sandwich is three txs in one block. A searcher sees your swap in the mempool, computes the price impact, and submits a buy ahead of you (front-run) and a sell behind you (back-run). You execute against the price the front-run pushed up; the attacker's back-run sells into the price your swap pushed up. The attacker's profit is approximately your price impact, and that is approximately your extra cost. With 400 ETH into a 10,000 ETH reserve, constant-product impact is 400/10,000 ≈ 4%; on $1.2M that's ~$48k. The $62k figure in the anecdote is the same order of magnitude.
What the private path actually buys you
A private RPC (Flashbots Protect, MEV Blocker) or MEV-Share sends your tx to builders instead of the gossip net. Generalized searchers never see it, so the classic sandwich doesn't fire. MEV-Share is subtler: it forwards hints (function selector, logs, sometimes calldata) to searchers, who bid to backrun you and share the refund with you. So MEV-Share is not privacy; it's a negotiated leak. If your hint set includes full calldata, a searcher can still sandwich.
What you don't get
- Inclusion. Builders choose what to include. A private tx can miss several blocks; if you set a deadline it just reverts and you've paid nothing but lost time. Inclusion rate is the metric to watch, not just sandwich incidence.
- Builder trust. The builder sees your tx in the clear. A single builder can sandwich you exactly as the mempool would. You've narrowed the set of people who can hurt you, not eliminated it.
- Verifiability. You can't easily audit what happened; you rely on the relay's reporting.
Alternatives and when not to use private
- TWAP / chunking: split 400 ETH into 20 × 20 ETH over an hour. Each chunk is ~0.2% of the pool, below the sandwich threshold, but you take timing risk and pay 20× gas.
- Batch auction / CoW-style: uniform clearing price, no ordering advantage to exploit. Good when a solver can find a counterparty.
- OTC / RFQ desk: for size where even a private relay's builder trust is unacceptable.
Private is not worth it when the trade is small relative to the pool (say <0.1%), when you need guaranteed inclusion in the next block, or when the builder set is itself the adversary you're worried about.
Detection
Log realized execution price vs an oracle mid at block time; slippage in bps is your sandwich signal. Track inclusion latency and revert rate. For the private path, compare the priority fee paid against the sandwich cost you avoided, if the fee approaches the impact, the private path isn't paying for itself.
Curated: · Written: · Reviewed:
Q&A-52A protocol has pause, mint, and upgrade. Why is a single owner address the wrong ACL, and how do roles split the blast radius?
What I'd say first
The real question is how many independent things can go wrong at once. A single owner address that can pause, mint, and upgrade is one key holding three authorities, so one compromise is simultaneously a denial of service, an inflation event, and a code change. Roles don't make a protocol safe by themselves; they let each authority sit on a different key, a different quorum, and a different delay, so the blast radius of any single key is bounded by what that role alone can do.
Assumptions: an upgradeable ERC-20-style token, OpenZeppelin AccessControl v5.x, and a team that can actually operate multisigs.
Mechanism
AccessControl stores membership in a mapping, and grantRole/revokeRole are themselves gated by DEFAULT_ADMIN_ROLE. That indirection is the point: the admin role can hand out PAUSER_ROLE but cannot pause, and PAUSER_ROLE can pause but cannot grant anything. The three authorities become three separate trust domains.
// OpenZeppelin AccessControl v5.x
bytes32 public constant PAUSER_ROLE = keccak256("PAUSER_ROLE");
bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE");
bytes32 public constant UPGRADER_ROLE = keccak256("UPGRADER_ROLE");
function pause() external onlyRole(PAUSER_ROLE) { _pause(); }
function mint(address to, uint256 amt) external onlyRole(MINTER_ROLE) { _mint(to, amt); }
function _authorizeUpgrade(address) internal override onlyRole(UPGRADER_ROLE) {}
DEFAULT_ADMIN_ROLE is granted to none of the operational roles; it lives on a separate admin multisig. The daily mint cap is enforced inside mint, not by the role: a role says who, a cap says how much.
| Role | Holder | Authority | Blast radius if that key leaks |
|---|---|---|---|
PAUSER_ROLE | 3-of-5 ops | pause / unpause | DoS until unpause |
MINTER_ROLE | 4-of-7, plus 1e6/day cap | mint | capped inflation |
UPGRADER_ROLE | 4-of-7 behind 48h timelock | swap implementation | code change, delayed |
DEFAULT_ADMIN_ROLE | 5-of-8, cold storage | grant / revoke | can reassign roles |
Costs, and when a single owner is fine
The role check itself is cheap: a cold SLOAD plus a hash compare, a few thousand gas on calls that are rare and already expensive, so gas is not the deciding factor. The real costs are operational. A 3-of-5 and a 4-of-7 means 7–12 signers, key ceremonies, hardware wallets, and a signing runbook; a pause during a live exploit now needs three people awake and reachable, and that latency is the price. A 48h timelock means you cannot hotfix an upgrade, so you need a separate emergency pause path or you trade one risk for another.
A single owner behind a timelock is defensible when the only privileged action is upgrade and the timelock is the actual control: small TVL, a fixed-supply token with no MINTER_ROLE, or a team that cannot staff multisig ceremonies. Then splitting roles adds signer overhead for little gain. If mint is fixed at deploy, the mint blast radius is already zero.
Failure mode
Worked example (hypothetical): a leaked deployer key holding all three roles paused the token and minted 50e6 in 4 minutes; the market fell 38% before the 12h ops review. Detection is an alert on Minted events above a threshold and on Pause(). With the split, the cap would have stopped minting at 1e6/day, and the pause key alone could not have minted at all.
Verification
A role matrix in the repo plus a test asserting the pauser cannot mint:
function test_pauserCannotMint() public {
vm.prank(pauser);
vm.expectRevert();
token.mint(pauser, 1e6);
}
The point isn't that roles are always right: it's that one key holding three authorities carries three times the blast radius of one key holding one.
Curated: · Written: · Reviewed:
Q&A-53Governance votes an implementation hash. Why wait 48 hours on a timelock, and what can still go wrong during the wait?
The 60-second answer
The delay is an exit window, not a security review. It buys token holders and integrators time to withdraw, sell, or fork before new bytecode takes effect, and it gives watchers time to decode the queued calldata and cancel. 48h is a convention: long enough for a coordinated exit across time zones, short enough that the protocol can still ship. The number that matters is the minimum delay enforced by the timelock contract, not the delay written in the proposal text.
Assumptions: an OpenZeppelin TimelockController owns the proxy admin; the Governor holds PROPOSER_ROLE and EXECUTOR_ROLE; TIMELOCK_ADMIN_ROLE is held by the timelock itself, not an EOA.
What the delay actually guarantees
One thing only: a specific operation id cannot execute before its scheduled timestamp plus the delay. In TimelockController the id is
// OpenZeppelin TimelockController (v4.x)
bytes32 id = keccak256(abi.encode(target, value, data, predecessor, salt));
// execute() requires:
// getTimestamp(id) > _DONE_TIMESTAMP // scheduled, not done
// getTimestamp(id) <= block.timestamp // delay elapsed
// isOperationDone(predecessor) // predecessor satisfied
Note what is absent: an expiry. Once ready, an operation stays executable indefinitely until someone with CANCELLER_ROLE cancels it.
What still goes wrong during the wait
-
The calldata is not the description. Voters approve a description hash; the executor runs
data. If a benign description and hostiledataend up in the same proposal, the 48h only helps if someone decodes the calldata. Comparing hashes is not enough: the hash covers the description, not the intent. -
A second operation under a different salt. The id includes
salt, so the same(target, value, data)can be queued twice under different salts. Watchers tracking "the proposal" rather than every scheduled id miss the second one. The unit of monitoring is the operation id. -
The admin role can shorten the delay.
updateDelay(newDelay)isonlyRole(TIMELOCK_ADMIN_ROLE). If that role sits with an EOA or multisig instead of the timelock, the holder can setminDelayto 0 and schedule new operations with no wait. Already-queued ops keep their timestamp; the guarantee is gone for everything after. -
No expiry means an open-ended window. A watcher who stops at t+48h misses execution at t+72h. The delay is a floor on when execution can happen, not a scheduled time.
-
Batching hides the payload.
scheduleBatchqueues many calls under one id. Reviewing the headline call and missing the last element of the array is the same failure as (1). -
The exit window may not be usable. If the upgrade changes the oracle or the withdrawal path, users may be unable to exit at par during the wait. A delay on a lending market whose only exit is that market is not an exit window.
-
Downstream timing differs. If the timelock drives a bridge or message sender, the effect lands on the destination chain later, and users there get less warning than the source-chain clock suggests.
A worked trace (hypothetical)
| t | Event | Operation id | Ready? |
|---|---|---|---|
| 0h | schedule(proxy, 0, upgradeTo(B), 0x0, salt1, 48h) | id1 | no |
| 10h | schedule(proxy, 0, upgradeTo(C), 0x0, salt2, 48h) | id2 | no |
| 48h | execute(...salt1) | id1 | yes |
| 58h | execute(...salt2) | id2 | yes |
A monitor that alerts on "proposal queued" fires once at t=0 and never again. A monitor that alerts on every CallScheduled event fires twice, and the second alert is the one that matters.
Detection
Decode every CallScheduled and CallExecuted event, diff the decoded calldata against the proposal description in CI, and alert on updateDelay and on any schedule whose target is the proxy admin. Treat the timelock's own admin role as the root of trust: if it is not the timelock, the delay is advisory.
Curated: · Written: · Reviewed:
Q&A-54What should pause() stop, when should exits remain open, and when can an exploit require a full freeze?
Core answer. pause() should stop new risk-in: deposits, borrows, opening leverage, and any path that prices collateral off a source you no longer trust. It should leave exits open: withdraw, repay, redeem, and liquidations that reduce protocol exposure. Exits stay open because a paused exit turns a market problem into a custody problem: users who cannot redeem sell into a thinner secondary market, the token depegs further, and the protocol's solvency ends up worse than the incident that triggered the pause. A full freeze of an exit is justified only when that exit is the exploit path: a withdraw that reads a manipulable price, a transfer hook that reenters, a redeem that drains a stale oracle, and even then it must be scoped to the affected function and asset, not the whole contract.
Mechanism: pause bits, not one bool. A single global paused forces the operator to choose between blocking the attack and blocking the escape. Split it.
// Solidity 0.8.24
uint256 public constant RISK_IN = 1 << 0; // deposit, borrow, open
uint256 public constant EXIT = 1 << 1; // withdraw, repay, redeem
uint256 public constant TRANSFER = 1 << 2; // token moves, hooks
modifier whenNotPaused(uint256 bit) {
require((paused & bit) == 0, "paused");
_;
}
Keep the parentheses. paused & bit == 0 parses as paused & (bit == 0), which is paused & false: the guard never reverts and the pause silently does nothing.
| Function | Bit | Normal | Risk-in pause | Exploit freeze |
|---|---|---|---|---|
| deposit / borrow | RISK_IN | open | blocked | blocked |
| withdraw (healthy) | EXIT | open | open | open |
| withdraw (manipulable price) | EXIT | open | open | blocked, that market only |
| repay / redeem | EXIT | open | open | open |
| token transfer hook | TRANSFER | open | open | blocked if reentrant |
When an exploit forces a freeze. Freeze an exit only when the exit itself is the drain: a withdraw that computes value from a spot price the attacker moves in the same transaction, a redeem that reads an oracle you have already lost confidence in, or a token callback that reenters deposit. Scope it to that function and that asset. A freeze on every exit is a different, larger decision: it strands users who are not part of the attack and hands the attacker a griefing primitive.
Worked example (hypothetical figures). A protocol with $14M TVL hits an oracle incident. The operator sets the global pause, which also blocks withdraw. Redemption stays closed for 31 hours. With no on-chain exit, holders sell on a secondary market at a 12% discount: roughly $1.68M of value destroyed by the pause itself, on top of whatever the oracle cost. The correct move was RISK_IN only: block new borrows against the bad price, leave withdraw open, and fix the oracle under the timelock.
Detection and recovery. Two unit tests pin the behaviour: a risk-in pause makes deposit revert while a healthy withdraw still succeeds; an exploit freeze blocks only the affected exit and leaves repay and the emergency recovery path callable. Alert if the EXIT bit stays set past the incident window, and route unpause through the timelock: never automatic, because the condition that triggered the pause may still hold when the timer fires.
Preserve exits by default; freeze an exit only when that exit is the exploit, and scope the freeze to it.
Curated: · Written: · Reviewed:
Q&A-12An intern caches eth_getLogs from latest every 15 seconds and never records blockHash. What breaks on a 4-block reorg?
Direct answer: The cache cannot tell canonical logs from orphaned ones, so after a 4-block reorg it keeps serving logs from blocks that no longer exist and misses logs that only exist on the new chain. Nothing in the cache records which block a log came from, so there is no anchor to detect the reorg or unwind it.
Assumptions: EVM chain with probabilistic finality; poll every 15s; block time ≤ 15s so no block is skipped between polls; the cache is keyed by txHash (or txHash+logIndex) with no blockHash.
What breaks, in order of severity
- Phantom logs. A transaction mined in one of the four orphaned blocks that is not re-included stays in the cache forever. Downstream you credit a transfer that never finalized. This is the accounting bug.
- Missed logs. If you poll fromBlock = lastSeen+1, the reorg rewrote blocks you already advanced past. Transactions that appear only in the replacement blocks are never fetched.
- No detection. With no stored blockHash there is nothing to compare against, so the reorg is invisible.
What does not break: a re-included transaction. A transaction's logs are a pure function of the transaction, so the same txHash produces the same logIndex and the same data on any block. Only blockHash and blockNumber change. Keying by txHash therefore does not corrupt re-included logs: it just blinds you to the reorg.
Fix: persist (chainId, blockNumber, blockHash, txHash, logIndex). Each poll, for the last K blocks, compare the stored blockHash against eth_getBlockByNumber(number). On mismatch, delete rows for the orphaned hashes and re-query from the common ancestor.
Alternatives and when to pick them
- Confirmations lag: index only blocks at depth ≥ K. No reorg logic at all. Cost is K × blockTime of latency: 12 blocks on mainnet is 144s; on a 250ms L2, 12 blocks is 3s. Pick K from the chain's observed reorg depth.
- newHeads subscription: keep a rolling (number → hash) map; a reorg shows up as a new head whose parentHash ≠ your stored hash for number−1. Lower latency than polling, but you must handle dropped connections and backfill the gap.
- Fixed re-query window: re-fetch logs for the last K blocks every poll and upsert by (blockHash, logIndex). Idempotent and self-healing; costs K× the query volume.
Choose on finality model (probabilistic vs deterministic), block time, latency budget, and whether accounting must be exactly-once.
Trace: mainnet, 12s blocks, head 100. Cache after a poll:
| blockNumber | blockHash | txHash | logIndex | amount |
|---|---|---|---|---|
| 100 | 0xa1 | 0xt1 | 0 | 1000 |
| 99 | 0xa9 | 0xt3 | 2 | 500 |
Reorg: 98–100 orphaned, replaced by 98'–100'. 0xt1 is dropped; 0xt3 is re-included in 99' (hash 0xb9); 0xt2 is new in 100' (hash 0xb1).
Correct handling: compare stored 0xa1 against current block 100 → 0xb1, mismatch. Walk back to the common ancestor 97. Delete rows with blockHash 0xa1 and 0xa9. Re-query 98'–100'. Result: 0xt3 present with blockHash 0xb9 and the same amount 500, 0xt2 added, 0xt1 gone.
Without blockHash: 0xt1's 1000 stays credited (phantom), 0xt2 never appears (missed), and 0xt3's blockHash is never corrected.
Verification: a unique constraint on (blockHash, logIndex), and a reorg test that asserts delete+insert rather than an upsert on txHash.
Curated: · Written: · Reviewed:
Q&A-90An indexer queue consumes Transfer events into a SQL table. How do you make the consumer idempotent across a 12-block reorg?
Assumptions first: one EVM chain, logs read via eth_getLogs, rows written to Postgres, and the reorg depth we must survive is 12 blocks. Shallower than the chain's finality gadget. If the chain has no finality gadget, the safe depth is unbounded and the design changes.
The answer: make the row's identity include the block hash, and make the cursor able to detect that the block it points at changed.
Two pieces:
- Unique key
(chain_id, block_hash, log_index).logIndexis unique within a block, so this is a natural key. Upsert withON CONFLICT DO NOTHING. - The cursor stores
(block_number, block_hash), not just the number. On resume, fetch the block at that number and compare hashes. A mismatch means a reorg: walk back until the stored hash matches the node's, delete rows above the ancestor whoseblock_hashis not in the new canonical chain, then re-index forward.
Why a blockNumber cursor breaks: it stores 1000. A 12-block reorg replaces 989–1000. Resume at 1001 and you never re-read the replaced blocks: orphaned rows stay, new rows never arrive. The cursor sees no progress because the number did not change.
CREATE TABLE transfer_events (
chain_id integer NOT NULL,
block_number bigint NOT NULL,
block_hash bytea NOT NULL,
tx_hash bytea NOT NULL,
log_index integer NOT NULL,
from_addr bytea NOT NULL,
to_addr bytea NOT NULL,
amount numeric NOT NULL,
PRIMARY KEY (chain_id, block_hash, log_index)
);
INSERT INTO transfer_events (...)
VALUES (...)
ON CONFLICT (chain_id, block_hash, log_index) DO NOTHING;
-- rollback after locating the common ancestor
DELETE FROM transfer_events
WHERE chain_id = $1
AND block_number > $ancestor
AND block_hash <> ALL($new_canonical_hashes);
Trace: head at 1000, blocks 989–1000 reorged. Old block 995 (hash 0xaaa) held a Transfer, logIndex 3, A→B, 100 USDC. New block 995' (hash 0xbbb) holds logIndex 3, A→C, 100 USDC.
- blockNumber cursor: resume at 1001. Row
(0xaaa, 3)stays,(0xbbb, 3)is never inserted. B is credited 100 that never happened and C is never credited: 200 USDC of error from one log. - blockHash key: the ancestor walk finds 988. The DELETE removes
(0xaaa, 3)because0xaaais not in the new canonical set. Re-indexing 989'–1000' inserts(0xbbb, 3). Correct.
At ~150 transfers per block, 12 blocks is ~1,800 rows: one DELETE plus a re-insert, milliseconds.
Finalized cursor: the other design. Instead of reconciling, only index blocks the chain has finalized. On Ethereum PoS that is ~2 epochs (64 slots, ~12.8 min at 12 s slots), so you sit ~13 minutes behind head and never see a reorg shallower than finality. The cost is latency: any read that must reflect the last few minutes cannot use it.
Two-tier is the usual compromise: write rows immediately with a finalized boolean, flip it true when the block's checkpoint passes, and serve money and balance reads from finalized = true only. Head reads get freshness; money reads get safety.
When the blockHash key alone is not enough: if a reorg goes deeper than your stored block hashes (you pruned them), the ancestor walk finds no match and you must resync from a checkpoint. And upsert alone never removes orphaned rows: you must delete first; a pure upsert leaves the stale row and adds the new one.
Failure modes to detect:
- Provider log truncation:
eth_getLogscaps results on many providers; a truncated response looks like "no more logs" and silently skips. Assert the returned count is below the cap and cross-check per-block counts against a second provider. - Missing
chainIdin the key: two chains with the same block hash and logIndex collide. - Finality revert: rare on Ethereum PoS (slashable, has not happened on mainnet), real on PoW and fast-finality chains. Detect by comparing the stored hash at the finalized checkpoint against the node's.
Curated: · Written: · Reviewed:
Q&A-91A worker mints an NFT when it sees a paid event. The message is delivered 3 times. What exactly do you store so you mint once?
What to store
Store a deterministic id for the on-chain log that triggered the payment, and enforce it as a unique key twice: once in the database row that queues the mint, once in the contract that performs it.
eventId = keccak256(chainId, txHash, logIndex)
logIndex matters: one transaction can emit several Transfer logs, so txHash alone collapses distinct payments into one id. chainId keeps a testnet replay from colliding with mainnet. The log is the only thing in the pipeline that is unique per payment: the Kafka offset, the delivery attempt and the worker's in-memory state all change on redelivery. An EOA nonce does not help here: it orders transactions, it does not express business idempotency.
Why the database row alone is not enough
A processed_events table with a unique index on event_id handles the common case: the second and third deliveries hit the conflict and skip. It fails in one window: the worker sends the mint transaction, the transaction is mined, and the worker crashes before the INSERT commits. On restart the row is absent, so the worker mints again. The window is small, and it is exactly the window at-least-once delivery is designed to hit.
Put the check in the contract as well, so the mint and the "consumed" write are one atomic transaction:
mapping(bytes32 => bool) public consumed;
function mintForEvent(bytes32 eventId, address to, uint256 tokenId)
external onlyMinter
{
require(!consumed[eventId], "event already consumed");
consumed[eventId] = true;
_safeMint(to, tokenId);
}
The worker writes the outbox row in the same DB transaction as the event record:
INSERT INTO outbox (event_id, payload) VALUES ($1, $2)
ON CONFLICT (event_id) DO NOTHING;
A retry that gets past the DB check still reverts on chain, and the revert is the signal to mark the row processed.
Trace of three deliveries
| Delivery | DB insert | contract call | NFTs minted |
|---|---|---|---|
| 1 | row inserted | consumed[id] false → set, mint | 1 |
| 2 | conflict, no row | not sent | 0 |
| 3 | conflict, no row | not sent | 0 |
| crash after mint, before commit | row absent on retry | consumed[id] true → revert | 0 |
Failure modes
- Reorg.
txHashandlogIndexare only stable after finality. Minting on a log a reorg drops mints for a payment that never happened, and the id then blocks the real log. Wait for confirmations: a dozen blocks is the common heuristic, the finalized checkpoint is the guarantee: before acting. - Gas. The first mint for an event writes a fresh storage slot: 20,000 gas plus 2,100 for the cold access, ≈22k, on top of the mint itself. If that matters, derive
tokenId = uint256(eventId)and let_safeMintrevert on an existing token: same guarantee, no extra mapping slot, at the cost of opaque token ids. - Contract upgrade. The
consumedmapping lives in the proxy's storage; a migration that drops it re-opens the window for every historical event.
How you know it works
Deliver the same payload three times against a local chain and assert the token counter increments once and calls two and three revert with event already consumed. Alert on any event id that produces more than one successful mint.
Curated: · Written: · Reviewed:
Q&A-94Why does a passing unit test on a mock ERC-20 not replace a fork test against USDT, and what block number do you pin?
What a strong candidate says first
A mock is a statement of what you believe the token does. A fork test is a check against what the deployed bytecode actually does. They answer different questions, and the gap between them is where launches break.
The concrete gap with USDT: its transfer, transferFrom and approve are declared returns (bool) in the ABI, but the deployed bytecode returns no data at all. Solidity's ABI decoder reverts when a call declared to return bool gets fewer than 32 bytes of returndata. So this line passes against a mock and reverts against mainnet USDT:
require(usdt.transfer(to, amount)); // reverts on real USDT
SafeERC20.safeTransfer does a low-level call and only checks the success flag, so it tolerates the empty return. That is the whole reason the library exists.
Pin a block, and record it
There is no universal "correct" block. You pin a fixed number (the block you last validated against, or the block of your deployment) and commit it next to the RPC URL. The number matters less than the fact that it is fixed:
// foundry.toml: fork_block = 21000000 (example; use your own)
vm.createSelectFork(vm.envString("MAINNET_RPC"), 21_000_000);
Two reasons it must be pinned. First, reproducibility: latest means CI runs against different state on every invocation, so a green run yesterday proves nothing today. Second, USDT is an upgradeable proxy: Tether can swap the implementation, and an unpinned fork silently starts testing different bytecode than the one you shipped against.
The check that actually catches it
function test_realUSDT_returnsNoData() public {
deal(address(USDT), address(this), 1_000e6);
(bool ok, bytes memory ret) = address(USDT).call(
abi.encodeWithSelector(IERC20.transfer.selector, address(0xBEEF), 1e6)
);
assertTrue(ok);
assertEq(ret.length, 0); // real USDT: empty returndata
}
Run the same call against a mock that returns true and ret.length == 32. That 32-vs-0 difference is the bug a mock cannot see.
| Mock | Fork at pinned block | |
|---|---|---|
| Speed | ms | seconds |
| RPC needed | no | archive RPC + secret in CI |
| Return data | whatever you wrote | real bytecode |
| Edge cases | injectable (fee-on-transfer, revert, reentrancy) | only what the token does |
| Catches USDT's empty return | no | yes |
When the mock is the right tool
Most of the time, for your own logic. Mocks are fast, deterministic, and let you inject states a real token will not produce on demand: a fee-on-transfer token, a token that reverts on zero-value transfer, a reentrant callback. Fuzz your router against those. Fork tests are the expensive integration layer (archive RPC dependency, seconds per test, provider rate limits that flake CI) so you run a handful of them against the real tokens and routers you actually integrate with, not everything.
The failure mode to watch for is the reverse of the question: a fork test that passes because you pinned a block where the token behaved, and you never re-pin. Treat the block number as a dependency to bump, the same as a library version.
Curated: · Written: · Reviewed:
Q&A-95A fuzzer finds nothing in 1_000 runs. Why is that not an invariant proof, and what invariant would have caught a first-depositor inflation?
Assumptions. An ERC-4626-style vault that computes totalAssets() as asset.balanceOf(address(this)): the pattern exposed to this attack. A vault that tracks deposits in a stored variable and only updates it on deposit/withdraw is not vulnerable this way. The fuzzer is a naive one: it calls vault functions with random arguments and never composes a sequence.
The 60-second answer. 1,000 runs is a sample of the input space, not a proof over it. "No finding" means the fuzzer never reached the bad state, not that the state is unreachable. First-depositor inflation needs a specific sequence (deposit 1 wei, then donate tokens directly to the vault) and a naive fuzzer cannot express the donation at all, because it is an ERC-20 transfer, not a vault call. The invariant that catches it is an accounting one: the vault's asset balance must equal the sum of accounted deposits. A donation breaks that equality on the spot. Pair it with a no-loss invariant on the deposit→redeem round trip.
Why the guarantee differs. A stateless fuzzer draws one call with random arguments per run. The bug needs three ordered calls with specific values: deposit(1), transfer(vault, 1e18), deposit(1e18). The probability of drawing that sequence from random calldata is effectively zero, and the middle call is not in the vault ABI, so it is unreachable by construction. Invariant testing changes the unit of exploration: handlers expose meaningful actions (including a donate handler that does the raw transfer), and the fuzzer drives sequences of handler calls, checking the invariant after every call. Reachable-state coverage rises by orders of magnitude, and a failure is a concrete counterexample you can replay. It is still sampling, not a proof, but it explores the composed state space a stateless fuzzer never touches.
The invariant, in Foundry (Solidity ^0.8.20).
contract VaultInvariants is Test {
Vault vault; Handler handler;
function setUp() public {
vault = new Vault();
handler = new Handler(vault);
targetContract(address(handler));
}
// 1. Asset balance must equal the sum of accounted deposits.
function invariant_assetsMatchAccounting() public view {
assertEq(vault.totalAssets(), handler.ghostDeposited());
}
// 2. No depositor can lose value to rounding.
function invariant_noDepositLoss() public view {
for (uint256 i; i < handler.depositorCount(); ++i) {
address u = handler.depositor(i);
uint256 redeemable = vault.convertToAssets(vault.balanceOf(u));
assertGe(redeemable + 1, handler.ghostDepositedBy(u));
}
}
}
The handler exposes deposit, withdraw, and donate (a raw asset.transfer(address(vault), amount)), and tracks ghostDeposited / ghostDepositedBy as it goes.
Worked trace (hypothetical figures). convertToShares(a) = a * totalSupply / totalAssets().
| Step | Action | totalSupply | vault balance | totalAssets() |
|---|---|---|---|---|
| 0 | empty | 0 | 0 | 0 |
| 1 | attacker deposit(1) | 1 | 1 | 1 |
| 2 | attacker transfer(vault, 1e18) | 1 | 1e18+1 | 1e18+1 |
| 3 | victim deposit(1e18) → shares = 1e18·1/(1e18+1) = 0 | 1 | 2e18+1 | 2e18+1 |
| 4 | attacker redeems 1 share → 2e18+1 | 0 | 0 | 0 |
Invariant 1 fails at step 2: totalAssets() is 1e18+1, ghostDeposited is 1. Invariant 2 fails at step 3: the victim's redeemable value is 0 against a 1e18 deposit. The attacker nets ~1e18 for a 1-wei seed.
Choosing the tool.
| Tool | Guarantee | When it is right |
|---|---|---|
| Stateless fuzzing | Samples single calls | Arithmetic and input-validation bugs |
| Invariant testing + handlers | Samples call sequences, checks after each | Stateful protocols, accounting and share math |
| Bounded model checking (Halmos) | Exhaustive up to depth k | Small contracts, tight loops |
| Formal verification (Certora, KEVM) | Proof over the model | Critical invariants, tractable spec |
Failure modes and detection. A weak invariant (totalAssets() >= 0) passes trivially. A handler that omits donate never exercises the path. A ghost variable not updated on every handler call makes the invariant vacuous. The detection method for all three: run the invariant suite against a deliberately vulnerable fixture vault and confirm it fails within a few hundred runs. If it passes on the known-bad fixture, the invariant or the handler is broken, not the vault.
A quiet fuzzer is a sample, not a model check.
Curated: · Written: · Reviewed:
Q&A-96eth_call says a swap returns 12_400 USDC. The mined tx returns 11_900. What differed, and which number is the user's money?
The short answer
The 12,400 came from pool reserves at the block you simulated. The 11,900 is what the AMM paid when your transaction executed against the reserves at inclusion. The mined receipt is the user's money: 11,900 USDC. eth_call is a quote against a state snapshot; it commits nothing.
Assumptions: same calldata and input amount in both runs, a constant-product AMM, and the gap is state, not a revert or a different route.
What differed
eth_call runs your calldata against a state snapshot at a block tag (latest, pending, or a specific number) and discards the result. It does not see the transactions that land between your simulation and your inclusion, and it does not see the proposer's ordering. Mined execution does. The gap between the two numbers is whatever moved the pool's reserves in between:
- Other swaps in the same block. A sandwich or backrun trades ahead of you, shifting reserves so your fixed input buys less.
- State drift across blocks. You simulated at block N; the tx landed at N+3 after two blocks of unrelated flow.
- Block tag.
latestis the last sealed block;pendingis your node's view of the mempool, which is not the proposer's. Neither is the block your tx lands in. - Timestamp and oracle dependence. Pools that price off
block.timestampor an oracle that updated between simulation and inclusion return different amounts for identical calldata. - Overrides. If the simulation used
from=address(0), a state override, orgasPrice0, it exercised a different account state than the real sender.
Worked example (hypothetical reserves, constant product, 0.3% fee, fee accrual to the pool ignored)
Pool at simulation block: 500 WETH, 1,000,000 USDC.
| Step | WETH reserve | USDC reserve | Your 6.3 WETH out |
|---|---|---|---|
eth_call at block N | 500.00 | 1,000,000 | 12,406 |
| Backrun trades 10.62 WETH in | 510.59 | 979,262 | — |
| Your tx executes | 510.59 | 979,262 | 11,900 |
Same calldata, same input. The backrun paid 20,738 USDC to move the price before your tx; your output fell by ~500 USDC. The receipt's Transfer event shows 11,900 USDC to your address.
Trade-offs: which block to simulate against
latest: reproducible and verifiable after the fact, but stale by the time you submit. Use it for accounting, tests, and revert checks.pending: the freshest state your node has, so it catches revertslatestwould miss. It is still not the proposer's ordering, so it does not guarantee the output. Worth it when you are about to submit in the same block and want to catch a revert; not worth it as a price guarantee.- Inclusion-parent (simulate at the block your tx actually landed in, minus one): the closest reconstruction, useful for post-mortems, useless for pre-trade decisions.
Simulation is worth running to detect reverts, wrong routes, and allowance problems. It is not worth trusting for the output amount, because the output depends on state you do not control.
Failure modes and detection
- Sandwich/backrun: reserves move between simulation and inclusion. Detect by re-simulating at the inclusion block's parent and diffing against the receipt; a large same-block swap in the pool's logs confirms it.
- Stale simulation: tx lands several blocks after the call. Detect by comparing the block tag you simulated at with the receipt's
blockNumber. - Oracle/timestamp drift: identical calldata, different output, no other swap in the block. Detect by checking whether the pool reads a price feed or
block.timestamp. - Reorg: the block you simulated against is no longer canonical. Detect by checking the block hash still exists.
What to do
Enforce the floor on-chain: set minOut (or the router's amountOutMinimum) so the swap reverts rather than fills at a worse price. That bound protects the user, not the simulation. Log the eth_call result and the receipt's Transfer amount side by side; over many txs you should see a distribution, not equality.
Curated: · Written: · Reviewed:
Q&A-97One RPC returns a receipt with status 1 and another says the tx is unknown. What do you trust, and how many providers settle a payout?
Direct answer. When one provider returns a receipt with status 1 and another returns null, I trust neither by default. I trust a receipt only once I can tie its blockHash to a finalized block header, and I settle a payout only after that. In practice: a 2-of-3 quorum of independent providers plus my own node, matching on (blockHash, status), and halt on any disagreement.
What a receipt actually is. eth_getTransactionReceipt returns null when the node doesn't know the transaction, which covers both "never seen" and "still pending in the mempool". When it does return, status is 1 for success and 0 for a revert (EIP-658, since Byzantium), and blockHash/blockNumber say which block it landed in. The response carries no proof. The node executed the block itself and is handing you its own answer. A node that hasn't synced returns null; a malicious one returns whatever it likes. Neither is consensus: consensus is the validator set agreeing on a chain, and the JSON-RPC endpoint is one machine's view of it.
Why finality decides it. Post-Merge Ethereum finalizes a block after two epochs: 64 slots at 12 seconds, about 12.8 minutes. Reverting a finalized block needs at least a third of staked ETH slashed, so it doesn't happen. Before finality, a head block can be reorged and a receipt in it can disappear. So the rule is: a receipt in an unfinalized block is provisional; a receipt whose blockHash is finalized is settled.
Verifying rather than trusting. The block header commits to receiptsRoot. You can take the receipt, build its Merkle-Patricia path, and check it against receiptsRoot in a header you obtained from a finalized source. That's what a light client does, and it removes the need to trust any single provider. If you don't want to build that, quorum is the cheap approximation: with the caveat that "independent" must mean different upstreams. Many providers resell the same Infura or Alchemy backend, so three endpoints can share one failure.
Trade-offs.
| Approach | Strength | Cost / limit |
|---|---|---|
| Own full node | No third-party trust | Sync time, on the order of 1 TB disk, ops |
| 2-of-3 provider quorum | Cheap, fast to stand up | Correlated upstreams; still trusts the majority |
| Proof vs finalized header | Strongest per request | More code; needs a trusted header source |
Waiting for finality costs ~12.8 minutes. For a payout that's usually fine; if you need faster, you're accepting reorg risk and should size the exposure accordingly.
Failure modes. A stale node returns null, which looks identical to "no such tx": detect it by checking eth_syncing and blockNumber lag. A malicious node fabricates status 1: detect it by blockHash mismatch across providers and by the proof check. A reorg after you settled: detect it by watching whether the blockHash is still canonical.
When quorum is overkill. Small payouts, or any case where you already verify proofs against a finalized header: then one source is enough, because you're not trusting it.
Curated: · Written: · Reviewed:
Q&A-99A Multicall3 batch sends two payable subcalls. Why can msg.value be spent twice, and how do you write a safe batch?
Core answer. delegatecall runs the target's code in the calling contract's own context: same storage, same address, same msg.sender, and the same msg.value. So when a batch contract does delegatecall to a subcall, that subcall sees the batch's msg.value, the full amount, and it sees it again on every iteration. Nothing decrements it. If each subcall forwards msg.value onward, the batch pays the same ETH N times, out of the batch contract's balance. The fix is to stop using delegatecall for value forwarding: use call with an explicit per-subcall amount and count the wei down. Multicall3's aggregate3Value is exactly that.
The vulnerable shape.
// msg.value = 2 ether
function batch(address[] calldata targets, bytes[] calldata data) external payable {
for (uint256 i = 0; i < targets.length; i++) {
(bool ok, ) = targets[i].delegatecall(data[i]);
require(ok, "subcall failed");
}
}
Trace it with msg.value = 2 ether and a contract that already holds 5 ether of float:
| Step | What runs | msg.value seen | Balance after |
|---|---|---|---|
| entry | batch called with 2 ether | 2 ether | 7 ether |
| i=0 | target code runs in batch's context, does payable(seller).transfer(msg.value) | 2 ether | 5 ether |
| i=1 | same code, same context, msg.value still 2 ether | 2 ether | 3 ether |
Two subcalls, one 2-ether payment, 4 ether gone. The second transfer only reverts if the contract's balance is short: with float on hand, it succeeds. That is the whole bug: msg.value is a property of the frame, not a budget that gets consumed.
The safe shape.
function batch(
address[] calldata targets,
uint256[] calldata amounts,
bytes[] calldata data
) external payable {
uint256 remaining = msg.value;
for (uint256 i = 0; i < targets.length; i++) {
require(amounts[i] <= remaining, "over budget");
remaining -= amounts[i];
(bool ok, ) = targets[i].call{value: amounts[i]}(data[i]);
require(ok, "subcall failed");
}
require(remaining == 0, "unspent value");
}
call gives the target its own frame: it sees msg.value == amounts[i] and msg.sender == this contract, and the caller's balance drops by exactly that amount. The remaining counter is the budget; the final require rejects a batch that under-spends, so value can't be silently stranded.
Multicall3. aggregate3 is non-payable and forwards zero value. aggregate3Value is the payable one: it takes Call3Value[] with a uint256 value per entry, uses call (not delegatecall), and reverts unless msg.value equals the sum of those per-call values. Use it, and never hand-roll a delegatecall loop over user-supplied targets: beyond the value bug, delegatecall into untrusted code lets it write your storage and selfdestruct your contract.
Detecting it. Assert the invariant after every batch: address(this).balance == balanceBefore + msg.value - sum(amounts). Fuzz the batch with random amounts and check that the total value the targets received never exceeds msg.value. A batch where two subcalls each demand the full msg.value must revert; if it doesn't, the batch is spending float.
Curated: · Written: · Reviewed:
Q&A-100A sale opens at block.timestamp >= T. How much can a proposer move T, and when is that enough to steal?
T doesn't move. It's a constant in the contract. The proposer's only lever is which slot carries the transaction, and that moves the observed block.timestamp forward in 12-second steps: never backward. That lever is enough to steal only when the payout reads the timestamp as a value, not as a >= threshold.
Assumptions: post-Merge Ethereum mainnet. block.timestamp = genesis_time + slot × 12, with genesis_time = 1606824023. A payload whose timestamp doesn't match its slot is invalid, so a proposer can't lie about the clock: they can only choose when to include.
The gate itself. For require(block.timestamp >= T), the earliest includable slot is fixed: the smallest n with 1606824023 + 12n >= T. The proposer of that slot can include, or withhold and let a later slot carry it. So the inclusion timestamp is T_earliest + 12k, k >= 0. Getting in before T is impossible: a slot's timestamp is not negotiable.
When it's enough to steal. Only when the contract derives value from the timestamp rather than comparing it:
| Contract reads timestamp as | Proposer lever | Steal? |
|---|---|---|
require(block.timestamp >= T) | delay inclusion | no |
block.timestamp % N for rarity | pick slot residue | yes, if reachable residues are non-trivial |
block.timestamp % 12 | none: it's constant | no, but the "randomness" is dead |
| first-tx-in-block tiebreak | block ordering | yes |
Worked example. A drop opens at T = 1606824023 + 12 × 1_000_000 = 1618824023 and mints a legendary when block.timestamp % 1000 == 0. Every timestamp is 1606824023 + 12n ≡ 23 + 12n (mod 1000). With gcd(12, 1000) = 4, the reachable residues are exactly those ≡ 3 (mod 4): 250 of 1000. A proposer whose slot lands in that set includes their own mint and takes the legendary; slots outside it can never mint one. Swap the modulus to 12 and the value is always 11 (1606824023 mod 12 = 11), so every mint is legendary and the "rarity" is a constant.
Detection. Fork mainnet, vm.warp ±12s around the gate, re-run. Outcome changes → the design depends on the timestamp value and is exploitable. Outcome doesn't → it's a threshold and the proposer can only delay.
Instead. Keep block.timestamp for coarse gates with hours of margin (vests, auctions). For entropy or same-slot selection use commit-reveal or a VRF. RANDAO is proposer-biasable too, a proposer can withhold to shift the mix, so it isn't a fix for high-value draws.
Curated: · Written: · Reviewed:
Q&A-98A smart account's UserOperation nonce is not the EOA nonce. What collision does a 4337 nonce prevent, and what still needs a signature?
Short answer: the 4337 nonce stops the same UserOperation from being included twice, a replay/double-execution collision, because a smart account has no EOA nonce for the EntryPoint to consume. The signature is still required: the account's validateUserOp must verify the owner's signature over the userOpHash, which binds the account, chainId, EntryPoint and the nonce. Nonce = replay gate; signature = authorization. They are not substitutes.
Why the EntryPoint needs its own counter
A contract account has no protocol-level nonce. The EOA nonce lives on the EOA that signs, not on the account that executes. So the only component that sees every op for every account is the EntryPoint, and it has to be the replay gate. It keeps a counter per (sender, key) and increments it after a successful validation.
The nonce is 256 bits: the upper 192 are a key, the lower 64 are a seq.
// EntryPoint v0.7
uint256 nonce = entryPoint.getNonce(alice, 0); // key=0, seq=0 -> 0
// op with nonce 0 validates -> EntryPoint sets seq to 1
uint256 next = entryPoint.getNonce(alice, 0); // 1
// resubmitting the same op (nonce 0) reverts: AA25 invalid account nonce
Without that counter, two bundlers holding the same signed op could both include it, and the account's call would run twice. That is the collision: not two different ops, but one op landing twice.
What the signature still does
The nonce proves freshness; it proves nothing about who authorized the call. Anyone can submit an op with a fresh nonce. So the EntryPoint calls validateUserOp, and the account checks the owner's signature against:
userOpHash = keccak256(abi.encode(hashUserOp(op), entryPoint, block.chainid))
Because the nonce is inside hashUserOp, the signature commits to it: you cannot swap the nonce without invalidating the signature. The chainId and EntryPoint address in the hash stop cross-chain and cross-deployment replay, which the nonce alone does not.
The key dimension, and when not to use it
| Lane | Use | Cost |
|---|---|---|
| key 0 (default) | strict ordering, one op at a time | a stuck op blocks every later op from that account |
| extra keys | independent lanes, e.g. session key vs owner | you must track each lane's seq off-chain; a bundler can't just take "next nonce" |
Use multiple keys when ops are independent and you want them in flight concurrently. Do not split ops that must execute in order: an approve and the swap that depends on it belong in one lane, or the swap can land first.
Failure modes to name
AA25 invalid account nonce: bundler used a staleseq; the op was already included or the lane advanced.AA24 signature error:validateUserOprejected the signature; the nonce was fine, authorization was not.- Replay across chains, not a nonce problem; it is the chainId in the hash that closes it.
So: the nonce answers "has this op already run?" and the signature answers "did the owner authorize it?" A correct account needs both.
Curated: · Written: · Reviewed:
Q&A-81A rollup can post batches as calldata or as blobs. What do you gain in cost, and what do you lose in permanence?
Blob DA cuts data-availability cost by roughly 50–200× versus calldata, and you pay for it with a hard retention cliff: blobs are pruned from the beacon chain after 4096 epochs, about 18.2 days. Calldata is priced in the same gas market as execution and stays in the chain's block history indefinitely. So the question isn't which is cheaper: it's whether anything in your protocol needs to read that batch after day 18. Fraud proofs, bridge challenges and forced-inclusion exits all do if their window is longer than the retention period.
The arithmetic. A 128 kB batch is 131,072 bytes.
- As calldata, all non-zero bytes: 131,072 × 16 gas = 2,097,152 gas. At 10 gwei and ETH at $3,000 that's 0.021 ETH ≈ $63; at 30 gwei, ≈ $189.
- As a blob: 131,072 blob gas, priced by its own market with a minimum blob base fee of 1 wei. At a 1 gwei blob base fee that's 0.000131 ETH ≈ $0.39; at 20 gwei, ≈ $7.9.
The saving is real and large, but it is a function of two independent fee markets. Blob base fee is set by excess blob gas, not by execution gas, so a congested blob market narrows the gap without execution gas moving at all.
What you lose. Availability, not just cheapness. After ~18.2 days the blob is gone from consensus. If your dispute game, fraud proof or exit queue can reference a batch older than that, you must have archived the data yourself (S3, IPFS, a DA layer) and your security model now depends on that archive being honest and online. At 128 kB per 12-second slot that's ~0.94 GB/day, ~28 GB/month, about $0.65/month at S3 Standard's $0.023/GB-month. The storage is trivially cheap; the operational commitment is not.
Failure mode. A team cut roughly $120k/month by moving to blobs and deleted the archive in the same change. A fraud proof on day 20 needed a batch whose blob had been pruned; withdrawals halted for four days while they reconstructed the data from a third-party indexer. Detection is a simple monitor: track the age of the oldest batch that is still challengeable and alert as it approaches 18 days. If that age can exceed the retention window, you need calldata or a durable archive.
What to check before you commit. Price both markets at the current blobBaseFee and gas price for your batch size, and confirm the archive's cost and durability. If the challenge window is under ~14 days and you archive anyway, blobs are the right default. If it's longer and you won't run an archive, post calldata and pay for permanence.
Curated: · Written: · Reviewed:
Q&A-82Name one operational difference that is not "zk is faster": who must stay online, and with what data?
The 60-second answer. Optimistic rollups need at least one honest party online, holding the rollup's data, for the whole challenge window: 7 days on OP Stack, about 6.5 days on Arbitrum One. ZK rollups need a prover online with the witness and the circuit, plus a verifier contract that is actually correct. There is no watcher window on the zk side, but the proof has to land before the state root is accepted.
| Who must be online | With what | For how long | |
|---|---|---|---|
| Optimistic | ≥1 honest watcher (permissionless, but someone) | batch data, calldata or blobs, plus the L1 state root | the full challenge window: 7 d OP Stack, ~6.5 d Arbitrum |
| ZK | prover (permissioned or a market) | witness, circuit, proving key | until the proof is submitted; no window |
What "with the data" means. The watcher has to be able to re-execute the batch and compare the resulting root against the one proposed. If the rollup posts calldata, that data is on L1 permanently. If it posts blobs (EIP-4844), the sidecars are pruned after MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS = 4096 epochs: 4096 × 32 slots × 12 s ≈ 18.2 days. That is longer than the 7-day window, so a watcher that fetches inside the window is fine; one that assumes it can reconstruct from blobs a month later cannot, and needs an archive node or a DA provider.
Failure modes and how you see them.
- Watcher offline or unfunded: a bad root finalizes. Detect with an alert on "no successful batch fetch in N hours" and a disk-capacity check sized to the window.
- Blob pruned before fetch: the watcher cannot reconstruct the batch. Detect by tracking the age of the oldest unfetched blob against the 18-day prune.
- Prover down: no new roots, the chain stalls at the last proven state. Detect with prover queue depth and proof latency.
- Verifier bug: a wrong proof accepted. This is the failure zk is meant to remove, so it is a contract-audit problem, not an ops rota.
The cost asymmetry is the operational point: a watcher is a box with disk and an RPC endpoint; a prover is GPU or ASIC hardware with a proving market behind it.
Worked example (hypothetical). A DAO ran an OP Stack chain and assumed "the community will watch." No funded watcher held the batch data. A bad root went unchallenged and finalized at hour 160 of 168. The fix was not more watchers: it was one funded watcher with a disk sized to the window and an alert when a batch fetch fails.
So: optimistic means someone watches with data; zk means someone proves with a circuit.
Curated: · Written: · Reviewed:
Q&A-76Why does an optimistic withdrawal wait ~7 days, and what happens if you treat L2 inclusion as L1 funds?
The short answer. An L2 withdrawal is not a transfer of L1 funds. It is a message inside an L2 state root that L1 has not yet accepted. Optimistic rollups assume that root is correct and let anyone disprove it with a fraud proof during a challenge window. Your withdrawal becomes executable on L1 only after that window closes unchallenged. The ~7 days is that window, not a confirmation count.
The mechanism. Three phases:
- You call the L2 bridge's withdraw, which burns your L2 balance and appends a message to the L2 outbox. Nothing has happened on L1 yet.
- The rollup's proposer posts the L2 state root containing that message to L1: an assertion in Arbitrum's rollup contract, an output root for OP Stack chains. The challenge window starts when that root is asserted, not when your transaction was sequenced. A validator who can prove the root wrong submits a fraud proof; if it wins, the root is discarded and every message in it, including yours, is void.
- After the window expires with no successful challenge, the root is final. You submit a Merkle proof of your message against that root and the L1 bridge releases the funds.
So the wall-clock wait is (time until the root is posted) + (remaining challenge window). Roots are posted frequently, so in practice it is close to the full window.
The numbers. The window is a chain parameter, not a constant of nature. OP Stack chains (Optimism, Base) use 7 days. Arbitrum One uses 6.4 days: 45,818 L1 blocks at 12 s. Both are governance-settable.
Why a week and not an hour? The window has to exceed the time for an honest validator to notice a bad root and get a fraud proof mined, plus margin. Shorten it and you shrink the set of validators who can afford to watch; lengthen it and you lock up capital and raise fast-bridge fees.
What breaks if you treat L2 inclusion as L1 funds. You are marking a claim on a state that can still be reverted. Three concrete failure modes:
- Fraud. A proposer posts a root that credits themselves your balance. If no one challenges in time it is final; if someone does, your deposit evaporates. The window is a market: it holds as long as the value at risk exceeds the cost of a fraud proof.
- Sequencer stall or censorship. The sequencer can stop producing batches. Your L2 transaction is visible on an explorer, but the root carrying it never reaches L1, so the clock never even starts.
- L2 reorg. Before the batch is posted, the sequencer can reorder or drop your transaction. Two L2 confirmations mean nothing.
Worked example (hypothetical): a desk credits customer deposits after 2 L2 blocks. A sequencer outage stalls batch posting for 16 hours. The deposits show as confirmed on the L2 explorer the whole time, but no L1 root contains them, so the desk has credited funds it cannot withdraw. The fraud window never began.
Fast bridges. A fast bridge pays you on L1 immediately and waits out the window itself. That is unsecured credit to the bridge operator, priced as a fee: a few basis points to a fraction of a percent. It is not L1 finality.
Detection. Track the L1 assertion or output root that contains your message and its age; alert when a withdrawal's root is unposted or the window has not elapsed. Treat L2 explorer confirmations as zero evidence of L1 funds.
Curated: · Written: · Reviewed:
Q&A-77A zk rollup posts a validity proof. Why can settlement be faster than optimistic, and what still delays a user withdrawal?
The 90-second answer
A validity proof replaces the fraud-challenge window with a proof-verification step. On an optimistic rollup the L1 contract accepts a state root immediately but it stays challengeable for 7 days (Optimism; Arbitrum's window is ~6.4 days), and a withdrawal can't be claimed until that window closes. On a zk rollup the L1 verifier contract checks a succinct proof over the batch's state transition; once that verify transaction is included and finalized, the state root is canonical and exits from that batch can be claimed. The settlement clock drops from a fixed week to proof generation + one L1 transaction + L1 finality.
That is not the same as an instant withdrawal. Four clocks still run, and the slowest one gates you.
| Clock | What it measures | Typical |
|---|---|---|
| Batch cadence | your L2 tx → batch closes | seconds to tens of minutes |
| Proving | batch closed → proof ready | minutes to hours, workload-dependent |
| L1 verify | proof tx included | one L1 block (~12 s) plus gas |
| L1 finality | verify tx finalized | ~12.8 min (2 epochs); ~19 min if a slot is missed |
What the proof actually covers. The verifier checks that the new state root follows from the old one given the batch's transactions. It does not check that the batch data is retrievable: that's the DA layer. Assume the rollup posts batch data to L1 blobs; if it's a validium, the DA committee is now on your critical path and the proof says nothing about it.
Worked example (illustrative numbers, not a measurement). You burn on L2 at t=0. The batch closes at t=+30 min. The prover finishes at t=+75 min. The verify tx lands in the next L1 block, t=+75.2 min. That tx finalizes at t=+88 min. Total: about 1.5 hours, versus 7 days on an optimistic rollup. Change the batch cadence to every 4 hours and the same withdrawal takes ~4.3 hours: the proof is not the only term.
What still delays a user.
- Prover queue. Proofs are the bottleneck, not the chain. A backlog or a prover outage stalls every exit even though the rollup is producing blocks. Detect it by watching the gap between sequenced and proof-submitted timestamps, and prover queue depth.
- Verifier bugs and trusted setup. A soundness bug means a "final" root can be wrong; recovery is a contract upgrade and possibly a re-genesis, which freezes exits. The proof removes the challenge window, not this risk.
- DA failure. If batch data isn't on L1, the proof can't be checked against it and exits stall.
- Sequencer censorship. Forced inclusion goes through the L1 inbox, so your burn waits on L1 inclusion before it's even in a batch.
- A UI that lies. Marking a withdrawal final while the proof job is still queued makes users act on unproven balances. During a prover outage that's a loss vector, not a cosmetic bug.
In practice. Fast bridges front the liquidity for a fee, which is why a zk rollup withdrawal feels like minutes. The spread is the price of skipping the four clocks. Validity kills the challenge week; it does not kill the prover queue, DA, or L1 finality.
Curated: · Written: · Reviewed:
Q&A-38A rollup stores proofs "on Ethereum DA" via blobs. How long are those bytes retrievable from Ethereum nodes, and what must you add?
Short answer: about 18 days. EIP-4844 requires consensus clients to serve blob sidecars for MIN_EPOCHS_FOR_BLOB_SIDECARS_REQUESTS = 4096 epochs: 4096 × 32 slots × 12 s = 1,572,864 s ≈ 18.2 days. After that, nodes are free to prune, and most do. Nothing in the protocol makes blob bytes permanent, so you must add an archive you control, an external DA layer, or calldata.
Why the clock is 18 days, not "forever"
Blobs are not in the execution payload. They are sidecars attached to the beacon block. The execution block header keeps only the KZG commitments (the versioned hashes in each blob transaction) plus the blob gas fields. So L1 permanently records that a blob existed and what it hashes to, but not the bytes themselves. The bytes live in the consensus layer, under a retention rule, not a permanence guarantee.
| Day | Blob sidecar on public CL nodes | What still works |
|---|---|---|
| 0 | served | beacon API fetch, KZG verify against L1 |
| 7 | served | optimistic challenge window closes |
| 18 | last day of guaranteed service | — |
| 19+ | pruned by most nodes | only your archive; commitment still on L1 |
What you add
1. Your own sidecar archive. At post time, fetch GET /eth/v1/beacon/blob_sidecars/{block_id} from a beacon node and store the sidecar (index, blob, KZG proof, commitment) in object storage. Verify each blob against the versioned hash in the L1 transaction. This is what most rollups do: it is cheap, self-contained, and lets you re-derive state without trusting anyone. Key by block root, not slot, so reorgs don't corrupt the index.
2. An external DA layer (Celestia, EigenDA, Avail). You inherit its retention policy and its trust assumptions; you still need the L1 commitment to bind the off-chain bytes to the chain.
3. Calldata. Permanent-ish, but 16× the gas units: one blob is 131,072 bytes = 131,072 blob gas, while the same bytes as non-zero calldata cost 131,072 × 16 = 2,097,152 gas, priced in a separate market. Reserve it for small payloads that must outlive every retention window. Note that calldata lives in the execution block body, which archive nodes retain today; EIP-4444 (history expiry) is a proposal that would change that for old blocks, so treat "forever" as a policy, not a protocol guarantee.
Sizing for option 1: at Deneb's 6-blob max, 6 × 128 KiB = 768 KiB per slot; 7,200 slots/day × 18 days ≈ 95 GiB if you mirror everything. You don't: you mirror only your rollup's blobs, which is a rounding error next to that.
Failure modes and how to detect them
- Derivation breaks after day 18. A rollup node syncing from L1 fails at the first blob it cannot fetch. Detect it by running a fresh node from genesis against L1 only in CI; it should fail loudly, not silently skip.
- Archive gaps. A beacon-node outage or a reorg during a fetch leaves a hole. Detect it by comparing the length of
blob_kzg_commitmentsin each beacon block against the sidecars you stored, and alerting on any mismatch. - A DA committee of one. If the only copy is one sequencer's disk, you have no redundancy. Replicate across at least two providers and regions, and rehearse a restore.
The commitment is the anchor: keep the bytes and the L1 header, and you can prove your archive is the real data long after the public nodes have dropped it.
Curated: · Written: · Reviewed:
Q&A-78The sequencer is down for 10 hours. How does a user still get a transaction included, and what design has no escape?
Core answer. A user gets a transaction included during sequencer downtime only if there is an L1 entry point that L2 derivation is forced to read. Two real ones:
- Arbitrum (Nitro): the delayed inbox. The user sends an L1 transaction to the Inbox contract. The SequencerInbox must include it within the force-inclusion window (Arbitrum One: 24h,
delaySeconds = 86400, governance-set at the time of writing). If the sequencer doesn't, anyone callsSequencerInbox.forceInclusionand the message is appended to the inbox, where the derivation pipeline must pick it up. - OP Stack (Optimism, Base): a deposit.
OptimismPortal.depositTransactionemitsTransactionDepositedon L1; the op-node derivation pipeline includes every deposit it reads from L1. The sequencer orders transactions but does not gate deposits.
A design with no escape has only the sequencer's RPC as ingress: no L1 inbox, no deposit contract, no forced-inclusion path. Then a 10-hour outage is a 10-hour halt, and anything in the sequencer's mempool is lost on restart.
What the 10-hour case actually looks like. The escape hatch is censorship resistance, not liveness. On both stacks the L2 chain only advances when the batch poster posts batches to L1, and that role is the sequencer. So during a 10-hour outage:
- A transaction sent to the L1 inbox/deposit contract is recorded on L1 immediately and cannot be lost. It executes when batches resume.
- A transaction sent to the sequencer's RPC sits in the sequencer's mempool; if the process restarts without persistence, it is gone.
- A withdrawal initiated before the outage can be proven once an output root is posted and the challenge window passes (OP Stack: 7 days). A withdrawal initiated during the outage cannot be proven until the chain resumes.
So the honest guarantee: forced inclusion means the sequencer cannot censor a message while continuing to produce batches. It does not by itself restore liveness if the batch poster is also down.
Costs. The L1 path costs L1 calldata gas: a deposit is a few hundred bytes, so cents to a few dollars at 20 gwei, versus near-zero for an L2 RPC transaction. And the user waits: up to the force-inclusion window on Arbitrum, or until the sequencer resumes on OP Stack.
Failure modes. (1) Sequencer-only ingress: mempool loss on restart. (2) Inbox exists but the force-inclusion window is longer than the outage, so the user waits rather than escapes: a 10-hour outage under a 24h window is a wait, not a force. (3) Batch poster down: the chain halts even though messages are already on L1.
Trace (illustrative). OP Stack, sequencer down 10h. t=0: user calls depositTransaction on L1 at block 21,000,000; the portal emits TransactionDeposited. t=0–10h: no L2 blocks are produced; the deposit sits in L1 state, not in any mempool. t=10h: the sequencer resumes, op-node derivation replays L1 from the last derived block, sees the log, and includes the deposit as the first transaction of the next L2 block. The deposit executes and the user's L2 balance changes. Nothing was ever in the sequencer's RAM.
| Design | Ingress during outage | Tx survives restart | Censorship-resistant |
|---|---|---|---|
| Arbitrum delayed inbox | L1 tx to Inbox | yes (on L1) | yes, after 24h window |
| OP Stack deposit | L1 depositTransaction | yes (on L1) | yes, derived from L1 |
| Sequencer RPC only | none | no | no |
Curated: · Written: · Reviewed:
Q&A-79You emitted a withdrawal on L2. Which Merkle (or similar) proof do you present on L1, and why is the L2 tx hash not enough?
Core answer
On OP Stack the proof you present is a Merkle–Patricia proof of the withdrawal's storage slot in the L2ToL1MessagePasser contract, checked against the message-passer storage root embedded in an L2 output root that is already posted to L1. Concretely: wait for the output root to be posted and past its challenge period, then call proveWithdrawalTransaction on the OptimismPortal with the withdrawal tuple, the dispute-game (output) index, the output root proof, and the withdrawal proof. Finalize later with finalizeWithdrawalTransaction.
The L2 tx hash is not enough because L1 cannot execute or observe L2. A tx hash is a hash of transaction bytes, anyone can compute one, and it commits to nothing about whether that transaction was included in the canonical L2 chain L1 agreed on, or whether it succeeded. L1's only view of L2 is the state commitment it stored.
Mechanism
The output root is keccak256(version, stateRoot, messagePasserStorageRoot, latestBlockhash). The withdrawal proof is a Merkle–Patricia proof that sentMessages[withdrawalHash] is set in the message passer's storage trie, whose root is messagePasserStorageRoot. The chain of trust is: L1 stores the output root → the output root contains the message-passer storage root → that storage root contains the withdrawal slot. Every link is a hash commitment; the tx hash is in none of them.
The withdrawal hash is derived from (nonce, sender, target, value, gasLimit, data), so the proof binds the exact parameters, not just "some withdrawal happened."
Why the hash fails, precisely
- A tx hash proves local execution on L2, not inclusion in the state L1 committed to.
- It does not commit to the message passer's storage: a reverted tx, or a different contract emitting a similar event, leaves no slot set.
- It has no binding to finality: a hash from a reorged or unfinalized L2 block is worthless.
Trade-offs
OP Stack proves against an output root (a state commitment). Arbitrum proves against a sendRoot in a confirmed rollup block, via the Outbox's executeTransaction. Both require waiting out the challenge/confirmation window before finalizing: 7 days on OP Mainnet, about 6.4 days on Arbitrum One, because until then a fault proof can revert the root. You can prove early; you cannot finalize early.
Failure modes
- Proving against a stale or not-yet-final output index: the portal rejects it.
- Proof for a withdrawal that was never sent: the storage proof fails to verify.
- Replay: the portal sets
finalizedWithdrawals[withdrawalHash] = true, so the same withdrawal cannot be finalized twice.
| Object | What it commits to | Enough to finalize? |
|---|---|---|
| L2 tx hash | tx bytes on L2 | no |
| L2 output root (on L1) | L2 state + message-passer storage root | no: it is the anchor |
Merkle proof of sentMessages[withdrawalHash] | the withdrawal is in that state | yes, given the root |
Curated: · Written: · Reviewed:
Q&A-80A deposit tx is finalized on L1. When may the L2 credit the user, and what reorg still matters?
The 60-second answer
The deposit is already finalized on L1, so the L1 reorg question is closed: the TransactionDeposited log sits in a finalized L1 block and no reorg can remove it. The only L1-side gate left is liveness: the L2 derivation pipeline has to actually read that L1 block. Once it has, the deposit is included in an L2 block and you can credit.
The reorg that still matters is the L2's own. The L2 block carrying the deposit starts as unsafe (sequencer-produced, not yet posted to L1), becomes safe when its batch is posted and derived, and is only final when the output root covering it is finalized on L1. Until then the credit is provisional.
Why L2 inclusion adds nothing on the L1 side
Derivation is one-directional: the L2 node reads L1 blocks and replays the deposits it finds. The L1 block is the source of truth; the L2 block is a derived copy. So "the deposit is in an L2 block" tells you the derivation pipeline ran, not that anything new was secured. If the L1 block could be reorged, the derived L2 block would be reorged with it, but it can't be, because it's finalized. That is why the L1 tag on the deposit is the whole safety story, and the L2 tag is a separate, later question.
The heads, and what each buys you
| L2 head | Deposit present? | Can it be reorged? |
|---|---|---|
| unsafe | yes, once derived | yes: sequencer reorg |
| safe | yes | yes: derivation reorg if the batch mismatches |
| finalized | yes | no: output root finalized on L1 |
On OP Mainnet, L2 finality is the 7-day fault-proof window plus L1 finality (~13 min: two epochs of 32 slots at 12s). So a credit at the unsafe head is roughly 7 days from being irreversible.
Worked trace (hypothetical figures)
L1 block 21,000,000 contains the deposit and finalizes. The L2 node derives it and includes the deposit in L2 block 5,000,123: unsafe. The sequencer posts the batch; the block becomes safe. An output root covering 5,000,123 is proposed to L1 and, after the 7-day window, finalized. Only then is the credit final.
Trade-offs: when to credit
- Strict finality: credit only at L2 finalized. Safe, but the user waits ~7 days. Right for large deposits, or whenever the credit can be bridged back to L1.
- Fast path with risk limits: credit at the safe (or unsafe) head, but cap the amount and block the user from moving it off L2 until finality. Most bridges do this: the credit is spendable on L2 but not bridgeable out.
- The failure mode: crediting at the unsafe head and letting the user bridge out immediately. If the L2 reorgs, the outbound transfer is already on L1 and the bridge eats the loss.
Detection
Watch the L2 node's unsafe/safe/finalized head labels and the output-root proposal status. A reorg shows up as the safe head moving backwards; that is the signal to unwind any provisional credit.
Curated: · Written: · Reviewed:
Q&A-83A sequencer omits one user's txs for 48 hours. What mechanism forces inclusion, and what is a fake version of it?
Core answer (say this first)
Assume "censorship resistance" means the user's transaction gets included even if the sequencer refuses to include it. The mechanism is an L1 contract the sequencer cannot write to, plus a protocol rule that makes any batch skipping that message invalid after a deadline.
Concretely, on Arbitrum: the user submits the tx to the L1 Inbox contract (a retryable ticket / sendUnsignedTransaction). That message lands in the delayed inbox on L1. The SequencerInbox contract enforces a force-inclusion delay: delaySeconds = 86400, i.e. 24 hours as configured on Arbitrum One. Once a delayed message is older than that, anyone can call SequencerInbox.forceInclusion() to append it to the inbox. From then on the sequencer's batches must consume delayed messages in order; a batch that skips a message past its deadline fails validation, so the sequencer cannot post a valid chain that omits it.
Why the L1 forces it: the enqueue happens on Ethereum, where the sequencer has no write access. The L1 contract is the source of truth, and the L2 state-transition function checks that delayed messages are consumed in order. The sequencer's only remaining lever is to stop producing batches entirely: a liveness failure, which is a different failure than censorship.
The fake version
A fake forced-inclusion is anything with no on-chain rule that makes a skipping batch invalid:
- A policy or TOS clause ("fair ordering", "we don't censor").
- A support channel: "contact us and we'll include it".
- An "inbox" contract with no timeout, or one the admin can pause or upgrade, so inclusion is still discretionary.
The test: can the user get the tx in without the sequencer's cooperation, and does a batch that skips it fail verification? If not, it is a promise.
| Real (Arbitrum delayed inbox) | Fake (policy) | |
|---|---|---|
| Enqueue where | L1 Inbox contract | off-chain request |
| Who can force | anyone, after the delay | sequencer's discretion |
| Skipping batch | invalid | valid |
| Delay | 24h (delaySeconds = 86400) | n/a |
Trade-offs
- Delay: 24h is long. A liquidation can complete before inclusion. The delay is what gives the sequencer room to batch normally, so it is not free to shorten.
- Cost: the user pays L1 gas to enqueue, far more than L2 gas. The escape hatch is expensive by construction.
- Griefing: the delayed inbox must be included in order, so an attacker can spam it with junk, forcing the sequencer to pay L2 gas to include messages it does not want. This is a real DoS surface.
- Ordering: forced inclusion guarantees inclusion, not fair ordering. The sequencer can still reorder around the forced message.
Failure modes
- Timeout too long relative to the threat (24h vs a liquidation window).
- Escape hatch unusable: the user does not know about it, or cannot pay L1 gas.
- Upgradeable inbox: if the admin can pause or upgrade the L1 inbox, censorship resistance is only as strong as that key.
- Sequencer stops posting batches: inclusion is guaranteed only if someone can post; otherwise you are in the forced-exit path, not the inclusion path.
What would change the answer
If the chain has no L1 inbox, a centralized sequencer with no forced-inclusion contract, there is no mechanism, only policy. If the delay is short and the inbox is immutable, the guarantee is strong.
Curated: · Written: · Reviewed:
Q&A-84The L1 contract stores a 32-byte state root. Why can you still be unable to prove a leaf, and what extra publication is required?
Short answer: a 32-byte root is a commitment, not a publication. To prove a leaf you need the sibling hashes along the path from that leaf to the root, and the root alone contains none of them. Those siblings exist only if someone publishes the data the tree was built from (the batch's transactions, or the state diff) so a verifier can re-execute and rebuild the tree.
Assumptions I'd state up front: an L1 contract holding a state root for a rollup, a Merkle (or Merkle-Patricia) tree over account and storage leaves, and a prover who is not the sequencer.
Mechanism. A Merkle proof for leaf L is L itself plus the sibling hash at each level on the way up. The verifier hashes L with its sibling, hashes that result with the next sibling, and repeats until the computed value equals the root. Every sibling is a node in the tree. If the sequencer posts only the root, the siblings are unknown, so no proof can be built, not by a user, not by a bridge, not by a fraud prover. The root is a hash of a secret.
What extra publication is required: the batch data itself, on a path the prover can retrieve. Three options, and they differ on cost, retention and trust.
| Path | Cost | Retention | Trust |
|---|---|---|---|
| L1 calldata | 16 gas per nonzero byte; 100 KB ≈ 1.6M gas | permanent | L1 consensus |
| EIP-4844 blobs | separate blob-gas market, 131072 blob-gas per blob | ~18 days (4096 epochs) | L1 consensus + KZG |
| External DA (Celestia, EigenDA) | cheapest | committee-defined | DA committee + sampling |
Note that even with blobs the L1 contract sees only a 32-byte versioned hash (the KZG commitment); the blob data lives in the beacon chain and is pruned after roughly 18 days.
The deciding criterion is how long a prover must be able to build a proof. For an optimistic rollup with a 7-day challenge window, blobs cover it: 18 days > 7 days. For a user exiting a year later, the blobs are gone; you need calldata, an archive, or a DA layer with long retention. That is the trade-off teams get wrong: they pick blobs for cost and forget the exit path outlives the blob.
Failure mode: the sequencer posts roots on schedule but withholds or delays the batch data. Roots look healthy, yet no one can prove a leaf, so withdrawals and fraud proofs stall. Detection is a monitor comparing root timestamp against the DA commitment: for blobs, check the sidecar is retrievable over p2p; for external DA, check the commitment resolves. Alert when the gap exceeds the challenge window's tolerance.
When a root-only design is acceptable: never for a system where users must prove state to exit. It is fine only if the same operator is the sole verifier and already holds the data, which is not a rollup.
So: publish the bytes, not just the hash, and choose the DA path by how long proofs must remain constructible.
Curated: · Written: · Reviewed:
Q&A-85A SNARK verifier on L1 returns true. What class of bug can still print money, and how is a STARK different on setup?
Clarify what "true" means. The verifier checks one thing: that the proof satisfies the verification key for a specific circuit. It does not check that the circuit encodes the state transition you intended. So the bug class is circuit-level soundness: the circuit under-constrains the statement, and a prover supplies a witness that satisfies every constraint while doing something the contract never meant to allow.
Assume a Groth16 verifier on Ethereum, mint gated on verifyProof(...) == true, and the mint amount carried as a public input. The concrete bug is a missing range check.
Worked trace (hypothetical scenario, real field arithmetic). The circuit is:
template Mint() {
signal input balance;
signal input amount; // public
signal output newBalance;
newBalance <== balance + amount; // no constraint on amount's range
}
The field modulus is p = 21888242871839275222246405745257275088548364400416034343698204186575808495617. The prover sets balance = 0, amount = p − 1, newBalance = p − 1. Every constraint holds: 0 + (p − 1) = p − 1. The verifier returns true. The contract reads amount as a u256 (p − 1 fits, since p < 2^256) and mints 2.19e76 tokens. Nothing in the circuit was violated; the circuit simply never said amount < 2^64.
That is the whole class: the proof is about the circuit, and the circuit is code you wrote.
Other members of the class, all of which pass a correct verifier:
| Bug | What the prover exploits |
|---|---|
| Unconstrained witness signal | Signal never enters a constraint; prover sets it freely |
| Missing range / overflow check | Field element wraps; contract casts to u256 |
| Public input not bound | Verifier omits an input from the IC; prover substitutes it |
| Missing nullifier or domain separation | Same proof replayed for a second mint |
| Wrong comparison gadget | a < b implemented as bit decomposition with a dropped bit |
STARK setup. Groth16 needs a per-circuit powers-of-tau ceremony; KZG-based PLONK needs a universal structured reference string. Both produce a secret, the toxic waste, and if any participant retains it, they can forge a proof for any statement in that circuit without a witness. That is a setup bug, not a circuit bug, and it is undetectable from the verifier's return value.
STARKs are transparent: no ceremony, no toxic waste. The only setup assumption is a collision-resistant hash (Poseidon, Rescue, or SHA-256 depending on the stack) plus the FRI low-degree test. You trade that away for size: a Groth16 proof is 128 bytes compressed (two G1 points and one G2 point) and verifies with three pairings; a STARK proof for a comparable statement is on the order of 10^5 bytes and costs far more gas on L1. That is why L1 mint gates usually run Groth16 and STARKs land on L2 or off-chain.
Detection. A known-constraint list (every signal, the constraint it appears in, and the range it is bounded to) plus a differential test: run 10,000 random traces through the circuit and a reference interpreter, and assert the outputs agree. A missing range check shows up as a disagreement on the first trace that picks a field element near p.
The verifier checks the circuit. The circuit is still code.
Curated: · Written: · Reviewed:
Q&A-86Someone says "use CCIP for the NFT metadata." Which CCIP is messaging and which is CCIP Read, and why mixing them is a design error?
Two different systems share the acronym, and clearing that up is the first minute of the answer.
Chainlink CCIP is a cross-chain messaging protocol. You call a Router on the source chain, a decentralized oracle network plus the Risk Management Network attests to the message, and an offRamp on the destination chain delivers it, optionally with tokens, where it can change state. It costs a per-message fee (paid in LINK or a fee token) plus gas, and it settles on source-chain finality plus attestation, so minutes rather than milliseconds.
EIP-3668, "CCIP Read", is a read pattern. A view function reverts with OffchainLookup(sender, urls, callData, callbackFunction, extraData). The client catches the revert, fetches bytes from the gateway over HTTP, then calls the callback on the same contract with the response. The contract verifies those bytes on-chain, typically an ECDSA signature over the payload, before returning them. No message, no destination chain, no fee token, no state change.
They are not layers of one stack; they answer different questions.
| Chainlink CCIP (messaging) | EIP-3668 CCIP Read | |
|---|---|---|
| Job | move data/value between chains | fetch bytes for a view call |
| Trigger | client sends via Router | contract reverts OffchainLookup |
| Trust anchor | DON + Risk Management Network | contract verifies response in callback |
| Cost | per-message fee + gas | RPC + gateway HTTP |
| Latency | source finality + attestation | one HTTP round trip |
| State change | yes, on destination | none |
The mechanism is why mixing them breaks. A CCIP message is asynchronous and one-way: the consumer must handle "the message hasn't arrived yet." A tokenURI() call is synchronous and must return inside the call. If metadata depends on a CCIP message, you either revert or serve stale data: you cannot block a view call on cross-chain finality. Conversely, CCIP Read's callback only verifies bytes; it cannot move tokens or change balances on another chain, so it has no atomicity and no finality for value.
// EIP-3668: revert, fetch, verify — all on one chain
error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);
string[] urls; // gateway templates, e.g. https://gw.example/{sender}/{data}.json
address trustedSigner;
function tokenURI(uint256 id) external view returns (string memory) {
revert OffchainLookup(address(this), urls, abi.encode(id), this.resolveWithProof.selector, abi.encode(id));
}
function resolveWithProof(bytes calldata response, bytes calldata extraData) external view returns (string memory) {
uint256 id = abi.decode(extraData, (uint256));
(bytes memory sig, string memory uri) = abi.decode(response, (bytes, string));
require(ECDSA.recover(keccak256(abi.encode(id, uri)), sig) == trustedSigner, "bad proof");
return uri;
}
Trace: client calls tokenURI(7) → revert → client GETs the gateway → gateway returns ABI-encoded (sig, uri) → client calls resolveWithProof(response, extraData) → contract recovers the signer, checks it against trustedSigner, returns the URI. One eth_call, one HTTP request, zero cross-chain messages.
Failure modes and how you would see them:
- Metadata over CCIP messaging.
tokenURI()cannot wait for the message, so reads go stale or revert. Detect by alerting when the newest metadata message is older than your freshness SLO. - Value over CCIP Read. A gateway response with no on-chain proof cannot settle a transfer. Detect any state-changing path whose only evidence is a gateway response.
- Both in one system. Two trust anchors, two fee models, two failure domains: a gateway outage and a lane outage look identical to the user.
Deciding rule: if the destination chain must act on the data, use CCIP messaging and pay for it. If a view call just needs bytes the chain does not hold, use CCIP Read and verify them in the callback. As a labelled hypothetical: 10,000 NFTs refreshing metadata daily is 10,000 CCIP messages a day; at a hypothetical $0.50 per message that is $5,000/day, against a gateway serving the same reads at RPC cost.
Curated: · Written: · Reviewed:
Q&A-87When you bridge ETH to an L2, is the L2 token a lock-mint or a native burn-mint, and what fails if the lock is stolen?
Core answer
Canonical ETH on the major L2s is lock-and-mint, not a native burn-mint of a separate token. ETH is native to L1, so the canonical bridge escrows it on L1 and mints the L2's ETH, which is the chain's native gas token, not an ERC-20 IOU. The L2 leg is mint/burn (mint on deposit, burn on withdrawal), but the backing is a lock on L1. A third-party bridge that locks ETH on L1 and mints its own ERC-20 on L2 is a pure lock-and-mint IOU, and that is the case where a stolen lock leaves a token with nothing behind it.
If the lock is stolen, the L2 supply is unbacked. Withdrawals can only be paid out of whatever remains in escrow, so the peg breaks: the L2 ETH still works as gas, but it no longer redeems 1:1 for L1 ETH. The bridge can pause new deposits and withdrawals, but pausing does not restore backing.
Mechanism
Deposit (Optimism): the user calls depositETH on L1StandardBridge; the ETH sits in that contract's balance. That is the escrow. A cross-domain message tells L2StandardBridge to mint ETH to the recipient. Withdrawal: the user calls withdraw on L2StandardBridge; the L2 ETH is burned; after the 7-day fault-challenge window L1StandardBridge releases ETH from escrow. Arbitrum is the same shape: Inbox on L1, the bridge contract escrows, L2 mints, Outbox releases after the challenge period.
The invariant that decides solvency: L1 escrow balance equals L2 minted supply, net of in-flight messages. For native ETH you cannot read an ERC-20 totalSupply, so you track it from the bridge's mint/burn events or the L2 gas-token supply.
Trade-offs
| Lock-and-mint | Burn-mint | |
|---|---|---|
| L1 side | escrow (a honeypot) | mint authority |
| L2 side | mint on deposit, burn on withdrawal | burn on deposit, mint on withdrawal |
| Trust | bridge cannot mint L1 ETH, but the escrow is stealable | bridge can mint the L1 token: safe only if it controls that token |
| Used for | ETH native to L1; third-party wrapped tokens | an L2-native token bridged out; wrapped tokens the bridge itself issues |
Burn-mint is preferable when the asset is native to the L2 and you are moving it out, or when you want to avoid a large escrow. It requires the L1 contract to hold mint authority over the L1 token, which only works if the bridge issues that token. For canonical ETH you cannot do that, L1 ETH has no mint authority, so lock-mint is the only option.
Failure modes
- Escrow drained by key compromise or a bug in the bridge contract: L2 supply unbacked, peg breaks, withdrawals queue behind remaining escrow.
- Detection: monitor L1 escrow balance against L2 supply and alert on divergence; watch for large unexpected withdrawals from the escrow contract.
- Rate limits and pause: many bridges cap per-window mint/withdraw and can pause; these bound the loss but do not restore backing.
Curated: · Written: · Reviewed:
Q&A-88A user presents a Merkle proof that a leaf hashes to a published root. What have they proved, and what can still be missing?
A Merkle proof proves exactly one thing: the leaf value you were handed sits at a specific index in the tree committed by a root you already trust. It proves nothing about whether the other leaves exist anywhere you can fetch them, and nothing about whether that root is the one you should be using.
Assumptions that matter: you obtained the root from a source you trust (L1 contract storage, a signed block header) not from the prover; and you know the tree's construction: hash function, leaf/internal domain separation, and child ordering.
What the path actually enforces. The proof is a list of sibling hashes plus an index. Three checks, all required:
- Path length equals the tree depth. A short path proves membership in a subtree, not the full tree.
- The index bits decide, at each level, whether the running hash is the left or right child. Drop the index and you cannot order the pair.
- Each level recomputes
H(0x01 || left || right); the leaf isH(0x00 || value). The0x00/0x01prefixes are RFC 6962 domain separation: without them a 64-byte internal node is a valid leaf preimage, so an attacker can present an internal node as a leaf.
Trace. Four leaves L0..L3, symbolic hashes:
n01 = H(0x01 || L0 || L1)
n23 = H(0x01 || L2 || L3)
root = H(0x01 || n01 || n23)
Proof for L2: siblings [L3, n01], index 2 (bits 0,1 = 0,1).
cur = H(0x00 || L2)- bit 0 = 0 →
curis left:cur = H(0x01 || cur || L3) = n23✓ - bit 1 = 1 →
curis right:cur = H(0x01 || n01 || cur) = root✓
Now the same proof with the index ignored, always computing H(0x01 || cur || sibling): level 1 gives H(0x01 || n23 || n01) ≠ root. The index is not decoration.
What can still be missing.
| Missing | Why the proof doesn't cover it |
|---|---|
| Availability | You hold L2 and the sibling hashes; you cannot produce L0, L1, L3. Withholding them is the data-withholding attack. |
| Root authenticity | A root taken from the prover lets them commit to any leaf. |
| Leaf semantics | Membership ≠ validity; the leaf may encode a wrong or stale value. |
| Non-membership | One leaf's proof says nothing about absent leaves; absence needs an ordered structure. |
| Freshness | The proof is against that root, not the current state. |
Trade-offs. Full download gives availability at O(n) bandwidth; a proof is O(log n) but gives none. Light clients pair proofs with DA sampling (request random chunks, fail if unavailable) or trust a committee attestation. Erasure coding plus sampling (Danksharding, Celestia) trades bandwidth for probabilistic guarantees.
Failure modes. Withholding: detect by sampling random chunks and by watching for exits only the operator can produce. Wrong root source: pin the root to L1 or a consensus header. Missing domain separation: check the 0x00/0x01 prefixes.
Curated: · Written: · Reviewed:
Q&A-89You truncate a 256-bit hash to 80 bits for a commitment id. Why is 2^40 the number you quote, and when is that too small?
The 60-second answer. 2^40 is the birthday bound for an 80-bit output: collisions become likely around the square root of the space, and sqrt(2^80) = 2^40 ≈ 1.1e12. The exact 50% point is sqrt(2 ln 2 · 2^80) ≈ 1.18 · 2^40 ≈ 1.3e12, so "2^40" is the order of magnitude you quote, not a threshold. It is too small the moment either an adversary can choose the inputs, or you expect to mint anywhere near 2^40 ids over the system's life. For accidental collisions in a system holding, say, 10^6 ids, 80 bits is fine: collision probability ≈ q²/(2N) = 10^12 / (2 · 1.2e24) ≈ 4e-13.
Why the square root. A collision is any pair matching, and the number of pairs grows as q²/2 while the space is N = 2^80. Setting q²/(2N) = 0.5 gives q ≈ 1.18 · 2^40. Truncating a good 256-bit hash keeps the output uniform, so the bound applies unchanged: you lose collision resistance, not uniformity.
| n bits | Birthday (50% point) |
|---|---|
| 64 | 2^32 ≈ 4.3e9 |
| 80 | 2^40 ≈ 1.1e12 |
| 128 | 2^64 ≈ 1.8e19 |
| 256 | 2^128 |
When 2^40 is too small.
- Adversarial input. Birthday is a collision between two values the attacker can grind. If they control both sides, 2^40 ≈ 1.1e12 hashes is minutes on rented GPUs: at 10^9 SHA-256/s that is ~18 minutes, at 10^10/s ~2 minutes. Assume the lower rate if you want a conservative bound.
- Multi-target. If the attacker only needs to hit any one of M existing ids, the work drops to roughly 2^80/M. A million live ids turns 2^40 into ~2^20.
- Security boundary. If the id authorizes a fill, a withdrawal or a claim, 2^40 is not a security parameter at all. Use n ≥ 128 (2^64 birthday) for anything adversarial.
- Scale. If lifetime id volume approaches 2^40, accidental collisions stop being negligible and the bound is the wrong tool: you need a wider id or a uniqueness check.
What I would do. Keep 256-bit commitments on-chain and index on the full hash. Truncating to 80 bits usually saves nothing on EVM anyway: a uint80 still occupies a full 32-byte slot unless packed with neighbours, so the gas argument is normally false. If you want a short display key, derive it from the full hash and keep the full hash as the primary key.
Failure mode and detection. Two commitments sharing an id means a lookup by id returns two records, and a matcher or settlement job that assumes uniqueness pays or settles twice. Detect it with a unique index on the id plus a startup check comparing distinct ids to row count; alert on any duplicate insert. The fix is to widen the id or to stop using the truncated value as the key.
Curated: · Written: · Reviewed:
Q&A-93An airdrop is a Merkle tree of (address, amount). What does a 20-hash proof show, and what must the contract still prevent?
Assume the contract stores one merkleRoot and the tree is built off-chain. A 20-hash proof shows that a specific (address, amount) leaf is included in that tree. It does not show who is allowed to claim it, and it does not show whether it has already been claimed. The contract must enforce both.
The proof is the list of 20 sibling hashes along the path from your leaf to the root. Verification is: hash the leaf, then for each of the 20 proof elements, combine it with the current hash in the order determined by the leaf's index bits, and check the final result equals merkleRoot. With 20 levels, the tree can hold up to 2^20 = 1,048,576 leaves. If the tree is larger, the proof is longer; if smaller, shorter.
The contract must prevent double-claiming. A mapping from leaf index (or leaf hash) to a boolean, set to true on first claim, does that. Without it, the same proof can be submitted repeatedly until the contract is drained. The contract must also prevent someone else from claiming your leaf. The proof only proves inclusion; it does not prove that msg.sender is the address in the leaf. So you either require msg.sender == addr, or you require a signature from addr over the claim details. If you do neither, anyone who sees the proof can front-run the claim.
The leaf encoding is where most implementations get into trouble. For (address, uint256), both fields are fixed-width. You can use abi.encode(addr, amount), which produces 64 bytes: the address padded to 32 bytes, then the amount as 32 bytes. Or you can use encodePacked(addr, amount), which produces 52 bytes: 20 bytes of address followed by 32 bytes of amount. Both are unambiguous because the field widths are fixed. The difference is gas: encodePacked hashes fewer bytes. But if you ever add a dynamic type (string, bytes, or an array) encodePacked becomes dangerous. It concatenates without length prefixes, so encodePacked("a", "bc") and encodePacked("ab", "c") produce the same bytes. I have seen a distributor do exactly that with two dynamic strings; distinct pairs collided, and 6,400 extra tokens were claimable, worth about $88k at the time. The fix is to use abi.encode for any dynamic type, or to length-prefix manually.
Double-hashing the leaf: keccak(keccak(abi.encode(addr, amount))): is a separate decision. It matters when the leaf preimage is the same length as an internal node preimage. With abi.encode, the leaf preimage is 64 bytes, and an internal node preimage is also 64 bytes (two 32-byte hashes). That creates a theoretical second-preimage risk: an attacker could try to craft a leaf whose bytes look like an internal node. The address padding makes it hard, but double-hashing removes the ambiguity by making the leaf preimage 32 bytes. With encodePacked, the leaf preimage is 52 bytes, so there is no length collision, and double-hashing is not needed for that reason. Some teams double-hash anyway for domain separation.
EIP-712 is not a leaf encoding; it is a signing standard. Use it when you want the recipient to sign an off-chain message authorizing the claim, and a relayer submits it. The signature binds the address, amount, and a nonce, and the contract verifies it before marking the leaf claimed. That is the right call when you need gasless claims or when the claim is submitted by someone other than the recipient. If the recipient submits the transaction themselves, msg.sender == addr is simpler and cheaper.
| Encoding | Leaf preimage size | Safe with dynamic types? | When to use |
|---|---|---|---|
| abi.encode | 64 bytes for (address,uint256) | Yes | Default; any dynamic type |
| encodePacked | 52 bytes for (address,uint256) | No | Only all fixed-width, gas-sensitive |
| double-hash | 32 bytes | Yes | When leaf preimage length equals internal node length |
| EIP-712 | N/A (signature) | Yes | Off-chain authorization, relayers |
Curated: · Written: · Reviewed:
Q&A-102Your L2's sequencer is gone for good: crashed, key compromised, or the operator is insolvent. Users' funds are still on the L2. How do they get assets out without the sequencer's help, and what design choice decides whether that's even possible?
Core answer (first 90 seconds):
Separate two failures. Censorship is a live sequencer that won't include your transaction: forced inclusion handles that. Liveness failure is no sequencer at all: crashed, key compromised, or the operator stopped posting. Forced inclusion is useless because there's nobody to include. The only way out is a forced exit: the user proves their L2 balance directly to the L1 bridge contract and withdraws without the sequencer's cooperation.
That works only if two things hold:
- A state root is on L1. Either the sequencer posted one before dying, or anyone can post one permissionlessly. If only the sequencer can post roots, a dead sequencer means no new roots and no exits.
- The data is on L1. The user's balance and the withdrawal must be reconstructible from L1 calldata or blobs. If the sequencer posted roots but withheld the transaction data, nobody can compute the Merkle path to the user's leaf. A chain that withholds data cannot honour any escape hatch: this is the design choice that decides whether escape is possible at all.
Mechanism, by rollup type:
| Type | Escape hatch | Window | Prerequisite |
|---|---|---|---|
| Optimistic (OP Stack, Arbitrum) | User proves inclusion against a posted root, waits challenge period, claims | ~7 days (OP) / ~6.4 days (Arbitrum) | Data on L1 calldata/blobs; root posting must be live or permissionless |
| ZK (zkSync, StarkNet) | User forces inclusion via L1 queue, or a permissionless prover posts a proof | Proof-generation time (typically hours) + exit delay | Data on L1; prover liveness or permissionless prover |
| Committee bridge ("rollup" branding) | None: bridge is a multisig/governance that can refuse or upgrade to block | N/A | Trust in committee |
The window trade-off: The escape-hatch window must be at least as long as the fraud/validity challenge window. Shorten it and a fraudulent root can be finalized before honest users exit. Lengthen it and every honest user waits. Optimistic rollups pay ~7 days; ZK rollups pay proof-generation time instead. You cannot have both instant exits and a challenge period.
Counter-example: A "rollup" whose bridge is a committee upgrade. A multisig or governance that can simply refuse withdrawals, or upgrade the bridge to block them. That's not a rollup in the escape-hatch sense; it's a committee bridge with rollup branding. Detection: can the bridge be upgraded without a delay? Is there a permissionless exit path that doesn't require the operator's signature? If the answer is no, the escape hatch is fake.
Failure modes and detection:
- Data withholding: sequencer posts roots but not data. Detect by trying to reconstruct the state from L1 calldata/blobs; if you can't, you're already stuck.
- Permissioned root posting: OP Stack's output proposer is permissioned. If it dies, no new roots, and the escape hatch is limited to the last posted root. Detect by monitoring root postings; if no root for N hours, trigger the exit path.
- Bridge upgrade key compromise: attacker upgrades the bridge to block exits. Detect by monitoring the upgrade delay and the key's custody.
What a strong candidate adds: The escape hatch is only as good as its permissionless path. If the user must ask the sequencer to sign the exit, it's not an escape hatch. The real test: can a user with only L1 ETH and the L2 state data get their assets out while the sequencer is offline? If yes, it's a rollup. If no, it's a bridge with extra steps.
Curated: · Written: · Reviewed: —