Curve DAO 백서

Curve DAO

원문

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

from Uniswap into the Curve pool 4. Perform a swap on the Curve pool (`USDT&lt;&gt;USDC`) via \*\*`exchange_received`\*\*5. Transfer `USDC` to the user info This method saves aggregators one redundant ERC-20 transfer and eliminates the need to grant approval to a curve pool. Without this function, the aggregator would have to conduct an additional transaction, transferring USDT from the Uniswap pool to their aggregator contract after the exchange, and then sending it to the Curve pool for another exchange (USDT<>USDC). However, with this method in place, the aggregator can transfer the output tokens directly into the next pool and perform an exchange. --- # CurveTwocryptoOptimized Source: [https://docs.curve.finance/developer/amm/twocrypto-ng/pools/twocrypto](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/twocrypto) A Twocrypto-NG pool consists of **two non-pegged assets**. The LP token is an ERC-20 token integrated directly into the liquidity pool. `CurveTwocryptoOptimized.vy` The source code for the `CurveTwocryptoOptimized.vy` contract can be found on [GitHub](https://github.com/curvefi/twocrypto-ng/blob/main/contracts/main/Twocrypto.vy). The contract is written in [Vyper](https://vyperlang.org/) version `0.3.10`. This is a **blueprint contract** — individual pools are deployed via the [Factory](https://docs.curve.finance/developer/amm/factory/twocrypto-ng/overview.md). Pool and LP token share the same address. Full list of all deployments can be found [here](https://docs.curve.finance/developer/deployments.md). info The token has the regular ERC-20 methods, which will not be further documented. In Twocrypto-NG pools, price scaling and fee **parameters are bundled and stored as a single unsigned integer**. This consolidation reduces storage read and write operations, leading to more cost-efficient calls. **▶pack▼** This internal function packs two or three integers into a single uint256. ```vyper @pure @internal def _pack_2(p1: uint256, p2: uint256) -> uint256: return p1 | (p2 << 128) @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] ``` **▶unpack▼** This internal function unpacks a single uin256 into two or three integers. ```vyper @pure @internal def _unpack_2(packed: uint256) -> uint256[2]: return [packed & (2**128 - 1), packed >> 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, ] ``` *The AMM contract utilizes two internal functions to transfer coins in and out of the pool e.g. when exchanging tokens or adding/removing liquidity:* **Token transfer into the AMM:** **▶\`\_transfer\_in(\_coin\_idx: uint256, \_dx: uint256, sender: address, expect\_optimistic\_transfer: bool) -> uint256:\`▼** Internal function to transfer tokens into the AMM, called by `exchange`, `exchange_received` or `add_liquidity`. | Input | Type | Description | | --- | --- | --- | | `_coin_idx` | `int128` | Index 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. | \*\*`expect_optimistic_transfer`\*\*is only `True` when using the `exchange_received` function. ```vyper balances: public(uint256[N_COINS]) @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 ``` **Token transfer out of the AMM:** **▶\`\_transfer\_out(\_coin\_idx: int128, \_amount: uint256, receiver: address):\`▼** Internal function to transfer tokens out of the AMM, called by the `remove_liquidity`, `remove_liquidity_one`, `_claim_admin_fees`, and `_exchange` methods. | Input | Type | Description | | --- | --- | --- | | `_coin_idx` | `int128` | Index of the token to transfer out. | | `_amount` | `uint256` | Amount to transfer out. | | `receiver` | `address` | Address to send the tokens to. | ```vyper balances: public(uint256[N_COINS]) @internal def _transfer_out(_coin_idx: uint256, _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`, `_claim_admin_fees` and `_exchange` methods. @params _coin_idx uint256 Index of the token to transfer out @params _amount Amount of token to transfer out @params receiver Address to send the tokens to """ # Adjust balances before handling transfers: self.balances[_coin_idx] -= _amount # EXTERNAL CALL assert ERC20(coins[_coin_idx]).transfer( receiver, _amount, default_return_value=True ) ``` * * * <a id="exchange-methods"></a> ## Exchange Methods *The contract offers two different ways to exchange tokens:* - A regular `exchange` method. - A novel `exchange_received` method, which swaps tokens based on the *"internal balances"* of the pool. This method is of great use for aggregators, as it **does not require token approval**of the pool, which eliminates certain smart contract risks and *can* remove one redundant ERC-20 transfer. More [here](https://docs.curve.finance/developer/amm/stableswap-ng/overview.md#exchange_received). <a id="exchange"></a> ### `exchange` `TwoCrypto.exchange(i: uint256, j: uint256, 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`. Charged fee at current states is `Pool.fee()`. | Input | Type | Description | | --- | --- | --- | | `i` | `uint256` | Index value for the input coin. | | `j` | `uint256` | Index value for the output coin. | | `dx` | `uint256` | Amount of input coin being swapped in. | | `min_dy` | `uint256` | Minimum amount of output coin to receive. | | `receiver` | `address` | Address to send output coin to. Defaults to `msg.sender`. | Returns: amount of output coin `j` received (`uint256`). Emits: `TokenExchange` **<>Source code▼** ```vyper event TokenExchange: buyer: indexed(address) sold_id: uint256 tokens_sold: uint256 bought_id: uint256 tokens_bought: uint256 fee: uint256 packed_price_scale: uint256 @external @nonreentrant("lock") def exchange( i: uint256, j: uint256, dx: uint256, min_dy: uint256, receiver: address = msg.sender ) -> uint256: """ @notice Exchange using wrapped native token by default @param i Index value for the input coin @param j Index value for the output coin @param dx Amount of input coin being swapped in @param min_dy Minimum amount of output coin to receive @param receiver Address to send the output coin to. Default is msg.sender @return uint256 Amount of tokens at index j received by the `receiver """ # _transfer_in updates self.balances here: dx_received: uint256 = self._transfer_in( i, dx, msg.sender, False ) # No ERC20 token transfers occur here: out: uint256[3] = self._exchange( i, j, dx_received, min_dy, ) # _transfer_out updates self.balances here. Update to state occurs before # external calls: self._transfer_out(j, out[0], receiver) # log: log TokenExchange(msg.sender, i, dx_received, j, out[0], out[1], out[2]) return out[0] @internal def _exchange( i: uint256, j: uint256, dx_received: uint256, min_dy: uint256, ) -> uint256[3]: assert i != j # dev: coin index out of range assert dx_received > 0 # dev: do not exchange 0 coins A_gamma: uint256[2] = self._A_gamma() xp: uint256[N_COINS] = self.balances dy: uint256 = 0 y: uint256 = xp[j] x0: uint256 = xp[i] - dx_received # old xp[i] price_scale: uint256 = self.cached_price_scale xp = [ xp[0] * PRECISIONS[0], unsafe_div(xp[1] * price_scale * PRECISIONS[1], PRECISION) ] # ----------- Update invariant if A, gamma are undergoing ramps --------- t: uint256 = self.future_A_gamma_time if t > block.timestamp: x0 *= PRECISIONS[i] if i > 0: x0 = unsafe_div(x0 * price_scale, PRECISION) x1: uint256 = xp[i] # <------------------ Back up old value in xp ... xp[i] = x0 # | self.D = MATH.newton_D(A_gamma[0], A_gamma[1], xp, 0) # | xp[i] = x1 # <-------------------------------------- ... and restore. # ----------------------- Calculate dy and fees -------------------------- D: uint256 = self.D y_out: uint256[2] = MATH.get_y(A_gamma[0], A_gamma[1], xp, D, j) dy = xp[j] - y_out[0] xp[j] -= dy dy -= 1 if j > 0: dy = dy * PRECISION / price_scale dy /= PRECISIONS[j] fee: uint256 = unsafe_div(self._fee(xp) * dy, 10**10) dy -= fee # <--------------------- Subtract fee from the outgoing amount. assert dy >= min_dy, "Slippage" y -= dy y *= PRECISIONS[j] if j > 0: y = unsafe_div(y * price_scale, PRECISION) xp[j] = y # <------------------------------------------------- Update xp. # ------ Tweak price_scale with good initial guess for newton_D ---------- price_scale = self.tweak_price(A_gamma, xp, 0, y_out[1]) return [dy, fee, price_scale] ``` ```vyper @external @view def newton_D(ANN: uint256, gamma: uint256, x_unsorted: uint256[N_COINS], K0_prev: uint256 = 0) -> uint256: """ Finding the invariant using Newton method. ANN is higher by the factor A_MULTIPLIER ANN is already A * N**N """ # Safety checks assert ANN > MIN_A - 1 and ANN < MAX_A + 1 # dev: unsafe values A assert gamma > MIN_GAMMA - 1 and gamma < MAX_GAMMA + 1 # dev: unsafe values gamma # Initial value of invariant D is that for constant-product invariant x: uint256[N_COINS] = x_unsorted if x[0] < x[1]: x = [x_unsorted[1], x_unsorted[0]] assert x[0] > 10**9 - 1 and x[0] < 10**15 * 10**18 + 1 # dev: unsafe values x[0] assert unsafe_div(x[1] * 10**18, x[0]) > 10**14 - 1 # dev: unsafe values x[i] (input) S: uint256 = unsafe_add(x[0], x[1]) # can unsafe add here because we checked x[0] bounds D: uint256 = 0 if K0_prev == 0: D = N_COINS * isqrt(unsafe_mul(x[0], x[1])) else: # D = isqrt(x[0] * x[1] * 4 / K0_prev * 10**18) D = isqrt(unsafe_mul(unsafe_div(unsafe_mul(unsafe_mul(4, x[0]), x[1]), K0_prev), 10**18)) if S < D: D = S __g1k0: uint256 = gamma + 10**18 diff: uint256 = 0 for i in range(255): D_prev: uint256 = D assert D > 0 # Unsafe division by D and D_prev is now safe # K0: uint256 = 10**18 # for _x in x: # K0 = K0 * _x * N_COINS / D # collapsed for 2 coins K0: uint256 = unsafe_div(unsafe_div((10**18 * N_COINS**2) * x[0], D) * x[1], D) _g1k0: uint256 = __g1k0 if _g1k0 > K0: _g1k0 = unsafe_add(unsafe_sub(_g1k0, K0), 1) # > 0 else: _g1k0 = unsafe_add(unsafe_sub(K0, _g1k0), 1) # > 0 # D / (A * N**N) * _g1k0**2 / gamma**2 mul1: uint256 = unsafe_div(unsafe_div(unsafe_div(10**18 * D, gamma) * _g1k0, gamma) * _g1k0 * A_MULTIPLIER, ANN) # 2*N*K0 / _g1k0 mul2: uint256 = unsafe_div(((2 * 10**18) * N_COINS) * K0, _g1k0) # calculate neg_fprime. here K0 > 0 is being validated (safediv). neg_fprime: uint256 = (S + unsafe_div(S * mul2, 10**18)) + mul1 * N_COINS / K0 - unsafe_div(mul2 * D, 10**18) # D -= f / fprime; neg_fprime safediv being validated D_plus: uint256 = D * (neg_fprime + S) / neg_fprime D_minus: uint256 = unsafe_div(D * D, neg_fprime) if 10**18 > K0: D_minus += unsafe_div(unsafe_div(D * unsafe_div(mul1, neg_fprime), 10**18) * unsafe_sub(10**18, K0), K0) else: D_minus -= unsafe_div(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) 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) if diff * 10**14 < max(10**16, D): # Could reduce precision for gas efficiency here for _x in x: frac: uint256 = _x * 10**18 / D assert (frac >= 10**16 - 1) and (frac < 10**20 + 1) # dev: unsafe values x[i] return D raise "Did not converge" @external @pure def get_y( _ANN: uint256, _gamma: uint256, _x: uint256[N_COINS], _D: uint256, i: uint256 ) -> uint256[2]: # Safety checks assert _ANN > MIN_A - 1 and _ANN < MAX_A + 1 # dev: unsafe values A assert _gamma > MIN_GAMMA - 1 and _gamma < MAX_GAMMA + 1 # dev: unsafe values gamma assert _D > 10**17 - 1 and _D < 10**15 * 10**18 + 1 # dev: unsafe values D ANN: int256 = convert(_ANN, int256) gamma: int256 = convert(_gamma, int256) D: int256 = convert(_D, int256) x_j: int256 = convert(_x[1 - i], int256) gamma2: int256 = unsafe_mul(gamma, gamma) # savediv by x_j done here: y: int256 = D**2 / (x_j * N_COINS**2) # K0_i: int256 = (10**18 * N_COINS) * x_j / D K0_i: int256 = unsafe_div(10**18 * N_COINS * x_j, D) assert (K0_i > 10**16 * N_COINS - 1) and (K0_i < 10**20 * N_COINS + 1) # dev: unsafe values x[i] ann_gamma2: int256 = ANN * gamma2 # a = 10**36 / N_COINS**2 a: int256 = 10**32 # b = ANN*D*gamma2/4/10000/x_j/10**4 - 10**32*3 - 2*gamma*10**14 b: int256 = ( D*ann_gamma2/400000000/x_j - convert(unsafe_mul(10**32, 3), int256) - unsafe_mul(unsafe_mul(2, gamma), 10**14) ) # c = 10**32*3 + 4*gamma*10**14 + gamma2/10**4 + 4*ANN*gamma2*x_j/D/10000/4/10**4 - 4*ANN*gamma2/10000/4/10**4 c: int256 = ( unsafe_mul(10**32, convert(3, int256)) + unsafe_mul(unsafe_mul(4, gamma), 10**14) + unsafe_div(gamma2, 10**4) + unsafe_div(unsafe_div(unsafe_mul(4, ann_gamma2), 400000000) * x_j, D) - unsafe_div(unsafe_mul(4, ann_gamma2), 400000000) ) # d = -(10**18+gamma)**2 / 10**4 d: int256 = -unsafe_div(unsafe_add(10**18, gamma) **2, 10**4) # delta0: int256 = 3*a*c/b - b delta0: int256 = 3 * a * c / b - b # safediv by b # delta1: int256 = 9*a*c/b - 2*b - 27*a**2/b*d/b delta1: int256 = 3 * delta0 + b - 27*a**2/b*d/b divider: int256 = 1 threshold: int256 = min(min(abs(delta0), abs(delta1)), a) if threshold > 10**48: divider = 10**30 elif threshold > 10**46: divider = 10**28 elif threshold > 10**44: divider = 10**26 elif threshold > 10**42: divider = 10**24 elif threshold > 10**40: divider = 10**22 elif threshold > 10**38: divider = 10**20 elif threshold > 10**36: divider = 10**18 elif threshold > 10**34: divider = 10**16 elif threshold > 10**32: divider = 10**14 elif threshold > 10**30: divider = 10**12 elif threshold > 10**28: divider = 10**10 elif threshold > 10**26: divider = 10**8 elif threshold > 10**24: divider = 10**6 elif threshold > 10**20: divider = 10**2 a = unsafe_div(a, divider) b = unsafe_div(b, divider) c = unsafe_div(c, divider) d = unsafe_div(d, divider) # delta0 = 3*a*c/b - b: here we can do more unsafe ops now: delta0 = unsafe_div(unsafe_mul(unsafe_mul(3, a), c), b) - b # delta1 = 9*a*c/b - 2*b - 27*a**2/b*d/b delta1 = 3 * delta0 + b - unsafe_div(unsafe_mul(unsafe_div(unsafe_mul(27, a**2), b), d), b) # sqrt_arg: int256 = delta1**2 + 4*delta0**2/b*delta0 sqrt_arg: int256 = delta1**2 + unsafe_mul(unsafe_div(4*delta0**2, b), delta0) sqrt_val: int256 = 0 if sqrt_arg > 0: sqrt_val = convert(isqrt(convert(sqrt_arg, uint256)), int256) else: return [ self._newton_y(_ANN, _gamma, _x, _D, i), 0 ] b_cbrt: int256 = 0 if b > 0: b_cbrt = convert(self._cbrt(convert(b, uint256)), int256) else: b_cbrt = -convert(self._cbrt(convert(-b, uint256)), int256) second_cbrt: int256 = 0 if delta1 > 0: # second_cbrt = convert(self._cbrt(convert((delta1 + sqrt_val), uint256) / 2), int256) second_cbrt = convert(self._cbrt(convert(unsafe_add(delta1, sqrt_val), uint256) / 2), int256) else: # second_cbrt = -convert(self._cbrt(convert(unsafe_sub(sqrt_val, delta1), uint256) / 2), int256) second_cbrt = -convert(self._cbrt(unsafe_div(convert(unsafe_sub(sqrt_val, delta1), uint256), 2)), int256) # C1: int256 = b_cbrt**2/10**18*second_cbrt/10**18 C1: int256 = unsafe_div(unsafe_mul(unsafe_div(b_cbrt**2, 10**18), second_cbrt), 10**18) # root: int256 = (10**18*C1 - 10**18*b - 10**18*b*delta0/C1)/(3*a), keep 2 safe ops here. root: int256 = (unsafe_mul(10**18, C1) - unsafe_mul(10**18, b) - unsafe_mul(10**18, b)/C1*delta0)/unsafe_mul(3, a) # y_out: uint256[2] = [ # convert(D**2/x_j*root/4/10**18, uint256), # <--- y # convert(root, uint256) # <----------------------- K0Prev # ] y_out: uint256[2] = [convert(unsafe_div(unsafe_div(unsafe_mul(unsafe_div(D**2, x_j), root), 4), 10**18), uint256), convert(root, uint256)] frac: uint256 = unsafe_div(y_out[0] * 10**18, _D) assert (frac >= 10**16 - 1) and (frac < 10**20 + 1) # dev: unsafe value for y return y_out ``` **▶Example▼** ```shell >>> soon ``` <a id="exchange_received"></a> ### `exchange_received` `TwoCrypto.exchange_received(i: uint256, j: uint256, dx: uint256, min_dy: uint256, receiver: address = msg.sender) -> uint256:` warning The transfer of coins into the pool and then calling `exchange_received` is highly advised to be done in the same transaction. If not, other users or MEV bots may frontrun `exchange_received`, potentially stealing the coins. Function to exchange `dx` amount of coin `i` for coin `j` and receive a minimum amount of `min_dy`. This function requires a transfer of `dx` amount of coin `i` to the pool prior to calling this function, as this exchange is based on the change of token balances in the pool. The pool will not call `transferFrom` and will only check if a surplus of `coins[i]` is greater than or equal to `dx`. Charged fee at current states is `Pool.fee()`. | Input | Type | Description | | --- | --- | --- | | `i` | `uint256` | Index value for the input coin. | | `j` | `uint256` | Index value for the output coin. | | `dx` | `uint256` | Amount of input coin being swapped in. | | `min_dy` | `uint256` | Minimum amount of output coin to receive. | | `receiver` | `address` | Address to send output coin to. Defaults to `msg.sender`. | Returns: amount of output coin `j` received (`uint256`). Emits: `TokenExchange` **<>Source code▼** ```vyper event TokenExchange: buyer: indexed(address) sold_id: uint256 tokens_sold: uint256 bought_id: uint256 tokens_bought: uint256 fee: uint256 packed_price_scale: uint256 @external @nonreentrant('lock') def exchange_received( i: uint256, j: uint256, dx: uint256, min_dy: uint256, receiver:
프로젝트로 돌아가기