Skip to content

About

Defensive price oracle: Chainlink staleness + L2 sequencer-uptime + TWAP-deviation guards with fallback, normalized to 1e18

Resources

Stars

0 stars

Watchers

0 watching

Forks

Latest commit

 

History

2 Commits

Folders and files

Repository files navigation

Defensive Price Oracle

A production-grade price-oracle aggregator for on-chain protocols. It reads a Chainlink-style feed behind a stack of safety guards, cross-checks it against an independent TWAP source, and returns a price normalized to 18 decimals — reverting on any anomaly rather than passing bad data to callers.

Bad oracle reads are the single most exploited surface in DeFi. Every guard here maps to a real, recurring exploit class.

Why each guard exists

Guard Exploit class it prevents
Staleness (updatedAt == 0 or now - updatedAt > maxStaleness) A feed that stopped updating (misconfigured heartbeat, halted node, depegged asset frozen at an old value) keeps reporting a stale price. Protocols that read it liquidate or mint against a price that no longer exists. Reverting forces callers to fail closed.
Validity (answer > 0) Aggregators can momentarily report 0 or a negative answer (feed decommissioned, math edge, L2 reorg). A 0 price has been used to borrow the entire reserves of a market for free.
Incomplete round (answeredInRound >= roundId) A round whose answer was carried over from a prior round is not fresh consensus. Reading it trusts data the aggregator itself has not finalized.
L2 sequencer uptime (SequencerDown / GracePeriodNotOver) When an L2 sequencer is down, users cannot submit transactions to defend positions, yet the price feed keeps ticking off-chain. On restart, a burst of stale-priced liquidations can be front-run. The classic Chainlink pattern: refuse prices while the sequencer is down, and for a gracePeriod after it returns.
TWAP deviation cross-check (TwapDeviation) A single price source is a single point of manipulation (flash-loan spot-price attacks, a compromised or thin feed). Requiring the primary feed to agree with an independent time-weighted price within maxDeviationBps neutralizes manipulation that moves only one source.

Contracts

  • src/interfaces/IAggregatorV3.sol — standard Chainlink AggregatorV3Interface (used for both the price feed and the L2 sequencer-uptime feed).
  • src/interfaces/ITwapSource.sol — minimal interface for an independent TWAP source (e.g. a Uniswap-V3 pool oracle adapter).
  • src/PriceOracle.sol — the aggregator.

API

  • price() → uint256 — fully-guarded price (1e18). Runs every check and reverts on the first failure. Use this by default.
  • priceWithFallback() → uint256 — if Chainlink is stale/invalid/incomplete, returns the TWAP instead of reverting. The sequencer guard still applies. See the trade-off below.
  • rawChainlink() / rawTwap() — unguarded reads for observability and off-chain monitoring.

Fallback trade-off

priceWithFallback() trades safety for liveness. When the primary feed is healthy it behaves exactly like price() (including the TWAP cross-check). When the primary feed is unusable it returns the TWAP alone, forgoing the cross-check — a single-source price. This keeps a protocol running through a temporary Chainlink outage instead of bricking it, at the cost of the manipulation resistance the cross-check provides. If both sources are unusable it reverts (NoPriceAvailable). Callers that require the strongest guarantee should use price() and handle the revert.

Normalization

Every price is scaled to 18 decimals using the source's own decimals(): feeds with fewer than 18 decimals are multiplied by 10**(18 - d), more than 18 are divided by 10**(d - 18). All math is checked (no unchecked on the scaling path). Tested for 6-, 8-, 18- and 20-decimal feeds with exact expected outputs.

Deviation semantics

Deviation is measured against the smaller of the two prices (the most conservative choice in either direction): the read reverts when |chainlink - twap| * 10_000 > maxDeviationBps * min(chainlink, twap). A deviation exactly equal to maxDeviationBps passes; anything larger reverts.

Trust model

The contract is Ownable. The owner can update the feed addresses and the three risk parameters (maxStaleness, gracePeriod, maxDeviationBps) — but every parameter is bounded in the contract itself, so a careless or malicious owner cannot disable the guards:

  • maxDeviationBps ≤ 5000 (50%) — the cross-check can never be widened into irrelevance.
  • 0 < maxStaleness ≤ 7 days — staleness can never be set to zero (which would always revert) or an unboundedly large window.
  • gracePeriod ≤ 7 days.
  • Feed addresses can never be set to address(0) (except the sequencer feed, where address(0) is the explicit L1 "no sequencer" mode).

Owner is set to the deployer; transfer or renounce via OpenZeppelin Ownable.

L1 vs L2

Pass address(0) as the sequencer feed for L1 deployments — the sequencer guard is skipped entirely. On an L2, pass the network's Chainlink sequencer-uptime feed and a gracePeriod (typically 3600s).

Deep dive (v2)

A second adversarial pass on the read paths surfaced two ways a bad value could escape _readChainlink — the "soft" read that priceWithFallback relies on. Both are fixed, each with a regression test that fails before the fix:

  • Zero after down-scaling could leak. The validity check answer > 0 is applied to the raw feed answer. For a feed with more than 18 decimals, a small but positive answer can down-scale to 0 in _scaleTo1e18 (integer division), and the read would return (0, OK). price() still reverted (the deviation guard's base == 0 check, or TwapUnavailable), but priceWithFallback() with an unavailable TWAP would return a zero price. Fix: a normalized value of 0 is now reported as INVALID, so no path can surface it. (Bonus: this also hardens the zero-answer rejection — it survives even if the raw answer <= 0 check is weakened.)
  • Future updatedAt reverted the soft read. A misconfigured or rogue feed reporting an updatedAt in the future made block.timestamp - updatedAt underflow and revert. That violated the "never reverts" contract of _readChainlink and, worse, made priceWithFallback() revert instead of degrading to the TWAP. Fix: a future updatedAt is treated as STALE, so price() reverts cleanly with StalePrice and priceWithFallback() still falls back.

Both are defensive hardening against a malfunctioning/hostile feed rather than exploits of the intended Chainlink-shaped inputs; the strict price() path never leaked a value either way (it fails closed). Coverage was extended with these regressions plus an adversarial invariant that drives arbitrary feed decimals, future timestamps and TWAP toggles and asserts no path ever returns a zero price.

Testing

forge test          # 58 unit/fuzz tests + 4 stateful invariants
forge build --sizes # PriceOracle runtime ~3.0 KB, well under the 24 KB EIP-170 limit
forge fmt --check

The suite covers the happy path, every revert path, decimal normalization exactness, owner-only access control and parameter bounds, and a fuzz property that the strict price is always the normalized primary value inside a [min*(1-dev), max*(1+dev)] envelope and never zero. A stateful invariant campaign drives the oracle with randomized feed inputs and asserts, via ghost variables, that no stale or invalid read ever passes the strict guard and no returned price ever leaves the safety envelope.

Deployment

See script/Deploy.s.sol. Set CHAINLINK_FEED, TWAP_SOURCE, and (on L2) SEQUENCER_FEED, plus the risk parameters, then forge script script/Deploy.s.sol.

About

Defensive price oracle: Chainlink staleness + L2 sequencer-uptime + TWAP-deviation guards with fallback, normalized to 1e18

Resources

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages