bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 52쪽
ve_liquidity(
_amount: uint256,
min_amounts: uint256[N_COINS],
use_eth: bool = False,
receiver: address = msg.sender,
claim_admin_fees: bool = True,
) -> uint256[N_COINS]:
"""
@notice This withdrawal method is very safe, does no complex math since
tokens are withdrawn in balanced proportions. No fees are charged.
@param _amount Amount of LP tokens to burn
@param min_amounts Minimum amounts of tokens to withdraw
@param use_eth Whether to withdraw ETH or not
@param receiver Address to send the withdrawn tokens to
@param claim_admin_fees If True, call self._claim_admin_fees(). Default is True.
@return uint256[3] Amount of pool tokens received by the `receiver`
"""
amount: uint256 = _amount
balances: uint256[N_COINS] = self.balances
d_balances: uint256[N_COINS] = empty(uint256[N_COINS])
if claim_admin_fees:
self._claim_admin_fees() # <------ We claim fees so that the DAO gets
# paid before withdrawal. In emergency cases, set it to False.
# -------------------------------------------------------- Burn LP tokens.
total_supply: uint256 = self.totalSupply # <------ Get totalSupply before
self.burnFrom(msg.sender, _amount) # ---- reducing it with self.burnFrom.
# There are two cases for withdrawing tokens from the pool.
# Case 1. Withdrawal does not empty the pool.
# In this situation, D is adjusted proportional to the amount of
# LP tokens burnt. ERC20 tokens transferred is proportional
# to : (AMM balance * LP tokens in) / LP token total supply
# Case 2. Withdrawal empties the pool.
# In this situation, all tokens are withdrawn and the invariant
# is reset.
if amount == total_supply: # <----------------------------------- Case 2.
for i in range(N_COINS):
d_balances[i] = balances[i]
self.balances[i] = 0 # <------------------------- Empty the pool.
else: # <-------------------------------------------------------- Case 1.
amount -= 1 # <---- To prevent rounding errors, favor LPs a tiny bit.
for i in range(N_COINS):
d_balances[i] = balances[i] * amount / total_supply
assert d_balances[i] >= min_amounts[i]
self.balances[i] = balances[i] - d_balances[i]
balances[i] = d_balances[i] # <-- Now it's the amounts going out.
D: uint256 = self.D
self.D = D - unsafe_div(D * amount, total_supply) # <----------- Reduce D
# proportional to the amount of tokens leaving. Since withdrawals are
# balanced, this is a simple subtraction. If amount == total_supply,
# D will be 0.
# ---------------------------------- Transfers ---------------------------
for i in range(N_COINS):
self._transfer_out(coins[i], d_balances[i], use_eth, receiver)
log RemoveLiquidity(msg.sender, balances, total_supply - _amount)
return d_balances
```
**▶Example▼**
```shell
>>> TriCrypto.remove_liquidity('todo')
''
```
<a id="remove_liquidity_one_coin"></a>
### `remove_liquidity_one_coin`
`TriCrypto.remove_liquidity_one_coin(token_amount: uint256, i: uint256, min_amount: uint256, use_eth: bool = False, receiver: address = msg.sender) -> uint256:`
Function to burn `token_amount` LP tokens and withdraw liquidity in a single token `i`.
| Input | Type | Description |
| --- | --- | --- |
| `token_amount` | `uint256` | Amount of LP tokens to burn. |
| `i` | `uint256` | Index of the token to withdraw. |
| `min_amount` | `uint256` | Minimum amount of token to withdraw. |
| `use_eth` | `bool` | True = withdraw ETH, False = withdraw wETH. |
| `receiver` | `address` | Receiver of the coins; defaults to `msg.sender`. |
Returns: amount of coins withdrawn (`uint256`).
Emits: `RemoveLiquidityOne`
**<>Source code▼**
```vyper
@external
@nonreentrant("lock")
def remove_liquidity_one_coin(
token_amount: uint256,
i: uint256,
min_amount: uint256,
use_eth: bool = False,
receiver: address = msg.sender
) -> uint256:
"""
@notice Withdraw liquidity in a single token.
Involves fees (lower than swap fees).
@dev This operation also involves an admin fee claim.
@param token_amount Amount of LP tokens to burn
@param i Index of the token to withdraw
@param min_amount Minimum amount of token to withdraw.
@param use_eth Whether to withdraw ETH or not
@param receiver Address to send the withdrawn tokens to
@return Amount of tokens at index i received by the `receiver`
"""
A_gamma: uint256[2] = self._A_gamma()
dy: uint256 = 0
D: uint256 = 0
p: uint256 = 0
xp: uint256[N_COINS] = empty(uint256[N_COINS])
approx_fee: uint256 = 0
# ---------------------------- Claim admin fees before removing liquidity.
self._claim_admin_fees()
# ------------------------------------------------------------------------
dy, D, xp, approx_fee = self._calc_withdraw_one_coin(
A_gamma,
token_amount,
i,
(self.future_A_gamma_time > block.timestamp), # <------- During ramps
) # we need to update D.
assert dy >= min_amount, "Slippage"
# ------------------------- Transfers ------------------------------------
self.balances[i] -= dy
self.burnFrom(msg.sender, token_amount)
self._transfer_out(coins[i], dy, use_eth, receiver)
packed_price_scale: uint256 = self.tweak_price(A_gamma, xp, D, 0)
# Safe to use D from _calc_withdraw_one_coin here ---^
log RemoveLiquidityOne(
msg.sender, token_amount, i, dy, approx_fee, packed_price_scale
)
return dy
@internal
@view
def _calc_withdraw_one_coin(
A_gamma: uint256[2],
token_amount: uint256,
i: uint256,
update_D: bool,
) -> (uint256, uint256, uint256[N_COINS], uint256):
token_supply: uint256 = self.totalSupply
assert token_amount <= token_supply # dev: token amount more than supply
assert i < N_COINS # dev: coin out of range
xx: uint256[N_COINS] = self.balances
precisions: uint256[N_COINS] = self._unpack(self.packed_precisions)
xp: uint256[N_COINS] = precisions
D0: uint256 = 0
# -------------------------- Calculate D0 and xp -------------------------
price_scale_i: uint256 = PRECISION * precisions[0]
packed_prices: uint256 = self.price_scale_packed
xp[0] *= xx[0]
for k in range(1, N_COINS):
p: uint256 = (packed_prices & PRICE_MASK)
if i == k:
price_scale_i = p * xp[i]
xp[k] = unsafe_div(xp[k] * xx[k] * p, PRECISION)
packed_prices = packed_prices >> PRICE_SIZE
if update_D: # <-------------- D is updated if pool is undergoing a ramp.
D0 = MATH.newton_D(A_gamma[0], A_gamma[1], xp, 0)
else:
D0 = self.D
D: uint256 = D0
# -------------------------------- Fee Calc ------------------------------
# Charge fees on D. Roughly calculate xp[i] after withdrawal and use that
# to calculate fee. Precision is not paramount here: we just want a
# behavior where the higher the imbalance caused the more fee the AMM
# charges.
# xp is adjusted assuming xp[0] ~= xp[1] ~= x[2], which is usually not the
# case. We charge self._fee(xp), where xp is an imprecise adjustment post
# withdrawal in one coin. If the withdraw is too large: charge max fee by
# default. This is because the fee calculation will otherwise underflow.
xp_imprecise: uint256[N_COINS] = xp
xp_correction: uint256 = xp[i] * N_COINS * token_amount / token_supply
fee: uint256 = self._unpack(self.packed_fee_params)[1] # <- self.out_fee.
if xp_correction < xp_imprecise[i]:
xp_imprecise[i] -= xp_correction
fee = self._fee(xp_imprecise)
dD: uint256 = unsafe_div(token_amount * D, token_supply)
D_fee: uint256 = fee * dD / (2 * 10**10) + 1 # <------- Actual fee on D.
# --------- Calculate `approx_fee` (assuming balanced state) in ith token.
# -------------------------------- We only need this for fee in the event.
approx_fee: uint256 = N_COINS * D_fee * xx[i] / D
# ------------------------------------------------------------------------
D -= (dD - D_fee) # <----------------------------------- Charge fee on D.
# --------------------------------- Calculate `y_out`` with `(D - D_fee)`.
y: uint256 = MATH.get_y(A_gamma[0], A_gamma[1], xp, D, i)[0]
dy: uint256 = (xp[i] - y) * PRECISION / price_scale_i
xp[i] = y
return dy, D, xp, approx_fee
```
```vyper
@external
@view
def newton_D(
ANN: uint256,
gamma: uint256,
x_unsorted: uint256[N_COINS],
K0_prev: uint256 = 0,
) -> uint256:
"""
@notice Finding the invariant via newtons method using good initial guesses.
@dev ANN is higher by the factor A_MULTIPLIER
@dev ANN is already A * N**N
@param ANN the A * N**N value
@param gamma the gamma value
@param x_unsorted the array of coin balances (not sorted)
@param K0_prev apriori for newton's method derived from get_y_int. Defaults
to zero (no apriori)
"""
x: uint256[N_COINS] = self._sort(x_unsorted)
assert x[0] < max_value(uint256) / 10**18 * N_COINS**N_COINS # dev: out of limits
assert x[0] > 0 # dev: empty pool
# Safe to do unsafe add since we checked largest x's bounds previously
S: uint256 = unsafe_add(unsafe_add(x[0], x[1]), x[2])
D: uint256 = 0
if K0_prev == 0:
# Geometric mean of 3 numbers cannot be larger than the largest number
# so the following is safe to do:
D = unsafe_mul(N_COINS, self._geometric_mean(x))
else:
if S > 10**36:
D = self._cbrt(
unsafe_div(
unsafe_div(x[0] * x[1], 10**36) * x[2],
K0_prev
) * 27 * 10**12
)
elif S > 10**24:
D = self._cbrt(
unsafe_div(
unsafe_div(x[0] * x[1], 10**24) * x[2],
K0_prev
) * 27 * 10**6
)
else:
D = self._cbrt(
unsafe_div(
unsafe_div(x[0] * x[1], 10**18) * x[2],
K0_prev
) * 27
)
# D not zero here if K0_prev > 0, and we checked if x[0] is gt 0.
# initialise variables:
K0: uint256 = 0
_g1k0: uint256 = 0
mul1: uint256 = 0
mul2: uint256 = 0
neg_fprime: uint256 = 0
D_plus: uint256 = 0
D_minus: uint256 = 0
D_prev: uint256 = 0
diff: uint256 = 0
frac: uint256 = 0
for i in range(255):
D_prev = D
# K0 = 10**18 * x[0] * N_COINS / D * x[1] * N_COINS / D * x[2] * N_COINS / D
K0 = unsafe_div(
unsafe_mul(
unsafe_mul(
unsafe_div(
unsafe_mul(
unsafe_mul(
unsafe_div(
unsafe_mul(
unsafe_mul(10**18, x[0]), N_COINS
),
D,
),
x[1],
),
N_COINS,
),
D,
),
x[2],
),
N_COINS,
),
D,
) # <-------- We can convert the entire expression using unsafe math.
# since x_i is not too far from D, so overflow is not expected. Also
# D > 0, since we proved that already. unsafe_div is safe. K0 > 0
# since we can safely assume that D < 10**18 * x[0]. K0 is also
# in the range of 10**18 (it's a property).
_g1k0 = unsafe_add(gamma, 10**18) # <--------- safe to do unsafe_add.
if _g1k0 > K0: # The following operations can safely be unsafe.
_g1k0 = unsafe_add(unsafe_sub(_g1k0, K0), 1)
else:
_g1k0 = unsafe_add(unsafe_sub(K0, _g1k0), 1)
# D / (A * N**N) * _g1k0**2 / gamma**2
# mul1 = 10**18 * D / gamma * _g1k0 / gamma * _g1k0 * A_MULTIPLIER / ANN
mul1 = unsafe_div(
unsafe_mul(
unsafe_mul(
unsafe_div(
unsafe_mul(
unsafe_div(unsafe_mul(10**18, D), gamma), _g1k0
),
gamma,
),
_g1k0,
),
A_MULTIPLIER,
),
ANN,
) # <------ Since D > 0, gamma is small, _g1k0 is small, the rest are
# non-zero and small constants, and D has a cap in this method,
# we can safely convert everything to unsafe maths.
# 2*N*K0 / _g1k0
# mul2 = (2 * 10**18) * N_COINS * K0 / _g1k0
mul2 = unsafe_div(
unsafe_mul(2 * 10**18 * N_COINS, K0), _g1k0
) # <--------------- K0 is approximately around D, which has a cap of
# 10**15 * 10**18 + 1, since we get that in get_y which is called
# with newton_D. _g1k0 > 0, so the entire expression can be unsafe.
# neg_fprime: uint256 = (S + S * mul2 / 10**18) + mul1 * N_COINS / K0 - mul2 * D / 10**18
neg_fprime = unsafe_sub(
unsafe_add(
unsafe_add(S, unsafe_div(unsafe_mul(S, mul2), 10**18)),
unsafe_div(unsafe_mul(mul1, N_COINS), K0),
),
unsafe_div(unsafe_mul(mul2, D), 10**18),
) # <--- mul1 is a big number but not huge: safe to unsafely multiply
# with N_coins. neg_fprime > 0 if this expression executes.
# mul2 is in the range of 10**18, since K0 is in that range, S * mul2
# is safe. The first three sums can be done using unsafe math safely
# and since the final expression will be small since mul2 is small, we
# can safely do the entire expression unsafely.
# D -= f / fprime
# D * (neg_fprime + S) / neg_fprime
D_plus = unsafe_div(D * unsafe_add(neg_fprime, S), neg_fprime)
# D*D / neg_fprime
D_minus = unsafe_div(D * D, neg_fprime)
# Since we know K0 > 0, and neg_fprime > 0, several unsafe operations
# are possible in the following. Also, (10**18 - K0) is safe to mul.
# So the only expressions we keep safe are (D_minus + ...) and (D * ...)
if 10**18 > K0:
# D_minus += D * (mul1 / neg_fprime) / 10**18 * (10**18 - K0) / K0
D_minus += unsafe_div(
unsafe_mul(
unsafe_div(D * unsafe_div(mul1, neg_fprime), 10**18),
unsafe_sub(10**18, K0),
),
K0,
)
else:
# D_minus -= D * (mul1 / neg_fprime) / 10**18 * (K0 - 10**18) / K0
D_minus -= unsafe_div(
unsafe_mul(
unsafe_div(D * unsafe_div(mul1, neg_fprime), 10**18),
unsafe_sub(K0, 10**18),
),
K0,
)
if D_plus > D_minus:
D = unsafe_sub(D_plus, D_minus) # <--------- Safe since we check.
else:
D = unsafe_div(unsafe_sub(D_minus, D_plus), 2)
if D > D_prev:
diff = unsafe_sub(D, D_prev)
else:
diff = unsafe_sub(D_prev, D)
# Could reduce precision for gas efficiency here:
if unsafe_mul(diff, 10**14) < max(10**16, D):
# Test that we are safe with the next get_y
for _x in x:
frac = unsafe_div(unsafe_mul(_x, 10**18), D)
assert frac >= 10**16 - 1 and frac < 10**20 + 1, "Unsafe values x[i]"
return D
raise "Did not converge"
@external
@view
def get_y(
_ANN: uint256, _gamma: uint256, x: uint256[N_COINS], _D: uint256, i: uint256
) -> uint256[2]:
"""
@notice Calculate x[i] given other balances x[0..N_COINS-1] and invariant D.
@dev ANN = A * N**N.
@param _ANN AMM.A() value.
@param _gamma AMM.gamma() value.
@param x Balances multiplied by prices and precisions of all coins.
@param _D Invariant.
@param i Index of coin to calculate y.
"""
# Safety checks
assert _ANN > MIN_A - 1 and _ANN < MAX_A + 1 # dev: unsafe values A
assert _gamma > MIN_GAMMA - 1 and _gamma < MAX_GAMMA + 1 # dev: unsafe values gamma
assert _D > 10**17 - 1 and _D < 10**15 * 10**18 + 1 # dev: unsafe values D
frac: uint256 = 0
for k in range(3):
if k != i:
frac = x[k] * 10**18 / _D
assert frac > 10**16 - 1 and frac < 10**20 + 1, "Unsafe values x[i]"
# if above conditions are met, x[k] > 0
j: uint256 = 0
k: uint256 = 0
if i == 0:
j = 1
k = 2
elif i == 1:
j = 0
k = 2
elif i == 2:
j = 0
k = 1
ANN: int256 = convert(_ANN, int256)
gamma: int256 = convert(_gamma, int256)
D: int256 = convert(_D, int256)
x_j: int256 = convert(x[j], int256)
x_k: int256 = convert(x[k], int256)
gamma2: int256 = unsafe_mul(gamma, gamma)
a: int256 = 10**36 / 27
# 10**36/9 + 2*10**18*gamma/27 - D**2/x_j*gamma**2*ANN/27**2/convert(A_MULTIPLIER, int256)/x_k
b: int256 = (
unsafe_add(
10**36 / 9,
unsafe_div(unsafe_mul(2 * 10**18, gamma), 27)
)
- unsafe_div(
unsafe_div(
unsafe_div(
unsafe_mul(
unsafe_div(unsafe_mul(D, D), x_j),
gamma2
) * ANN,
27**2
),
convert(A_MULTIPLIER, int256)
),
x_k,
)
) # <------- The first two expressions can be unsafe, and unsafely added.
# 10**36/9 + gamma*(gamma + 4*10**18)/27 + gamma**2*(x_j+x_k-D)/D*ANN/27/convert(A_MULTIPLIER, int256)
c: int256 = (
unsafe_add(
10**36 / 9,
unsafe_div(unsafe_mul(gamma, unsafe_add(gamma, 4 * 10**18)), 27)
)
+ unsafe_div(
unsafe_div(
unsafe_mul(
unsafe_div(gamma2 * unsafe_sub(unsafe_add(x_j, x_k), D), D),
ANN
),
27
),
convert(A_MULTIPLIER, int256),
)
) # <--------- Same as above with the first two expressions. In the third
# expression, x_j + x_k will not overflow since we know their range from
# previous assert statements.
# (10**18 + gamma)**2/27
d: int256 = unsafe_div(unsafe_add(10**18, gamma)**2, 27)
# abs(3*a*c/b - b)
d0: int256 = abs(unsafe_mul(3, a) * c / b - b) # <------------ a is smol.
divider: int256 = 0
if d0 > 10**48:
divider = 10**30
elif d0 > 10**44:
divider = 10**26
elif d0 > 10**40:
divider = 10**22
elif d0 > 10**36:
divider = 10**18
elif d0 > 10**32:
divider = 10**14
elif d0 > 10**28:
divider = 10**10
elif d0 > 10**24:
divider = 10**6
elif d0 > 10**20:
divider = 10**2
else:
divider = 1
additional_prec: int256 = 0
if abs(a) > abs(b):
additional_prec = abs(unsafe_div(a, b))
a = unsafe_div(unsafe_mul(a, additional_prec), divider)
b = unsafe_div(b * additional_prec, divider)
c = unsafe_div(c * additional_prec, divider)
d = unsafe_div(d * additional_prec, divider)
else:
additional_prec = abs(unsafe_div(b, a))
a = unsafe_div(a / additional_prec, divider)
b = unsafe_div(unsafe_div(b, additional_prec), divider)
c = unsafe_div(unsafe_div(c, additional_prec), divider)
d = unsafe_div(unsafe_div(d, additional_prec), divider)
# 3*a*c/b - b
_3ac: int256 = unsafe_mul(3, a) * c
delta0: int256 = unsafe_div(_3ac, b) - b
# 9*a*c/b - 2*b - 27*a**2/b*d/b
delta1: int256 = (
unsafe_div(3 * _3ac, b)
- unsafe_mul(2, b)
- unsafe_div(unsafe_div(27 * a**2, b) * d, b)
)
# delta1**2 + 4*delta0**2/b*delta0
sqrt_arg: int256 = (
delta1**2 +
unsafe_div(4 * delta0**2, b) * delta0
)
sqrt_val: int256 = 0
if sqrt_arg > 0:
sqrt_val = convert(isqrt(convert(sqrt_arg, uint256)), int256)
else:
return [self._newton_y(_ANN, _gamma, x, _D, i), 0]
b_cbrt: int256 = 0
if b >= 0:
b_cbrt = convert(self._cbrt(convert(b, uint256)), int256)
else:
b_cbrt = -convert(self._cbrt(convert(-b, uint256)), int256)
second_cbrt: int256 = 0
if delta1 > 0:
# convert(self._cbrt(convert((delta1 + sqrt_val), uint256)/2), int256)
second_cbrt = convert(
self._cbrt(unsafe_div(convert(delta1 + sqrt_val, uint256), 2)),
int256
)
else:
second_cbrt = -convert(
self._cbrt(unsafe_div(convert(-(delta1 - sqrt_val), uint256), 2)),
int256
)
# b_cbrt*b_cbrt/10**18*second_cbrt/10**18
C1: int256 = unsafe_div(
unsafe_div(b_cbrt * b_cbrt, 10**18) * second_cbrt,
10**18
)
# (b + b*delta0/C1 - C1)/3
root_K0: int256 = unsafe_div(b + b * delta0 / C1 - C1, 3)
# D*D/27/x_k*D/x_j*root_K0/a
root: int256 = unsafe_div(
unsafe_div(
unsafe_div(unsafe_div(D * D, 27), x_k) * D,
x_j
) * root_K0,
a
)
out: uint256[2] = [
convert(root, uint256),
convert(unsafe_div(10**18 * root_K0, a), uint256)
]
frac = unsafe_div(out[0] * 10**18, _D)
assert frac >= 10**16 - 1 and frac < 10**20 + 1, "Unsafe value for y"
# due to precision issues, get_y can be off by 2 wei or so wrt _newton_y
return out
```
**▶Example▼**
```shell
>>> TriCrypto.remove_liquidity_one_coin('todo')
''
```
<a id="calc_token_amount"></a>
### `calc_token_amount`
`TriCrypto.def calc_token_amount(amounts: uint256[N_COINS], deposit: bool) -> uint256:`
Function to calculate the LP tokens to be minted or burned for depositing or removing `amounts` of coins. This method takes fees into consideration.
| Input | Type | Description |
| --- | --- | --- |
| `amounts` | `uint256[N_COINS]` | Amounts of tokens being deposited or withdrawn. |
| `deposit` | `bool` | `true` for deposit, `false` for withdrawal. |
Returns: amount of LP tokens deposited or withdrawn (`uint256`).
**<>Source code▼**
```vyper
interface Factory:
def admin() -> address: view
def fee_receiver() -> address: view
def views_implementation() -> address: view
interface Views:
def calc_token_amount(
amounts: uint256[N_COINS], deposit: bool, swap: address
) -> uint256: view
def get_dy(
i: uint256, j: uint256, dx: uint256, swap: address
) -> uint256: view
def get_dx(
i: uint256, j: uint256, dy: uint256, swap: address
) -> uint256: view
@external
@view
def calc_token_amount(amounts: uint256[N_COINS], deposit: bool) -> uint256:
"""
@notice Calculate LP tokens minted or to be burned for depositing or
removing `amounts` of coins
@dev Includes fee.
@param amounts Amounts of tokens being deposited or withdrawn
@param deposit True if it is a deposit action, False if withdrawn.
@return uint256 Amount of LP tokens deposited or withdrawn.
"""
view_contract: address = Factory(self.factory).views_implementation()
return Views(view_contract).calc_token_amount(amounts, deposit, self)
@external
@view
def calc_token_fee(
amounts: uint256[N_COINS], xp: uint256[N_COINS]
) -> u프로젝트로 돌아가기