Skip to content
Tech Interview Prep
Technical interview guide

Oracles & Cross-Chain Interoperability

How smart contracts get real-world data they can't natively access, and how assets and messages move between otherwise-isolated chains.

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

Scope: Chainlink Data Feeds, Sequencer Uptime Feeds, VRF v2.5 and CCIP documentation; Uniswap v2 oracle design; IBC core and ICS-23 specifications; EIP-3668 reviewed 2026-09-07.

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 oracle boundary for an application.

Answer

The 90-second answer

The oracle boundary is the written contract between your contract and the outside world: the exact fact you accept, where it comes from, in what units, how fresh it must be, who may report it, and what your code does when the report is late, disputed, or missing. Inside the boundary is native chain state you can recompute; outside it is an assumption you are choosing to trust.

Assumptions I'd state before drawing it: which chain, which asset, and the maximum value at risk per block. Then one question per fact: what does it cost to verify this myself, and what is at risk if it is wrong? If verification is cheap (a token balance, a block hash), keep it inside. If it is expensive (the ETH/USD price on Binance at 12:00:00 UTC), you are buying a claim, and the boundary is the purchase order.

Mechanism: how a claim becomes chain state

Chainlink Data Feeds on Ethereum mainnet run off-chain reporting: a set of node operators each pull from a list of exchanges, the median is computed off-chain, and one transaction posts the aggregate. The consumer calls latestRoundData() and gets answer, updatedAt, answeredInRound. The trust assumption is "no single node can move the median", not "the price is true."

Pyth inverts the flow: publishers sign prices, Pythnet aggregates them, and the result reaches the chain as a Wormhole VAA that your transaction must pull and post. You pay gas per update, but the payload carries the publisher's confidence interval and publish_time.

Worked example

A lending market on Ethereum mainnet prices collateral with Chainlink ETH/USD. The feed's documented parameters are a 0.5% deviation threshold and a 1-hour heartbeat, so the boundary says: accept the answer only if block.timestamp - updatedAt <= 3600 + 300 (heartbeat plus a 5-minute buffer for the posting transaction) and answeredInRound >= roundId.

Trace at block timestamp 17,000,000:

  • updatedAt = 16,996,200 → age 3,800 s. 3,800 ≤ 3,900 → accept.
  • Next block, updatedAt unchanged, timestamp 17,000,400 → age 4,200 s > 3,900 → revert the borrow; repay and liquidation still allowed.

That last line is the boundary doing its job: the protocol would rather halt new debt than price collateral off a stale number.

Trade-offs

  • Push (Chainlink) vs pull (Pyth): push costs nothing per read but you inherit the heartbeat; pull gives fresher prices, but every consumer transaction pays to post the update, and a liquidator who forgets to post is liquidating against an old price.
  • Spot vs TWAP: a Uniswap V3 TWAP over a 30-minute window costs an attacker roughly the arbitrage loss of holding a manipulated price for the whole window; a spot read costs one block of capital. For a lending market, TWAP is usually the right default; for a perp funding rate, spot with a confidence check is.
  • Single source vs median: median costs latency and a larger trust set; a single source is defensible when the value at risk is below the cost of the second source.

Failure modes and detection

  • Stale data: updatedAt older than heartbeat plus buffer. Detect with a per-feed age metric; alert at 80% of heartbeat.
  • Ambiguous truth: two exchanges disagree by more than the deviation threshold. Detect by comparing the feed against a second source off-chain and paging on a gap above your tolerance.
  • Reporter collusion: the median moves without a matching move on any tracked exchange. Detect by monitoring the feed against an independent index.
  • Chain mismatch: the same feed address on a testnet or L2 returns a different answer. Detect by pinning feed addresses per chain ID in config and asserting block.chainid at deploy.
  • Availability treated as correctness: the feed returns a number, so the code proceeds. Detect by making the staleness and round checks revert, not warn.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

How does an oracle network aggregate independent node reports into a single on-chain answer, and how do you choose the aggregation function and outlier handling for a feed?

Answer

Start with where the aggregation runs, because that decides everything else. A Chainlink Data Feed does not put N transactions on-chain. Nodes run an off-chain consensus protocol: each signs an observation for the round, a leader collects them, the protocol computes the aggregate, and one report carrying a quorum of signatures is transmitted. The on-chain aggregator contract verifies the signature set and round metadata, then writes the answer. A 9-node feed therefore costs one transaction per round, not nine. Two triggers decide when a round writes: a deviation threshold (e.g. 0.5%) against the last answer, and a heartbeat (e.g. 1 hour) that forces an update even when the price is flat. Consumers read latestRoundData() and must check updatedAt and answeredInRound, not just answer.

Worked example, 9 nodes reporting ETH/USD, one compromised:

report set (sorted)2998.7, 2999.4, 2999.9, 3000.0, 3000.5, 3001.2, 3001.9, 3002.1, 4200.0
median3000.50
mean3133.74 (+4.4%)
trimmed mean, drop 1 each end3000.71 (+0.02%)

The mean would push a 4.4%-wrong answer on-chain and, being past the 0.5% deviation threshold, would do it immediately. The median ignores the magnitude of the bad report entirely. That is the whole argument for median on price feeds.

Choosing the function:

functionwhen it fitscost
medianadversarial node set, heavy-tailed errors; default for price feedsdiscards magnitude, needs odd n
meannodes are trusted and near-identical; you want sensitivity to small shiftsone bad node moves the answer
trimmed meanyou want some sensitivity but bounded outlier pullneeds a trim parameter and enough nodes
stake/reputation weightedoperator quality genuinely differsconcentrates power in large operators
mode / quorumlow-cardinality data: booleans, enums, rate bucketsuseless on continuous prices

Median's breakpoint is the number that matters: with n=9 it tolerates 4 corrupt reports, and 5 colluding nodes control the answer outright. Node count and operator independence buy more safety than any function choice.

Outlier handling. Median is implicit rejection; explicit policy adds a band. Reject observations deviating more than X% from the median or from the previous answer, and exclude nodes flagged repeatedly. OCR flags observations outside a configured band and drops persistently flagged nodes from later rounds. Scale the band to real volatility: a 1% band on a feed that legitimately moves 5% in a minute flags honest nodes and stalls the feed exactly when it matters. A robust alternative is MAD: median absolute deviation, threshold at k * 1.4826 * MAD, which adapts to the spread instead of assuming it. Add a circuit breaker: if the new aggregate deviates more than Y% from the last answer, require a second round before publishing.

Failure modes and detection. Feed freeze: deviation never crosses and the heartbeat is long, so updatedAt ages out. Monitor roundId advancement against the heartbeat. answeredInRound < roundId means a stale round was carried forward. Even n produces a median tie; use odd n. A too-tight outlier band lags the feed during real moves. On an L2, a down sequencer leaves the feed looking fresh with no new rounds: gate on the sequencer uptime feed. Consumer-side check, Solidity ^0.8:

solidity (uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) = feed.latestRoundData(); require(answer > 0, "bad answer"); require(updatedAt != 0 && block.timestamp - updatedAt <= MAX_AGE, "stale"); require(answeredInRound >= roundId, "stale round");

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-24

How do low-latency pull-based oracle architectures differ from push-based oracle networks for settlement in RWA and perpetual markets?

Answer

The 90-second answer

Push oracles move the price onchain on the oracle's schedule. Pull oracles move it on the trader's schedule. Everything else follows from that inversion: who pays gas, how fresh the price is, and who gets to choose which price is used.

Push (Chainlink Data Feeds, AggregatorV3Interface): the DON writes a round when the price deviates past a threshold or a heartbeat expires. Commonly 0.5% / 1 hour for ETH/USD on Ethereum mainnet. Each round costs a storage write plus signature verification, paid by the DON, whether or not anyone trades against it.

Pull (Pyth, Chainlink Data Streams): the DON signs a report offchain every few hundred milliseconds and publishes it to an API or websocket. The report reaches the chain only when a transaction carries it. The caller fetches the signed payload, submits it in the same transaction, and the settlement contract verifies the signatures and the validity window before using the price.

For perps the payoff is that the fill and liquidation price is bound to the executing block rather than the last round. For RWA the nuance is that the binding constraint is usually the NAV publication cadence (daily, T+1) not oracle latency. Pull oracles buy intraday collateral marks and liquidation pricing for leveraged positions; they do not make NAV faster.

Push (AggregatorV3)Pull (Pyth / Data Streams)
Trigger0.5% deviation or 1h heartbeatper transaction
Who paysDON, every roundcaller, per use
Freshnesslast round, up to a heartbeat oldreport timestamp, sub-second
Onchain costSSTORE per round: 20,000 gas cold, 2,900 warmverify only, no price write
Price selectionnone, one canonical roundcaller picks among valid reports
Dominant failurestale price in a fast movegateway outage, fee underfunding

What verification actually does

SOLIDITY
// Pyth EVM, Solidity 0.8.20
function settle(uint256 orderId, bytes[] calldata updateData) external payable {
    uint256 fee = pyth.getUpdateFee(updateData);        // 1 wei per update
    require(msg.value >= fee, "UNDERFUNDED");
    pyth.updatePriceFeeds{value: fee}(updateData);      // verifies Wormhole VAA, writes price

    PythStructs.Price memory p = pyth.getPriceNoOlderThan(priceId, 2); // reverts if age > 2s
    require(p.publishTime <= block.timestamp, "FUTURE_REPORT");

    uint256 scale = 10 ** uint256(18 + p.expo);         // expo = -8 -> 10**10
    _fill(orderId, int256(p.price) * int256(scale));
}

Trace, BTC at $64,231.00 with expo = -8, publishTime = block.timestamp - 1:

  1. getUpdateFee returns 1 wei for one update; msg.value must be at least that.
  2. updatePriceFeeds verifies the Wormhole VAA and writes the price into Pyth's own storage: a push-style write, but only when someone pays for it.
  3. getPriceNoOlderThan(priceId, 2) reverts if block.timestamp - publishTime > 2.
  4. scale = 10 ** (18 + (-8)) = 10**10; 6_423_100_000_000 * 10**10 = 6.4231e22, i.e. $64,231.00 in 18-decimal fixed point.

Failure modes

Report selection. At a 400 ms publish cadence, a 2 s validity window holds roughly five signed reports. The caller submits whichever is best for them. This is not front-running the oracle: it is choosing among prices the oracle already signed. Defend by committing to a report hash offchain, requiring monotonic publishTime per account, or tightening the window and bounding slippage.

Gateway outage. Pull puts an HTTP dependency in the liquidation path. Gateway down, no valid liquidation transaction, bad debt accrues. Run your own relay, fetch the VAA from a second source, and define a degraded mode: pause opens, raise margin requirements, or fall back to a push feed with wider bands.

Fee and gas. Verification is paid in the same transaction, so a miscomputed fee reverts the liquidation. On an L2 the fee is in the native token, which a liquidator holding only the collateral token cannot pay.

