bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 24쪽 중 16쪽
check_address
=
staticcall Factory
(
new_admin
)
.
emergency_admin
(
)
check_address
=
staticcall Factory
(
new_admin
)
.
fee_receiver
(
)
check_address
=
staticcall Factory
(
new_admin
)
.
gauge_controller
(
)
check_uint
:
uint256
=
staticcall Factory
(
new_admin
)
.
min_admin_fee
(
)
self
.
admin
=
new_admin
log SetAdmin
(
admin
=
new_admin
)
set_rate()
Description:
Sets the interest rate in the AMM. This function can only be called by the admin and forwards the call to the AMM contract. Interest rate can only be changed by the
admin
of this contract or the
admin
of the
Factory
.
Returns:
No return value (void function).
Input
Type
Description
rate
uint256
New interest rate
📄 View Source Code
@external
@nonreentrant
def
set_rate
(
rate
:
uint256
)
:
self
.
_check_admin
(
)
extcall self
.
amm
.
set_rate
(
rate
)
set_amm_fee()
Description:
Sets the trading fee in the AMM. This function can only be called by the admin and forwards the call to the AMM contract. AMM fee can only be changed by the
admin
of this contract or the
admin
of the
Factory
.
Returns:
No return value (void function).
Input
Type
Description
fee
uint256
New trading fee
📄 View Source Code
@external
@nonreentrant
def
set_amm_fee
(
fee
:
uint256
)
:
self
.
_check_admin
(
)
extcall self
.
amm
.
set_fee
(
fee
)
allocate_stablecoins()
Description:
Allocates stablecoins to the AMM for this pool. This method must be used once the contract has received allocation of stablecoins. Allocation can only be handled by the
admin
of this contract or the
admin
of the
Factory
.
Returns:
No return value (void function).
Emits:
AllocateStablecoins
- Allocation event with allocator address, allocation amount, and allocated amount.
Input
Type
Description
limit
uint256
Limit to allocate for this pool (max uint256 = do not change)
📄 View Source Code
@external
@nonreentrant
def
allocate_stablecoins
(
limit
:
uint256
=
max_value
(
uint256
)
)
:
allocator
:
address
=
self
.
admin
allocation
:
uint256
=
limit
allocated
:
uint256
=
self
.
stablecoin_allocated
if
limit
==
max_value
(
uint256
)
:
allocation
=
self
.
stablecoin_allocation
else
:
self
.
_check_admin
(
)
self
.
stablecoin_allocation
=
limit
extcall self
.
amm
.
check_nonreentrant
(
)
if
allocation
>
allocated
:
# Bring in only what the allocator can actually transfer
to_transfer
:
uint256
=
min
(
allocation
-
allocated
,
staticcall STABLECOIN
.
balanceOf
(
allocator
)
)
assert
extcall STABLECOIN
.
transferFrom
(
allocator
,
self
.
amm
.
address
,
to_transfer
,
default_return_value
=
True
)
allocated
+=
to_transfer
self
.
stablecoin_allocated
=
allocated
elif
allocation
<
allocated
:
lp_price
:
uint256
=
extcall
(
staticcall self
.
amm
.
PRICE_ORACLE_CONTRACT
(
)
)
.
price_w
(
)
# Safe lower limit for deflating the market: 3/4 of LP-priced collateral value.
# Equilibrium leaves a 50% surplus (coefficient 1); the edge case is 1/2; 3/4
# is the conservative cap that still lets governance deallocate.
safe_lower_limit
:
uint256
=
lp_price
*
(
staticcall self
.
amm
.
collateral_amount
(
)
)
*
3
//
4
//
10
**
18
to_transfer
:
uint256
=
min
(
min
(
allocated
-
allocation
,
allocated
-
safe_lower_limit
)
,
staticcall STABLECOIN
.
balanceOf
(
self
.
amm
.
address
)
)
allocated
-=
to_transfer
assert
extcall STABLECOIN
.
transferFrom
(
self
.
amm
.
address
,
allocator
,
to_transfer
,
default_return_value
=
True
)
self
.
stablecoin_allocated
=
allocated
log AllocateStablecoins
(
allocator
=
allocator
,
stablecoin_allocation
=
allocation
,
stablecoin_allocated
=
allocated
)
pricePerShare()
Description:
Non-manipulatable "fair price per share" oracle of the yb-asset token.
Returns:
uint256
- Price per share in 1e18 units.
📄 View Source Code
@external
@view
def
pricePerShare
(
)
-
>
uint256
:
# Short-circuit BEFORE the heavy _calculate_values call when supply is empty.
if
self
.
totalSupply
==
0
:
return
10
**
18
else
:
v
:
LiquidityValuesOut
=
self
.
_calculate_values
(
self
.
_price_oracle
(
)
)
return
v
.
total
*
10
**
18
//
v
.
supply_tokens
symbol()
Description:
Returns the token symbol in the format 'yb-asset'. This implements the ERC20 symbol standard.
Returns:
String[32]
- Token symbol (e.g., "yb-BTC").
📄 View Source Code
@external
@view
def
symbol
(
)
-
>
String
[
32
]
:
return
concat
(
'yb-'
,
staticcall IERC20Slice
(
ASSET_TOKEN
.
address
)
.
symbol
(
)
)
name()
Description:
Returns the token name in the format 'Yield Basis liquidity for asset'. This implements the ERC20 name standard.
Returns:
String[58]
- Token name (e.g., "Yield Basis liquidity for BTC").
📄 View Source Code
@external
@view
def
name
(
)
-
>
String
[
58
]
:
return
concat
(
'Yield Basis liquidity for '
,
staticcall IERC20Slice
(
ASSET_TOKEN
.
address
)
.
symbol
(
)
)
emergency_withdraw()
and
preview_emergency_withdraw()
Description:
The only exit path while the AMM is killed (
We're dead. Use emergency_withdraw
). Bypasses the oracle-driven
_calculate_values
rebase: the caller settles debt from their own wallet and the AMM hands back its raw
(collateral, debt)
pair. Convexity of the bonding curve ensures the worst an attacker can do is lose value, so no
min_*
slippage parameter is exposed.
Three auth branches, distinguished by whether
admin
is a contract (factory) and whether the AMM is currently killed:
Caller
receiver
constraint
When allowed
owner
of the position
any
Always — full self-service exit.
emergency_admin
(factory only)
receiver == owner
While AMM is killed OR
value_oracle()
reverts. Can sweep stuck positions but must send proceeds to the position owner.
admin
(factory only)
receiver == owner
Same rules as
emergency_admin
.
Any other contract caller
—
Reverts
"owner"
unless the caller IS the owner.
Any caller while AMM is live
—
Reverts
"Not killed"
. Use the normal
withdraw
path.
The return tuple is
(asset_out, stables_to_return)
. If
stables_to_return < 0
, the contract pulls that much crvUSD from
msg.sender
via
transferFrom
to settle the debt leg — approve crvUSD to the LT before calling.
preview_emergency_withdraw(shares) -> (uint256, int256)
is the matching view. It does not enforce any auth check — quote the position from any address.
Returns:
(asset_received, stables_to_return)
:
int256
on the second leg so the contract can signal that the caller must bring stables (negative value) versus that they will receive stables back (positive).
Input
Type
Description
shares
uint256
yb-LP shares to redeem
receiver
address
Destination for the asset leg (and stables leg if positive). Default
msg.sender
.
owner
address
Position owner whose shares are burned. Default
msg.sender
.
withdraw_admin_fees()
Description:
Permissionless trigger that materialises pending admin fees as yb-LP shares and mints them to the factory's
fee_receiver
. Anyone can call it as long as
LT.admin
resolves to a factory contract (
admin.is_contract
must be true and
Factory(admin).fee_receiver()
must be set). Keepers and MEV searchers run this on a schedule to keep the FeeDistributor topped up.
Mechanism:
Runs
_calculate_values(self._price_oracle_w())
to refresh buckets — admin must be non-negative (
Loss made admin fee negative
).
Computes
to_mint = supply_tokens × (total + admin) / total − supply_tokens
.
Mints
to_mint
yb-LP to
fee_receiver
, sets
liquidity.admin = 0
, and updates
liquidity.total
accordingly.
Emits
WithdrawAdminFees(receiver, amount)
.
Reverts:
String
Cause
Need factory
admin
is an EOA (no
fee_receiver
).
Killed
AMM is killed — wait for unkill or use
emergency_withdraw
.
No fee_receiver
Factory exists but
fee_receiver
is the zero address.
Staker=fee_receiver
Sanity check: cannot mint to the staker contract.
Loss made admin fee negative
Admin bucket is currently in deficit. Wait for fees to recover.
No
min_amount
or
min_assets
parameter — the mint is deterministic from the current bucket state.
updated_balances()
Description:
View helper used by
LiquidityGauge._total_assets()
to compute its strict ERC-4626
totalAssets()
. Runs
_calculate_values
against the current oracle without writing.
Returns:
(supply_tokens, staked_tokens)
— post-rebase supply and the staker's post-rebase share count. When
totalSupply == 0
, returns
(0, 0)
.
Used by portfolio trackers and LP-as-collateral integrations that read gauge balances and need to translate them back to LT-share equivalents.
@external
@view
def
updated_balances
(
)
-
>
(
uint256
,
uint256
)
:
if
self
.
totalSupply
>
0
:
lv
:
LiquidityValuesOut
=
self
.
_calculate_values
(
self
.
_price_oracle
(
)
)
return
(
lv
.
supply_tokens
,
lv
.
staked_tokens
)
else
:
return
(
0
,
0
)
distribute_borrower_fees()
Description:
Permissionless. Sweeps accrued borrower interest out of LEVAMM and donates the resulting crvUSD into the underlying Cryptoswap pool via
add_liquidity([amount, 0], min_amount, empty(address), donation=True)
. The donation flows into the pool's donation-protected buffer and unlocks over the pool's donation window rather than minting fresh LP tokens to a user.
Triggered automatically at the end of every
deposit
and
withdraw
with the default
FEE_CLAIM_DISCOUNT
(1%). External callers can run it more often than that — useful when the pool's reserve is thin and the operator wants to top it up immediately rather than wait for the next user op.
The
discount
parameter caps how much price-scale movement is acceptable on the Cryptoswap side:
min_amount = (1e18 - discount) × crvusd_amount / CRYPTOPOOL.lp_price()
. Larger discounts allow the donation to land even when the pool is mid-rebalance. Only admin can pass a discount greater than the default 1%.
Reverts:
the underlying Cryptoswap
add_liquidity
reverts (typically
Slippage
) when the donation cannot meet
min_amount
. Try again with a larger discount, or wait for the pool to settle.
Emits
DistributeBorrowerFees(sender, amount, min_amount, discount)
.
Admin-only setters (governance)
These are called only by the LT's admin — either an EOA owner or (via
_check_admin
) a factory contract whose
admin()
matches the caller. Integrators usually do not call these directly; documented here for governance audit and indexing.
Function
Effect
Emits
set_amm(amm)
One-shot. Sets the AMM contract address; rejects subsequent calls with
"Already set"
.
—
set_admin(new_admin)
Transfers admin to a new EOA or factory. Sanity-checks the candidate's
admin
/
emergency_admin
/
fee_receiver
/
gauge_controller
/
min_admin_fee
getters if it is a contract.
SetAdmin
set_rate(rate)
Forwards to
AMM.set_rate
. Bounded by
MAX_RATE
(100% APR).
SetRate
(from AMM)
set_amm_fee(fee)
Forwards to
AMM.set_fee
. Bounded by
MAX_FEE
(10%).
SetFee
(from AMM)
set_staker(staker)
One-shot. Wires the
LiquidityGauge
address. Any pre-existing balance at the staker address is swept to
fee_receiver
.
SetStaker
set_killed(is_killed)
Kills or unkills the AMM. Callable by LT admin, factory admin,
or
emergency_admin
.
SetKilled
(from AMM)
Other public views
Function
Returns
is_killed()
True
if the AMM is currently killed (proxies
AMM.is_killed
). Use this before deciding whether to call
withdraw
versus
emergency_withdraw
.
min_admin_fee()
Current minimum admin-fee floor (
Factory.min_admin_fee()
when admin is a factory, else
0
).
checkpoint_staker_rebase()
Only meaningful when called by the staker contract (
LiquidityGauge
does this before every gauge op). Forces a
_calculate_values
write so subsequent ops see fresh buckets. Silent no-op for other callers.
Overview
Function Documentation
Public Variables
Data Structs
Events
_calculate_values()
deposit()
withdraw()
preview_deposit()
preview_withdraw()
set_amm()
set_admin()
set_rate()
set_amm_fee()
allocate_stablecoins()
pricePerShare()
symbol()
name()
emergency_withdraw()
and
preview_emergency_withdraw()
withdraw_admin_fees()
updated_balances()
distribute_borrower_fees()
Admin-only setters (governance)
Other public views
## /dev/core/amm
On this page
The source code of the
AMM.vy
contract can be found on
GitHub
. The contract is written with
Vyper
version 0.4.3.
Overview
The
LEVAMM
is a two-asset AMM that maintains a
constant leverage
between
coins(0) = STABLECOIN
(18 decimals) and
coins(1) = COLLATERAL
(the Curve pool's LP token). It supports any leverage > 1; in YieldBasis we use
2×
. The AMM tracks LP collateral and debt, prices trades along a leveraged curve anchored to an external price oracle, enforces a safe post-trade region, and charges a configurable trading fee.
Debt grows over time at an interest rate set by the linked
LT.vy
contract; accrued interest is periodically realized and sent to LT as fees.
Used by
VirtualPool
.
VirtualPool
routes swaps through this AMM so users can trade between the market's tokens
without ever handling LP tokens
. Flash loans cover transient balances so any LP exposure stays internal to
VirtualPool
during the call.
Function Documentation
Public Variables
Constants
MAX_FEE
(
uint256
) - Maximum allowed trading fee (10^17 = 10%)
MAX_RATE
(
uint256
) - Maximum allowed interest rate (10^18 / (365 * 86400) = 100% APR)
Immutable Variables
LEVERAGE
(
uint256
) - Leverage ratio set at deployment (must be > 1e18)
LT_CONTRACT
(
address
) - LT contract address (immutable)
COLLATERAL
(
IERC20
) - LP token contract address (immutable)
STABLECOIN
(
IERC20
) - Stablecoin contract address (immutable)
PRICE_ORACLE_CONTRACT
(
PriceOracle
) - Price oracle contract address (immutable)
State Variables
fee
(
uint256
) - Current trading fee rate
collateral_amount
(
uint256
) - Current LP token balance
rate
(
uint256
) - Current interest rate
rate_mul
(
uint256
) - Rate multiplier for interest calculation
rate_time
(
uint256
) - Last rate update timestamp
minted
(
uint256
) - Total stablecoins minted
redeemed
(
uint256
) - Total stablecoins redeemed
is_killed
(
bool
) - Emergency kill switch status
Data Structs
AMMState
collateral
(
uint256
) - LP token amount held as collateral
debt
(
uint256
) - Interest-accrued stablecoin debt
x0
(
uint256
) - Virtual balance for maintaining leverage
Pair
collateral
(
uint256
) - LP token amount
debt
(
uint256
) - Stablecoin debt amount
OraclizedValue
p_o
(
uint256
) - Oracle price used for calculation
value
(
uint256
) - Calculated value in stablecoin terms
Events
TokenExchange
(Emitted when tokens are exchanged through the AMM)
buyer
(
indexed address
) - Address that initiated the exchange
sold_id
(
uint256
) - Index of token sold (0=stablecoin, 1=collateral)
tokens_sold
(
uint256
) - Amount of tokens sold
bought_id
(
uint256
) - Index of token bought (0=stablecoin, 1=collateral)
tokens_bought
(
uint256
) - Amount of tokens bought
fee
(
uint256
) - Fee rate applied to this swap (1e18-based)
price_oracle
(
uint256
) - Oracle price observed for the swap
AddLiquidityRaw
token_amounts
(
uint256[2]
) - Amounts of tokens added
invariant
(
uint256
) - Pool invariant after adding liquidity
price_oracle
(
uint256
) - Oracle price at time of addition
RemoveLiquidityRaw
collateral_change
(
uint256
) - Amount of collateral removed
debt_change
(
uint256
) - Amount of debt removed
SetRate
rate
(
uint256
) - New interest rate
rate_mul
(
uint256
) - Rate multiplier
time
(
uint256
) - Timestamp
CollectFees
amount
(
uint256
) - Amount of fees collected
new_supply
(
uint256
) - New supply
SetFee
—
fee: uint256
SetKilled
—
is_killed: bool
exchange()
Description:
Main trading function — swaps between stablecoin and LP token. Maintains constant leverage through the state-update invariant.
Returns:
uint256
- Output amount received after the swap.
Emits:
TokenExchange
- Swap execution event.
Input
Type
Description
i
uint256
Input token index (0=stablecoin, 1=LP token)
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
@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
)
assert
not
self
.
is_killed
collateral
:
uint256
=
self
.
collateral_amount
assert
collateral
>
0
,
"Empty AMM"
debt
:
uint256
=
self
.
_debt_w
(
)
p_o
:
uint256
=
extcall PRICE_ORACLE_CONTRACT
.
price_w
(
)
x0
:
uint256
=
self
.
get_x0
(
p_o
,
collateral
,
debt
,
False
)
x_initial
:
uint256
=
x0
-
debt
out_amount
:
uint256
=
0
fee
:
uint256
=
self
.
fee
# Asymmetric safety check: capture coll/debt ratio BEFORE the trade and
# AFTER, then only enforce the strict `safe_limits` branch when the trade
# made the state worse. If the trade moves the AMM toward L=2 equilibrium
# we relax the check so rebalances are not blocked.
coll_vs_debt_before
:
uint256
=
unsafe_div
(
p_o
*
collateral
*
COLLATERAL_PRECISION
,
debt
)
if
debt
==
0
:
coll_vs_debt_before
=
max_value
(
uint256
)
if
i
==
0
:
# Trader buys collateral from us
x
:
uint256
=
x_initial
+
in_amount
y
:
uint256
=
math
.
_ceil_div
(
x_initial
*
collateral
,
x
)
out_amount
=
(
collateral
-
y
)
*
(
10
**
18
-
fee
)
//
10
**
18
assert
out_amount
>=
min_out
,
"Slippage"
debt
-=
in_amount
collateral
-=
out_amount
self
.
redeemed
+=
in_amount
assert
extcall STABLECOIN
.
transferFrom
(
msg
.
sender
,
self
,
in_amount
,
default_return_value
=
True
)
assert
extcall COLLATERAL
.
transfer
(
_for
,
out_amount
,
default_return_value
=
True
)
else
:
# Trader sells collateral to us
y
:
uint256
=
collateral
+
in_amount
x
:
uint256
=
math
.
_ceil_div
(
x_initial
*
collateral
,
y
)
out_amount
=
(
x_initial
-
x
)
*
(
10
**
18
-
fee
)
//
10
**
18
assert
out_amount
>=
min_out
,
"Slippage"
debt
+=
out_amount
self
.
minted
+=
out_amount
collateral
=
y
assert
extcall COLLATERAL
.
transferFrom
(
msg
.
sender
,
self
,
in_amount
,
default_return_value
=
True
)
assert
extcall STABLECOIN
.
transfer
(
_for
,
out_amount
,
default_return_value
=
True
)
coll_vs_debt_after
:
uint256
=
unsafe_div
(
p_o
*
collateral
*
COLLATERAL_PRECISION
,
debt
)
if
debt
==
0
:
coll_vs_debt_after
=
max_value
(
uint256
)
check_state
:
bool
=
True
if
coll_vs_debt_after
>
2
*
10
**
18
:
if
coll_vs_debt_before
>
coll_vs_debt_after
:
check_state
=
False
# state improved on the "too-much-collateral" side
else
:
if
coll_vs_debt_before
<
coll_vs_debt_after
:
check_state
=
False
# state improved on the "too-much-debt" side
assert
self
.
get_x0
(
p_o
,
collateral
,
debt
,
check_state
)
>=
x0
,
"Bad final state"
self
.
collateral_amount
=
collateral
self
.
debt
=
debt
log TokenExchange
(
buyer
=
msg
.
sender
,
sold_id
=
i
,
tokens_sold
=
in_amount
,
bought_id
=
j
,
tokens_bought
=
out_amount
,
fee
=
fee
,
price_oracle
=
p_o
)
if
LT_CONTRACT
!=
empty
(
address
)
and
LT_CONTRACT
.
is_contract
:
self
.
_collect_fees
(
)
extcall LT
(
LT_CONTRACT
)
.
distribute_borrower_fees
(
)
return
out_amount
get_dy()
Description:
Quote expected output for a given input. Applies fee. View function.
Returns:
uint256
- Expected output amount.
Input
Type
Description
i
uint256
Input token index (0=stablecoin, 1=LP token)
j
uint256
Output token index (must be opposite of
i
)
in_amount
uint256
Amount of input tokens to swap
📄 View Source Code
@external
@view
def
get_dy
(
i
:
uint256
,
j
:
uint256
,
in_amount
:
uint256
)
-
>
uint256
:
assert
(
i
==
0
and
j프로젝트로 돌아가기