Skip to main content

Oracles and MEV

Every YieldBasis market defends LPs against flash-loan manipulation and toxic arbitrage across two layers: a stateless LP oracle (CryptopoolLPOracle) that insulates LEVAMM from spot-price manipulation, and optional v3 Curve pool policies (YBOraclizedPolicy or YBTwocryptoPolicy) that govern swap fees and price_scale recentering.

CryptopoolLPOracle and sandwich resistance​

CryptopoolLPOracle prices one Curve Cryptoswap LP token in USD on demand from three live on-chain reads—storing no mutable state and requiring no keeper updates:

po=2⋅vp⋅price_scale⋅paggp_o = 2 \cdot v_p \cdot \sqrt{\text{price\_scale}} \cdot p_{\text{agg}}
TermSourceRole
vpv_pPOOL.virtual_price()Cumulative fee-growth accounting per LP token.
price_scalePOOL.price_scale()Curve pool's internal liquidity center (crvUSD per volatile asset).
paggp_{\text{agg}}AGG.price() or AGG.price_w()Curve's external crvUSD/USD EMA price aggregator across multiple crvUSD markets.

Balanced-pool derivation​

In a constant-product pool with crvUSD reserve xx, volatile-asset reserve yy, and x⋅y=kpoolx \cdot y = k_{\text{pool}}, balance at price_scale implies x=y⋅price_scalex = y \cdot \text{price\_scale}, so total pool value is 2kpool⋅price_scale2\sqrt{k_{\text{pool}} \cdot \text{price\_scale}}. Dividing by LP supply ScS_c and substituting vp=kpool/Scv_p = \sqrt{k_{\text{pool}}} / S_c yields 2⋅vp⋅price_scale2 \cdot v_p \cdot \sqrt{\text{price\_scale}} in crvUSD per LP token; multiplying by paggp_{\text{agg}} converts to USD.

Why single-block manipulation fails​

CryptopoolLPOracle never reads the Curve pool's spot price or an external spot feed directly:

  • Single-step limit per block: Only the first pool interaction in a block that passes the pool's profit test (vp_boosted > lp_xcp_profit) can move price_scale.
  • Bounded step size: Each move is capped by the pool's adjustment_step() maximum and cannot push per-LP value below the profit floor (lp_xcp_profit).
  • 20% EMA clamp: The Curve pool clamps every proposed price_scale target to within ±20%\pm 20\% of its own internal trade-price EMA (price_oracle).
  • Aggregator safety band: Factory requires AGG.price() to lie strictly inside ($0.90, $1.10) when initializing Factory or calling set_agg(). Each market's CryptopoolLPOracle stores AGG as an immutable.

Because price_scale can move by at most one bounded step per block, a single-block sandwich attack cannot materially distort LEVAMM's collateral valuation (AMM.value_oracle()). The tradeoff is intentional lag during fast spot moves, which drives Temporary Redemption Discount (TRD); see TRD and pricing.

Pool policies: YBOraclizedPolicy versus YBTwocryptoPolicy​

A Curve Twocrypto v3 pool can attach an external policy contract (POOL.POLICY()) that overrides its swap fee, its price_scale target, or both. Check Contract addresses or call POLICY() on a pool to see which policy it runs.

FeatureYBOraclizedPolicy (oracle-report policy)YBTwocryptoPolicy
Swap feeDiscounts corrective swaps backed by fresh signed Pyth Pro reports; all other swaps pay fallback_feeLeaves the pool's native dynamic fee curve unchanged
price_scale targetDual-EMA trend-gated driver observing Pyth Pro reports (until report_lifetime), else prior pool spotExtrapolated from two EMAs of the pool's own trade prices
External inputsPythReportBank, AGGREGATOR(), optional BASIS_POOLNone
Deposit protectionEnforces LT deviation ratio check (ratio_tolerance)None
Governance & kill switchOwned by YB DAO; killable by YB DAO or Curve Emergency DAOImmutable: no owner, setters, or kill switch

