Skip to content
Tech Interview Prep
Technical interview guide

Layer 2 Scaling & Rollups

How rollups and other Layer 2 systems scale transaction throughput while still inheriting the base chain's security guarantees.

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

Scope: Ethereum rollup architecture and EIP-4844; OP Stack derivation, deposits, withdrawals, fault proofs and interoperability specifications reviewed 2026-09-04; Arbitrum Nitro architecture (protocol-specific parameters must be verified at deployment).

Interview Q&A

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

Curated: · Written: · Reviewed:

25 questions

Q&A-1

Define the trust boundary of a proposed rollup.

Answer

The trust boundary is the line where L1 stops being able to force a correct state root. Everything inside it (sequencer, prover, challengers, bridge contracts, upgrade keys) can change your balance or block your exit without L1 correcting it. Everything outside is verified by L1, so you don't have to trust it.

For an optimistic rollup like Arbitrum One or OP Mainnet, the boundary sits at the challenge window. L1 resolves a bad state root only if an honest party posts a bond and a fraud proof inside the window: 7 days on both. So the boundary includes "at least one live, funded, honest challenger for 7 days." If nobody challenges, L1 accepts the root. Arbitrum's BoLD made that challenger set permissionless and bonded; OP Mainnet's fault proofs went permissionless in June 2024.

For a validity rollup like zkSync Era or Starknet, the boundary is the verifier contract and the proof system. L1 resolves everything as long as the verifier is sound and the data is available: no challenger needed. But the prover becomes a liveness dependency: no proof, no finality.

Where the boundary falls:

ComponentInside the boundary (you trust it)Outside (L1 enforces)
SequencerOrdering, censorship, MEVForced inclusion via L1 inbox
Data publicationBatch data posted to L1Availability of blob/calldata
Proof / disputeChallenger or prover livenessFraud/validity proof verification
SettlementState root postedL1 contract accepts the root
Bridge custodyUpgrade keys, admin multisigExit proof verification
UpgradesTimelock length, signer set—

Failure modes, and how you detect each:

  • Sequencer censorship. Detect by submitting a forced-inclusion transaction to the L1 inbox. Arbitrum's delayed inbox auto-includes after 24 hours; OP Stack has an L1 force-inclusion path. If your tx never lands, the sequencer is inside the boundary.
  • Data withholding. Detect by checking the batch's blob or calldata on L1. EIP-4844 blobs are 128 KiB each (3 target / 6 max per block at Dencun) and are pruned after ~18 days, so DA must be settled before then or the state is unreconstructable.
  • Inactive challengers. Detect by watching the dispute game. If the 7-day window closes with no dispute, the root is final and L1 has ceded the boundary.
  • Prover failure. Detect by proof-submission latency. A validity rollup with no proof posted is stalled, not unsafe, but your exit is blocked.
  • Bridge compromise. Detect via the upgrade timelock. A zero-day timelock means the boundary includes the multisig, not the proof system.
  • Unusable exits. Detect by attempting a withdrawal. If it needs a proof only the sequencer can produce, the exit is inside the boundary.

The trade-off: optimistic rollups are cheap to post but expensive to exit. 7 days and bonded capital. Validity rollups are expensive to prove but give fast finality, at the cost of prover liveness. Pick optimistic when proving cost dominates and users tolerate a 7-day exit; pick validity when you need fast finality or the state is too complex to re-execute.

Arithmetic: 7 days × 86,400 s / 12 s L1 blocks = 50,400 blocks. A challenger must monitor every root for 50,400 blocks. A one-hour monitoring gap is 300 blocks of unguarded window: that's the boundary you actually have.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Define a rollup data-availability strategy.

Answer

The 90-second answer

Assume Ethereum L1 settlement, a single sequencer, and a rollup that must let any user exit without the sequencer's cooperation. A data-availability strategy is a written contract with four fields: (1) the exact bytes published (the compressed batch, not the state root; (2) where they are published) L1 calldata, blobs, a DAC, or an external DA layer; (3) the retention window. How long a fresh node can still fetch them; (4) the mechanism that lets an unprivileged node prove retrievability, or fail the batch if it can't. The state commitment is not the data: a root lets you verify a transition, not reconstruct it, so it can't produce an exit or a fault proof on its own.

Choosing where

optioncost for 128 KiBretentiontrust assumption
L1 calldata131,072 × 16 = 2,097,152 gas ≈ 0.042 ETH (~$126 at 20 gwei, $3k ETH)foreverEthereum
EIP-4844 blob131,072 blob gas; at the 1 wei floor ≈ 1.3×10⁻¹³ ETH~18 days (4096 epochs)Ethereum
Validium / DACoff-chain, near-zerooperator-definedM-of-N committee
External DA (Celestia, EigenDA)off-chain, near-zerolayer-definedlayer consensus + sampling

Deciding criteria: if exits must survive a total sequencer and committee failure, pay for blobs and accept the 18-day window. After that, availability rests on whoever archived the sidecars. If the asset is low-value and the committee is genuinely independent, validium is defensible. Blobs are ~16× cheaper than calldata per byte at equal gas price because blob gas is 1 gas/byte against calldata's 16 gas/nonzero byte, and the blob base fee is a separate market that has often sat at its 1 wei floor.

Worked trace: one batch, one blob

Sequencer compresses 1,000 txs to 90 KB, pads to 128 KiB, computes a KZG commitment, and posts a blob tx plus the commitment in calldata. A fresh node: (1) reads the commitment from L1; (2) fetches the blob sidecar from beacon gossip; (3) checks the KZG proof. The blob hashes to the committed value; (4) decompresses and executes against pre-state; (5) compares the resulting root to the batch's claimed root. Step 3 is the DA check: it fails if the sidecar is missing, and no amount of proof verification substitutes for it.

Failure modes and detection

  • Withholding: sequencer posts the commitment, withholds the blob. Detection: a monitor polls ≥2 independent sources (own beacon node + a DA gateway) and alerts when a commitment has no retrievable blob after N slots. Cost: the batch can't be proven, so it can't finalize, but if it already finalized on a validity rollup, users are stuck until the proof window closes.
  • Incomplete encoding: with 2D Reed–Solomon, >50% of chunks withheld makes the block unrecoverable. A light node taking 30 random samples accepts such a block with probability ≤2⁻³⁰ (~1 in 10⁹); that's the number to quote, not "sampling is secure."
  • Archive expiry: after ~18 days blobs are pruned from beacon nodes. Detection: run a sidecar archiver and alert if any commitment in the last 30 days has no archived copy.
  • Wrong commitment: KZG verification fails immediately. Cheap to detect, and it's a liveness bug, not a safety one.
  • Committee collusion (validium): M-of-N signers attest availability without serving data. Detection: sample the committee's endpoints yourself; if any signer can't serve the bytes, treat the attestation as void.

The strategy is only as strong as the weakest of those four fields, so write them down and test the retrieval path on a fresh node before mainnet.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Validate state commitments in a rollup node.

Answer

Core answer (first 90 seconds)

Assume an optimistic rollup (OP Stack-style): a proposer posts a state commitment, an output root, to L1 every 120 seconds, and the node's job is to decide whether that root is the one its own derivation produces. The check is three steps, in order: derive, execute, compare. If any step disagrees, the commitment is invalid, and the node must be able to prove which step failed.

Assumptions: L1 is canonical enough to read; the node has the rollup's chain config (genesis, L1 contract addresses, hardfork schedule); the commitment names the L1 origin it was derived from.

Mechanism

Derivation. Read L1 blocks forward from the last known origin, pull batch data from the batch inbox (calldata or EIP-4844 blobs), decompress channels, order frames by timestamp, and emit the L2 input sequence. This is deterministic given L1: same L1 blocks, same batches, same sequence.

Execution. Apply that sequence to the parent L2 state with the rollup's EVM and gas rules, producing a new state root.

Compare. The commitment is an output root, not a raw state root:

Python
# OP Stack output root; version is currently 0x00..00
# all four fields are 32 bytes
def output_root(version, state_root, message_passer_storage_root, latest_block_hash):
    return keccak256(version + state_root + message_passer_storage_root + latest_block_hash)

The version field is what lets the protocol change the commitment format without invalidating old roots: a node must reject a root whose version it does not implement rather than guess.

Provenance. Store, per commitment, the L1 origin block hash, the batch hashes consumed, and the protocol version. Without it you can detect a mismatch but not localize it.

Trade-offs

designwhat the node checkscostwhen to use
optimistic (OP Stack, Arbitrum)re-execute and compare; disputes resolved by bisection over the execution tracecheap on L1, 7-day challenge windowdefault; you trust at least one honest validator
validity / ZKverify a succinct proof on L1proving cost, no challenge windowfast finality needed
multisig / committeecheck signaturestrivialpermissioned deployments only

Deciding criterion: how long you can wait for finality, and who you are willing to trust.

Failure modes and detection

  • Wrong derivation (bad batch ordering, dropped frame): recomputed root diverges at a specific L1 origin. Detectable by re-deriving from the last matching origin.
  • Version mismatch: root's version byte not implemented. Reject immediately, do not fall back.
  • Malicious assertion: proposer posts a root for a state it never executed. Caught by the compare step; the fault proof bisects to the first divergent instruction.
  • Missing data: batch data unavailable on L1 (pruned blobs). Derivation stalls; the node must not advance past the gap.
  • Nondeterminism: same inputs, different root. Usually a gas-metering or precompile difference between node builds; detect by running the same batch on two builds.
  • Reorg: an L1 reorg changes the origin. Invalidate commitments derived from orphaned blocks and re-derive.

Trace of a mismatch

Node at L1 origin 21,000,000, committed root C for L2 block 12,000,000. Derive → 3 batches. Execute → state root R. output_root(0x00, R, ...) = C' ≠ C. Bisect: replay half the batches, compare intermediate roots; first divergence at batch 2, frame 4. A frame the proposer dropped. That localizes the fault to a specific frame instead of just flagging the root.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Implement and test a derivation pipeline.

Answer

Assumptions. OP Stack derivation as op-node implements it: L1 = Ethereum mainnet (12 s blocks), L2 = OP Mainnet (2 s blocks), span batches enabled (Canyon+). Span batches change only the batch encoding inside a channel; the frame and channel layers below are untouched, so I decode the legacy batch payload: smaller decoder, same channel.

Core. Derivation is a pull-based pipeline: L1 traversal → L1 retrieval → frame queue → channel bank → channel assembler → batch queue → payload attributes → engine queue. Each stage is a pure function of (canonical L1 data, rollup config) plus one cursor. That is what makes an L1 reorg cheap: rewinding the cursor re-derives everything downstream, with no side effects to roll back. Test it the same way: a fake L1 source, a golden L2 chain, and a reorg injected mid-stream.

Go
// go1.22 — frame/channel layer.
package derive

import (
	"encoding/binary"
	"errors"
)

const (
	MaxFrameSize      = 120_000 // frame_data_length upper bound
	ChannelTimeout    = 300     // L1 blocks a channel may stay open
	MaxSequencerDrift = 600     // seconds past the L1 origin timestamp
)

var (
	ErrFrameTooShort = errors.New("frame truncated")
	ErrFrameTooLarge = errors.New("frame data exceeds MaxFrameSize")
)

type Frame struct {
	ID     [16]byte
	Number uint16
	Data   []byte
	IsLast bool
}

