Curve DAO 백서

Curve DAO

원문

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

] * _x[1], 10**18) * _x[2], 10**18 ) if prod == 0: return 0 return self._cbrt(prod) @internal @pure def _cbrt(x: uint256) -> uint256: xx: uint256 = 0 if x >= 115792089237316195423570985008687907853269 * 10**18: xx = x elif x >= 115792089237316195423570985008687907853269: xx = unsafe_mul(x, 10**18) else: xx = unsafe_mul(x, 10**36) log2x: int256 = convert(self._snekmate_log_2(xx, False), int256) # When we divide log2x by 3, the remainder is (log2x % 3). # So if we just multiply 2**(log2x/3) and discard the remainder to calculate our # guess, the newton method will need more iterations to converge to a solution, # since it is missing that precision. It's a few more calculations now to do less # calculations later: # pow = log2(x) // 3 # remainder = log2(x) % 3 # initial_guess = 2 **pow * cbrt(2) **remainder # substituting -> 2 = 1.26 ≈ 1260 / 1000, we get: # # initial_guess = 2 **pow * 1260 **remainder // 1000 **remainder remainder: uint256 = convert(log2x, uint256) % 3 a: uint256 = unsafe_div( unsafe_mul( pow_mod256(2, unsafe_div(convert(log2x, uint256), 3)), # <- pow pow_mod256(1260, remainder), ), pow_mod256(1000, remainder), ) # Because we chose good initial values for cube roots, 7 newton raphson iterations # are just about sufficient. 6 iterations would result in non-convergences, and 8 # would be one too many iterations. Without initial values, the iteration count # can go up to 20 or greater. The iterations are unrolled. This reduces gas costs # but takes up more bytecode: a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) a = unsafe_div(unsafe_add(unsafe_mul(2, a), unsafe_div(xx, unsafe_mul(a, a))), 3) if x >= 115792089237316195423570985008687907853269 * 10**18: a = unsafe_mul(a, 10**12) elif x >= 115792089237316195423570985008687907853269: a = unsafe_mul(a, 10**6) return a ``` **▶Example▼** ```shell >>> Math.geometric_mean([3000000000000000000,3000000000000000000,3000000000000000000]) 3000000000000000000 ``` <a id="reduction_coefficient"></a> ### `reduction_coefficient` `Math.reduction_coefficient(x: uint256[N_COINS], fee_gamma: uint256) -> uint256:` Function to calculate the reduction coefficient for `x` and `fee_gamma`. This method is used for calculating fees. | Input | Type | Description | | --- | --- | --- | | `x` | `uint256[N_COINS]` | Values of x | | `fee_gamma` | `uint256` | Fee gamma | Returns: reduction coefficient (`uint256`). **<>Source code▼** ```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 >>> Math.reduction_coefficient([1123,1123,11], 500000000000000) 516570424625783 ``` <a id="wad_exp"></a> ### `wad_exp` `Math.wad_exp(_power: int256) -> uint256:` Function to calculate the natural exponential function of a signed integer with a precision of 1e18. | Input | Type | Description | | --- | --- | --- | | `_power` | `int256` | Value to calculate the natural exponential function of | Returns: natural exponential (`uint256`). tip More here: [https://github.com/pcaversaccio/snekmate](https://github.com/pcaversaccio/snekmate). **<>Source code▼** ```vyper @external @view def wad_exp(_power: int256) -> uint256: """ @notice Calculates the e**x with 1e18 precision @param _power The number to calculate the exponential of """ return self._snekmate_wad_exp(_power) @internal @pure def _snekmate_wad_exp(x: int256) -> uint256: """ @dev Calculates the natural exponential function of a signed integer with a precision of 1e18. @notice Note that this function consumes about 810 gas units. The implementation is inspired by Remco Bloemen's implementation under the MIT license here: https://xn--2-umb.com/22/exp-ln. @dev This implementation is derived from Snekmate, which is authored by pcaversaccio (Snekmate), distributed under the AGPL-3.0 license. https://github.com/pcaversaccio/snekmate @param x The 32-byte variable. @return int256 The 32-byte calculation result. """ value: int256 = x # If the result is `< 0.5`, we return zero. This happens when we have the following: # "x <= floor(log(0.5e18) * 1e18) ~ -42e18". if (x <= -42139678854452767551): return empty(uint256) # When the result is "> (2 **255 - 1) / 1e18" we cannot represent it as a signed integer. # This happens when "x >= floor(log((2 **255 - 1) / 1e18) * 1e18) ~ 135". assert x < 135305999368893231589, "wad_exp overflow" # `x` is now in the range "(-42, 136) * 1e18". Convert to "(-42, 136) * 2 **96" for higher # intermediate precision and a binary base. This base conversion is a multiplication with # "1e18 / 2 **96 = 5 **18 / 2 **78". value = unsafe_div(x << 78, 5 **18) # Reduce the range of `x` to "(-½ ln 2, ½ ln 2) * 2 **96" by factoring out powers of two # so that "exp(x) = exp(x') * 2 **k", where `k` is a signer integer. Solving this gives # "k = round(x / log(2))" and "x' = x - k * log(2)". Thus, `k` is in the range "[-61, 195]". k: int256 = unsafe_add(unsafe_div(value << 96, 54916777467707473351141471128), 2 **95) >> 96 value = unsafe_sub(value, unsafe_mul(k, 54916777467707473351141471128)) # Evaluate using a "(6, 7)"-term rational approximation. Since `p` is monic, # we will multiply by a scaling factor later. y: int256 = unsafe_add(unsafe_mul(unsafe_add(value, 1346386616545796478920950773328), value) >> 96, 57155421227552351082224309758442) p: int256 = unsafe_add(unsafe_mul(unsafe_add(unsafe_mul(unsafe_sub(unsafe_add(y, value), 94201549194550492254356042504812), y) >> 96,\ 28719021644029726153956944680412240), value), 4385272521454847904659076985693276 << 96) # We leave `p` in the "2 **192" base so that we do not have to scale it up # again for the division. q: int256 = unsafe_add(unsafe_mul(unsafe_sub(value, 2855989394907223263936484059900), value) >> 96, 50020603652535783019961831881945) q = unsafe_sub(unsafe_mul(q, value) >> 96, 533845033583426703283633433725380) q = unsafe_add(unsafe_mul(q, value) >> 96, 3604857256930695427073651918091429) q = unsafe_sub(unsafe_mul(q, value) >> 96, 14423608567350463180887372962807573) q = unsafe_add(unsafe_mul(q, value) >> 96, 26449188498355588339934803723976023) # The polynomial `q` has no zeros in the range because all its roots are complex. # No scaling is required, as `p` is already "2 **96" too large. Also, # `r` is in the range "(0.09, 0.25) * 2**96" after the division. r: int256 = unsafe_div(p, q) # To finalise the calculation, we have to multiply `r` by: # - the scale factor "s = ~6.031367120", # - the factor "2 **k" from the range reduction, and # - the factor "1e18 / 2 **96" for the base conversion. # We do this all at once, with an intermediate result in "2**213" base, # so that the final right shift always gives a positive value. # Note that to circumvent Vyper's safecast feature for the potentially # negative parameter value `r`, we first convert `r` to `bytes32` and # subsequently to `uint256`. Remember that the EVM default behaviour is # to use two's complement representation to handle signed integers. return unsafe_mul(convert(convert(r, bytes32), uint256), 3822833074963236453042738258902158003155416615667) >> convert(unsafe_sub(195, k), uint256) ``` **▶Example▼** ```shell >>> Math.wad_exp(1000000) 1000000000001000000 ``` <a id="version"></a> ### `version` `Math.version() -> String[8]: view` Getter for the current version of the contract. Returns: current contract version (`String[8]`). **<>Source code▼** ```vyper version: public(constant(String[8])) = "v2.0.0" ``` **▶Example▼** ```shell >>> Math.version() 'v2.0.0' ``` --- # Views Contract Source: [https://docs.curve.finance/developer/amm/tricrypto-ng/utility-contracts/views](https://docs.curve.finance/developer/amm/tricrypto-ng/utility-contracts/views) This contract contains **view-only external methods** which can be gas-inefficient when called from smart contracts. Contract Source & Deployment Source code for this contract is available on [Github](https://github.com/curvefi/tricrypto-ng/blob/main/contracts/main/CurveCryptoViews3Optimized.vy). Full list of all deployments can be found [here](https://docs.curve.finance/developer/deployments.md). * * * <a id="exchange-methods"></a> ## Exchange Methods <a id="get_dy"></a> ### `get_dy` `ViewMethodContract.get_dy(i: uint256, j: uint256, dx: uint256, swap: address) -> uint256:` Getter method for the amount of coin `j` tokens received for swapping in `dx` amount of coin `i`. This function includes the fee. | Input | Type | Description | | --- | --- | --- | | `i` | `uint256` | Index of input token (use `pool.coins(i)` to get coin address at i-th index) | | `j` | `uint256` | Index of output token | | `dx` | `uint256` | Amount of input coin\[i\] tokens | | `swap` | `address` | Pool contract address | Returns: `dy` (`uint256`). **<>Source code▼** ```vyper @external @view def get_dy( i: uint256, j: uint256, dx: uint256, swap: address ) -> uint256: dy: uint256 = 0 xp: uint256[N_COINS] = empty(uint256[N_COINS]) # dy = (get_y(x + dx) - y) * (1 - fee) dy, xp = self._get_dy_nofee(i, j, dx, swap) dy -= Curve(swap).fee_calc(xp) * dy / 10**10 return dy ``` **▶Example▼** ```shell >>> ViewMethodContract.get_dy(0, 1, 100000000000, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4") 384205076 ``` <a id="get_dx"></a> ### `get_dx` `ViewMethodContract.get_dx(i: uint256, j: uint256, dy: uint256, swap: address) -> uint256:` Getter method for the amount of coin\[i\] tokens to input for swapping out dy amount of coin\[j\] | Input | Type | Description | | --- | --- | --- | | `i` | `uint256` | Index of input token (check pool.coins(i) to get coin address at i-th index) | | `j` | `uint256` | Index of output token | | `dy` | `uint256` | amount of input coin\[j\] tokens received | | `swap` | `address` | Pool contract address | Returns: dx (`uint256`). note This is an approximate method, and returns estimates close to the input amount. Expensive to call on-chain. **<>Source code▼** ```vyper @view @external def get_dx( i: uint256, j: uint256, dy: uint256, swap: address ) -> uint256: dx: uint256 = 0 xp: uint256[N_COINS] = empty(uint256[N_COINS]) fee_dy: uint256 = 0 _dy: uint256 = dy # for more precise dx (but never exact), increase num loops for k in range(5): dx, xp = self._get_dx_fee(i, j, _dy, swap) fee_dy = Curve(swap).fee_calc(xp) * _dy / 10**10 _dy = dy + fee_dy + 1 return dx ``` **▶Example▼** ```shell >>> ViewMethodContract.get_dx(0, 1, 1000, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4") 259849 ``` <a id="calc_withdraw_one_coin"></a> ### `calc_withdraw_one_coin` `ViewMethodContract.calc_withdraw_one_coin(token_amount: uint256, i: uint256, swap: address) -> uint256:` Getter method for the output tokens (including fees) when withdrawing one coin. | Input | Type | Description | | --- | --- | --- | | `token_amount` | `uint256` | LP token amount | | `i` | `uint256` | Index of the token to withdraw | | `swap` | `address` | Pool contract address | Returns: amount of output tokens (`uint256`). **<>Source code▼** ```vyper @view @external def calc_withdraw_one_coin( token_amount: uint256, i: uint256, swap: address ) -> uint256: return self._calc_withdraw_one_coin(token_amount, i, swap)[0] @internal @view def _calc_withdraw_one_coin( token_amount: uint256, i: uint256, swap: address ) -> (uint256, uint256): token_supply: uint256 = Curve(swap).totalSupply() assert token_amount <= token_supply # dev: token amount more than supply assert i < N_COINS # dev: coin out of range math: Math = Curve(swap).MATH() xx: uint256[N_COINS] = empty(uint256[N_COINS]) price_scale: uint256[N_COINS-1] = empty(uint256[N_COINS-1]) for k in range(N_COINS): xx[k] = Curve(swap).balances(k) if k > 0: price_scale[k - 1] = Curve(swap).price_scale(k - 1) precisions: uint256[N_COINS] = Curve(swap).precisions() A: uint256 = Curve(swap).A() gamma: uint256 = Curve(swap).gamma() xp: uint256[N_COINS] = precisions D0: uint256 = 0 p: uint256 = 0 price_scale_i: uint256 = PRECISION * precisions[0] xp[0] *= xx[0] for k in range(1, N_COINS): p = price_scale[k-1] if i == k: price_scale_i = p * xp[i] xp[k] = xp[k] * xx[k] * p / PRECISION if Curve(swap).future_A_gamma_time() > block.timestamp: D0 = math.newton_D(A, gamma, xp, 0) else: D0 = Curve(swap).D() D: uint256 = D0 fee: uint256 = self._fee(xp, swap) dD: uint256 = token_amount * D / token_supply D_fee: uint256 = fee * dD / (2 * 10**10) + 1 approx_fee: uint256 = N_COINS * D_fee * xx[i] / D D -= (dD - D_fee) y_out: uint256[2] = math.get_y(A, gamma, xp, D, i) dy: uint256 = (xp[i] - y_out[0]) * PRECISION / price_scale_i xp[i] = y_out[0] return dy, approx_fee ``` **▶Example▼** ```shell >>> ViewMethodContract.calc_withdraw_one_coin(1000000000000000, 0, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4") 1049071 ``` <a id="calc_token_amount"></a> ### `calc_token_amount` `ViewMethodContract.calc_token_amount(amounts: uint256[N_COINS], deposit: bool, swap: address) -> uint256:` Function to calculate LP tokens minted or to be burned for depositing or removing `amounts` of coins to or from `swap`. | Input | Type | Description | | --- | --- | --- | | `amounts` | `uint256[N_COINS]` | LP token amount | | `deposit` | `bool` | `True` = deposit, `False` = withdraw | | `swap` | `address` | Pool contract address | Returns: LP token amount to be burned/minted (`uint256`). **<>Source code▼** ```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 @internal @view def _calc_dtoken_nofee( amounts: uint256[N_COINS], deposit: bool, swap: address ) -> (uint256, uint256[N_COINS], uint256[N_COINS]): math: Math = Curve(swap).MATH() xp: uint256[N_COINS] = empty(uint256[N_COINS]) precisions: uint256[N_COINS] = empty(uint256[N_COINS]) price_scale: uint256[N_COINS-1] = empty(uint256[N_COINS-1]) D0: uint256 = 0 token_supply: uint256 = 0 A: uint256 = 0 gamma: uint256 = 0 xp, D0, token_supply, price_scale, A, gamma, precisions = self._prep_calc(swap) amountsp: uint256[N_COINS] = amounts if deposit: for k in range(N_COINS): xp[k] += amounts[k] else: for k in range(N_COINS): xp[k] -= amounts[k] xp[0] *= precisions[0] amountsp[0] *= precisions[0] for k in range(N_COINS - 1): p: uint256 = price_scale[k] * precisions[k + 1] xp[k + 1] = xp[k + 1] * p / PRECISION amountsp[k + 1] = amountsp[k + 1] * p / PRECISION D: uint256 = math.newton_D(A, gamma, xp, 0) d_token: uint256 = token_supply * D / D0 if deposit: d_token -= token_supply else: d_token = token_supply - d_token return d_token, amountsp, xp ``` **▶Example▼** ```shell >>> ViewMethodContract.calc_token_amount([1,1,1], 0, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4") 248287947930 ``` <a id="calculating-fees-methods"></a> ## Calculating Fees Methods Methods to calculate fees for **`get_dy`**, \*\*`withdraw_one_coin`\*\*and **`calc_token_amount`**. <a id="calc_fee_get_dy"></a> ### `calc_fee_get_dy` `ViewMethodContract.calc_fee_get_dy(i: uint256, j: uint256, dx: uint256, swap: address) -> uint256:` Function to calculate the fees for `get_dy`. | Input | Type | Description | | --- | --- | --- | | `i` | `uint256` | Index of input token (check pool.coins(i) to get coin address at i-th index) | | `j` | `uint256` | Index of output token | | `dx` | `uint256` | Amount of input coin\[i\] tokens | | `swap` | `address` | Pool contract address | Returns: fee (`uint256`). **<>Source code▼** ```vyper @external @view def calc_fee_get_dy(i: uint256, j: uint256, dx: uint256, swap: address ) -> uint256: dy: uint256 = 0 xp: uint256[N_COINS] = empty(uint256[N_COINS]) dy, xp = self._get_dy_nofee(i, j, dx, swap) return Curve(swap).fee_calc(xp) * dy / 10**10 @internal @view def _get_dy_nofee( i: uint256, j: uint256, dx: uint256, swap: address ) -> (uint256, uint256[N_COINS]): assert i != j and i < N_COINS and j < N_COINS, "coin index out of range" assert dx > 0, "do not exchange 0 coins" math: Math = Curve(swap).MATH() xp: uint256[N_COINS] = empty(uint256[N_COINS]) precisions: uint256[N_COINS] = empty(uint256[N_COINS]) price_scale: uint256[N_COINS-1] = empty(uint256[N_COINS-1]) D: uint256 = 0 token_supply: uint256 = 0 A: uint256 = 0 gamma: uint256 = 0 xp, D, token_supply, price_scale, A, gamma, precisions = self._prep_calc(swap) # adjust xp with input dx xp[i] += dx xp[0] *= precisions[0] for k in range(N_COINS - 1): xp[k + 1] = xp[k + 1] * price_scale[k] * precisions[k + 1] / PRECISION y_out: uint256[2] = math.get_y(A, gamma, xp, D, j) dy: uint256 = xp[j] - y_out[0] - 1 xp[j] = y_out[0] if j > 0: dy = dy * PRECISION / price_scale[j - 1] dy /= precisions[j] return dy, xp ``` **▶Example▼** ```shell >>> ViewMethodContract.calc_fee_get_dy(0, 1, 100000000, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4") 142 ``` <a id="calc_fee_withdraw_one_coin"></a> ### `calc_fee_withdraw_one_coin` `ViewMethodContract.calc_fee_withdraw_one_coin(token_amount: uint256, i: uint256, swap: address) -> uint256:` Function to calculate the fees for `withdraw_one_coin`. | Input | Type | Description | | --- | --- | --- | | `token_amount` | `uint256` | LP token amount | | `i` | `uint256` | Index of the token to withdraw | | `swap` | `address` | Pool contract address | Returns: fee (`uint256`). **<>Source code▼** ```vyper @external @view def calc_fee_withdraw_one_coin( token_amount: uint256, i: uint256, swap: address ) -> uint256: return self._calc_withdraw_one_coin(token_amount, i, swap)[1] @internal @view def _calc_withdraw_one_coin( token_amount: uint256, i: uint256, swap: address ) -> (uint256, uint256): token_supply: uint256 = Curve(swap).totalSupply() assert token_amount <= token_supply # dev: token amount more than supply assert i < N_COINS # dev: coin out of range math: Math = Curve(swap).MATH() xx: uint256[N_COINS] = empty(uint256[N_COINS]) price_scale: uint256[N_COINS-1] = empty(uint256[N_COINS-1]) for k in range(N_COINS): xx[k] = Curve(swap).balances(k) if k > 0: price_scale[k - 1] = Curve(swap).price_scale(k - 1) precisions: uint256[N_COINS] = Curve(swap).precisions() A: uint256 = Curve(swap).A() gamma: uint256 = Curve(swap).gamma() xp: uint256[N_COINS] = precisions D0: uint256 = 0 p: uint256 = 0 price_scale_i: uint256 = PRECISION * precisions[0] xp[0] *= xx[0] for k in range(1, N_COINS): p = price_scale[k-1] if i == k: pri
프로젝트로 돌아가기