Curve DAO 백서

Curve DAO

원문

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

s 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" # -------------------------- Cache last_xcp -------------------------- self.last_xcp = xcp # geometric_mean(D * price_scale) 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 = unsafe_div( unsafe_mul(price_oracle, 10**18), price_scale ) if norm > 10**18: norm = unsafe_sub(norm, 10**18) else: norm = unsafe_sub(10**18, norm) 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 = unsafe_div( price_scale * unsafe_sub(norm, adjustment_step) + adjustment_step * price_oracle, norm ) # <---- norm is non-zero and gt adjustment_step; unsafe = safe. # ---------------- Update stale xp (using price_scale) with p_new. xp = [ _xp[0], unsafe_div(_xp[1] * p_new, price_scale) ] # ------------------------------------------ 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. # ------------------------------------- Convert xp to real prices. xp = [ unsafe_div(D, N_COINS), D * PRECISION / (N_COINS * p_new) ] # ---------- 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 * isqrt(xp[0] * xp[1]), 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 ): self.D = D self.virtual_price = old_virtual_price self.cached_price_scale = p_new return p_new # --------- price_scale was not adjusted. Update the profit counter and D. self.D = D_unadjusted self.virtual_price = virtual_price return price_scale ``` * * * <a id="other-methods"></a> ## Other Methods <a id="last_prices"></a> ### `last_prices` `CurveTwocryptoOptimized.last_prices() -> uint256: view` Getter for the last price of the coin at index 1 with regard to the coin at index 0. This variable is used to calculate the moving average price oracle. Returns: last price (`uint256`). **<>Source code▼** ```vyper last_prices: public(uint256) @internal def tweak_price( A_gamma: uint256[2], _xp: uint256[N_COINS], new_D: uint256, K0_prev: uint256 = 0, ) -> uint256: """ @notice Updates 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`. """ ... # ----------------------- Calculate last_prices -------------------------- self.last_prices = unsafe_div( MATH.get_p(_xp, D_unadjusted, A_gamma) * price_scale, 10**18 ) ... ``` ```vyper @external @view def get_p( _xp: uint256[N_COINS], _D: uint256, _A_gamma: uint256[N_COINS] ) -> uint256: """ @notice Calculates dx/dy. @dev Output needs to be multiplied with price_scale to get the actual value. @param _xp Balances of the pool. @param _D Current value of D. @param _A_gamma Amplification coefficient and gamma. """ assert _D > 10**17 - 1 and _D < 10**15 * 10**18 + 1 # dev: unsafe D values # K0 = P * N**N / D**N. # K0 is dimensionless and has 10**36 precision: K0: uint256 = unsafe_div( unsafe_div(4 * _xp[0] * _xp[1], _D) * 10**36, _D ) # GK0 is in 10**36 precision and is dimensionless. # GK0 = ( # 2 * _K0 * _K0 / 10**36 * _K0 / 10**36 # + (gamma + 10**18)**2 # - (_K0 * _K0 / 10**36 * (2 * gamma + 3 * 10**18) / 10**18) # ) # GK0 is always positive. So the following should never revert: GK0: uint256 = ( unsafe_div(unsafe_div(2 * K0 * K0, 10**36) * K0, 10**36) + pow_mod256(unsafe_add(_A_gamma[1], 10**18), 2) - unsafe_div( unsafe_div(pow_mod256(K0, 2), 10**36) * unsafe_add(unsafe_mul(2, _A_gamma[1]), 3 * 10**18), 10**18 ) ) # NNAG2 = N**N * A * gamma**2 NNAG2: uint256 = unsafe_div(unsafe_mul(_A_gamma[0], pow_mod256(_A_gamma[1], 2)), A_MULTIPLIER) # denominator = (GK0 + NNAG2 * x / D * _K0 / 10**36) denominator: uint256 = (GK0 + unsafe_div(unsafe_div(NNAG2 * _xp[0], _D) * K0, 10**36) ) # p_xy = x * (GK0 + NNAG2 * y / D * K0 / 10**36) / y * 10**18 / denominator # p is in 10**18 precision. return unsafe_div( _xp[0] * ( GK0 + unsafe_div(unsafe_div(NNAG2 * _xp[1], _D) * K0, 10**36) ) / _xp[1] * 10**18, denominator ) ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.last_prices() '74644221911388' ``` <a id="last_timestamp"></a> ### `last_timestamp` `CurveTwocryptoOptimized.last_timestamp() -> uint256: view` Getter for the last timestamps when price and xcp oracles were updated. Both timestamps are packed into a single variable. The lower 128 bits represent the timestamp of the price update, the upper 128 bits the timestamps of the xcp update. The distinction between price and xcp is neccessary because these values are not always updated in parallel. Usually they are, but when liquidity is removed in a balanced matter, the price oracle is not updated but the xcp one is. Returns: packed value of the timestamps of the most recent updated of the price and xcp oracle (`uint256`). **<>Source code▼** ```vyper last_timestamp: public(uint256) # idx 0 is for prices, idx 1 is for xcp. ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.last_timestamp() 585060874787625947552086540639603571285491911031 # unpacking >>> 585060874787625947552086540639603571285491911031 & (2**128 - 1) 1719339383 >>> 585060874787625947552086540639603571285491911031 >> 128 1719339383 ``` <a id="ma_time"></a> ### `ma_time` `CurveTwocryptoOptimized.ma_time() -> uint256: view` Getter for the moving average time for `price_oracle` denominated in seconds. This variable can be changed using the `apply_new_parameters` method. Returns: moving average time (`uint256`). **<>Source code▼** ```vyper packed_rebalancing_params: public(uint256) # <---------- Contains rebalancing # parameters allowed_extra_profit, adjustment_step, and ma_time. @view @external def ma_time() -> uint256: """ @notice Returns the current moving average time in seconds @dev To get time in seconds, the parameter is multipled by ln(2) One can expect off-by-one errors here. @return uint256 ma_time value. """ return self._unpack_3(self.packed_rebalancing_params)[2] * 694 / 1000 ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.ma_time() 601 ``` <a id="xcp_ma_time"></a> ### `xcp_ma_time` `CurveTwocryptoOptimized.xcp_ma_time() -> uint256: view` Getter for the moving-average periodicity for `price_oracle` denominated in seconds. This variable can be changed using the `apply_new_parameters` method. Returns: ma time (`uint256`). **<>Source code▼** ```vyper xcp_ma_time: public(uint256) @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_ma_time = 62324 # <--------- 12 hours default on contract start. ... ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.xcp_ma_time() 62324 ``` <a id="lp_price"></a> ### `lp_price` `CurveTwocryptoOptimized.lp_price() -> uint256: view` Function to calculate the price of the LP token with regard to the coin at `index 0` in the pool. The value is calculate the following: $\text{lp\_price} = \frac{2 \times \text{virtual\_price} \times \sqrt{\text{price\_oracle} \times 10^{18}}}{10^{18}}$ Returns: LP token price (`uint256`). **<>Source code▼** ```vyper @external @view @nonreentrant("lock") def lp_price() -> uint256: """ @notice Calculates the current price of the LP token w.r.t coin at the 0th index @return uint256 LP price. """ return 2 * self.virtual_price * isqrt(self.internal_price_oracle() * 10**18) / 10**18 @internal @view def internal_price_oracle() -> uint256: """ @notice Returns the oracle price of the coin at index `k` w.r.t the coin at index 0. @dev The oracle is an exponential moving average, with a periodicity determined by `self.ma_time`. The aggregated prices are cached state prices (dy/dx) calculated AFTER the latest trade. @param k The index of the coin. @return uint256 Price oracle value of kth coin. """ price_oracle: uint256 = self.cached_price_oracle price_scale: uint256 = self.cached_price_scale last_prices_timestamp: uint256 = self._unpack_2(self.last_timestamp)[0] if last_prices_timestamp < block.timestamp: # <------------ Update moving # average if needed. last_prices: uint256 = self.last_prices ma_time: uint256 = self._unpack_3(self.packed_rebalancing_params)[2] alpha: uint256 = MATH.wad_exp( -convert( unsafe_sub(block.timestamp, last_prices_timestamp) * 10**18 / ma_time, int256, ) ) # ---- We cap state price that goes into the EMA with 2 x price_scale. return ( min(last_prices, 2 * price_scale) * (10**18 - alpha) + price_oracle * alpha ) / 10**18 return price_oracle ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.lp_price() 26545349102641443 # lp token price in wETH ``` <a id="virtual_price"></a> ### `virtual_price` `CurveTwocryptoOptimized.virtual_price() -> uint256: view` `get_virtual_price` ≠ `virtual_price` `get_virtual_price` should not be confused with `virtual_price`, which is a cached virtual price. Getter for the cached virtual price. This variable provides a fast read by accessing the cached value instead of recalculating it. Returns: cached virtual price (`uint256`). **<>Source code▼** ```vyper virtual_price: public(uint256) # <------ Cached (fast to read) virtual price. # The cached `virtual_price` is also used internally. ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.virtual_price() 1000270251060292804 ``` <a id="get_virtual_price"></a> ### `get_virtual_price` `CurveTwocryptoOptimized.get_virtual_price() -> uint256: view` `get_virtual_price` ≠ `virtual_price` `get_virtual_price` should not be confused with `virtual_price`, which is a cached virtual price. Function to dynamically calculate the current virtual price of the pool's LP token. It essentially calculates the virtual price based on the current state of the pool (`D` and `cached_price_scale`) and the total supply of LP tokens. Returns: virtual price (`uint256`). **<>Source code▼** ```vyper @external @view @nonreentrant("lock") def get_virtual_price() -> uint256: """ @notice Calculates the current virtual price of the pool LP token. @dev Not to be confused with `self.virtual_price` which is a cached virtual price. @return uint256 Virtual Price. """ return 10**18 * self.get_xcp(self.D, self.cached_price_scale) / self.totalSupply @internal @pure def get_xcp(D: uint256, price_scale: uint256) -> uint256: x: uint256[N_COINS] = [ unsafe_div(D, N_COINS), D * PRECISION / (price_scale * N_COINS) ] return isqrt(x[0] * x[1]) # <------------------- Geometric Mean. ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.get_virtual_price() 1000270251060292804 ``` --- # Pools: Overview Source: [https://docs.curve.finance/developer/amm/twocrypto-ng/pools/overview](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/overview) **New Features Over the Regular Two-Coin CryptoSwap Implementation:**\- New fee claiming approach - [**`exchange_received`**](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/overview.md#exchange_received) - Overall gas optimizations <a id="fee-claiming"></a> ## Fee Claiming Admin fees of a Curve pool are usually claimed through an external function, callable by anyone. **Twocrypto-NG does not have any external function to directly claim fees**. Admin fees are claimed through an internal function, which is called when liquidity is removed single-sidedly via the `_remove_liquidity_one_coin` function, and then sent to the fee receiver determined within the Factory contract. **▶\`\_claim\_admin\_fees()\`▼** ```vyper @internal def _claim_admin_fees(): """ @notice Claims admin fees and sends it to fee_receiver set in the factory. @dev Functionally similar to: 1. Calculating admin's share of fees, 2. minting LP tokens, 3. admin claims underlying tokens via remove_liquidity. """ # --------------------- Check if fees can be claimed --------------------- # Disable fee claiming if: # 1. If time passed since last fee claim is less than # MIN_ADMIN_FEE_CLAIM_INTERVAL. # 2. Pool parameters are being ramped. last_claim_time: uint256 = self.last_admin_fee_claim_timestamp if ( unsafe_sub(block.timestamp, last_claim_time) < MIN_ADMIN_FEE_CLAIM_INTERVAL or self.future_A_gamma_time > block.timestamp ): return xcp_profit: uint256 = self.xcp_profit # <---------- Current pool profits. xcp_profit_a: uint256 = self.xcp_profit_a # <- Profits at previous claim. current_lp_token_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 current_lp_token_supply < 10**18: return # ---------- Conditions met to claim admin fees: compute state. ---------- A_gamma: uint256[2] = self._A_gamma() D: uint256 = self.D vprice: uint256 = self.virtual_price price_scale: uint256 = self.cached_price_scale fee_receiver: address = factory.fee_receiver() balances: uint256[N_COINS] = self.balances # 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. # This is the admin fee tokens claimed in self.add_liquidity. We add it to # the LP token share that the admin needs to claim: admin_share: uint256 = self.admin_lp_virtual_balance frac: uint256 = 0 if fee_receiver != empty(address) and fees > 0: # -------------------------------- Calculate admin share to be minted. frac = vprice * 10**18 / (vprice - fees) - 10**18 admin_share += current_lp_token_supply * frac / 10**18 # ------ Subtract fees from profits that will be used for rebalancing. xcp_profit -= fees * 2 # ------------------- Recalculate virtual_price following admin fee claim. total_supply_including_admin_share: uint256 = ( current_lp_token_supply + admin_share ) vprice = ( 10**18 * self.get_xcp(D, price_scale) / total_supply_including_admin_share ) # Do not claim fees if doing so causes virtual price to drop below 10**18. if vprice < 10**18: return # ---------------------------- Update State ------------------------------ # Set admin virtual LP balances to zero because we claimed: self.admin_lp_virtual_balance = 0 self.xcp_profit = xcp_profit self.last_admin_fee_claim_timestamp = block.timestamp # Since we reduce balances: virtual price goes down self.virtual_price = vprice # Adjust D after admin seemingly removes liquidity self.D = D - unsafe_div(D * admin_share, total_supply_including_admin_share) if xcp_profit > xcp_profit_a: self.xcp_profit_a = xcp_profit # <-------- Cache last claimed profit. # --------------------------- Handle Transfers --------------------------- admin_tokens: uint256[N_COINS] = empty(uint256[N_COINS]) if admin_share > 0: for i in range(N_COINS): admin_tokens[i] = ( balances[i] * admin_share / total_supply_including_admin_share ) # _transfer_out tokens to admin and update self.balances. State # update to self.balances occurs before external contract calls: self._transfer_out(i, admin_tokens[i], fee_receiver) log ClaimAdminFee(fee_receiver, admin_tokens) ``` <a id="exchange_received"></a> ## `exchange_received` This new function **allows the exchange of tokens without actually transfering tokens in**, as the exchange is based on the change of the coins balances within the pool (see code below). Users of this method are dex aggregators, arbitrageurs, or other users who **do not wish to grant approvals to the contract**. They can instead send tokens directly to the contract and call **`exchange_received()`**. **▶Transfer logic when using \`exchange\_received()\`▼** ```vyper @internal def _transfer_in( _coin_idx: uint256, _dx: uint256, sender: address, expect_optimistic_transfer: bool, ) -> uint256: """ @notice Transfers `_coin` from `sender` to `self` and calls `callback_sig` if it is not empty. @params _coin_idx uint256 Index of the coin to transfer in. @params dx amount of `_coin` to transfer into the pool. @params sender address to transfer `_coin` from. @params expect_optimistic_transfer bool True if pool expects user to transfer. This is only enabled for exchange_received. @return The amount of tokens received. """ coin_balance: uint256 = ERC20(coins[_coin_idx]).balanceOf(self) if expect_optimistic_transfer: # Only enabled in exchange_received: # it expects the caller of exchange_received to have sent tokens to # the pool before calling this method. # If someone donates extra tokens to the contract: do not acknowledge. # We only want to know if there are dx amount of tokens. Anything extra, # we ignore. This is why we need to check if received_amounts (which # accounts for coin balances of the contract) is atleast dx. # If we checked for received_amounts == dx, an extra transfer without a # call to exchange_received will break the method. dx: uint256 = coin_balance - self.balances[_coin_idx] assert dx >= _dx # dev: user didn't give us coins # Adjust balances self.balances[_coin_idx] += dx return dx # ----------------------------------------------- ERC20 transferFrom flow. # EXTERNAL CALL assert ERC20(coins[_coin_idx]).transferFrom( sender, self, _dx, default_return_value=True ) dx: uint256 = ERC20(coins[_coin_idx]).balanceOf(self) - coin_balance self.balances[_coin_idx] += dx return dx ``` * * * info Lets say a user wants to swap \*\*`GOV-TOKEN&lt;&gt;USDC`\*\*through an aggregator. For simplicity we assume, \*\*`GOV-TOKEN&lt;&gt;USDT`\*\*exchange is done via a uniswap pool, \*\*`USDT&lt;&gt;USDC`\*\*via a Curve pool. 1. User gives approval the `AGGREGATOR`, which then transfers tokens into the aggregator contract 2. Aggregator exchanges `GOV-TOKEN` for `USDT` using Uniswap 3. Transfers the `USDT` directly
프로젝트로 돌아가기