L2 sequencer and clock. publishTime is compared against the sequencer's block.timestamp. Chainlink's Sequencer Uptime Feed pattern: check the feed, then wait a grace period (30 minutes in Chainlink's example) after recovery: applies to pull exactly as it does to push.

Trust model is unchanged. Onchain verification proves the signature, not the price. Pull settles a bad price just as fast as a good one, and it relocates MEV rather than removing it: the race moves from the oracle update to the freshest report, and the counterparty becomes the perp or AMM.

When push is still right

Daily-NAV RWA, non-leveraged collateral, and anything where an offchain HTTP call in the liquidation path is a worse risk than a one-hour-old price. The hybrid worth knowing: Chainlink Automation plus Streams, where the check phase does the offchain lookup and the perform phase submits the report. Push-like UX with pull-like freshness.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-2

Configure a price-feed registry.

Answer

Assume an EVM chain, Chainlink-style aggregators behind proxies, and more than one feed per chain. A registry is a contract that maps a pair key to the feed's chain, proxy address, base asset, quote asset, decimals and heartbeat. The key is keccak256(chainId, base, quote) so the same pair on two chains cannot collide.

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

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

struct FeedConfig {
    address aggregator;   // proxy address, not implementation
    uint8 decimals;       // must equal aggregator.decimals()
    uint32 heartbeat;     // seconds; ETH/USD mainnet is 3600
    address base;         // e.g. WETH
    address quote;        // e.g. USD
}

contract PriceFeedRegistry {
    address public owner;
    mapping(bytes32 => FeedConfig) public feeds;

    function setFeed(bytes32 key, FeedConfig calldata cfg) external {
        require(msg.sender == owner, "not owner");
        require(cfg.aggregator.code.length > 0, "not a contract");
        require(AggregatorV3Interface(cfg.aggregator).decimals() == cfg.decimals, "decimals mismatch");
        feeds[key] = cfg;
    }

    function read(bytes32 key) external view returns (int256 price, uint8 decimals) {
        FeedConfig memory cfg = feeds[key];
        require(cfg.aggregator != address(0), "feed not set");
        (, int256 answer, , uint256 updatedAt, ) = AggregatorV3Interface(cfg.aggregator).latestRoundData();
        require(answer > 0, "invalid price");
        require(block.timestamp - updatedAt <= cfg.heartbeat, "stale");
        return (answer, cfg.decimals);
    }
}

Trace read for ETH/USD on Ethereum mainnet: latestRoundData returns answer = 3000_00000000 (8 decimals), updatedAt = block.timestamp - 120. The heartbeat is 3600, so 120 <= 3600 passes and the function returns (300000000000, 8). If the round had never started, updatedAt is 0, block.timestamp - 0 > 3600, and the call reverts with stale.

Configuration steps: pick the key, resolve the proxy address from the vendor's official feed list, read decimals() and the documented heartbeat, call setFeed, then verify on-chain that feeds[key].aggregator matches the vendor page and that decimals() still matches. On Arbitrum, also read the sequencer uptime feed before trusting a price; if the sequencer is down, updatedAt can be old even though the feed is healthy.

Hardcoding addresses in each consumer is simpler and cheaper per read, but every feed migration forces a redeploy of every consumer. An on-chain registry costs one extra SLOAD and one external call per read and centralises the migration risk in the owner key. Off-chain config with signed payloads suits frequent changes but adds a signer you must trust.

failuredetection
wrong chainkey includes chainId; deployment test asserts block.chainid
inverse pairstore base and quote; unit test compares answer to a known ETH/USD value
proxy upgrademonitor decimals() and roundId; alert if either changes without a registry update
stale registryread reverts on stale; off-chain monitor alerts when block.timestamp - updatedAt > heartbeat
synthetic asset mismatchstore base token address; test that feed tracks the expected asset, not a wrapped or synthetic variant
decimal errorsetFeed requires decimals() == cfg.decimals; off-chain check repeats it
counterfeit addressallowlist of vendor proxy addresses per chain, verified against the official feed list

A production review that only lists these names is not enough. Each row needs the check that catches it before a trade settles.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-3

Implement a defensive feed adapter.

Answer

What I'd say first. Assume the feed is a Chainlink-style aggregator proxy exposing latestRoundData() and decimals(), and that a wrong read moves funds, so the adapter reverts rather than returning a best-effort number. The adapter's whole job is to turn an untrusted external call into a value the caller can use without re-checking anything. That means: read through the proxy (never a cached aggregator address), reject zero rounds, reject stale updatedAt against the feed's published heartbeat, reject non-positive and out-of-band answers, then scale to 18 decimals with a multiply that cannot overflow.

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

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

contract DefensiveFeedAdapter {
    AggregatorV3Interface public immutable feed; // proxy address, not the aggregator
    uint256 public immutable heartbeat;          // feed's published heartbeat, seconds
    int256  public immutable minAnswer;          // sanity floor, per feed
    int256  public immutable maxAnswer;          // sanity ceiling, per feed
    uint8   private immutable feedDecimals;

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

    constructor(address feed_, uint256 heartbeat_, int256 minAnswer_, int256 maxAnswer_) {
        feed = AggregatorV3Interface(feed_);
        heartbeat = heartbeat_;
        minAnswer = minAnswer_;
        maxAnswer = maxAnswer_;
        feedDecimals = AggregatorV3Interface(feed_).decimals();
        require(feedDecimals <= 18, "decimals");
    }

    /// @return price 18-decimal fixed point
    function read() external view returns (uint256 price) {
        (uint80 roundId, int256 answer, , uint256 updatedAt, uint80 answeredInRound) =
            feed.latestRoundData();

        if (roundId == 0) revert ZeroRound();
        if (updatedAt == 0 || updatedAt > block.timestamp
            || block.timestamp - updatedAt > heartbeat) revert Stale(updatedAt, block.timestamp);
        if (answer <= 0) revert NonPositive(answer);
        if (answer < minAnswer || answer > maxAnswer) revert OutOfBounds(answer);
        if (answeredInRound < roundId) revert BadRound(roundId, answeredInRound);

        price = uint256(answer) * (10 ** uint256(18 - feedDecimals));
    }
}

Trace. ETH/USD on Ethereum mainnet: 8 decimals, published heartbeat 1 hour. block.timestamp = 1_700_000_000; the feed returns roundId = 11068046444225731000, answer = 243156789000 ($2431.56789), updatedAt = 1_699_999_700, answeredInRound = roundId. Round is non-zero; updatedAt < now and now - updatedAt = 300 ≤ 3600; answer > 0; with minAnswer = 1e8 and maxAnswer = 1e15 it is in band; answeredInRound == roundId. Price = 243156789000 * 1e10 = 2_431_567_890_000_000_000_000, i.e. 2431.56789e18. Now shift updatedAt to 1_699_996_000: now - updatedAt = 4000 > 3600, so it reverts Stale(1699996000, 1700000000).

Trade-offs. Reverting is right when a bad read moves funds: a lending market must not liquidate on a frozen price. A dashboard should instead return the last good value plus a stale flag, so the deciding criterion is whether the consumer acts on the number. answeredInRound is deprecated on OCR2 aggregators: it is set equal to roundId, so the check is vestigial but harmless. Keep it for older feeds. The heartbeat is not exposed on AggregatorV3Interface, so it is hardcoded per feed and must be re-checked when Chainlink changes it. A blanket answer > 0 is wrong for feeds whose reference price can go negative (WTI crude settled below zero in April 2020); the criterion is whether the underlying index has a floor at zero.

Failure modes and detection. A frozen feed trips Stale; alert on revert rate and separately on updatedAt age off-chain. On an L2, a sequencer outage freezes prices and Chainlink recommends a grace period (commonly 30 minutes) after recovery before trusting them: read the sequencer uptime feed's startedAt and gate on it. A minAnswer clamp shows as answer pinned exactly at minAnswer for many consecutive rounds; alert on that pattern. Proxy migration breaks any cached aggregator address: always read through the proxy and alert when its aggregator() changes. Over-tight bounds halt the protocol on a legitimate move: set them from historical extremes, not from the current price, and alert on OutOfBounds reverts.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-4

Choose a maximum feed age for lending.

Answer

Clarify first. Which feed, which chain, and what does the price gate? Max feed age is not one number for a lending market: it is per feed, and it is derived from that feed's own published heartbeat rather than picked freely. The threshold has to gate liquidations and borrows, not just the UI, because a stale price that only fails a display check still executes liquidations.

The answer. For Chainlink ETH/USD on Ethereum mainnet: 0.5% deviation threshold, 3,600 s heartbeat: I'd set max age to 5,400 s (90 minutes), 1.5× the heartbeat. For a pull oracle like Pyth, where I choose the age at read time, 60 s. For a 30-minute Uniswap V3 TWAP, 30 minutes plus one block of slack.

Why 1.5× the heartbeat. The heartbeat is the feed's contractual maximum silence under normal operation. Set max age equal to it and a single late round (gas spike, keeper miss, RPC hiccup) trips the staleness check and blocks liquidations. One missed round of headroom absorbs that without letting a price go arbitrarily old.

The heartbeat is the worst case, not the typical case. ETH/USD updates far more often than hourly because 0.5% moves happen constantly, so the effective age in a live market is minutes. The threshold only bites when the feed genuinely goes quiet, which is exactly when you want to stop trusting it.

feedpublished cadencemax age I'd set
Chainlink ETH/USD, Ethereum mainnet0.5% deviation, 3,600 s heartbeat5,400 s
Chainlink BTC/USD, Ethereum mainnet0.5% deviation, 3,600 s heartbeat5,400 s
stablecoin pair0.25% deviation, 86,400 s heartbeat129,600 s (36 h)
Pyth (pull, EVM)sub-second publish60 s at read time
Uniswap V3 TWAP30 min window30 min + 1 block

Failure modes and how each is detected.

False stale rejection. Threshold too tight, so StalePrice reverts block liquidations while bad debt accrues. Detect by counting reverts per feed by error selector and alerting on any in a 24 h window.

Halted feed accepted. The feed stops updating but the last price sits inside the threshold. A heartbeat check cannot catch this: a halted feed and a quiet market look identical. Detect by cross-checking a second source (a TWAP or a second oracle) and alerting on divergence beyond a set band.

L2 sequencer downtime. On Arbitrum and Optimism prices freeze while the sequencer is down, and the first price after recovery can be stale. Gate on the sequencer-uptime feed and hold liquidations for a grace period after recovery.

Governance change. Someone swaps the aggregator or changes its heartbeat and your hardcoded max age is now wrong. Detect with a config-diff alert on aggregator address and heartbeat.

One threshold reused across unlike feeds. 90 minutes is right for ETH/USD and wrong for a stablecoin pair on a 24 h heartbeat: it would reject healthy rounds. Keep the threshold per feed, derived from that feed's heartbeat.

When the threshold is wrong. The binding constraint is liquidation latency, not feed cadence. Max age bounds how stale the price is at the moment of execution, and a slow keeper executes on a price older than the one that triggered it. If your keeper acts in 5 minutes, 90 minutes is comfortable; if it takes 30, tighten the threshold or add a deviation-triggered fast path. If the engine cannot act inside the threshold, the threshold is too loose.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

Gate L2 risk actions on sequencer status.

Answer

Assume an L2 with a centralized sequencer (Arbitrum, Optimism, Base) and a Chainlink L2 Sequencer Uptime Feed deployed on that chain. The feed's latestRoundData() returns answer, where 0 means the sequencer is up and 1 means it is down, plus startedAt, the timestamp the current round began.

The gate: read the feed before any action that increases the caller's risk or moves value out of the system. If answer != 0, revert borrows, collateral withdrawals, leverage increases and liquidations. Never gate repayments or collateral top-ups: those reduce risk and are exactly what a borrower needs during an outage. Once the sequencer is back (answer == 0), require block.timestamp - startedAt > GRACE_PERIOD before re-enabling the gated actions. Chainlink's guidance is a 30-minute grace period.

Why: during an outage users cannot submit L2 transactions, so they cannot defend a position. L2 oracle prices can be stale or diverge from L1. Liquidating the moment the sequencer resumes lets a liquidator seize collateral at a price the borrower had no chance to react to. The grace period lets the price feeds refresh and gives borrowers a window to top up.

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

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

contract SequencerGate {
    AggregatorV3Interface public immutable uptimeFeed;
    uint256 public constant GRACE_PERIOD = 30 minutes;

    error SequencerDown();
    error GracePeriodNotOver();

    constructor(address feed) { uptimeFeed = AggregatorV3Interface(feed); }

    modifier onlyWhenSequencerUp() {
        (, int256 answer, uint256 startedAt, , ) = uptimeFeed.latestRoundData();
        if (answer != 0) revert SequencerDown();          // 0 = up, 1 = down
        if (block.timestamp - startedAt <= GRACE_PERIOD) revert GracePeriodNotOver();
        _;
    }
}

answer != 0 is deliberate: any non-zero value is treated as down, so an unexpected value fails closed.

Trace, GRACE_PERIOD = 1800s:

timeeventfeed stategated callresult
1000sequencer haltsanswer=1, startedAt=1000repayallowed
1500outageanswer=1liquidaterevert SequencerDown
2000sequencer resumesanswer=0, startedAt=2000——
2100100s after resumeanswer=0liquidaterevert GracePeriodNotOver
38001800s after resumeanswer=0liquidaterevert (boundary is exclusive)
38011801s after resumeanswer=0liquidateallowed

Alternatives and when to pick them. Pausing every action is simpler but denies repayments and top-ups, which can force the very liquidations the gate exists to prevent: reject it. Sourcing prices from L1 or a TWAP removes the uptime-feed dependency entirely and is worth it if you can afford the latency; it does not help if the L2 price is what your contracts read. Gating liquidations only leaves risk-increasing actions priced off a stale oracle. A longer grace period is safer for borrowers but lets bad debt accumulate on positions already underwater before the outage. The deciding criterion is simple: does the action reduce the caller's risk? Allow it; otherwise gate it.

Failure modes and how to catch them. Wrong feed address or chain mismatch returns plausible data for the wrong chain: assert the address against a per-chain allowlist at deploy and in a fork test; a mismatch usually shows as answer never changing or startedAt far in the past. A stale feed round means the status is unknown: check updatedAt/startedAt freshness and block risk-increasing actions if the round is older than your threshold. Grace-period math breaks on startedAt (round start, not recovery) and on <= vs <: cover the exact boundary in unit tests. A reverting or unset feed turns a naive require into a permanent DoS: monitor revert rate and keep repayments off the gated path. Exempting a keeper or admin from the gate lets them liquidate during an outage: audit every caller of the gated path for privileged bypass. And RPC availability is independent of sequencer health: never infer sequencer state from an RPC call succeeding, only from the feed.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-7

Specify oracle disagreement and outage states.

Answer

Assumptions I'd state first: an on-chain lending market on Ethereum mainnet; the primary price is a Chainlink aggregator (ETH/USD runs a 0.5% deviation threshold and a 3600 s heartbeat. Verify per feed, they differ); the secondary is an independent source, either a Pyth pull feed or a 30-minute Uniswap V3 TWAP; the protocol can pause borrows but must keep repay and withdraw open.

The states, decided by two booleans: is each source fresh, and do they agree:

StateDetection ruleAction
Healthyboth fresh; spread ≤ bandnormal operation
Disagreementboth fresh; spread > bandfreeze risk-increasing actions (borrow, new leverage); keep repay, withdraw, and interest accrual
Single-source outageone source stale: now - updatedAt > heartbeat + buffercontinue on the survivor only if it is the primary; if the survivor is the fallback, treat as Disagreement
Total outageboth staleemergency: pause borrows, allow repay and withdraw, no liquidations (you have no price to liquidate against)
Emergencyno valid price for longer than the recovery windowhold paused, require a reviewed governance action to exit

Mechanism. Freshness is a timestamp check, not a value check: block.timestamp - updatedAt > heartbeat + buffer. For Chainlink ETH/USD that is 3600 s + a 300 s buffer; for a Pyth pull feed, publishTime within 60 s. Agreement is a spread test: (max - min) / median. Set the band at roughly twice the primary's own deviation threshold: 2% for a volatile pair, 0.5% for a stable pair. The reason is concrete: the primary only pushes a new answer after a 0.5% move, so its on-chain value can legitimately sit ~0.5% off true spot; a band tighter than that fires on noise and you halt a healthy market.

Trade-offs. Tight band buys manipulation resistance and pays in liveness: you halt on ordinary volatility. Wide band buys uptime and pays in exposure: you accept a wrong price for longer. The fallback choice is the real decision. A 30-minute TWAP resists single-block manipulation but lags a genuine move: during a real 15% crash it still prints the old price for minutes, so borrowers drain against stale collateral. A second aggregator like Pyth is faster but correlated if it aggregates the same CEX venues as the primary. Fallback is the right call when the secondary has an independent data path and you only need it for read paths, repay and withdraw valuation, not for liquidations. It is the wrong call when the secondary is a thin spot pool, because that is exactly the asset an attacker can move when the primary is down.

Failure modes and how each is detected.

  • Manipulable spot fallback: attacker pushes a thin pool while the primary is stale. Detect by comparing the fallback against a TWAP and checking pool depth before trusting it.
  • Cascading pause: pausing blocks liquidations, so bad debt accrues silently. Detect with a bad-debt counter and a pause-duration metric.
  • Stale manual price: a multisig feed set once and forgotten. Detect with an updatedAt alert past 24 h.
  • Governance abuse: the feed address is swapped to an attacker-controlled source. Detect with a timelock plus a FeedChanged event monitor.
  • Liveness loss: every source stale at once, protocol frozen. Detect with an off-chain heartbeat monitor per feed.
  • Inconsistent decimals: Chainlink returns 8, some feeds 18. Detect by reading decimals() at integration and normalizing once.
  • Permanent emergency mode: never unpaused. Detect with a time-in-pause metric.

The decision point that matters: if the primary is stale and the fallback is independent, serve reads from the fallback and keep the market open; if the fallback is a spot pool or shares venues with the primary, stay in Disagreement and let governance recover the primary.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-5

Evaluate oracle decentralization.

Answer

Core answer. "Decentralized" for an oracle means the answer is hard to move, not that many nodes signed it. I'd separate three layers and ask about each: the source layer (where the price comes from), the reporter layer (who signs it), and the aggregation layer (how reports become one number). Most production oracles are genuinely decentralized at the reporter layer and centralized at the source layer: twenty independent node operators all reading the same exchange API is one source with twenty signatures. State your assumptions first: which chain and feed, push or pull delivery, and what the consumer does with the value. A lending protocol's collateral price and a dashboard display have completely different security bars.

Mechanism. Chainlink Data Feeds run a DON of node operators that report off-chain, aggregate via OCR into a single median, and post one transaction with a threshold signature. OCR2 requires n ≥ 3f+1, so a 7-node feed tolerates f = 2 Byzantine nodes. The feed updates on a deviation threshold or heartbeat: ETH/USD on Ethereum mainnet publishes at 0.5% deviation or a 1-hour heartbeat, whichever comes first. Feeds also carry minAnswer/maxAnswer bounds; a report outside them is rejected, which stops fat-finger values but can pin a feed at the bound during a real depeg. Pyth is pull-based: roughly 90 publishers (exchanges, market makers) publish to Pythnet, the aggregate is a median with a confidence interval, and the consumer posts the update in its own transaction and pays the fee. UMA's optimistic oracle is different again: one proposer asserts a value, a dispute escalates to a token-holder vote, and security is explicitly economic.

Why aggregation doesn't buy independence. A median removes outliers. It does not remove correlation. If every reporter's input is the same Binance spot price, the median is that price and the decentralization is cosmetic. Detection: pull the pre-aggregation submissions and compute pairwise correlation of deviations; check whether reporters share RPC providers, cloud regions, or exchange APIs. If 5 of 7 nodes run in AWS us-east-1, a regional outage is a correlated failure that node count hides.

Chainlink DONPythUMA optimistic
who reportsnode operatorspublishers (exchanges/MMs)single proposer
aggregationOCR median, threshold sigmedian + confidencedispute → token vote
update triggerdeviation/heartbeat (push)consumer pullson request
cost to corruptreputational; no large bondpublisher reputationbuy enough UMA to win the vote
main failureshared source, stale feedstale pull, fee unpaidwrong-but-undisputed proposal

Failure modes and detection.

  • Thin market. Mango Markets, Oct 2022: MNGO was pumped ~10x on thin order books, the oracle followed, and ~$114M was borrowed against inflated collateral. Detect by comparing the oracle price to a depth-weighted price across venues, and flagging when the oracle's own market is the only venue.
  • Shared source. All reporters read one API. Detect with a source-graph audit, not a node count.
  • Correlated software. Same client version, same RPC endpoint. Detect with a version and endpoint inventory across the DON.
  • Stale feed. An exchange halts and the heartbeat hasn't fired. Detect by monitoring updatedAt against the configured heartbeat.
  • minAnswer pinning. The feed sits at the floor while the real price is below it. Detect by alerting when answer == minAnswer.
  • Reporting lag. Push feeds are up to one heartbeat old. Detect by measuring the updatedAt distribution at consumption time.

Trade-offs. Push is right when many consumers read the same feed and you want bounded staleness without per-read fees; it's wrong when reads are rare and gas per update dominates. Pull is right when you need the freshest price and can pay in-transaction; it's wrong when the consumer can't pay the fee or can be front-run on the update. Optimistic oracles are right for low-frequency, high-value, human-judgeable values like insurance payouts; they're wrong for anything a liquidator needs in the same block.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-6

Design an AMM-derived oracle.

Answer

Clarify first. "AMM-derived oracle" is underspecified. I'd ask: what consumes it. A lending market's liquidation price, or a slow-moving NAV? What's the asset: a major with a Chainlink feed, or a long-tail token whose only price discovery is on-chain? Which chain? My answer assumes a lending market on an Ethereum-mainnet long-tail pair with no CEX listing, so the AMM is the only source, and liquidations need a price that can't be moved for less than the value at risk.

The design. Use Uniswap v3's built-in TWAP, not spot. Pick the deepest pool for the pair: for most pairs that's the 0.05% (500) fee tier, but check TVL share, don't assume. Window: 30 minutes (1800 s). Read it with observe:

SOLIDITY
// Uniswap v3 pool; @uniswap/v3-core 1.0.0, v3-periphery 1.4.4
uint32[] memory ago = new uint32[](2);
ago[0] = 1800; ago[1] = 0;
(int56[] memory cum, ) = pool.observe(ago);
int24 tick = int24((cum[1] - cum[0]) / 1800);   // truncates toward zero
uint160 sqrtP = TickMath.getSqrtRatioAtTick(tick);

Mechanism. The pool stores a running sum of tick × seconds: tickCumulative. Every swap writes an observation, at most one per block. observe returns the cumulative at two timestamps, interpolating between the last stored observation and now using the current tick. The difference divided by elapsed seconds is the time-weighted average tick. So a single-block spike contributes 12 s of distortion out of 1800: 0.7% of the window. To move the 30-minute average by 5%, an attacker must hold spot 5% off for most of 30 minutes.

What that costs. Rough model, labelled: cost ≈ deviation × pool depth × (window / block time) × arbitrage extraction per block. For a $50M pool, 5% deviation, 1800 s, 12 s blocks = 150 blocks, and arbitrageurs extracting 0.1% of depth per block: 0.05 × $50M × 150 × 0.001 ≈ $375k. Compare that to the protocol's exposure to the pair; if TVL at risk is $2M, the oracle is safe by ~5×. If it's $20M, it isn't: widen the window or use a different source.

Cardinality is the thing that bites. Default observationCardinality is 1: only the latest observation is stored, and observe([1800,0]) reverts with OLD. You must call increaseObservationCardinalityNext to at least window/blockTime + buffer: 150 + 50 = 200 on mainnet. On an L2 with 250 ms blocks that's 7,200 slots, and the gas to initialize them is real.

Failure modes and detection.

  • Cardinality too low → observe reverts OLD. Monitor oldest observation age vs window; alert when it drops below 1800 s.
  • Shallow liquidity → manipulation cost below value at risk. Recompute the cost model hourly; alert if the ratio falls under 3×.
  • Sustained multi-block attack → TWAP diverges from a second source. Compare against Chainlink or a second pool; alert on >2% divergence for >5 min.
  • Stale crash response → TWAP lags a real 40% drop by up to 30 min. Compare TWAP to spot; if spot is >15% below TWAP, pause liquidations rather than liquidate at a stale price.
  • Wrong orientation → token0/token1 ordering flips the price. Assert direction in a fork test with a known trade.
  • Fee-tier migration → liquidity moves to another tier. Track the chosen pool's share of pair TVL; alert below 60%.
  • Timestamp assumptions → L2 sequencer-controlled timestamps. Monitor block timestamp delta vs wall clock.

When not to use it. If the asset has a deep CEX market, Chainlink is cheaper and faster. A TWAP is deliberately laggy: never use it as a spot price for anything that must react within one block.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Integrate verifiable randomness into a game.

Answer

First I'd clarify the trust model: can a player profit by predicting or manipulating the outcome? If yes, I need randomness the operator can't bias. On Ethereum mainnet I'd use Chainlink VRF v2.5 with a subscription. Assumptions: one dice roll per player per round, six outcomes, reward granted off-chain.

The integration: the player calls rollDice(). I store s_rollers[requestId] = msg.sender before the request returns. I set requestConfirmations = 3 (mainnet minimum and default), callbackGasLimit = 200_000, numWords = 1. The oracle waits three blocks, then calls fulfillRandomWords. There I check a fulfilled mapping, derive the outcome, and emit DiceLanded. I don't grant the reward until the fulfillment tx is finalized: two epochs, about 12.8 minutes on mainnet, because a reorg can re-execute the callback. If I granted off-chain on the first log, a reorg would double-grant.

Modulo bias: naive randomWords[0] % 6 is biased because 2^256 mod 6 = 4, so four faces get one extra chance in 2^256. That's negligible for 256 bits, but the same pattern with a 32-bit source is exploitable. Rejection sampling: compute limit = type(uint256).max - (type(uint256).max % n); if word >= limit, reroll; else word % n. For n = 6, limit = 2^256 - 4. A word of 123456789 is below the limit, 123456789 % 6 = 3, so face 4.

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

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

contract Dice is VRFConsumerBaseV2Plus {
    uint256 public s_subscriptionId;
    bytes32 public s_keyHash;
    uint32 public s_callbackGasLimit = 200_000;
    uint16 public s_requestConfirmations = 3;
    uint32 public constant NUM_WORDS = 1;

    mapping(uint256 => address) public s_rollers;
    mapping(uint256 => uint256) public s_results;
    mapping(uint256 => bool) public s_fulfilled;

    event DiceRolled(uint256 indexed requestId, address indexed roller);
    event DiceLanded(uint256 indexed requestId, uint256 result);

    constructor(uint256 subscriptionId, address vrfCoordinator, bytes32 keyHash)
        VRFConsumerBaseV2Plus(vrfCoordinator)
    {
        s_subscriptionId = subscriptionId;
        s_keyHash = keyHash;
    }

    function rollDice() external returns (uint256 requestId) {
        requestId = s_vrfCoordinator.requestRandomWords(
            VRFV2PlusClient.RandomWordsRequest({
                keyHash: s_keyHash,
                subId: s_subscriptionId,
                requestConfirmations: s_requestConfirmations,
                callbackGasLimit: s_callbackGasLimit,
                numWords: NUM_WORDS,
                extraArgs: VRFV2PlusClient._argsToBytes(
                    VRFV2PlusClient.ExtraArgsV1({nativePayment: false})
                )
            })
        );
        s_rollers[requestId] = msg.sender;
        emit DiceRolled(requestId, msg.sender);
    }

    function fulfillRandomWords(uint256 requestId, uint256[] calldata randomWords) internal override {
        require(!s_fulfilled[requestId], "already fulfilled");
        s_fulfilled[requestId] = true;
        uint256 result = (randomWords[0] % 6) + 1;
        s_results[requestId] = result;
        emit DiceLanded(requestId, result);
    }

    function _unbiased(uint256 word, uint256 n) internal pure returns (uint256) {
        uint256 limit = type(uint256).max - (type(uint256).max % n);
        if (word >= limit) revert("reroll");
        return word % n;
    }
}

Failure modes and detection:

failuredetectioncost
Rerolling before fulfillmentmapping(address => uint256) activeRequest; reject if non-zeroextra LINK per request, state bloat
Stale request staterequire(s_rollers[requestId] == address(0)) before storingstuck game if overwritten
Callback gas failureno DiceLanded within 100 blocks; off-chain monitorplayer waits, needs timeout refund
Reorgwait 64 blocks (2 epochs) before granting reward12.8 min latency
Modulo biaschi-square test over 1M rollsunfair game
Duplicate fulfillments_fulfilled[requestId] guarddouble reward
Subscription exhaustiongetSubscription(subId) balance < 1 LINKgame halts
Privileged cancellationadmin cancel eventtrust assumption

Delayed fulfillment: if no DiceLanded in 100 blocks, allow the player to cancel and refund. Store requestBlock[requestId].

Trade-offs: commit-reveal is cheap but the last revealer can withhold to bias; mitigate with a timeout and penalty. Off-chain RNG is fast but the operator can bias; use only if the trust model allows. VRF costs a LINK premium plus gas and adds three blocks plus finality latency, but it's verifiable. Choose VRF when the payout exceeds the cost of manipulation; otherwise commit-reveal or a signed off-chain seed is enough.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-10

Define a canonical cross-chain message envelope.

Answer

Core answer. Assume an arbitrary-message bridge between EVM chains where the destination contract verifies the message before executing. A canonical envelope is a versioned, fixed-layout struct that binds the lane and the sender to the payload, so two distinct messages can never produce the same bytes and a receiver can reject replays without trusting the relayer.

The fields, in order:

fieldtypepurpose
versionuint8schema version; receiver rejects unknown layouts
srcEiduint32source domain
senderbytes32source application, left-padded
dstEiduint32destination domain
receiverbytes32target application
nonceuint64per-sender monotonic counter
payloadHashbytes32keccak256 of the payload
value / token dataamount, token addressonly for token transfers

messageId = keccak256(abi.encode(version, srcEid, sender, dstEid, receiver, nonce, payloadHash)).

Why it works. Domain separation: because srcEid and dstEid sit inside the digest, the same payload sent on lane A→B and lane A→C hashes differently, so a relayer cannot take a valid message from one lane and submit it on another. The nonce makes each message unique per sender, so a replay fails the receiver's high-water-mark check. The payloadHash commits to the payload without forcing the receiver to carry it inline.

Alternatives and when to pick them. IBC's packet carries sequence, source_port, source_channel, dest_port, dest_channel, timeout, data: no version field, because the channel handshake pins the encoding; pick it when both ends are IBC and you want the transport to own versioning. CCIP's Any2EVMMessage carries messageId, sourceChainSelector, sender, receiver, data, tokenAmounts, where the chain selector is a bridge-assigned domain, not EIP-155. LayerZero v2 uses a header (version, nonce, srcEid, sender, dstEid, receiver) plus payloadHash, with guid = keccak256(header, payloadHash).

Encoding choice matters: ABI encoding is not canonical for dynamic types. Two different byte strings can decode to the same value, so a hash over ABI-encoded dynamic data is ambiguous. Use fixed-width static fields (head-only) or SSZ, which Ethereum's consensus layer uses precisely because its layout is deterministic and Merkleizable.

Failure modes and detection.

  • Cross-chain replay: same message accepted on a second lane. Include both domains in the digest; test by submitting a lane-A message to lane B and asserting revert.
  • Nonce reset: sender redeployed, counter restarts at 0, old messages replay. Persist a (sender, nonce) high-water mark across upgrades.
  • Ambiguous chain ID: EIP-155 chain IDs are reused across testnets and forks. Use bridge-assigned domain IDs.
  • Encoding collision: dynamic types without length prefixes. Use static fields or SSZ.
  • Address-format mismatch: 20-byte EVM vs 32-byte Solana. Left-pad to 32 and assert length on decode.

Worked trace of the encoding. All seven fields are static, so ABI encoding is head-only, 32 bytes each, 224 bytes total (0xE0). With version=1, srcEid=30101, dstEid=30111 (illustrative domain IDs), nonce=7:

  • 0x00 version → 0x00…01
  • 0x20 srcEid → 0x00…7595 (30101 = 0x7595)
  • 0x40 sender
  • 0x60 dstEid → 0x00…759F (30111 = 0x759F)
  • 0x80 receiver
  • 0xA0 nonce → 0x00…07
  • 0xC0 payloadHash

messageId is keccak256 of those 224 bytes. Change srcEid to 30110 and every byte from offset 0x20 shifts, so the ID changes: that is the domain separation, checkable byte by byte.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Implement replay-safe message execution.

Answer

Clarify first. "Replay-safe" means the transport may hand you the same message twice and the application's effects still land once. I assume at-least-once delivery, each message carrying (domain, message_id) where message_id is unique within its domain, and effects that write to the same database as the dedup record. If an effect is external (sending mail, calling another service) the single-transaction trick below does not cover it and you need a transactional outbox instead.

Core answer. Put the dedup marker and the effects in one transaction. The marker is a row keyed by the full identity of the message, and it commits or rolls back with the work it guards.

SQL
-- Postgres 16
CREATE TABLE processed_messages (
  domain       smallint    NOT NULL,
  message_id   bytea       NOT NULL,
  processed_at timestamptz NOT NULL DEFAULT now(),
  PRIMARY KEY (domain, message_id)
);
Python
# Python 3.12, psycopg 3
def handle(msg, conn):
    with conn.transaction():                      # one transaction
        row = conn.execute(
            "INSERT INTO processed_messages (domain, message_id) "
            "VALUES (%s, %s) ON CONFLICT DO NOTHING RETURNING message_id",
            (msg.domain, msg.message_id)).fetchone()
        if row is None:
            return "duplicate"                    # already applied
        apply_effects(conn, msg)                  # same tx
    return "applied"

Trace it. Message (domain=1, id=0xab) is delivered twice.

  1. First delivery: INSERT finds no conflict, returns 0xab, so row is not None. apply_effects runs, the transaction commits. Returns "applied".
  2. Second delivery: INSERT hits the primary key, ON CONFLICT DO NOTHING suppresses the insert and returns no row, so fetchone() is None. Returns "duplicate" and apply_effects never runs.
  3. Crash between the INSERT and the commit: the transaction rolls back, so the marker and the effects both disappear. Redelivery re-applies cleanly. This is the property that makes it safe: the marker cannot outlive the work it guards.

Failure modes.

  • Mark-then-execute. If you commit the marker in its own transaction and then run effects, a crash in between loses the message permanently: the marker says done, the work never happened. Detect it by asserting marker count equals effect count for a given domain in reconciliation.
  • Keying on message_id alone. A legitimate message on domain 2 that reuses an id gets silently swallowed as a duplicate. The composite primary key is what prevents cross-domain replay from being either accepted or dropped.
  • Storage reset on upgrade. Dropping or truncating processed_messages reopens the replay window for every message still inside the retry horizon. Prune by processed_at older than the maximum retry window (e.g. 7 days) rather than truncating.
  • Ordering. Dedup gives you at-most-once effects, not ordering. If effects depend on sequence, add a per-domain sequence number and reject gaps.

Trade-offs.

ApproachGives youCost
Dedup table in the effects transactionExactly-once effects, no idempotence requiredTable grows; needs pruning; only covers same-DB effects
Idempotent effects (natural keys, upserts)No dedup tableEvery effect must be idempotent: hard for sends and mints
Outbox + consumer offset commitExactly-once across servicesExtra table, a relay process, and offset storage in the same DB

Pick the first when effects are local writes. Reach for the outbox the moment an effect leaves the database.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Choose channel ordering for an application.

Answer

What I'd say first

Assume IBC-style channels between two chains (ICS-004, ibc-go v8), where a relayer ferries packets and the receiving chain verifies them. The decision is whether to open the channel ORDERED or UNORDERED. Default to UNORDERED; open ORDERED only when the application's own state machine breaks if packets are applied out of order. ICS-20 token transfers use unordered channels; ICS-27 interchain accounts use ordered ones: that split is the whole decision in one line.

Why the two behave differently

An ordered channel keeps one counter, nextSequenceRecv. RecvPacket succeeds only if packet.sequence == nextSequenceRecv, then increments it, so packet N+1 cannot be applied before N: the chain rejects it. An unordered channel instead writes a per-packet receipt keyed by sequence; any packet applies in any order, and a duplicate is rejected because the receipt already exists.

The consequence that decides most designs: on an ordered channel, TimeoutPacket closes the channel. If packet N times out (its timeout height or timestamp passed before it was relayed), the channel transitions to CLOSED and every later packet on it fails until the channel is reopened through a fresh handshake. On an unordered channel, a timeout fails that one packet; the channel stays OPEN.

Trade-offs

ORDEREDUNORDERED
Ordering guaranteeStrict, enforced by nextSequenceRecvNone; app must add its own
One packet times outChannel CLOSED, all traffic stopsThat packet fails, channel lives
One relayer censors a packetHead-of-line block: later packets stallOther relayers carry later packets
App complexityLow: order is freeHigher: you need causal IDs and idempotency
Typical userICS-27 ICA, ordered state machinesICS-20 transfers, independent messages

Failure modes and how you see them

  • Head-of-line blocking on an ordered channel: a censoring or offline relayer withholds packet N, nextSequenceRecv never advances, later packets pile up. Detect by watching nextSequenceRecv lag the counterparty's send sequence, and by the age of unrelayed packet commitments.
  • Timeout-closed channel: after a timeout on an ordered channel the state is CLOSED and every subsequent RecvPacket errors. Detect via a channel-state query and a spike in failed relay attempts.
  • Replay on an unordered channel: correctness rests on the receipt store. Reimplement the app layer without idempotency keys and a re-relayed packet double-applies. Detect by comparing applied-effect counts against packet counts.
  • Assuming order on an unordered channel: the app reads packets as if sequenced and corrupts state. Detect with an invariant that rejects out-of-order application.

Trace: same timeout, two channels

Ordered channel, packets 1, 2, 3 sent; relayer delivers 1, then 2's timeout height passes before delivery:

  • RecvPacket(1) → nextSequenceRecv 1→2, OK.
  • TimeoutPacket(2) → channel state OPEN→CLOSED.
  • RecvPacket(3) → fails, channel closed. Traffic stops.

Unordered channel, same events:

  • RecvPacket(1) → receipt written for seq 1, OK.
  • TimeoutPacket(2) → packet 2 fails, channel stays OPEN.
  • RecvPacket(3) → receipt written for seq 3, OK. Traffic continues.

That is the decision: pay the ordered channel's liveness risk only when out-of-order application would corrupt state.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-21

Verify bridged-token accounting.

Answer

Core answer

First I pin the bridge model, because the reconciliation differs. Lock-and-mint: canonical tokens sit in escrow on the source, a representation is minted on the destination. Burn-and-mint (Circle CCTP for USDC): the issuer burns on source and mints natively on destination, so there is no escrow to reconcile. You reconcile burn events against the issuer's attestation. Liquidity-pool bridges hold inventory instead of minting. I'll assume lock-and-mint, the common case, and state the invariant.

For each lane ((source chain, destination chain, token address)) the invariant is:

escrow_balance(source) - accrued_fees >= minted_supply(destination) + in_flight

In-flight is value locked on source whose message has not executed on destination yet. Fees are protocol revenue sitting in escrow that no minted token backs, so they come off the escrow side.

The procedure: snapshot escrow balanceOf at block N; snapshot destination totalSupply at block M; enumerate pending messages from the message layer (LayerZero endpoint nonce, unredeemed Wormhole VAAs); subtract accrued fees; normalize decimals to a common unit; compare.

Worked check: WETH lane, Ethereum to Arbitrum, 18 decimals both sides. Hypothetical figures:

termvalue (WETH)
escrow balance on Ethereum12,480.5
accrued protocol fees in escrow30.5
in-flight (3 messages, not yet executed)150.0
minted supply on Arbitrum12,300.0

escrow - fees = 12,450.0; minted + in-flight = 12,450.0. Balanced. Now suppose minted reads 12,301.0: one WETH unbacked. That is a forged mint or a double release, and the invariant catches it at the next block.

Trade-offs. Lock-and-mint keeps the source token canonical and needs no issuer cooperation, but it locks capital and every mint is a liability you must reconcile. Burn-and-mint removes the escrow entirely, CCTP reconciles burn events against Circle's attestation, but you inherit the issuer's liveness and cannot bridge arbitrary tokens. Liquidity pools mint nothing, so accounting is inventory plus rebalancing cost, but the pool can be drained. Deciding criterion: does the token have an issuer that can mint natively on both chains? If yes, burn-and-mint; if not, lock-and-mint and own the escrow invariant.

Failure modes and detection.

  • Forged mint: minted > escrow - fees. Detect with a per-block invariant check; alert on any positive delta.
  • Double release: same message executed twice. Detect by counting executions per message ID / nonce; the replay guard should make the second a revert.
  • Fee-on-transfer deficit: source token takes a cut on transfer in, so escrow receives less than minted. A 1% FoT token: user sends 100, escrow gets 99, destination mints 100, so 1 is unbacked. Detect by measuring the balance delta, not the transfer argument.
  • Rebase: stETH-style balance changes with no bridge event, so escrow drifts. Use a non-rebasing wrapper (wstETH) or track shares.
  • Decimal truncation: 18-decimal source to 6-decimal destination truncates; 1 wei of 18 decimals rounds to 0 at 6. Dust accumulates. Detect by normalizing and bounding the residue.
  • Canonical-token confusion: USDC.e vs native USDC on Arbitrum. Reconciling the wrong contract. Pin the token address per lane and assert against the canonical registry.
  • Upgrade: proxy implementation change alters accounting or storage. Monitor the implementation address and re-run the invariant after every upgrade.
  • Stuck in-flight: message never executes, escrow locked. Alert on in-flight age past the message layer's finality window.

That is the verification: one invariant per lane, checked continuously, with the failure mode each term of it detects.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-13

Set bridge confirmation thresholds.

Answer

Assumptions I'd state up front: which chain is the source, what the verifier actually proves (full node, light client, or a quorum of relayers), the value at risk per message, and whether the destination action can be undone. The threshold is a function of those four, not a constant.

Core answer. I set tiers by value and reversibility, and I anchor each tier to the source chain's own finality model rather than a round number.

Source finality modelLow value, reversible (< ~$1k, notification)High value (mint, governance, > ~$100k)
Ethereum PoS1–2 slots (~12–24 s)finalized checkpoint, ~2 epochs ≈ 12.8 min
Bitcoin PoW1 conf (~10 min)6 conf (~60 min)
Tendermint/Cosmos1 block (~6 s)1 block: commit is final, no reorg
Solanaoptimistic confirmation (~a few s)finalized, ~32 slots ≈ 13 s
Optimistic rollupL2 soft confirmation (~s)L1 finality after the 7-day challenge window

Why depth maps to a count. On probabilistic-finality chains the reorg probability decays with depth, so the count is a risk budget: Bitcoin's 6 confirmations is ~60 min of accumulated work, and the cost to rewrite that grows with each block. On Ethereum PoS the model is different: finality is deterministic once two epochs are justified and finalized (~12.8 min), and reverting a finalized checkpoint requires ≥1/3 of stake to equivocate and be slashed. So below finality you tolerate shallow reorgs (1–2 slots happen), and above it you treat the claim as canonical. That is why the high-value tier waits for the checkpoint and the low-value tier does not.

Light client staleness changes the threshold. An Ethereum light client verifies against a sync committee that rotates every 256 epochs (~27.3 h). If your bridge trusts a light-client header, that header can be up to a full period behind the real head. So the rule is not just "wait for finality": it is "reject any update whose finalized slot is older than one sync committee period," otherwise you import a stale, superseded view.

Failure modes and how I'd detect each:

  • Deep reorg past the threshold: monitor source head vs. your last-imported block; alert when observed reorg depth exceeds the tier's count.
  • Validator attack / ≥1/3 equivocation: two conflicting finalized roots for the same epoch; detect via slashing events and duplicate-finality alarms.
  • Stale light client: compare the client's finalized slot to wall clock; reject if the gap exceeds the sync committee period.
  • Economic finality mismatch: you assumed deterministic finality on a probabilistic chain; detect by measuring the observed reorg-depth distribution against your assumption.
  • Premature mint: reconcile destination minted supply against source locked/burned value; a positive gap means you minted before the source claim was safe.
  • Inconsistent relayers: quorum members attest different roots; detect by diffing attestations across relayers before accepting.
  • Downstream irreversibility: once minted on the destination, it cannot be clawed back; detect via reconciliation lag between source lock and destination mint.

The trade-off is explicit: every extra confirmation is latency the user feels, so I buy assurance only where the loss from a bad import exceeds the wait.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-20

Operate redundant relaying.

Answer

Assumptions first. EVM source and destination chains; an attestation layer (light client, oracle committee, or DVN set) that the destination contract verifies; relayers that only transport an already-attested message. If the relayer also signs the attestation, adding relayers multiplies the trust instead of removing it: check that before anything else.

Core answer. Redundant relaying means two or more independent processes can carry the same attested message, so one relayer's downtime or censorship delays delivery rather than blocking it. Safety lives in the attestation the destination verifies; liveness lives in having at least one courier willing to pay destination gas. Keep those separate and redundancy is cheap. Conflate them and it is theatre.

Mechanism.

Message identity: key = keccak256(abi.encode(srcChainId, srcEmitter, nonce, keccak256(payload))). The destination keeps mapping(bytes32 => bool) processed plus a per-emitter lastNonce. Delivery reverts AlreadyProcessed if the key is set, and BadNonce if nonce != lastNonce + 1 (strict ordering) or nonce <= lastNonce (unordered). That one check is what makes N relayers safe to run: the second one to land pays gas and reverts.

Fees: quote = destGasLimit × destGasPrice × nativeUsd + margin, with the excess refunded on delivery. A quote taken at 20 gwei stalls when the destination spikes to 300 gwei, a 15× move, so either buffer the quote 2–3× or expose a top-up call the sender can hit.

Lag: define it as the age of the oldest attested-but-undelivered message, not "relayer is up". Baseline p95 delivery latency (say 90 s on a 12 s-slot chain), alert at 3× p95, page at 10×. Add a canary: a test emitter sends a heartbeat every 60 s; if it is not delivered within 5 minutes, page. That catches a silently dead relayer before a real message is stuck behind it.

Worked trace: duplicate delivery. Two relayers see the source event for nonce 42 at block 19,000,000 and both call deliver(1, 0xBridge, 42, payload).

  • R1 lands first at 30 gwei, sets processed[key] = true, emits MessageDelivered, consumes ~120,000 gas.
  • R2's transaction reverts with AlreadyProcessed after ~45,000 gas.
  • At 30 gwei and ETH at $3,000: 45,000 × 30e-9 × 3,000 ≈ $4.05 burned per duplicate.

Duplicates cost gas, not correctness. If reverts exceed ~5% of delivery attempts, the delivery bounty is too high relative to the pre-check cost: add a cheap eth_call simulation before broadcast.

Failure modes and detection.

failurehow it shows updetection
censored messageone relayer drops it, others never see itcanary heartbeat misses the 5-minute deadline
correlated infraall relayers share one RPC provider or cloud regioncount distinct providers/regions per relayer; alert if < 2
gas griefingdestination handler burns the full gas limit and revertssimulate with the exact gas limit before broadcast; cap the limit; no refund on revert
stale attestationproof signed at block N, delivered at N+1000 after state moveddeadline field on the message; revert Expired
fee spikemessage sits undelivered while dest gas exceeds the quotetrack quote vs. current dest gas; alert at 2×

Trade-offs.

topologysurvives one relayer downsafety comes fromcost
single relayernodestination verification (if any)lowest
permissionless deliveryyesdestination verificationgas races, duplicate txs
k-of-n signing committeek−1fewer than k honestn× infra plus coordination

Pick permissionless delivery when the attestation is verified on the destination: it is the only topology where liveness does not depend on a named operator. Pick a signing committee only when the destination cannot verify a proof cheaply (no light client for that chain, say); then you are buying safety with a threshold, and you should say so out loud rather than calling it redundancy.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-19

Design packet recovery behavior.

Answer

Assume IBC-style channels (ICS-004) with permissionless relayers, source escrow, destination mint/release, and either ORDERED or UNORDERED channels. A packet carries a sequence, a timeout height (revision number + height) and a timeout timestamp (nanoseconds since Unix epoch). The source stores a packet commitment; the destination stores a receipt and an acknowledgement commitment.

The design is a single-use commitment on the source. Three terminal outcomes exist: ack success, ack error, timeout. Each deletes the commitment exactly once and resolves escrow. Ack success: a relayer submits MsgAcknowledgement; the source verifies the ack commitment against the stored packet commitment and channel, deletes the commitment, and releases escrow to the receiver. Ack error: same deletion, but refunds the sender. Timeout: a relayer submits MsgTimeout with proof that the destination has no receipt at the timeout height or timestamp; the source verifies the timeout has passed and no receipt exists, deletes the commitment, and refunds the sender. The commitment deletion is the atomic compare-and-delete. If ack and timeout race, the first transaction that deletes wins; the second fails because the commitment is absent. That is the exclusivity.

choicebehaviorwhen to usecost
ORDERED channeltimeout closes the channel; all later packets failstrict sequence, e.g. an ordered streamrecovery requires channel reopen or upgrade; head-of-line blocking
UNORDERED channeltimeout affects only that packet; later packets proceedindependent transfersapp must handle out-of-order and per-packet recovery
app-level retry with a new packetnew sequence, new escrowafter timeout, if the user still wants the transferdouble escrow if the old packet later succeeds; must wait for timeout

Deciding criteria: if the application cannot tolerate reordering, use ORDERED and accept channel closure. Otherwise use UNORDERED. ICS-20 transfer uses unordered channels.

Failure modes and detection:

  • Ack-timeout race: resolved by commitment deletion. Detect by an indexer comparing packet commitment age against timeout plus a grace period.
  • Wrong height or timestamp domain: timeout height revision must match the destination chain revision; timestamp is nanoseconds. Using a block height where a timestamp is expected can make the timeout never fire or fire immediately. Detect by validating packet fields on send.
  • Duplicate refund: if commitment deletion is not atomic or a retry runs after deletion, escrow can be released twice. Detect by comparing escrow balance against outstanding commitments.
  • Stuck escrow: no relayer submits timeout. Detect by packet commitments older than timeout plus grace; run a permissionless timeout relayer.
  • Forged proof: the light client verifies membership or non-membership; if the client is expired, the proof fails. Detect by client-expiry alerts.
  • Application error encoded as success: ack success but the app failed. Define ack error semantics and test them.

For a 5 s block time, a 10-minute timestamp timeout is 120 blocks. If the light client trusting period is 14 days, that is far inside it. A timeout height of destination revision + 100 blocks is about 8 minutes at 5 s blocks. These are examples; the app must pick based on block time and client trusting period.

Trace the race: t=0 source commits packet P, escrows 100 ATOM. t=9m destination writes receipt and ack. Relayer R1 submits ack; relayer R2 submits timeout at t=10m. If R1 lands first, the commitment is deleted, 100 ATOM is released to the receiver, and R2 fails. If R2 lands first, the commitment is deleted, 100 ATOM is refunded to the sender, and R1 fails. The destination receipt remains; the destination must reject any recv after timeout, so it should not have minted if the timeout was valid. The invariant: source commitment deletion is single-use; destination receipt is idempotent.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-17

How do cross-chain token transfer protocols use rate limits and independent risk management networks to prevent bridge drain exploits?

Answer

To prevent bridge drain exploits from smart contract vulnerabilities or compromised primary signer keys, institutional cross-chain transfer protocols (such as Chainlink CCIP) decouple message execution from message validation using dual independent networks combined with configurable on-chain throughput caps.

1. Dual-Layer Verification: Committing vs. Risk Management Network (RMN)

Rather than relying on a single relayer or multisig committee to authorize minting or unlocking tokens, the execution pipeline separates responsibilities:

  1. Committing Network (Primary DON): Listens to source chain CCIPSendRequested events, waits for source finality, builds a Merkle root over a batch of cross-chain messages, and writes this Merkle root to the destination chain CommitStore.
  2. Risk Management Network (RMN): An entirely independent node network running separate client software (written in a different language, e.g., Rust/Go, with separate node operators and infrastructure). The RMN independently monitors source chain finality and recalculates the expected Merkle root. It then submits an on-chain blessing (bless(bytes32 root)) or an automated curse/pause (curse()) to the destination RMNContract.
  3. Execution Network: Only after the Merkle root is committed and blessed by the RMN can an execution DON submit transactions to the destination ExecutionPool with valid Merkle proofs.
Source Chain          Dest CommitStore           Dest RMNContract         Dest ExecutionRouter
  [Bridge Msg] ---> [Primary DON Commits Root]
                           |                            |
                    [RMN Monitors Source] -> [RMN Node Blesses Root]
                                                        |                      |
                                             [Verify Blessed & Root] -> [Execute Transfer]

2. Rate Limiting Mechanism

Even if both the primary committee and the RMN were compromised, on-chain token pools apply token-specific, sliding-window rate limits (typically using a leaky-bucket or linear refill model) to bound worst-case drain rate per unit time.

SOLIDITY
struct RateLimit {
    uint128 capacity;     // Maximum burst limit (e.g., 5,000,000 USDC)
    uint128 tokens;       // Current available transfer quota
    uint32  rate;         // Refill rate in tokens per second
    uint32  lastUpdated;  // Timestamp of last update
}

function _consumeRateLimit(RateLimit storage rl, uint256 amount) internal {
    uint256 timePassed = block.timestamp - rl.lastUpdated;
    rl.tokens = uint128(Math.min(rl.capacity, rl.tokens + timePassed * rl.rate));
    rl.lastUpdated = uint32(block.timestamp);

    require(rl.tokens >= amount, "RateLimitExceeded");
    rl.tokens -= uint128(amount);
}

Comparison of Defensive Controls

Control LayerPrimary Threat MitigatedFailure Detection / TriggerWorst-Case ImpactLatency Impact
RMN BlessingsPrimary DON key compromise or consensus bugRMN halts blessing if source state doesn't match root hashTransfers stall until manual inspection or resolution+10 to +30 sec (RMN attestation window)
RMN CursingDestination exploit or anomalous transaction flowOn-chain curse() triggered by RMN anomaly monitorLane suspended; prevents execution of inflight commitsImmediate halt
Token Rate LimitsTotal pool drain via 0-day contract bugTransaction reverts on destination when quota depletedBridge loss bounded to capacity + (rate * T_pause)0 latency during normal flow; rejects burst volume

Concrete Failure Modes & Operational Detection

  • RMN Liveness Failure: If the RMN encounters network partition or gas exhaustion, execution halts because unblessed roots cannot be executed. Detected via alerting on block.timestamp - lastBlessTimestamp > threshold on the destination.
  • Rate Limit Saturation Under High Volume: A market shock causes genuine volume to deplete the pool's tokens balance, causing valid bridge transactions to revert. Detected by alerting on rl.tokens / rl.capacity < 0.10.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-22

Implement secure CCIP Read resolution.

Answer

Core answer

CCIP Read (EIP-3668) lets a contract answer a query it cannot compute onchain: it reverts with OffchainLookup, the client fetches the answer from a gateway, and calls a callback on the same contract with the response. The gateway is untrusted for integrity: it only provides availability. Everything that makes the answer trustworthy lives in the callback: an authenticated response bound to the exact request, the exact contract, and a deadline.

Assumptions: the data has a signer or a proof you can verify onchain; one extra round trip is acceptable; the client implements EIP-3668.

The flow

  1. Client calls resolve(name, data).
  2. Contract reverts OffchainLookup(address(this), urls, callData, this.resolveWithProof.selector, extraData): selector 0x556f1830.
  3. Client decodes the revert, substitutes {sender} and {data} into each URL, and issues the request.
  4. Gateway returns {"data": "0x..."}.
  5. Client calls resolveWithProof(response, extraData) on the contract that reverted.
  6. Contract verifies and returns.

Code (Solidity ^0.8.20, OpenZeppelin ECDSA)

SOLIDITY
error OffchainLookup(address sender, string[] urls, bytes callData, bytes4 callbackFunction, bytes extraData);

function resolve(bytes calldata name, bytes calldata data) external view returns (bytes memory) {
    revert OffchainLookup(
        address(this),
        _urls,
        abi.encodeWithSelector(this.resolveWithProof.selector, name, data),
        this.resolveWithProof.selector,
        abi.encode(name, data)
    );
}

function resolveWithProof(bytes calldata response, bytes calldata extraData)
    external view returns (bytes memory)
{
    (bytes memory name, bytes memory data) = abi.decode(extraData, (bytes, bytes));
    (bytes memory result, uint64 expires, bytes memory sig) =
        abi.decode(response, (bytes, uint64, bytes));
    require(expires >= block.timestamp, "stale");
    bytes32 digest = keccak256(abi.encode(
        name, data, expires, address(this), block.chainid
    ));
    require(ECDSA.recover(digest, sig) == signer, "bad sig");
    return result;
}

The digest is the whole security argument. name and data bind the answer to the request, so a gateway cannot answer a different query. address(this) binds it to this contract, so a signature harvested from another resolver is useless. block.chainid kills cross-chain replay. expires bounds staleness.

Trade-offs

  • Onchain storage vs offchain: storing the record onchain costs gas on every write; CCIP Read moves that to a signed blob. Use it when writes are frequent and reads can tolerate a round trip.
  • Signature vs Merkle proof vs zk: a single signer is cheap but is a trust anchor; a Merkle root anchored onchain removes the signer but needs the tree published; zk removes both but costs proving time.
  • When not to use it: if the answer must be trustless with no signer and no onchain anchor, CCIP Read does not help. It just relocates the trust. If the caller cannot make a second call (a purely onchain consumer), it is the wrong tool.

Failure modes

  • Malicious gateway returns a different record → signature check fails; the client should try the next URL.
  • Stale signed response → expires check.
  • Callback confusion: the client must call the callback on the contract that reverted, and the contract must not expose a callback that trusts msg.sender.
  • DoS: one gateway down → the client iterates urls; run at least two independent operators.
  • URL injection: never build the URL from user input; only {sender}/{data} substitution.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-11

Secure a cross-chain admin handler.

Answer

The 90-second answer. A cross-chain admin handler has one job: turn a message from a foreign chain into a privileged local call, and refuse everything else. Four things get pinned before anything executes: the local endpoint address (msg.sender), the source chain, the source contract, and the message identity. Then the identity is marked consumed before the first external call, and the handler's authority is capped so a bridge compromise is survivable.

Assume the handler sits behind a proxy, is reachable only through the endpoint, and that the endpoint has already verified the transport (DVN signatures, guardian quorum, oracle committee). Everything below is about what the endpoint does not do for you.

Why each pin. msg.sender == endpoint is necessary and not sufficient: any contract can implement lzReceive with the same selector and call you, and tx.origin is useless because the immediate caller is always the endpoint's delivery path. The endpoint address alone doesn't tell you which chain the message came from: that's _origin.srcEid on LayerZero V2, emitterChainId on Wormhole, sourceChainSelector on CCIP. And a real message from a real chain is worthless if it came from a contract you don't control, so you pin the peer address too.

The ordering rule is the one people get wrong. Mark the message consumed before the external call, not after. Mark it after and a reentrant call with the same message re-enters while the flag is still false.

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

interface IEndpointV2 {
    struct Origin { uint32 srcEid; bytes32 sender; uint64 nonce; }
    function lzReceive(Origin calldata, bytes32, bytes calldata, address, bytes calldata) external payable;
}

contract AdminHandler {
    IEndpointV2 public immutable endpoint;
    uint32 public immutable srcEid;   // e.g. 30101 = Ethereum mainnet
    bytes32 public immutable peer;    // trusted remote handler
    mapping(bytes32 => bool) public consumed;

    error Unauthorized();
    error Replay();

    function lzReceive(
        IEndpointV2.Origin calldata o,
        bytes32 guid,
        bytes calldata message,
        address,
        bytes calldata
    ) external {
        if (msg.sender != address(endpoint)) revert Unauthorized();
        if (o.srcEid != srcEid) revert Unauthorized();
        if (o.sender != peer) revert Unauthorized();
        if (consumed[guid]) revert Replay();
        consumed[guid] = true;        // before _execute
        _execute(message);
    }
}

What you pin, per protocol. The field widths differ, and that is a real bug source.

protocolsource chain fieldsource contractdedupe keywho dedupes
LayerZero V2srcEid uint32 (Ethereum = 30101)sender bytes32guid bytes32endpoint enforces nonce order; record guid anyway
WormholeemitterChainId uint16 (Ethereum = 2)emitterAddress bytes32(chainId, emitter, sequence)you must: the core bridge does not
Chainlink CCIPsourceChainSelector uint64 (Ethereum = 5009297550715157269)sender bytesmessageId bytes32router enforces; record anyway

The Wormhole row is the one that bites. parseAndVerifyVM proves 13 of 19 guardians signed the VAA; it does not prove you haven't seen that VAA before. Store the triple.

Trace: replay via reentrancy. Handler marks consumed after _execute:

  1. Endpoint delivers guid = 0xaa, nonce 7. consumed[0xaa] is false.
  2. _execute calls recipient.onAdminAction(): a contract the message names.
  3. That contract calls back into lzReceive with the same guid = 0xaa.
  4. consumed[0xaa] is still false. It passes. _execute runs a second time.
  5. Two grantRole calls from one message.

With the flag set first, step 4 reverts Replay(). The endpoint's own nonce check does not save you: the nonce was already accepted on the first delivery.

Trade-offs. Pinning one peer is cheap and fast, and it makes the bridge the single point of failure: whoever controls the DVN set or guardian quorum controls your admin. Two alternatives. Require two independent attestations (LayerZero and Wormhole) before executing: doubles message fee, adds the slower bridge's latency, and you need a policy for when one arrives and the other never does. Or make the cross-chain message only propose: it writes to a pending queue and a local timelock (48h is common) executes. That buys an exit window at the cost of latency. The deciding question is what the handler can do. If it can call upgradeTo, take the timelock. If it can only rotate a fee parameter, single-peer pinning is proportionate.

Failure modes and how you see them. Endpoint spoofing: a lookalike contract calls your handler; you see Unauthorized reverts from a non-endpoint caller, alert on any. Wrong source: a genuine message from a genuine endpoint on the wrong chain; emit srcEid and sender on every accepted message and diff against the allowlist. Chain selector confusion: storing the peer as uint64 and comparing against a uint32 EID truncates; assert against the real constants (30101, not 1) in tests. Upgrade mismatch: a proxy upgrade that reorders storage wipes consumed; run a storage-layout diff in CI before every upgrade. Bridge compromise: the guardian set or DVN set changes on-chain; that change is a paging event, and the handler's capped authority is the blast radius.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-15

Assess a committee bridge's controls.

Answer

Core answer (first 90 seconds)

Assess a committee bridge by one number: the effective threshold. How many independent parties an attacker must compromise to mint or release funds. Everything else is supporting evidence.

Assumptions I'd state up front: the bridge escrows assets on the source chain and mints or releases on the destination; the committee signs attestations of source events; I don't control the committee's infrastructure. Under those, my judgement, ranked: (1) effective threshold and key independence, (2) what the signed message actually authorizes. Unchecked mint is fatal at any threshold, (3) upgrade and rotation authority, (4) pause and monitoring. A 5-of-9 with nine independent operators is a different asset from a 5-of-9 where four keys sit with one company.

Mechanism: threshold maps to attack cost

The committee is a quorum signature scheme, so security ≈ cost to obtain threshold valid signatures. With independent keys that is roughly threshold × (cost to compromise one operator). Correlated custodians collapse it. Ronin was configured 5-of-9, but Sky Mavis held 4 keys and Axie DAO held 1, so the attacker needed one external key plus a backdoored RPC node: 173,600 ETH and 25.5M USDC, about $624M, March 2022. Harmony Horizon was 2-of-5; two compromised keys drained roughly $100M in June 2022. Same class, threshold 2 versus effective 1.

Contrast: Wormhole's guardian set was 19 with threshold 13. The threshold held: the Solana verification code accepted a forged signature account, $326M, February 2022. Threshold is necessary, not sufficient.

Controls

controlpassfail / detection
effective threshold≥5 independent operators, no shared custodiancount keys per org; if any org holds ≥ threshold−1, fail
message scopesigned payload binds chain, contract, recipient, amount, noncere-submit a signed message with an altered amount; if it lands, fail
rotationtimelock plus separate governance key, old keys revokedalert on rotation outside the timelock path
upgrade keysmultisig + timelock, no single EOAdiff the proxy admin on every upgrade
pausecallable by ≥2 independent partiesdrill it; measure time-to-pause
monitoringalert on mint with no matching source depositreconcile minted supply against escrow each block

Failure modes and detection

  • Key compromise: anomalous signing from a key whose operator reports no activity; rotate immediately.
  • Correlated custodians: map key → legal entity → cloud provider → RPC endpoint; shared infra is a shared failure.
  • Malicious rotation: rotation transaction from a non-timelock path.
  • Low threshold: arithmetic. 2-of-5 costs the attacker two compromises, 5-of-9 costs five.
  • Signer outage: at 5-of-9, four offline signers halt the bridge; liveness margin is n − threshold.
  • Unchecked mint: destination minted supply drifting from source escrow is the alarm.
  • Opaque membership: if you cannot enumerate signers, you cannot assess. Treat as fail.
  • TVL above security budget: $500M escrowed against a $5M/yr operational security spend is under-insured; cap TVL or raise the threshold.

Trade-offs

Multisig committee: cheap, fast finality, but trust is explicit and key custody is the whole game. MPC/threshold signatures: no single key exists, stronger against single-host compromise, but the signing service becomes a new single point and key-share generation is a ceremony you must audit. Light client or optimistic: trust minimized, but latency (challenge window) and per-message gas are higher, and the verification code becomes the attack surface. Wormhole again. Choose a committee when the asset is small relative to the cost of running validators; choose a light client when TVL justifies the latency.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-14

Evaluate a light-client bridge.

Answer

Core answer

Evaluating a light-client bridge means answering two questions, not auditing a list: what does the client trust, and what happens when that trust is violated or the client goes stale? Relayer software, proof format and incentives are all downstream of those two.

A light-client bridge verifies remote state locally. The client stores a trusted consensus state: a validator set or sync committee plus a block root. A relayer submits a new consensus update; the client checks it against the trusted set, advances the root, then verifies a membership proof of application state against that root. The relayer is untrusted: it can censor or delay, but a forged update has to fail the threshold check. So the security budget is the client's, and the relayer only moves liveness.

The trade-off that decides the design

The central knob is the trusting period: how long a stored consensus state stays valid without a fresh update. In ibc-go the Tendermint client defaults to 2/3 of the source chain's unbonding period: Cosmos Hub's 21-day unbonding gives a 14-day trusting period. Ethereum's Altair sync committee client works differently: 512 validators, rotating every 256 epochs (~27 hours), with finality updates needing ≥2/3 (342) signatures.

Longer trusting period → the relayer can be lazy and updates are cheap, but the weak-subjectivity window widens: an attacker who rewrites history from before the trusted checkpoint can fool a fresh client. Shorter → safer, but the relayer must update before expiry or the bridge halts. Pick the trusting period from the source chain's finality guarantees and the relayer's realistic worst-case downtime, not from gas cost alone.

Failure modes and how you detect them

  • Expired client: no update within the trusting period. Detect via the client's own timestamp check against the latest header; ibc-go returns ErrTrustingPeriodExpired. Cost: the bridge halts, and recovery needs a header inside the period. Past weak subjectivity, a governance-supplied checkpoint.
  • Long-range attack: attacker builds an alternate chain from genesis. Detect by comparing incoming header height/timestamp against the trusted checkpoint and rejecting anything older than the weak-subjectivity horizon (~2 weeks on Ethereum mainnet at current validator counts).
  • Invalid validator update: forged set change. Detect with a threshold signature check against the currently trusted set before accepting the new one.
  • Proof-path confusion: proof verified against the wrong store key or root. Detect by asserting the expected commitment prefix and that the root equals the client's stored root.
  • Misbehaviour: two conflicting headers at one height. Detect with CheckForMisbehaviour; the client freezes and needs governance to unfreeze.

Two clients side by side

IBC Tendermint clientEthereum sync committee
Trusted setvalidator set, 2/3 stake512 validators, 2/3 sigs
Trusting period2/3 unbonding (14 d on Cosmos Hub)~27 h committee rotation
Update cadence≤ trusting periodevery committee period
On stalenessclient expires, proofs rejectedupdate rejected, bridge stalls

Worked check

Source: Cosmos Hub, unbonding 21 days → trusting period 14 days. The relayer last submitted a header at T. At T+14d+1s the client is expired: every VerifyMembership call fails, not just new updates. Detection is the client's timestamp check, not a relayer log. Recovery means submitting a header with a timestamp inside the period: impossible if the relayer was down 15 days, so you fall back to a governance checkpoint. That is the operational cost the trusting-period choice buys.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-16

Threat-model an optimistic message bridge.

Answer

Clarify, then assume. An optimistic bridge verifies nothing on the destination chain. It accepts a claim ("this withdrawal is valid," "this is the L2 state root") and finalizes it after a challenge window unless someone disputes it. So the security property is not "the verifier is correct." It is: an honest watcher, holding a bond, can get a dispute transaction included on L1 before the window closes. Everything below is an attack on that sentence. I'll assume L1 is live and honest, and that the bridge is moving real money.

The mechanism. A proposer posts a claim plus a bond. The claim sits for the challenge window: 7 days on Optimism's canonical bridge. Undisputed, it finalizes. Disputed, it enters an interactive bisection game: proposer and challenger halve the disputed state transition until they're arguing over a single instruction, which the fault-proof VM executes on-chain (Cannon/MIPS on the OP Stack; Arbitrum's BoLD is the same shape). The loser's bond is slashed. The window exists because the game is expensive and rare: you pay for verification only when someone lies.

Where it breaks. The adversary's goal is not to win the game. It is to make sure the game never happens.

  • Censorship and liveness. The dispute tx has to land on L1. A builder that censors it, or a base-fee spike the watcher didn't price for, is enough.
  • Data availability. The claim points at data the watcher can't fetch: an expired blob, a DA layer that's down. No data, no dispute.
  • Bond economics. If the bond is smaller than what a false claim extracts, silence is rational. A 1 ETH bond ($3k) against a 5,000 ETH claim ($15M) is not a deterrent.
  • Verifier bugs. Nomad, August 2022: a faulty initialization set the trusted root to zero, so anyone could prove arbitrary messages. Roughly $190M left in hours. The bug wasn't in the challenge game: the game never ran.
  • Governance bypass. If an admin key can upgrade the verifier or pause the game, the cryptographic argument is decoration.
  • Premature execution. A fast bridge or relayer that credits the destination on the claim rather than on finalization has deleted the window.

The trade-off. Window length is the dial. Seven days is safe and slow: capital is locked for a week. Shortening it to an hour buys UX and forces one of two things: a bonded, permissioned proposer set, which reintroduces the trust assumption you were avoiding, or validity proofs, which remove the window but add proving cost and latency. The deciding criterion: what is the most a single false claim can extract, and can an independent watcher cover that with a bond and land a transaction inside the window?

Worked trace (hypothetical figures). An attacker posts a false 5,000 ETH withdrawal claim at t=0. The watcher's dispute tx is priced at 30 gwei; L1 base fee spikes to 400 gwei and the tx sits. At t+30 min the watcher's "dispute pending" alert fires; the operator re-submits at 500 gwei and it lands at t+45 min. With a 7-day window that's slack. With a 1-hour window the claim finalizes at t+60 min and $15M is gone: against a watcher running cost of a few hundred dollars a month.

What you actually monitor.

SignalThreshold that should pageWhat it means
Dispute tx pending on L1> 30 minWatcher cannot land a dispute
DA fetch failure rate> 1% over 10 minWatcher is blind to the claim's data
Bond ÷ largest single claim< 1Silence is the rational play
Verifier upgrade without timelockanyGovernance bypass, not a crypto failure
Destination credit before finalizationanyThe window has been removed

If you can't fill in a number for the bond row and a latency for the first row, you don't have a threat model yet: you have a diagram.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-23

Upgrade a live bridge lane.

Answer

Clarify and assume first. A "lane" is one shard of the bridge: its own consumer group, its own committed offset, its own rollout state. That matters because it means lanes upgrade independently and a bad lane rolls back without touching the rest. I'd also state up front: the bridge is at-least-once, both old and new producers are live during the window, and I control the bridge but not necessarily every downstream consumer. If any of those is false the plan changes.

The core answer. Upgrade a live lane with expand–contract, not a cutover. Ship a versioned envelope, make the bridge able to decode both eras, roll the lane forward one shard at a time behind a drain barrier, and keep the old decoder deployed until the last old-format message has reached a terminal state.

Mechanism. Every message carries a schema version in the envelope, a protobuf field number or a v header, so the version travels with the payload, not with the topic. The new bridge reads the version, decodes v1 through a translation shim and v2 natively, and writes v2 downstream. The shim is the only component that understands both eras, so the blast radius of a decode bug is one function.

The drain barrier is what makes it safe. For each lane, record the highest offset that can still contain a v1 message: the v1 watermark. The lane is done only when the committed offset passes that watermark and no producer has emitted v1 for a full window. Until both hold, the shim stays.

Trade-offs. Translate-on-read (shim in the bridge) versus dual-write (producers emit both formats). Translate-on-read leaves producers untouched and is reversible; dual-write doubles write volume and opens a window where the two copies disagree. I pick translate-on-read when I own the bridge and the rate is high, and dual-write only when a consumer I don't control needs the new format before the bridge can ship. Per-lane rollout versus global: per-lane costs more operational attention but bounds a bad decode to one shard's traffic.

Failure modes and how I'd catch each.

failuredetection
decoder ambiguity (a v1 payload parses as v2)round-trip every sampled message through both decoders; alert when they disagree
stranded v1 message after shim removalv1-topic lag metric and DLQ depth; alarm if either is non-zero at lane completion
double execution across the cutoveridempotency-key collision counter on the consumer
rollback binary can't read v2 staterun the old binary against a v2 shadow store before cutover, not after

Worked trace (hypothetical figures). Lane 3, 40k msg/s, 12M messages in flight. At t0 I flip the lane to dual-decode. Producers keep emitting v1 for another 90s, so the v1 watermark advances to offset 12.4M. The shim keeps translating until the committed offset passes 12.4M: at 40k/s that is roughly 310s of drain, so I budget about 6 minutes per lane, not 30 seconds. Only then do I remove the shim and let the old decoder age out one release later.

The one thing I would not do is remove the shim in the same deploy that flips the lane: that is exactly the rollback that cannot read new state.

Curated: · Written: · Reviewed:

Difficulty: Hard