l's
exchange(i, j, in_amount, min_out)
wraps the profitable side
without LP custody
:
Stable → Asset Swaps (crvUSD→BTC)
: flash-borrow stable →
AMM.exchange(0,1, …)
(stable→LP) →
POOL.remove_liquidity(lp, [0,0])
→ repay flash from the stable side → user receives
asset
.
Asset → Stable Swaps (BTC→crvUSD)
: flash-borrow stable →
POOL.add_liquidity([flash, asset], 0)
(mint LP) →
AMM.exchange(1,0, lp, 0)
(LP→stable) → repay flash → user receives
crvUSD
.
Because the AMM quote
improves
in the direction that restores 2×, the combined AMM+Curve route yields
positive edge
whenever DTV has drifted enough to cover fees. The final
assert
in
AMM.exchange
guarantees that any executed trade has moved the state
toward
safety, never away.
Relevant functions to read:
AMM
:
get_state
,
get_p
,
get_dy
,
exchange
,
get_x0
,
set_rate
,
fee
,
MIN_SAFE_DEBT
,
MAX_SAFE_DEBT
— see
AMM documentation
.
VirtualPool
:
get_dy
,
exchange
,
_calculate
,
onFlashLoan
— see
VirtualPool documentation
.
Arbitrage Profit Calculation
Use
VirtualPool.get_dy()
to calculate expected output tokens:
📋
VirtualPool.get_dy()
Source Code
# i=0: crvUSD → BTC, i=1: BTC → crvUSD
out
=
VirtualPool
.
get_dy
(
i
,
j
,
in_amount
)
@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
# Check expected crvUSD output for BTC input
expected_crvusd
=
VirtualPool
.
get_dy
(
1
,
0
,
0.1
*
10
**
8
)
# BTC → crvUSD
# Check expected BTC output for crvUSD input
expected_btc
=
VirtualPool
.
get_dy
(
0
,
1
,
10_000
*
10
**
18
)
# crvUSD → BTC
Important
: The VirtualPool handles the entire arbitrage process internally:
Takes your input
(BTC or crvUSD)
Executes LP ↔ crvUSD trades
using flash loans
Returns the entire output amount
in the output token (crvUSD or BTC)
Note
:
get_dy()
already reflects the full internal route (AMM + Curve + flash repay). No LP math needed.
See this
Google Colab notebook
for a working example of calculating expected outputs.
Arbitrage Scenarios
The two VirtualPool routes. Each restores the LEVAMM debt-to-value ratio toward 50% while paying the arbitrageur the price gap.
Scenario 1: BTC Price Increases
BTC price increases from $100,000 to $110,000 (+10%)
Initial State
:
LP Composition
: 1 BTC + 100,000 crvUSD
LP Value
: $200,000
Debt
: $100,000
Debt-to-Value
: 50%
After Price Increase
:
LP Value
: $210,000 (1 BTC × $110,000 + 100,000 crvUSD)
Debt
: $100,000 (unchanged)
Debt-to-Value
: 47.62% (below target 50%)
Why Arbitrage Opportunity Exists
:
The AMM's bonding curve pricing creates an incentive when DTV ≠ 50%:
Current DTV
: 47.62% (under-leveraged)
Target DTV
: 50% (2x leverage)
AMM Trading
: AMM trades LP tokens ↔ crvUSD
Arbitrage Opportunity
: When under-leveraged, AMM offers better prices for selling LP tokens (getting crvUSD)
Economic Incentive
: Arbitrageurs can profit by selling LP tokens to the AMM, which reduces the AMM's LP position and increases its crvUSD, restoring 50% DTV
Arbitrage Process
:
Note
: The Virtual Pool handles all the complex logic internally. Arbitrageurs simply call
VirtualPool.exchange()
.
Internal Steps
(handled automatically by Virtual Pool):
Input
: BTC to Virtual Pool via
VirtualPool.exchange(1, 0, asset_in, min_out)
Flash borrow
: stablecoin from
Factory.flash()
Mint LP
:
POOL.add_liquidity([flash_stable, asset_in], 0)
→ mint LP
Sell LP
:
AMM.exchange(1, 0, lp_amount, 0)
→ LP → stable
Repay flash
: from stable side
Output
: remaining stablecoin (crvUSD) → arbitrageur
Scenario 2: BTC Price Decreases
BTC price decreases from $100,000 to $90,000 (-10%)
Initial State
:
LP Composition
: 1 BTC + 100,000 crvUSD
LP Value
: $200,000
Debt
: $100,000
Debt-to-Value
: 50%
After Price Decrease
:
LP Value
: $190,000 (1 BTC × $90,000 + 100,000 crvUSD)
Debt
: $100,000 (unchanged)
Debt-to-Value
: 52.63% (above target 50%)
Why Arbitrage Opportunity Exists
:
The AMM's bonding curve pricing creates an incentive when DTV ≠ 50%:
Current DTV
: 52.63% (over-leveraged)
Target DTV
: 50% (2x leverage)
AMM Trading
: AMM trades LP tokens ↔ crvUSD
Arbitrage Opportunity
: When over-leveraged, AMM offers better prices for buying LP tokens (spending crvUSD)
Economic Incentive
: Arbitrageurs can profit by buying LP tokens from the AMM, which increases the AMM's LP position and reduces its crvUSD, restoring 50% DTV
Arbitrage Process
:
Note
: The Virtual Pool handles all the complex logic internally. Arbitrageurs simply call
VirtualPool.exchange()
.
Internal Steps
(handled automatically by Virtual Pool):
Input
: crvUSD to Virtual Pool via
VirtualPool.exchange(0, 1, stable_in, min_out)
Flash borrow
: stablecoin from
Factory.flash()
Buy LP
:
AMM.exchange(0, 1, stable_in*(1-ROUNDING_DISCOUNT) + flash, 0)
→ stable → LP
Remove liquidity
:
POOL.remove_liquidity(lp_amount, [0, 0])
→ LP → (stable, asset)
Repay flash
: from stable side
Output
: remaining asset (BTC) → arbitrageur
How to Execute Arbitrage
Flash sizing is internal.
exchange
borrows the lender's full capacity (
flash.maxFlashLoan
) and the callback computes the amount it actually needs by solving the same quadratic documented in
Math Primer §3.5
; everything unused is repaid in the same transaction.
Step 1: Check for Arbitrage Opportunities
Price Comparison
:
Get AMM LP price:
AMM.get_p()
— returns stable per LP (see
AMM documentation
)
Get Curve LP price:
POOL.lp_price()
(or
POOL.get_virtual_price()
) — returns stable per LP
Compare LP prices to identify opportunities
Leverage Check
:
Get current AMM state:
AMM.get_state()
— returns
(collateral, debt, x0)
(see
AMM documentation
)
Calculate current DTV ratio:
debt / (collateral * price)
(use the oracle price, not
get_p()
)
Target DTV should be 50% (2x leverage)
Step 2: Calculate Expected Profit
For Price Increase Arbitrage
:
# Calculate expected output from Virtual Pool
expected_output
=
VirtualPool
.
get_dy
(
1
,
0
,
btc_amount
)
profit
=
expected_output
-
btc_amount
*
market_price
For Price Decrease Arbitrage
:
# Calculate expected output from Virtual Pool
expected_output
=
VirtualPool
.
get_dy
(
0
,
1
,
stablecoin_amount
)
profit
=
expected_output
-
stablecoin_amount
/
market_price
Step 3: Execute Arbitrage
Price Increase (BTC → crvUSD)
:
# Call Virtual Pool exchange
VirtualPool
.
exchange
(
1
,
0
,
btc_amount
,
min_out_amount
)
Price Decrease (crvUSD → BTC)
:
# Call Virtual Pool exchange
VirtualPool
.
exchange
(
0
,
1
,
stablecoin_amount
,
min_out_amount
)
Key Functions for Arbitrage
VirtualPool Functions
get_dy() — Expected Output
:
# Returns expected output in either stablecoin or asset
# i=0: stablecoin, i=1: asset
expected_output
=
VirtualPool
.
get_dy
(
i
,
j
,
in_amount
)
coins() — Token Addresses
:
# Get token addresses
stablecoin
=
VirtualPool
.
coins
(
0
)
# crvUSD address
asset
=
VirtualPool
.
coins
(
1
)
# BTC address
AMM Functions
get_state() — Current State
:
# Returns (collateral, debt, x0)
state
=
AMM
.
get_state
(
)
collateral
=
state
[
0
]
# LP token amount
debt
=
state
[
1
]
# Interest-accrued debt
x0
=
state
[
2
]
# Virtual balance for 2x leverage
Calculate Current DTV Ratio
:
def
calculate_dtv_ratio
(
)
:
state
=
AMM
.
get_state
(
)
# collateral (LP), debt, x0
p_o
=
PRICE_ORACLE_CONTRACT
.
price
(
)
# oracle price
# Include the same precision scaling you use elsewhere if needed
collateral_value
=
p_o
*
state
.
collateral
dtv
=
state
.
debt
*
10
**
18
//
collateral_value
return
dtv
# ~5e17 (50%) at target
Related
Core: AMM (LEVAMM)
— invariant,
exchange
,
get_dy
,
get_state
,
get_x0
.
Core: VirtualPool
— flash-loan wrapper.
Action Flow: Rebalance
— full call sequence.
Action Flow Overview
— high-level asset and fee flow.
User: Arbitrage & MEV
— user-level framing.
Overview
How the VirtualPool routes trades
Mathematical Foundation
Leverage Calculation
How the code creates (and enforces) arbitrage back to ~2×
Why the price becomes favorable (how the spread appears)
How VirtualPool turns the quote into an executable arb
Arbitrage Profit Calculation
Arbitrage Scenarios
Scenario 1: BTC Price Increases
Scenario 2: BTC Price Decreases
How to Execute Arbitrage
Step 1: Check for Arbitrage Opportunities
Step 2: Calculate Expected Profit
Step 3: Execute Arbitrage
Key Functions for Arbitrage
VirtualPool Functions
AMM Functions
Related
## /dev/integration/quote-and-route
On this page
View functions you can rely on.
Reliable quote surface
LT.vy
exposes preview/quote view functions. Note
LT
is ERC-4626-like but not strictly compliant — signatures are custom and some ERC-4626 methods (
previewMint
,
previewRedeem
,
mint
,
redeem
) do not exist on
LT
. They DO exist on
LiquidityGauge
(the staker), which is strictly ERC-4626.
What you want
Call
Quote asset → crvUSD swap
VirtualPool.get_dy(1, 0, dx)
Quote crvUSD → asset swap
VirtualPool.get_dy(0, 1, dx)
Quote deposit (assets -> shares)
LT.preview_deposit(assets, debt, raise_overflow=True)
— reverts on overflow; pass
False
for a soft quote (returns 0 when
debt
would exceed
AMM.max_debt() / 2
)
Quote redemption (shares → assets, live Cryptoswap)
LT.preview_withdraw(tokens)
— parameter is share count
Current PPS (oracle-priced, sandwich-resistant)
LT.pricePerShare()
Liquidity bucket state
LT.liquidity()
returns
(admin, total, ideal_staked, staked)
Emergency-path quote
LT.preview_emergency_withdraw(shares)
Gauge ERC-4626 (staker shares)
LiquidityGauge.convertToShares/convertToAssets/previewDeposit/previewRedeem
Oracle price
PriceOracle.price()
LT.preview_withdraw(tokens)
runs
calc_withdraw_fixed_out
against current Cryptoswap state — its output includes TRD and realised slippage.
LT.pricePerShare()
uses LEVAMM's
value_oracle
— oracle-priced, TRD-free.
Integrator notes
For withdrawal routing,
prefer
preview_withdraw
— it is the realistic redemption.
pricePerShare()
is an upper bound.
TRD:
1 − preview_withdraw(1e18) / pricePerShare()
.
Preview functions are
@view
;
_w
variants (e.g.
AMM.price_w
) are mutating and update EMA state. Do not call mutating functions in quote paths.
LT.preview_deposit
requires a
debt
parameter. Typical LT-call estimate:
debt ≈ assets × oracle_price / 10**asset_decimals
, denominated in crvUSD wei. Example: 1 asset with 18 decimals at a
100_000e18
oracle price uses about
100_000e18
crvUSD debt. The AMM's
L = 2
target is
debt ≈ LP collateral value / 2
; the LT call adds the volatile leg plus the borrowed stable leg, so the borrowed leg is roughly the volatile leg's oracle value.
Routing metadata
Factory.markets(i)
— returns the
Market
struct:
{asset_token, cryptopool, amm, lt, price_oracle, virtual_pool, staker}
(7 fields, in this order —
Factory.vy:32
). No
agg
field; resolve the crvUSD aggregator from
Factory.agg()
or
LT.agg()
.
Factory.market_count()
— upper bound for iteration.
Gauge lookup: read
staker
from the market struct, or call
LT.staker()
directly.
GaugeController.gauges
is a
address[1_000_000_000]
enumerated by index, not a mapping by LT address — do not call
gauges(lt_address)
.
There is no
Factory.get_market_info
function; iterate over
markets(i)
directly.
Related
Core: LT
Core: VirtualPool
Deposit & Withdraw
Arbitrage
Reliable quote surface
Integrator notes
Routing metadata
Related
## /dev/integration/event-catalog
On this page
Use for indexer/subgraph setup. Names and signatures pulled from
yb-core-master
source.
Core
LT
Deposit(sender indexed, owner indexed, assets, shares)
— ERC-4626
Withdraw(sender indexed, receiver indexed, owner indexed, assets, shares)
— ERC-4626
Transfer(sender indexed, receiver indexed, value)
— ERC-20
Approval(owner indexed, spender indexed, value)
— ERC-20
SetStaker(staker indexed)
WithdrawAdminFees(receiver, amount)
AllocateStablecoins(allocator indexed, stablecoin_allocation, stablecoin_allocated)
DistributeBorrowerFees(sender indexed, amount, min_amount, discount)
SetAdmin(admin)
AMM
TokenExchange(buyer, sold_id, tokens_sold, bought_id, tokens_bought, fee, price_oracle)
AddLiquidityRaw(token_amounts[2], invariant, price_oracle)
RemoveLiquidityRaw(collateral_change, debt_change)
SetRate(rate, rate_mul, time)
CollectFees(amount, new_supply)
SetFee(fee)
SetKilled(is_killed)
VirtualPool
TokenExchange(buyer indexed, sold_id, tokens_sold, bought_id, tokens_bought)
Factory
MarketParameters(idx indexed, asset_token indexed, cryptopool indexed, amm, lt, price_oracle, virtual_pool, staker, agg)
SetImplementations(amm, lt, virtual_pool, price_oracle, staker)
SetAllocator(allocator, amount)
SetFeeReceiver(fee_receiver)
SetAgg(agg)
SetFlash(flash)
SetAdmin(admin, emergency_admin, old_admin, old_emergency_admin)
SetMinAdminFee(admin_fee)
SetGaugeController(gc)
HybridVault
SetPersonalLimit(pool_id, limit)
SetCrvusdVault(vault)
HybridVaultFactory
VaultCreated(user indexed, vault indexed)
SetVaultImpl(impl)
SetStablecoinFraction(stablecoin_fraction)
SetPoolLimit(pool_id, limit)
SetAllowedCrvusdVault(vault, allowed)
SetCrvusdVaultLimit(crvusd_vault, limit)
LTMigrator
No events.
CryptopoolLPOracle
/
YBLendingOracle
No events.
DAO
YB
Transfer
,
Approval
— standard ERC-20
RoleMinterChanged(minter, status)
— Snekmate
VotingEscrow
Deposit(_from indexed, _for indexed, value, locktime indexed, type, ts)
—
type ∈ LockActions
Withdraw(_from indexed, _for indexed, value, ts)
Supply(prevSupply, supply)
SetTransferClearanceChecker(clearance_checker)
GaugeController
VoteForGauge(time, user, gauge_addr, weight)
— no fields are indexed in source
NewGauge(addr)
SetKilled(gauge, is_killed)
LiquidityGauge
AddReward(token indexed, distributor, id)
ChangeRewardDistributor(token indexed, distributor)
DepositRewards(token indexed, distributor, amount, finish_time)
FeeDistributor
FundEpoch(epoch indexed, token indexed, amount)
AddTokenSet(token_set_id indexed, token_set)
Claim(user indexed, token indexed, amount)
Kill(is_killed)
InflationaryVest
Start(timestamp, amount)
NewRecepient(recipient, old_recipient)
(source spelling)
Claim(recipient, claimed)
VestingEscrow
Fund(recipient indexed, amount)
Defund(recipient indexed, refund_recipient, amount)
Claim(recipient indexed, claimed)
ToggleDisable(recipient, disabled)
CliffEscrow
TokenRecovered(token indexed, to, amount)
StakeZap
,
SnapshotSplitter
,
TokenSender
,
Multisend
,
CallComparator
,
VotingPowerCondition
No events.
Related
Error Codes
Contract Addresses
Core
LT
AMM
VirtualPool
Factory
HybridVault
HybridVaultFactory
LTMigrator
CryptopoolLPOracle
/
YBLendingOracle
DAO
YB
VotingEscrow
GaugeController
LiquidityGauge
FeeDistributor
InflationaryVest
VestingEscrow
CliffEscrow
StakeZap
,
SnapshotSplitter
,
TokenSender
,
Multisend
,
CallComparator
,
VotingPowerCondition
Related
## /dev/integration/error-codes
On this page
Debug table of revert strings encountered when calling yb-core contracts. Strings are drawn from
yb-core-master
source. ERC-4626 strings (
erc4626: deposit/mint/withdraw/redeem more than maximum
) are listed once per family rather than repeated for each method.
Core
LT.vy
String
Cause
Access
Caller neither admin nor factory admin
Already set
Second
set_amm
Slippage
min_shares
/
min_assets
not met
Debt too high
Deposit/redeem value would exceed
AMM.max_debt() / 2
Withdrawing nothing
withdraw(0)
Withdraw to/from staker
Staker is
msg.sender
or
receiver
We're dead. Use emergency_withdraw
Normal
withdraw
while AMM killed
Remainder too small
Supply would drop below
MIN_SHARE_REMAINDER
(1e6)
Deposit to staker
receiver == staker
in
deposit
N>2
Constructor: Cryptoswap pool has more than 2 coins (
coins(2)
did not revert)
receiver
emergency_withdraw
: emergency-admin / admin caller must set
receiver == owner
owner
emergency_withdraw
: non-owner caller is not the position owner
Not killed
Emergency withdrawal path used while AMM is live
Need factory
withdraw_admin_fees
called when admin is not a factory contract
Killed
Admin-fee withdrawal while AMM killed
No fee_receiver
Factory fee receiver is unset
Staker=fee_receiver
Fee receiver equals staker
Loss made admin fee negative
Admin-fee withdrawal attempted while admin bucket is negative
Staker already set
Second
set_staker
GAS
Gauge
checkpoint
retry path:
_checkpoint_gauge
falls back to a fixed-gas call (200k) and requires the caller to supply at least that much — guards against gas-griefing of reward checkpoints
AMM.vy
String
Cause
Fee too high
Constructor:
fee > MAX_FEE
(10%).
set_fee
reverts without a message on the same check.
Unsafe min
debt < coll_value · MIN_SAFE_DEBT / 1e18
Unsafe max
debt > coll_value · MAX_SAFE_DEBT / 1e18
Access
set_rate
/
set_fee
/
set_killed
from non-LT
Access violation
_deposit
/
_withdraw
from non-LT
Rate too high
rate > MAX_RATE
(100% APR)
Amount too large
get_dy(i=0, in_amount > debt)
Slippage
exchange
with
out < min_out
Empty AMM
exchange
with
collateral_amount == 0
Bad final state
Post-swap
x0 < x0_pre
VirtualPool.vy
String
Cause
Wrong caller
onFlashLoan
not from
FACTORY.flash()
Slippage
Output below
min_out
Factory.vy
String
Cause
Access
Non-admin on admin function
Wrong stablecoin
Pool's coin 0 ≠ factory STABLECOIN
Only set once
set_mint_factory
re-called
Minter
set_allocator
targets
mint_factory
Already set
set_gauge_controller
re-called
Admin fee too high
min_admin_fee > 1e18
Bad aggregator
Init /
set_agg
with
agg.price() ∉ (0.9e18, 1.1e18)
(open interval, both ends)
Too many markets
market_count ≥ 50000
Nonexistent market
fill_staker_vpool(i ≥ market_count)
HybridVault.vy
String
Cause
Already initialized
Re-init
Access
Generic non-owner caller on owner-only function (
deposit
,
withdraw
,
emergency_withdraw
,
stake
,
unstake
,
redeem_crvusd
,
withdraw_scrvusd
,
recover_tokens
)
Only admin
set_personal_limit
from non-vault-factory-admin
Only owner
Owner-gated call from non-owner (
set_crvusd_vault
)
Vault not allowed
New
crvusd_vault
not in allow-list
Has active positions
set_crvusd_vault
while positions exist
Bad pool_id
market.lt == 0
Not enough crvUSD
Insufficient backing without
deposit_stablecoins
flag
Beyond pool limit
Deposit exceeds cap
Debt made too high
Sanity:
debt > 1.1 · additional_crvusd
No liquidity given
lt_shares == 0
from deposit
Ca프로젝트로 돌아가기