Curve DAO 백서

Curve DAO

원문

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

cking values The value needs to be unpacked, as it contains two values, **ma\_last\_time\_p** and **ma\_last\_time\_D**. For example, 579359617954437487117250992339883299967854142015 is unpacked into two uint256 numbers. First, its lower 128 bits are isolated using a bitwise AND with 2\*\*128 − 1, and then the value is shifted right by 128 bits to extract the upper 128 bits. It returns: \[1702584895, 1702584895\], meaning both moving-average oracles were updated at the same time. ::: * * * <a id="updating-oracles"></a> ## Updating Oracles The internal `upkeep_oracles` method is responsible for updating the price and D oracle. info Both EMA values, `ema_price` and `ma_D`, are updated maximally once per block. If there are two or more actions within the same block that would update the oracles, only the first action will update these values. The spot price (`last_price` or `last_D`) will always update. The rationale behind this approach is that all transactions within a block share the same timestamp. Therefore, the condition `if ma_last_time < block.timestamp` can only be satisfied once per block (the first time it's called). If there are multiple actions that would trigger an oracle update, it will be updated in the next relevant action. **▶Source code for the internal \*\*\`upkeep\_oracle\`\*\*function▼** ```vyper @internal def upkeep_oracles(xp: DynArray[uint256, MAX_COINS], amp: uint256, D: uint256): """ @notice Upkeeps price and D oracles. """ ma_last_time_unpacked: uint256[2] = self.unpack_2(self.ma_last_time) last_prices_packed_current: DynArray[uint256, MAX_COINS] = self.last_prices_packed last_prices_packed_new: DynArray[uint256, MAX_COINS] = last_prices_packed_current spot_price: DynArray[uint256, MAX_COINS] = self._get_p(xp, amp, D) # -------------------------- Upkeep price oracle ------------------------- for i in range(MAX_COINS): if i == N_COINS - 1: break if spot_price[i] != 0: # Update packed prices ----------------- last_prices_packed_new[i] = self.pack_2( min(spot_price[i], 2 * 10**18), # <----- Cap spot value by 2. self._calc_moving_average( last_prices_packed_current[i], self.ma_exp_time, ma_last_time_unpacked[0], # index 0 is ma_last_time for prices ) ) self.last_prices_packed = last_prices_packed_new # ---------------------------- Upkeep D oracle --------------------------- last_D_packed_current: uint256 = self.last_D_packed self.last_D_packed = self.pack_2( D, self._calc_moving_average( last_D_packed_current, self.D_ma_time, ma_last_time_unpacked[1], # index 1 is ma_last_time for D ) ) # Housekeeping: Update ma_last_time for p and D oracles ------------------ for i in range(2): if ma_last_time_unpacked[i] < block.timestamp: ma_last_time_unpacked[i] = block.timestamp self.ma_last_time = self.pack_2(ma_last_time_unpacked[0], ma_last_time_unpacked[1]) ``` * * * <a id="price-oracles"></a> ### Price Oracles The price oracle is updated when the `upkeep_oracles` method is called. This occurs in response to one of the following actions: - Token exchange (`__exchange`) - Liquidity addition (`add_liquidity`) - Single-sided liquidity (`remove_liquidity_one_coin`) - Liquidity removal in an imbalanced proportion (`remove_liquidity_imbalance`) *When price oracles are upkept, the code calculates both the spot price and the moving-average price. These values are then packed and stored together in `last_prices_packed`.* ```vyper # -------------------------- Upkeep price oracle ------------------------- for i in range(MAX_COINS): if i == N_COINS - 1: break if spot_price[i] != 0: # Update packed prices ----------------- last_prices_packed_new[i] = self.pack_2( min(spot_price[i], 2 * 10**18), # <----- Cap spot value by 2. self._calc_moving_average( last_prices_packed_current[i], self.ma_exp_time, ma_last_time_unpacked[0], # index 0 is ma_last_time for prices ) ) self.last_prices_packed = last_prices_packed_new ``` 1. `last_price` which represents the last stored spot price within the AMM is calculated using `_get_p`. Additionally, the value is capped at `2 * 10**18` to prevent price oracle manipulation. Note: It's not actually the spot price which is capped, but rather the spot price that is used in the calculation for the EMA price oracle. **▶\`\_get\_p\`▼** ```vyper @internal @pure def _get_p( xp: DynArray[uint256, MAX_COINS], amp: uint256, D: uint256, ) -> DynArray[uint256, MAX_COINS]: # dx_0 / dx_1 only, however can have any number of coins in pool ANN: uint256 = unsafe_mul(amp, N_COINS) Dr: uint256 = unsafe_div(D, pow_mod256(N_COINS, N_COINS)) for i in range(N_COINS_128, bound=MAX_COINS_128): Dr = Dr * D / xp[i] p: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) xp0_A: uint256 = unsafe_div(ANN * xp[0], A_PRECISION) for i in range(1, MAX_COINS): if i == N_COINS: break p.append(10**18 * (xp0_A + unsafe_div(Dr * xp[0], xp[i])) / (xp0_A + Dr)) return p ``` 2. The moving-average price (`ema_price`) is calculated using `_calc_moving_average`. This value can only be updated once per block. If there are two actions which would update the value, only the first action will update it. For the second action, only the `last_price` is updated, while `ema_price` will not be updated and have the same value as in the first action. **▶\`\_calc\_moving\_average\`▼** ```vyper @internal @view def _calc_moving_average( packed_value: uint256, averaging_window: uint256, ma_last_time: uint256 ) -> uint256: last_spot_value: uint256 = packed_value & (2**128 - 1) last_ema_value: uint256 = (packed_value >> 128) if ma_last_time < block.timestamp: # calculate new_ema_value and return that. alpha: uint256 = self.exp( -convert( unsafe_div(unsafe_mul(unsafe_sub(block.timestamp, ma_last_time), 10**18), averaging_window), int256 ) ) return unsafe_div(last_spot_value * (10**18 - alpha) + last_ema_value * alpha, 10**18) return last_ema_value ``` * * * <a id="d-oracle"></a> ### D Oracle The D oracle is updated when the `upkeep_oracles` method is called. This occurs in response to one of the following actions: - Token exchange (`__exchange`) - Liquidity addition (`add_liquidity`) - Single-sided liquidity (`remove_liquidity_one_coin`) - Liquidity removal in an imbalanced proportion (`remove_liquidity_imbalance`) - Balanced proportion liquidity removal. For this action, the `remove_liquidity` function, which executes it, does not directly call the `upkeep_oracles` method. Instead, the D oracle update is performed "manually" within the function. The rationale behind this approach is that updating the price oracle is not necessary in this scenario, because removing in a balanced proportion does not change the prices within the AMM. *When the D oracle is updated, the code calculates both the "spot" D invariant and the moving-average D invariant value. These values are then packed and stored together in `last_D_packed`.* ```vyper # ---------------------------- Upkeep D oracle --------------------------- last_D_packed_current: uint256 = self.last_D_packed self.last_D_packed = self.pack_2( D, self._calc_moving_average( last_D_packed_current, self.D_ma_time, ma_last_time_unpacked[1], # index 1 is ma_last_time for D ) ) ``` --- # plainpool Source: [https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool) Plain pools are liquidity **exchange contracts which contain at least 2 and up to 8 coins.** Contract Source & Deployment Source code available on [Github](https://github.com/curvefi/stableswap-ng/blob/bff1522b30819b7b240af17ccfb72b0effbf6c47/contracts/main/CurveStableSwapNG.vy). The deployment of plain pools is permissionless and can be done via the [**`deploy_plain_pool`**](https://docs.curve.finance/developer/amm/factory/stableswap-ng/deployer-api.md#deploy_plain_pool) function within the Stableswap-NG Factory. Examples The examples following each code block of the corresponding functions provide a basic illustration of input/output values. **When using the function in production, ensure not to set `_min_dy`, `_min_amount`, etc., to zero or other arbitrary numbers**. Otherwise, MEV bots may frontrun or sandwich your transaction, leading to a potential loss of funds. **Oracle Methods Documentation** Comprehensive documentation for Oracle Methods is available on a dedicated page, accessible [here](https://docs.curve.finance/developer/amm/stableswap-ng/pools/oracles.md). * * * *The AMM contract utilizes two internal functions to transfer tokens/coins in and out of the pool and then accordingly update `stored_balances`:* - **`_transfer_in()`** **▶\`\_transfer\_in(coin\_idx: int128, dx: uint256, sender: address, expect\_optimistic\_transfer: bool) -> uint256:\`▼** `expect_optimistic_transfer` is relevant when using the [`exchange_received()`](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool.md#exchange_received) function. | Input | Type | Description | | --- | --- | --- | | `coin_idx` | `int128` | Index value of the token to transfer in. | | `dx` | `uint256` | Amount to transfer in. | | `sender` | `address` | Address to transfer coins from. | | `expect_optimistic_transfer` | `bool` | `True` if the contract expects an optimistic coin transfer. | ```vyper stored_balances: DynArray[uint256, MAX_COINS] @internal def _transfer_in( coin_idx: int128, dx: uint256, sender: address, expect_optimistic_transfer: bool, ) -> uint256: """ @notice Contains all logic to handle ERC20 token transfers. @param coin_idx Index of the coin to transfer in. @param dx amount of `_coin` to transfer into the pool. @param dy amount of `_coin` to transfer out of the pool. @param sender address to transfer `_coin` from. @param receiver address to transfer `_coin` to. @param expect_optimistic_transfer True if contract expects an optimistic coin transfer """ _dx: uint256 = ERC20(coins[coin_idx]).balanceOf(self) # ------------------------- Handle Transfers ----------------------------- if expect_optimistic_transfer: _dx = _dx - self.stored_balances[coin_idx] assert _dx >= dx else: assert dx > 0 # dev : do not transferFrom 0 tokens into the pool assert ERC20(coins[coin_idx]).transferFrom( sender, self, dx, default_return_value=True ) _dx = ERC20(coins[coin_idx]).balanceOf(self) - _dx # --------------------------- Store transferred in amount --------------------------- self.stored_balances[coin_idx] += _dx return _dx ``` - **`_transfer_out()`** **▶\`\_transfer\_out(\_coin\_idx: int128, \_amount: uint256, receiver: address):\`▼** | Input | Type | Description | | --- | --- | --- | | `coin_idx` | `int128` | Index value of the token to transfer out. | | `_amount` | `uint256` | Amount to transfer out. | | `receiver` | `address` | Address to send the tokens to. | ```vyper stored_balances: DynArray[uint256, MAX_COINS] @internal def _transfer_out(_coin_idx: int128, _amount: uint256, receiver: address): """ @notice Transfer a single token from the pool to receiver. @dev This function is called by `remove_liquidity` and `remove_liquidity_one`, `_exchange` and `_withdraw_admin_fees` methods. @param _coin_idx Index of the token to transfer out @param _amount Amount of token to transfer out @param receiver Address to send the tokens to """ # 'gulp' coin balance of the pool to stored_balances here to account for # donations etc. coin_balance: uint256 = ERC20(coins[_coin_idx]).balanceOf(self) # ------------------------- Handle Transfers ----------------------------- assert ERC20(coins[_coin_idx]).transfer( receiver, _amount, default_return_value=True ) # ----------------------- Update Stored Balances ------------------------- self.stored_balances[_coin_idx] = coin_balance - _amount ``` * * * <a id="exchange-methods"></a> ## Exchange Methods *Two functions for token exchanges:* - The regular `exchange` function. - A novel `exchange_received` function that executes a token exchange based on the internal balances of the pool. There is no `exchange_underlying` function, as this implementation is for plain pools and not for metapools, meaning no tokens are paired against other LP tokens. <a id="exchange"></a> ### `exchange` `StableSwap.exchange(i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address = msg.sender) -> uint256:` Function to exchange `_dx` amount of coin `i` for coin `j` and receive a minimum amount of `_min_dy`. Returns: amount of output coin received (`uint256`). Emits: `TokenExchange` | Input | Type | Description | | --- | --- | --- | | `i` | `int128` | Index value of input coin. | | `j` | `int128` | Index value of output coin. | | `_dx` | `uint256` | Amount of coin `i` being exchanged. | | `_min_dy` | `uint256` | Minimum amount of coin `j` to receive. | | `_receiver` | `address` | Receiver of the output tokens; defaults to `msg.sender`. | **<>Source code▼** ```vyper event TokenExchange: buyer: indexed(address) sold_id: int128 tokens_sold: uint256 bought_id: int128 tokens_bought: uint256 @external @nonreentrant('lock') def exchange( i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address = msg.sender, ) -> uint256: """ @notice Perform an exchange between two coins @dev Index values can be found via the `coins` public getter method @param i Index value for the coin to send @param j Index value of the coin to recieve @param _dx Amount of `i` being exchanged @param _min_dy Minimum amount of `j` to receive @return Actual amount of `j` received """ return self._exchange( msg.sender, i, j, _dx, _min_dy, _receiver, False ) @internal def _exchange( sender: address, i: int128, j: int128, _dx: uint256, _min_dy: uint256, receiver: address, expect_optimistic_transfer: bool ) -> uint256: assert i != j # dev: coin index out of range assert _dx > 0 # dev: do not exchange 0 coins rates: DynArray[uint256, MAX_COINS] = self._stored_rates() old_balances: DynArray[uint256, MAX_COINS] = self._balances() xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances) # --------------------------- Do Transfer in ----------------------------- # `dx` is whatever the pool received after ERC20 transfer: dx: uint256 = self._transfer_in( i, _dx, sender, expect_optimistic_transfer ) # ------------------------------- Exchange ------------------------------- x: uint256 = xp[i] + dx * rates[i] / PRECISION dy: uint256 = self.__exchange(x, xp, rates, i, j) assert dy >= _min_dy, "Exchange resulted in fewer coins than expected" # --------------------------- Do Transfer out ---------------------------- self._transfer_out(j, dy, receiver) # ------------------------------------------------------------------------ log TokenExchange(msg.sender, i, _dx, j, dy) return dy def __exchange( x: uint256, _xp: DynArray[uint256, MAX_COINS], rates: DynArray[uint256, MAX_COINS], i: int128, j: int128, ) -> uint256: amp: uint256 = self._A() D: uint256 = self.get_D(_xp, amp) y: uint256 = self.get_y(i, j, x, _xp, amp, D) dy: uint256 = _xp[j] - y - 1 # -1 just in case there were some rounding errors dy_fee: uint256 = dy * self._dynamic_fee((_xp[i] + x) / 2, (_xp[j] + y) / 2, self.fee) / FEE_DENOMINATOR # Convert all to real units dy = (dy - dy_fee) * PRECISION / rates[j] self.admin_balances[j] += ( dy_fee * admin_fee / FEE_DENOMINATOR ) * PRECISION / rates[j] # Calculate and store state prices: xp: DynArray[uint256, MAX_COINS] = _xp xp[i] = x xp[j] = y # D is not changed because we did not apply a fee self.upkeep_oracles(xp, amp, D) return dy ``` **▶Example▼** ```shell >>> expected_dy = pool.get_dy(0, 1, 10**18) * 0.99 >>> StableSwap.exchange(0, 1, 10**18, expected_dy) 999712 ``` note This function exchanges one crvUSD for 0.999712 amount of USDV. `expected_dy` calculates the predicted input amount `j` to receive `dy` of coin `i`. This value can then be used as `_min_dy` in the `exchange` function. <a id="exchange_received"></a> ### `exchange_received` `StableSwap.exchange_received(i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address) -> uint256:` danger `exchange_received` will revert if the pool contains a rebasing asset. A pool that contains a rebasing token should have an `asset_type` of 2. If this is not the case, the pool is using an incorrect implementation, and rebases can be stolen. Function to exchange `_dx` amount of coin `i` for coin `j`, receiving a minimum amount of `_min_dy`. This is done without actually transferring the coins into the pool within the same call. The exchange is based on the change in the balance of coin `i`, eliminating the need to grant approval to the contract. \*\*A detailed article can be found here: [https://blog.curvemonitor.com/posts/exchange-received/.\*\*Returns](https://blog.curvemonitor.com/posts/exchange-received/.**Returns): amount of output coin received (`uint256`). Emits: `TokenExchange` | Input | Type | Description | | --- | --- | --- | | `i` | `int128` | Index value of input coin. | | `j` | `int128` | Index value of output coin. | | `_dx` | `uint256` | Amount of coin `i` being exchanged. | | `_min_dy` | `uint256` | Minimum amount of coin `j` to receive. | | `_receiver` | `address` | Receiver of the output tokens. | **<>Source code▼** ```vyper event TokenExchange: buyer: indexed(address) sold_id: int128 tokens_sold: uint256 bought_id: int128 tokens_bought: uint256 stored_balances: DynArray[uint256, MAX_COINS] @external @nonreentrant('lock') def exchange_received( i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address, ) -> uint256: """ @notice Perform an exchange between two coins without transferring token in @dev The contract swaps tokens based on a change in balance of coin[i]. The dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of this method are dex aggregators, arbitrageurs, or other users who do not wish to grant approvals to the contract: they would instead send tokens directly to the contract and call `exchange_received`. Note: This is disabled if pool contains rebasing tokens. @param i Index value for the coin to send @param j Index valie of the coin to recieve @param _dx Amount of `i` being exchanged @param _min_dy Minimum amount of `j` to receive @return Actual amount of `j` received """ assert not POOL_IS_REBASING_IMPLEMENTATION # dev: exchange_received not supported if pool contains rebasing tokens return self._exchange( msg.sender, i, j, _dx, _min_dy, _receiver, True, # <--------------------------------------- swap optimistically. ) @internal def _exchange( sender: address, i: int128, j: int128, _dx: uint256, _min_dy: uint256, receiver: address, expect_optimistic_transfer: bool ) -> uint256: assert i != j # dev: coin index out of range assert _dx > 0 # dev: do not exchange 0 coins rates: DynArray[uint256, MAX_COINS] = self._stored_rates() old_balances: DynArray[uint256, MAX_COINS] = self._balances() xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances) # --------------------------- Do Transfer in ----------------------------- # `dx` is whatever the pool received after ERC20 transfer: dx: uint256 = self._transfer_in( i, _dx, sender, expect_optimistic_transfer ) # ------------------------------- Exchange ------------------------------- x: uint256 = xp[i] + dx * rates[i] / PRECISION dy: uint256 = self.__exchange(x, xp, rates, i, j) assert dy >= _min_dy, "Exchange resulted in fewer coins than expected" # --------------------------- Do Transfer out ---------------------------- self._transfer_out(j, dy, receiver) # ------------------------------------------------------------------------ log TokenExchange(msg.sender, i, _dx, j, dy) return dy def __exchange( x: uint256, _xp: DynArray[uint256, MAX_COINS], rates: DynArray[uint256, MAX_COI
프로젝트로 돌아가기