Curve DAO 백서

Curve DAO

원문

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

e is out of range else: new_out_fee = current_fee_params[1] if new_mid_fee > MAX_FEE: new_mid_fee = current_fee_params[0] assert new_mid_fee <= new_out_fee # dev: mid-fee is too high if new_fee_gamma < 10**18: assert new_fee_gamma > 0 # dev: fee_gamma out of range [1 .. 10**18] else: new_fee_gamma = current_fee_params[2] self.packed_fee_params = self._pack_3([new_mid_fee, new_out_fee, new_fee_gamma]) # ----------------- Set liquidity rebalancing parameters ----------------- new_allowed_extra_profit: uint256 = _new_allowed_extra_profit new_adjustment_step: uint256 = _new_adjustment_step new_ma_time: uint256 = _new_ma_time current_rebalancing_params: uint256[3] = self._unpack_3(self.packed_rebalancing_params) if new_allowed_extra_profit > 10**18: new_allowed_extra_profit = current_rebalancing_params[0] if new_adjustment_step > 10**18: new_adjustment_step = current_rebalancing_params[1] if new_ma_time < 872542: # <----- Calculated as: 7 * 24 * 60 * 60 / ln(2) assert new_ma_time > 86 # dev: MA time should be longer than 60/ln(2) else: new_ma_time = current_rebalancing_params[2] self.packed_rebalancing_params = self._pack_3( [new_allowed_extra_profit, new_adjustment_step, new_ma_time] ) # Set xcp oracle moving average window time: new_xcp_ma_time: uint256 = _new_xcp_ma_time if new_xcp_ma_time < 872542: assert new_xcp_ma_time > 86 # dev: xcp MA time should be longer than 60/ln(2) else: new_xcp_ma_time = self.xcp_ma_time self.xcp_ma_time = new_xcp_ma_time # ---------------------------------- LOG --------------------------------- log NewParameters( new_mid_fee, new_out_fee, new_fee_gamma, new_allowed_extra_profit, new_adjustment_step, new_ma_time, _new_xcp_ma_time, ) ``` **▶Example▼** ```shell >>> soon ``` <a id="contract-info-methods"></a> ## Contract Info Methods <a id="initial_a_gamma"></a> ### `initial_A_gamma` `TwoCrypto.initial_A_gamma -> uint256: view` Getter for the initial A/gamma. Returns: A/gamma (`uint256`). **<>Source code▼** ```vyper initial_A_gamma: public(uint256) ``` **▶Example▼** ```shell >>> soon ``` <a id="initial_a_gamma_time"></a> ### `initial_A_gamma_time` `TwoCrypto.initial_A_gamma_time -> uint256: view` Getter for the initial A/gamma time. Returns: A/gamma time (`uint256`). **<>Source code▼** ```vyper initial_A_gamma_time: public(uint256) ``` **▶Example▼** ```shell >>> soon ``` <a id="future_a_gamma"></a> ### `future_A_gamma` `TwoCrypto.future_A_gamma -> uint256: view` Getter for the future A/gamma. Returns: future A/gamma (`uint256`). **<>Source code▼** ```vyper future_A_gamma: public(uint256) ``` **▶Example▼** ```shell >>> soon ``` <a id="future_a_gamma_time"></a> ### `future_A_gamma_time` `TwoCrypto.future_A_gamma_time -> uint256: view` info This value is initially set to 0 (default) when the pool is first deployed. It only gets populated by `block.timestamp + future_time` in the `ramp_A_gamma` function when the ramping process is initiated. After ramping is finished (i.e., `self.future_A_gamma_time < block.timestamp`), the variable is left as is and not set to 0. Getter for the future A/gamma time. This is the timestamp when the ramping process is finished. Returns: future A/gamma time (`uint256`). **<>Source code▼** ```vyper future_A_gamma_time: public(uint256) # <------ Time when ramping is finished. # This value is 0 (default) when pool is first deployed, and only gets # populated by block.timestamp + future_time in `ramp_A_gamma` when the # ramping process is initiated. After ramping is finished # (i.e. self.future_A_gamma_time < block.timestamp), the variable is left # and not set to 0. ``` **▶Example▼** ```shell >>> soon ``` --- # Twocrypto-NG Oracles Source: [https://docs.curve.finance/developer/amm/twocrypto-ng/pools/oracles](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/oracles) <a id="price-oracle"></a> ## Price Oracle *Twocrypto-NG pools contain the following built-in oracles:* `price_oracle` * * * An exponential moving-average (EMA) price oracle with a periodicity determined by `ma_time`. It returns the price of the coin at index 1 with regard to the coin at index 0 in the pool. [→ Jump to section](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/oracles.md#price_oracle) `xcp_oracle` * * * An exponential moving-average (EMA) oracle value of the estimated TVL in the pool with a periodicity determined by `xcp_ma_time`. [→ Jump to section](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/oracles.md#xcp_oracle) Example: Price Oracle for CVG/ETH The [`CVG/ETH`](https://etherscan.io/address/0x004c167d27ada24305b76d80762997fa6eb8d9b2) pool consists of `CVG &lt;&gt; wETH`. Because `wETH` is `coin[0]`, the price of `CVG` is returned with regard to `wETH`. ```shell >>> price_oracle() = 74644221911389 0.000074644221911389 # price of CVG w.r.t wETH ``` *In order to get the reverse EMA (e.g. price of `wETH` with regard to `CVG`):* $\frac{10^{36}}{\text{price\_oracle()}} = 1.3396884e+22$ * * * *The AMM implementation uses several private variables to pack and store values, which are used for calculating the EMA oracles.* **<>Source code▼** ```vyper @internal @pure def _pack_3(x: uint256[3]) -> uint256: """ @notice Packs 3 integers with values <= 10**18 into a uint256 @param x The uint256[3] to pack @return uint256 Integer with packed values """ return (x[0] << 128) | (x[1] << 64) | x[2] @pure @internal def _pack_2(p1: uint256, p2: uint256) -> uint256: return p1 | (p2 << 128) @internal @pure def _unpack_3(_packed: uint256) -> uint256[3]: """ @notice Unpacks a uint256 into 3 integers (values must be <= 10**18) @param val The uint256 to unpack @return uint256[3] A list of length 3 with unpacked integers """ return [ (_packed >> 128) & 18446744073709551615, (_packed >> 64) & 18446744073709551615, _packed & 18446744073709551615, ] @pure @internal def _unpack_2(packed: uint256) -> uint256[2]: return [packed & (2**128 - 1), packed >> 128] ``` | Variable | Description | | --- | --- | | `block.timestamp` | Timestamp of the block. Since all transactions within a block share the same timestamp, EMA oracles can only be updated once per block. | | `last_prices_timestamp` | Timestamp when the EMA oracle was last updated. | | `ma_time` | Time window for the moving-average oracle. | | `last_prices` | Last stored spot price of the coin to calculate the price oracle for. | | `price_scale` | Price scale value of the coin to calculate the price oracle for. | | `price_oracle` | Price oracle value of the coin to calculate the price oracle for. | | `alpha` | Weighting multiplier that adjusts the impact of the latest spot value versus the previous EMA in the new EMA calculation. | <a id="price_oracle"></a> ### `price_oracle` `CurveTwocryptoOptimized.price_oracle() -> uint256: view` Oracle Manipulation Prevention The state price that goes into the EMA is capped with `2 x price_scale` to prevent oracle manipulation. Getter for the oracle price of the coin at `index 1` with regard to the coin at `index 0`. The price oracle is an exponential moving-average, with a periodicity determined by `ma_time`. The aggregated prices are cached state prices (dy/dx) calculated AFTER the latest trade. $\alpha = e^{\text{power}}$ $\text{power} = -\frac{(\text{block.timestamp} - \text{last\_prices\_timestamp}) \times 10^{18}}{\text{ma\_time}}$ $\text{EMA} = \frac{\min(\text{last\_prices}, 2 \times \text{price\_scale}) \times (10^{18} - \alpha) + \text{price\_oracle} \times \alpha}{10^{18}}$ Returns: ema oracle price of coin at index 1 w.r.t coin at index 0 (`uint256`). **<>Source code▼** ```vyper @external @view @nonreentrant("lock") def 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. @return uint256 Price oracle value of kth coin. """ return self.internal_price_oracle() @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.last_timestamp 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 ``` ```vyper @external @pure def wad_exp(x: int256) -> int256: """ @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. @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 <= -42_139_678_854_452_767_551): return empty(int256) # 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 < 135_305_999_368_893_231_589, "Math: 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, 54_916_777_467_707_473_351_141_471_128), 2 **95) >> 96 value = unsafe_sub(value, unsafe_mul(k, 54_916_777_467_707_473_351_141_471_128)) # 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, 1_346_386_616_545_796_478_920_950_773_328), value) >> 96, 57_155_421_227_552_351_082_224_309_758_442) p: int256 = unsafe_add(unsafe_mul(unsafe_add(unsafe_mul(unsafe_sub(unsafe_add(y, value), 94_201_549_194_550_492_254_356_042_504_812), y) >> 96,\ 28_719_021_644_029_726_153_956_944_680_412_240), value), 4_385_272_521_454_847_904_659_076_985_693_276 << 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, 2_855_989_394_907_223_263_936_484_059_900), value) >> 96, 50_020_603_652_535_783_019_961_831_881_945) q = unsafe_sub(unsafe_mul(q, value) >> 96, 533_845_033_583_426_703_283_633_433_725_380) q = unsafe_add(unsafe_mul(q, value) >> 96, 3_604_857_256_930_695_427_073_651_918_091_429) q = unsafe_sub(unsafe_mul(q, value) >> 96, 14_423_608_567_350_463_180_887_372_962_807_573) q = unsafe_add(unsafe_mul(q, value) >> 96, 26_449_188_498_355_588_339_934_803_723_976_023) # 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 convert(unsafe_mul(convert(convert(r, bytes32), uint256), 3_822_833_074_963_236_453_042_738_258_902_158_003_155_416_615_667) >>\ convert(unsafe_sub(195, k), uint256), int256) ``` **▶Example▼** ```shell >>> CurveTwocryptoOptimized.price_oracle() 176068711374120 # CVG/ETH price ``` <a id="xcp_oracle"></a> ### `xcp_oracle` `CurveTwocryptoOptimized.xcp_oracle() -> uint256: view` Getter for the oracle value for xcp. The oracle is an exponential moving-average, with a periodicity determined by `xcp_ma_time`. $\alpha = e^{\text{power}}$ $\text{power} = -\frac{(\text{block.timestamp} - \text{last\_prices\_timestamp}) \times 10^{18}}{\text{xcp\_ma\_time}}$ $\text{xcp\_oracle} = \frac{\text{last\_xcp} \times (10^{18} - \alpha) + \text{cached\_xcp\_oracle} \times \alpha}{10^{18}}$ Returns: xcp ema oracle value (`uint256`). **<>Source code▼** ```vyper cached_xcp_oracle: uint256 # <----------- EMA of totalSupply * virtual_price. @external @view @nonreentrant("lock") def xcp_oracle() -> uint256: """ @notice Returns the oracle value for xcp. @dev The oracle is an exponential moving average, with a periodicity determined by `self.xcp_ma_time`. `TVL` is xcp, calculated as either: 1. virtual_price * total_supply, OR 2. self.get_xcp(...), OR 3. MATH.geometric_mean(xp) @return uint256 Oracle value of xcp. """ last_prices_timestamp: uint256 = self._unpack_2(self.last_timestamp)[1] cached_xcp_oracle: uint256 = self.cached_xcp_oracle if last_prices_timestamp < block.timestamp: alpha: uint256 = MATH.wad_exp( -convert( unsafe_div( unsafe_sub(block.timestamp, last_prices_timestamp) * 10**18, self.xcp_ma_time ), int256, ) ) return (self.last_xcp * (10**18 - alpha) + cached_xcp_oracle * alpha) / 10**18 return cached_xcp_oracle ``` **▶Example▼** ```shell In [1]: CurveTwocryptoOptimized.xcp_oracle() Out [1]: 3501656271269889041418 ``` * * * <a id="updating-oracles"></a> ## Updating Oracles The AMM has an internal `tweak_price` function that updates `price_oracle`, `xcp_oracle`, and `last_prices`, and conditionally adjusts `price_scale` based on the new invariant and xcp profit. The function includes logic to adjust the `price_scale` if certain conditions are met, such as sufficient profits being made within the pool. This mechanism ensures the pool remains balanced. The function is called whenever `add_liquidity`, `remove_liquidity_one_coin`, or `_exchange` is called. It is not called when removing liquidity in a balanced manner via `remove_liquidity`, as this function does not alter prices. However, the xCP oracle is updated nonetheless. To prevent oracle manipulation, `price_oracle` and `xcp_oracle` are only **updated once per block**. **<>Source code▼** *The function takes the following inputs:* | Input | Type | Description | | --- | --- | --- | | `A_gamma` | `uint256[2]` | Array of `A` and `gamma` values. | | `_xp` | `uint256[N_COINS]` | Array of the current coin balances. | | `new_D` | `uint256` | New `D` value. | | `K0_preb` | `uint256` | Initial guess for `newton_D`. | ```vyper @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`. """ # ---------------------------- Read storage ------------------------------ price_oracle: uint256 = self.cached_price_oracle last_prices: uint256 = self.last_prices price_scale: uint256 = self.cached_price_scale rebalancing_params: uint256[3] = self._unpack_3(self.packed_rebalancing_params) # Contains: allowed_extra_profit, adjustment_step, ma_time. -----^ total_supply: uint256 = self.totalSupply old_xcp_profit: uint256 = self.xcp_profit old_virtual_price: uint256 = self.virtual_price # ----------------------- Update Oracles if needed ----------------------- last_timestamp: uint256[2] = self._unpack_2(self.last_timestamp) alpha: uint256 = 0 if last_timestamp[0] < block.timestamp: # 0th index is for price_oracle. # 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 = MATH.wad_exp( -convert( unsafe_div( unsafe_sub(block.timestamp, last_timestamp[0]) * 10**18, rebalancing_params[2] # <----------------------- ma_time. ), int256, ) ) # ---------------------------------------------- Update price oracles. # ----------------- We cap state price that goes into the EMA with # 2 x price_scale. price_oracle = unsafe_div( min(last_prices, 2 * price_scale) * (10**18 - alpha) + price_oracle * alpha, # ^-------- Cap spot price into EMA. 10**18 ) self.cached_price_oracle = price_oracle last_timestamp[0] = block.timestamp # ----------------------------------------------------- Update xcp oracle. if last_timestamp[1] < block.timestamp: cached_xcp_oracle: uint256 = self.cached_xcp_oracle alpha = MATH.wad_exp( -convert( unsafe_div( unsafe_sub(block.timestamp, last_timestamp[1]) * 10**18, self.xcp_ma_time # <---------- xcp ma time has is longer. ), int256, ) ) self.cached_xcp_oracle = unsafe_div( self.last_xcp * (10**18 - alpha) + cached_xcp_oracle * alpha, 10**18 ) # Pack and store timestamps: last_timestamp[1] = block.timestamp self.last_timestamp = self._pack_2(last_timestamp[0], last_timestamp[1]) # `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 -------------------------- self.last_prices = unsafe_div( MATH.get_p(_xp, D_unadjusted, A_gamma) * price_scale, 10**18 ) # ---------- Update profit numbers without price adjustment first -------- xp: uint256[N_COINS] = [ unsafe_div(D_unadjusted, N_COINS), D_unadjusted * PRECISION / (N_COINS * price_scale) # <------ safediv. ] # with price_scale. xcp_profit: uint256 = 10**18 virtual_price: uint256 = 10**18 if old_virtual_price > 0: xcp: uint256 = isqrt(xp[0] * xp[1]) virtual_price = 10**18 * xcp / total_supply xcp_profit = unsafe_div( old_xcp_profit * virtual_price, old_virtual_price ) # <---------------- Safu to do unsafe_div a
프로젝트로 돌아가기