Curve DAO 백서

Curve DAO

원문

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

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 get_dx(i: uint256, j: uint256, dy: uint256) -> uint256: """ @notice Get amount of coin[i] tokens to input for swapping out dy amount of coin[j] @dev This is an approximate method, and returns estimates close to the input amount. Expensive to call on-chain. @param i index of input token. Check pool.coins(i) to get coin address at ith index @param j index of output token @param dy amount of input coin[j] tokens received @return uint256 Approximate amount of input i tokens to get dy amount of j tokens. """ view_contract: address = Factory(self.factory).views_implementation() return Views(view_contract).get_dx(i, j, dy, self) @external @view def fee_calc(xp: uint256[N_COINS]) -> uint256: # <----- For by view contract. """ @notice Returns the fee charged by the pool at current state. @param xp The current balances of the pool multiplied by coin precisions. @return uint256 Fee value. """ return self._fee(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 @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 @internal @view def _get_dx_fee( i: uint256, j: uint256, dy: uint256, swap: address ) -> (uint256, uint256[N_COINS]): # here, dy must include fees (and 1 wei offset) assert i != j and i < N_COINS and j < N_COINS, "coin index out of range" assert dy > 0, "do not exchange out 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 output dy. dy contains fee element, which we handle later # (hence this internal method is called _get_dx_fee) xp[j] -= dy xp[0] *= precisions[0] for k in range(N_COINS - 1): xp[k + 1] = xp[k + 1] * price_scale[k] * precisions[k + 1] / PRECISION x_out: uint256[2] = math.get_y(A, gamma, xp, D, i) dx: uint256 = x_out[0] - xp[i] xp[i] = x_out[0] if i > 0: dx = dx * PRECISION / price_scale[i - 1] dx /= precisions[i] return dx, xp @internal @view def _prep_calc(swap: address) -> ( uint256[N_COINS], uint256, uint256, uint256[N_COINS-1], uint256, uint256, uint256[N_COINS] ): precisions: uint256[N_COINS] = Curve(swap).precisions() token_supply: uint256 = Curve(swap).totalSupply() xp: uint256[N_COINS] = empty(uint256[N_COINS]) for k in range(N_COINS): xp[k] = Curve(swap).balances(k) price_scale: uint256[N_COINS - 1] = empty(uint256[N_COINS - 1]) for k in range(N_COINS - 1): price_scale[k] = Curve(swap).price_scale(k) A: uint256 = Curve(swap).A() gamma: uint256 = Curve(swap).gamma() D: uint256 = self._calc_D_ramp( A, gamma, xp, precisions, price_scale, swap ) return xp, D, token_supply, price_scale, A, gamma, precisions ``` ```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.get_dx(0, 1, 10000000) 2767670393 ``` <a id="fee_calc"></a> ### `fee_calc` `TriCrypto.fee_calc(xp: uint256[N_COINS]) -> uint256: view` Getter for the charged exchange fee by the pool at the current state. | Input | Type | Description | | --- | --- | --- | | `xp` | `uint256[N_COINS]` | Pool balances multiplied by the coin precisions. | Returns: fee (`uint256`). **<>Source code▼** ```vyper @external @view def fee_calc(xp: uint256[N_COINS]) -> uint256: # <----- For by view contract. """ @notice Returns the fee charged by the pool at current state. @param xp The current balances of the pool multiplied by coin precisions. @return uint256 Fee value. """ return self._fee(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_calc('todo') '' ``` * * * <a id="adding-and-removing-liquidity"></a> ## Adding and Removing Liquidity *The tricrypto-ng implementation utilizes the usual methods to add and remove liquidity.* **Adding liquidity**can be done via the `add_liquidity` method. The code uses a list of unsigned integers `uint256[N_COINS]` as input for the pools underlying tokens to add. **Any proportion is possible**. For example, adding fully single-sided can be done using `[0, 1e18]` or `[1e18, 0]`, but again, any variation is possible, e.g., `[1e18, 1e19]`. **Removing liquidity**can be done in two different ways. Either withdraw the underlying assets in a **balanced proportion**using the `remove_liquidity` method **or fully single-sided**in a single underlying token using `remove_liquidity_one_coin`. <a id="add_liquidity"></a> ### `add_liquidity` `TriCrypto.add_liquidity(amounts: uint256[N_COINS], min_mint_amount: uint256, use_eth: bool = False, receiver: address = msg.sender) -> uint256:` Function to add liquidity to the pool and mint the corresponding LP tokens. | Input | Type | Description | | --- | --- | --- | | `amounts` | `uint256[N_COINS]` | Amount of each coin to add. | | `min_mint_amount` | `uint256` | Minimum amount of LP tokens to mint. | | `use_eth` | `bool` | `True` = native token is added to the pool. | | `receiver` | `address` | Receiver of the LP tokens; defaults to msg.sender. | Returns: amount of LP tokens received (`uint256`). Emits: `AddLiquidity` **<>Source code▼** ```vyper event AddLiquidity: provider: indexed(address) token_amounts: uint256[N_COINS] fee: uint256 token_supply: uint256 packed_price_scale: uint256 @payable @external @nonreentrant("lock") def add_liquidity( amounts: uint256[N_COINS], min_mint_amount: uint256, use_eth: bool = False, receiver: address = msg.sender ) -> uint256: """ @notice Adds liquidity into the pool. @param amounts Amounts of each coin to add. @param min_mint_amount Minimum amount of LP to mint. @param use_eth True if native token is being added to the pool. @param receiver Address to send the LP tokens to. Default is msg.sender @return uint256 Amount of LP tokens received by the `receiver """ A_gamma: uint256[2] = self._A_gamma() xp: uint256[N_COINS] = self.balances amountsp: uint256[N_COINS] = empty(uint256[N_COINS]) xx: uint256[N_COINS] = empty(uint256[N_COINS]) d_token: uint256 = 0 d_token_fee: uint256 = 0 old_D: uint256 = 0 assert amounts[0] + amounts[1] + amounts[2] > 0 # dev: no coins to add # --------------------- Get prices, balances ----------------------------- precisions: uint256[N_COINS] = self._unpack(self.packed_precisions) packed_price_scale: uint256 = self.price_scale_packed price_scale: uint256[N_COINS-1] = self._unpack_prices(packed_price_scale) # -------------------------------------- Update balances and calculate xp. xp_old: uint256[N_COINS] = xp for i in range(N_COINS): bal: uint256 = xp[i] + amounts[i] xp[i] = bal self.balances[i] = bal xx = xp xp[0] *= precisions[0] xp_old[0] *= precisions[0] for i in range(1, N_COINS): xp[i] = unsafe_div(xp[i] * price_scale[i-1] * precisions[i], PRECISION) xp_old[i] = unsafe_div( xp_old[i] * unsafe_mul(price_scale[i-1], precisions[i]), PRECISION ) # ---------------- transferFrom token into the pool ---------------------- for i in range(N_COINS): if amounts[i] > 0: if coins[i] == WETH20: self._transfer_in( coins[i], amounts[i], 0, # <----------------------------------- msg.value, # | No callbacks empty(address), # <----------------------| for empty(bytes32), # <----------------------| add_liquidity. msg.sender, # | empty(address), # <----------------------- use_eth ) else: self._transfer_in( coins[i], amounts[i], 0, 0, # <----------------- mvalue = 0 if coin is not WETH20. empty(address), empty(bytes32), msg.sender, empty(address), False # <-------- use_eth is False if coin is not WETH20. ) amountsp[i] = xp[i] - xp_old[i] # -------------------- Calculate LP tokens to mint ----------------------- if self.future_A_gamma_time > block.timestamp: # <--- A_gamma is ramping. # ----- Recalculate the invariant if A or gamma are undergoing a ramp. old_D = MATH.newton_D(A_gamma[0], A_gamma[1], xp_old, 0) else: old_D = self.D D: uint256 = MATH.newton_D(A_gamma[0], A_gamma[1], xp, 0) token_supply: uint256 = self.totalSupply if old_D > 0: d_token = token_supply * D / old_D - token_supply else: d_token = self.get_xcp(D) # <------------------------- Making initial # virtual price equal to 1. assert d_token > 0 # dev: nothing minted if old_D > 0: d_token_fee = ( self._calc_token_fee(amountsp, xp) * d_token / 10**10 + 1 ) d_token -= d_token_fee token_supply += d_token self.mint(receiver, d_token) packed_price_scale = self.tweak_price(A_gamma, xp, D, 0) else: self.D = D self.virtual_price = 10**18 self.xcp_profit = 10**18 self.xcp_profit_a = 10**18 self.mint(receiver, d_token) assert d_token >= min_mint_amount, "Slippage" log AddLiquidity( receiver, amounts, d_token_fee, token_supply, packed_price_scale ) self._claim_admin_fees() # <--------------------------- Claim admin fees. return d_token ``` ```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" ``` **▶Example▼** ```shell >>> TriCrypto.add_liquidity('todo') '' ``` <a id="calc_token_fee"></a> ### `calc_token_fee` `TriCrypto.calc_token_fee(amounts: uint256[N_COINS], xp: uint256[N_COINS]) -> uint256:` Function to calculate the charged fee on `amounts` when adding liquidity. | Input | Type | Description | | --- | --- | --- | | `amounts` | `uint256[N_COINS]` | Amount of coins added to the pool. | | `xp` | `uint256[N_COINS]` | Pool balances multiplied by the coin precisions. | Returns: fee (`uint256`). **<>Source code▼** ```vyper @external @view def calc_token_fee( amounts: uint256[N_COINS], xp: uint256[N_COINS] ) -> uint256: """ @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 ``` **▶Example▼** ```shell >>> TriCrypto.calc_token_fee() 'todo' ``` <a id="remove_liquidity"></a> ### `remove_liquidity` `TriCrypto.remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS], use_eth: bool = False, receiver: address = msg.sender, claim_admin_fees: bool = True) -> uint256[N_COINS]:` Function to remove liquidity from the pool and burn the LP tokens. When removing liquidity with this function, no fees are charged as the coins are withdrawn in balanced proportions. If admin fees are claimed, they are claimed before withdrawing liquidity, ensuring the DAO gets paid first. | Input | Type | Description | | --- | --- | --- | | `_amount` | `uint256` | Amount of LP tokens to burn. | | `min_amounts` | `uint256[N_COINS]` | Minimum amounts of tokens to withdraw. | | `use_eth` | `bool` | True = withdraw ETH, False = withdraw wETH. | | `receiver` | `address` | Receiver of the coins; defaults to `msg.sender`. | | `claim_admin_fees` | `bool` | Whether to claim admin fees; defaults to `True`. | Returns: withdrawn balances (`uint256[N_COINS]`). Emits: `RemoveLiquidity` **<>Source code▼** ```vyper event RemoveLiquidity: provider: indexed(address) token_amounts: uint256[N_COINS] token_supply: uint256 @external @nonreentrant("lock") def remo
프로젝트로 돌아가기