Skip to main content

Core vault and AMM

Every YieldBasis market is deployed by Factory as a five-contract stack: an ERC-20 vault (LT), a constant-leverage rebalancing AMM (AMM), an LP price oracle (CryptopoolLPOracle), an atomic flash-loan swapper (VirtualPool), and an optional staking gauge (staker). Together with an underlying Curve Twocrypto pool (CRYPTOPOOL), these contracts maintain 2x leveraged LP positions that keep full price exposure to BTC or ETH, up and down.

LT (LT.vy)​

LT is the ERC-20 vault token (yb-<symbol>, 18 decimals) for a single market. It accepts deposits of ASSET_TOKEN, borrows STABLECOIN from AMM, adds liquidity to CRYPTOPOOL, tracks the value split between staked and unstaked shares, and routes protocol admin fees.

Constants, immutables, and storage​

NameKind / TypeValue / Meaning
CRYPTOPOOLpublic(immutable(CurveCryptoPool))Underlying 2-coin Curve Twocrypto pool (coins(0) == STABLECOIN, coins(1) == ASSET_TOKEN).
STABLECOINpublic(immutable(IERC20))Market debt stablecoin (18 decimals).
ASSET_TOKENpublic(immutable(IERC20))Underlying volatile asset (for example WBTC, cbBTC, tBTC, or WETH).
CRYPTOPOOL_N_COINSconstant(uint256)2. Constructor asserts coins(2) reverts ("N>2").
FEE_CLAIM_DISCOUNTconstant(uint256)10**16 (1%). Default slippage discount for distribute_borrower_fees.
MIN_SHARE_REMAINDERconstant(uint256)10**6 wei. Minimum nonzero totalSupply after deposit or partial withdrawal.
SQRT_MIN_UNSTAKED_FRACTIONconstant(int256)10**14 (10−410^{-4}). Caps token_reduction when unstaked supply approaches zero.
MIN_STAKED_FOR_FEESconstant(int256)10**16 (0.01 yb-LP). Threshold above which positive admin fees wait for below-watermark losses to clear.
decimalspublic(constant(uint8))18.
adminpublic(address)Factory contract (or EOA).
ammpublic(LevAMM)Paired AMM contract, set once via set_amm.
aggpublic(PriceOracle)Stablecoin USD aggregator read from amm.PRICE_ORACLE_CONTRACT().AGG().
stakerpublic(address)Liquidity gauge contract, set once via set_staker.
liquiditypublic(LiquidityValues)Stored (admin, total, ideal_staked, staked) accounting state.
balanceOf, allowance, totalSupplyStandard ERC-20 storageToken balances, allowances, and total supply.
stablecoin_allocationpublic(uint256)Target stablecoin credit line assigned to this market.
stablecoin_allocatedpublic(uint256)Stablecoins currently transferred from admin to amm.

Structs​

struct LiquidityValues:
admin: int256 # Can be negative when staked < MIN_STAKED_FOR_FEES
total: uint256 # User equity in asset terms (1e18)
ideal_staked: uint256 # High-water mark for staked equity (1e18)
staked: uint256 # Current staked equity (1e18)

struct LiquidityValuesOut:
admin: int256
total: uint256
ideal_staked: uint256
staked: uint256
staked_tokens: uint256
supply_tokens: uint256
token_reduction: int256

Value accounting and staker rebase​

Before mutating shares on deposit, withdraw, emergency_withdraw (when live), withdraw_admin_fees, checkpoint_staker_rebase, or transfers involving staker, LT calls _calculate_values(p_o) where p_o = CRYPTOPOOL.price_scale() * agg.price() // 10**18.

Flow of LT._calculate_values showing dynamic admin fee computation, below-watermark loss recovery, and staker token reduction.Flow of LT._calculate_values showing dynamic admin fee computation, below-watermark loss recovery, and staker token reduction.

The dynamic admin fee fraction scales with the staked share of supply:

fa=1−(1−fmin⁡)1−stakedsupplyf_a = 1 - (1 - f_{\min})\sqrt{1 - \frac{\text{staked}}{\text{supply}}}

where fmin⁡f_{\min} is Factory.min_admin_fee() (0 if admin is an EOA).

  • Above the watermark (staked >= ideal_staked): Stakers forego trading fee profit in exchange for YB emissions. Positive profits reduce the gauge's LT balance (token_reduction > 0) and totalSupply equally, transferring value to unstaked holders and the admin fee buffer.
  • Below the watermark (staked < ideal_staked while balanceOf[staker] >= MIN_STAKED_FOR_FEES): Positive value gains first repay the staked deficit v_st_loss = ideal_staked - staked before admin fees accrue. Losses reduce user equity without turning admin negative.
  • Small staked balance (balanceOf[staker] < MIN_STAKED_FOR_FEES): Both gains and losses split by (1−fa)(1 - f_a), so liquidity.admin can become negative.

