Yield Basis 백서

Yield Basis

원문

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

nnot withdraw stables Oracle broken, not opting into stablecoin path Not enough crvUSD left Backing would drop below requirement Token not allowed recover_tokens targets protected token Oracle is broken Global and per-pool oracle both fail Zero shares emergency_withdraw(0) HybridVaultFactory.vy ​ String Cause Already created User already has a vault Vault not allowed crvusd_vault not in allow-list Vault impl not set vault_impl == 0 Access Non-ADMIN on admin function Only vaults can call update_* from non-registered vault Vault wind-down Requirement increase on disallowed vault Beyond vault limit Increase exceeds crvusd_vault_limits LTMigrator.vy ​ String Cause lt_to deprecated Migration target has been deprecated not enough out shares_out < min_out in migrate_staked DAO ​ YB.vy ​ String Cause erc20: access is denied emit not from a minter VotingEscrow.vy ​ String Cause Min value create_lock / increase_amount value < UMAXTIME Withdraw old tokens first create_lock with existing lock Can only lock until time in the future unlock_time ≤ now Voting lock can be 4 years max Exceeds 4y No existing lock found increase_amount on empty Cannot add to expired lock. Withdraw Expired lock Nothing is locked increase_unlock_time on empty Lock expired Expired lock Can only increase lock duration New end ≤ current end Not allowed infinite_lock_toggle blocked by clearance checker The lock didn't expire withdraw before expiry Not supported delegate / delegateBySig erc721: caller is not token owner or approved Transfer auth fail Wrong token ID Token ID mismatches owner's address Need max veLock Transfer with non-max or non-infinite locks GaugeController.vy ​ String Cause Gauge already added Duplicate gauge registration Gauge not alive Gauge has no live weight Vote checker not set veYB's transfer_clearance_checker ≠ this Mismatch in lengths Array-length mismatch Expired User's veYB lock expired Weight too large Single weight > 10000 bps Killed Voting for killed gauge Gauge not added Unregistered gauge ( vote_for_gauge_weights or set_killed ) Cannot vote so often Same-gauge re-vote within 10 days Used too much power Sum of veYB vote weights across gauges exceeds 10000 bps (100%) after this vote LiquidityGauge.vy ​ String Cause YB add_reward / deposit_reward targets YB LP_TOKEN add_reward targets LT Already added Duplicate add_reward Not added Unknown reward in change_reward_distributor / deposit_reward No rewards deposit_reward(0) Finishes in the past New finish time ≤ now Rate unknown Extending past old finish time No reward Zero distributor erc4626: deposit/mint/withdraw/redeem more than maximum Cap breach receiver Kill-mode redeem with receiver ≠ owner FeeDistributor.vy ​ String Cause Ded fill_epochs when killed Might be a vest Fee claim routed through a vesting escrow when direct receiver rules do not allow it InflationaryVest.vy ​ String Cause Admin required start / set_recipient from non-owner Already started Second start() VestingEscrow.vy ​ String Cause Lengths mismatch fund with mismatched arrays Rugged Re-target rugged recipient Disabled Re-fund disabled recipient Cannot disable toggle_disable when can_disable = False Not disabled rug_disabled on enabled CliffEscrow.vy ​ String Cause Empty recipient initialize(recipient=0) Already initialized Re-init Cliff still applies Transfer/approve before unlock_time Not authorized Non-recipient ve op Cannot recover YB recover_token(YB) SnapshotSplitter.vy ​ String Cause Already claimed Double-claim CallComparator.vy ​ String Cause Not equal check_equal Equal check_nonequal Not greater check_gt Not less check_lt Timestamp not greater check_timestamp_gt Timestamp not less check_timestamp_lt Too early check_called_after rate limit TokenSender , Multisend , StakeZap ​ No custom revert strings. Fail on token-transfer reverts. Related ​ Event Catalog Core: AMM Core: LT Core LT.vy AMM.vy VirtualPool.vy Factory.vy HybridVault.vy HybridVaultFactory.vy LTMigrator.vy DAO YB.vy VotingEscrow.vy GaugeController.vy LiquidityGauge.vy FeeDistributor.vy InflationaryVest.vy VestingEscrow.vy CliffEscrow.vy SnapshotSplitter.vy CallComparator.vy TokenSender , Multisend , StakeZap Related ## /dev/action-flows/deposit On this page Deposit places the user into a 2×-leveraged LP position in one atomic call. The borrow is internal (LT holds the debt, not the user); the user only provides the volatile asset. Why the borrowed leg matches the deposit value ​ The debt parameter targets L = 2 inside the AMM. At equilibrium, AMM collateral value is about 2 × debt in crvUSD-denominated units. An LT deposit creates that collateral by adding the user's volatile asset plus the borrowed stable leg into Cryptoswap, so the LT-call estimate is: debt ≈ assets × oracle price 10 asset decimals \text{debt} \approx \frac{\text{assets} \times \text{oracle price}}{10^{\text{asset decimals}}} debt ≈ 1 0 asset decimals assets × oracle price ​ Example: if the asset has 18 decimals, assets = 1e18 , and the oracle price is 100_000e18 crvUSD per asset, then debt_estimate = 100_000e18 crvUSD. The resulting Cryptoswap LP collateral is roughly the volatile leg plus the borrowed stable leg, so AMM debt is about half of collateral value. The tradeoff: leverage amplifies Cryptoswap fee capture (you hold 2× the LP exposure of a flat deposit) but also amplifies any IL-related drawdown if markets move before arbitrageurs have rebalanced LEVAMM back to L=2. Continuous rebalancing via arb (see Compounding Leverage ) is what keeps the amplification bounded. Safety band ​ At L = 2 , the AMM enforces a band on coll_vs_debt = p_o × y / d of roughly 6.25% to 53.125% around the target. A debt that would push post-deposit state outside this band reverts — including debt = 0 in almost all cases. The edge-cases table below shows the concrete failure modes. Use LT.preview_deposit(assets, debt) to check before sending the transaction. What happens inside Cryptoswap (separate from LEVAMM) ​ When LT calls add_liquidity , Cryptoswap may internally rebalance its price_scale if the deposit moves the pool's target price. This is not the same as LEVAMM rebalancing: Cryptoswap price_scale rebalance — internal to the pool, fee-funded. May consume rebalance reserve when price_scale shifts. Can impact all Cryptoswap LPs (including LEVAMM as holder). LEVAMM L=2 drift correction — happens later via arb trades through VirtualPool . Not triggered by this deposit directly. The two are decoupled. Your deposit interacts with the first; the second cleans up any oracle-vs-LEVAMM drift afterwards. Contracts touched ​ LT.vy — entry; manages share accounting and bucket reallocation. AMM.vy (LEVAMM) — receives LP as collateral, updates debt and invariant state via _deposit . Curve Cryptoswap — add_liquidity with LEVAMM as receiver. The AMM address holds the borrowing budget (allocated by Factory.set_allocator ); crvUSD flows from the AMM to LT to Cryptoswap. Events emitted ​ LT.Deposit(sender, owner, assets, shares) AMM.AddLiquidityRaw(token_amounts, invariant, price_oracle) Cryptoswap.AddLiquidity (from the pool) LT.DistributeBorrowerFees(sender, amount, min_amount, discount) — on the refuel hook Edge cases ​ Case Behaviour receiver == LT.staker() Reverts "Deposit to staker" Post-deposit value > AMM.max_debt() / 2 Reverts "Debt too high" Computed shares < min_shares Reverts "Slippage" Post-mint shares + supply < MIN_SHARE_REMAINDER (1e6) Reverts "Remainder too small" Cryptoswap balance too imbalanced for the requested deposit Reverts from Cryptoswap Gas ​ ~ 300–500k on mainnet, dominated by add_liquidity and LEVAMM invariant solve. Computing debt before the call ​ p_o = PriceOracle ( oracle ) . price ( ) debt_estimate = assets * p_o // 10 ** asset_decimals # Preview to check safety bounds before committing shares_estimate = lt . preview_deposit ( assets , debt_estimate ) preview_deposit reverts with "Debt too high" if debt_estimate would breach AMM.max_debt() / 2 . To get a soft quote (return 0 instead of reverting), pass a third argument raise_overflow=False . LTMigrator and HybridVault use this path. Related ​ Core: LT Core: AMM (LEVAMM) Integration: Deposit & Withdraw Protocol: Constant-Leverage Rebalancing Why the borrowed leg matches the deposit value Safety band What happens inside Cryptoswap (separate from LEVAMM) Contracts touched Events emitted Edge cases Gas Computing debt before the call Related ## /dev/action-flows/withdraw On this page Withdraw unwinds the position proportionally. The user receives the volatile asset; LT handles debt repayment and share burning atomically. remove_liquidity_fixed_out takes a fixed debt-token amount out (pinning the crvUSD side) and lets the asset side float — that is how LT guarantees the AMM's debt is repaid exactly while the user receives whatever asset falls out. Why you might receive less than PPS × shares ​ Three independent causes. A single withdrawal can experience any combination of them. 1. Temporary Redemption Discount (TRD) ​ Nature : LEVAMM's invariant-implied state vs. Cryptoswap's current price disagree at the moment of withdrawal. Sign : preview_withdraw(shares) < pricePerShare() × shares / 1e18 . Resolution : transient — closes as arbs move through VirtualPool and realign LEVAMM with Cryptoswap. Typical: hours to days. Applies to : both staked and unstaked positions. Reference : Protocol: TRD . 2. PPS drag ​ Nature : cumulative rebalance slippage over the holding period exceeded cumulative fees captured. PPS grew less than a corresponding unleveraged position would suggest — drag is embedded in the vault's accounting, not a transient gap. Sign : even with TRD = 0 , the redemption value at unwind is below a hypothetical "pure-fees" expectation. Resolution : only recovers if forward fee capture outpaces forward rebalance cost — not guaranteed. Applies to : unstaked positions (staked has watermark protection). Reference : Protocol: PPS vs Redemption Value . 3. Watermark shortfall ​ Nature : staked < ideal_staked at the time of withdrawal. The staked bucket has absorbed losses that have not yet been paid back by incoming fees. Sign : staked-position redemption below the watermark; visible as 1 − staked/ideal_staked . Resolution : transient — Recovery Mode routes all admin fee to the staked bucket until parity is restored. Applies to : staked positions only. Reference : Protocol: Watermark & Recovery . Interaction ​ TRD and watermark shortfall are independent — a withdrawal can have nonzero TRD while also seeing a watermark shortfall. PPS drag is structurally different (accumulated inside PPS itself) and coexists with both. Use preview_withdraw for a pre-trade estimate that includes TRD, and inspect LT.liquidity for the watermark gap separately. PPS drag is visible only by comparing realised PPS to expectation over your holding period — there is no single on-chain value that surfaces it. Events emitted ​ LT.Withdraw(sender, receiver, owner, assets, shares) AMM.RemoveLiquidityRaw(collateral_change, debt_change) Cryptoswap.RemoveLiquidity (from the pool) LT.DistributeBorrowerFees — on the refuel hook Edge cases ​ Case Behaviour shares == 0 Reverts "Withdrawing nothing" msg.sender == staker() or receiver == staker() Reverts "Withdraw to/from staker" — unstake from gauge first AMM.is_killed() Reverts "We're dead. Use emergency_withdraw" crypto_received < min_assets Reverts "Slippage" Post-burn supply < MIN_SHARE_REMAINDER + shares and supply ≠ shares Reverts "Remainder too small" — withdraw more or withdraw all Gas ​ ~ 300–450k on mainnet, dominated by Cryptoswap remove_liquidity_fixed_out and LEVAMM invariant update. Related ​ Core: LT Integration: Deposit & Withdraw Guide: Withdraw Liquidity Protocol: TRD Protocol: Watermark & Recovery Protocol: PPS vs Redemption Value Why you might receive less than PPS × shares 1. Temporary Redemption Discount (TRD) 2. PPS drag 3. Watermark shortfall Interaction Events emitted Edge cases Gas Related ## /dev/action-flows/rebalance On this page LEVAMM does not rebalance itself. It posts quotes via its invariant. When an arbitrageur finds the quote profitable versus Cryptoswap spot, their trade moves LEVAMM's state — and by construction that state drift is toward L = 2 L = 2 L = 2 . The two prices ​ LEVAMM holds Curve LP as collateral ( y y y ) and owes crvUSD as debt ( d d d ). Its invariant links those to an "x0" quantity derived from the oracle price ( p o p_o p o ​ ): x 0 ( p o , y , d ) = p o ⋅ y + ( p o ⋅ y ) 2 − 4 ⋅ LEV_RATIO ⋅ p o ⋅ y ⋅ d 2 ⋅ LEV_RATIO x_0(p_o, y, d) = \frac{p_o \cdot y + \sqrt{(p_o \cdot y)^2 - 4 \cdot \text{LEV\_RATIO} \cdot p_o \cdot y \cdot d}}{2 \cdot \text{LEV\_RATIO}} x 0 ​ ( p o ​ , y , d ) = 2 ⋅ LEV_RATIO p o ​ ⋅ y + ( p o ​ ⋅ y ) 2 − 4 ⋅ LEV_RATIO ⋅ p o ​ ⋅ y ⋅ d ​ ​ From AMM.vy::get_x0 (lines 142–157). The AMM then quotes at get_p() = (x0 − d) / y scaled to collateral precision. When get_p() drifts from Cryptoswap's implied LP price, an arb can flash-loan crvUSD, trade through LEVAMM in one direction, round-trip through Cryptoswap in the other, and pocket the gap minus fees and flash premium. The call path ​ The arb invokes VirtualPool.exchange , which internally flash-borrows crvUSD, trades against LEVAMM, and unwinds through Cryptoswap. Reference: VirtualPool.vy::exchange (lines 182–210) and ::onFlashLoan (lines 136–179). crvUSD → asset (buy direction) ​ asset → crvUSD (sell direction) ​ What the trade changes on LEVAMM ​ The AMM.exchange call (lines 286–365) updates stored state: collateral_amount ( y ) — increases on asset-in direction, decreases on asset-out. debt — mirror change after accrual via _debt_w() . A fee is carved from the output ( out = raw_out × (1 − fee) / 1e18 ). The fee is not sent elsewhere; it stays in the AMM, which means the new x0 is strictly greater than the old x0 . The invariant check at line 353 enforces this directly: assert self.get_x0(p_o, collateral, debt, check_state) >= x0, "Bad final state" x0 after the trade must equal or exceed x0 before. That is how fees are captured and how the AMM refuses trades that would leave it worse off. Why this drifts toward L = 2 L = 2 L = 2 ​ At equilibrium, collateral value equals twice the debt ( p o ⋅ y ⋅ COLLATERAL_PRECISION = 2 ⋅ d p_o \cdot y \cdot \text{COLLATERAL\_PRECISION} = 2 \cdot d p o ​ ⋅ y ⋅ COLLATERAL_PRECISION = 2 ⋅ d in 1e18 units). The AMM tracks deviation as coll_vs_debt = p_o × y / d and applies the invariant check asymmetrically ( AMM.vy lines 337–351): If the trade moves coll_vs_debt toward 2, the strict check is relaxed ( check_state = False ). If the trade moves it away , the strict safe-bounds check runs. Arbs only trade when the quote-vs-spot gap exceeds costs. That gap opens precisely when oracle price has moved and the AMM is off-equilibrium. The profitable arbs are the ones that reduce that offset. The AMM doesn't pull the system back — it tilts the field so the profitable path for arbs is the restoring one. Post-trade hooks ​ If LT_CONTRACT is set and is a contract, the exchange ends by calling _collect_fees() and LT.distribute_borrower_fees() (AMM.vy lines 361–363). Accrued interest flows from AMM's stablecoin balance into LT's accounting on every user-facing swap. Not a gas-optional path — it runs unconditionally. Interest accrual and rate setting ​ Interest accrues on the crvUSD CDP line inside LEVAMM via a compounding multiplier: # AMM.vy def _rate_mul ( ) - > uint256 : return unsafe_div ( self . rate_mul * ( 10 ** 18 + self . rate * ( block . timestamp - self . rate_time ) ) , 10 ** 18 ) Admin sets the rate through LT , which forwards to AMM ( LT.set_rate → AMM.set_rate ), bounded by MAX_RATE (≤ 100% APR). The realized rate updates on every _collect_fees() call, which runs on every rebalance exchange. Refueling loop ​ When LT receives stablecoin fees from AMM, it donates them back into the Cryptoswap pool rather than skimming. This concentrates pool liquidity without minting LP to LT: # LT.vy def _distribute_borrower_fees ( discount : uint256 ) : amount = STABLECOIN . balanceOf ( self ) if amount > 0 : min_amount = ( 10 ** 18 - discount ) * amount // CRYPTOPOOL . lp_price ( ) CRYPTOPOOL . add_liquidity ( [ amount , 0 ] , min_amount , empty ( address ) , True ) # donation=True donation=True means no LP minted; the tokens just deepen the pool. 100% of borrower interest cycles back into the pool where it benefits all Cryptoswap LPs — including LEVAMM as the dominant holder. See User: Refueling & Donations for the economic framing. Gas and failure modes ​ Condition Behaviour AMM killed exchange reverts ( assert not self.is_killed ) Empty AMM ( collateral_amount = 0 ) Reverts "Empty AMM" Resulting x0 < prior x0 Reverts "Bad final state" coll_vs_debt outside safe bounds and moving away from L=2 Reverts "Unsafe min" / "Unsafe max" min_out unmet Reverts "Slippage" VirtualPool flash loan not set on Factory flashLoan call reverts Gas: one flash loan (crvUSD), one AMM.exchange (includes _debt_w , price_w , invariant solve, fee collect, and LT hook), one CurveCryptoPool.remove_liquidity or add_liquidity . Typically 400–600k on mainnet depending on Cryptoswap state. Related ​ Core: AMM Core: VirtualPool Integration: Arbitrage Recipe Compounding Leverage The two prices The call path crvUSD → asset (buy direction) asset → crvUSD (sell direction) What the trade changes on LEVAMM Why this drifts toward L = 2 Post-trade hooks Interest accrual and rate setting Refueling loop Gas and failure modes Related ## /dev/action-flows/stake-unstake On this page Stake ​ Unstake ​ LT accounting on stake/unstake ​ From LT.vy (~lines 980–1012), transferring into/out of staker : Stake: increase staked by proportional value, increase ideal_staked proportionally. Unstake: decrease staked proportionally to shares removed; ideal_staked adjusted in same ratio. Related ​ Core: LT DAO: LiquidityGauge Protocol: Watermark & Recovery Guide: Stake yb-LP Stake Unstake LT accounting on stake/unstake Related ## /dev/core/lt On this page The source code of the LT.vy contract can be found on GitHub . The contract is written with Vyper version 0.4.3. Overview ​ The LT contract is the market’s leveraged-liquidity share token (ERC-20, 18 decimals; symbol yb-asset ). Users deposit the asset token (e.g., BTC) while the contract borrows a matching amount of stablecoin liquidity from the market (via its allocation) to mint Curve LP and hand the LP into the LEVAMM . In return, users receive LT shares that represent a pro-rata claim on the AMM position’s value. Withdrawals burn shares and unwind through the AMM and Curve pool back to asset (and any required stablecoin settlement). The contract exposes standard deposit/withdraw flows with slippage guards and a fair, oracle-anchored price-per-share. LT also manages the yb markets: it owns the LEVAMM instance, forwards interest-rate and fee updates to the AMM, manages the stablecoin allocation to the AMM ( allocate_stablecoins ), and periodically sweeps borrower interest collected in the AMM into the Curve pool as LP tokens ( distribute_borrower_fees ). An optional staker address can be set once to integrate with gauges/rewards, and admin fees are tracked and withdrawable to the protocol’s fee receiver. Safety is enforced with access controls (admin/factory admins), non-reentrancy on state-changing entry points, kill/unkill passthrough to the AMM, and oracle-based checks to keep the position within safe bounds. Deployed by the Factory: LT instances are cloned from the configured implementation using Vyper’s cre
프로젝트로 돌아가기