If no policy is attached, or if YBOraclizedPolicy is killed (is_killed == True), get_fee and get_price_scale return 0, and the pool reverts to its native fee curve and internal price_oracle EMA target. After initial pool deployment, only a Curve DAO vote (set_policy_contract) can attach, replace, or remove a policy.

How YBOraclizedPolicy mitigates LVR​

Without an oracle-report policy, a Cryptoswap pool's native fee depends only on reserve imbalance, not trade direction—charging the same rate to corrective swaps moving back toward external market price as to informed swaps exploiting a stale quote. On a pool running YBOraclizedPolicy, swap fee pricing (not swap execution price) and price_scale targeting read signed Pyth Pro (Pyth Lazer) reports stored in a shared PythReportBank. The Twocrypto curve always determines execution price; the oracle only computes the fee within FeeConfig{base_fee, capture, fallback_fee, relax_time} and updates the dual-EMA driver.

LVR trade-off across market regimes: By pricing corrective swaps at base_fee + capture * (edge - base_fee), the policy recaptures LVR effectively during two-sided chop (monetizing small corrective gaps that a flat fallback_fee would block). During sustained one-way trends or sudden price jumps, discounting corrective swaps can underperform a flat fallback_fee because inventory is sold along the trend at lower effective fees, and searchers can select favorable timestamps within the PythReportBank delivery window (MAX_AGE_US = 60 s, decaying via age/relax_time\sqrt{\text{age}/\text{relax\_time}}). If reports are withheld or stale, the pool fails safe to fallback_fee.

Report delivery (PythReportBank)​

Pull-based delivery, not a cron feed

Pyth Pro (Pyth Lazer) reports are not pushed onchain on a fixed schedule or cron job. Instead, arbitrageurs and routers fetch signed updates offchain and bundle PythReportBank.deliver_report(_update) atomically with pool.exchange() in the same transaction to lock in the age-0 fee discount.

Anyone can call PythReportBank.deliver_report(_update) (paying verification_fee() in ETH) to submit a signed Pyth Lazer update containing 1 to 8 feeds on a channel. The bank verifies the signature via verifier(), enforces a delivery window (MAX_AGE_US = 60 seconds before block.timestamp to MAX_FUTURE_US = 6 seconds after), and updates latest[feed_id][channel] strictly forward in observation time.

Price conversion, BASIS_POOL, and price_bounds()​

When YBOraclizedPolicy reads a report from BANK:

  1. Basis adjustment (BASIS_POOL): If configured (for example, pricing a wrapped BTC token from a BTC/USD feed), the policy multiplies—or divides when INVERT_BASIS is True—the USD feed price by BASIS_POOL.price_oracle(0).
  2. Sanity bounds (price_bounds()): Every report read must lie inside the DAO-configured [min_price, max_price] USD bounds, or the policy treats the report as absent.
  3. crvUSD rate (AGGREGATOR()): For swap fees only, the policy converts the USD price to crvUSD using AGGREGATOR() (reading last_price() if at most RATE_MAX_AGE = 4 hours old, else price()). If the crvUSD/USD rate lies outside [$0.50, $2.00], no swap earns a discount.

Why swap fees use AGGREGATOR() while the price_scale driver assumes 1 crvUSD = $1: Swap fees must measure exact arbitrage edge in live crvUSD terms; ignoring even a small crvUSD peg offset misstates edge and over- or under-charges corrective swaps. By contrast, price_scale recentering spends the pool's finite rebalancing reserve. Because crvUSD is assumed to mean-revert toward $1, counting 1 crvUSD = $1 in the price_scale driver avoids wasting pool reserves chasing temporary stablecoin peg noise.

Corrective-swap fee discount and relax_time​

Only a swap that moves the pool's marginal price toward the reported crvUSD price without crossing it (corrective swap) with positive pre-fee edge (1 - input_value / output_value) and a report younger than relax_time earns a fee below fallback_fee:

ffresh=min⁡ ⁣(ffallback,  fbase+capture⋅max⁡(edge−fbase,  0))f_{\text{fresh}} = \min\!\Bigl(f_{\text{fallback}},\; f_{\text{base}} + \text{capture} \cdot \max(\text{edge} - f_{\text{base}},\; 0)\Bigr)

