Skip to main content

Pool policy and report bank

A Curve Twocrypto v3.0.0 pool delegates fee pricing, price_scale steering, and post-operation state checks to an attached policy contract (pool.POLICY()). YieldBasis uses two policy implementations: YBOraclizedPolicy (which reads signed Pyth Pro / Pyth Lazer reports from a shared PythReportBank) and YBTwocryptoPolicy (an immutable dual-EMA controller without external feeds). Inspect any pool's active policy and parameters on-chain via pool.POLICY(), policy.config(), policy.price_bounds(), policy.ratio_tolerance(), and policy.BANK(), or check Contract addresses.

Curve Twocrypto v3.0.0 policy hook​

Interface called by the pool​

interface Policy:
def get_fee(xp: uint256[2]) -> uint256: view
def get_price_scale() -> uint256: view
def update_pool_state(
xp: uint256[2],
price_scale: uint256,
price_oracle: uint256,
last_prices: uint256,
virtual_price: uint256,
xcp_profit: uint256,
D: uint256,
oracle_timestamp: uint256,
): nonpayable

POLICY initializes to empty(address). During one-time pool initialize(), the deployer or Twocrypto factory.admin() can attach a policy. Thereafter, only set_policy_contract(policy) (callable by Twocrypto factory.admin(), reverting "only owner" otherwise) can attach, replace, or detach (empty(address)) a policy. policy cannot equal coins[0] or coins[1], and attaching when D > 0 calls update_pool_state with must_succeed = True.

Hook execution order​

Curve Twocrypto v3.0.0 swap fee hook flow: pool.exchange() calls YBOraclizedPolicy.get_fee(xp), reading PythReportBank, Curve crvUSD/USD AGGREGATOR, optional BASIS_POOL, and price_bounds to return either the discounted corrective fee or fallback_fee (0 if killed), with fees retained in the pool for LPs.Curve Twocrypto v3.0.0 swap fee hook flow: pool.exchange() calls YBOraclizedPolicy.get_fee(xp), reading PythReportBank, Curve crvUSD/USD AGGREGATOR, optional BASIS_POOL, and price_bounds to return either the discounted corrective fee or fallback_fee (0 if killed), with fees retained in the pool for LPs.
  • Swaps, add_liquidity (non-donation), remove_liquidity_fixed_out, remove_liquidity_one_coin: Call get_fee(xp) (return 0 selects the native fee; non-zero clamps to [10**5, 10**10], 0.1 bp to 100%), run tweak_price, and require update_pool_state to succeed.
  • Donations (add_liquidity with donation = True): Skip get_fee, pay NOISE_FEE (0.1 bp), run tweak_price, and require update_pool_state to succeed.
  • Balanced remove_liquidity (amount > 0): Skip get_fee and tweak_price, and invoke update_pool_state best-effort with a 300,000 gas cap (ignored on failure if at least 500,000 gas remained before the call; reverts otherwise).
How tweak_price queries get_price_scale past the profit gate on the first tweak_price of a block, clamps to price_oracle +/- 20%, steps one fifth of the distance, and updates state.How tweak_price queries get_price_scale past the profit gate on the first tweak_price of a block, clamps to price_oracle +/- 20%, steps one fifth of the distance, and updates state.

tweak_price calls get_price_scale() only when vp_boosted > lp_xcp_profit and block.timestamp > last_timestamp. A return of 0 selects price_oracle; any non-zero target clamps to price_oracle ± 20%. Because the pool steps one fifth of the distance (TWEAK_PRICE_MULTIPLIER = 5), YieldBasis policies return price_scale ± 5 * move to request a step of move.

How price_scale moves across blocks when the policy driver updates EMAs and requests capped steps.How price_scale moves across blocks when the policy driver updates EMAs and requests capped steps. Consumers of CRYPTOPOOL.price_scale() (CryptopoolLPOracle for AMM, LT._calculate_values, YBOraclizedPolicy, and YBLendingOracle) and CRYPTOPOOL.price_oracle() (YBLendingOracle and MerklPIDDriver converting yb-LP fees to crvUSD for Merkl sink-pool incentives).Consumers of CRYPTOPOOL.price_scale() (CryptopoolLPOracle for AMM, LT._calculate_values, YBOraclizedPolicy, and YBLendingOracle) and CRYPTOPOOL.price_oracle() (YBLendingOracle and MerklPIDDriver converting yb-LP fees to crvUSD for Merkl sink-pool incentives).

YBOraclizedPolicy​

On a pool running YBOraclizedPolicy, swap fees are priced off Pyth Lazer reports stored in BANK(), price_scale is steered by a trend-gated dual EMA, and LT.deposit() calls pass through an on-chain debt-ratio gate.