External functions​

SignatureMutabilityAccessNotes and invariants
deposit(assets: uint256, debt: uint256, min_shares: uint256, receiver: address = msg.sender) -> uint256nonpayable, @nonreentrantAnyoneReverts "Deposit to staker" if receiver == staker, "Debt too high" if amm.max_debt() // 2 < v.value, "Remainder too small" if shares + supply < MIN_SHARE_REMAINDER, or "Slippage" if shares < min_shares. Checkpoints gauge and calls _distribute_borrower_fees(FEE_CLAIM_DISCOUNT).
withdraw(shares: uint256, min_assets: uint256, receiver: address = msg.sender) -> uint256nonpayable, @nonreentrantAnyoneReverts "Withdrawing nothing" if shares == 0, "Withdraw to/from staker" if staker is sender or receiver, "We're dead. Use emergency_withdraw" if amm.is_killed(), "Remainder too small", or "Slippage". Uses CRYPTOPOOL.remove_liquidity_fixed_out.
emergency_withdraw(shares: uint256, receiver: address = msg.sender, owner: address = msg.sender) -> (uint256, int256)nonpayable, @nonreentrantOwner (or emergency_admin when killed or value_oracle() reverts, with receiver == owner)Uses balanced CRYPTOPOOL.remove_liquidity. Returns (asset_out, stables_to_return). If stables_to_return < 0, pulls -stables_to_return of STABLECOIN from msg.sender.
preview_deposit(assets: uint256, debt: uint256, raise_overflow: bool = True) -> uint256view, @nonreentrantAnyoneSimulates shares minted. Reverts "Debt too high" when raise_overflow is True and amm.max_debt() // 2 < v.value. Does not run pool-policy LT gate checks.
preview_withdraw(tokens: uint256) -> uint256view, @nonreentrantAnyoneSimulates ASSET_TOKEN received from withdraw.
preview_emergency_withdraw(shares: uint256) -> (uint256, int256)view, @nonreentrantAnyoneSimulates (asset_out, signed_stables) from emergency_withdraw.
pricePerShare() -> uint256viewAnyoneManipulation-resistant equity per share in ASSET_TOKEN units (1e18). Returns 10**18 if totalSupply == 0.
updated_balances() -> (uint256, uint256)viewAnyoneReturns projected (supply_tokens, staked_tokens) after applying _calculate_values.
min_admin_fee() -> uint256viewAnyoneReads Factory(admin).min_admin_fee() (or 0 for EOA admin).
is_killed() -> boolviewAnyoneReturns amm.is_killed().
checkpoint_staker_rebase()nonpayablestaker only (no-op otherwise or when killed)Settles staker token reduction before gauge mint/burn operations.
distribute_borrower_fees(discount: uint256 = FEE_CLAIM_DISCOUNT)nonpayable, @nonreentrantAnyone (if discount <= 1%), else adminCalls amm.collect_fees() and donates LT's STABLECOIN balance into CRYPTOPOOL (donation=True).
withdraw_admin_fees()nonpayable, @nonreentrantAnyoneRequires factory admin ("Need factory"), live AMM ("Killed"), nonzero fee_receiver, and v.admin >= 0. Mints LT shares to Factory.fee_receiver().
allocate_stablecoins(limit: uint256 = max_value(uint256))nonpayable, @nonreentrantAnyone when limit == max_value(uint256), else adminMoves STABLECOIN between admin and amm. Reductions preserve at least 3/4 of lp_price * collateral_amount.
set_amm(amm: LevAMM)nonpayable, @nonreentrantAdminOne-time setter ("Already set"). Validates STABLECOIN, COLLATERAL, and LT_CONTRACT.
set_staker(staker: address)nonpayable, @nonreentrantAdminOne-time setter ("Staker already set"). Sweeps any pre-existing staker balance to fee_receiver.
set_admin(new_admin: address)nonpayable, @nonreentrantAdminValidates Factory getters if new_admin is a contract.
set_rate(rate: uint256) / set_amm_fee(fee: uint256)nonpayable, @nonreentrantAdminForwards to amm.set_rate or amm.set_fee.
set_killed(is_killed: bool)nonpayableAdmin or Factory.emergency_admin()Forwards to amm.set_killed.
symbol(), name(), transfer, transferFrom, approveStandard ERC-20AnyoneTransfers to/from staker trigger _calculate_values, update staked/ideal_staked, and checkpoint the gauge.