// ParseFrames splits one batcher calldata payload (the bytes after the
// leading 0x00 derivation version byte) into frames.
func ParseFrames(data []byte) ([]Frame, error) {
	var out []Frame
	for len(data) > 0 {
		if len(data) < 23 {
			return nil, ErrFrameTooShort
		}
		var f Frame
		copy(f.ID[:], data[:16])
		f.Number = binary.BigEndian.Uint16(data[16:18])
		n := binary.BigEndian.Uint32(data[18:22])
		if n > MaxFrameSize {
			return nil, ErrFrameTooLarge
		}
		if uint32(len(data)-23) < n {
			return nil, ErrFrameTooShort
		}
		f.Data = data[22 : 22+n]
		f.IsLast = data[22+n] == 1
		out = append(out, f)
		data = data[23+n:]
	}
	return out, nil
}

type Channel struct {
	ID     [16]byte
	frames map[uint16][]byte
	last   uint16
	closed bool
	openAt uint64
}

func (c *Channel) Add(f Frame, l1Block uint64) {
	if c.frames == nil {
		c.frames = map[uint16][]byte{}
		c.openAt = l1Block
	}
	if _, dup := c.frames[f.Number]; dup {
		return
	}
	c.frames[f.Number] = f.Data
	if f.IsLast {
		c.last, c.closed = f.Number, true
	}
}

// Read returns the channel payload once frames 0..last are all present.
func (c *Channel) Read() ([]byte, bool) {
	if !c.closed {
		return nil, false
	}
	var buf []byte
	for i := 0; i <= int(c.last); i++ {
		d, ok := c.frames[uint16(i)]
		if !ok {
			return nil, false
		}
		buf = append(buf, d...)
	}
	return buf, true
}

// Expired reports whether the channel has been open longer than
// ChannelTimeout L1 blocks.
func (c *Channel) Expired(l1Block uint64) bool {
	return l1Block > c.openAt+ChannelTimeout
}
Go
package derive

import (
	"encoding/binary"
	"errors"
	"testing"
)

func encodeFrame(id [16]byte, num uint16, data []byte, last bool) []byte {
	b := append([]byte{}, id[:]...)
	b = binary.BigEndian.AppendUint16(b, num)
	b = binary.BigEndian.AppendUint32(b, uint32(len(data)))
	b = append(b, data...)
	if last {
		return append(b, 1)
	}
	return append(b, 0)
}

func TestChannelReassembly(t *testing.T) {
	id := [16]byte{0xAA}
	// frame 1 arrives before frame 0: calldata order must not matter
	raw := append(encodeFrame(id, 1, []byte("world"), true),
		encodeFrame(id, 0, []byte("hello"), false)...)

	frames, err := ParseFrames(raw)
	if err != nil {
		t.Fatal(err)
	}
	if len(frames) != 2 {
		t.Fatalf("frames = %d, want 2", len(frames))
	}
	ch := &Channel{}
	for _, f := range frames {
		ch.Add(f, 100)
	}
	got, ok := ch.Read()
	if !ok || string(got) != "helloworld" {
		t.Fatalf("Read() = %q, %v; want \"helloworld\", true", got, ok)
	}
}

func TestFrameTooLarge(t *testing.T) {
	id := [16]byte{0xBB}
	b := append([]byte{}, id[:]...)
	b = binary.BigEndian.AppendUint16(b, 0)
	b = binary.BigEndian.AppendUint32(b, MaxFrameSize+1)
	b = append(b, 0) // one byte of frame data
	if _, err := ParseFrames(b); !errors.Is(err, ErrFrameTooLarge) {
		t.Fatalf("err = %v, want ErrFrameTooLarge", err)
	}
}

func TestChannelTimeout(t *testing.T) {
	ch := &Channel{}
	ch.Add(Frame{ID: [16]byte{1}, Number: 0, Data: []byte("x")}, 100)
	if _, ok := ch.Read(); ok {
		t.Fatal("open channel must not read")
	}
	if ch.Expired(400) {
		t.Fatal("expired at 400, want open")
	}
	if !ch.Expired(401) {
		t.Fatal("not expired at 401, want expired")
	}
}

Trace of TestChannelReassembly. raw is 56 bytes: frame 1 (16-byte ID + 2-byte number + 4-byte length + 5 bytes world + 1 byte 1) then frame 0 (same shape, hello, trailing 0). First iteration: len(data) = 56 ≥ 23, n = 5, len(data)-23 = 33 ≥ 5, so Data = data[22:27] = "world" and IsLast = data[27] == 1 → true; the cursor advances 28 bytes. Second iteration: Number = 0, Data = "hello", IsLast = false; advances 28, leaving 0. Add sees frame 1 first, so openAt = 100, frames[1] = "world", last = 1, closed = true; frame 0 then lands in the map. Read walks i = 0, 1 and returns "helloworld", true. TestFrameTooLarge builds exactly 23 bytes with n = 120001 > 120000, so ParseFrames returns ErrFrameTooLarge before reading any frame data. TestChannelTimeout opens at L1 block 100; 400 > 400 is false, 401 > 400 is true.

