Verified contractExact
YBOraclizedPolicy
Address0xe28a23c5bfd057dd0ed398fa6bb9d33abb41c044
- Balance
0 ETH
- Transactions
2
- Compiler
vyper 0.4.3
- Same code
Only this contract
Details
- Compiler
- vyper 0.4.3+commit.bff19ea2
- Language
- vyper
- License
- Not stated
- Match
- Exactcreation code: yes, runtime code: yes
- Verified on Sourcify
- Created in block
- 26,414,193
- Creation transaction
- 0xb7a536b11e…76785e7cd0
6 files
- contracts/policies/YBOraclizedPolicy.vymain29.92 KB
- .venv/lib/python3.12/site-packages/snekmate/auth/ownable.vy3.1 KB
- .venv/lib/python3.12/site-packages/snekmate/utils/math.vy28.12 KB
- contracts/policies/modules/policy_math.vy6.56 KB
- contracts/policies/modules/pyth_reports.vy8.29 KB
- contracts/policies/modules/yb_lt_gate.vy7.62 KB
contracts/policies/YBOraclizedPolicy.vy
# pragma version 0.4.3
# pragma optimize gas
"""
@title YB Oraclized Policy
@notice Twocrypto policy for a YieldBasis market: swap fees priced off Pyth
Lazer reports at the market's crvUSD rate, a trend-gated dual-EMA
price_scale target, and an LT deposit ratio check.
Notable features are:
- A swap toward the report pays base_fee plus a share of its edge; every
other operation pays fallback_fee
- Optionally, coin1's price is the Pyth feed's times, or divided by, a
Curve pool's price_oracle basis, say WBTC/USD from BTC/USD and WBTC in
cbBTC
- get_target(), get_report(), get_fee_with_report() and
get_dy_with_report() share the pool hooks' code: at the same pool state
and time, a report in the bank gets what they show
@dev Port of the backtested `report_lean` policy (curve-fx-sim twocrypto-cpp,
policies/report_lean.hpp) plus yb-core's LTAdmissionPolicy gate. This
contract holds the pricing rules and the order of operations; three
modules in ./modules hold the rest:
pyth_reports coin1's USD report from a PythReportBank: feed,
Curve pool basis and price bounds
policy_math the pool math's get_p, the pool's swap for
get_dy_with_report, and the EMA
yb_lt_gate the LT deposit ratio check
FEE
A swap whose marginal price moves toward the reported price without
passing it pays base_fee plus `capture` of its edge at the report above
base_fee, at most fallback_fee. The discount fades into fallback_fee with
the square root of the report's age and is gone at relax_time.
CRVUSD RATE
Fees value the report in coin0 at the rate the market's LT reads: the
stablecoin aggregator behind the LevAMM's price oracle, as LT.set_amm
finds it, immutable in both. Its stored last_price() counts while at most
RATE_MAX_AGE old, else price(), the rate its price_w() would store. A rate
outside [MIN_RATE, MAX_RATE] prices no discount.
DRIVER
A fast and a slow EMA of an observed price, both with true half-lives. The
target follows the observation as far as the two EMAs disagree, and each
touch requests half the gap from price_scale to it, at most step_cap of
price_scale.
CALLERS
pool get_fee, get_price_scale, update_pool_state
anyone sync, views; reports are delivered to the bank
owner (YB DAO) set_policy_config, set_price_bounds, set_ratio_tolerance,
set_killed, ownership
emergency admin set_killed
UNITS
Fees in FEE_PRECISION (1e10 = 100%). Prices and EMAs have 18 decimals: a
report prices coin1 in USD (1e18 = $1). Fees value it in coin0 at the
crvUSD rate; the driver counts coin0 as one USD. Pyth times are
microseconds. A hook that returns 0 hands the pool its native fee or
price_scale target.
A RAMPS
A is cached at deployment and by sync(). During a ramp a swap re-solves D
before asking for the fee and pays fallback_fee; get_dy_with_report solves
the same D and quotes it too. Call sync() once the pool has checkpointed
its final A.
@license Copyright (c) Curve.Fi, 2026 - all rights reserved
@author curve.fi
"""
################################################################
# MODULES #
################################################################
from snekmate.auth import ownable
from .modules import policy_math as math # snekmate also has a math module
from .modules import pyth_reports
from .modules import yb_lt_gate as lt_gate
initializes: ownable
initializes: lt_gate
initializes: math
initializes: pyth_reports
exports: (
ownable.owner,
ownable.transfer_ownership,
ownable.renounce_ownership,
pyth_reports.BANK,
pyth_reports.FEED_ID,
pyth_reports.CHANNEL,
pyth_reports.BASIS_POOL,
pyth_reports.INVERT_BASIS,
pyth_reports.price_bounds,
lt_gate.AMM,
lt_gate.ratio_tolerance,
lt_gate.cached_supply,
lt_gate.amm_surplus,
)
################################################################
# CONSTANTS #
################################################################
N_COINS: constant(uint256) = 2
PRECISION: constant(uint256) = 10**18
FEE_PRECISION: constant(uint256) = 10**10 # Twocrypto fee units: 10**10 = 100%
MIN_FEE: constant(uint256) = 10**5 # Twocrypto MIN_FEE (0.1 bp): lower fees get clamped
# The pool steps price_scale one fifth of the way to the target (tweak_price)
TWEAK_PRICE_MULTIPLIER: constant(uint256) = 5
RATE_MAX_AGE: constant(uint256) = 14_400 # 4 hours
MIN_RATE: constant(uint256) = PRECISION // 2 # $0.50
MAX_RATE: constant(uint256) = 2 * PRECISION # $2
################################################################
# INTERFACES #
################################################################
interface Pool:
def A() -> uint256: view
def D() -> uint256: view
def coins(i: uint256) -> address: view
def price_scale() -> uint256: view # nonreentrant: reverts inside a pool operation
interface LevAMM:
def PRICE_ORACLE_CONTRACT() -> address: view
interface LPOracle:
def AGG() -> address: view
interface StableAggregator:
def price() -> uint256: view
def last_price() -> uint256: view
def last_timestamp() -> uint256: view
################################################################
# STRUCTS #
################################################################
struct FeeConfig:
base_fee: uint256 # FEE_PRECISION: floor of a discounted fee
capture: uint256 # PRECISION: share of the reported edge above base_fee
fallback_fee: uint256 # FEE_PRECISION: fee without a discount, and the cap
relax_time: uint256 # seconds: report age at which the discount is gone
struct DriverConfig:
fast_half_life: uint256 # seconds
slow_half_life: uint256 # seconds
trend_gate: uint256 # WAD: |fast / slow - 1| at which the target is the observed price
step_cap: uint256 # WAD: largest requested price_scale move per touch
report_lifetime: uint256 # seconds: report age below which the EMAs observe it; 0 never
struct PolicyConfig:
fee: FeeConfig
driver: DriverConfig
# Pool geometry as of the last callback or sync(); EMAs and spot as of the last
# callback. get_fee compares an operation's balances with it.
struct State:
last_update_ts: uint256 # block.timestamp of the last callback
fast_ema: uint256
slow_ema: uint256
price_scale: uint256
xp: uint256[N_COINS] # balances, coin1 scaled by price_scale
D: uint256
last_prices: uint256 # the pool's spot after the last callback's operation
################################################################
# EVENTS #
################################################################
event SetPolicyConfig:
config: PolicyConfig
event SetKilled:
is_killed: bool
################################################################
# STORAGE #
################################################################
POOL: public(immutable(address))
EMERGENCY_ADMIN: public(immutable(address))
AGGREGATOR: public(immutable(address)) # crvUSD in USD: the stablecoin aggregator LT reads
config: public(PolicyConfig)
is_killed: public(bool)
state: public(State) # state.xp[0] is the LT gate's stablecoin baseline
cached_A: public(uint256) # the pool's A as of deployment or the last sync()
################################################################
# CONSTRUCTOR #
################################################################
@deploy
def __init__(
pool: address,
amm: address,
bank: address,
feed_id: uint32,
channel: uint8,
basis_pool: address,
invert_basis: bool,
emergency_admin: address,
bounds: pyth_reports.PriceBounds,
config: PolicyConfig,
ratio_tolerance: uint256,
):
"""
@notice The deployer becomes the owner
@param pool Twocrypto pool; coin0 is the LevAMM's stablecoin
@param amm LevAMM that holds the pool's LP as collateral
@param bank PythReportBank that stores the reports
@param feed_id Pyth Lazer feed of coin1/USD, or of the asset it wraps
@param channel Pyth Lazer channel of the reports this policy reads
@param basis_pool Curve stableswap-ng pool whose price_oracle(0) prices
coin1 in the feed's asset, or its inverse; 0 for none
@param invert_basis True when price_oracle(0) prices the feed's asset in coin1
@param emergency_admin May kill and revive the policy, as may the owner
@param bounds Initial price bounds
@param config Initial policy config
@param ratio_tolerance Initial LT gate tolerance, WAD
"""
assert pool != empty(address), "pool=0"
assert emergency_admin != empty(address), "emergency admin=0"
# Checks the market: one pool and LevAMM, coin0 unscaled, no admin fee
lt_gate.__init__(pool, amm, ratio_tolerance)
math.__init__(pool)
pyth_reports.__init__(
bank, feed_id, channel, basis_pool, invert_basis, staticcall Pool(pool).coins(1), bounds
)
aggregator: address = staticcall LPOracle(staticcall LevAMM(amm).PRICE_ORACLE_CONTRACT()).AGG()
rate: uint256 = staticcall StableAggregator(aggregator).price() # reverts unless it is one
ownable.__init__()
POOL = pool
EMERGENCY_ADMIN = emergency_admin
AGGREGATOR = aggregator
self.cached_A = staticcall Pool(pool).A()
self._set_policy_config(config)
################################################################
# POOL HOOKS #
################################################################
@external
@view
def get_fee(xp: uint256[N_COINS]) -> uint256:
"""
@notice Fee of the pool operation in progress: a swap is priced against the
bank's report (see _get_fee), anything else pays fallback_fee
@param xp Pool balances after the operation and before its fee, coin1 scaled
by price_scale
@return FEE_PRECISION fee, or 0 for the pool's native fee while killed
"""
if self.is_killed:
return 0
old_xp: uint256[N_COINS] = self.state.xp
# Only a swap can earn a discount: anything else skips the bank
if not self._is_swap(xp, old_xp):
return self.config.fee.fallback_fee
relax_time_us: uint256 = self.config.fee.relax_time * 1_000_000
report: pyth_reports.Report = pyth_reports._stored_report(relax_time_us)
return self._get_fee(xp, old_xp, 0, report.asset_price, report.age_us)
@external
@view
def get_price_scale() -> uint256:
"""
@notice Twocrypto's price_scale target, or 0 for the native target before
attachment or while killed
@dev The pool steps a fifth of the way to it, so this is price_scale plus
five times half the gap to get_target(), at most step_cap of
price_scale; config bounds keep the request within 5 * 60 bp = 3%. The
pool's oracle clamp, step limits and profit gate still apply. The pool
asks only in its first tweak_price at a new timestamp that passes its
profit test.
"""
if self.is_killed:
return 0
snapshot: State = self.state
scale: uint256 = snapshot.price_scale
if scale == 0:
return 0
target: uint256 = self._target(snapshot)
move: uint256 = min(
(max(target, scale) - min(target, scale)) // 2,
scale * self.config.driver.step_cap // PRECISION,
)
if target >= scale:
return scale + TWEAK_PRICE_MULTIPLIER * move
return scale - TWEAK_PRICE_MULTIPLIER * move
@external
def update_pool_state(
xp: uint256[N_COINS],
price_scale: uint256,
price_oracle: uint256,
last_prices: uint256,
_virtual_price: uint256,
_xcp_profit: uint256,
D: uint256,
_oracle_timestamp: uint256,
):
"""
@notice Pool callback after every operation, with its post-operation state:
gate LT deposits, settle the EMAs and store the snapshot, whose spot
the next touch observes
@dev A balanced removal calls back best-effort with 300k gas: if this fails,
the pool carries on with a stale snapshot when it had at least 500k gas
before the call, and reverts otherwise. Until sync(), the LT gate can
then miss one deposit (see yb_lt_gate).
"""
assert msg.sender == POOL, "auth!"
snapshot: State = self.state
# Gate first, against the previous snapshot: a revert unwinds an LT deposit
if not self.is_killed:
lt_gate._update(xp[0], snapshot.xp[0])
# The attachment callback seeds both EMAs with the pool's price_oracle
fast: uint256 = price_oracle
slow: uint256 = price_oracle
if snapshot.price_scale != 0:
fast = snapshot.fast_ema
slow = snapshot.slow_ema
# Later touches of a block keep the EMAs and skip the observation
if block.timestamp != snapshot.last_update_ts:
fast, slow = self._project_emas(snapshot, self._observation(snapshot))
self.state = State(
last_update_ts=block.timestamp,
fast_ema=fast,
slow_ema=slow,
price_scale=price_scale,
xp=xp,
D=D,
last_prices=last_prices,
)
################################################################
# PERMISSIONLESS FUNCTIONS #
################################################################
@external
def sync():
"""
@notice Re-read the pool's A, the fee snapshot's geometry and the LT gate's
baselines; the EMAs wait for the next callback. Anyone may call:
after a ramp's final pool checkpoint, a failed balanced-removal
callback, or an LP gift to the LevAMM.
"""
self._sync()
################################################################
# VIEW FUNCTIONS #
################################################################
@external
@view
def get_target() -> uint256:
"""
@notice Where the driver steers price_scale: the trend-gated target in USD
per coin1 (crvUSD at $1), before get_price_scale's capped half-gap
step; 0 while killed or before attachment
"""
if self.is_killed:
return 0
snapshot: State = self.state
if snapshot.price_scale == 0:
return 0
return self._target(snapshot)
@external
@view
def get_emas() -> uint256[2]:
"""
@notice [fast EMA, slow EMA] of the driver projected to now, in USD per coin1;
[0, 0] before attachment
"""
snapshot: State = self.state
if snapshot.price_scale == 0:
return [0, 0]
if block.timestamp == snapshot.last_update_ts: # as the callback settles them
return [snapshot.fast_ema, snapshot.slow_ema]
fast: uint256 = 0
slow: uint256 = 0
fast, slow = self._project_emas(snapshot, self._observation(snapshot))
return [fast, slow]
@external
@view
def get_report() -> (uint256, uint256, uint256):
"""
@notice The bank's newest report as the policy prices it, at any age
@return (coin1 in USD with this block's basis, coin1 in coin0 at this
block's crvUSD rate, the feed's observation time in us). Prices are
0 when the report is absent or the policy killed; the coin0 price
also when the rate is out of bounds. Fees use it younger than
relax_time, the driver younger than report_lifetime.
"""
if self.is_killed:
return 0, 0, 0
report: pyth_reports.Report = pyth_reports._stored_report(max_value(uint256))
if report.asset_price == 0:
return 0, 0, report.observation_us
return (
report.asset_price,
self._coin0_price(report.asset_price),
report.observation_us,
)
@external
@view
def get_fee_with_report(
xp: uint256[N_COINS], feed_price: uint256, report_age_us: uint256
) -> uint256:
"""
@notice get_fee(xp) with a hypothetical report of this Pyth feed price in
USD (1e18 = $1, before the basis) observed report_age_us
microseconds ago; pass age 0 for an observation after the block.
This block's basis, price bounds and crvUSD rate apply, as to a
report in the bank. Nothing checks a signature or the bank's
delivery window.
"""
return self._fee_with_report(xp, 0, feed_price, report_age_us)
@external
@view
def get_dy_with_report(
i: uint256, j: uint256, dx: uint256, feed_price: uint256, report_age_us: uint256
) -> uint256:
"""
@notice pool.get_dy(i, j, dx) with a hypothetical report of this Pyth feed
price in USD (1e18 = $1, before the basis) observed report_age_us
microseconds ago; pass age 0 for an observation after the block.
This block's basis, price bounds and crvUSD rate apply, as to a
report in the bank. Nothing checks a signature or the bank's
delivery window.
"""
dy: uint256 = 0
xp: uint256[N_COINS] = empty(uint256[N_COINS])
D: uint256 = 0
dy, xp, D = math._get_dy_nofee(i, j, dx)
return math._apply_fee(dy, xp, self._fee_with_report(xp, D, feed_price, report_age_us))
################################################################
# OWNER FUNCTIONS #
################################################################
@external
def set_policy_config(config: PolicyConfig):
"""
@notice Replace the whole policy config. Owner only.
@dev No EMA checkpoint: new half-lives apply to the whole interval since the
last touch, and raising relax_time or report_lifetime can revive a
bank report.
"""
ownable._check_owner()
self._set_policy_config(config)
@external
def set_price_bounds(bounds: pyth_reports.PriceBounds):
"""
@notice Set the sanity bounds on coin1's USD price. Owner only.
@dev Bounds apply at every use of a report, the bank's current record
included.
"""
ownable._check_owner()
pyth_reports._set_price_bounds(bounds)
@external
def set_ratio_tolerance(ratio_tolerance: uint256):
"""@notice Set the LT gate's tolerance, WAD, at most 10 bp. Owner only."""
ownable._check_owner()
lt_gate._set_ratio_tolerance(ratio_tolerance)
@external
def set_killed(is_killed: bool):
"""
@notice Kill (True) or revive the policy. Owner or emergency admin.
@dev While killed, get_fee and get_price_scale return 0 (the pool's native
fee and target), the bank, basis pool and aggregator are not read, and
the LT gate is off, external reads included. Callbacks still settle the
EMAs, on the pool's spot. Neither killing nor reviving touches reports
or calls the bank. Reviving calls sync() for the LT gate's baselines,
so a bank report still young enough counts again at once.
"""
assert msg.sender == EMERGENCY_ADMIN or msg.sender == ownable.owner, "access"
if not is_killed:
self._sync()
self.is_killed = is_killed
log SetKilled(is_killed=is_killed)
################################################################
# INTERNAL FUNCTIONS #
################################################################
# ---------------------------- Fee ----------------------------
@internal
@view
def _get_fee(
xp: uint256[N_COINS],
old_xp: uint256[N_COINS],
quote_D: uint256,
asset_price: uint256,
report_age_us: uint256,
) -> uint256:
"""
@dev The fee of a swap from the snapshot's balances old_xp to xp (see
_is_swap) against a report of asset_price in USD report_age_us old,
valued in coin0 at this block's crvUSD rate. Callers pass price 0 for
no report, including one relax_time old or older.
@param quote_D The swap's D: 0 for the pool's stored one (the hook), a
quote's own otherwise
"""
fallback_fee: uint256 = self.config.fee.fallback_fee
if asset_price == 0:
return fallback_fee
# The swap's D must be the snapshot's. It is not before attachment, after a
# failed best-effort removal callback, and usually in a swap during an A
# ramp, which re-solves D first; a quote passes the D it solved.
D: uint256 = self.state.D
execution_D: uint256 = quote_D
if execution_D == 0:
execution_D = staticcall Pool(POOL).D()
if D == 0 or execution_D != D:
return fallback_fee
report_price: uint256 = self._coin0_price(asset_price)
if report_price == 0:
return fallback_fee
price_scale: uint256 = self.state.price_scale
coin_in: uint256 = 0 if xp[0] > old_xp[0] else 1
edge: uint256 = self._reported_edge(xp, old_xp, price_scale, report_price, coin_in)
if edge == 0:
return fallback_fee
fee: uint256 = self._reported_fee(self.config.fee, edge, report_age_us)
if fee < fallback_fee and self._is_corrective(
xp, old_xp, D, self.cached_A, price_scale, report_price, coin_in
):
return fee
return fallback_fee
@internal
@pure
def _is_swap(xp: uint256[N_COINS], old_xp: uint256[N_COINS]) -> bool:
"""@dev One balance rose and the other fell: only a swap can earn a discount."""
return (xp[0] > old_xp[0] and xp[1] < old_xp[1]) or (xp[0] < old_xp[0] and xp[1] > old_xp[1])
@internal
@pure
def _reported_edge(
xp: uint256[N_COINS],
old_xp: uint256[N_COINS],
price_scale: uint256,
report_price: uint256,
coin_in: uint256,
) -> uint256:
"""
@dev The swap's edge at the report, 1 - input value / output value with both
legs valued in coin0, rounded up in fee units; 0 when the input is worth
at least the output. A coin1 amount in xp times report_price /
price_scale is its value at the report.
"""
coin_out: uint256 = 1 - coin_in
input_value: uint256 = xp[coin_in] - old_xp[coin_in]
output_value: uint256 = old_xp[coin_out] - xp[coin_out]
if coin_in == 1:
input_value = input_value * report_price // price_scale
else:
output_value = output_value * report_price // price_scale
if input_value >= output_value:
return 0
return FEE_PRECISION - input_value * FEE_PRECISION // output_value
@internal
@pure
def _reported_fee(fee: FeeConfig, reported_edge: uint256, report_age_us: uint256) -> uint256:
"""
@dev (1 - w) * fresh + w * fallback with w = sqrt(age / relax_time), computed
as fresh + sqrt((fallback - fresh)**2 * age / relax_time). The caller
keeps report_age_us below relax_time.
"""
excess_edge: uint256 = reported_edge - min(reported_edge, fee.base_fee)
fresh_fee: uint256 = min(
fee.fallback_fee, fee.base_fee + fee.capture * excess_edge // PRECISION
)
if report_age_us == 0 or fresh_fee == fee.fallback_fee:
return fresh_fee
# The floored root plus one fee unit never understates the surcharge, and
# age < relax_time keeps the fee at most fallback_fee
relax_time_us: uint256 = fee.relax_time * 1_000_000
discount: uint256 = fee.fallback_fee - fresh_fee
return fresh_fee + isqrt(discount * discount * report_age_us // relax_time_us) + 1
@internal
@pure
def _is_corrective(
xp: uint256[N_COINS],
old_xp: uint256[N_COINS],
D: uint256,
A: uint256,
price_scale: uint256,
report_price: uint256,
coin_in: uint256,
) -> bool:
"""@dev The marginal price moves toward the report and does not pass it."""
# An emptied balance has no marginal price
if xp[0] == 0 or xp[1] == 0:
return False
A_gamma: uint256[N_COINS] = [A, 0]
# Marginal prices times price_scale are coin0 per coin1, like report_price
p_before: uint256 = math._get_p(old_xp, D, A_gamma) * price_scale // PRECISION
p_after: uint256 = math._get_p(xp, D, A_gamma) * price_scale // PRECISION
if coin_in == 0:
return p_before < p_after and p_after <= report_price
return p_before > p_after and p_after >= report_price
@internal
@view
def _coin0_price(usd_price: uint256) -> uint256:
"""
@dev usd_price (18 decimals) in crvUSD at this block's rate, rounded down,
or 0 when that rate is out of bounds
"""
rate: uint256 = 0
if block.timestamp <= staticcall StableAggregator(AGGREGATOR).last_timestamp() + RATE_MAX_AGE:
rate = staticcall StableAggregator(AGGREGATOR).last_price()
else:
rate = staticcall StableAggregator(AGGREGATOR).price()
if rate < MIN_RATE or rate > MAX_RATE:
return 0
return usd_price * PRECISION // rate
# --------------------------- Driver --------------------------
@internal
@view
def _target(snapshot: State) -> uint256:
"""
@dev The trend-gated target of the EMAs projected to now: fast + w *
(observed - fast) with w = min(1, |fast / slow - 1| / trend_gate), or
fast when trend_gate is 0. slow > 0: the EMAs are convex mixes of
bounded positive prices.
"""
observed: uint256 = self._observation(snapshot)
fast: uint256 = 0
slow: uint256 = 0
fast, slow = self._project_emas(snapshot, observed)
trend_gate: uint256 = self.config.driver.trend_gate
if trend_gate == 0:
return fast
trend: uint256 = (max(fast, slow) - min(fast, slow)) * PRECISION // slow
if trend >= trend_gate:
return observed
if observed >= fast:
return fast + (observed - fast) * trend // trend_gate
return fast - (fast - observed) * trend // trend_gate
@internal
@view
def _project_emas(snapshot: State, observation: uint256) -> (uint256, uint256):
dt: uint256 = block.timestamp - snapshot.last_update_ts
if dt == 0: # later touches of a block keep the EMAs
return snapshot.fast_ema, snapshot.slow_ema
return (
math._ema(snapshot.fast_ema, observation, dt, self.config.driver.fast_half_life),
math._ema(snapshot.slow_ema, observation, dt, self.config.driver.slow_half_life),
)
@internal
@view
def _observation(snapshot: State) -> uint256:
"""
@dev What the EMAs and the target observe, bounded to [price_scale / 2,
2 * price_scale]: the report while younger than report_lifetime
(separate from the fee's relax_time) and the policy is live, else the
pool's spot after the previous callback's operation, as in the pool's
own EMA, so a touch cannot steer them with its own trade.
"""
price: uint256 = 0
if not self.is_killed:
lifetime_us: uint256 = self.config.driver.report_lifetime * 1_000_000
price = pyth_reports._stored_report(lifetime_us).asset_price
if price == 0:
price = snapshot.last_prices
return min(max(price, snapshot.price_scale // 2), 2 * snapshot.price_scale)
# -------------------------- Quotes ---------------------------
@internal
@view
def _fee_with_report(
xp: uint256[N_COINS], quote_D: uint256, feed_price: uint256, report_age_us: uint256
) -> uint256:
"""
@dev get_fee(xp) for a hypothetical report of feed_price (before the basis)
report_age_us old: 0 while killed, fallback_fee for a non-swap or a
report relax_time old or older; only a usable report reads the basis
pool. quote_D as for _get_fee.
"""
if self.is_killed:
return 0
old_xp: uint256[N_COINS] = self.state.xp
# As get_fee: against a stale snapshot a quote's swap may not look like one
if not self._is_swap(xp, old_xp):
return self.config.fee.fallback_fee
price: uint256 = 0
if feed_price != 0 and report_age_us < self.config.fee.relax_time * 1_000_000:
price = pyth_reports._coin1_price(feed_price)
return self._get_fee(xp, old_xp, quote_D, price, report_age_us)
# ------------------------ Config, sync -----------------------
@internal
def _set_policy_config(config: PolicyConfig):
fee: FeeConfig = config.fee
assert fee.base_fee >= MIN_FEE and fee.base_fee <= fee.fallback_fee, "base fee"
assert fee.fallback_fee <= FEE_PRECISION // 10, "fallback fee" # 10%
assert fee.capture <= PRECISION, "capture"
assert fee.relax_time > 0 and fee.relax_time <= 3_600, "relax time" # 1 hour
driver: DriverConfig = config.driver
# Half-lives from 10 minutes to a week, fast at most slow
assert (
driver.fast_half_life >= 600 and driver.fast_half_life <= driver.slow_half_life
), "fast half-life"
assert driver.slow_half_life <= 604_800, "slow half-life"
assert driver.trend_gate <= PRECISION // 10, "trend gate" # 10%
# Up to 60 bp per touch: a requested gap of at most 3% of price_scale
assert driver.step_cap > 0 and driver.step_cap <= 60 * PRECISION // 10_000, "step cap"
assert driver.report_lifetime <= 14_400, "report lifetime" # 4 hours
self.config = config
log SetPolicyConfig(config=config)
@internal
def _sync():
# price_scale() is nonreentrant: this reverts inside a pool operation
price_scale: uint256 = staticcall Pool(POOL).price_scale()
assert price_scale > 0, "pool uninitialized"
self.cached_A = staticcall Pool(POOL).A()
# Before attachment, leave the snapshot and the gate's supply for the
# attachment callback to seed together
attached: bool = self.state.price_scale != 0
if attached:
self.state.xp = math._xp(price_scale)
self.state.D = staticcall Pool(POOL).D()
self.state.price_scale = price_scale
lt_gate._sync(attached)
.venv/lib/python3.12/site-packages/snekmate/auth/ownable.vy
# pragma version ~=0.4.3
# pragma nonreentrancy off
"""
@title Owner-Based Access Control Functions
@custom:contract-name ownable
@license GNU Affero General Public License v3.0 only
@author pcaversaccio
@notice These functions can be used to implement a basic access
control mechanism, where there is an account (an owner)
that can be granted exclusive access to specific functions.
By default, the owner account will be the one that deploys
the contract. This can later be changed with `transfer_ownership`.
An exemplary integration can be found in the ERC-20 implementation here:
https://github.com/pcaversaccio/snekmate/blob/main/src/snekmate/tokens/erc20.vy.
The implementation is inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol.
"""
# @dev Returns the address of the current owner.
# @notice If you declare a variable as `public`,
# Vyper automatically generates an `external`
# getter function for the variable.
owner: public(address)
# @dev Emitted when the ownership is transferred
# from `previous_owner` to `new_owner`.
event OwnershipTransferred:
previous_owner: indexed(address)
new_owner: indexed(address)
@deploy
@payable
def __init__():
"""
@dev To omit the opcodes for checking the `msg.value`
in the creation-time EVM bytecode, the constructor
is declared as `payable`.
@notice The `owner` role will be assigned to
the `msg.sender`.
"""
self._transfer_ownership(msg.sender)
@external
def transfer_ownership(new_owner: address):
"""
@dev Transfers the ownership of the contract
to a new account `new_owner`.
@notice Note that this function can only be
called by the current `owner`. Also,
the `new_owner` cannot be the zero address.
@param new_owner The 20-byte address of the new owner.
"""
self._check_owner()
assert new_owner != empty(address), "ownable: new owner is the zero address"
self._transfer_ownership(new_owner)
@external
def renounce_ownership():
"""
@dev Leaves the contract without an owner.
@notice Renouncing ownership will leave the
contract without an owner, thereby
removing any functionality that is
only available to the owner.
"""
self._check_owner()
self._transfer_ownership(empty(address))
@internal
def _check_owner():
"""
@dev Throws if the sender is not the owner.
"""
assert msg.sender == self.owner, "ownable: caller is not the owner"
@internal
def _transfer_ownership(new_owner: address):
"""
@dev Transfers the ownership of the contract
to a new account `new_owner`.
@notice This is an `internal` function without
access restriction.
@param new_owner The 20-byte address of the new owner.
"""
old_owner: address = self.owner
self.owner = new_owner
log OwnershipTransferred(previous_owner=old_owner, new_owner=new_owner)
.venv/lib/python3.12/site-packages/snekmate/utils/math.vy
# pragma version ~=0.4.3
# pragma nonreentrancy off
"""
@title Standard Mathematical Utility Functions
@custom:contract-name math
@license GNU Affero General Public License v3.0 only
@author pcaversaccio
@custom:coauthor bout3fiddy
@notice These functions implement standard mathematical utility
functions that are missing in the Vyper language. If a
function is inspired by an existing implementation, it
is properly referenced in the function docstring. The
following functions have been added for convenience:
- `_uint256_average` (`internal` `pure` function),
- `_int256_average` (`internal` `pure` function),
- `_ceil_div` (`internal` `pure` function),
- `_signum` (`internal` `pure` function),
- `_mul_div` (`internal` `pure` function),
- `_log2` (`internal` `pure` function),
- `_log10` (`internal` `pure` function),
- `_log256` (`internal` `pure` function),
- `_wad_ln` (`internal` `pure` function),
- `_wad_exp` (`internal` `pure` function),
- `_cbrt` (`internal` `pure` function),
- `_wad_cbrt` (`internal` `pure` function).
"""
@deploy
@payable
def __init__():
"""
@dev To omit the opcodes for checking the `msg.value`
in the creation-time EVM bytecode, the constructor
is declared as `payable`.
"""
pass
@internal
@pure
def _uint256_average(x: uint256, y: uint256) -> uint256:
"""
@dev Returns the average of two 32-byte unsigned integers.
@notice Note that the result is rounded towards zero. For
more details on finding the average of two unsigned
integers without an overflow, please refer to:
https://devblogs.microsoft.com/oldnewthing/20220207-00/?p=106223.
@param x The first 32-byte unsigned integer of the data set.
@param y The second 32-byte unsigned integer of the data set.
@return uint256 The 32-byte average (rounded towards zero) of
`x` and `y`.
"""
return unsafe_add(x & y, (x ^ y) >> 1)
@internal
@pure
def _int256_average(x: int256, y: int256) -> int256:
"""
@dev Returns the average of two 32-byte signed integers.
@notice Note that the result is rounded towards infinity.
For more details on finding the average of two signed
integers without an overflow, please refer to:
https://patents.google.com/patent/US6007232A/en.
@param x The first 32-byte signed integer of the data set.
@param y The second 32-byte signed integer of the data set.
@return int256 The 32-byte average (rounded towards infinity)
of `x` and `y`.
"""
return unsafe_add(unsafe_add(x >> 1, y >> 1), x & y & 1)
@internal
@pure
def _ceil_div(x: uint256, y: uint256) -> uint256:
"""
@dev Calculates "ceil(x / y)" for any strictly positive `y`.
@notice The implementation is inspired by OpenZeppelin's
implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte numerator.
@param y The 32-byte denominator.
@return uint256 The 32-byte rounded up result of "x/y".
"""
assert y != empty(uint256), "math: ceil_div division by zero"
# Due to a known compiler bug (https://github.com/vyperlang/vyper/issues/3480),
# we use `0` instead of `empty(uint256)` as return value.
return 0 if (x == empty(uint256)) else unsafe_add(unsafe_div(x - 1, y), 1)
@internal
@pure
def _signum(x: int256) -> int256:
"""
@dev Returns the indication of the sign of a 32-byte signed integer.
@notice The function returns `-1` if `x < 0`, `0` if `x == 0`, and `1`
if `x > 0`. For more details on finding the sign of a signed
integer, please refer to:
https://graphics.stanford.edu/~seander/bithacks.html#CopyIntegerSign.
@param x The 32-byte signed integer variable.
@return int256 The 32-byte sign indication (`1`, `0`, or `-1`) of `x`.
"""
return unsafe_sub(convert((x > empty(int256)), int256), convert((x < empty(int256)), int256))
@internal
@pure
def _mul_div(x: uint256, y: uint256, denominator: uint256, roundup: bool) -> uint256:
"""
@dev Calculates "(x * y) / denominator" in 512-bit precision,
following the selected rounding direction.
@notice The implementation is inspired by Remco Bloemen's
implementation under the MIT license here:
https://xn--2-umb.com/21/muldiv.
Furthermore, the rounding direction design pattern is
inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte multiplicand.
@param y The 32-byte multiplier.
@param denominator The 32-byte divisor.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# Handle division by zero.
assert denominator != empty(uint256), "math: mul_div division by zero"
# 512-bit multiplication "[prod1 prod0] = x * y".
# Compute the product "mod 2**256" and "mod 2**256 - 1".
# Then use the Chinese Remainder theorem to reconstruct
# the 512-bit result. The result is stored in two 256-bit
# variables, where: "product = prod1 * 2**256 + prod0".
mm: uint256 = uint256_mulmod(x, y, max_value(uint256))
# The least significant 256 bits of the product.
prod0: uint256 = unsafe_mul(x, y)
# The most significant 256 bits of the product.
prod1: uint256 = empty(uint256)
if mm < prod0:
prod1 = unsafe_sub(unsafe_sub(mm, prod0), 1)
else:
prod1 = unsafe_sub(mm, prod0)
# Handling of non-overflow cases, 256 by 256 division.
if prod1 == empty(uint256):
if roundup and uint256_mulmod(x, y, denominator) != empty(uint256):
# Calculate "ceil((x * y) / denominator)". The following
# line cannot overflow because we have the previous check
# "(x * y) % denominator != 0", which accordingly rules out
# the possibility of "x * y = 2**256 - 1" and `denominator == 1`.
return unsafe_add(unsafe_div(prod0, denominator), 1)
return unsafe_div(prod0, denominator)
# Ensure that the result is less than "2**256". Also,
# prevents that `denominator == 0`.
assert denominator > prod1, "math: mul_div overflow"
#######################
# 512 by 256 Division #
#######################
# Make division exact by subtracting the remainder
# from "[prod1 prod0]". First, compute remainder using
# the `uint256_mulmod` operation.
remainder: uint256 = uint256_mulmod(x, y, denominator)
# Second, subtract the 256-bit number from the 512-bit
# number.
if remainder > prod0:
prod1 = unsafe_sub(prod1, 1)
prod0 = unsafe_sub(prod0, remainder)
# Factor powers of two out of the denominator and calculate
# the largest power of two divisor of denominator. Always `>= 1`,
# unless the denominator is zero (which is prevented above),
# in which case `twos` is zero. For more details, please refer to:
# https://cs.stackexchange.com/q/138556.
twos: uint256 = unsafe_sub(empty(uint256), denominator) & denominator
# Divide denominator by `twos`.
denominator_div: uint256 = unsafe_div(denominator, twos)
# Divide "[prod1 prod0]" by `twos`.
prod0 = unsafe_div(prod0, twos)
# Flip `twos` such that it is "2**256 / twos". If `twos` is zero,
# it becomes one.
twos = unsafe_add(unsafe_div(unsafe_sub(empty(uint256), twos), twos), 1)
# Shift bits from `prod1` to `prod0`.
prod0 |= unsafe_mul(prod1, twos)
# Invert the denominator "mod 2**256". Since the denominator is
# now an odd number, it has an inverse modulo "2**256", so we have:
# "denominator * inverse = 1 mod 2**256". Calculate the inverse by
# starting with a seed that is correct for four bits. That is,
# "denominator * inverse = 1 mod 2**4".
inverse: uint256 = unsafe_mul(3, denominator_div) ^ 2
# Use Newton-Raphson iteration to improve accuracy. Thanks to Hensel's
# lifting lemma, this also works in modular arithmetic by doubling the
# correct bits in each step.
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**8".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**16".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**32".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**64".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**128".
inverse = unsafe_mul(inverse, unsafe_sub(2, unsafe_mul(denominator_div, inverse))) # Inverse "mod 2**256".
# Since the division is now exact, we can divide by multiplying
# with the modular inverse of the denominator. This returns the
# correct result modulo "2**256". Since the preconditions guarantee
# that the result is less than "2**256", this is the final result.
# We do not need to calculate the high bits of the result and
# `prod1` is no longer necessary.
result: uint256 = unsafe_mul(prod0, inverse)
if roundup and uint256_mulmod(x, y, denominator) != empty(uint256):
# Calculate "ceil((x * y) / denominator)". The following
# line uses intentionally checked arithmetic to prevent
# a theoretically possible overflow.
result += 1
return result
@internal
@pure
def _log2(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 2 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. The implementation
is inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log2(max_value(uint256)) < max_value(uint256)`.
if x >> 128 != empty(uint256):
x >>= 128
result = 128
if x >> 64 != empty(uint256):
x >>= 64
result = unsafe_add(result, 64)
if x >> 32 != empty(uint256):
x >>= 32
result = unsafe_add(result, 32)
if x >> 16 != empty(uint256):
x >>= 16
result = unsafe_add(result, 16)
if x >> 8 != empty(uint256):
x >>= 8
result = unsafe_add(result, 8)
if x >> 4 != empty(uint256):
x >>= 4
result = unsafe_add(result, 4)
if x >> 2 != empty(uint256):
x >>= 2
result = unsafe_add(result, 2)
if x >> 1 != empty(uint256):
result = unsafe_add(result, 1)
if roundup and (1 << result) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _log10(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 10 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. The implementation
is inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log10(max_value(uint256)) < max_value(uint256)`.
if x >= 10 ** 64:
x = unsafe_div(x, 10 ** 64)
result = 64
if x >= 10 ** 32:
x = unsafe_div(x, 10 ** 32)
result = unsafe_add(result, 32)
if x >= 10 ** 16:
x = unsafe_div(x, 10 ** 16)
result = unsafe_add(result, 16)
if x >= 10 ** 8:
x = unsafe_div(x, 10 ** 8)
result = unsafe_add(result, 8)
if x >= 10 ** 4:
x = unsafe_div(x, 10 ** 4)
result = unsafe_add(result, 4)
if x >= 10 ** 2:
x = unsafe_div(x, 10 ** 2)
result = unsafe_add(result, 2)
if x >= 10:
result = unsafe_add(result, 1)
if roundup and (10 ** result) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _log256(x: uint256, roundup: bool) -> uint256:
"""
@dev Returns the log in base 256 of `x`, following the selected
rounding direction.
@notice Note that it returns `0` if given `0`. Also, adding one to the
rounded down result gives the number of pairs of hex symbols
needed to represent `x` as a hex string. The implementation is
inspired by OpenZeppelin's implementation here:
https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/math/Math.sol.
@param x The 32-byte variable.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return uint256 The 32-byte calculation result.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
value: uint256 = x
result: uint256 = empty(uint256)
# The following lines cannot overflow because we have the well-known
# decay behaviour of `log256(max_value(uint256)) < max_value(uint256)`.
if x >> 128 != empty(uint256):
x >>= 128
result = 16
if x >> 64 != empty(uint256):
x >>= 64
result = unsafe_add(result, 8)
if x >> 32 != empty(uint256):
x >>= 32
result = unsafe_add(result, 4)
if x >> 16 != empty(uint256):
x >>= 16
result = unsafe_add(result, 2)
if x >> 8 != empty(uint256):
result = unsafe_add(result, 1)
if roundup and (1 << (result << 3)) < value:
result = unsafe_add(result, 1)
return result
@internal
@pure
def _wad_ln(x: int256) -> int256:
"""
@dev Calculates the natural logarithm of a signed integer with a
precision of 1e18.
@notice Note that it returns `0` if given `0`. Furthermore, this function
consumes about 1,400 to 1,650 gas units depending on the value
of `x`. The implementation is inspired by Remco Bloemen's
implementation under the MIT license here:
https://xn--2-umb.com/22/exp-ln.
@param x The 32-byte variable.
@return int256 The 32-byte calculation result.
"""
assert x >= empty(int256), "math: wad_ln undefined"
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(int256):
return empty(int256)
# We want to convert `x` from "10**18" fixed point to "2**96"
# fixed point. We do this by multiplying by "2**96 / 10**18".
# But since "ln(x * C) = ln(x) + ln(C)" holds, we can just do
# nothing here and add "ln(2**96 / 10**18)" at the end.
# Reduce the range of `x` to "(1, 2) * 2**96".
# Also remember that "ln(2**k * x) = k * ln(2) + ln(x)" holds.
k: int256 = unsafe_sub(convert(self._log2(convert(x, uint256), False), int256), 96)
# Note that to circumvent Vyper's safecast feature for the potentially
# negative expression `x <<= uint256(159 - k)`, we first convert the
# expression `x <<= uint256(159 - k)` to `bytes32` and subsequently
# to `uint256`. Remember that the EVM default behaviour is to use two's
# complement representation to handle signed integers.
x = convert(convert(convert(x << convert(unsafe_sub(159, k), uint256), bytes32), uint256) >> 159, int256)
# Evaluate using a "(8, 8)"-term rational approximation. Since `p` is monic,
# we will multiply by a scaling factor later.
p: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 3_273_285_459_638_523_848_632_254_066_296), x) >> 96,
24_828_157_081_833_163_892_658_089_445_524,
)
p = unsafe_add(unsafe_mul(p, x) >> 96, 43_456_485_725_739_037_958_740_375_743_393)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 11_111_509_109_440_967_052_023_855_526_967)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 45_023_709_667_254_063_763_336_534_515_857)
p = unsafe_sub(unsafe_mul(p, x) >> 96, 14_706_773_417_378_608_786_704_636_184_526)
p = unsafe_sub(unsafe_mul(p, x), 795_164_235_651_350_426_258_249_787_498 << 96)
# We leave `p` in the "2**192" base so that we do not have to scale it up
# again for the division. Note that `q` is monic by convention.
q: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 5_573_035_233_440_673_466_300_451_813_936), x) >> 96,
71_694_874_799_317_883_764_090_561_454_958,
)
q = unsafe_add(unsafe_mul(q, x) >> 96, 283_447_036_172_924_575_727_196_451_306_956)
q = unsafe_add(unsafe_mul(q, x) >> 96, 401_686_690_394_027_663_651_624_208_769_553)
q = unsafe_add(unsafe_mul(q, x) >> 96, 204_048_457_590_392_012_362_485_061_816_622)
q = unsafe_add(unsafe_mul(q, x) >> 96, 31_853_899_698_501_571_402_653_359_427_138)
q = unsafe_add(unsafe_mul(q, x) >> 96, 909_429_971_244_387_300_277_376_558_375)
# It is known that the polynomial `q` has no zeros in the domain.
# No scaling is required, as `p` is already "2**96" too large. Also,
# `r` is in the range "(0, 0.125) * 2**96" after the division.
r: int256 = unsafe_div(p, q)
# To finalise the calculation, we have to proceed with the following steps:
# - multiply by the scaling factor "s = 5.549...",
# - add "ln(2**96 / 10**18)",
# - add "k * ln(2)", and
# - multiply by "10**18 / 2**96 = 5**18 >> 78".
# In order to perform the most gas-efficient calculation, we carry out all
# these steps in one expression.
return (
unsafe_add(
unsafe_add(
unsafe_mul(r, 1_677_202_110_996_718_588_342_820_967_067_443_963_516_166),
unsafe_mul(
k, 16_597_577_552_685_614_221_487_285_958_193_947_469_193_820_559_219_878_177_908_093_499_208_371
),
),
600_920_179_829_731_861_736_702_779_321_621_459_595_472_258_049_074_101_567_377_883_020_018_308,
)
>> 174
)
@internal
@pure
def _wad_exp(x: int256) -> int256:
"""
@dev Calculates the natural exponential function of a signed integer with
a precision of 1e18.
@notice Note that this function consumes about 810 gas units. The implementation
is inspired by Remco Bloemen's implementation under the MIT license here:
https://xn--2-umb.com/22/exp-ln.
@param x The 32-byte variable.
@return int256 The 32-byte calculation result.
"""
# If the result is `< 1`, we return zero. This happens when we have the following:
# "x <= (log(1e-18) * 1e18) ~ -4.15e19".
if x <= -41_446_531_673_892_822_313:
return empty(int256)
# When the result is "> (2**255 - 1) / 1e18" we cannot represent it as a signed integer.
# This happens when "x >= floor(log((2**255 - 1) / 1e18) * 1e18) ~ 135".
assert x < 135_305_999_368_893_231_589, "math: wad_exp overflow"
# `x` is now in the range "(-42, 136) * 1e18". Convert to "(-42, 136) * 2**96" for higher
# intermediate precision and a binary base. This base conversion is a multiplication with
# "1e18 / 2**96 = 5**18 / 2**78".
x = unsafe_div(x << 78, 5 ** 18)
# Reduce the range of `x` to "(-½ ln 2, ½ ln 2) * 2**96" by factoring out powers of two
# so that "exp(x) = exp(x') * 2**k", where `k` is a signer integer. Solving this gives
# "k = round(x / log(2))" and "x' = x - k * log(2)". Thus, `k` is in the range "[-61, 195]".
k: int256 = unsafe_add(unsafe_div(x << 96, 54_916_777_467_707_473_351_141_471_128), 2 ** 95) >> 96
x = unsafe_sub(x, unsafe_mul(k, 54_916_777_467_707_473_351_141_471_128))
# Evaluate using a "(6, 7)"-term rational approximation. Since `p` is monic,
# we will multiply by a scaling factor later.
y: int256 = unsafe_add(
unsafe_mul(unsafe_add(x, 1_346_386_616_545_796_478_920_950_773_328), x) >> 96,
57_155_421_227_552_351_082_224_309_758_442,
)
p: int256 = unsafe_add(
unsafe_mul(
unsafe_add(
unsafe_mul(unsafe_sub(unsafe_add(y, x), 94_201_549_194_550_492_254_356_042_504_812), y) >> 96,
28_719_021_644_029_726_153_956_944_680_412_240,
),
x,
),
4_385_272_521_454_847_904_659_076_985_693_276 << 96,
)
# We leave `p` in the "2**192" base so that we do not have to scale it up
# again for the division.
q: int256 = unsafe_add(
unsafe_mul(unsafe_sub(x, 2_855_989_394_907_223_263_936_484_059_900), x) >> 96,
50_020_603_652_535_783_019_961_831_881_945,
)
q = unsafe_sub(unsafe_mul(q, x) >> 96, 533_845_033_583_426_703_283_633_433_725_380)
q = unsafe_add(unsafe_mul(q, x) >> 96, 3_604_857_256_930_695_427_073_651_918_091_429)
q = unsafe_sub(unsafe_mul(q, x) >> 96, 14_423_608_567_350_463_180_887_372_962_807_573)
q = unsafe_add(unsafe_mul(q, x) >> 96, 26_449_188_498_355_588_339_934_803_723_976_023)
# The polynomial `q` has no zeros in the range because all its roots are complex.
# No scaling is required, as `p` is already "2**96" too large. Also,
# `r` is in the range "(0.09, 0.25) * 2**96" after the division.
r: int256 = unsafe_div(p, q)
# To finalise the calculation, we have to multiply `r` by:
# - the scale factor "s = ~6.031367120",
# - the factor "2**k" from the range reduction, and
# - the factor "1e18 / 2**96" for the base conversion.
# We do this all at once, with an intermediate result in "2**213" base,
# so that the final right shift always gives a positive value.
# Note that to circumvent Vyper's safecast feature for the potentially
# negative parameter value `r`, we first convert `r` to `bytes32` and
# subsequently to `uint256`. Remember that the EVM default behaviour is
# to use two's complement representation to handle signed integers.
return convert(
unsafe_mul(
convert(convert(r, bytes32), uint256), 3_822_833_074_963_236_453_042_738_258_902_158_003_155_416_615_667
)
>> convert(unsafe_sub(195, k), uint256),
int256,
)
@internal
@pure
def _cbrt(x: uint256, roundup: bool) -> uint256:
"""
@dev Calculates the cube root of an unsigned integer.
@notice Note that this function consumes about 1,600 to 1,800 gas units
depending on the value of `x` and `roundup`. The implementation is
inspired by Curve Finance's implementation under the MIT license here:
https://github.com/curvefi/tricrypto-ng/blob/main/contracts/main/CurveCryptoMathOptimized3.vy.
@param x The 32-byte variable from which the cube root is calculated.
@param roundup The Boolean variable that specifies whether
to round up or not. The default `False` is round down.
@return The 32-byte cube root of `x`.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
y: uint256 = unsafe_div(self._wad_cbrt(x), 10 ** 12)
if roundup and unsafe_mul(unsafe_mul(y, y), y) != x:
y = unsafe_add(y, 1)
return y
@internal
@pure
def _wad_cbrt(x: uint256) -> uint256:
"""
@dev Calculates the cube root of an unsigned integer with a precision
of 1e18.
@notice Note that this function consumes about 1,500 to 1,700 gas units
depending on the value of `x`. The implementation is inspired
by Curve Finance's implementation under the MIT license here:
https://github.com/curvefi/tricrypto-ng/blob/main/contracts/main/CurveCryptoMathOptimized3.vy.
@param x The 32-byte variable from which the cube root is calculated.
@return The 32-byte cubic root of `x` with a precision of 1e18.
"""
# For the special case `x == 0`, we already return `0` here in order
# not to iterate through the remaining code.
if x == empty(uint256):
return empty(uint256)
# Since this cube root is for numbers with base 1e18, we have to scale
# the input by 1e36 to increase the precision. This leads to an overflow
# for very large numbers. So we conditionally sacrifice precision.
value: uint256 = empty(uint256)
if x >= unsafe_mul(unsafe_div(max_value(uint256), 10 ** 36), 10 ** 18):
value = x
elif x >= unsafe_div(max_value(uint256), 10 ** 36):
value = unsafe_mul(x, 10 ** 18)
else:
value = unsafe_mul(x, 10 ** 36)
# Compute the binary logarithm of `value`.
log2x: uint256 = self._log2(value, False)
# If we divide log2x by 3, the remainder is "log2x % 3". So if we simply
# multiply "2**(log2x/3)" and discard the remainder to calculate our guess,
# the Newton-Raphson method takes more iterations to converge to a solution
# because it lacks this precision. A few more calculations now in order to
# do fewer calculations later:
# - "pow = log2(x) // 3" (the operator `//` means integer division),
# - "remainder = log2(x) % 3",
# - "initial_guess = 2**pow * cbrt(2)**remainder".
# Now substituting "2 = 1.26 ≈ 1,260 / 1,000", we get:
# - "initial_guess = 2**pow * 1,260**remainder // 1,000**remainder".
remainder: uint256 = log2x % 3
y: uint256 = unsafe_div(
unsafe_mul(pow_mod256(2, unsafe_div(log2x, 3)), pow_mod256(1_260, remainder)), pow_mod256(1_000, remainder)
)
# Since we have chosen good initial values for the cube roots, 7 Newton-Raphson
# iterations are just sufficient. 6 iterations would lead to non-convergences,
# and 8 would be one iteration too many. Without initial values, the iteration
# number can be up to 20 or more. The iterations are unrolled. This reduces the
# gas cost, but requires more bytecode.
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
y = unsafe_div(unsafe_add(unsafe_mul(2, y), unsafe_div(value, unsafe_mul(y, y))), 3)
# Since we scaled up, we have to scale down accordingly.
if x >= unsafe_mul(unsafe_div(max_value(uint256), 10 ** 36), 10 ** 18):
return unsafe_mul(y, 10 ** 12)
elif x >= unsafe_div(max_value(uint256), 10 ** 36):
return unsafe_mul(y, 10 ** 6)
return y
contracts/policies/modules/policy_math.vy
# pragma version 0.4.3
"""
@title Policy Math
@notice The arithmetic YBOraclizedPolicy uses but does not decide, in three
sections:
STABLESWAP MATH get_p, the pool math's marginal price
POOL QUOTE the pool's balances as it scales them, and its
swap and fee for get_dy_with_report
EMA an exponential moving average with a true
half-life
@dev Initialized with the pool for the quote section; the other two are pure.
Pools with StableswapMath only. Prices have 18 decimals, fees are in
FEE_PRECISION (1e10 = 100%).
@license Copyright (c) Curve.Fi, 2020 - 2026 - all rights reserved
@author curve.fi
"""
from snekmate.utils import math as snekmate_math
N_COINS: constant(uint256) = 2
PRECISION: constant(uint256) = 10**18
################################################################
# STABLESWAP MATH #
################################################################
# StableswapMath exposes get_p only as an external function. _get_p is copied
# line by line from contracts/main/StableswapMath.vy, which stays byte-identical
# to the deployed math.
A_MULTIPLIER: constant(uint256) = 10000
@internal
@pure
def _get_p(
_xp: uint256[N_COINS], _D: uint256, _A_gamma: uint256[N_COINS]
) -> uint256:
"""
@notice Calculates dx/dy.
@dev Output needs to be multiplied with price_scale to get the actual value.
@param _xp Balances of the pool.
@param _D Current value of D.
@param _A_gamma Amplification coefficient and gamma.
"""
# dx_0 / dx_1 only, however can have any number of coins in pool
ANN: uint256 = unsafe_mul(_A_gamma[0], N_COINS)
Dr: uint256 = unsafe_div(_D, N_COINS**N_COINS)
for i: uint256 in range(N_COINS):
Dr = Dr * _D // _xp[i]
xp0_A: uint256 = unsafe_div(ANN * _xp[0], A_MULTIPLIER)
return 10**18 * (xp0_A + unsafe_div(Dr * _xp[0], _xp[1])) // (xp0_A + Dr)
################################################################
# POOL QUOTE #
################################################################
# _get_dy_nofee is TwocryptoView._get_dy_nofee with the pool's state read
# directly and the pool's math and coin1 precision held as immutables. It
# returns the D it solved as well: during an A ramp the pool re-solves D before
# asking the policy for the fee, and a quote must hand the fee that same D. The
# policy prices the fee, and _apply_fee applies it as the pool does.
FEE_PRECISION: constant(uint256) = 10**10
interface Pool:
def A() -> uint256: view
def D() -> uint256: view
def balances(i: uint256) -> uint256: view
def price_scale() -> uint256: view
def precisions() -> uint256[N_COINS]: view
def POLICY() -> address: view
def MATH() -> Math: view
def future_A_gamma_time() -> uint256: view
def last_timestamp() -> uint256: view
def fee_calc(xp: uint256[N_COINS]) -> uint256: view
interface Math:
def get_y(
ANN: uint256, gamma: uint256, x: uint256[N_COINS], D: uint256, i: uint256
) -> uint256[2]: view
def newton_D(
ANN: uint256, gamma: uint256, x_unsorted: uint256[N_COINS], K0_prev: uint256
) -> uint256: view
POOL: immutable(address)
MATH: immutable(Math) # the pool's math, immutable in the pool
PRECISION1: immutable(uint256) # the pool's coin1 precision; coin0's is 1
@deploy
def __init__(pool: address):
"""@param pool Twocrypto pool whose coin0 has precision 1"""
POOL = pool
MATH = staticcall Pool(pool).MATH()
PRECISION1 = (staticcall Pool(pool).precisions())[1]
@internal
@view
def _xp(price_scale: uint256) -> uint256[N_COINS]:
"""@dev The pool's balances as Twocrypto._xp scales them at price_scale."""
return [
staticcall Pool(POOL).balances(0),
staticcall Pool(POOL).balances(1) * PRECISION1 * price_scale // PRECISION,
]
@internal
@view
def _get_dy_nofee(i: uint256, j: uint256, dx: uint256) -> (uint256, uint256[N_COINS], uint256):
"""
@return (dy before the fee in coin j, the pool's balances after the swap and
before its fee with coin1 scaled by price_scale, the D the swap used)
"""
assert i != j and i < N_COINS and j < N_COINS, "coin index out of range"
# A detached policy no longer prices the pool's swaps
assert staticcall Pool(POOL).POLICY() == self, "not attached"
xp: uint256[N_COINS] = [staticcall Pool(POOL).balances(0), staticcall Pool(POOL).balances(1)]
price_scale: uint256 = staticcall Pool(POOL).price_scale()
A: uint256 = staticcall Pool(POOL).A()
# StableswapMath ignores gamma: 0 here
D: uint256 = staticcall Pool(POOL).D()
if staticcall Pool(POOL).future_A_gamma_time() > staticcall Pool(POOL).last_timestamp():
ramp_xp: uint256[N_COINS] = [xp[0], xp[1] * price_scale * PRECISION1 // PRECISION]
D = staticcall MATH.newton_D(A, 0, ramp_xp, 0)
xp[i] += dx
xp = [xp[0], xp[1] * price_scale * PRECISION1 // PRECISION]
y_out: uint256[2] = staticcall MATH.get_y(A, 0, xp, D, j)
assert y_out[0] < xp[j], "unsafe value for y"
dy: uint256 = xp[j] - y_out[0] - 1
xp[j] = y_out[0]
if j > 0:
dy = dy * PRECISION // price_scale // PRECISION1
return dy, xp, D
@internal
@view
def _apply_fee(dy: uint256, xp: uint256[N_COINS], fee: uint256) -> uint256:
"""
@dev dy less a policy fee, or less the pool's native fee at xp for 0, as
Twocrypto._fee applies them. The policy's fees are within the pool's
clamp to [MIN_FEE, 100%]: at least base_fee >= MIN_FEE, at most 10%.
"""
pool_fee: uint256 = fee
if fee == 0:
pool_fee = staticcall Pool(POOL).fee_calc(xp)
return dy - pool_fee * dy // FEE_PRECISION
################################################################
# EMA #
################################################################
LN2: constant(uint256) = 693_147_180_559_945_309
@internal
@pure
def _ema(ema: uint256, price: uint256, dt: uint256, half_life: uint256) -> uint256:
"""@dev ema moved toward price over dt seconds; half_life is in seconds."""
# alpha = exp(-ln(2) * dt / half_life): the parameter is a true half-life
alpha: uint256 = convert(
snekmate_math._wad_exp(-convert(dt * LN2 // half_life, int256)), uint256
)
return (price * (PRECISION - alpha) + ema * alpha) // PRECISION
contracts/policies/modules/pyth_reports.vy
# pragma version 0.4.3
"""
@title Pyth Reports
@notice coin1's USD price for a policy, from a PythReportBank's newest record
of a Pyth Lazer feed: optionally times a Curve pool's price_oracle
basis, within owner-set price bounds.
@dev The report is the bank's newest record of FEED_ID on CHANNEL, read when
used. With BASIS_POOL set (0 is off), coin1's price is the feed's times
that Curve stableswap-ng pool's price_oracle(0), or divided by it with
INVERT_BASIS: say WBTC/USD from BTC/USD and WBTC in cbBTC, cbBTC counting
as BTC. The basis is read live, and only for a report the caller can use:
present and younger than the caller's maximum age. The basis is capped to
move coin1's price at most 1% from the feed's. The report is absent when
the price is outside the bounds, which apply at every use. Its time is the
feed's observation.
The bank's verifier decides which prices are authentic. The basis pool's
price_oracle is an EMA of its own trades: moving it is accepted, and the
cap bounds what it can do. The policy checks its kill switch before
calling here, so a killed policy reads neither. Prices have 18 decimals
(1e18 = $1); Pyth times are microseconds.
@license Copyright (c) Curve.Fi, 2026 - all rights reserved
@author curve.fi
"""
################################################################
# CONSTANTS #
################################################################
PRECISION: constant(uint256) = 10**18
# Hard limits for the price bounds
MIN_REPORT_PRICE: constant(uint256) = 10**6 # $1e-12
MAX_REPORT_PRICE: constant(uint256) = 10**30 # $1e12
# coin1's price is the feed's times a basis capped to [MIN_BASIS, MAX_BASIS]: 1% at most
MIN_BASIS: constant(uint256) = 99 * PRECISION // 100
MAX_BASIS: constant(uint256) = 101 * PRECISION // 100
# Inverted, the basis is PRECISION**2 / price_oracle(0): the cap on price_oracle(0)
# itself, rounded inward
MIN_INVERTED_ORACLE: constant(uint256) = (PRECISION * PRECISION + MAX_BASIS - 1) // MAX_BASIS
MAX_INVERTED_ORACLE: constant(uint256) = PRECISION * PRECISION // MIN_BASIS
################################################################
# INTERFACES #
################################################################
interface ReportBank: # (price, observation_us)
def latest(feed_id: uint32, channel: uint8) -> (uint256, uint256): view
interface BasisPool: # Curve stableswap-ng: price_oracle(0) is coin1 in coin0
def coins(i: uint256) -> address: view
def price_oracle(i: uint256) -> uint256: view
################################################################
# STRUCTS #
################################################################
# Sanity bounds on coin1's USD price; a price outside is absent
struct PriceBounds:
min_price: uint256
max_price: uint256
struct Report:
asset_price: uint256 # coin1 in USD; 0 when absent
observation_us: uint256 # the feed's Pyth update time
age_us: uint256 # now less observation_us; 0 for an observation after the block
################################################################
# EVENTS #
################################################################
event SetPriceBounds:
bounds: PriceBounds
################################################################
# STORAGE #
################################################################
BANK: public(immutable(address)) # PythReportBank
FEED_ID: public(immutable(uint32)) # Pyth Lazer feed priced in USD; ids are stable
CHANNEL: public(immutable(uint8)) # 1 real_time, 2 fixed_rate@50ms, 3 @200ms, 4 @1000ms
BASIS_POOL: public(immutable(address)) # 0: none
INVERT_BASIS: public(immutable(bool)) # coin1 is the feed's price over price_oracle(0)
price_bounds: public(PriceBounds)
################################################################
# CONSTRUCTOR #
################################################################
@deploy
def __init__(
bank: address,
feed_id: uint32,
channel: uint8,
basis_pool: address,
invert_basis: bool,
coin1: address,
bounds: PriceBounds,
):
"""
@param bank PythReportBank that stores the reports
@param feed_id Pyth Lazer feed of coin1/USD, or of the asset it wraps
@param channel Pyth Lazer channel of the reports
@param basis_pool Curve stableswap-ng pool whose price_oracle(0) prices
coin1 in the feed's asset, or its inverse; 0 for none
@param invert_basis True when price_oracle(0) prices the feed's asset in coin1
@param coin1 The policy pool's coin1, which the basis pool must hold
@param bounds Initial price bounds
"""
assert bank.is_contract, "bank"
assert feed_id > 0, "feed id"
# The four channels Pyth Lazer defines (PythLazerStructs.Channel)
assert channel >= 1 and channel <= 4, "channel"
if basis_pool == empty(address):
assert not invert_basis, "invert basis"
else:
# The pool prices coin1 as its coin1, or inverted as its coin0. Near
# parity a wrong pool or orientation would pass any price check.
coin1_index: uint256 = 0 if invert_basis else 1
assert staticcall BasisPool(basis_pool).coins(coin1_index) == coin1, "basis coin"
# Rejects a pool without price_oracle(uint256); a depeg past the cap is
# capped, not refused
oracle: uint256 = staticcall BasisPool(basis_pool).price_oracle(0)
BANK = bank
FEED_ID = feed_id
CHANNEL = channel
BASIS_POOL = basis_pool
INVERT_BASIS = invert_basis
self._set_price_bounds(bounds)
################################################################
# INTERNAL FUNCTIONS #
################################################################
@internal
@view
def _stored_report(max_age_us: uint256) -> Report:
"""
@dev The bank's record as a report: price 0 when the record is empty, at
least max_age_us old, or rejected by _coin1_price. The first two come
first, so a report the caller cannot use never reads the basis pool.
"""
price: uint256 = 0
observation_us: uint256 = 0
price, observation_us = staticcall ReportBank(BANK).latest(FEED_ID, CHANNEL)
time_us: uint256 = block.timestamp * 1_000_000
age_us: uint256 = time_us - min(time_us, observation_us)
if price == 0 or age_us >= max_age_us:
return Report(asset_price=0, observation_us=observation_us, age_us=age_us)
return Report(
asset_price=self._coin1_price(price), observation_us=observation_us, age_us=age_us
)
@internal
@view
def _coin1_price(feed_price: uint256) -> uint256:
"""
@dev coin1 in USD from the feed's price: times the capped price_oracle(0),
or over it with INVERT_BASIS, rounded down once; 0 when the result is
outside the price bounds
"""
price: uint256 = feed_price
if BASIS_POOL != empty(address):
# Out of bounds whatever the basis, and the product could overflow. The
# bank's prices are below 2**123; a quote's price is anything.
if feed_price > max_value(uint256) // MAX_INVERTED_ORACLE:
return 0
oracle: uint256 = staticcall BasisPool(BASIS_POOL).price_oracle(0)
if INVERT_BASIS:
oracle = min(max(oracle, MIN_INVERTED_ORACLE), MAX_INVERTED_ORACLE)
price = feed_price * PRECISION // oracle
else:
oracle = min(max(oracle, MIN_BASIS), MAX_BASIS)
price = feed_price * oracle // PRECISION
bounds: PriceBounds = self.price_bounds
if price < bounds.min_price or price > bounds.max_price:
return 0
return price
@internal
def _set_price_bounds(bounds: PriceBounds):
assert (
MIN_REPORT_PRICE <= bounds.min_price
and bounds.min_price <= bounds.max_price
and bounds.max_price <= MAX_REPORT_PRICE
), "price bounds"
self.price_bounds = bounds
log SetPriceBounds(bounds=bounds)
contracts/policies/modules/yb_lt_gate.vy
# pragma version 0.4.3
"""
@title YB LT Gate
@notice Keeps LT deposits into a YieldBasis market's Twocrypto pool on the
LevAMM book's ratio. A policy initializes it, calls _update from its
pool callback and _sync from its sync(), and exports its getters.
@dev LT.deposit(assets, debt) lets the caller pick the debt, and a debt off the
LevAMM book's ratio is a fee-free trade against its holders. The fair
deposit has
debt == added_lp * old_debt / old_collateral
LT mints the LP to the LevAMM, the pool calls back, and only then does LT
book it: the LevAMM still reports the old book, and a revert unwinds the
deposit. added_lp is the growth of pool.user_supply(), and the debt the
growth of the pool's stablecoin balance, exact while the pool's admin fee
is zero (checked at deployment). Should governance set one, the deposit's
admin share goes unseen: an exact deposit can fail, and one can carry that
share of extra debt beyond the tolerance.
A balanced removal's callback is best-effort. If it fails, cached_supply
stays above the pool's supply, and until _sync an LT deposit that mints
less LP than that removal burned looks like an exit and goes unchecked.
After every successful update cached_supply equals pool.user_supply(), so
a keeper calls the policy's sync() whenever they differ while it is live.
@license Copyright (c) Curve.Fi, 2026 - all rights reserved
@author curve.fi
"""
################################################################
# CONSTANTS #
################################################################
PRECISION: constant(uint256) = 10**18
MAX_RATIO_TOLERANCE: constant(uint256) = PRECISION // 1000 # 10 bp
################################################################
# INTERFACES #
################################################################
interface Pool:
def admin_fee() -> uint256: view
def balanceOf(account: address) -> uint256: view
def coins(i: uint256) -> address: view
def precisions() -> uint256[2]: view
def user_supply() -> uint256: view
interface LevAMM:
def COLLATERAL() -> address: view
def STABLECOIN() -> address: view
def collateral_amount() -> uint256: view
def get_debt() -> uint256: view
################################################################
# EVENTS #
################################################################
event SetRatioTolerance:
ratio_tolerance: uint256
################################################################
# STORAGE #
################################################################
POOL: immutable(address)
AMM: public(immutable(address)) # the LevAMM that holds the pool's LP as collateral
# WAD tolerance around an LT deposit's proportional debt: it absorbs interest and
# trades between quoting and inclusion. 0 requires exact equality.
ratio_tolerance: public(uint256)
cached_supply: public(uint256) # pool.user_supply() as of the last update; 0 until attached
amm_surplus: public(uint256) # LP gifted to the LevAMM, as of the last add or sync
################################################################
# CONSTRUCTOR #
################################################################
@deploy
def __init__(pool: address, amm: address, ratio_tolerance: uint256):
"""
@param pool Twocrypto pool; coin0 is the LevAMM's stablecoin
@param amm LevAMM that holds the pool's LP as collateral
@param ratio_tolerance Initial tolerance, WAD
"""
# One market: the LevAMM's collateral is this pool's LP, and its stablecoin
# is coin0, which the pool holds unscaled
assert staticcall LevAMM(amm).COLLATERAL() == pool, "amm collateral"
assert staticcall LevAMM(amm).STABLECOIN() == staticcall Pool(pool).coins(0), "amm stablecoin"
assert (staticcall Pool(pool).precisions())[0] == 1, "pool precision"
# The gate measures deposited debt exactly only without a pool admin fee
assert staticcall Pool(pool).admin_fee() == 0, "admin fee"
POOL = pool
AMM = amm
self._set_ratio_tolerance(ratio_tolerance)
################################################################
# INTERNAL FUNCTIONS #
################################################################
@internal
def _update(stable: uint256, old_stable: uint256):
"""
@dev Gate the operation the pool just made; revert on an off-ratio LT deposit.
@param stable The pool's stablecoin balance after the operation
@param old_stable The pool's stablecoin balance as of the previous update or sync
"""
# Swaps and donations leave user LP supply unchanged
supply: uint256 = staticcall Pool(POOL).user_supply()
old_supply: uint256 = self.cached_supply
if supply == old_supply and old_supply != 0:
return
self.cached_supply = supply
# Exits reduce booked collateral and LP holdings together, preserving gifts
if supply < old_supply:
return
# LP the LevAMM holds beyond its booked collateral: gifts, plus a deposit
# minted but not yet booked
lp_balance: uint256 = staticcall Pool(POOL).balanceOf(AMM)
collateral: uint256 = staticcall LevAMM(AMM).collateral_amount()
surplus: uint256 = lp_balance - min(lp_balance, collateral)
old_surplus: uint256 = self.amm_surplus
# Nothing recorded yet: record only. At attachment the surplus is gifts. The
# first add to an empty pool meets an empty book, whose LP is that add's own
# unbooked LT deposit, not a gift.
if old_supply == 0:
if collateral == 0:
surplus = 0
else:
added_lp: uint256 = supply - old_supply
# An LT deposit leaves its minted LP unbooked on the LevAMM. An unrecorded
# gift can make another add look like one, never the reverse.
if surplus >= old_surplus + added_lp:
surplus -= added_lp
# An empty book has no ratio to keep and no holders to trade against
if collateral != 0:
added_debt: uint256 = stable - min(stable, old_stable)
proportional: uint256 = added_lp * staticcall LevAMM(AMM).get_debt() // collateral
deviation: uint256 = max(added_debt, proportional) - min(added_debt, proportional)
assert (
deviation * PRECISION <= proportional * self.ratio_tolerance
), "LT deviation"
if surplus != old_surplus:
self.amm_surplus = surplus
@internal
def _sync(attached: bool):
"""
@dev Re-read the baselines: the user supply once attached (before, the first
update seeds it with the policy's snapshot), and the LevAMM's gifts.
Trusts LT, the LevAMM and the tokens not to call it during an
unfinished LP transfer or book update.
"""
if attached:
self.cached_supply = staticcall Pool(POOL).user_supply()
lp_balance: uint256 = staticcall Pool(POOL).balanceOf(AMM)
collateral: uint256 = staticcall LevAMM(AMM).collateral_amount()
self.amm_surplus = lp_balance - min(lp_balance, collateral)
@internal
def _set_ratio_tolerance(ratio_tolerance: uint256):
assert ratio_tolerance <= MAX_RATIO_TOLERANCE, "ratio tolerance"
self.ratio_tolerance = ratio_tolerance
log SetRatioTolerance(ratio_tolerance=ratio_tolerance)
Compiler settingsShow
{
"search_paths": [
".venv/lib/python3.12/site-packages",
"."
]
}Source code and metadata: Sourcify.
The source code belongs to the authors of the contract.