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
- Swaps,
add_liquidity(non-donation),remove_liquidity_fixed_out,remove_liquidity_one_coin: Callget_fee(xp)(return0selects the native fee; non-zero clamps to[10**5, 10**10], 0.1 bp to 100%), runtweak_price, and requireupdate_pool_stateto succeed. - Donations (
add_liquiditywithdonation = True): Skipget_fee, payNOISE_FEE(0.1 bp), runtweak_price, and requireupdate_pool_stateto succeed. - Balanced
remove_liquidity(amount > 0): Skipget_feeandtweak_price, and invokeupdate_pool_statebest-effort with a 300,000 gas cap (ignored on failure if at least 500,000 gas remained before the call; reverts otherwise).
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.
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 inPRECISION = 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: MarketAMMholding the pool's LP as collateral (exported fromyb_lt_gate).BANK() -> address: SharedPythReportBankcontract (exported frompyth_reports).FEED_ID() -> uint32,CHANNEL() -> uint8: Pyth Lazer feed ID and channel read fromBANK.BASIS_POOL() -> address,INVERT_BASIS() -> bool: Optional Curve Stableswap-NG pool whoseprice_oracle(0)converts a wrapped asset (for example WBTC/BTC) relative to the Pyth feed (0x0for none).EMERGENCY_ADMIN() -> address: Address allowed to callset_killedalongsideowner().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
| Signature | Mutability | Access | Notes |
|---|---|---|---|
get_fee(xp: uint256[2]) -> uint256 | view | Anyone (called by POOL) | Returns 0 if killed; fallback_fee for non-swaps or missing/stale/uncorrective reports; discounted fee otherwise. |
get_price_scale() -> uint256 | view | Anyone (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) | nonpayable | POOL only ("auth!") | Runs lt_gate._update when live, projects EMAs on the first touch of a new timestamp, and stores state. |
sync() | nonpayable | Anyone | Re-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() -> uint256 | view | Anyone | Trend-gated USD target before step_cap (0 while killed or unattached). |
get_emas() -> uint256[2] | view | Anyone | Projected [fast_ema, slow_ema] at block.timestamp ([0, 0] before attachment). |
get_report() -> (uint256, uint256, uint256) | view | Anyone | Returns (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) -> uint256 | view | Anyone | Quotes 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) -> uint256 | view | Anyone | Quotes 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) | nonpayable | Owner | Replaces config without checkpointing EMAs. Emits SetPolicyConfig. |
set_price_bounds(bounds: PriceBounds) | nonpayable | Owner | Updates [min_price, max_price] immediately for all reads. Emits SetPriceBounds. |
set_ratio_tolerance(ratio_tolerance: uint256) | nonpayable | Owner | Updates LT gate tolerance (<= 10**15, 10 bp). Emits SetRatioTolerance. |
set_killed(is_killed: bool) | nonpayable | Owner 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 ownable | Owner for mutations | Ownership management. |
Swap fee pricing
get_fee(xp) evaluates these rules in order:
- If
is_killed, return0(native pool fee). - If the operation is not a swap (one balance up, one down relative to
state.xp), returnfallback_feewithout readingBANK. - Read
(FEED_ID, CHANNEL)fromBANKrequiringage_us < relax_time * 1_000_000. Apply optionalBASIS_POOL(price_oracle(0), capped at ±1%) andprice_bounds. If absent or out of bounds (asset_price == 0), returnfallback_fee. - Verify
state.D != 0andexecution_D == state.D. During anAramp, swaps re-solveDand fall back tofallback_feeuntilsync()is called after the ramp completes. - Convert
asset_pricefrom USD to coin 0 usingAGGREGATOR: readlast_price()ifblock.timestamp <= last_timestamp() + 14_400, elseprice(). If the rate is outside[0.5e18, 2e18], returnfallback_fee; elsereport_price = asset_price * 10**18 // rate. - Compute swap edge (in
FEE_PRECISION, coin 1 valued atreport_price / price_scale). Ifedge == 0, returnfallback_fee. - Compute fresh and age-relaxed fee:
(the fee unit applies when
age_us > 0andfresh < fallback). Returnfeeonly iffee < fallback_feeand the swap is corrective (marginal priceget_p(xp, D, [cached_A, 0]) * price_scalemoves towardreport_pricewithout 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:
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:
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
| Setter | Field | Allowed range | Revert string |
|---|---|---|---|
set_policy_config | base_fee | 10**5 <= base_fee <= fallback_fee | "base fee" |
set_policy_config | fallback_fee | <= 10**9 (10%) | "fallback fee" |
set_policy_config | capture | <= 10**18 (100%) | "capture" |
set_policy_config | relax_time | 1 .. 3_600 s | "relax time" |
set_policy_config | fast_half_life | 600 <= fast_half_life <= slow_half_life | "fast half-life" |
set_policy_config | slow_half_life | <= 604_800 s (7 days) | "slow half-life" |
set_policy_config | trend_gate | <= 10**17 (10%) | "trend gate" |
set_policy_config | step_cap | 1 .. 60 bp (6 * 10**15) | "step cap" |
set_policy_config | report_lifetime | <= 14_400 s (4 hours) | "report lifetime" |
set_price_bounds | min_price, max_price | 10**6 <= min_price <= max_price <= 10**30 | "price bounds" |
set_ratio_tolerance | ratio_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 beforeblock.timestamp),MAX_FUTURE_US = 6_000_000(6 s afterblock.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
| Signature | Mutability | Access | Notes |
|---|---|---|---|
deliver_report(_update: Bytes[301]) | payable, @nonreentrant | Anyone | Send 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) | view | Anyone | Unverified decode for off-chain quotes only. Checks format, _channel ("channel"), and _feed_id ("feed"). Never use for state changes. |
verification_fee() -> uint256 | view | Anyone | Returns PythLazer(verifier).verification_fee() in wei. |
set_verifier(_verifier: address) | nonpayable | Owner | Reverts "verifier" if not a contract; preserves stored reports. Emits SetVerifier. |
Admission rules and byte layout
deliver_report(_update) enforces:
msg.value == verifier.verification_fee()("fee").verifier.verifyUpdate(_update, value=fee)returnssigner != address(0)("signer") andlen(_update) == 71 + len(payload)("update length").- Header checks
PAYLOAD_MAGIC("payload magic"),1 <= feed_count <= 8("feed count"), exact length14 + 27 * feed_count("payload length"), and each feed checks property headers (0x0300,0x04,0x0c01), uniquefeed_id("duplicate feed"), andobservation_us <= message_us("observation time"). - Both
message_usand every feed'sobservation_usmust lie within[now_us - 60_000_000, now_us + 6_000_000]("message ahead","message age","observation ahead","observation age"). - Feeds with
mantissa <= 0orexponentoutside[-18, 0]decode toprice = 0and are skipped; feeds withobservation_us <= latest[feed_id][channel].observation_usare skipped. Supported prices scale asmantissa * 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(...)(POOLonly,"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.
Related
- Fees and policies: Conceptual overview of swap fees and policy types.
- Arbitrage and oracle reports: End-to-end guide for delivering Pyth reports and quoting swaps.
- Core vault and AMM: How
LTandCryptopoolLPOracleinteract withCRYPTOPOOL. - Contract addresses: Live policy and
PythReportBankaddresses.