AMM (AMM.vy)​

AMM (titled LEVAMM) holds the market's Curve LP tokens (COLLATERAL) and STABLECOIN reserves, enforces the constant-leverage rebalancing curve, accrues borrowing interest, and lets arbitrageurs trade STABLECOIN against Curve LP tokens to restore 2x leverage.

Constants, immutables, and storage​

NameKind / TypeValue / Meaning
LEVERAGEpublic(immutable(uint256))Fixed at 2 * 10**18 by Factory.LEVERAGE.
LEV_RATIOimmutable(uint256)L2/(2L−1)2L^2 / (2L - 1)^2 (4/9 * 1e18 for L=2L = 2).
MIN_SAFE_DEBTimmutable(uint256)1/(4L2)1 / (4L^2) (1/16 * 1e18 for L=2L = 2).
MAX_SAFE_DEBTimmutable(uint256)(2L−1)2/(4L2)−1/(8L2)(2L-1)^2/(4L^2) - 1/(8L^2) (8.5/16 * 1e18 for L=2L = 2).
LT_CONTRACTpublic(immutable(address))Controlling LT contract.
COLLATERALpublic(immutable(IERC20))Underlying Curve Twocrypto LP token.
STABLECOINpublic(immutable(IERC20))Market debt stablecoin (18 decimals).
PRICE_ORACLE_CONTRACTpublic(immutable(PriceOracle))Market's CryptopoolLPOracle.
COLLATERAL_PRECISIONimmutable(uint256)10**(18 - COLLATERAL.decimals()) (1 for 18-decimal LP tokens).
MAX_FEEconstant(uint256)10**17 (10%).
MAX_RATEconstant(uint256)10**18 // (365 * 86400) (100% APR).
feepublic(uint256)Swap fee on exchange (1e18-scaled).
collateral_amountpublic(uint256)Tracked Curve LP collateral held by AMM.
rate, rate_mulpublic(uint256)Per-second interest rate and cumulative multiplier (1e18-scaled).
minted, redeemedpublic(uint256)Cumulative borrowed and repaid stablecoin accounting for interest extraction.
is_killedpublic(bool)Emergency kill switch blocking exchange, _deposit, and collect_fees.

Structs​

struct AMMState:
collateral: uint256
debt: uint256
x0: uint256

struct Pair:
collateral: uint256
debt: uint256

struct OraclizedValue:
p_o: uint256
value: uint256

Invariant and safe debt bounds​

Given LP oracle price pop_o, collateral yy, and debt dd, AMM computes collateral value Vc=po⋅y⋅COLLATERAL_PRECISION/1018V_c = p_o \cdot y \cdot \text{COLLATERAL\_PRECISION} / 10^{18} and solves for the invariant x0x_0:

x0=Vc+Vc2−4⋅Vc⋅LEV_RATIO⋅d/10182⋅LEV_RATIO/1018x_0 = \frac{V_c + \sqrt{V_c^2 - 4 \cdot V_c \cdot \text{LEV\_RATIO} \cdot d / 10^{18}}}{2 \cdot \text{LEV\_RATIO} / 10^{18}}

The AMM's manipulation-resistant fiat equity is value = x0 * 10**18 // (2 * LEVERAGE - 10**18) (which equals x0/3x_0 / 3 at L=2L = 2).

Safe debt band and equilibrium rule in AMM.vy showing MIN_SAFE_DEBT, equilibrium 50% debt-to-collateral ratio, and MAX_SAFE_DEBT.Safe debt band and equilibrium rule in AMM.vy showing MIN_SAFE_DEBT, equilibrium 50% debt-to-collateral ratio, and MAX_SAFE_DEBT.
  • Equilibrium occurs at d=Vc/2d = V_c / 2 (collateral-to-debt ratio 2 * 10**18).
  • get_x0(..., safe_limits=True) enforces MIN_SAFE_DEBT * V_c <= d <= MAX_SAFE_DEBT * V_c (reverts "Unsafe min" or "Unsafe max").
  • In exchange, check_state is relaxed to False when a trade moves coll_vs_debt closer to 2 * 10**18, allowing arbitrageurs to rescue an imbalanced AMM. Every trade must satisfy get_x0_after >= x0_before ("Bad final state").

External functions​

