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
| Name | Kind / Type | Value / Meaning |
|---|---|---|
CRYPTOPOOL | public(immutable(CurveCryptoPool)) | Underlying 2-coin Curve Twocrypto pool (coins(0) == STABLECOIN, coins(1) == ASSET_TOKEN). |
STABLECOIN | public(immutable(IERC20)) | Market debt stablecoin (18 decimals). |
ASSET_TOKEN | public(immutable(IERC20)) | Underlying volatile asset (for example WBTC, cbBTC, tBTC, or WETH). |
CRYPTOPOOL_N_COINS | constant(uint256) | 2. Constructor asserts coins(2) reverts ("N>2"). |
FEE_CLAIM_DISCOUNT | constant(uint256) | 10**16 (1%). Default slippage discount for distribute_borrower_fees. |
MIN_SHARE_REMAINDER | constant(uint256) | 10**6 wei. Minimum nonzero totalSupply after deposit or partial withdrawal. |
SQRT_MIN_UNSTAKED_FRACTION | constant(int256) | 10**14 (). Caps token_reduction when unstaked supply approaches zero. |
MIN_STAKED_FOR_FEES | constant(int256) | 10**16 (0.01 yb-LP). Threshold above which positive admin fees wait for below-watermark losses to clear. |
decimals | public(constant(uint8)) | 18. |
admin | public(address) | Factory contract (or EOA). |
amm | public(LevAMM) | Paired AMM contract, set once via set_amm. |
agg | public(PriceOracle) | Stablecoin USD aggregator read from amm.PRICE_ORACLE_CONTRACT().AGG(). |
staker | public(address) | Liquidity gauge contract, set once via set_staker. |
liquidity | public(LiquidityValues) | Stored (admin, total, ideal_staked, staked) accounting state. |
balanceOf, allowance, totalSupply | Standard ERC-20 storage | Token balances, allowances, and total supply. |
stablecoin_allocation | public(uint256) | Target stablecoin credit line assigned to this market. |
stablecoin_allocated | public(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.
The dynamic admin fee fraction scales with the staked share of supply:
where 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'sLTbalance (token_reduction > 0) andtotalSupplyequally, transferring value to unstaked holders and the admin fee buffer. - Below the watermark (
staked < ideal_stakedwhilebalanceOf[staker] >= MIN_STAKED_FOR_FEES): Positive value gains first repay the staked deficitv_st_loss = ideal_staked - stakedbefore admin fees accrue. Losses reduce user equity without turningadminnegative. - Small staked balance (
balanceOf[staker] < MIN_STAKED_FOR_FEES): Both gains and losses split by , soliquidity.admincan become negative.
External functions
| Signature | Mutability | Access | Notes and invariants |
|---|---|---|---|
deposit(assets: uint256, debt: uint256, min_shares: uint256, receiver: address = msg.sender) -> uint256 | nonpayable, @nonreentrant | Anyone | Reverts "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) -> uint256 | nonpayable, @nonreentrant | Anyone | Reverts "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, @nonreentrant | Owner (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) -> uint256 | view, @nonreentrant | Anyone | Simulates 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) -> uint256 | view, @nonreentrant | Anyone | Simulates ASSET_TOKEN received from withdraw. |
preview_emergency_withdraw(shares: uint256) -> (uint256, int256) | view, @nonreentrant | Anyone | Simulates (asset_out, signed_stables) from emergency_withdraw. |
pricePerShare() -> uint256 | view | Anyone | Manipulation-resistant equity per share in ASSET_TOKEN units (1e18). Returns 10**18 if totalSupply == 0. |
updated_balances() -> (uint256, uint256) | view | Anyone | Returns projected (supply_tokens, staked_tokens) after applying _calculate_values. |
min_admin_fee() -> uint256 | view | Anyone | Reads Factory(admin).min_admin_fee() (or 0 for EOA admin). |
is_killed() -> bool | view | Anyone | Returns amm.is_killed(). |
checkpoint_staker_rebase() | nonpayable | staker 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, @nonreentrant | Anyone (if discount <= 1%), else admin | Calls amm.collect_fees() and donates LT's STABLECOIN balance into CRYPTOPOOL (donation=True). |
withdraw_admin_fees() | nonpayable, @nonreentrant | Anyone | Requires 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, @nonreentrant | Anyone when limit == max_value(uint256), else admin | Moves STABLECOIN between admin and amm. Reductions preserve at least 3/4 of lp_price * collateral_amount. |
set_amm(amm: LevAMM) | nonpayable, @nonreentrant | Admin | One-time setter ("Already set"). Validates STABLECOIN, COLLATERAL, and LT_CONTRACT. |
set_staker(staker: address) | nonpayable, @nonreentrant | Admin | One-time setter ("Staker already set"). Sweeps any pre-existing staker balance to fee_receiver. |
set_admin(new_admin: address) | nonpayable, @nonreentrant | Admin | Validates Factory getters if new_admin is a contract. |
set_rate(rate: uint256) / set_amm_fee(fee: uint256) | nonpayable, @nonreentrant | Admin | Forwards to amm.set_rate or amm.set_fee. |
set_killed(is_killed: bool) | nonpayable | Admin or Factory.emergency_admin() | Forwards to amm.set_killed. |
symbol(), name(), transfer, transferFrom, approve | Standard ERC-20 | Anyone | Transfers 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
| Name | Kind / Type | Value / Meaning |
|---|---|---|
LEVERAGE | public(immutable(uint256)) | Fixed at 2 * 10**18 by Factory.LEVERAGE. |
LEV_RATIO | immutable(uint256) | (4/9 * 1e18 for ). |
MIN_SAFE_DEBT | immutable(uint256) | (1/16 * 1e18 for ). |
MAX_SAFE_DEBT | immutable(uint256) | (8.5/16 * 1e18 for ). |
LT_CONTRACT | public(immutable(address)) | Controlling LT contract. |
COLLATERAL | public(immutable(IERC20)) | Underlying Curve Twocrypto LP token. |
STABLECOIN | public(immutable(IERC20)) | Market debt stablecoin (18 decimals). |
PRICE_ORACLE_CONTRACT | public(immutable(PriceOracle)) | Market's CryptopoolLPOracle. |
COLLATERAL_PRECISION | immutable(uint256) | 10**(18 - COLLATERAL.decimals()) (1 for 18-decimal LP tokens). |
MAX_FEE | constant(uint256) | 10**17 (10%). |
MAX_RATE | constant(uint256) | 10**18 // (365 * 86400) (100% APR). |
fee | public(uint256) | Swap fee on exchange (1e18-scaled). |
collateral_amount | public(uint256) | Tracked Curve LP collateral held by AMM. |
rate, rate_mul | public(uint256) | Per-second interest rate and cumulative multiplier (1e18-scaled). |
minted, redeemed | public(uint256) | Cumulative borrowed and repaid stablecoin accounting for interest extraction. |
is_killed | public(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 , collateral , and debt , AMM computes collateral value and solves for the invariant :
The AMM's manipulation-resistant fiat equity is value = x0 * 10**18 // (2 * LEVERAGE - 10**18) (which equals at ).
- Equilibrium occurs at (collateral-to-debt ratio
2 * 10**18). get_x0(..., safe_limits=True)enforcesMIN_SAFE_DEBT * V_c <= d <= MAX_SAFE_DEBT * V_c(reverts"Unsafe min"or"Unsafe max").- In
exchange,check_stateis relaxed toFalsewhen a trade movescoll_vs_debtcloser to2 * 10**18, allowing arbitrageurs to rescue an imbalanced AMM. Every trade must satisfyget_x0_after >= x0_before("Bad final state").
External functions
| Signature | Mutability | Access | Notes |
|---|---|---|---|
exchange(i: uint256, j: uint256, in_amount: uint256, min_out: uint256, _for: address = msg.sender) -> uint256 | nonpayable, @nonreentrant | Anyone | 0 = 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) -> uint256 | view | Anyone | Quotes exchange output after fee. When i == 0, reverts "Amount too large" if in_amount > debt. |
get_p() -> uint256 | view | Anyone | Returns the AMM's internal marginal price (x0 - debt) * (10**18 // COLLATERAL_PRECISION) // collateral. |
get_state() -> AMMState | view | Anyone | Returns (collateral, debt, x0) using live PRICE_ORACLE_CONTRACT.price(). |
get_debt() -> uint256 / outdated_debt() -> uint256 | view | Anyone | get_debt includes accrued interest via _rate_mul(); outdated_debt returns stored self.debt. |
get_rate_mul() -> uint256 | view | Anyone | Current rate multiplier (1e18-scaled). |
value_oracle() -> OraclizedValue | view | Anyone | Current (p_o, value) in USD (1e18). |
value_oracle_for(collateral: uint256, debt: uint256) -> OraclizedValue | view | Anyone | Computes (p_o, value) for arbitrary (collateral, debt). |
value_change(collateral_amount: uint256, borrowed_amount: uint256, is_deposit: bool) -> OraclizedValue | view | Anyone | Computes post-operation (p_o, value); enforces safe_limits when is_deposit is True. |
max_debt() -> uint256 | view | Anyone | STABLECOIN.balanceOf(self) + _debt(). |
accumulated_interest() -> uint256 | view | Anyone | Uncollected interest max(_debt() + redeemed, minted) - minted. |
collect_fees() -> uint256 | nonpayable, @nonreentrant | Anyone | Transfers accrued interest in STABLECOIN to LT_CONTRACT (capped by STABLECOIN.balanceOf(self)). |
coins(i: uint256) -> IERC20 | view | Anyone | 0 -> STABLECOIN, 1 -> COLLATERAL. |
check_nonreentrant() | view, @nonreentrant | Anyone | Read-only reentrancy guard probe used by LT and external oracles. |
_deposit(d_collateral: uint256, d_debt: uint256) -> OraclizedValue | nonpayable | LT_CONTRACT only | Adds collateral and debt, enforces safe_limits = True. |
_withdraw(frac: uint256) -> Pair | nonpayable | LT_CONTRACT only | Removes frac / 1e18 of collateral (floored) and debt (ceiled). |
set_rate(rate: uint256) -> uint256 | nonpayable, @nonreentrant | LT_CONTRACT only | Updates debt to current rate_mul and sets rate <= MAX_RATE. |
set_fee(fee: uint256) | nonpayable | LT_CONTRACT only | Sets fee <= MAX_FEE. |
set_killed(is_killed: bool) | nonpayable | LT_CONTRACT only | Sets 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 to10**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").
| Signature | Mutability | Notes |
|---|---|---|
add_market(pool: CurveCryptoPool, fee: uint256, rate: uint256, debt_ceiling: uint256) -> Market | nonpayable, @nonreentrant | Verifies 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) | nonpayable | Deploys 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, @nonreentrant | One-time setter ("Only set once"). Grants mint_factory infinite STABLECOIN approval so it can reclaim minted stablecoins. |
set_allocator(allocator: address, amount: uint256) | nonpayable, @nonreentrant | Rejects mint_factory ("Minter"). Pulls amount - old_allocation on increase; increases STABLECOIN allowance by old_allocation - amount on decrease. |
set_agg(agg: address) | nonpayable | Updates agg and verifies 0.9e18 < Agg(agg).price() < 1.1e18 ("Bad aggregator"). |
set_flash(flash: address) | nonpayable | Updates the ERC-3156 flash lender address read by VirtualPool. |
set_admin(new_admin: address, new_emergency_admin: address) | nonpayable | Requires both addresses nonzero. |
set_fee_receiver(new_fee_receiver: address) | nonpayable | Destination for LT.withdraw_admin_fees(). |
set_gauge_controller(gc: address) | nonpayable | One-time setter ("Already set"). |
set_min_admin_fee(new_min_admin_fee: uint256) | nonpayable | Requires new_min_admin_fee <= 10**18 ("Admin fee too high"). |
set_implementations(amm, lt, virtual_pool, price_oracle, staker) | nonpayable | Updates 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
| Name | Type | Meaning |
|---|---|---|
FACTORY | public(immutable(Factory)) | Deploying Factory (provides flash()). |
AMM | public(immutable(YbAMM)) | Market's AMM. |
POOL | public(immutable(Pool)) | Underlying Curve Twocrypto pool (AMM.COLLATERAL()). |
STABLECOIN, ASSET_TOKEN | public(immutable(ERC20)) | Coin 0 and coin 1 of POOL. |
IMPL | public(immutable(address)) | Blueprint implementation recorded at deployment. |
ROUNDING_DISCOUNT | public(constant(uint256)) | 10**10 ( relative buffer on i == 0 swaps). |
External functions and swap paths
| Signature | Mutability | Access | Notes |
|---|---|---|---|
coins(i: uint256) -> ERC20 | view | Anyone | 0 -> STABLECOIN, 1 -> ASSET_TOKEN. |
get_dy(i: uint256, j: uint256, in_amount: uint256) -> uint256 | view | Anyone | Quotes 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) -> uint256 | nonpayable, @nonreentrant | Anyone | Pulls 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) | nonpayable | FACTORY.flash() only ("Wrong caller") | Requires initiator == self and token == STABLECOIN. |
Inside onFlashLoan:
- Stablecoin to crypto (
i == 0): Swapsin_amount * (1 - ROUNDING_DISCOUNT) + flash_amountofSTABLECOINfor LP tokens inAMM, callsPOOL.remove_liquidity(lp_amount, [0, 0]), repays the flash loan with the resultingSTABLECOIN, and leavesASSET_TOKENas output. - Crypto to stablecoin (
i == 1): Deposits[flash_amount, in_amount]intoPOOL, swaps the minted LP tokens forSTABLECOINinAMM, repaystotal_flash_amount, and leaves the surplusSTABLECOINas 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:
| Signature | Mutability | Notes |
|---|---|---|
price() -> uint256 | view | Read-only LP price in USD (1e18) using AGG.price(). |
price_w() -> uint256 | nonpayable | Checkpoints AGG via AGG.price_w() before computing LP price. |
Related
- Deposit, withdraw, and migrate: End-to-end integration patterns for
LT,LTDepositZap, and migrators. - Arbitrage and oracle reports: Rebalancing
AMMandVirtualPoolalongside pool policies. - Pool policy and report bank: Curve Twocrypto
v3.0.0policy hooks and LT deposit gate. - Events and Errors: Complete event signatures and revert strings.