Curve DAO 백서

Curve DAO

원문

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

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 D0: uint256 = 0 # -------------------------- Calculate D0 and xp ------------------------- price_scale_i: uint256 = self.cached_price_scale * PRECISIONS[1] xp: uint256[N_COINS] = [ xx[0] * PRECISIONS[0], unsafe_div(xx[1] * price_scale_i, PRECISION) ] if i == 0: price_scale_i = PRECISION * PRECISIONS[0] 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_3(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 # <------------------<---------- TODO: Check math. # ------------------------------------------------------------------------ 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: """ Finding the invariant using Newton method. ANN is higher by the factor A_MULTIPLIER ANN is already A * N**N """ # 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 # Initial value of invariant D is that for constant-product invariant x: uint256[N_COINS] = x_unsorted if x[0] < x[1]: x = [x_unsorted[1], x_unsorted[0]] assert x[0] > 10**9 - 1 and x[0] < 10**15 * 10**18 + 1 # dev: unsafe values x[0] assert unsafe_div(x[1] * 10**18, x[0]) > 10**14 - 1 # dev: unsafe values x[i] (input) S: uint256 = unsafe_add(x[0], x[1]) # can unsafe add here because we checked x[0] bounds D: uint256 = 0 if K0_prev == 0: D = N_COINS * isqrt(unsafe_mul(x[0], x[1])) else: # D = isqrt(x[0] * x[1] * 4 / K0_prev * 10**18) D = isqrt(unsafe_mul(unsafe_div(unsafe_mul(unsafe_mul(4, x[0]), x[1]), K0_prev), 10**18)) if S < D: D = S __g1k0: uint256 = gamma + 10**18 diff: uint256 = 0 for i in range(255): D_prev: uint256 = D assert D > 0 # Unsafe division by D and D_prev is now safe # K0: uint256 = 10**18 # for _x in x: # K0 = K0 * _x * N_COINS / D # collapsed for 2 coins K0: uint256 = unsafe_div(unsafe_div((10**18 * N_COINS**2) * x[0], D) * x[1], D) _g1k0: uint256 = __g1k0 if _g1k0 > K0: _g1k0 = unsafe_add(unsafe_sub(_g1k0, K0), 1) # > 0 else: _g1k0 = unsafe_add(unsafe_sub(K0, _g1k0), 1) # > 0 # D / (A * N**N) * _g1k0**2 / gamma**2 mul1: uint256 = unsafe_div(unsafe_div(unsafe_div(10**18 * D, gamma) * _g1k0, gamma) * _g1k0 * A_MULTIPLIER, ANN) # 2*N*K0 / _g1k0 mul2: uint256 = unsafe_div(((2 * 10**18) * N_COINS) * K0, _g1k0) # calculate neg_fprime. here K0 > 0 is being validated (safediv). neg_fprime: uint256 = (S + unsafe_div(S * mul2, 10**18)) + mul1 * N_COINS / K0 - unsafe_div(mul2 * D, 10**18) # D -= f / fprime; neg_fprime safediv being validated D_plus: uint256 = D * (neg_fprime + S) / neg_fprime D_minus: uint256 = unsafe_div(D * D, neg_fprime) if 10**18 > K0: D_minus += unsafe_div(unsafe_div(D * unsafe_div(mul1, neg_fprime), 10**18) * unsafe_sub(10**18, K0), K0) else: D_minus -= unsafe_div(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) 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) if diff * 10**14 < max(10**16, D): # Could reduce precision for gas efficiency here for _x in x: frac: uint256 = _x * 10**18 / D assert (frac >= 10**16 - 1) and (frac < 10**20 + 1) # dev: unsafe values x[i] return D raise "Did not converge" @external @pure def get_y( _ANN: uint256, _gamma: uint256, _x: uint256[N_COINS], _D: uint256, i: uint256 ) -> uint256[2]: # 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 ANN: int256 = convert(_ANN, int256) gamma: int256 = convert(_gamma, int256) D: int256 = convert(_D, int256) x_j: int256 = convert(_x[1 - i], int256) gamma2: int256 = unsafe_mul(gamma, gamma) # savediv by x_j done here: y: int256 = D**2 / (x_j * N_COINS**2) # K0_i: int256 = (10**18 * N_COINS) * x_j / D K0_i: int256 = unsafe_div(10**18 * N_COINS * x_j, D) assert (K0_i > 10**16 * N_COINS - 1) and (K0_i < 10**20 * N_COINS + 1) # dev: unsafe values x[i] ann_gamma2: int256 = ANN * gamma2 # a = 10**36 / N_COINS**2 a: int256 = 10**32 # b = ANN*D*gamma2/4/10000/x_j/10**4 - 10**32*3 - 2*gamma*10**14 b: int256 = ( D*ann_gamma2/400000000/x_j - convert(unsafe_mul(10**32, 3), int256) - unsafe_mul(unsafe_mul(2, gamma), 10**14) ) # c = 10**32*3 + 4*gamma*10**14 + gamma2/10**4 + 4*ANN*gamma2*x_j/D/10000/4/10**4 - 4*ANN*gamma2/10000/4/10**4 c: int256 = ( unsafe_mul(10**32, convert(3, int256)) + unsafe_mul(unsafe_mul(4, gamma), 10**14) + unsafe_div(gamma2, 10**4) + unsafe_div(unsafe_div(unsafe_mul(4, ann_gamma2), 400000000) * x_j, D) - unsafe_div(unsafe_mul(4, ann_gamma2), 400000000) ) # d = -(10**18+gamma)**2 / 10**4 d: int256 = -unsafe_div(unsafe_add(10**18, gamma) **2, 10**4) # delta0: int256 = 3*a*c/b - b delta0: int256 = 3 * a * c / b - b # safediv by b # delta1: int256 = 9*a*c/b - 2*b - 27*a**2/b*d/b delta1: int256 = 3 * delta0 + b - 27*a**2/b*d/b divider: int256 = 1 threshold: int256 = min(min(abs(delta0), abs(delta1)), a) if threshold > 10**48: divider = 10**30 elif threshold > 10**46: divider = 10**28 elif threshold > 10**44: divider = 10**26 elif threshold > 10**42: divider = 10**24 elif threshold > 10**40: divider = 10**22 elif threshold > 10**38: divider = 10**20 elif threshold > 10**36: divider = 10**18 elif threshold > 10**34: divider = 10**16 elif threshold > 10**32: divider = 10**14 elif threshold > 10**30: divider = 10**12 elif threshold > 10**28: divider = 10**10 elif threshold > 10**26: divider = 10**8 elif threshold > 10**24: divider = 10**6 elif threshold > 10**20: divider = 10**2 a = unsafe_div(a, divider) b = unsafe_div(b, divider) c = unsafe_div(c, divider) d = unsafe_div(d, divider) # delta0 = 3*a*c/b - b: here we can do more unsafe ops now: delta0 = unsafe_div(unsafe_mul(unsafe_mul(3, a), c), b) - b # delta1 = 9*a*c/b - 2*b - 27*a**2/b*d/b delta1 = 3 * delta0 + b - unsafe_div(unsafe_mul(unsafe_div(unsafe_mul(27, a**2), b), d), b) # sqrt_arg: int256 = delta1**2 + 4*delta0**2/b*delta0 sqrt_arg: int256 = delta1**2 + unsafe_mul(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: # second_cbrt = convert(self._cbrt(convert((delta1 + sqrt_val), uint256) / 2), int256) second_cbrt = convert(self._cbrt(convert(unsafe_add(delta1, sqrt_val), uint256) / 2), int256) else: # second_cbrt = -convert(self._cbrt(convert(unsafe_sub(sqrt_val, delta1), uint256) / 2), int256) second_cbrt = -convert(self._cbrt(unsafe_div(convert(unsafe_sub(sqrt_val, delta1), uint256), 2)), int256) # C1: int256 = b_cbrt**2/10**18*second_cbrt/10**18 C1: int256 = unsafe_div(unsafe_mul(unsafe_div(b_cbrt**2, 10**18), second_cbrt), 10**18) # root: int256 = (10**18*C1 - 10**18*b - 10**18*b*delta0/C1)/(3*a), keep 2 safe ops here. root: int256 = (unsafe_mul(10**18, C1) - unsafe_mul(10**18, b) - unsafe_mul(10**18, b)/C1*delta0)/unsafe_mul(3, a) # y_out: uint256[2] = [ # convert(D**2/x_j*root/4/10**18, uint256), # <--- y # convert(root, uint256) # <----------------------- K0Prev # ] y_out: uint256[2] = [convert(unsafe_div(unsafe_div(unsafe_mul(unsafe_div(D**2, x_j), root), 4), 10**18), uint256), convert(root, uint256)] frac: uint256 = unsafe_div(y_out[0] * 10**18, _D) assert (frac >= 10**16 - 1) and (frac < 10**20 + 1) # dev: unsafe value for y return y_out ``` **▶Example▼** ```shell In [1]: Pool.calc_withdraw_one_coin(1000000000000000000, 0) Out [1]: 26501860406190437 In [2]: Pool.calc_withdraw_one_coin(1000000000000000000, 1) Out [2]: 150537307454780254829 ``` * * * <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/twocrypto-ng/pools/twocrypto.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. Unlike for most other Curve pools, there is no external method to claim the admin fees. They are claimed when removing liquidity single sided. `xcp_profit`, `xcp_profit_a`, and `last_xcp` 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` `TwoCrypto.fee() -> uint256:` Getter for the fee charged by the pool at the current state. Returns: fee in bps (`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(self.balances, self.cached_price_scale)) @internal @view def _fee(xp: uint256[N_COINS]) -> uint256: fee_params: uint256[3] = self._unpack_3(self.packed_fee_params) f: uint256 = xp[0] + xp[1] f = fee_params[2] * 10**18 / ( fee_params[2] + 10**18 - (10**18 * N_COINS**N_COINS) * xp[0] / f * xp[1] / f ) return unsafe_div( fee_params[0] * f + fee_params[1] * (10**18 - f), 10**18 ) ``` **▶Example▼** ```shell In [1]: Pool.fee() Out [1]: 30622026 ``` <a id="mid_fee"></a> ### `mid_fee` `TwoCrypto.mid_fee() -> uint256:` Getter for the `mid_fee`. This fee 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_3(self.packed_fee_params)[0] ``` **▶Example▼** ```shell In [1]: Pool.mid_fee() Out [1]: 26000000 ``` <a id="out_fee"></a> ### `out_fee` `TwoCrypto.out_fee() -> uint256:` Getter for the `out_fee`. This fee 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_3(self.packed_fee_params)[1] ``` **▶Example▼** ```shell In [1]: Pool.out_fee() Out [1]: 45000000 ``` <a id="fee_gamma"></a> ### `fee_gamma` `TwoCrypto.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 current fee gamma @return uint256 fee_gamma value. """ return self._unpack_3(self.packed_fee_params)[2] ``` **▶Example▼** ```shell In [1]: Pool.fee_gamma() Out [1]: 230000000000000 ``` <a id="packed_fee_params"></a> ### `packed_fee_params` `TwoCrypto.packed_fee_params() -> uint256: view` Getter for the packed fee parameters. Returns: packed fee params (`uint256`). **<>Source code▼** ```vyper # Fee params that determine dynamic fees: packed_fee_params: public(uint256) # <---- Packs mid_fee, out_fee, fee_gamma. @external def __init__( _name: String[64], _symbol: String[32], _coins: address[N_COINS], _math: address, _salt: bytes32, packed_precisions: uint256, packed_gamma_A: uint256, packed_fee_params: uint256, packed_rebalancing_params: uint256, initial_price: uint256, ): ... self.packed_fee_params = packed_fee_params # <-------------- Contains Fee # params: mid_fee, out_fee and fee_gamma. ... ``` **▶Example▼** ```shell In [1]: Pool.packed_fee_params() Out [1]: 8847341539944400050877843276543133320576000000 ``` <a id="admin_fee"></a> ### `ADMIN_FEE` `TwoCrypto.packed_fee_params() -> uint256: view` Getter for the admin fee of the pool. This value is hardcoded to 50% (5000000000) of the earned fees and can not be changed. Returns: admin fee (`uint256`). **<>Source code▼** ```vyper ADMIN_FEE: public(constant(uint256)) = 5 * 10**9 # <----- 50% of earned fees. ``` **▶Example▼** ```shell In [1]: Pool.ADMIN_FEE() Out [1]: 5000000000 ``` <a id="fee_receiver"></a> ### `fee_receiver` `TwoCrypto.fee_receiver() -> address:` Getter for the fee receiver of the admin fees. This address is set within the [Twocrypto-NG Factory](https://docs.curve.finance/developer/amm/factory/twocrypto-ng/overview.md). Every pool created through the Factory has the same fee receiver. Returns: fee receiver (`address`). **<>Source code▼** ```vyper interface Factory: def fee_receiver() -> address: view @external @view def fee_receiver() -> address: """ @notice Returns the address of the admin fee receiver. @return address Fee receiver. """ return factory.fee_receiver() ``` **▶Example▼** ```shell In [1]: Pool.fee_receiver() Out [1]: '0xeCb456EA5365865EbAb8a2661B0c503410e9B347' ``` <a id="xcp_profit"></a> ### `xcp_profit` `TwoCrypto.xcp_profit() -> uint256: view` Getter for the current pool profits. Returns: current profits (`uint256`). **<>Source code▼** ```vyper xcp_profit: public(uint256) ``` **▶Example▼** ```shell In [1]: Pool.xcp_profit() Out [1]: 1000280532115852216 ``` <a id="xcp_profit_a"></a> ### `xcp_profit_a` `TwoCrypto.xcp_profit_a() -> uint256: view` Getter for the full profit at the last claim of admin fees. Returns: profit at last claim (`uint256`). **<>Source code▼** ```vyper xcp_profit_a: public(uint256) # <--- Full profit at last claim of admin fees. @external def __init__( _name: String[64], _symbol: String[32], _coins: address[N_COINS], _math: address, _salt: bytes32, packed_precisions: uint256, packed_gamma_A: uint256, packed_fee_params: uint256, packed_rebalancing_params: uint256, initial_price: uint256, ): ... self.xcp_profit_a = 10**18 ... ``` **▶Example▼** ```shell In [1]: Pool.xcp_profit_a() Out [1]: 1000000000000000000 ``` <a id="last_xcp"></a> ### `last_xcp` `TwoCrypto.last_xcp() -> uint256: view` Getter for the last xcp action. This variable is updated by calling `tweak_price` or `remove_liquidity`. Returns: timestamp of last xcp action (`uint256`). **<>Source code▼** ```vyper last_xcp: public(uint256) ``` **▶Example▼** ```shell In [1]: Pool.last_xcp() Out [1]: 4177413767556756716238 ``` * * * <a id="price-scaling"></a> ## Price Scaling Curve v2 pools automatically adjust liquidity to optimize depth close to the prevailing market rates, reducing slippage. More [here](https://docs.curve.finance/developer/amm/legacy/cryptoswap-overview.md#price-scaling). Price scaling parameter can be adjusted by the [admin](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/twocrypto.md#apply_new_parameters). <a id="price_scale"></a> ### `price_scale` `TwoCrypto.price_scale() -> uint256:` Getter for the price scale of the coin at index 1 with regard to the coin at index 0. The price scale determines the price band around which liquidity is concentrated. Returns: price scale (`uint256`). **<>Source code▼** ```vyper cached_price_scale: uint256 # <------------------------ Internal price scale. @external @view @nonreentrant("lock") def price_scale() -> uint256: """ @notice Returns the price scale of the coin at index `k` w.r.t the coin at index 0. @dev Price scale determines the price band around which liquidity is concentrated. @return uint256 Price scale of coin. """ return self.cached_price_scale ``` **▶Example▼** ```shell In [1]: Pool.price_scale() Out [1]: 176501696719232 ``` <a id="allowed_extra_profit"></a> ### `allowed_extra_profit` `TwoCrypto.allowed_extra_profit() -> uint256:` Getter for the allowed extra profit value. Returns: allowed extra profit (`uint256`). **<>Source code▼** ```vyper packed_rebalancing_params: public(uint256) # <---------- Contains rebalancing # parameters allowed_extra_profit, adjustment_step, and ma_time. @view @external def allowed_extra_profit() -> uint256: """ @notice Returns the current allowed extra profit @return uint256 allowed_extra_profit value. """ return self._unpack_3(self.packed_rebalancing_params)[0] ``` **▶Example▼** ```shell In [1]: Pool.allowed_extra_profit() Out [1]: 2000000000000 ``` <a id="adjustment_step"></a> ### `adjustment_step` `TwoCrypto.allowed_extra_profit() -> uint256:` Getter for the adjustment step value. Returns: adjustment step (
프로젝트로 돌아가기