Draft: feat(stable-reserve): oracle-priced fills, 1:1 unit clamp, and underwater rebuild fee

I'll look at the actual diff to see what's currently on this branch. Targets develop. Contains the clamp commits from !4975 (closed) (still open separately against develop); if that merges first, these rebase away cleanly.

Why

The Stable Reserve intercepts a market swap between two eligible stables and fills it directly from module inventory, bypassing the pools. Several properties of the original design let the reserve lose value:

  1. The fill ratio came from pool-derived prices (pool.BalanceRune/BalanceAsset). Any swap can dislocate a pool within the ±1% depeg band, so an attacker could push a pool to make the reserve pay out more units than it received.
  2. Each leg passes IsEligibleStable independently against $1 ± tolerance, so two "healthy" stables can sit on opposite edges of the band. Repeated in-band round-trips bleed USD value out of the reserve with nothing to rebuild it.
  3. A depeg rescue is irreversible once queued. It liquidates the module's whole position in an asset through the AMM at slip, and nothing re-evaluated whether it should still run — so a transient oracle gap, or a dip that recovered, cost the reserve the entire position.

What changed

1. Unit clamp — grossTarget = MinUint(grossTarget, grossIn). The payout can never exceed the input token count; surplus accrues to the reserve. Defense-in-depth that holds even if pricing is wrong.

2. Oracle pricing, and it's the only mode — the fill ratio now comes from the enshrined price-feed oracle (keeper.GetPrice, quorum-signed supermajority median, swap-independent) instead of pool ratios. If either leg has no oracle price, the fill is declined and the swap falls through to the regular AMM pools. The StableReserveOraclePricing mimir, stableReserveDollarsPerRune's use as a fill price, and stableReserveSourceWorthAtLeastTarget are gone.

3. Two chain-qualified guards, because the oracle is keyed by TICKER — ETH.USDC and AVAX.USDC share one oracle price, so a chain-local failure (bridge compromise, halted chain, wrapper depeg) is invisible to it. The pools are the only per-chain price signal the network has:

  • The per-asset pool-price check in IsEligibleStable is restored (it was dropped in the move to oracle pricing). Without it a dislocated asset is depositable at its ticker price — crediting a deposit floor at up to twice its real value — and is selectable as a rescue target, liquidating into the compromised chain. It is a gate, not a price: it can only ever reject, so manipulating a pool denies fills at the attacker's own slip cost rather than extracting value.
  • New poolImpliedOutput cap in TrySwap: the payout is additionally capped at what a slip-free AMM double-swap would return. The eligibility gate bounds absolute deviation from $1 only, so two assets can both pass while their pools imply a materially different ratio; this prices that. The cap only ever lowers the payout — the oracle and grossIn terms still bind above it — so it cannot reintroduce pool-price manipulation. A missing/undepthed pool declines the fill (AMM fallback) rather than paying out zero.

4. Deposit USD floor + underwater rebuild fee — the unit clamp preserves token count, not USD value, so the reserve still needs a way to recover.

  • New reserve-wide state: aggregate USD value of deposits in 1e8 fixed-point (Get/SetStableReserveDepositValue). Incremented on Deposit at the oracle value, decremented on Withdraw, round-tripped through genesis (proto field 50) — it is not derivable from the per-asset credits.
  • On each fill, currentReserveUSD values the module's anchor inventory at oracle prices. While that sits below the deposit value, StableReserveUnderwaterFee is withheld from the payout; while fully backed, nothing is charged. The withheld portion stays in the reserve automatically — the full grossIn is deposited, only the reduced grossTarget is paid out.
  • Withdrawals unwind at $1 when no live price exists. OracleMgr.BeginBlock deletes every price each block, so prices exist only in blocks where a price-feed batch landed — "skip the decrement on a missing price" is the common case, not a rare one, and would leave the floor permanently inflated and the reserve reading as underwater forever. Deposits are admitted only inside $1 ± tolerance, so unwinding at $1 is bounded by that same tolerance (100 bps) instead of being unbounded and permanent.

5. Depeg rescue: hold band, and only on real evidence — rescue eligibility is now its own predicate (isDepegged) rather than !IsEligibleStable:

  • Rescue only on a price the oracle is actively reporting outside the band, never on a missing one. An outage says nothing about the asset's value; fills already decline while a price is absent, so holding through it is the recoverable failure.
  • Hysteresis. Rescue fires on StableReserveRescueToleranceBps (default 300), wider than the fill band StableReserveDepegToleranceBps (default 100), clamped up if misconfigured narrower. With one shared threshold the reserve accumulates the weak asset at fair value right to the edge and then dumps the whole position one basis point later — buying all the way down and selling at the bottom. The gap is a hold band: fills have stopped, but the position is not liquidated while the asset may recover.
  • Abort on recovery. handler_swap.go now aborts a queued rescue stream as soon as the SOURCE is eligible again — the pre-existing per-sub-swap check validated only the target. The abort is terminal: it returns a sentinel error that both swap queues settle and remove immediately (proceeds already swapped land in the module, unswapped secured shares never left it), so the stream cannot resume on a later block without a price feed.