SignatureMutabilityAccessNotes
exchange(i: uint256, j: uint256, in_amount: uint256, min_out: uint256, _for: address = msg.sender) -> uint256nonpayable, @nonreentrantAnyone0 = STABLECOIN, 1 = COLLATERAL. Reverts if killed or empty ("Empty AMM"). After swapping, calls _collect_fees() and LT.distribute_borrower_fees().
get_dy(i: uint256, j: uint256, in_amount: uint256) -> uint256viewAnyoneQuotes exchange output after fee. When i == 0, reverts "Amount too large" if in_amount > debt.
get_p() -> uint256viewAnyoneReturns the AMM's internal marginal price (x0 - debt) * (10**18 // COLLATERAL_PRECISION) // collateral.
get_state() -> AMMStateviewAnyoneReturns (collateral, debt, x0) using live PRICE_ORACLE_CONTRACT.price().
get_debt() -> uint256 / outdated_debt() -> uint256viewAnyoneget_debt includes accrued interest via _rate_mul(); outdated_debt returns stored self.debt.
get_rate_mul() -> uint256viewAnyoneCurrent rate multiplier 1+∫r dt1 + \int r\,dt (1e18-scaled).
value_oracle() -> OraclizedValueviewAnyoneCurrent (p_o, value) in USD (1e18).
value_oracle_for(collateral: uint256, debt: uint256) -> OraclizedValueviewAnyoneComputes (p_o, value) for arbitrary (collateral, debt).
value_change(collateral_amount: uint256, borrowed_amount: uint256, is_deposit: bool) -> OraclizedValueviewAnyoneComputes post-operation (p_o, value); enforces safe_limits when is_deposit is True.
max_debt() -> uint256viewAnyoneSTABLECOIN.balanceOf(self) + _debt().
accumulated_interest() -> uint256viewAnyoneUncollected interest max(_debt() + redeemed, minted) - minted.
collect_fees() -> uint256nonpayable, @nonreentrantAnyoneTransfers accrued interest in STABLECOIN to LT_CONTRACT (capped by STABLECOIN.balanceOf(self)).
coins(i: uint256) -> IERC20viewAnyone0 -> STABLECOIN, 1 -> COLLATERAL.
check_nonreentrant()view, @nonreentrantAnyoneRead-only reentrancy guard probe used by LT and external oracles.
_deposit(d_collateral: uint256, d_debt: uint256) -> OraclizedValuenonpayableLT_CONTRACT onlyAdds collateral and debt, enforces safe_limits = True.
_withdraw(frac: uint256) -> PairnonpayableLT_CONTRACT onlyRemoves frac / 1e18 of collateral (floored) and debt (ceiled).
set_rate(rate: uint256) -> uint256nonpayable, @nonreentrantLT_CONTRACT onlyUpdates debt to current rate_mul and sets rate <= MAX_RATE.
set_fee(fee: uint256)nonpayableLT_CONTRACT onlySets fee <= MAX_FEE.
set_killed(is_killed: bool)nonpayableLT_CONTRACT onlySets is_killed.

Factory (Factory.vy)​

Factory deploys YieldBasis markets from Vyper blueprint implementations, manages stablecoin credit lines from mint_factory and allocators, and stores protocol-wide configuration.

Constants, struct, and storage​

  • Constants: MAX_MARKETS = 50000, LEVERAGE = 2 * 10**18.
  • Immutable: STABLECOIN: IERC20 (must have 18 decimals).
  • Storage: markets[MAX_MARKETS], market_count, admin, emergency_admin, fee_receiver, gauge_controller, min_admin_fee (initialized to 10**17), amm_impl, lt_impl, virtual_pool_impl, price_oracle_impl, staker_impl, agg, flash, allocators[address], mint_factory.
struct Market:
asset_token: IERC20
cryptopool: CurveCryptoPool
amm: address
lt: address
price_oracle: address
virtual_pool: address
staker: address

External functions​

All state-changing functions require msg.sender == self.admin ("Access").