Constants, immutables, and storage​

  • Units: Fees in FEE_PRECISION = 10**10 (100%); MIN_FEE = 10**5 (0.1 bp). Prices and EMAs in PRECISION = 10**18 (1e18 = $1 for USD reports). Ratios in WAD (10**18). Pyth timestamps in Unix microseconds.
  • Constants: N_COINS = 2, TWEAK_PRICE_MULTIPLIER = 5, RATE_MAX_AGE = 14_400 (4 hours), MIN_RATE = 5 * 10**17 ($0.50), MAX_RATE = 2 * 10**18 ($2).
  • Immutables:
    • POOL() -> address: Attached Curve Twocrypto pool.
    • AMM() -> address: Market AMM holding the pool's LP as collateral (exported from yb_lt_gate).
    • BANK() -> address: Shared PythReportBank contract (exported from pyth_reports).
    • FEED_ID() -> uint32, CHANNEL() -> uint8: Pyth Lazer feed ID and channel read from BANK.
    • BASIS_POOL() -> address, INVERT_BASIS() -> bool: Optional Curve Stableswap-NG pool whose price_oracle(0) converts a wrapped asset (for example WBTC/BTC) relative to the Pyth feed (0x0 for none).
    • EMERGENCY_ADMIN() -> address: Address allowed to call set_killed alongside owner().
    • AGGREGATOR() -> address: Stablecoin USD aggregator (LPOracle(AMM.PRICE_ORACLE_CONTRACT()).AGG()), used to convert USD reports into coin 0 (crvUSD).
  • Public storage getters: owner(), config(), price_bounds(), ratio_tolerance(), is_killed(), state(), cached_A(), cached_supply(), amm_surplus().

Structs​

struct FeeConfig:
base_fee: uint256 # FEE_PRECISION: floor of a discounted swap fee
capture: uint256 # 1e18: share of reported edge above base_fee
fallback_fee: uint256 # FEE_PRECISION: undiscounted fee and cap
relax_time: uint256 # seconds: report age at which discount expires

struct DriverConfig:
fast_half_life: uint256 # seconds
slow_half_life: uint256 # seconds
trend_gate: uint256 # 1e18: |fast / slow - 1| for full observation tracking
step_cap: uint256 # 1e18: max requested price_scale move per touch
report_lifetime: uint256 # seconds: max report age for EMA observation (0 = never)

struct PolicyConfig:
fee: FeeConfig
driver: DriverConfig

struct PriceBounds: # exported by pyth_reports
min_price: uint256 # 1e18 = $1
max_price: uint256

struct State:
last_update_ts: uint256
fast_ema: uint256
slow_ema: uint256
price_scale: uint256
xp: uint256[2]
D: uint256
last_prices: uint256

External functions​

SignatureMutabilityAccessNotes
get_fee(xp: uint256[2]) -> uint256viewAnyone (called by POOL)Returns 0 if killed; fallback_fee for non-swaps or missing/stale/uncorrective reports; discounted fee otherwise.
get_price_scale() -> uint256viewAnyone (called by POOL)Returns 0 if killed or before attachment; otherwise scale ± 5 * move.
update_pool_state(xp, price_scale, price_oracle, last_prices, _virtual_price, _xcp_profit, D, _oracle_timestamp)nonpayablePOOL only ("auth!")Runs lt_gate._update when live, projects EMAs on the first touch of a new timestamp, and stores state.
sync()nonpayableAnyoneRe-reads pool.price_scale(), pool.A(), xp, D, and lt_gate baselines. Reverts "pool uninitialized" if price_scale == 0 or on pool reentrancy.
get_target() -> uint256viewAnyoneTrend-gated USD target before step_cap (0 while killed or unattached).
get_emas() -> uint256[2]viewAnyoneProjected [fast_ema, slow_ema] at block.timestamp ([0, 0] before attachment).
get_report() -> (uint256, uint256, uint256)viewAnyoneReturns (asset_price_usd, coin0_price, observation_us) at any age; (0, 0, 0) when killed.
get_fee_with_report(xp: uint256[2], feed_price: uint256, report_age_us: uint256) -> uint256viewAnyoneQuotes get_fee(xp) for a hypothetical USD feed_price (before basis) observed report_age_us ago.
get_dy_with_report(i: uint256, j: uint256, dx: uint256, feed_price: uint256, report_age_us: uint256) -> uint256viewAnyoneQuotes pool.get_dy(i, j, dx) with a hypothetical report, solving the same D as execution. Reverts "not attached" if pool.POLICY() != self.
set_policy_config(config: PolicyConfig)nonpayableOwnerReplaces config without checkpointing EMAs. Emits SetPolicyConfig.
set_price_bounds(bounds: PriceBounds)nonpayableOwnerUpdates [min_price, max_price] immediately for all reads. Emits SetPriceBounds.
set_ratio_tolerance(ratio_tolerance: uint256)nonpayableOwnerUpdates LT gate tolerance (<= 10**15, 10 bp). Emits SetRatioTolerance.
set_killed(is_killed: bool)nonpayableOwner or EMERGENCY_ADMIN ("access")Kill returns 0 from hooks and disables the LT gate; revive runs _sync() first. Emits SetKilled.
owner(), transfer_ownership(new_owner), renounce_ownership()snekmate ownableOwner for mutationsOwnership management.

