Curve DAO 백서

Curve DAO

원문

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

current fee gamma @return uint256 fee_gamma value. """ return self._unpack(self.packed_fee_params)[2] ``` **▶Example▼** ```shell >>> TriCrypto.fee_gamma() 500000000000000 ``` <a id="packed_fee_params"></a> ### `packed_fee_params` `TriCrypto.packed_fee_params() -> uint256: view` Getter for the packed fee parameters. Returns: packed fee params (`uint256`). **<>Source code▼** ```vyper packed_fee_params: public(uint256) # <---- Packs mid_fee, out_fee, fee_gamma. ``` **▶Example▼** ```shell >>> TriCrypto.packed_fee_params() 510423210099040776839142618093032111655788544 ``` <a id="fee_receiver"></a> ### `fee_receiver` `TriCrypto.fee_receiver() -> address: view` Getter for the fee receiver of the admin fees. This address is set within the Tricrypto Factory. Every pool created through the Factory has the same fee receiver. Returns: fee receiver (`address`). **<>Source code▼** ```vyper interface Factory: def admin() -> address: view def fee_receiver() -> address: view def views_implementation() -> address: view @external @view def fee_receiver() -> address: """ @notice Returns the address of the admin fee receiver. @return address Fee receiver. """ return Factory(self.factory).fee_receiver() ``` **▶Example▼** ```shell >>> TriCrypto.fee_receiver() '0xeCb456EA5365865EbAb8a2661B0c503410e9B347' ``` <a id="admin_fee"></a> ### `ADMIN_FEE` `TriCrypto.ADMIN_FEE() -> uint256: view` Getter for the admin fee of the pool. This value is hardcoded to 50% (5000000000). Returns: admin fee (`uint256`). **<>Source code▼** ````vyper ADMIN_FEE: public(constant(uint256)) = 5 * 10**9 # <----- 50% of earned fees. ``` ```` **▶Example▼** ```shell >>> TriCrypto.ADMIN_FEE() 5000000000 ``` <a id="claim_admin_fees"></a> ### `claim_admin_fees` `CryptoSwap.claim_admin_fees() -> uint256:` Function to claim the accumulated admin fees from the pool and send them to the fee receiver. Emits: `ClaimAdminFee` **<>Source code▼** ```vyper event ClaimAdminFee: admin: indexed(address) tokens: uint256 @external @nonreentrant("lock") def claim_admin_fees(): """ @notice Claim admin fees. Callable by anyone. """ self._claim_admin_fees() @internal def _claim_admin_fees(): """ @notice Claims admin fees and sends it to fee_receiver set in the factory. """ A_gamma: uint256[2] = self._A_gamma() xcp_profit: uint256 = self.xcp_profit # <---------- Current pool profits. xcp_profit_a: uint256 = self.xcp_profit_a # <- Profits at previous claim. total_supply: uint256 = self.totalSupply # Do not claim admin fees if: # 1. insufficient profits accrued since last claim, and # 2. there are less than 10**18 (or 1 unit of) lp tokens, else it can lead # to manipulated virtual prices. if xcp_profit <= xcp_profit_a or total_supply < 10**18: return # Claim tokens belonging to the admin here. This is done by 'gulping' # pool tokens that have accrued as fees, but not accounted in pool's # `self.balances` yet: pool balances only account for incoming and # outgoing tokens excluding fees. Following 'gulps' fees: for i in range(N_COINS): if coins[i] == WETH20: self.balances[i] = self.balance else: self.balances[i] = ERC20(coins[i]).balanceOf(self) # If the pool has made no profits, `xcp_profit == xcp_profit_a` # and the pool gulps nothing in the previous step. vprice: uint256 = self.virtual_price # Admin fees are calculated as follows. # 1. Calculate accrued profit since last claim. `xcp_profit` # is the current profits. `xcp_profit_a` is the profits # at the previous claim. # 2. Take out admin's share, which is hardcoded at 5 * 10**9. # (50% => half of 100% => 10**10 / 2 => 5 * 10**9). # 3. Since half of the profits go to rebalancing the pool, we # are left with half; so divide by 2. fees: uint256 = unsafe_div( unsafe_sub(xcp_profit, xcp_profit_a) * ADMIN_FEE, 2 * 10**10 ) # ------------------------------ Claim admin fees by minting admin's share # of the pool in LP tokens. receiver: address = Factory(self.factory).fee_receiver() if receiver != empty(address) and fees > 0: frac: uint256 = vprice * 10**18 / (vprice - fees) - 10**18 claimed: uint256 = self.mint_relative(receiver, frac) xcp_profit -= fees * 2 self.xcp_profit = xcp_profit log ClaimAdminFee(receiver, claimed) # ------------------------------------------- Recalculate D b/c we gulped. D: uint256 = MATH.newton_D(A_gamma[0], A_gamma[1], self.xp(), 0) self.D = D # ------------------- Recalculate virtual_price following admin fee claim. # In this instance we do not check if current virtual price is greater # than old virtual price, since the claim process can result # in a small decrease in pool's value. self.virtual_price = 10**18 * self.get_xcp(D) / self.totalSupply self.xcp_profit_a = xcp_profit # <------------ Cache last claimed profit. ``` ```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 >>> CryptoSwap.claim_admin_fees() ``` <a id="xcp_profit"></a> ### `xcp_profit` `TriCrypto.xcp_profit() -> uint256:` Getter for the current pool profits. Returns: current profits (`uint256`). **<>Source code▼** ```vyper xcp_profit: public(uint256) ``` **▶Example▼** ```shell >>> TriCrypto.xcp_profit() 1003213938530958270 ``` <a id="xcp_profit_a"></a> ### `xcp_profit_a` `TriCrypto.xcp_profit_a() -> uint256:` 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. ``` **▶Example▼** ```shell >>> TriCrypto.xcp_profit_a() 1003211094190051384 ``` * * * <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/tricrypto-ng/pools/tricrypto.md#apply_new_parameters). <a id="price_scale"></a> ### `price_scale` `TriCrypto.price_scale(k: uint256) -> uint256:` Getter for the price scale of the coin at index `k` with regard to the coin at index 0. Price scale determines the price band around which liquidity is concentrated and is conditionally updated when calling the functions `add_liquidity`, `remove_liquidity_one_coin`, `exchange`, `exchange_underlying` or `exchange_extended`. | Input | Type | Description | | --- | --- | --- | | `k` | `uint256` | Index of the coin. | Returns: last price (`uint256`). **<>Source code▼** ```vyper price_scale_packed: uint256 # <------------------------ Internal price scale. @external @view def price_scale(k: uint256) -> 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. @param k The index of the coin. @return uint256 Price scale of coin. """ return self._unpack_prices(self.price_scale_packed)[k] @internal def tweak_price( A_gamma: uint256[2], _xp: uint256[N_COINS], new_D: uint256, K0_prev: uint256 = 0, ) -> uint256: """ @notice Tweaks price_oracle, last_price and conditionally adjusts price_scale. This is called whenever there is an unbalanced liquidity operation: _exchange, add_liquidity, or remove_liquidity_one_coin. @dev Contains main liquidity rebalancing logic, by tweaking `price_scale`. @param A_gamma Array of A and gamma parameters. @param _xp Array of current balances. @param new_D New D value. @param K0_prev Initial guess for `newton_D`. """ # ---------------------------- Read storage ------------------------------ rebalancing_params: uint256[3] = self._unpack( self.packed_rebalancing_params ) # <---------- Contains: allowed_extra_profit, adjustment_step, ma_time. price_oracle: uint256[N_COINS - 1] = self._unpack_prices( self.price_oracle_packed ) last_prices: uint256[N_COINS - 1] = self._unpack_prices( self.last_prices_packed ) packed_price_scale: uint256 = self.price_scale_packed price_scale: uint256[N_COINS - 1] = self._unpack_prices( packed_price_scale ) total_supply: uint256 = self.totalSupply old_xcp_profit: uint256 = self.xcp_profit old_virtual_price: uint256 = self.virtual_price last_prices_timestamp: uint256 = self.last_prices_timestamp # ----------------------- Update MA if needed ---------------------------- if last_prices_timestamp < block.timestamp: # The moving average price oracle is calculated using the last_price # of the trade at the previous block, and the price oracle logged # before that trade. This can happen only once per block. # ------------------ Calculate moving average params ----------------- alpha: uint256 = MATH.wad_exp( -convert( unsafe_div( (block.timestamp - last_prices_timestamp) * 10**18, rebalancing_params[2] # <----------------------- ma_time. ), int256, ) ) for k in range(N_COINS - 1): # ----------------- We cap state price that goes into the EMA with # 2 x price_scale. price_oracle[k] = unsafe_div( min(last_prices[k], 2 * price_scale[k]) * (10**18 - alpha) + price_oracle[k] * alpha, # ^-------- Cap spot price into EMA. 10**18 ) self.price_oracle_packed = self._pack_prices(price_oracle) self.last_prices_timestamp = block.timestamp # <---- Store timestamp. # price_oracle is used further on to calculate its vector # distance from price_scale. This distance is used to calculate # the amount of adjustment to be done to the price_scale. # ------------------ If new_D is set to 0, calculate it ------------------ D_unadjusted: uint256 = new_D if new_D == 0: # <--------------------------- _exchange sets new_D to 0. D_unadjusted = MATH.newton_D(A_gamma[0], A_gamma[1], _xp, K0_prev) # ----------------------- Calculate last_prices -------------------------- last_prices = MATH.get_p(_xp, D_unadjusted, A_gamma) for k in range(N_COINS - 1): last_prices[k] = unsafe_div(last_prices[k] * price_scale[k], 10**18) self.last_prices_packed = self._pack_prices(last_prices) # ---------- Update profit numbers without price adjustment first -------- xp: uint256[N_COINS] = empty(uint256[N_COINS]) xp[0] = unsafe_div(D_unadjusted, N_COINS) for k in range(N_COINS - 1): xp[k + 1] = D_unadjusted * 10**18 / (N_COINS * price_scale[k]) # ------------------------- Update xcp_profit ---------------------------- xcp_profit: uint256 = 10**18 virtual_price: uint256 = 10**18 if old_virtual_price > 0: xcp: uint256 = MATH.geometric_mean(xp) virtual_price = 10**18 * xcp / total_supply xcp_profit = unsafe_div( old_xcp_profit * virtual_price, old_virtual_price ) # <---------------- Safu to do unsafe_div as old_virtual_price > 0. # If A and gamma are not undergoing ramps (t < block.timestamp), # ensure new virtual_price is not less than old virtual_price, # else the pool suffers a loss. if self.future_A_gamma_time < block.timestamp: assert virtual_price > old_virtual_price, "Loss" self.xcp_profit = xcp_profit # ------------ Rebalance liquidity if there's enough profits to adjust it: if virtual_price * 2 - 10**18 > xcp_profit + 2 * rebalancing_params[0]: # allowed_extra_profit --------^ # ------------------- Get adjustment step ---------------------------- # Calculate the vector distance between price_scale and # price_oracle. norm: uint256 = 0 ratio: uint256 = 0 for k in range(N_COINS - 1): ratio = unsafe_div(price_oracle[k] * 10**18, price_scale[k]) # unsafe_div because we did safediv before ----^ if ratio > 10**18: ratio = unsafe_sub(ratio, 10**18) else: ratio = unsafe_sub(10**18, ratio) norm = unsafe_add(norm, ratio**2) norm = isqrt(norm) # <-------------------- isqrt is not in base 1e18. adjustment_step: uint256 = max( rebalancing_params[1], unsafe_div(norm, 5) ) # ^------------------------------------- adjustment_step. if norm > adjustment_step: # <---------- We only adjust prices if the # vector distance between price_oracle and price_scale is # large enough. This check ensures that no rebalancing # occurs if the distance is low i.e. the pool prices are # pegged to the oracle prices. # ------------------------------------- Calculate new price scale. p_new: uint256[N_COINS - 1] = empty(uint256[N_COINS - 1]) for k in range(N_COINS - 1): p_new[k] = unsafe_div( price_scale[k] * unsafe_sub(norm, adjustment_step) + adjustment_step * price_oracle[k], norm ) # <- norm is non-zero and gt adjustment_step; unsafe = safe # ---------------- Update stale xp (using price_scale) with p_new. xp = _xp for k in range(N_COINS - 1): xp[k + 1] = unsafe_div(_xp[k + 1] * p_new[k], price_scale[k]) # unsafe_div because we did safediv before ----^ # ------------------------------------------ Update D with new xp. D: uint256 = MATH.newton_D(A_gamma[0], A_gamma[1], xp, 0) for k in range(N_COINS): frac: uint256 = xp[k] * 10**18 / D # <----- Check validity of assert (frac > 10**16 - 1) and (frac < 10**20 + 1) # p_new. xp[0] = D / N_COINS for k in range(N_COINS - 1): xp[k + 1] = D * 10**18 / (N_COINS * p_new[k]) # <---- Convert # xp to real prices. # ---------- Calculate new virtual_price using new xp and D. Reuse # `old_virtual_price` (but it has new virtual_price). old_virtual_price = unsafe_div( 10**18 * MATH.geometric_mean(xp), total_supply ) # <----- unsafe_div because we did safediv before (if vp>1e18) # ---------------------------- Proceed if we've got enough profit. if ( old_virtual_price > 10**18 and 2 * old_virtual_price - 10**18 > xcp_profit ): packed_price_scale = self._pack_prices(p_new) self.D = D self.virtual_price = old_virtual_price self.price_scale_packed = packed_price_scale return packed_price_scale # --------- price_scale was not adjusted. Update the profit counter and D. self.D = D_unadjusted self.virtual_price = virtual_price return packed_price_scale ``` **▶Example▼** ```shell >>> TriCrypto.price_scale(0) 27902293922834345521086 ``` <a id="allowed_extra_profit"></a> ### `allowed_extra_profit` `TriCrypto.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(self.packed_rebalancing_params)[0] ``` **▶Example▼** ```shell >>> TriCr
프로젝트로 돌아가기