SignatureMutabilityNotes
add_market(pool: CurveCryptoPool, fee: uint256, rate: uint256, debt_ceiling: uint256) -> Marketnonpayable, @nonreentrantVerifies pool.coins(0) == STABLECOIN and pool.decimals() == 18. Deploys CryptopoolLPOracle, LT, AMM, and (if implementations are set) VirtualPool and staker. Approves STABLECOIN to LT, allocates debt_ceiling, and emits MarketParameters.
fill_staker_vpool(i: uint256)nonpayableDeploys or upgrades virtual_pool (when VirtualPool.IMPL() != virtual_pool_impl) and deploys staker if unset on market i.
set_mint_factory(mint_factory: address)nonpayable, @nonreentrantOne-time setter ("Only set once"). Grants mint_factory infinite STABLECOIN approval so it can reclaim minted stablecoins.
set_allocator(allocator: address, amount: uint256)nonpayable, @nonreentrantRejects mint_factory ("Minter"). Pulls amount - old_allocation on increase; increases STABLECOIN allowance by old_allocation - amount on decrease.
set_agg(agg: address)nonpayableUpdates agg and verifies 0.9e18 < Agg(agg).price() < 1.1e18 ("Bad aggregator").
set_flash(flash: address)nonpayableUpdates the ERC-3156 flash lender address read by VirtualPool.
set_admin(new_admin: address, new_emergency_admin: address)nonpayableRequires both addresses nonzero.
set_fee_receiver(new_fee_receiver: address)nonpayableDestination for LT.withdraw_admin_fees().
set_gauge_controller(gc: address)nonpayableOne-time setter ("Already set").
set_min_admin_fee(new_min_admin_fee: uint256)nonpayableRequires new_min_admin_fee <= 10**18 ("Admin fee too high").
set_implementations(amm, lt, virtual_pool, price_oracle, staker)nonpayableUpdates any non-zero blueprint implementation address for future markets.

VirtualPool (VirtualPool.vy)​

VirtualPool wraps AMM and POOL behind an ERC-3156 flash loan so arbitrageurs and routers can rebalance AMM by swapping STABLECOIN (0) directly for ASSET_TOKEN (1) without holding Curve LP tokens.

Constants and immutables​

NameTypeMeaning
FACTORYpublic(immutable(Factory))Deploying Factory (provides flash()).
AMMpublic(immutable(YbAMM))Market's AMM.
POOLpublic(immutable(Pool))Underlying Curve Twocrypto pool (AMM.COLLATERAL()).
STABLECOIN, ASSET_TOKENpublic(immutable(ERC20))Coin 0 and coin 1 of POOL.
IMPLpublic(immutable(address))Blueprint implementation recorded at deployment.
ROUNDING_DISCOUNTpublic(constant(uint256))10**10 (10−810^{-8} relative buffer on i == 0 swaps).

External functions and swap paths​

SignatureMutabilityAccessNotes
coins(i: uint256) -> ERC20viewAnyone0 -> STABLECOIN, 1 -> ASSET_TOKEN.
get_dy(i: uint256, j: uint256, in_amount: uint256) -> uint256viewAnyoneQuotes swap output. Applies ROUNDING_DISCOUNT to in_amount when i == 0.
exchange(i: uint256, j: uint256, in_amount: uint256, min_out: uint256, _for: address = msg.sender) -> uint256nonpayable, @nonreentrantAnyonePulls in_amount, takes a STABLECOIN flash loan from FACTORY.flash(), executes the rebalance inside onFlashLoan, checks out_amount >= min_out ("Slippage"), and transfers out_coin to _for.
onFlashLoan(initiator, token, total_flash_amount, fee, data)nonpayableFACTORY.flash() only ("Wrong caller")Requires initiator == self and token == STABLECOIN.

Inside onFlashLoan:

  • Stablecoin to crypto (i == 0): Swaps in_amount * (1 - ROUNDING_DISCOUNT) + flash_amount of STABLECOIN for LP tokens in AMM, calls POOL.remove_liquidity(lp_amount, [0, 0]), repays the flash loan with the resulting STABLECOIN, and leaves ASSET_TOKEN as output.
  • Crypto to stablecoin (i == 1): Deposits [flash_amount, in_amount] into POOL, swaps the minted LP tokens for STABLECOIN in AMM, repays total_flash_amount, and leaves the surplus STABLECOIN as output.

CryptopoolLPOracle (CryptopoolLPOracle.vy)​

CryptopoolLPOracle computes a manipulation-resistant USD price for the underlying Curve Twocrypto LP token.

Immutables and functions​

  • Immutables: POOL: Cryptopool, AGG: PriceOracle (stablecoin USD aggregator).
  • Formula:
pLP,USD=⌊2⋅POOL.virtual_price()⋅⌊POOL.price_scale()⋅1018⌋1018⌋⋅AGG.price()1018p_{\text{LP,USD}} = \left\lfloor \frac{2 \cdot \text{POOL.virtual\_price()} \cdot \left\lfloor \sqrt{\text{POOL.price\_scale()} \cdot 10^{18}} \right\rfloor}{10^{18}} \right\rfloor \cdot \frac{\text{AGG.price()}}{10^{18}}
SignatureMutabilityNotes
price() -> uint256viewRead-only LP price in USD (1e18) using AGG.price().
price_w() -> uint256nonpayableCheckpoints AGG via AGG.price_w() before computing LP price.