6. Per-block RUNE deployment cap — StableReserveDeployMaxPoolBps (default 100 = 1%) bounds a single deployment swap to a share of the target pool's RUNE depth. Deployment swaps are queued with quantity 0 / interval 0 and the streaming auto-sizer degenerates to quantity 1 for this leg pair, so previously the module's entire RUNE balance was swapped into one pool in one block at whatever slip that cost. Normally that balance is a per-block trickle from the POL share, but a depeg rescue falling back to RUNE accumulates the whole reserve first. Any remainder deploys on the next block; 0, or an undepthed pool, leaves it uncapped.

Mimirs: StableReserveUnderwaterFee reuses the now-dead StableReserveOraclePricing slot; it is a fraction of 1e8 rather than basis points so sub-1-bps values are expressible (default 10_000 = 1 bps). StableReserveRescueToleranceBps and StableReserveDeployMaxPoolBps are new. All three are operational.

Safety properties

  • All price math is big.Rat, floored toward the reserve — no float, consensus-safe. Price strings are length-bounded (≤64) for G113 / CVE-2022-23772.
  • The underwater fee is applied after the MinUint clamps, so it can only ever reduce the payout. A misconfigured mimir at 1e8 withholds the whole payout; TrySwap then declines the fill (falls through to the AMM) rather than handing Withdraw a zero amount and hard-failing the swap.
  • currentReserveUSD iterates only the TOR anchors (bounded — this is the swap hot path) and skips assets with no oracle price. That undercounts (omits non-anchor inventory mid-depeg and transient RUNE), which biases toward charging the fee: the deposit-protecting direction.
  • poolImpliedOutput rounds to the target pool's decimals, so a 6-decimal stable loses dust against the 8-decimal oracle output — a shortfall that favors the reserve, the safe direction for a cap.
  • Deposit value tracking logs-and-skips on a missing oracle price rather than reverting the user's transaction.

Test-harness correction

OpTxPriceFeed's contract was documented (and relied on) as "send once, prices stay live for the rest of the run." That is wrong: the post handler removes the batch once it is included, and OracleMgr clears the prices at the next BeginBlock, so one feed supplies prices for exactly one block. The comment is corrected and the affected suites are rewritten to feed each block that needs a live price — which is what drives the size of the management.yaml and withdraw-unfilled.yaml diffs.

Tests

Unit:

  • TestFreeStableSwapOraclePricingFillsBandEdges / ...NeverPaysOutMoreUnits / ...FallsBackWhenPriceMissing — oracle-driven ratio, clamp holds, missing price → filled=false (AMM fallback).
  • TestEligibilityRejectsChainDislocatedPool, ...DifferentTicker, TestFillCapsWithinBandRelativeDivergence, TestFillPoolCapNeverRaisesPayout — the chain-qualified gate and cap.
  • TestStableReserveUSDValue, TestDepositValueTrackedAndDecrementedOnWithdraw, TestDepositFloorUnwindsWithoutALivePrice.
  • TestFreeStableSwapNoFeeWhenFullyBacked, TestFreeStableSwapChargesUnderwaterFee, TestFreeStableSwapUnderwaterFeeSupportsSubBps.
  • TestDepegRescueIgnoresOracleOutage, TestDepegRescueHoldsBetweenFillAndRescueBands, TestRescueAbortsOnlyWhenSourceActuallyRecovers, TestRescueRecoveryCancelsQueuedStream, TestDepegRescueQueueScanLifecycle.
  • TestRuneDeploymentCapsPerBlockPoolShare.
  • TestGenesisStableReserveDepositValueRoundTrip, TestStableReserveDepositValue_RoundTrip.

Regression:

  • suites/stable-reserve/swap.yaml scenario 3 asserts the combined path — USDC=0.99, USDT=1.01, reserve marginally underwater:
oracle out     = floor(100000000 * 0.99 / 1.01) = 98019801   (under the 100000000 cap)
underwater fee = 98019801 * 10_000 / 1e8        = 9802
payout                                          = 98009999
  • New suites/stable-reserve/rescue-oracle-outage.yaml: a cross-stable rescue whose target price vanishes mid-stream fails all sub-swaps, and the missing source price must not schedule a RUNE fallback; once a genuinely bad price returns, the RUNE rescue is scheduled and drains the position.
  • withdraw-unfilled.yaml reworked onto the RUNE fallback path; management.yaml adapted to chunked deployment and per-block feeds; exports refreshed repo-wide for genesis field 50.

🤖 Generated with Claude Code

Edited by Son of Odin

Merge request reports

Loading
Loading