Batch → payload attributes. A channel payload is a sequence of version-prefixed batches. 0x00 is a legacy batch (RLP [epoch_num, epoch_hash, timestamp, tx_list]); 0x01 is a span batch carrying the same fields for a run of L2 blocks. Two timestamp rules decide acceptance against the L1 origin block: timestamp >= epochTime and timestamp <= epochTime + MaxSequencerDrift (600 s). Derived attributes: {timestamp: batch.Timestamp, prevRandao: epoch.mixHash, parent: last L2 block, noTxPool: true, gasLimit: 30_000_000, transactions: [L1 attributes deposit] ++ [deposits from the epoch's OptimismPortal logs] ++ batch.Txs}. At 2 s L2 blocks and 12 s L1 blocks that is 6 L2 blocks per epoch, and the 600 s drift window spans 300 L2 blocks.

Trade-offs. Pull-based stages make a rewind a cursor reset; a push-based event loop needs explicit backpressure and turns reorg handling into a distributed rollback. Span batches cut per-block calldata overhead versus legacy batches but need a more complex decoder. Since Ecotone the batcher can post to EIP-4844 blobs instead of calldata: cheaper, but blobs are pruned after 4096 epochs × 32 slots × 12 s ≈ 18.2 days, so derivation must never lag the L1 head by more than that or the data is gone. Calldata is permanent, which is why it stays the fallback.

failuresymptomdetection
parser divergencetwo nodes derive different L2 blocks from identical L1hash derived payload attributes per L1 block and compare across nodes
skipped deposituser funds never credited on L2reconcile L2 deposit count against TransactionDeposited logs from the L1 OptimismPortal per epoch
timestamp rule errorbatch accepted past epochTime + 600assert in derivation; alert on the drift error
config mismatchempty channel bank, chain stallscompare --batch-inbox-address (default 0xff00000000000000000000000000000000000010) and L2 chain ID across nodes at startup
malformed channelframe over 120 000 bytes or truncatedcount ErrFrameTooLarge / ErrFrameTooShort; a spike means a bad batcher
deep reorgsafe head sits above a reorged L1 origintrack the safe head's L1 origin; rewind when L1 ancestry changes
inconsistent safe headsafe head not a prefix of unsafe headassert safeHead.number <= unsafeHead.number and shared ancestry

Channel timeout is 300 L1 blocks = 3600 s: a channel whose first frame lands at block N is dropped once the L1 head passes N+300, so a batcher that stalls mid-channel loses the whole channel, not just the tail.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Operate batch publication with blobs.

Answer

Assumptions and core answer

I'm running the batch poster for an L2 rollup that publishes transaction batches to Ethereum L1 as EIP-4844 blob transactions (type 0x03). Two problems, and conflating them is the classic mistake: getting the batch committed on-chain inside the fee budget, and keeping the data retrievable after Ethereum stops serving it.

Core answer: monitor blob base fee and inclusion, verify the KZG commitment matches what you archived, and archive the blob data yourself before the retention window closes. Blobs are cheap; they are not permanent.

Mechanism

Blobs have their own fee market, separate from execution gas. Blob base fee is denominated in wei per blob gas, not gwei, and updates by a fake-exponential rule over blob gas used, with a floor of 1 wei. One blob is 131072 blob gas (128 KiB). Since Pectra (May 2025) the target is 6 blobs per block and the max is 9; before that it was 3 and 6. Above target the base fee climbs block over block; below it decays. Your batch poster competes there, not in the execution fee market.

Cost arithmetic, illustrative: one blob costs blob_base_fee × 131072. At the 1 wei floor that's 131072 wei ≈ 1.3e-13 ETH. Even at 1000 wei, well above the floor, it's ~1.3e-10 ETH. The same 128 KiB as calldata is 131072 nonzero bytes × 16 gas = 2,097,152 gas; at 20 gwei that's ~0.042 ETH. The exact multiple moves with the blob base fee, but it is never close.

Choosing the publication path

pathcost for 128 KiBdurabilityEVM-readableuse when
blob (type 0x03)blob_base_fee × 131072pruned after 4096 epochs (~18 days)no: only the versioned hashdefault for rollup batches
calldata~2.1M gaskept by archive nodesyescontracts must read the data
delayed publicationsame as blob, latersamenolong challenge window, cost-sensitive

Failure modes and detection

  • Retention misunderstanding: someone assumes blob data is permanent. Consensus clients prune blobs after 4096 epochs (~18 days). Detect: alert when a batch's blob is older than ~17 days and your archiver doesn't hold it.
  • Missing sidecar: the blob tx is included but the sidecar (blob + KZG proof) never propagated, so nobody can reconstruct the data. Detect: after inclusion, fetch the blob by versioned hash from a beacon node; alert if it isn't retrievable within a few slots.
  • Commitment mismatch: the on-chain versioned hash doesn't match the blob you archived. Detect: recompute kzg_to_versioned_hash(commitment) and compare.
  • Fee spike / posting backlog: blob base fee jumps, your max fee cap is too low, txs sit pending and the batch backlog grows. Detect: pending blob tx age and batch age metrics.
  • Censorship: builders exclude your blob txs. Detect: the same backlog metric plus per-builder inclusion rate.

When not to use blobs

Contracts can't read blob data: they see only the versioned hash, so on-chain verification needs the point-evaluation precompile at 0x0A plus the sidecar off-chain. If contracts must read the data directly, use calldata. If you can't run your own archiver, don't rely on blobs alone. Delayed publication trades latency for cost: fine with a long challenge window, wrong when users expect fast finality.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Review a validity-rollup proving pipeline.

Answer

Core answer. Assume Groth16 over BN254, verifier on Ethereum L1, batch data in EIP-4844 blobs, verifier upgradeable behind a timelock. Review in the order trust flows, and at each stage ask what would have to be true for it to be wrong and what you would actually observe.

1. Circuit spec vs. implementation. Read the spec for what the circuit claims: "there exists a witness such that applying the batch to preRoot yields postRoot and the DA commitment matches", then check the implementation constrains every signal that claim depends on. The classic bug is an under-constrained signal: a range check on a balance that the spec asserts but the constraint system never enforces. A prover can then mint a transition that violates the spec and still produce a valid proof. Detection: differential-fuzz the circuit against a reference implementation, and keep a test that tries to prove a known-invalid witness. It must fail.

2. Setup. Groth16 needs a circuit-specific ceremony; if every participant colluded, the toxic waste lets them forge proofs for any statement. Check the transcript, the contribution hashes, and that the deployed verification key matches the published one. PLONK and Halo2 use a universal Powers of Tau (the Perpetual ceremony reached 2^28), so a circuit change does not force a new ceremony.

3. Prover. Reproduce a witness from the batch and re-prove it. Measure p99 proving latency and peak RAM, not the median. A 1M-constraint Groth16 proof is tens of seconds and several GB on a 16-core box; if batches arrive every 12 s, one prover cannot keep up.

4. Verifier. Confirm the public inputs bind preRoot, postRoot and the DA commitment, and that the verifier rejects a proof replayed from another chain. Groth16 verification is roughly 200k gas, dominated by the ecPairing precompile (45,000 base + 34,000 per pair after EIP-1108).

5. Data. Blobs are pruned after 4096 epochs ≈ 18 days. Six blobs per block at 128 KiB is 768 KiB per 12 s slot ≈ 5.3 GiB/day, so the retained window is ~95 GiB. If the rollup archives nowhere else, state older than 18 days is unreconstructable. Detection: run a reconstruction job against a 20-day-old blob; it fails.

6. Upgrade. A vkey change invalidates in-flight proofs; a malicious verifier upgrade accepts forged ones. Timelock plus a canary batch after each upgrade.

Trade-offs.

Groth16 (BN254)PLONK / Halo2STARK
setupcircuit-specific ceremonyuniversal / transparenttransparent
proof size128 B compressed, 256 B uncompresseda few KBhundreds of KB
L1 verify~200k gashigher: MSM over opening pointsusually impractical on L1
pick whencircuit is stable and a ceremony is crediblecircuits change oftenyou need transparency or post-quantum

Failure modes and how they show up. Key mismatch, deployed vkey ≠ prover vkey, is 100% proof rejection; compare the keccak of the vkey in the verifier against the build artifact. Prover centralization is a liveness risk: alert when no proof lands for 30 minutes. A proof backlog shows as growing queue depth. A verifier flaw that drops the chain-id check shows as a proof from chain A verifying on chain B.

Deciding criteria. How often the circuit changes, whether you can run a ceremony anyone believes, and whether verification must be cheap on L1. Those three pick the proof system; everything else is operational.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Threat-model a fault-proof game.

Answer

Core answer. A fault-proof game exists to answer one question on L1: is this state root correct? Two bonded parties disagree, and an interactive protocol narrows the disagreement until a single instruction can be executed on-chain. So the threat model is not "what could go wrong with the code": it is: who can make a false claim, what can they withhold, what can they spend, and what will the L1 verifier accept as proof. Assume the sequencer is the adversary (it can censor and reorder), L1 is honest but congested, and at least one challenger is bonded and watching. If that last assumption fails, nothing else matters.

Assets and attackers. Three things are at risk: the honest claim's liveness, the bonds, and the correctness of the on-chain verifier.

ThreatAttacker capabilityConsequenceDetection
False rootSequencer posts a wrong rootWrong state finalizes after the windowIndependent node recomputes the root
Censorship of dispute txSequencer excludes the challenger's bisection moveChallenger misses the response clock, loses bondTime-to-inclusion monitor on dispute txs
Verifier bugNone needed: the bug is passiveOne-step proof accepts a wrong instructionDifferential fuzzing vs a reference interpreter
Prestate withholdingData lives only on a centralized storeChallenger cannot build the one-step proofRebuild the proof from a fresh node
Bond griefingAttacker opens many gamesHonest challengers' capital lockedCount open games per challenger

Mechanism. Bisection. The root claim sits at depth 0. Each round the responder picks the midpoint of the disputed range and claims the state at that index; the range halves. After d rounds the range is one instruction. Then the one-step proof: the challenger submits the prestate hash, the instruction, and the poststate hash, and the L1 contract runs that single instruction in its VM. Optimism's fault dispute game uses Cannon's MIPS VM, Arbitrum's BoLD uses the same bisect-then-single-step shape. The loser's bond is slashed.

Worked trace (hypothetical numbers, structure matches production): trace length 2^30 steps, 30 bisection rounds, one L1 transaction each. At 200k gas per round and 20 gwei, that is 30 × 200,000 × 20e-9 = 0.12 ETH of gas per game, on top of the bond. The real cost of a challenge is the gas to walk 30 rounds, not the bond.

Trade-offs. Permissionless vs allowlisted challengers: allowlisting caps griefing but reintroduces a trusted set. The thing the game was supposed to remove. Fixed bond vs escalating bond: escalating bonds make a long grief expensive but require the challenger to hold 2^d × base in reserve, so production systems cap the bisection depth and use a fixed per-game bond instead. On-chain VM vs off-chain referee with an on-chain fraud proof: on-chain is trustless but the VM must be small enough to audit (MIPS is a small instruction set); a richer VM is faster but a bigger attack surface.

Failure modes and detection. Verifier bug: the on-chain VM mis-executes; detect by differential fuzzing the contract against a reference interpreter across the full instruction set and replaying historical games. Clock exhaustion: the response window is measured in L1 blocks, so a censoring sequencer or a gas spike can starve the challenger; detect by alerting on dispute txs unconfirmed past half the window. Unavailable prestate: the one-step proof needs the prestate hash, and if it lives only on a centralized store the challenger is stuck; detect by rebuilding the proof from a fresh node. Inactive challengers: with no bonded watcher live, wrong roots finalize; detect by counting distinct bonded challengers per open game and alerting at zero. Upgrade during dispute: a contract upgrade mid-game changes the rules the game is being judged under; freeze upgrades while games are open.

What to test. End to end: run a permissionless game on a testnet with a deliberately wrong root, a censoring sequencer, and a challenger that goes offline mid-game. The game should still resolve to the honest root, or fail loudly.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Specify an assertion lifecycle.

Answer

Clarify first. "Assertion" here means an optimistic rollup's claim about L2 state posted to L1: Optimism's fault dispute game, Arbitrum's assertion under BoLD. If you meant a unit-test assertion, the lifecycle is setup/act/assert/teardown and there's nothing to design.

The lifecycle, stage by stage.

  1. Propose. A proposer posts an assertion to an L1 contract: an output root plus the L2 block number it covers, backed by a bond in ETH. The bond is the security argument: it has to exceed the maximum value a false assertion could extract (a fraudulent bridge withdrawal), or lying is profitable. On Optimism that's op-proposer writing into the dispute game factory; on Arbitrum any validator can assert.

  2. Challenge window. A fixed clock during which anyone can dispute. Optimism's fault dispute game runs a 3.5-day clock (302400 s); Arbitrum One's challenge period is 6.5 days. The clock must be read from L1 time. A window derived from L2 block numbers drifts with L2 block time and is not the length you think it is.

  3. Challenge. The challenger posts a matching bond and the two sides bisect: each move halves the disputed range and posts another bond, until one instruction remains. That instruction is executed on-chain by a VM: Cannon/MIPS on Optimism, WAVM on Arbitrum. Execution is deterministic, so the wrong party loses by construction rather than by a judge's ruling.

  4. Resolution. The contract names a winner, slashes the loser's bond and pays it to the winner. The assertion is confirmed or rejected. Competing assertions at the same index are settled by whichever game resolves first; the other claim is discarded.

  5. Finalization. Optimism adds a further 3.5-day delay (DISPUTE_GAME_FINALITY_DELAY_SECONDS = 302400) after resolution before the root is usable, so a game can't be resolved and consumed in the same block. Total L1 finality is roughly 7 days; the pre-fault-proof L2OutputOracle used a flat 7-day FINALIZATION_PERIOD_SECONDS.

  6. Rollback. If the assertion is rejected, the output root is deleted from the oracle. The L2 chain is not reorged: the sequencer keeps producing blocks. What unwinds is L1-side accounting: withdrawals already proven against the deleted root must be re-proven against a new one, and the bridge's per-root bookkeeping resets. That blast radius is why withdrawals gate on finalization, not on the assertion being posted.

stagewho actsclockat stake
proposeproposer—bond in ETH
challenge windowany watcher3.5 d (OP), 6.5 d (Arb)challenger's matching bond
bisectionboth sidesbounded by game clockone bond per move
resolutioncontract—loser's bond slashed
finalization—+3.5 d (OP)root becomes usable
rollbackbridge—proven withdrawals re-proven

Trade-off. Optimistic versus validity proof: optimistic posts a root cheaply and pays only when disputed, but you buy ~7 days of latency and you must have at least one honest, funded watcher. A validity proof removes the window and the watcher requirement, at the cost of proving per batch and prover complexity. If you can't guarantee a live challenger with capital, optimistic is the wrong choice; if withdrawals need fast L1 finality, ZK is.

Failure modes and how you'd catch them.

  • No honest challenger: the sequencer is the only watcher. Detect by running an independent watcher that re-executes L2 blocks and alerts on a root mismatch. If nobody runs one, the system is trusted and you should say so out loud.
  • Bond too small: compare the bond against the largest single withdrawal the bridge allows inside one window. Bond below that number means fraud is profitable.
  • Ambiguous clock: assert the contract reads L1 block.timestamp; an L2-derived window drifts.
  • Griefing: a challenger forces the proposer to spend gas and post bonds. Bounded by bisection depth and by requiring the challenger to bond too.
  • Faulty verifier: the on-chain interpreter is the highest-risk component; a bug lets both sides "prove" the same thing. Optimism replaced its original MIPS VM with Cannon, and any such VM needs a second implementation or spec-level tests.
  • Releasing assets early: a bridge that credits a withdrawal when the root is posted rather than finalized. Detect by asserting the withdrawal path reads the finality delay.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Explain and operate an optimistic withdrawal.

Answer

What I'd say first

Assume OP Stack (Optimism, Base) with fault proofs enabled, moving ETH or an ERC-20 from L2 to L1, and I'm the one operating the withdrawal. An optimistic withdrawal is a three-transaction, two-chain sequence (initiate on L2, prove on L1, finalize on L1) with a mandatory dispute window between prove and finalize. The window exists because L1 holds the escrow and must not pay out against an L2 state root a challenger could still prove fraudulent. "Proof submitted" is not "money moved"; only finalize moves it.

Mechanism

  1. Initiate (L2). Call L2ToL1MessagePasser.initiateWithdrawal(target, gasLimit, data) with value. Nothing crosses to L1 yet: the withdrawal is appended to the message passer's storage and the value is escrowed on L2. You get a withdrawal hash. Cost is L2 gas only, order 100k gas.

  2. Wait for the output root. The withdrawal is provable only once an L2 output root covering that block is proposed on L1. With fault proofs that means a dispute game created by the DisputeGameFactory; on mainnet games are created roughly hourly. Until a game covering your block exists, proveWithdrawalTransaction has nothing to prove against.

  3. Prove (L1). Call OptimismPortal2.proveWithdrawalTransaction(...) with the withdrawal proof and output-root proof. This records the proof and starts the maturity clock. Cost is L1 gas, order 100k.

  4. Wait out the dispute window. On OP Stack mainnet the portal enforces proofMaturityDelaySeconds = 3.5 days and disputeGameFinalityDelaySeconds = 3.5 days: 7 days total, matching the fault-proof challenge period. If the game is challenged, its clock resets and your maturity timer effectively restarts.

  5. Finalize (L1). Call finalizeWithdrawalTransaction. The portal checks the game resolved DEFENDER_WINS, the proof is mature, and the withdrawal hash is not already finalized, then releases the escrowed asset. Cost is L1 gas, order 100k.

Trade-off: native vs liquidity bridge

Native withdrawalThird-party bridge
Time~7 daysminutes
CostL1 gas for prove + finalizebridge fee, typically ~0.1–0.5%
TrustL1 escrow + fault proofbridge solvency and honesty
Choose whenlarge amounts, no urgency, trust-minimizedsmall amounts, urgent, fee acceptable

Deciding criterion is amount × urgency against counterparty risk. A $5M treasury move waits 7 days; a $200 payout a user needs now goes through a bridge and eats the fee.

Failure modes and detection

  • Wrong or stale output root: proveWithdrawalTransaction reverts (InvalidProof, or the game is not the respected type). Detect by simulating with eth_call before broadcasting.
  • Challenge reset: the game clock resets and your 7-day timer restarts. Detect by watching game status on the DisputeGameFactory.
  • L1 reorg: the block your proof referenced is orphaned. Detect by re-checking the L2 block is still canonical before finalize; re-prove if not.
  • Replay: finalizedWithdrawals[withdrawalHash] is already true; a second finalize reverts WithdrawalAlreadyFinalized. Detect by reading the mapping.
  • Paused portal: a guardian pause makes finalize revert. Detect via paused().
  • Gas underestimation: finalize is gas-heavy; under-provisioning reverts out-of-gas and you lose the gas. Detect with estimateGas plus a buffer.
  • Premature credit: a bridge credits you before the native withdrawal finalizes; if finalize fails, the bridge (or you) eats the loss. Detect by reconciling bridge credit against native finalization.

Trace

Initiate at L2 block 120,000,000 → game covering it created at L1 block 20,100,000 → prove at L1 block 20,100,050 → earliest finalize at 20,100,050 + 7 days of L1 blocks → finalize releases 1 ETH from the portal to the target.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Integrate canonical deposits safely.

Answer

Assumptions: an OP Stack chain (Optimism, Base), and we are the L2-side integrator crediting user balances when a deposit lands, not the rollup operator.

Core answer. Never credit on the L1 receipt. Credit on the L2 deposit receipt, keyed by the deposit's (L1 block number, log index), and treat the credit as irreversible only once the L1 block that emitted TransactionDeposited is finalized. Alias checks, gas limits and token mapping are validation on top of that one rule.

How a deposit becomes L2 state. A user calls depositETH/depositERC20 on the L1 bridge, or depositTransaction on the OptimismPortal. The portal emits TransactionDeposited. The op-node derivation pipeline walks each L1 block's receipts in order and, for every such log, emits a deposit transaction into the L2 block: a type-0x7E transaction whose from is the L1 sender, whose value is minted on L2 against ETH locked in the portal, and whose calldata is the opaque payload. Derivation is deterministic and ordered, so one L1 log can only ever produce one L2 deposit. The nonce is assigned from the L1 block number and log index, which makes that pair the unique key to index on.

Sender aliasing. If the L1 sender is a contract, the L2 deposit's from is not that contract's address: it is the address plus 0x1111000000000000000000000000000000001111. The offset exists so an L1 contract cannot impersonate an L2 EOA that happens to share its address. EOAs are not aliased. A check like msg.sender == L1_VAULT therefore fails silently for every contract deposit:

SOLIDITY
// L2 target of a direct deposit, Solidity ^0.8.24
uint160 constant ALIAS_OFFSET = 0x1111000000000000000000000000000000001111;
address constant L1_VAULT = 0x...; // our L1 contract

function onDeposit(uint256 amount) external {
    require(msg.sender == address(uint160(L1_VAULT) + ALIAS_OFFSET), "unexpected sender");
}

If the deposit is relayed through L2CrossDomainMessenger (0x4200000000000000000000000000000000000007), msg.sender is the messenger and the original L1 sender comes from xDomainMessageSender().

Mint vs call. ETH deposits mint on L2; the ETH is locked in the portal on L1. ERC-20 deposits through the Standard Bridge lock the L1 token and either mint a paired OptimismMintableERC20 or pay out of the L2 bridge's pre-funded pool. The two paths fail differently: a mint cannot fail for liquidity, a pool payout can.

Failure modes and detection.

failuresymptomdetection
Wrong portal / counterfeit UIdeposit never appears on L2pin the L1 address to the chain's deployment registry; verify the L2 deposit's from is the aliased expected sender
L1 reorg before derivationcredited on the L1 receipt, no L2 depositreconcile against the L2 deposit receipt, not the L1 receipt
Duplicate creditsame deposit credited twiceunique index on (L1 block number, log index)
Alias confusioncontract deposits rejectedassert against sender + 0x1111...1111
Failed target calldeposit included, call revertedsimulate with eth_call on L2 before sending; alert on TransactionDeposited with no successful L2 receipt
Gas limit too lowtarget call OOG on L2estimate L2 gas and add buffer; the L1 portal charges for the limit you set
Token mismatchwrong L2 token creditedcheck the bridge's l1Token↔l2Token mapping

Trade-off: when to credit. L1 blocks are 12 s; Ethereum finality is 2 epochs = 64 slots ≈ 12.8 minutes. The sequencer picks the deposit up within seconds of L1 inclusion, so you can show a balance in roughly 15–30 s, but that credit is reorg-revertible until finality. Crediting only at finality costs ~13 minutes and removes the reorg class entirely. The middle path most teams take: credit optimistically at L2 inclusion, and block withdrawal of that credit until the L1 block finalizes. If 13 minutes is unacceptable, a third-party fast bridge fronts liquidity for a relayer fee: faster, but you inherit its trust assumptions, so that is a product decision, not a safety one.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Implement a withdrawal finalizer.

Answer

Assumptions. OP Stack, fault-proof era: op-contracts v1.8.0, OptimismPortal2. The L2 side is L2ToL1MessagePasser at 0x4200000000000000000000000000000000000016; the L1 side is a chain-specific portal. A zk rollup changes the constants, not the ordering argument.

Answer. A finalizer is two phases, because the Merkle proof is expensive and the security window is long. Prove once, finalize later.

Phase 1: proveWithdrawalTransaction(tx, gameIndex, outputRootProof, withdrawalProof):

  • withdrawalHash = keccak256(abi.encode(nonce, sender, target, value, gasLimit, data))
  • keccak256(abi.encode(version, stateRoot, messagePasserStorageRoot, latestBlockhash)) must equal the dispute game's root claim
  • SecureMerkleTrie.get(abi.encodePacked(withdrawalHash), withdrawalProof, messagePasserStorageRoot) must return exactly the byte 0x01: that is sentMessages[withdrawalHash] set in the message passer
  • store provenWithdrawals[withdrawalHash][msg.sender] = ProvenWithdrawal(root, uint128(block.timestamp), uint128(gameIndex))

Phase 2: finalizeWithdrawalTransaction(tx):

SOLIDITY
function finalizeWithdrawalTransaction(WithdrawalTransaction memory _tx) external nonReentrant {
    bytes32 h = hashWithdrawal(_tx);
    if (finalizedWithdrawals[h]) revert AlreadyFinalized();
    if (address(this).balance < _tx.value) revert InsufficientBalance();

    ProvenWithdrawal memory p = provenWithdrawals[h][msg.sender];
    if (p.timestamp == 0) revert Unproven();
    if (block.timestamp - p.timestamp < PROOF_MATURITY_DELAY_SECONDS) revert ProofNotMature();
    if (disputeGames[p.l2OutputIndex].status() != GameStatus.DEFENDER_WINS) revert ProposalNotFinalized();

    finalizedWithdrawals[h] = true;                  // effects before interaction
    (bool ok, ) = _tx.target.call{value: _tx.value, gas: _tx.gasLimit}(_tx.data);
    emit WithdrawalFinalized(h, ok);                 // no revert on failure
}

Trace (illustrative values). Alice initiates 1 ETH on OP Mainnet at L2 block 120,000,000, nonce 42. sentMessages[0x9f2c…] = true. The game covering that block resolves after its 3.5-day clock. Alice proves at time T, so provenWithdrawals[0x9f2c…][alice].timestamp = T. She finalizes at T + 3.5 days. Total from L2 inclusion: about 7 days. The 3.5-day game clock plus the 3.5-day maturity delay reconstruct the pre-fault-proof 7-day window.

Trade-offs.

  • Two-phase versus one: proving once and finalizing later keeps the Merkle proof off the finalization path and lets a third party front the proof gas. Cost is two L1 transactions and a stored proof per submitter.
  • provenWithdrawals[hash][submitter] versus [hash]: keying by submitter lets anyone re-prove against a newer game if the first game is invalidated. Keying by hash alone is cheaper but one bad proof bricks the withdrawal.
  • Marking finalized before the call is what stops reentrancy. The price is that a reverting target leaves the value in the portal with the withdrawal already spent, which is why the portal emits WithdrawalFinalized(hash, false) rather than reverting, so the user can retry the target call themselves.

Failure modes and detection.

  • Replay: AlreadyFinalized revert; alert on two WithdrawalFinalized events carrying the same hash.
  • Stale output: the game is re-checked at finalization, so a game that lost its challenge reverts ProposalNotFinalized.
  • Challenge not elapsed: ProofNotMature.
  • Failed call: WithdrawalFinalized(hash, false); the value stays in the portal.
  • Wrong chain or portal: the withdrawal hash binds no chain ID, so a proof is valid on any fork of the same chain. Monitor block.chainid and the portal address.
  • Indexer drift: L1 reorgs can drop WithdrawalFinalized; index on finalized L1 blocks only.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

Compare canonical and fast bridge routes.

Answer

The 60-second version

The comparison only bites in one direction. Going L1→L2 through the rollup's own bridge is minutes on both Arbitrum and Optimism, because the L1 state is already final. The interesting case is L2→L1: the canonical route waits for the rollup's proof or challenge window, and a fast bridge sells you the difference by having someone else front the money.

Assumptions I'd state: comparing a rollup's native bridge against a liquidity bridge (Across, Hop, Stargate) for a stablecoin-sized transfer, and caring about three things. Time to funds, time to final settlement, and who holds the risk in between.

Why canonical waits

You burn or lock on L2. The rollup posts a state root to L1, and the L1 contract releases funds only once that root is final. On Optimism that is the 7-day challenge period; on zkSync Era the proof is verified and then an execution delay of up to ~24 hours applies. The wait is not a policy choice: the L1 contract cannot pay out until it is sure the L2 state it is paying against cannot be reverted.

Why fast exits can skip it

A liquidity provider fronts the destination funds in 1–5 minutes and is repaid later, either when the canonical message finally lands or through an independent messaging layer. Nothing about the rollup got faster. The delay moved from the user to the LP, and the user pays for that with a fee and with exposure to the LP's credit.

CanonicalFast (liquidity bridge)
L1→L2minutesminutes
L2→L1 time to funds7 days (Optimism), ~24 h (zkSync Era)1–5 minutes
Time to final settlementsame as time to fundsstill the canonical window; the early credit is a claim
Who waitsthe userthe LP
FeeL1 + L2 gas, no spreadrelayer/LP fee, typically single-digit to low-tens of bps (Stargate's pool fee is 6 bps; Across and Hop are dynamic)
Trust addednone beyond the rollupLP solvency, relayer liveness, the bridge's verifier

Failure modes, with detection and cost

LP insolvency or paused repayment. The LP fronts the destination funds and is repaid only when the source message lands. If repayment is paused or the LP's capital is exhausted, new transfers stall and in-flight ones fall back to the canonical path. Detect by tracking outstanding unclaimed obligations against LP TVL and watching the bridge's paused state. Cost: the user waits the canonical window, up to 7 days. Principal is usually intact, but only because the LP, not the user, is the counterparty of record.

Forged message. Fast bridges that settle over an independent messaging layer add a verifier whose compromise mints unbacked funds on the destination. Detect by reconciling destination minted supply against source locked supply every block and alerting on divergence. Cost is unbounded: Wormhole's February 2022 exploit minted 120,000 wETH on Solana, about $326M at the time.

Relayer liveness. If the only relayer serving a route goes down or censors, the route silently degrades to the canonical path. Detect by tracking relayer count per route and fill-latency p99. Cost: the canonical delay, plus users who assumed minutes and built a workflow on it.

Speed mistaken for finality. The destination credit is a claim, not settlement. A source-chain reorg deeper than the bridge's confirmation threshold invalidates it after the user has already moved the funds. Detect with reorg-depth monitoring against the bridge's confirmation setting. Cost lands on the LP first, then on whoever received the funds.

When not to use fast

When the transfer is large enough that the LP's credit is the weakest link in the chain, or when the destination funds will be moved again immediately: the early credit is not final, and acting on it is the mistake. Split the transfer, or take the canonical route and plan around the window.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-12

Test rollup behavior across L1 reorgs.

Answer

Core answer. Assume an OP-Stack-style rollup: L2 blocks are a deterministic function of L1 history, and the node tracks three heads. Unsafe (sequencer-published, not yet on L1), safe (derived from L1), and finalized (derived from finalized L1). Testing reorg behavior means running a reorg-injection harness: rewind the L1 view the node sees, then assert that the L2 safe head, the derivation state, and every cross-domain message converge to exactly the state a node that never saw the orphaned blocks would reach. The pass condition is convergence, not "no crash."

Why shallow and deep reorgs differ. The derivation pipeline is a function of L1: origin block → batch transactions → L2 blocks. The safe head only advances when the L1 origin advances, so an L1 reorg invalidates every L2 block derived from the orphaned L1 blocks.

A shallow reorg (depth of a few blocks, well before finality) is routine. The node detects the origin hash mismatch, rewinds the safe head to the last L2 block derived from the common-ancestor L1 block, and re-derives from the new canonical chain. Batches that lived in orphaned L1 blocks are dropped; batches in the replacement blocks are picked up. If a replacement block carries no batch, the safe head stalls until a later L1 block carries it: still inside the sequencer window, the number of L1 blocks a batch may lag its L2 block.

A deep reorg past finality is not a normal event. Ethereum PoS finality is two epochs: 64 slots at 12 s, about 12.8 minutes, and reverting a finalized checkpoint requires at least one third of staked ETH to be slashed. The correct behavior is to halt and alert, not to silently re-derive, because the rollup's finality assumption is broken.

Worked trace (hypothetical). L1 blocks 100, 101, 102; batches in 101 and 102. Safe head: L1 100 → L2 500, L1 101 → L2 501, L1 102 → L2 502. L1 reorgs: 101 and 102 are replaced by 101′ and 102′. The node sees the origin hash mismatch at 101, rewinds the safe head to L2 500, then re-derives: 101′ carries a batch → L2 501′; 102′ carries none → the safe head stays at 501′ until a later L1 block carries the batch.

reorg depthL1 contextexpected node behaviorfirst production miss if wrong
1–2 blockspre-finalityrewind to common ancestor, re-deriveorphaned deposit credited
up to ~64 slotspre-finalitysame; safe head may stallduplicate message replay
past finalitypost-finalityhalt and alertbridge credit on a non-final deposit

Trade-offs in how you test. Deterministic unit injection into the derivation pipeline is fast and reproducible but never exercises the RPC or beacon layer. A fork-based devnet that actually reorgs geth or anvil is realistic but slower and flakier. Run both: unit tests for the pipeline invariants, devnet for the wiring. Shadow-forking mainnet catches real batch timing but is expensive; use it only for release candidates.

Failure modes and how they are detected.

  • Orphaned deposits: an L1 deposit in an orphaned block credited on L2. Reconcile L2 deposit credits against canonical L1 logs; any credit with no canonical L1 log is a leak.
  • Duplicate messages: the same deposit replayed after a reorg. Detect with message nonce/hash dedup at the bridge.
  • Stale indexer: the indexer did not rewind. Compare indexer head to node safe head; divergence is the signal.
  • Bridge credit before finality: an exchange credits a deposit before L1 finality. Assert credit fires only on finalized L1.
  • Missed rewind: the node keeps an orphaned safe head. Diff the safe-head hash against a reference node.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Design a confirmation model for an L2 wallet.

Answer

Assumptions I'd state first (20 s). OP Stack rollup on Ethereum L1: Base or OP Mainnet: 2 s L2 blocks, 12 s L1 slots, 32-slot epochs. The wallet shows balances, credits deposits, and gates a bridge release. The dollar thresholds below are policy examples, not protocol constants; the latencies are protocol-level.

The model. Four states, each with a derivation rule, a latency, and the failure it rules out:

tierderived fromlatencyrules out
unsafesequencer feed, optimism_syncStatus.unsafe_l2~2 s (one L2 block)nothing: the sequencer can reorg it
safebatch data present on L1, and that L1 block at least one epoch (6.4 min) oldminutesDA failure, 1–2 block L1 reorg
L1-finalizedthe batch's L1 block finalized (2 epochs, 64 slots, ~12.8 min)~12.8 min after batch inclusionL1 reorg
output-root finalizedL2 output root past the fault-proof challenge window (7 days on OP Mainnet and Base)7 daysan invalid state transition

Each step buys something specific. unsafe is one sequencer's promise: it can rewrite that block and no L1 data exists to check it against. safe means the batch is on L1, so anyone can re-derive the state, but the L1 block holding it can still be orphaned, which is why the wallet adds a one-epoch buffer before trusting it. L1-finalized removes that reorg risk. Only the challenge window removes the risk that the state transition itself is invalid, which is why withdrawals on OP Stack wait it out.

Policy. Map action to tier, not to a vibe:

actionminimum tierexample threshold
show balance, estimate gasunsafeany
credit an in-wallet swapunsafe≤ $500
credit a depositsafe$500–$50k
release a bridge withdrawaloutput-root finalizedany
anything above $50kL1-finalized—

The gate is a comparison against the sync status, not a timer:

TypeScript
// viem 2.x against an OP Stack node
const s = await client.request({ method: 'optimism_syncStatus' })
// s.unsafe_l2 / s.safe_l2 / s.finalized_l2: { number, hash, timestamp }
const tier = (n: bigint) =>
  n <= s.finalized_l2.number ? 'finalized'
  : n <= s.safe_l2.number   ? 'safe'
  : n <= s.unsafe_l2.number ? 'unsafe'
  : 'unknown'

Trade-offs. The deciding criterion is the cost of a reorg versus the value at risk and whether the action is reversible. A 2 s confirmation is correct for a UI balance and wrong for a withdrawal, because the withdrawal is irreversible once the counterparty's chain credits it. Alternatives: trust the sequencer outright (fastest, single point of failure); wait for L1 data (safe against DA failure, still reorgable); wait for L1 finality (12.8 min, safe against L1 reorg); wait out the proof (7 days, safe against invalid transitions). On a validity rollup (zkSync Era, Linea) the last two tiers collapse: once the proof verifies on L1, the state root is final modulo L1 reorg, so the 7-day wait disappears. Arbitrum sits between: ~250 ms soft confirmation, then L1 batch, then assertion confirmed after the challenge window.

Failure modes and detection.

  • False finality: the sequencer reorgs the unsafe chain after the wallet credited it. Detect by comparing the hash of L2 block N derived from L1 against the hash the sequencer served at N; divergence means history was rewritten. Freeze credits on mismatch.
  • Sequencer equivocation: two RPCs return different hashes at the same unsafe height. Poll at least two independent providers and compare unsafe_l2.hash at equal number.
  • L1 reorg: the batch's L1 block is orphaned and the safe head moves backwards. Assert monotonicity on safe_l2.number; the 6.4-min buffer absorbs one or two blocks, deeper reorgs page.
  • Delayed batches: unsafe_l2.number - safe_l2.number grows without bound. Alert on the gap; past the sequencer window, forced inclusion through L1 is the escape hatch.
  • Premature cross-chain release: the release path reads the unsafe head. Assert in tests that it reads output-root finalization, and rehearse with a reorg simulation in staging.

What would change the decision. Small, reversible amounts only: drop to unsafe with a per-user cap. Validity rollup: the 7-day tier becomes proof verification. An L1 with faster finality shrinks the 12.8-min tier proportionally.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Set confirmation thresholds for an exchange deposit.

Answer

Clarify first. Which chain, what's the largest single deposit, what's the daily volume, and what does a false credit cost versus a 20-minute delay? The threshold falls out of those, not out of habit.

Core answer. I set three tiers and bind them to the node's own block tags (latest/unsafe, safe, finalized) instead of a fixed confirmation count. Block times differ by 10x across chains, and on an L2 a sequencer can produce thousands of blocks that never reach L1, so "N confirmations" measures the wrong thing.

chainblock timeunsafesafefinalizedcredit at
Ethereum L112 slatest headjustified checkpoint, ~6.4 min (32 slots)2 epochs, 64 slots, ~12.8 minfinalized above the daily loss cap
Arbitrum One250 mssequencer headbatch posted to L1L1 block holding the batch finalized, ~12.8 min after postingfinalized, ~15–20 min
OP Mainnet / Base2 ssequencer headbatch posted to L1L1 finalized, ~12.8 min after postingfinalized
Polygon PoS2 sbor head—checkpoint on Ethereum (~30 min) + L1 finalityfinalized, ~45 min

Why the tiers differ. Ethereum's finality is a gadget, not a depth: two epochs (64 slots, 12.8 min), and a reorg past it needs more than a third of stake slashed. The old 12-block heuristic is obsolete post-Merge. On an L2 the binding constraint is the L1 posting cadence, not the L2 block time: Arbitrum's 250 ms blocks buy nothing if the batch is still sitting in the sequencer's inbox. So the number I actually tune is "time from deposit to the L1 block containing the batch being finalized," and I read it off the safe and finalized tags rather than computing it.

Value tiers. Below the cost of a support ticket (~$50), credit at unsafe: a reorg is cheaper than the ops load. Between that and the daily loss cap, credit at safe. Above it, finalized only. The deciding criterion is expected loss = P(reorg past tier) × value, weighed against the cost of the delay.

Failure modes and detection.

  • Sequencer equivocation: two providers return different unsafe heads. Poll at least two independent RPCs and alert on divergence.
  • Delayed posting: unsafe advances while safe stalls. Alert on unsafe_number − safe_number and on time since the last batch exceeding the chain's normal cadence.
  • L1 reorg: finalized regresses. Should be impossible; page immediately.
  • Mislabeled RPC fields: some providers alias safe to latest. Cross-check the safe tag against the batch inbox contract before trusting it.
  • Double credit: idempotency key on (chainId, txHash, logIndex), not on the deposit address.

When to go faster. If the asset is a stablecoin on a chain whose sequencer is a single operator you already trust, and the value sits under the ticket cost, unsafe is fine. If the sequencer is permissionless or the value is large, finalized is the only defensible bar.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Design around sequencer failure.

Answer

Assumptions first. I'll assume an optimistic rollup with a single centralized sequencer (Arbitrum One, OP Mainnet, Base), an app that wants sub-second UX but can tolerate a bounded inclusion delay, and a sequencer that is trusted for liveness and ordering but not for safety. If the app can't tolerate a multi-hour escape hatch, the answer changes: you need a shared or decentralized sequencer set, not a better escape hatch.

Core design. Treat the sequencer as a liveness and ordering service, never as a safety authority. Safety lives on L1: state roots are posted and, for optimistic rollups, challengeable for 7 days, so a malicious sequencer can reorder and censor but cannot finalize an invalid state transition. Everything else is about bounding how long a bad sequencer can hurt you.

Three mechanisms carry that:

  1. Forced inclusion (the escape hatch). On Arbitrum One, a transaction sent to the L1 Delayed Inbox is force-included after 24 hours if the sequencer hasn't included it. On the OP Stack the equivalent is the sequencer window: the derivation pipeline includes L1-submitted deposits once the window elapses, configurable per chain. This converts "sequencer censors me forever" into "sequencer can delay me by 24 hours."

  2. Independent read path. Don't read state only from the sequencer's RPC. Run a node that derives L2 state from L1 data (op-node, or Nitro in L1-derivation mode) and compare. If the sequencer feed and the L1-derived chain disagree, the L1-derived chain is the one that wins.

  3. Confirmation tiers, published. Users need to know what a receipt means:

    • sequencer receipt (~250 ms–2 s): ordering intent, reversible
    • batch posted to L1: data available, still challengeable
    • L1 finalized plus challenge period elapsed (7 days, optimistic): final

Trade-offs.

optionlatencycensorship resistancecost
single sequencer~250 ms–2 s24 h escape hatchlowest
shared sequencer set (Espresso, Astria)secondsno single censorextra hop, new trust
L1-based sequencing12 s L1 slotstrongesthighest latency/cost

Pick a single sequencer when UX latency dominates and a 24-hour worst case is acceptable. Pick a shared set when you can't accept one operator's outage or allowlist. Pick L1 sequencing when the app is settlement-grade and latency is secondary.

Failure modes and detection.

  • Stall: no new L2 block for more than N seconds; alert on the sequencer feed heartbeat.
  • Censorship: the L1 forced-inclusion queue grows while L2 inclusion doesn't; alert if a forced tx isn't included within the window.
  • Equivocation: two derivation nodes produce different batch hashes at the same height; compare across independent RPC providers.
  • Withheld data: a state root is posted without matching calldata or blobs; check DA against L1.
  • Correlated outage: several rollups on the same operator or cloud region; track operator and region as a dependency.
  • MEV and allowlists: ordering-policy failures, not safety failures. Detect by comparing your tx's inclusion position against the L1-derived ordering, and by checking whether the allowlist is enforced on-chain or only in the feed.

Worked timeline. Sequencer dies at t=0. Users notice within ~30 s (heartbeat). They submit to the L1 Delayed Inbox; the tx is force-included at t=24 h. Worst-case delay: 24 h plus one L1 block (~12 s). If your SLA is one hour, a single sequencer fails it by construction: that's the deciding number. Rehearse the forced-inclusion path in a game day, because it's the path you'll be using under stress.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Evaluate a rollup's censorship escape path.

Answer

Assume the sequencer is censoring, it won't include your transaction, but the L1 contracts, the bridge, and the proof system are honest. If the proof system is captured too, no escape path saves you; that's a different question. Under that assumption, evaluate the escape path on three axes: the trigger (what lets you bypass the sequencer), the delay (how long until inclusion is guaranteed), and the enforcement (what punishes a sequencer that ignores the forced transaction). A trigger without enforcement is a suggestion, not an escape.

Mechanism. Two designs dominate.

OP Stack (Optimism, Base). You call depositTransaction on the L1 OptimismPortal, which emits TransactionDeposited. The L2 derivation pipeline reads L1 and requires every deposit to be included within the sequencing window (3600 L2 blocks). The sequencer can order deposits but cannot drop them: omit one and the output root it proposes won't match what derivation computes from L1, so the output is challengeable in the fault-proof game and the proposer's bond is at risk. Enforcement is indirect: it runs through the fault proof, so it only bites after the challenge window and dispute game resolve.

Arbitrum. You post to the L1 Inbox (the delayed inbox). The sequencer gets a force-inclusion delay, 24 hours on Arbitrum One, to move it into the fast inbox. If it doesn't, anyone calls SequencerInbox.forceInclusion() and the L1 contract itself appends the message. Enforcement is direct: the L1 contract, not the sequencer, guarantees inclusion.

OP StackArbitrum
L1 entry pointOptimismPortal.depositTransactionInbox (delayed inbox)
Bypass triggerdeposit omitted from sequencing windowforce-inclusion delay elapses
Enforcementfault proof invalidates output rootL1 contract appends message
Guaranteeeventual, proof-mediateddirect, contract-mediated

Cost. Forced inclusion pays L1 calldata. A ~200-byte deposit is ~3,200 gas of calldata (16 gas per non-zero byte) plus execution: call it 100k gas all-in. At 20 gwei and $3,000 ETH that's ~$6 (hypothetical). EIP-4844 blobs cut batch-posting cost but not the calldata of a forced deposit, so the escape stays expensive next to a normal L2 transaction.

Alternatives. Escape queue vs. exit to L1 vs. alternate proposer:

  • Escape queue: keeps your L2 state and address, but you wait the full delay and pay L1 calldata.
  • Exit to L1: works even if the sequencer is fully down, but needs a finalized state root and drops L2 composability.
  • Alternate proposer / forced batch: only helps if the protocol lets a third party post batches; most don't.

Failure modes to check.

  • Disabled hatch: is the L1 entry point callable, or paused by an admin?
  • Prohibitive fees: does the forced path cost more than the value at risk?
  • Queue griefing: can an attacker fill the queue and push your transaction further back?
  • Delayed enforcement: does the bond actually get slashed, or is the challenge window longer than your deadline?
  • Unavailable state: can you exit if the sequencer never posts a state root?
  • Emergency-key override: can an admin cancel or reorder your forced transaction?
  • UI hiding: is the path reachable without the official frontend?

Decision trigger. Sequencer censoring, L1 contracts honest → use the forced-inclusion path. L1 contracts also compromised → exit to L1 immediately.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-25

Walk me through how a rollup sequencer makes money, and what its ordering discretion does to the users paying it.

Answer

Core (first 90 seconds). A sequencer is a business with three revenue lines and one cost centre. Revenue: the L2 execution fee it charges users, priority fees users pay to jump the queue, and ordering value. MEV it captures directly or sells to searchers. Cost: posting batch data to L1 (blobs or calldata) plus the fixed L1 gas of the submission transaction. Post-EIP-4844 the data line collapsed, so the spread is now mostly execution margin and ordering value. That is the point: the sequencer's profit is a function of its discretion over ordering, not of its cost base.

The arithmetic. Take a hypothetical batch of 6 blobs: 786,432 blob gas, since EIP-7691 in Pectra raised the target to 6 blobs and the max to 9. At a blob base fee of 10 gwei that is 786,432 × 10⁻⁸ ETH ≈ 0.0079 ETH ≈ $25 at $3,200/ETH. Compressed to roughly 25 bytes per transfer, 786 KB carries about 31,000 transfers, so data cost lands near $0.0008 per transfer. The L2 execution fee on the same transfer at an L2 base fee of 0.001 gwei is 21,000 × 0.001 gwei = 21 gwei ≈ $0.00007, and the sequencer's marginal cost to execute it is a rounding error on commodity hardware. The submission transaction itself burns a few hundred thousand L1 gas: the one cost the per-tx L1 data fee formula does not fully recover. So the sequencer is not arbitraging data cost; it is selling blockspace whose price it sets.

Ordering discretion. The sequencer is the only party that sees the plaintext mempool and picks the order, and it can reorder its own unfinalized L2 blocks. That is last-look. A sandwich is the canonical extraction: a user submits a swap with 1% slippage; the sequencer inserts a buy ahead of it, the user's fill moves the price, the sequencer sells behind it. The user pays slippage they already accepted; the sequencer's profit is the price impact, taken directly or auctioned to a searcher for a priority fee. The same discretion is censorship: drop a tx, or delay it past a liquidation window.

Levers.

leverwhat it changeswhat it does not
forced-inclusion queue (L1 inbox)bounds censorship: a user can land a tx via L1ordering and MEV unchanged; costs L1 gas plus a delay window
encrypted mempool / threshold encryptionhides contents until order is fixed; kills sandwichingadds latency and a decryptor trust assumption
L2 PBS / ordering auctionsequencer sells ordering rights openly instead of taking MEV privatelyextraction still happens; it is redistributed and made visible
shared sequencingatomic ordering across several rollupsone sequencer set now holds ordering power over several domains
sequencer auction / decentralized sequencingcompetition for the slot bids revenue to the rollupthe winner still has discretion; latency and liveness risk
based rollup (L1 proposers sequence)MEV accrues to L1, no L2 sequencer margininherits L1 12s slots and L1 liveness

Who pays whom. Users pay the sequencer in L2 fees and priority fees. The sequencer pays L1 for blob or calldata space and submission gas. Searchers pay the sequencer for ordering. If the sequencer is the foundation, revenue accrues off-chain; if it is a contract or an auction, it can flow to a treasury or token holders.

What a user or app does. Route through a private or protected RPC so the tx is not sandwichable, set slippage tight enough that extraction is unprofitable, use batch-auction routing where a solver competes, and keep the forced-inclusion path tested. On OP Stack, L1→L2 deposits are derivation-mandated and cannot be censored; on Arbitrum the delayed inbox lets anyone force inclusion after the sequencer's window. For an app the practical test is: can a user get a tx included within N blocks without the sequencer's cooperation, and what does it cost?

Failure modes. Sequencer reorg of unfinalized L2 blocks: detect by comparing block hashes across independent RPCs and alerting on depth. Censorship: detect with a canary tx that must land within a bound, plus a forced-inclusion probe. Sandwiching: detect by ordering analysis on your own txs, looking for adjacent txs paying high priority fees around yours. Divergence between the sequencer's incentives and the user's is not a bug to fix; it is a parameter to measure.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Build an honest L2 fee estimator.

Answer

Assumptions. OP Stack chain (Optimism, Base) after the Ecotone upgrade; the sequencer posts batch data to L1 as blobs. The transaction is an ordinary L2 transaction.

Core answer (say this first). An honest estimator has three parts: L2 execution gas, the L1 data fee, and a buffer for L1 price movement between estimation and inclusion. The L1 data fee dominates and is the part people get wrong. Don't reimplement it: call GasPriceOracle.getL1Fee(encodedTx) at 0x420000000000000000000000000000000000000F. It returns the exact fee for the current L1 state.

Mechanism. Post-Ecotone the L1 fee is a function of the fastLZ-compressed size of the RLP-encoded transaction, not its raw calldata gas. The oracle:

  1. Compresses the transaction with fastLZ: tx_compressed_size = max(flz_compress_len(tx), 100). The 100-byte floor stops tiny transactions from being undercharged.
  2. Reads l1_base_fee and blob_base_fee from L1Block (0x4200000000000000000000000000000000000015).
  3. Reads two scalars, base_fee_scalar and blob_fee_scalar, packed into one uint256.
  4. Computes approximately (tx_compressed_size * 16 * base_fee_scalar * l1_base_fee + tx_compressed_size * blob_fee_scalar * blob_base_fee) / 16e6.

The two scalars exist because the operator tunes how much L1 cost to pass through, and because blob and calldata posting have different cost curves. They are governance-set; read them at estimation time.

The pre-Ecotone Bedrock formula was different: tx_data_gas * l1_base_fee * scalar / 1e6 with tx_data_gas = 16 * nonzero_bytes + 4 * zero_bytes. If a blog post shows that, it's stale.

Code.

Python
from web3 import Web3

w3 = Web3(Web3.HTTPProvider("https://mainnet.optimism.io"))
oracle = w3.eth.contract(
    address="0x420000000000000000000000000000000000000F",
    abi=GAS_PRICE_ORACLE_ABI,
)

encoded_tx = bytes.fromhex(signed_tx_raw)          # RLP-encoded transaction
l1_fee = oracle.functions.getL1Fee(encoded_tx).call()

l2_gas = w3.eth.estimate_gas(tx)
l2_fee = l2_gas * w3.eth.gas_price

total = l2_fee + int(l1_fee * 1.2)                 # 20% buffer on L1

Worked example (hypothetical scalars). RLP-encoded tx = 200 bytes; fastLZ compresses to 120; floor 100 → tx_compressed_size = 120. l1_base_fee = 20 gwei = 20e9 wei, blob_base_fee = 1 wei, base_fee_scalar = 4,000,000, blob_fee_scalar = 1,000,000.

  • Base term: 120 * 16 * 4,000,000 * 20e9 / 16e6 = 9.6e12 wei
  • Blob term: 120 * 1,000,000 * 1 / 16e6 = 7.5 wei
  • L1 total ≈ 9.6e12 wei = 0.0000096 ETH
  • L2: 100,000 gas * 0.001 gwei = 1e11 wei = 0.0000001 ETH
  • Total ≈ 0.0000097 ETH; L1 is 99% of it. With the 20% buffer: 0.00001162 ETH.

Trade-offs.

  • Simulation vs analytic. getL1Fee is exact for current state but can't predict future L1 prices. Analytic models let you stress-test but miss chain-specific overheads. Use the contract for the number, analytic for sensitivity.
  • Blob vs calldata. Post-Ecotone the OP Stack posts blobs. If blob space is unavailable the sequencer falls back to calldata, which is more expensive. Estimate both and take the higher.
  • Compression. zk rollups compress before posting; the ratio is data-dependent. Use the sequencer's estimator (zks_estimateFee) or calibrate against recent batches.

Failure modes.

  • Stale base fees. L1 base fee changes every 12 s. Detect by comparing estimated vs actual in the receipt. Cost: underpayment or a failed transaction.
  • Calldata fallback. Detect by checking whether the batch used blobs. Cost: 2–10x higher L1 fee.
  • Compression mismatch. Detect by comparing estimated compressed size to actual batch size. Cost: 10–50% fee error.
  • Scalar upgrade. Detect by reading scalars at estimation time. Cost: systematic under- or over-estimation.
  • Unusual transaction bytes. A tx with many zero bytes compresses differently. Detect by computing the exact compressed size. Cost: 5–20% error.
  • Refund differences. On the OP Stack the L1 fee is charged upfront and not refunded. Detect in the receipt. Cost: overpayment if you overestimate.
  • Underfunded. Detect by checking balance before sending. Cost: failed transaction, wasted gas.

Refresh before signing: re-fetch L1 base fee, blob base fee, and scalars. If the estimate moved more than 10%, show the user the new number.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Port an Ethereum application to an EVM-like rollup.

Answer

What I'd say first

The EVM is the easy part: your bytecode runs. The port is an inventory of the environment assumptions your contracts and services encode, then a decision per assumption. State the assumptions up front: which rollup (OP Stack and Arbitrum Nitro differ on block.number), whether L1 stays the source of truth, and whether you need atomic L1↔L2 composability. Then the rule: any assumption touching money or liveness gets fixed before mainnet; everything else can ship with a monitor.

Three assumptions that actually break

Block number as a clock. On Arbitrum, block.number returns the L1 block number; on OP Stack it is the L2 block number, advancing every 2 seconds. A duration written in blocks is off by 6x on OP Stack. Trace: unlockAt = startBlock + 216_000 is 30 days on L1 (12s blocks) and 5 days on OP Stack. Use block.timestamp.

SOLIDITY
// solc 0.8.24
uint256 unlockAt = startBlock + 216_000;          // 30d on L1, 5d on OP Stack
require(block.timestamp >= startTime + 30 days);  // portable

Randomness. keccak256(abi.encodePacked(block.prevrandao, block.timestamp)) is not safe: prevrandao is not the beacon RANDAO on rollups, and the sequencer controls the timestamp within a window, so it can grind outcomes. Any mint or value assignment derived from block fields is a finding.

Address aliasing. When an L1 contract sends an L1→L2 message, OP Stack adds 0x1111000000000000000000000000000000001111 to the sender. An onlyOwner check on the L2 side sees the aliased address and reverts. Undo it with AddressAliasHelper.undoL1ToL2Alias before comparing.

Fees and finality

tx.gasprice on OP Stack is the L2 execution price; the L1 data-availability fee is charged on top and is not in it. A contract that refunds or prices from tx.gasprice undercharges. Read GasPriceOracle.getL1Fee (predeploy 0x420000000000000000000000000000000000000F). L2→L1 withdrawals sit through the challenge period, 7 days on OP Stack, so any "withdraw then act on L1" flow has a week of latency, not minutes.

Trade-off

Two credible ports. Minimal-change: keep contracts, fix only broken assumptions, keep L1 as source of truth, use the canonical bridge. Rollup-native: move sequencing and state to L2, use predeploys and the native bridge, accept the loss of L1 composability. Decide on one criterion: how much of your value depends on atomic L1↔L2 composability and L1 finality. If a lot, minimal-change; if you are latency-sensitive and self-contained, redesign.

Failure modes and detection

  • Aliased sender → onlyOwner reverts on the first L1→L2 governance call. Detect: fork test that routes the call through the real messenger.
  • Block-number duration → vesting unlocks 6x early. Detect: assert unlock math against the target chain's block time.
  • Stale reads → sequencer down, RPC returns last state. Detect: compare eth_blockNumber across two providers, alert on divergence.
  • Fee undercharge → L1 data fee unbudgeted. Detect: reconcile getL1Fee against actual receipts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-18

Secure a cross-domain admin message.

Answer

Cross-domain admin messages fail two ways: a forged message, or a genuine one executed twice or out of order. I secure it in three layers: authenticate the envelope, bind and de-duplicate the payload, then keep the handler narrow.

Authenticate the envelope. The handler accepts calls only from the trusted messenger contract on this chain (msg.sender == endpoint), and then checks the message really came from the expected source chain and the expected admin contract on that chain. Every messenger exposes both fields: LayerZero V2 gives origin.srcEid and origin.sender; CCIP gives sourceChainSelector and sender; Wormhole gives emitterChainId and emitterAddress. Checking only msg.sender is the classic bug: it proves a message arrived, not whose. A peer contract on a different chain that happens to share your admin's address passes a messenger-only check.

Bind and de-duplicate. Carry a monotonic nonce and reject anything that is not exactly lastNonce + 1. A re-delivered message then reverts instead of re-running.

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

contract AdminReceiver {
    address public immutable endpoint;   // trusted messenger on this chain
    uint32  public immutable srcEid;     // expected source chain
    bytes32 public immutable adminPeer;  // authorized admin contract on source
    uint64  public lastNonce;            // replay guard

    error Unauthorized();
    error StaleNonce();

    function lzReceive(
        Origin calldata origin,          // LayerZero V2 origin struct
        bytes32, bytes calldata message, address, bytes calldata
    ) external {
        if (msg.sender != endpoint) revert Unauthorized();
        if (origin.srcEid != srcEid || origin.sender != adminPeer) revert Unauthorized();

        (uint64 nonce, address newFeeRecipient) = abi.decode(message, (uint64, address));
        if (nonce != lastNonce + 1) revert StaleNonce();
        lastNonce = nonce;

        _setFeeRecipient(newFeeRecipient);   // one narrow action, no arbitrary call
    }
}

Trace a replay: the admin sends nonce 7. First delivery passes all three auth checks, 7 == 6 + 1, so lastNonce becomes 7 and the recipient is set. A relayer re-submits the identical bytes: auth passes, but 7 != 8, so it reverts StaleNonce and no state changes.

Keep the handler narrow. The message should select one pre-approved action (set a fee recipient, pause, upgrade to an already-registered implementation) never an arbitrary call/delegatecall with attacker-supplied target and calldata. That is what stops a compromised admin key from becoming a full takeover.

Choosing a messenger. The trust model is the real decision:

MessengerTrusted callerSource chainSource sender
LayerZero V2EndpointV2origin.srcEid (uint32)origin.sender (bytes32)
Chainlink CCIPRoutersourceChainSelector (uint64)sender (bytes)
WormholeCore bridgeemitterChainId (uint16)emitterAddress (bytes32)

Wormhole's security rests on a 13-of-19 guardian quorum; LayerZero lets you pick the DVN set, so you trade cost and latency for how many independent verifiers must collude. For admin traffic, prefer the stricter config even at higher gas.

Failure modes and detection. Messenger spoofing: a direct call to lzReceive reverts Unauthorized. Alert on that revert from any non-endpoint caller. Wrong chain or sender aliasing: caught by the srcEid/sender check. Replay: StaleNonce. Reentrancy or partial execution: if the handler makes an external call before writing lastNonce, a malicious recipient can re-enter. Write state first (checks-effects-interactions) or add a guard. Upgrade mismatch: source and destination encodings drift, so put a version byte in the payload and reject unknown versions. Ordered delivery (LayerZero's default) means one stuck message blocks every later one, head-of-line blocking, so monitor the path's nonce gap.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Set safety rules for cross-rollup messages.

Answer

Assumptions first. You're moving a message from rollup A to rollup B: a governance call, a mint, a liquidity release. There is no canonical L2↔L2 bridge on Ethereum today; the message routes A → L1 → B, so it inherits both rollups' L1 confirmation requirements. A third-party bridge (LayerZero, CCIP, Wormhole, Hyperlane) swaps that for a verifier set you have to trust. The rules below assume the canonical route.

Rule 1: every message carries a dependency record. Source chain ID, source block number and hash, the L1 block the source batch was derived from, and the confirmation tier the sender requires. A destination that can't resolve the record rejects the message. This is what makes invalidation possible later.

Rule 2: confirmation tiers, and irreversibility maps to them.

tierwhat it meanslatencysafe for
0source sequencer included the txsecondsUI, notifications
1source batch posted to L1, L1 block has ≥ 32 confirmations~6.4 minreversible state, quotes
2L1 finalized (2 epochs, 12.8 min)~12.8 minmost value transfer
3source rollup finality: 7-day challenge period on OP Mainnet / Arbitrum One, or batch proof verified on L1 for zkSync Era / Starknet / Scroll7 days / hoursmint, liquidity release, governance

Rule: anything irreversible requires tier 3 on the source. Tier 0 and 1 messages must be cancellable at the destination.

Rule 3: invalidation propagates by block hash, not by time. The destination stores the source block hash from the dependency record and re-checks it against the source chain at execution time. If the hash is no longer canonical, the message is dead: no partial execution, no "close enough."

Rule 4: execution is a second call. The destination holds the message pending until the tier is satisfied; a separate execute call consumes it. That's what stops a weak input from triggering an irreversible action.

Rule 5: publish the tier→latency table to callers. The app picks the tier; the bridge doesn't pick for it.

Trace. A message is sent on OP Mainnet at block N, tier 3 requested. The batch containing block N is posted to L1; the L1 block reaches finality at 12.8 min. The 7-day challenge period runs. On day 7 the destination on Arbitrum One reads the source block hash, matches it, and executes. Had OP Mainnet reorged block N at hour 3, the hash check fails and the message is dropped: the destination never saw a valid input.

When not to use this. Don't route a latency-sensitive UX through tier 3; don't route governance through a third-party bridge's default config just to get minutes. If the action is reversible, tier 1 is fine and 7 days is waste.

Failure modes and detection.

  • Cascading reorg: source reorg invalidates a batch that already fired downstream. Detect: a watcher re-checks stored source block hashes against the source RPC every block; alert on mismatch.
  • Replay: same message executed twice. Detect: consumed set keyed on (sourceChainId, sourceBlockHash, nonce); alert on duplicate nonce.
  • Stale dependency view: destination reads a cached head. Detect: compare cached head to source RPC head; alert if lag > 32 blocks.
  • Partial invalidation: some messages in a batch die, others live. Detect: invalidate at batch granularity and assert the per-batch message count matches.
  • Sequencer censorship: detect via forced inclusion. OP Stack's sequencing window is 3600 L1 blocks (~12 h), Arbitrum's force-inclusion delay is 24 h. If a message hasn't landed in that window, the sequencer is the problem.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design an asynchronous cross-rollup workflow.

Answer

Assumptions. Two EVM rollups, no shared sequencer, so nothing is atomic across them. We control contracts on both sides and can pick the transport. A user action on the source chain must produce an effect on the destination chain, and the destination may be slow, may fail, and may be retried. That last sentence is the whole design constraint.

Core answer. Treat the hop as a message with an ID, not a transaction. The source contract assigns msgId = keccak256(sourceChainId, nonce) when it locks or burns the asset, and writes its own state before emitting. The destination handler keys every effect on that ID and is idempotent: a second delivery of the same ID is a no-op. Every message carries a deadline. Past it, the destination marks the message failed and the source refunds after a timeout. Nothing assumes the two sides commit together.

StateWritten byLeaves on
INITIATEDsourcesource tx included
SENTsourcemessage emitted with msgId
DELIVEREDdestination routertransport delivers
EXECUTEDdestination handlereffect applied
FAILEDdestination handlercall reverted or deadline passed
REFUNDEDsourcesource timeout with no proof of EXECUTED

The refund rule is the real decision. Optimistic: the source refunds after a timeout unless someone submits proof of execution. Cheap, but a slow destination can be refunded while the effect also lands, so the destination must be able to reverse. Return-message: the destination sends a FAILED message back. Correct, but you pay for a second hop and the source must handle it.

SOLIDITY
// Solidity ^0.8.20
enum Status { None, Executed, Failed }
mapping(bytes32 => Status) public status;

function onMessage(bytes32 msgId, address to, uint256 amount, uint256 deadline)
    external onlyRouter
{
    if (status[msgId] != Status.None) return;   // duplicate delivery: no-op
    _execute(msgId, to, amount, deadline);
}

function retry(bytes32 msgId, address to, uint256 amount, uint256 deadline) external {
    require(status[msgId] == Status.Failed, "not retryable");
    _execute(msgId, to, amount, deadline);
}

function _execute(bytes32 msgId, address to, uint256 amount, uint256 deadline) private {
    if (block.timestamp > deadline) {
        status[msgId] = Status.Failed;
        emit Expired(msgId);
        return;
    }
    status[msgId] = Status.Executed;            // effects before interaction
    (bool ok, ) = to.call{value: amount}("");
    if (!ok) {
        status[msgId] = Status.Failed;
        emit Failed(msgId);
    }
}

Trace it. The router delivers X twice. First call: status is None, deadline holds, status flips to Executed, the transfer succeeds. Second call: status is Executed, so onMessage returns and no second transfer happens. If the recipient reverts, status flips to Failed and Failed(X) is emitted; retry can re-attempt, but only while block.timestamp <= deadline. After the deadline _execute sets Failed and emits Expired, and the source refunds. A reentrant to calling onMessage(X) sees Executed and returns; calling retry(X) fails the require.

Transport choice sets your latency floor.

TransportDestination latencyWhat you trust
Native rollup bridge, L2→L17-day challenge periodthe rollup's fraud proof
Acrossminutes; a relayer fronts capitalrelayer plus UMA optimistic-oracle dispute window (hours)
CCIPtens of minutes; waits for source finalityChainlink DON plus risk-management network
LxLy exit-root bridgeone batch-proof cyclethe zk proof

That table is why compensation beats atomicity. A relayer that fronts capital takes inventory risk; if the fee does not cover its cost of capital and destination gas, the message simply sits undelivered. That is the "delayed" case, and it is why the refund is timeout-based rather than waiting on a return message that may never come.

Failure modes and how you see them. Double execution: blocked by the msgId guard; if you ever see two Executed events for one ID, the guard is bypassed. Stuck partial state: DELIVERED with no EXECUTED after N blocks. Alert on age, not on error. Stale price or authorization: reject when block.timestamp - priceTimestamp > maxAge, and carry the deadline in the message. Destination gas exhaustion: the transport must let you set a destination gas limit (CCIP's gasLimit extraArg) and allow manual execution; detect via Failed events. Destination pause: queue, do not drop, and retry after unpause. Reorg: wait for source finality before delivering, since a reorged source tx invalidates the msgId. Unbounded retries: cap attempts, then mark Failed and refund.

When not to use this. If both legs live on one rollup, do it in one transaction. If the flow is L2→L1 and latency is tolerable, the native bridge's 7-day window buys you trustlessness you cannot match with a relayer.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

Compare centralized proving against decentralized prover marketplaces for a ZK-rollup in terms of latency, unit economics, hardware requirements, and failure modes.

Answer

What a strong candidate says first

The L1 verifier is identical in both designs: it checks one proof against the pre-state and post-state roots, and its cost is fixed. A Groth16 verifier is three pairings plus scalar multiplications, on the order of 250k gas on BN254, and STARK systems normally wrap the STARK in a SNARK to stay in that range. So the choice does not change rollup safety. A malicious prover cannot forge a state transition; it can only delay one. You are buying liveness and cost, not security.

Centralized proving wins on latency determinism and hardware specialization. A marketplace wins on capital efficiency, you do not pay for peak capacity, and pays for it in auction latency, redundant compute, and a risk premium for slashing. As of late 2025 the marketplace category includes Boundless, Succinct's Prover Network, Fermah and Gevulot; Starknet's SHARP is the canonical centralized-but-shared prover, aggregating many applications' proofs into one L1 submission.

Latency

Centralized critical path: witness generation → proving → recursive aggregation → L1 submission. Because one operator owns the whole pipeline, it can keep the witness in memory, keep provers warm, and pipeline batches. Illustrative budget for one batch: witness 10 s, proving 120 s, aggregation 20 s, L1 submit 15 s ≈ 165 s, and it is repeatable.

A marketplace adds three stages to that path: task publication, a bidding window, and witness transfer. Sealed-bid auctions need a window, 30–120 s is typical, and that is dead time on the critical path. Witness transfer is the one people underestimate: a batch execution trace runs to hundreds of megabytes, so at 80 Mbps it is ~20 s and at 1 Gbps ~2 s. Race-to-prove removes the bidding window (latency becomes the minimum over provers) but multiplies compute.

Unit economics

CentralizedMarketplace
Cost shapeFixed CapEx/OpEx sized for peak; off-peak idlePay-per-proof at market rate
Redundant workNone: scheduled onceRace: N−1 losers burn compute. Auction: none, but adds a window
Capital lockupNoneStake posted against timeout/griefing; carrying cost on that capital
Price floorMarginal cost + amortized hardwareAuction ≈ marginal + margin; race ≈ N × marginal

The race arithmetic is the part worth doing out loud. With N symmetric provers each spending C per attempt and one winner taking R, zero profit requires R/N = C, so R = N·C. At N = 5 and C = $0.40, the rollup pays $2.00 per proof and $1.60 of that is burned. A single-assignee auction prices near C plus a margin ($0.45) but adds the bidding window. Race buys latency with waste; auction buys efficiency with latency.

Centralized has the mirror-image problem: a cluster sized for peak running at 30% average utilization has an effective cost 3.3× its marginal cost.

Hardware

Centralized operators can specialize: FPGA or ASIC for MSM and NTT, NVLink-class interconnects, tuned memory hierarchies. Custom silicon only amortizes at scale, which is exactly why it appears on the centralized side.

A marketplace inverts the constraint: the circuit must run on hardware strangers already own, or the market collapses to the few operators who can afford the specialized rig. That is the centralization pressure inside a "decentralized" market. The standard mitigation is recursive composition: split the batch into chunks whose proofs fit a 24 GB GPU.

Failure modes

  1. Griefing and timeout stalling (marketplace). A prover wins the task and never submits. Proof finality halts and canonical bridge withdrawals stall. Mitigation: stake ≥ bounty + L1 submission gas penalty, a hard timeout, and automatic escalation to a racing pool or a fallback coordinator. Note that the fallback is itself an admission of centralization.
  2. Collusion or monopolization. If the circuit needs >512 GB RAM or custom silicon, one or two operators set the price. Mitigation: cap constraint counts, recursive composition, reserve pricing.
  3. Witness availability. If the witness lives only on the sequencer, the market is not decentralized: nobody else can build the proof. Mitigation: publish witness data as blobs with authenticated commitments so provers reconstruct state locally.
  4. Centralized single point of failure. One prover bug or outage halts finality for every batch at once; recovery is a restart, which is fast, but there is no fallback path.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-22

Assess rollup governance and upgrade risk.

Answer

Core answer

The question behind "assess governance and upgrade risk" is: what can the upgrade authority change, how fast, and can a user leave before it does? A rollup's L1 contracts (the bridge, the state-transition verifier, the output oracle) are almost always behind an upgradeable proxy. The "trust-minimized" claim is therefore conditional on who holds the proxy admin key. State three things up front: the upgrade authority (a multisig, a DAO vote, or an immutable contract), the delay between scheduling and execution, and the exit path's latency. If the delay is shorter than the exit latency, the delay buys nothing.

Mechanism

An upgradeable proxy keeps its storage in the proxy and delegates calls to an implementation address held at a fixed slot: EIP-1967 defines it as bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1). An upgrade is one transaction that writes a new address into that slot. There is no partial state: the next call runs entirely new code. If the new implementation changes the verifier or the bridge's accounting, every subsequent withdrawal is governed by the new rules. That is why the upgrade key, not the sequencer, is the real root of trust.

A timelock (OpenZeppelin TimelockController, minDelay) inserts a scheduling step: the upgrade is queued and only executable after the delay. A security council is a multisig whose threshold sets how many key compromises an attacker needs. Both are only as good as the exit path they protect.

The arithmetic that decides it

Exit latency on an optimistic rollup is the withdrawal challenge period: 7 days on Optimism, ~6.4 days (45,818 L1 blocks) on Arbitrum. Suppose the upgrade timelock is 3 days. A user watching the scheduled upgrade has 3 days before it executes, but their withdrawal cannot finalize for 7. The effective exit window is 3 − 7 = −4 days: negative. The timelock is decorative. For the delay to mean anything it must exceed the withdrawal period, which is why L2Beat's Stage 1 criteria pair a working proof system with a ≥7-day exit window.

Trade-offs

Fast upgrades (small council, no delay) let you patch a live exploit in minutes; slow ones (long timelock, large threshold) let users exit but leave you unable to react. The deciding criterion is whether the proof system can catch a bad state transition on its own. If fault proofs are live and permissionless, the council is a backstop and a long delay is cheap. If the council is the only thing between a bug and drained funds, a long delay is a liability. Risk is acceptable when the council's power is bounded: it can act only on a defined emergency set, and normal upgrades still go through the delay.

Failure modes and detection

  • Key compromise: the attacker reaches the threshold. Detect by monitoring signer addresses for anomalous signing, and by checking threshold size against signer independence: co-located signers on one hardware vendor collapse to a single compromise.
  • Malicious upgrade: the implementation slot changes to an unreviewed address. Detect by watching the EIP-1967 slot and diffing the new bytecode against the audited build.
  • Hidden proxy: a contract that looks immutable but delegates. Detect by reading the slot and scanning the bytecode for delegatecall.
  • Paused exits: the upgrade adds a pause on withdrawals, so the timelock window is unusable. Detect by running the exit path against the pending implementation on a fork.

Governance postures

postureupgrade authoritydelayexit windowverdict
Stage 0operator multisignonen/atrust the operator
Stage 1security council≥7 days≥7 daysacceptable with a bounded council
Stage 2proof systemn/an/acouncil is emergency-only

Curated: · Written: · Reviewed:

Difficulty: Hard