Swap fee pricing​

get_fee(xp) evaluates these rules in order:

  1. If is_killed, return 0 (native pool fee).
  2. If the operation is not a swap (one balance up, one down relative to state.xp), return fallback_fee without reading BANK.
  3. Read (FEED_ID, CHANNEL) from BANK requiring age_us < relax_time * 1_000_000. Apply optional BASIS_POOL (price_oracle(0), capped at ±1%) and price_bounds. If absent or out of bounds (asset_price == 0), return fallback_fee.
  4. Verify state.D != 0 and execution_D == state.D. During an A ramp, swaps re-solve D and fall back to fallback_fee until sync() is called after the ramp completes.
  5. Convert asset_price from USD to coin 0 using AGGREGATOR: read last_price() if block.timestamp <= last_timestamp() + 14_400, else price(). If the rate is outside [0.5e18, 2e18], return fallback_fee; else report_price = asset_price * 10**18 // rate.
  6. Compute swap edge edge=1−input_value/output_value\text{edge} = 1 - \text{input\_value} / \text{output\_value} (in FEE_PRECISION, coin 1 valued at report_price / price_scale). If edge == 0, return fallback_fee.
  7. Compute fresh and age-relaxed fee: fresh=min⁡(fallback, base+capture⋅max⁡(edge−base,0))\text{fresh} = \min\left(\text{fallback},\ \text{base} + \text{capture}\cdot\max(\text{edge} - \text{base}, 0)\right) fee=fresh+⌊(fallback−fresh)2⋅age_usrelax_time_us⌋+1\text{fee} = \text{fresh} + \left\lfloor\sqrt{(\text{fallback}-\text{fresh})^2 \cdot \frac{\text{age\_us}}{\text{relax\_time\_us}}}\right\rfloor + 1 (the +1+1 fee unit applies when age_us > 0 and fresh < fallback). Return fee only if fee < fallback_fee and the swap is corrective (marginal price get_p(xp, D, [cached_A, 0]) * price_scale moves toward report_price without crossing it or emptying a coin).

Trend-gated price_scale driver​

The driver treats 1 crvUSD as $1. On the first touch of a new timestamp, it observes the bank's USD report if live and younger than report_lifetime, otherwise state.last_prices, clamped to [price_scale / 2, 2 * price_scale]. Both EMAs decay with exact half-lives (fast_half_life, slow_half_life), and the target blends toward the observation by relative EMA divergence:

trend=∣fast−slow∣slow,w=min⁡(1, trendtrend_gate),target=fast+w⋅(obs−fast)\text{trend} = \frac{|\text{fast}-\text{slow}|}{\text{slow}},\qquad w = \min\left(1,\ \frac{\text{trend}}{\text{trend\_gate}}\right),\qquad \text{target} = \text{fast} + w\cdot(\text{obs}-\text{fast})

get_price_scale() requests half the gap to target, capped by step_cap * price_scale, multiplied by 5.

LT deposit ratio gate​

Inside LT.deposit(), CRYPTOPOOL.add_liquidity triggers update_pool_state before AMM._deposit(). When not killed, yb_lt_gate._update checks whether pool.user_supply() increased and pool.balanceOf(AMM) - AMM.collateral_amount() >= amm_surplus + added_lp. If so, the deposit must satisfy:

proportional=added_lp⋅AMM.get_debt()AMM.collateral_amount(),∣added_debt−proportional∣≤proportional⋅ratio_tolerance\text{proportional} = \frac{\text{added\_lp}\cdot\text{AMM.get\_debt()}}{\text{AMM.collateral\_amount()}},\qquad |\text{added\_debt} - \text{proportional}| \le \text{proportional}\cdot\text{ratio\_tolerance}

Otherwise update_pool_state reverts with "LT deviation". Call sync() after an A ramp ends, after a failed balanced-removal callback, or after a direct LP transfer to AMM.

Governance bounds​

