Yield Basis 백서

Yield Basis

원문

bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 24쪽 중 17쪽

== 1 ) or ( i == 1 and j == 0 ) p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt ( ) x_initial : uint256 = self . get_x0 ( p_o , collateral , debt , False ) - debt if i == 0 : # Buy collateral assert in_amount <= debt , "Amount too large" x : uint256 = x_initial + in_amount y : uint256 = math . _ceil_div ( x_initial * collateral , x ) return ( collateral - y ) * ( 10 ** 18 - self . fee ) // 10 ** 18 else : # Sell collateral y : uint256 = collateral + in_amount x : uint256 = math . _ceil_div ( x_initial * collateral , y ) return ( x_initial - x ) * ( 10 ** 18 - self . fee ) // 10 ** 18 get_state() ​ Description: Returns the current AMM state (collateral, debt, x0) . Returns: AMMState . 📄 View Source Code @external @view def get_state ( ) - > AMMState : p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) state : AMMState = empty ( AMMState ) state . collateral = self . collateral_amount state . debt = self . _debt ( ) state . x0 = self . get_x0 ( p_o , state . collateral , state . debt , False ) return state get_debt() ​ Description: Current debt including accumulated interest. Returns: uint256 . 📄 View Source Code @external @view def get_debt ( ) - > uint256 : return self . _debt ( ) @internal @view def _debt ( ) - > uint256 : return self . debt * self . _rate_mul ( ) // self . rate_mul get_rate_mul() ​ Description: Rate multiplier 1.0 + integral(rate, dt) . Returns: uint256 - Rate multiplier (1.0 == 1e18). 📄 View Source Code @external @view def get_rate_mul ( ) - > uint256 : return self . _rate_mul ( ) @internal @view def _rate_mul ( ) - > uint256 : return unsafe_div ( self . rate_mul * ( 10 ** 18 + self . rate * ( block . timestamp - self . rate_time ) ) , 10 ** 18 ) set_rate() ​ Description: Set interest rate. Only callable by LT. Returns: uint256 - Rate multiplier. Emits: SetRate . Input Type Description rate uint256 New rate (int(fraction * 1e18) per second) 📄 View Source Code @external @nonreentrant def set_rate ( rate : uint256 ) - > uint256 : assert msg . sender == LT_CONTRACT , "Access" assert rate <= MAX_RATE , "Rate too high" rate_mul : uint256 = self . _rate_mul ( ) self . debt = self . debt * rate_mul // self . rate_mul self . rate_mul = rate_mul self . rate_time = block . timestamp self . rate = rate log SetRate ( rate = rate , rate_mul = rate_mul , time = block . timestamp ) return rate_mul _deposit() (LT-only) ​ Description: Deposit LP tokens and borrow stablecoins. Only callable by LT. Returns: OraclizedValue . Emits: AddLiquidityRaw . Input Type Description d_collateral uint256 LP tokens to add d_debt uint256 Stablecoins to borrow 📄 View Source Code @external def _deposit ( d_collateral : uint256 , d_debt : uint256 ) - > OraclizedValue : assert msg . sender == LT_CONTRACT , "Access violation" assert not self . is_killed p_o : uint256 = extcall PRICE_ORACLE_CONTRACT . price_w ( ) collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt_w ( ) debt += d_debt collateral += d_collateral self . minted += d_debt self . debt = debt self . collateral_amount = collateral value_after : uint256 = self . get_x0 ( p_o , collateral , debt , True ) * 10 ** 18 // ( 2 * LEVERAGE - 10 ** 18 ) log AddLiquidityRaw ( token_amounts = [ d_collateral , d_debt ] , invariant = value_after , price_oracle = p_o ) return OraclizedValue ( p_o = p_o , value = value_after ) _withdraw() (LT-only) ​ Description: Withdraw LP tokens and repay stablecoins proportionally. Only callable by LT. Returns: Pair - (collateral_withdrawn, debt_repaid) . Emits: RemoveLiquidityRaw . Input Type Description frac uint256 Fraction of position to withdraw (1e18 units) 📄 View Source Code @external def _withdraw ( frac : uint256 ) - > Pair : assert msg . sender == LT_CONTRACT , "Access violation" collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt_w ( ) d_collateral : uint256 = collateral * frac // 10 ** 18 d_debt : uint256 = math . _ceil_div ( debt * frac , 10 ** 18 ) self . collateral_amount -= d_collateral self . debt = debt - d_debt self . redeemed += d_debt log RemoveLiquidityRaw ( collateral_change = d_collateral , debt_change = d_debt ) return Pair ( collateral = d_collateral , debt = d_debt ) collect_fees() ​ Description: Realize accrued interest. Transfers available stablecoins to LT. Returns: uint256 - Amount of fees collected. Emits: CollectFees . 📄 View Source Code @external @nonreentrant def collect_fees ( ) - > uint256 : return self . _collect_fees ( ) @internal def _collect_fees ( ) - > uint256 : assert not self . is_killed debt : uint256 = self . _debt_w ( ) self . debt = debt minted : uint256 = self . minted to_be_redeemed : uint256 = debt + self . redeemed if to_be_redeemed > minted : self . minted = to_be_redeemed to_be_redeemed = unsafe_sub ( to_be_redeemed , minted ) stables_in_amm : uint256 = staticcall STABLECOIN . balanceOf ( self ) if stables_in_amm < to_be_redeemed : self . minted -= ( to_be_redeemed - stables_in_amm ) to_be_redeemed = stables_in_amm assert extcall STABLECOIN . transfer ( LT_CONTRACT , to_be_redeemed , default_return_value = True ) log CollectFees ( amount = to_be_redeemed , new_supply = debt ) return to_be_redeemed else : log CollectFees ( amount = 0 , new_supply = debt ) return 0 set_fee() (LT-only) ​ Description: Update trading fee. Only callable by LT. Emits: SetFee . Input Type Description fee uint256 New trading fee (must be ≤ MAX_FEE ) 📄 View Source Code @external def set_fee ( fee : uint256 ) : assert msg . sender == LT_CONTRACT , "Access" assert fee <= MAX_FEE self . fee = fee log SetFee ( fee = fee ) set_killed() (LT-only) ​ Description: Emergency kill switch. Only callable by LT. Emits: SetKilled . Input Type Description is_killed bool New kill switch status 📄 View Source Code @external def set_killed ( is_killed : bool ) : assert msg . sender == LT_CONTRACT , "Access" self . is_killed = is_killed log SetKilled ( is_killed = is_killed ) get_p() ​ Description: AMM price of LP tokens in stablecoins. Returns: uint256 . 📄 View Source Code @external @view def get_p ( ) - > uint256 : p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt ( ) return ( self . get_x0 ( p_o , collateral , debt , False ) - debt ) * ( 10 ** 18 // COLLATERAL_PRECISION ) // collateral value_oracle() ​ Description: USD value of the AMM position at oracle price (sandwich-resistant). Returns: OraclizedValue . 📄 View Source Code @external @view def value_oracle ( ) - > OraclizedValue : p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt ( ) return OraclizedValue ( p_o = p_o , value = self . get_x0 ( p_o , collateral , debt , False ) * 10 ** 18 // ( 2 * LEVERAGE - 10 ** 18 ) ) value_oracle_for() ​ Description: USD value for a hypothetical position with given collateral and debt. Returns: OraclizedValue . Input Type Description collateral uint256 Hypothetical collateral amount debt uint256 Hypothetical debt amount 📄 View Source Code @external @view def value_oracle_for ( collateral : uint256 , debt : uint256 ) - > OraclizedValue : p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) return OraclizedValue ( p_o = p_o , value = self . get_x0 ( p_o , collateral , debt , False ) * 10 ** 18 // ( 2 * LEVERAGE - 10 ** 18 ) ) value_change() ​ Description: USD value after a hypothetical deposit or withdrawal. Returns: OraclizedValue - (oracle_price, value_after) . Input Type Description collateral_amount uint256 Amount of collateral to add/remove borrowed_amount uint256 Amount of debt to add/remove is_deposit bool True for deposit, false for withdrawal 📄 View Source Code @external @view def value_change ( collateral_amount : uint256 , borrowed_amount : uint256 , is_deposit : bool ) - > OraclizedValue : p_o : uint256 = staticcall PRICE_ORACLE_CONTRACT . price ( ) collateral : uint256 = self . collateral_amount debt : uint256 = self . _debt ( ) if is_deposit : collateral += collateral_amount debt += borrowed_amount else : collateral -= collateral_amount debt -= borrowed_amount x0_after : uint256 = self . get_x0 ( p_o , collateral , debt , is_deposit ) return OraclizedValue ( p_o = p_o , value = x0_after * 10 ** 18 // ( 2 * LEVERAGE - 10 ** 18 ) ) max_debt() ​ Description: Maximum debt the AMM can take (current stable balance + current debt). Returns: uint256 . 📄 View Source Code @external @view def max_debt ( ) - > uint256 : return staticcall STABLECOIN . balanceOf ( self ) + self . _debt ( ) accumulated_interest() ​ Description: Amount of interest fees available for collection. Returns: uint256 . 📄 View Source Code @external @view def accumulated_interest ( ) - > uint256 : minted : uint256 = self . minted return unsafe_sub ( max ( self . _debt ( ) + self . redeemed , minted ) , minted ) coins() ​ Description: Token address at index (0 = stablecoin, 1 = LP token). Input Type Description i uint256 Token index 📄 View Source Code @external @view def coins ( i : uint256 ) - > IERC20 : return [ STABLECOIN , COLLATERAL ] [ i ] outdated_debt() ​ Description: Debt amount without applying the rate multiplier (pre-interest-accrual). Returns: uint256 . 📄 View Source Code @external @view def outdated_debt ( ) - > uint256 : return self . debt check_nonreentrant() ​ Description: View function to check that the nonreentrant modifier is in place. 📄 View Source Code @external @nonreentrant @view def check_nonreentrant ( ) : pass Related ​ Core: LT — vault that owns this AMM. Core: VirtualPool — flash-loan wrapper that routes arb trades through exchange . Core: CryptopoolLPOracle — oracle source used by PRICE_ORACLE_CONTRACT . Action Flow: Rebalance — end-to-end arb call sequence. User: Math Primer §3 — full invariant derivation. Overview Function Documentation Public Variables Data Structs Events exchange() get_dy() get_state() get_debt() get_rate_mul() set_rate() _deposit() (LT-only) _withdraw() (LT-only) collect_fees() set_fee() (LT-only) set_killed() (LT-only) get_p() value_oracle() value_oracle_for() value_change() max_debt() accumulated_interest() coins() outdated_debt() check_nonreentrant() Related ## /dev/core/virtual-pool On this page The source code of the VirtualPool.vy contract can be found on GitHub . The contract is written with Vyper version 0.4.3. Overview ​ The VirtualPool is a simplified, two-coin swap interface for a market. It lets users trade between the pool's two tokens without ever touching LP tokens . Quotes are provided via get_dy(i, j, in_amount) and swaps execute through exchange(i, j, in_amount, min_out, _for) . Under the hood, swaps are backed by a flash loan of the stablecoin from the Factory's flash provider. For stable→asset, the contract borrows stablecoin, combines it with the user's input to route into LP via the YieldBasis AMM, withdraws back to the pool's coins, repays the flash, and delivers the asset to the recipient. For asset→stable, it borrows stablecoin, adds liquidity together with the user's asset to mint LP, routes LP→stable via the AMM, repays the flash, and delivers the stablecoin. Any LP exposure is strictly transient during the call; users never receive LP. Function Documentation ​ Public Variables ​ Constants ROUNDING_DISCOUNT ( uint256 ) - Rounding discount applied to stablecoin inputs (10^18 / 10^8) Contract Addresses FACTORY ( Factory ) - Factory contract address (immutable) AMM ( YbAMM ) - YieldBasis AMM contract address (immutable) POOL ( Pool ) - Curve pool contract address (immutable) ASSET_TOKEN ( ERC20 ) - Crypto asset token address (immutable) STABLECOIN ( ERC20 ) - Stablecoin token address (immutable) IMPL ( address ) - Implementation address (immutable) View Functions coins(i: uint256) ( ERC20 ) - Returns token address for index i (0=stablecoin, 1=crypto) Data Structs ​ AMMState collateral ( uint256 ) - LP token amount held as collateral debt ( uint256 ) - Interest-accrued stablecoin debt x0 ( uint256 ) - Virtual balance for maintaining leverage Events ​ TokenExchange (Emitted when tokens are exchanged through the VirtualPool) buyer ( address ) - Address that initiated the exchange sold_id ( uint256 ) - Index of token sold (0=stablecoin, 1=asset) tokens_sold ( uint256 ) - Amount of tokens sold bought_id ( uint256 ) - Index of token bought (0=stablecoin, 1=asset) tokens_bought ( uint256 ) - Amount of tokens bought exchange() ​ Description: Executes swaps between stablecoins and crypto assets through the virtual pool mechanism. Uses a flash loan of stablecoin internally — users never need to hold LP tokens. Returns: uint256 - Output amount received after the swap. Emits: TokenExchange . Input Type Description i uint256 Input token index (0=stablecoin, 1=crypto) j uint256 Output token index (must be opposite of i ) in_amount uint256 Amount of input tokens to swap min_out uint256 Minimum acceptable output amount (slippage protection) _for address Recipient address for output tokens (defaults to msg.sender) 📄 View Source Code interface Flash : def flashLoan ( receiver : address , token : address , amount : uint256 , data : Bytes [ 10 ** 5 ] ) - > bool : nonpayable def supportedTokens ( token : address ) - > bool : view def maxFlashLoan ( token : address ) - > uint256 : view ASSET_TOKEN : public ( immutable ( ERC20 ) ) STABLECOIN : public ( immutable ( ERC20 ) ) @external @nonreentrant def exchange ( i : uint256 , j : uint256 , in_amount : uint256 , min_out : uint256 , _for : address = msg . sender ) - > uint256 : assert ( i == 0 and j == 1 ) or ( i == 1 and j == 0 ) flash : Flash = staticcall FACTORY . flash ( ) in_coin : ERC20 = [ STABLECOIN , ASSET_TOKEN ] [ i ] out_coin : ERC20 = [ STABLECOIN , ASSET_TOKEN ] [ j ] assert extcall in_coin . transferFrom ( msg . sender , self , in_amount , default_return_value = True ) data : Bytes [ 128 ] = empty ( Bytes [ 128 ] ) data = abi_encode ( i , in_amount ) extcall flash . flashLoan ( self , STABLECOIN . address , staticcall flash . maxFlashLoan ( STABLECOIN . address ) , data ) out_amount : uint256 = staticcall out_coin . balanceOf ( self ) assert out_amount >= min_out , "Slippage" assert extcall out_coin . transfer ( _for , out_amount , default_return_value = True ) log TokenExchange ( buyer = _for , sold_id = i , tokens_sold = in_amount , bought_id = j , tokens_bought = out_amount ) return out_amount get_dy() ​ Description: Quote the expected output for a given input. Applies the AMM fee and, on i=0 (stable → asset), a small ROUNDING_DISCOUNT to avoid over-estimation. Returns: uint256 - Expected output amount. Input Type Description i uint256 Input token index (0=stablecoin, 1=crypto) j uint256 Output token index (must be opposite of i ) in_amount uint256 Amount of input tokens to swap 📄 View Source Code interface Pool : def approve ( _spender : address , _value : uint256 ) - > bool : nonpayable def coins ( i : uint256 ) - > ERC20 : view def balances ( i : uint256 ) - > uint256 : view def calc_token_amount ( amounts : uint256 [ 2 ] , deposit : bool ) - > uint256 : view def add_liquidity ( amounts : uint256 [ 2 ] , min_mint_amount : uint256 ) - > uint256 : nonpayable def remove_liquidity ( amount : uint256 , min_amounts : uint256 [ 2 ] ) - > uint256 [ 2 ] : nonpayable def totalSupply ( ) - > uint256 : view FACTORY : public ( immutable ( Factory ) ) AMM : public ( immutable ( YbAMM ) ) POOL : public ( immutable ( Pool ) ) ASSET_TOKEN : public ( immutable ( ERC20 ) ) STABLECOIN : public ( immutable ( ERC20 ) ) ROUNDING_DISCOUNT : public ( constant ( uint256 ) ) = 10 ** 18 // 10 ** 8 IMPL : public ( immutable ( address ) ) @external @view def get_dy ( i : uint256 , j : uint256 , in_amount : uint256 ) - > uint256 : assert ( i == 0 and j == 1 ) or ( i == 1 and j == 0 ) _in_amount : uint256 = in_amount if i == 0 : _in_amount = in_amount * ( 10 ** 18 - ROUNDING_DISCOUNT ) // 10 ** 18 return self . _calculate ( i , _in_amount , False ) [ 0 ] @internal @view def _calculate ( i : uint256 , in_amount : uint256 , only_flash : bool ) - > ( uint256 , uint256 ) : stables_in_pool : uint256 = staticcall POOL . balances ( 0 ) out_amount : uint256 = 0 if i == 0 : state : AMMState = staticcall AMM . get_state ( ) pool_supply : uint256 = staticcall POOL . totalSupply ( ) fee : uint256 = staticcall AMM . fee ( ) r0fee : uint256 = stables_in_pool * ( 10 ** 18 - fee ) // pool_supply # Solving quadratic eqn instead of calling the AMM b/c we have a special case b : uint256 = state . x0 - state . debt + in_amount - r0fee * state . collateral // 10 ** 18 D : uint256 = b ** 2 + 4 * state . collateral * r0fee // 10 ** 18 * in_amount flash_amount : uint256 = ( isqrt ( D ) - b ) // 2 # We received this withdrawing from the pool if not only_flash : crypto_in_pool : uint256 = staticcall POOL . balances ( 1 ) out_amount = flash_amount * crypto_in_pool // stables_in_pool # Withdrawal was ideally balanced return out_amount , flash_amount else : crypto_in_pool : uint256 = staticcall POOL . balances ( 1 ) flash_amount : uint256 = in_amount * stables_in_pool // crypto_in_pool if not only_flash : pool_supply : uint256 = staticcall POOL . totalSupply ( ) lp_amount : uint256 = pool_supply * in_amount // crypto_in_pool out_amount = staticcall AMM . get_dy ( 1 , 0 , lp_amount ) - flash_amount return out_amount , flash_amount onFlashLoan() ​ Description: Flash-loan callback. Executes the swap logic: the flash loan borrows stablecoin, the contract performs the token exchange through AMM + Curve pool, then repays the loan. Rejects if the caller is not the configured flash provider or the token is not the stablecoin. Input Type Description initiator address Contract that initiated the flash loan (must be self) token address Token borrowed (must be stablecoin) total_flash_amount uint256 Total amount borrowed including fees fee uint256 Flash loan fee amount data Bytes[10**5] Encoded parameters (i, in_amount) 📄 View Source Code interface Pool : def approve ( _spender : address , _value : uint256 ) - > bool : nonpayable def coins ( i : uint256 ) - > ERC20 : view def balances ( i : uint256 ) - > uint256 : view def calc_token_amount ( amounts : uint256 [ 2 ] , deposit : bool ) - > uint256 : view def add_liquidity ( amounts : uint256 [ 2 ] , min_mint_amount : uint256 ) - > uint256 : nonpayable def remove_liquidity ( amount : uint256 , min_amounts : uint256 [ 2 ] ) - > uint256 [ 2 ] : nonpayable def totalSupply ( ) - > uint256 : view interface YbAMM : def coins ( i : uint256 ) - > ERC20 : view def get_dy ( i : uint256 , j : uint256 , in_amount : uint256 ) - > uint256 : view def get_state ( ) - > AMMState : view def fee ( ) - > uint256 : view def exchange ( i : uint256 , j : uint256 , in_amount : uint256 , min_out : uint256 ) - > uint256 : nonpayable def
프로젝트로 돌아가기