bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 53쪽
int256:
"""
@notice Returns the fee charged on the given amounts for add_liquidity.
@param amounts The amounts of coins being added to the pool.
@param xp The current balances of the pool multiplied by coin precisions.
@return uint256 Fee charged.
"""
return self._calc_token_fee(amounts, xp)
@view
@internal
def _calc_token_fee(amounts: uint256[N_COINS], xp: uint256[N_COINS]) -> uint256:
# fee = sum(amounts_i - avg(amounts)) * fee' / sum(amounts)
fee: uint256 = unsafe_div(
unsafe_mul(self._fee(xp), N_COINS),
unsafe_mul(4, unsafe_sub(N_COINS, 1))
)
S: uint256 = 0
for _x in amounts:
S += _x
avg: uint256 = unsafe_div(S, N_COINS)
Sdiff: uint256 = 0
for _x in amounts:
if _x > avg:
Sdiff += unsafe_sub(_x, avg)
else:
Sdiff += unsafe_sub(avg, _x)
return fee * Sdiff / S + NOISE_FEE
```
```vyper
@view
@external
def calc_token_amount(
amounts: uint256[N_COINS], deposit: bool, swap: address
) -> uint256:
d_token: uint256 = 0
amountsp: uint256[N_COINS] = empty(uint256[N_COINS])
xp: uint256[N_COINS] = empty(uint256[N_COINS])
d_token, amountsp, xp = self._calc_dtoken_nofee(amounts, deposit, swap)
d_token -= (
Curve(swap).calc_token_fee(amountsp, xp) * d_token / 10**10 + 1
)
return d_token
@view
@external
def calc_fee_token_amount(
amounts: uint256[N_COINS], deposit: bool, swap: address
) -> uint256:
d_token: uint256 = 0
amountsp: uint256[N_COINS] = empty(uint256[N_COINS])
xp: uint256[N_COINS] = empty(uint256[N_COINS])
d_token, amountsp, xp = self._calc_dtoken_nofee(amounts, deposit, swap)
return Curve(swap).calc_token_fee(amountsp, xp) * d_token / 10**10 + 1
```
**▶Example▼**
```shell
>>> TriCrypto.calc_token_amount(todo)
'todo'
```
<a id="calc_withdraw_one_coin"></a>
### `calc_withdraw_one_coin`
`TriCrypto.calc_withdraw_one_coin(token_amount: uint256, i: uint256) -> uint256:`
Function to calculate the amount of output token `i` when burning `token_amount` of LP tokens. This method takes fees into consideration.
| Input | Type | Description |
| --- | --- | --- |
| `token_amount` | `uint256` | Amount of LP tokens burned. |
| `i` | `uint256` | Index of the coin to withdraw. |
Returns: amount of tokens to receive (`uint256`).
**<>Source code▼**
```vyper
@view
@external
def calc_withdraw_one_coin(token_amount: uint256, i: uint256) -> uint256:
"""
@notice Calculates output tokens with fee
@param token_amount LP Token amount to burn
@param i token in which liquidity is withdrawn
@return uint256 Amount of ith tokens received for burning token_amount LP tokens.
"""
return self._calc_withdraw_one_coin(
self._A_gamma(),
token_amount,
i,
(self.future_A_gamma_time > block.timestamp)
)[0]
@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.calc_withdraw_one_coin(1000000000000000000, 0)
1071872163
```
* * *
<a id="fees-and-pool-profits"></a>
## Fees and Pool Profits
The cryptoswap algorithm uses different fees, such as `fee`, `mid_fee`, `out_fee`, or `fee_gamma` to determine the fees charged, more on that [here](https://docs.curve.finance/developer/amm/legacy/cryptoswap-overview.md#fees). All Fee values are denominated in 1e10 and [can be changed](https://docs.curve.finance/developer/amm/tricrypto-ng/pools/tricrypto.md#apply_new_parameters) by the admin.
Additionally, just as for other curve pools, there is an `ADMIN_FEE`, which is hardcoded to 50%. All twocrypto-ng pools share a universal `fee_receiver`, which is determined within the Factory contract.
`xcp_profit` and `xcp_profit_a` are used for tracking pool profits, which is necessary for the pool's rebalancing mechanism. These values are denominated in 1e18.
<a id="fee"></a>
### `fee`
`TriCrypto.fee() -> uint256:`
Getter for the fee charged by the pool at the current state.
Returns: fee (`uint256`).
**<>Source code▼**
```vyper
@external
@view
def fee() -> uint256:
"""
@notice Returns the fee charged by the pool at current state.
@dev Not to be confused with the fee charged at liquidity action, since
there the fee is calculated on `xp` AFTER liquidity is added or
removed.
@return uint256 fee bps.
"""
return self._fee(self.xp())
@internal
@view
def _fee(xp: uint256[N_COINS]) -> uint256:
fee_params: uint256[3] = self._unpack(self.packed_fee_params)
f: uint256 = MATH.reduction_coefficient(xp, fee_params[2])
return unsafe_div(
fee_params[0] * f + fee_params[1] * (10**18 - f),
10**18
)
```
```vyper
@external
@view
def reduction_coefficient(x: uint256[N_COINS], fee_gamma: uint256) -> uint256:
"""
@notice Calculates the reduction coefficient for the given x and fee_gamma
@dev This method is used for calculating fees.
@param x The x values
@param fee_gamma The fee gamma value
"""
return self._reduction_coefficient(x, fee_gamma)
@internal
@pure
def _reduction_coefficient(x: uint256[N_COINS], fee_gamma: uint256) -> uint256:
# fee_gamma / (fee_gamma + (1 - K))
# where
# K = prod(x) / (sum(x) / N)**N
# (all normalized to 1e18)
S: uint256 = x[0] + x[1] + x[2]
# Could be good to pre-sort x, but it is used only for dynamic fee
K: uint256 = 10**18 * N_COINS * x[0] / S
K = unsafe_div(K * N_COINS * x[1], S) # <- unsafe div is safu.
K = unsafe_div(K * N_COINS * x[2], S)
if fee_gamma > 0:
K = fee_gamma * 10**18 / (fee_gamma + 10**18 - K)
return K
```
**▶Example▼**
```shell
>>> TriCrypto.fee()
3771992
```
<a id="mid_fee"></a>
### `mid_fee`
`TriCrypto.mid_fee() -> uint256:`
Getter for the current `mid_fee`. This is the minimum fee and is charged when the pool is completely balanced.
Returns: mid fee (`uint256`).
**<>Source code▼**
```vyper
packed_fee_params: public(uint256) # <---- Packs mid_fee, out_fee, fee_gamma.
@view
@external
def mid_fee() -> uint256:
"""
@notice Returns the current mid fee
@return uint256 mid_fee value.
"""
return self._unpack(self.packed_fee_params)[0]
```
**▶Example▼**
```shell
>>> TriCrypto.mid_fee()
1499999
```
<a id="out_fee"></a>
### `out_fee`
`TriCrypto.out_fee() -> uint256:`
Getter for the "out-fee". This is the maximum fee and is charged when the pool is completely imbalanced.
Returns: out fee (`uint256`).
**<>Source code▼**
```vyper
packed_fee_params: public(uint256) # <---- Packs mid_fee, out_fee, fee_gamma.
@view
@external
def out_fee() -> uint256:
"""
@notice Returns the current out fee
@return uint256 out_fee value.
"""
return self._unpack(self.packed_fee_params)[1]
```
**▶Example▼**
```shell
>>> TriCrypto.out_fee()
140000000
```
<a id="fee_gamma"></a>
### `fee_gamma`
`TriCrypto.fee_gamma() -> uint256:`
Getter for the current "fee-gamma". This parameter modifies the rate at which fees rise as imbalance intensifies. Smaller values result in rapid fee hikes with growing imbalances, while larger values lead to more gradual increments in fees as imbalance expands.
Returns: fee gamma (`uint256`).
**<>Source code▼**
```vyper
packed_fee_params: public(uint256) # <---- Packs mid_fee, out_fee, fee_gamma.
@view
@external
def fee_gamma() -> uint256:
"""
@notice Returns the 프로젝트로 돌아가기