SetterFieldAllowed rangeRevert string
set_policy_configbase_fee10**5 <= base_fee <= fallback_fee"base fee"
set_policy_configfallback_fee<= 10**9 (10%)"fallback fee"
set_policy_configcapture<= 10**18 (100%)"capture"
set_policy_configrelax_time1 .. 3_600 s"relax time"
set_policy_configfast_half_life600 <= fast_half_life <= slow_half_life"fast half-life"
set_policy_configslow_half_life<= 604_800 s (7 days)"slow half-life"
set_policy_configtrend_gate<= 10**17 (10%)"trend gate"
set_policy_configstep_cap1 .. 60 bp (6 * 10**15)"step cap"
set_policy_configreport_lifetime<= 14_400 s (4 hours)"report lifetime"
set_price_boundsmin_price, max_price10**6 <= min_price <= max_price <= 10**30"price bounds"
set_ratio_toleranceratio_tolerance<= 10**15 (10 bp)"ratio tolerance"

PythReportBank​

PythReportBank verifies signed Pyth Lazer updates and stores the newest report per (feed_id, channel) stream for all downstream YBOraclizedPolicy contracts.

Constants, structs, and storage​

  • Constants: MAX_FEEDS = 8, ENVELOPE_BYTES = 71, HEADER_BYTES = 14, FEED_BYTES = 27, MAX_PAYLOAD_BYTES = 230, MAX_UPDATE_BYTES = 301, EVM_MAGIC = 0x2a22999a, PAYLOAD_MAGIC = 0x93c7d375.
  • Delivery window (inclusive): MAX_AGE_US = 60_000_000 (60 s before block.timestamp), MAX_FUTURE_US = 6_000_000 (6 s after block.timestamp).
  • Channels: 1 (real_time), 2 (fixed_rate@50ms), 3 (fixed_rate@200ms), 4 (fixed_rate@1000ms). Channels never share storage.
  • Public storage: verifier() -> address, latest(feed_id: uint32, channel: uint8) -> Report(price, observation_us), owner() -> address.

External functions​

SignatureMutabilityAccessNotes
deliver_report(_update: Bytes[301])payable, @nonreentrantAnyoneSend exact verification_fee() wei ("fee"). Verifies signature, checks every feed against the delivery window, stores newer supported feeds, and emits ReportStored.
decode(_update: Bytes[301], _feed_id: uint32, _channel: uint8) -> (uint256, uint256)viewAnyoneUnverified decode for off-chain quotes only. Checks format, _channel ("channel"), and _feed_id ("feed"). Never use for state changes.
verification_fee() -> uint256viewAnyoneReturns PythLazer(verifier).verification_fee() in wei.
set_verifier(_verifier: address)nonpayableOwnerReverts "verifier" if not a contract; preserves stored reports. Emits SetVerifier.

Admission rules and byte layout​

deliver_report(_update) enforces:

  1. msg.value == verifier.verification_fee() ("fee").
  2. verifier.verifyUpdate(_update, value=fee) returns signer != address(0) ("signer") and len(_update) == 71 + len(payload) ("update length").
  3. Header checks PAYLOAD_MAGIC ("payload magic"), 1 <= feed_count <= 8 ("feed count"), exact length 14 + 27 * feed_count ("payload length"), and each feed checks property headers (0x0300, 0x04, 0x0c01), unique feed_id ("duplicate feed"), and observation_us <= message_us ("observation time").
  4. Both message_us and every feed's observation_us must lie within [now_us - 60_000_000, now_us + 6_000_000] ("message ahead", "message age", "observation ahead", "observation age").
  5. Feeds with mantissa <= 0 or exponent outside [-18, 0] decode to price = 0 and are skipped; feeds with observation_us <= latest[feed_id][channel].observation_us are skipped. Supported prices scale as mantissa * 10**(18 + exponent).

YBTwocryptoPolicy​

On a pool running YBTwocryptoPolicy, get_fee always returns 0 (selecting the pool's native fee) and price_scale is steered by an immutable, ownerless dual-EMA controller with no external oracle.

Immutables, storage, and functions​

  • Immutables: POOL, FAST_HALF_LIFE, SLOW_HALF_LIFE (600 <= fast <= slow <= 604_800), KAPPA (<= 2e18), DEADBAND (<= 60 bp), MIN_CAP, MAX_CAP (1 bp <= min_cap <= max_cap <= 60 bp).
  • Storage: state() returning (last_update_ts, last_prices, fast_ema, slow_ema, price_scale).
  • External functions: get_fee(_xp) -> 0 (pure), get_emas() -> uint256[2] (view), get_price_scale() -> uint256 (view), update_pool_state(...) (POOL only, "auth!").

get_price_scale() computes raw_target = max(slow + KAPPA * (fast - slow), 0), holds price_scale inside DEADBAND, ramps the step cap linearly from MIN_CAP to MAX_CAP over CAP_RAMP_SECONDS = 3_600, and returns price_scale ± 5 * move.