Yield Basis 백서

Yield Basis

원문

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

quidityGauge , and the relevant ERC-20 tokens. Token amounts are in raw units. For LT deposits, compute debt with the asset's decimals: assets * oracle_price / 10**asset_decimals , where oracle_price is crvUSD per whole asset with 18 decimals. Minimal Python-style binding shape: from web3 import Web3 w3 = Web3 ( Web3 . HTTPProvider ( RPC_URL ) ) factory = w3 . eth . contract ( address = FACTORY , abi = FACTORY_ABI ) gc = w3 . eth . contract ( address = GAUGE_CONTROLLER , abi = GAUGE_CONTROLLER_ABI ) # Per market, bind these from Factory.markets(i) lt = w3 . eth . contract ( address = market [ "lt" ] , abi = LT_ABI ) vp = w3 . eth . contract ( address = market [ "virtual_pool" ] , abi = VIRTUAL_POOL_ABI ) asset = w3 . eth . contract ( address = market [ "asset_token" ] , abi = ERC20_ABI ) 1. Discover markets ​ The addresses below are the entrypoints most integrators hardcode. The full per-market list (LEVAMM / VirtualPool / LP Oracle / Gauge per asset), deprecated markets, and DAO/vesting contracts live on the canonical Contract Addresses page. Contract Address Use Factory 0x370a449FeBb9411c95bf897021377fe0B7D100c0 Enumerate markets, resolve per-market contracts GaugeController 0x1Be14811A3a06F6aF4fA64310a636e1Df04c1c21 lt → gauge lookup; gauge voting YB 0x01791F726B4103694969820be083196cC7c045fF YB token VotingEscrow (veYB) 0x8235c179E9e84688FBd8B12295EfC26834dAC211 veYB balance / voting power FeeDistributor 0xD11b416573EbC59b6B2387DA0D2c0D1b3b1F7A90 veYB admin-fee claims StakeZap 0xE862bC39B8D5F12D8c4117d3e2D493Dc20051EC6 Atomic deposit + stake LTMigrator 0xE707c7a9dD58fb7eEa17acFF875CEF8d10eD1a9F Legacy→current market migration (current migrator; older ones listed as deprecated) HybridVaultFactory 0xBdC32268851C324c6185809271dfe6d8dab8dC5b HybridVault deploy/registry crvUSD 0xf939E0A03FB07F59A73314E73794Be0E57ac1b4E Debt asset DAO 0x42F2A41A0D0e65A440813190880c8a65124895Fa Governance execution Enumerate per-market contracts ​ Prefer on-chain enumeration over hardcoding per-market addresses — new markets are added over time and enumeration picks them up automatically. Factory.markets(i) returns a Market struct; the gauge is the struct's staker field (also exposed as LT.staker() ): FACTORY = "0x370a449FeBb9411c95bf897021377fe0B7D100c0" factory = IFactory ( FACTORY ) count = factory . market_count ( ) for i in range ( count ) : m = factory . markets ( i ) # Market struct fields (Factory.vy:32, 7 fields, in this order): # (asset_token, cryptopool, amm, lt, price_oracle, virtual_pool, staker) gauge = m . staker # LiquidityGauge; equivalent to lt.staker() print ( i , m . lt , m . amm , m . virtual_pool , m . price_oracle , gauge ) GaugeController.gauges is an enumerated address[1_000_000_000] indexed by integer, not a mapping by LT address; resolve gauges via the market struct or LT.staker() . To distinguish active vs. deprecated LTs, cross-check against the lists on the Contract Addresses page — the on-chain state is not annotated. LTMigrator handles legacy → current migration. HybridVault discovery ​ Per-user HybridVaults are deployed as minimal proxies pointing to the HybridVault impl . Look up a user's vault via the factory: hvf = IHybridVaultFactory ( "0xBdC32268851C324c6185809271dfe6d8dab8dC5b" ) user_vault = hvf . vaults ( user ) # zero address if no vault 2. Read market state ​ # PPS — fundamental per-share value (oracle-priced, sandwich-resistant) pps = lt . pricePerShare ( ) # Realistic redemption for one share (live Cryptoswap state, includes TRD) redemption = lt . preview_withdraw ( 10 ** 18 ) # TRD for one share (signed) trd = redemption / pps - 1 # negative during a discount; rare positive = premium # Staked bucket state (for staked-position logic) ( admin , total , ideal_staked , staked ) = lt . liquidity ( ) # Oracle price p_o = PriceOracle ( oracle ) . price ( ) The gap between pps and redemption is TRD — a timing mismatch that resolves via arbitrage. For latency-sensitive integrations (e.g. same-block quotes), preview_withdraw is the number to rely on; pricePerShare() is an upper bound. Note: LT does not implement convertToAssets — that function lives on LiquidityGauge (the staker), where it maps gauge-shares to LT-shares. 3. Quote a swap via VirtualPool ​ # crvUSD → asset dy = VirtualPool ( vp ) . get_dy ( 0 , 1 , amount_in ) # asset → crvUSD dy = VirtualPool ( vp ) . get_dy ( 1 , 0 , amount_in ) get_dy prices in the full flash-loan round-trip through LEVAMM + Cryptoswap. Result reflects fees and internal slippage — no further adjustment needed to check arb profitability. Note: for i=0 (crvUSD-in direction), a ROUNDING_DISCOUNT = 1e18 / 1e8 is applied to the input inside the quote (see VirtualPool.vy line 131). Quote and execution may differ by ~1e-8 of input. 4. Execute a swap ​ # asset → crvUSD asset . approve ( vp , amount_in ) out = VirtualPool ( vp ) . exchange ( 1 , 0 , amount_in , min_out , recipient ) # crvUSD → asset crvusd . approve ( vp , amount_in ) out = VirtualPool ( vp ) . exchange ( 0 , 1 , amount_in , min_out , recipient ) The flash loan is taken internally; your account only needs to hold the input token and approve the VirtualPool. Expect 400–600k gas. 5. Deposit / withdraw against LT ​ # Deposit — mints yb-LP asset . approve ( lt , amount ) debt = amount * oracle_price // 10 ** asset_decimals shares_estimate = lt . preview_deposit ( amount , debt ) # raise_overflow=True default; pass False for soft quote shares = lt . deposit ( amount , debt , min_shares , receiver ) # Withdraw — burns yb-LP, returns asset amount = lt . withdraw ( shares , min_assets , receiver ) Gotchas: receiver cannot be the LT.staker address on deposit. Use StakeZap if you want atomic deposit + stake. msg.sender and receiver cannot be the staker address on withdraw. Unstake from gauge first. preview_withdraw(shares) includes TRD. For the fundamental reference, compare against pricePerShare() × shares / 1e18 . Slippage protection: pass a realistic min_shares / min_assets . See Deposit & Withdraw and Action Flow: Deposit / Withdraw for the call-level detail. 6. Watch events ​ Key events you'll care about: Deposit(sender, owner, assets, shares) on LT Withdraw(sender, receiver, owner, assets, shares) on LT Transfer(from, to, value) on LT (ERC-20 side; transfers to/from staker trigger bucket rebalancing) TokenExchange(buyer, sold_id, tokens_sold, bought_id, tokens_bought) on VirtualPool TokenExchange(buyer, sold_id, tokens_sold, bought_id, tokens_bought, fee, price_oracle) on AMM (LEVAMM) Full list: Event Catalog . Related ​ Integration: Deposit & Withdraw Integration: Arbitrage Recipe Integration: Quote & Route Core: VirtualPool Core: LT Contract Addresses Setup assumptions 1. Discover markets Enumerate per-market contracts HybridVault discovery 2. Read market state 3. Quote a swap via VirtualPool 4. Execute a swap 5. Deposit / withdraw against LT 6. Watch events Related ## /dev/integration/deposit-withdraw On this page LT.vy is ERC-4626-like but not strictly compliant. It emits ERC-4626 Deposit / Withdraw events, but its deposit takes an explicit debt parameter (not computed from assets ) and it does not implement convertToAssets , convertToShares , mint , redeem , previewMint , or previewRedeem . It implements IERC20 only. Transfers to/from the staker address are rejected via explicit revert. For strict ERC-4626 semantics, use the LiquidityGauge (staker) instead, which wraps LT shares. This page covers the integration-side call pattern. For the on-chain sequence (what LT does with your deposit), see Action Flow: Deposit and Action Flow: Withdraw . Deposit ​ Signature ​ def deposit( assets: uint256, debt: uint256, min_shares: uint256, receiver: address = msg.sender ) -> uint256 assets — amount of the volatile asset (e.g. WBTC) you are depositing. debt — crvUSD amount LEVAMM will borrow to maintain L = 2 L = 2 L = 2 . For an LT deposit, this is typically the oracle value of the volatile leg: assets × oracle_price / 10**asset_decimals , denominated in crvUSD wei. min_shares — sandwich/slippage protection. receiver — destination for minted yb-LP. Must not equal LT.staker() ; use StakeZap for atomic deposit + stake. Call pattern ​ # 1. Compute expected debt at current oracle price p_o = PriceOracle ( oracle ) . price ( ) debt_estimate = assets * p_o // 10 ** asset_decimals # 2. Preview to get expected shares (reverts if Debt too high) shares_estimate = lt . preview_deposit ( assets , debt_estimate ) # Soft quote alternative: returns 0 instead of reverting on overflow. # Used by LTMigrator and HybridVault. # shares_estimate = lt.preview_deposit(assets, debt_estimate, False) # 3. Approve + deposit asset . approve ( lt , assets ) shares = lt . deposit ( assets , debt_estimate , min_shares , receiver ) Worked example: if the asset uses 18 decimals, assets = 1e18 , and the oracle price is 100_000e18 crvUSD per asset, then debt_estimate = 100_000e18 crvUSD. The AMM's L = 2 target is applied to the resulting Cryptoswap LP collateral value; because the deposit adds both the volatile leg and the borrowed stable leg, the borrowed leg is roughly equal to the volatile leg's oracle value. Error modes ​ Error Cause "Deposit to staker" receiver == LT.staker() . Either pass a different receiver or use StakeZap . "Debt too high" debt exceeds AMM.max_debt() / 2 . Reduce debt or wait for allocation. "Slippage" shares < min_shares . Re-quote via preview_deposit and retry. "Remainder too small" Final supply after mint would be below MIN_SHARE_REMAINDER (1e6) . Increase deposit or combine with another. Gas ​ ~ 300–500k on mainnet. Dominated by Cryptoswap add_liquidity and LEVAMM invariant solve. Withdraw ​ Signature ​ def withdraw( shares: uint256, min_assets: uint256, receiver: address = msg.sender ) -> uint256 Returns the amount of underlying asset received. Call pattern ​ # If staked, unstake first if gauge . balanceOf ( user ) > 0 : lp_amount = gauge . previewRedeem ( gauge . balanceOf ( user ) ) gauge . withdraw ( lp_amount , user , user ) # withdraw(assets, receiver, owner) — returns yb-LP to user # Quote redemption (includes TRD) expected_assets = lt . preview_withdraw ( shares ) # Withdraw with slippage bound assets = lt . withdraw ( shares , min_assets , receiver ) Error modes ​ Error Cause "Withdrawing nothing" shares == 0 . "Withdraw to/from staker" Either msg.sender or receiver equals LT.staker() . Unstake from gauge first. "We're dead. Use emergency_withdraw" AMM.is_killed() == True . Use emergency_withdraw instead; repay debt from wallet. "Slippage" crypto_received < min_assets . Re-quote and retry. "Remainder too small" Post-burn, supply would fall below MIN_SHARE_REMAINDER . Withdraw less, or (if full exit) withdraw all shares atomically — the last-withdrawer path is special-cased. preview_withdraw vs pricePerShare ​ Both speak to per-share value but via different reference prices: pricePerShare() — returns v.total × 1e18 / v.supply_tokens from _calculate_values at oracle price. The fundamental per-share value; sandwich-resistant; does not include TRD. Multiply by shares / 1e18 for per-position PPS. preview_withdraw(shares) — realistic redemption: runs calc_withdraw_fixed_out against the current Cryptoswap state, factoring the fixed-debt-output unwind. Includes TRD. TRD = preview_withdraw(1e18) / pricePerShare() − 1 for one share, or generally preview_withdraw(shares) × 1e18 / (pricePerShare() × shares) − 1 . Negative during a discount (the common case); positive in the rare premium case. See Temporary Redemption Discount for resolution dynamics. Note: LT does not expose convertToAssets — it implements IERC20 only. The ERC-4626 convertToAssets / previewRedeem shape lives on LiquidityGauge instead, where it maps gauge-shares to underlying LT-shares. Gas ​ ~ 300–450k. Dominated by Cryptoswap remove_liquidity_fixed_out and LEVAMM accounting. Staked positions ​ If the user has yb-LP staked in LiquidityGauge : Call gauge.withdraw(assets, receiver, owner) (strict ERC-4626 signature; assets = yb-LP amount) — transfers yb-LP back to the receiver, forfeiting future emissions. Accrued emissions are claimable separately. Then call LT.withdraw as above. There is no combined "unstake + withdraw" helper. Use multicall if atomicity matters. Preview reliability ​ Preview functions are view calls that read current state. In the same block, they are accurate. Across blocks, state may change (oracle updates, rebalance trades, other LPs' deposits/withdrawals). For MEV-sensitive flows: Quote in the simulation, then execute with tight min_* bounds. preview_withdraw varies with Cryptoswap state — re-quote if you observe large trades in the mempool. preview_deposit varies with LEVAMM invariant state — same advice. Events ​ Event When Deposit(sender, owner, assets, shares) Every deposit Withdraw(sender, receiver, owner, assets, shares) Every withdraw Transfer(from, to, value) ERC-20 transfers of yb-LP, plus bucket-reallocation transfers on stake/unstake DistributeBorrowerFees(sender, amount, min_amount, discount) When LT routes borrower interest to the donation path Related ​ Core: LT — full contract reference. Action Flow: Deposit — what LT does on-chain. Action Flow: Withdraw — on-chain withdraw sequence. Quote & Route — shared preview patterns. Error Codes — full error-string catalog. Protocol: Temporary Redemption Discount — why preview_withdraw < pricePerShare × shares / 1e18 . Deposit Signature Call pattern Error modes Gas Withdraw Signature Call pattern Error modes preview_withdraw vs pricePerShare Gas Staked positions Preview reliability Events Related ## /dev/integration/arbitrage On this page Overview ​ The Yield Basis system maintains 2x leverage through two key mechanisms: AMM (Automated Market Maker) : Uses mathematical bonding curves to maintain constant leverage Virtual Pool : Enables arbitrage without requiring users to handle LP tokens directly Arbitrage opportunities arise when: AMM prices deviate from Curve pool prices Leverage ratios drift from the target 2x How the VirtualPool routes trades ​ The VirtualPool enables arbitrage between STABLECOIN (i=0) and ASSET (i=1) using the Curve pool and the market's LEVAMM , facilitated by a flash loan of the stablecoin from Factory.flash() . Flash loan covers only the opposite leg : you supply the input token (BTC or crvUSD); the VirtualPool flash-borrows stablecoin (crvUSD) internally. No LP handling : LP mint/burn is internal — users never receive LP tokens. Safety & leverage : The LEVAMM enforces a constant-leverage curve (L≈2× in YieldBasis) with a safety band; VirtualPool just routes trades through it. Protection : Always quote with get_dy() and set min_out to avoid unprofitable fills. Stable → Asset Swaps ( i=0, j=1 ) : User sends crvUSD to VirtualPool. VirtualPool takes a stablecoin flash loan . VirtualPool buys LP from the AMM : AMM.exchange(0, 1, user_stable*(1−ROUNDING_DISCOUNT)+flash, 0) . VirtualPool removes liquidity in the Curve pool: POOL.remove_liquidity(lp_amount, [0,0]) . VirtualPool repays the flash loan from the stable side. Remaining asset is transferred to the user. Asset → Stable Swaps ( i=1, j=0 ) : User sends BTC to VirtualPool. VirtualPool takes a stablecoin flash loan . VirtualPool mints LP in the Curve pool: POOL.add_liquidity([flash, user_asset], 0) . VirtualPool sells LP to the AMM : AMM.exchange(1, 0, lp_amount, 0) . VirtualPool repays the flash loan . Remaining stablecoin is transferred to the user. The flash callback enforces that the caller is the configured flash provider and the borrowed token is the stablecoin . A small ROUNDING_DISCOUNT is applied on stable→asset quotes to avoid over-estimation. Mathematical Foundation ​ Leverage Calculation ​ The AMM maintains leverage through a bonding curve: # AMM.vy def get_x0 ( p_o : uint256 , collateral : uint256 , debt : uint256 , safe_limits : bool ) - > uint256 : # x0 represents the virtual balance maintaining 2x leverage # p_o = oracle price # collateral = LP token amount (the AMM's collateral) # debt = stablecoin debt (interest-accrued where applicable) # safe_limits = enforce safety band when True Target Leverage : 2x (50% debt-to-value ratio) Price Increase : DTV < 50% → Arbitrageurs add debt to restore leverage Price Decrease : DTV > 50% → Arbitrageurs reduce debt to restore leverage How the code creates (and enforces) arbitrage back to ~2× ​ The LEVAMM prices trades on a constant-leverage curve anchored to the oracle, and it only accepts trades that move the system toward the safe region around 2×. When debt-to-value (DTV) drifts away from ~50%, the AMM's quoted price for LP ↔ crvUSD shifts so that an external route (Curve mint/burn) + AMM.exchange becomes profitable. VirtualPool packages that route with a flash-loaned stable leg so arbitrageurs never touch LP. State & price basis get_state() exposes (collateral, debt, x0) where collateral is LP amount and debt is interest-accrued. get_p() derives the AMM price (stable per LP) from the oracle and current state: it uses get_x0(p_o, collateral, debt, False) internally. Safety band (keeps DTV sane) get_x0(p_o, collateral, debt, safe_limits=True) enforces min/max debt vs oracle collateral value (for L=2×, roughly 6.25%–53.125% of value). Every trade ends with: # AMM.exchange(...) assert self . get_x0 ( p_o , collateral_after , debt_after , True ) >= x0_before , "Bad final state" This rejects trades that would leave safe bounds or move the state toward the "untradable" region. In practice it nudges the system back toward the 2× area. Directional inventory changes Stable → LP ( exchange(0,1,…) ): reduces debt , reduces collateral (AMM sells LP for stables to the trader). Used to decrease DTV when the system is over-leveraged. LP → Stable ( exchange(1,0,…) ): increases debt , increases collateral (AMM buys LP from the trader, paying stables). Used to increase DTV when the system is under-leveraged. These updates are explicit in exchange(...) after computing out_amount . Why the price becomes favorable (how the spread appears) ​ Quotes come from the curve, not from the pool: get_dy(i, j, in_amount) (and its on-chain twin inside exchange(...) ) uses the constant-leverage geometry (via x0 , x_initial ) and applies fee . The resulting marginal price moves with DTV . If the AMM is under-leveraged (DTV < 50%), it bids LP aggressively in get_dy(1→0) (LP→crvUSD). Selling LP to the AMM and redeeming/creating LP via Curve becomes attractive → arbitrage adds debt (pushes DTV up). If the AMM is over-leveraged (DTV > 50%), it offers LP cheaply in get_dy(0→1) (crvUSD→LP). Buying LP from the AMM and burning it to underlying via Curve becomes attractive → arbitrage reduces debt (pushes DTV down). Oracle-anchored pricing: get_p() and get_x0() both use the pool's oracle price ( PRICE_ORACLE_CONTRACT.price() / price_w() ), so quoted trades react to exogenous price moves. After a price jump/drop, the AMM quote shifts immediately, creating the spread vs the Curve mint/burn price that VirtualPool exploits. Fees & rounding: Each quote applies fee (AMM) and, on the VirtualPool's stable→asset path, a small ROUNDING_DISCOUNT to avoid over-estimating user input. These don't create the opportunity, but they set the threshold where arbitrage becomes profitable after gas/flash costs. How VirtualPool turns the quote into an executable arb ​ VirtualPoo
프로젝트로 돌아가기