As the report ages toward relax_time, the discount decays with the square root of report age:

f(age)=ffresh+(ffallback−ffresh)⋅agerelax_time.f(\text{age}) = f_{\text{fresh}} + (f_{\text{fallback}} - f_{\text{fresh}}) \cdot \sqrt{\frac{\text{age}}{\text{relax\_time}}}.

Illustrative example. Suppose base_fee is 0.50%, capture is 67.5%, fallback_fee is 1.75%, and relax_time is 300 s. For a corrective swap with a 1.20% edge:

  • Fresh report (0 s): Fee is 0.50%+0.675×(1.20%−0.50%)=0.9725%0.50\% + 0.675 \times (1.20\% - 0.50\%) = 0.9725\%; the pool captures 0.9725% and the arbitrageur keeps 0.2275% before gas.
  • 12 s old report: 12/300=0.20\sqrt{12 / 300} = 0.20 of the discount has decayed, raising the fee to 1.128%1.128\% and shrinking arbitrageur margin to 0.072%.
  • Toxic (non-corrective) swap or stale report (≥300\ge 300 s): Pays the full 1.75% fallback_fee.

Call config() on the policy contract to read live FeeConfig and DriverConfig settings.

Dual-EMA price_scale driver​

YBOraclizedPolicy maintains a fast EMA (fast_half_life) and slow EMA (slow_half_life) of an observed USD price (counting 1 crvUSD as $1). While the bank's report is younger than report_lifetime, both EMAs observe the report; otherwise they observe the pool's spot price from the previous callback so an in-flight trade cannot steer them.

In calm markets, the target stays near the fast EMA. When abs(fast / slow - 1) approaches trend_gate, the target shifts toward the observed price. Each rebalance requests half the gap from price_scale to the target, capped at step_cap (up to 60 bp per touch), subject to the Curve pool's ±20%\pm 20\% price_oracle clamp, adjustment_step() cap, and profit floor.

LT deposit gate (ratio_tolerance)​

On every update_pool_state callback while active, YBOraclizedPolicy checks that any new LT.deposit, Hybrid Vault deposit, or LTMigrator migration adds debt matching LEVAMM's existing debt-to-collateral ratio within ratio_tolerance() (capped at 10 bp). Exceeding it reverts with "LT deviation", blocking ratio-skewing deposits.

How arbitrageurs keep markets pegged​

External arbitrageurs maintain peg alignment across two coupled venues:

  1. Curve Cryptoswap pool: Direct swaps align the pool's spot price with external markets. Under YBOraclizedPolicy, arbitrageurs bundle PythReportBank.deliver_report() and the corrective swap in the same transaction to capture the age-0 fee discount and avoid being front-run.
  2. LEVAMM via VirtualPool: As price_scale updates, LEVAMM drifts from 50% debt-to-collateral. Arbitrageurs call VirtualPool.exchange() to rebalance atomically with a crvUSD flash loan from Factory.flash():
    • Price rose (debt < 50%): VirtualPool.exchange(1, 0, ...) flash-borrows crvUSD, adds balanced Curve liquidity, sells LP to LEVAMM for crvUSD, and repays the flash loan—raising debt toward 50%.
    • Price fell (debt > 50%): VirtualPool.exchange(0, 1, ...) flash-borrows ϕ\phi crvUSD, buys LP from LEVAMM, withdraws balanced Curve liquidity, and repays ϕ\phi—lowering debt toward 50%.
Arbitrage paths in a YieldBasis market showing direct Curve Cryptoswap swaps and atomic VirtualPool flash-loan rebalances against LEVAMMArbitrage paths in a YieldBasis market showing direct Curve Cryptoswap swaps and atomic VirtualPool flash-loan rebalances against LEVAMM

Two arbitrage paths: direct swaps on the Curve Cryptoswap pool and atomic flash-loan rebalances through VirtualPool.

All LEVAMM swap fees (AMM.fee()) remain inside LEVAMM and flow to LT. All Curve swap fees remain inside the Curve pool for LP holders (predominantly LEVAMM), less any Curve admin_fee().