Curve DAO 백서

Curve DAO

원문

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

: uint256 = 0 if amounts[0] == 0: S = xx[0] * precisions[0] precision = precisions[1] ix = 1 else: S = xx[1] * precisions[1] precision = precisions[0] S = S * d_token / token_supply p = S * PRECISION / (amounts[ix] * precision - d_token * xx[ix] * precision / token_supply) if ix == 0: p = (10**18)**2 / p self.tweak_price(A_gamma, xp, p, D) else: self.D = D self.virtual_price = 10**18 self.xcp_profit = 10**18 CurveToken(lp_token).mint(receiver, d_token) assert d_token >= min_mint_amount, "Slippage" log AddLiquidity(receiver, amounts, d_token_fee, token_supply) return d_token ``` **▶Example▼** ```shell >>> CryptoSwap.add_liquidity(todo) ``` <a id="calc_token_amount"></a> ### `calc_token_amount` `CryptoSwap.calc_token_amount(amounts: uint256[N_COINS]) -> uint256:` Function to calculate the amount of tokens to deposit/withdraw to get `amounts`. Returns amount of LP tokens (`uint256`). | Input | Type | Description | | --- | --- | --- | | `_amount` | `uint256[N_COINS]` | amount of coins to withdraw/deposit | **<>Source code▼** ```vyper @view @external def calc_token_amount(amounts: uint256[N_COINS]) -> uint256: token_supply: uint256 = CurveToken(self.token).totalSupply() precisions: uint256[2] = self._get_precisions() price_scale: uint256 = self.price_scale * precisions[1] A_gamma: uint256[2] = self._A_gamma() xp: uint256[N_COINS] = self.xp() amountsp: uint256[N_COINS] = [ amounts[0] * precisions[0], amounts[1] * price_scale / PRECISION] D0: uint256 = self.D if self.future_A_gamma_time > 0: D0 = self.newton_D(A_gamma[0], A_gamma[1], xp) xp[0] += amountsp[0] xp[1] += amountsp[1] D: uint256 = self.newton_D(A_gamma[0], A_gamma[1], xp) d_token: uint256 = token_supply * D / D0 - token_supply d_token -= self._calc_token_fee(amountsp, xp) * d_token / 10**10 + 1 return d_token ``` **▶Example▼** ```shell >>> CryptoSwap.calc_token_amount(todo) ``` <a id="remove_liquidity"></a> ### `remove_liquidity` `CryptoSwap.remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS], use_eth: bool = False, receiver: address = msg.sender):` Function to remove liquidity from the pool and burn the lp tokens. When removing liquidity via this function, no fees are charged as the coins are withdrawin in balanced proportions. Emits: `RemoveLiquidity` | Input | Type | Description | | --- | --- | --- | | `_amount` | `uint256[N_COINS]` | amount of lp tokens to burn | | `min_amounts` | `uint256[N_COINS]` | minimum amounts of token to withdraw | | `use_eth` | `bool` | True = withdraw ETH, False = withdraw wETH | | `receiver` | `address` | receiver of the coins; defaults to msg.sender | **<>Source code▼** ```vyper event RemoveLiquidity: provider: indexed(address) token_amounts: uint256[N_COINS] token_supply: uint256 N_COINS: constant(int128) = 2 @external @nonreentrant('lock') def remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS], use_eth: bool = False, receiver: address = msg.sender): """ This withdrawal method is very safe, does no complex math """ lp_token: address = self.token total_supply: uint256 = CurveToken(lp_token).totalSupply() CurveToken(lp_token).burnFrom(msg.sender, _amount) balances: uint256[N_COINS] = self.balances amount: uint256 = _amount - 1 # Make rounding errors favoring other LPs a tiny bit for i in range(N_COINS): d_balance: uint256 = balances[i] * amount / total_supply assert d_balance >= min_amounts[i] self.balances[i] = balances[i] - d_balance balances[i] = d_balance # now it's the amounts going out coin: address = self.coins[i] if use_eth and coin == WETH20: raw_call(receiver, b"", value=d_balance) else: if coin == WETH20: WETH(WETH20).deposit(value=d_balance) response: Bytes[32] = raw_call( coin, _abi_encode(receiver, d_balance, method_id=method_id("transfer(address,uint256)")), max_outsize=32, ) if len(response) != 0: assert convert(response, bool) D: uint256 = self.D self.D = D - D * amount / total_supply log RemoveLiquidity(msg.sender, balances, total_supply - _amount) ``` **▶Example▼** ```shell >>> CryptoSwap.remove_liquidity(todo) ``` <a id="remove_liquidity_one_coin"></a> ### `remove_liquidity_one_coin` `CryptoSwap.remove_liquidity_one_coin(token_amount: uint256, i: uint256, min_amount: uint256, use_eth: bool = False, receiver: address = msg.sender) -> uint256:` Funtion to withdraw liquidity in a single token. Returns: amount of withdrawn coin (`uint256`). Emits: `RemoveLiquidityOne` | Input | Type | Description | | --- | --- | --- | | `token_amount` | `uint256` | amount of lp tokens to burn | | `i` | `uint256` | index of the token to withdraw | | `min_amount` | `uint256` | minimum amount of token to withdraw | | `use_eth` | `bool` | True = withdraw ETH, False = withdraw wETH | | `receiver` | `address` | receiver of the coins; defaults to msg.sender | **<>Source code▼** ```vyper event RemoveLiquidityOne: provider: indexed(address) token_amount: uint256 coin_index: uint256 coin_amount: uint256 @external @nonreentrant('lock') def remove_liquidity_one_coin(token_amount: uint256, i: uint256, min_amount: uint256, use_eth: bool = False, receiver: address = msg.sender) -> uint256: A_gamma: uint256[2] = self._A_gamma() dy: uint256 = 0 D: uint256 = 0 p: uint256 = 0 xp: uint256[N_COINS] = empty(uint256[N_COINS]) future_A_gamma_time: uint256 = self.future_A_gamma_time dy, p, D, xp = self._calc_withdraw_one_coin(A_gamma, token_amount, i, (future_A_gamma_time > 0), True) assert dy >= min_amount, "Slippage" if block.timestamp >= future_A_gamma_time: self.future_A_gamma_time = 1 self.balances[i] -= dy CurveToken(self.token).burnFrom(msg.sender, token_amount) coin: address = self.coins[i] if use_eth and coin == WETH20: raw_call(receiver, b"", value=dy) else: if coin == WETH20: WETH(WETH20).deposit(value=dy) response: Bytes[32] = raw_call( coin, _abi_encode(receiver, dy, method_id=method_id("transfer(address,uint256)")), max_outsize=32, ) if len(response) != 0: assert convert(response, bool) self.tweak_price(A_gamma, xp, p, D) log RemoveLiquidityOne(msg.sender, token_amount, i, dy) return dy ``` **▶Example▼** ```shell >>> CryptoSwap.remove_liquidity_one_coin() ``` <a id="calc_withdraw_one_coin"></a> ### `calc_withdraw_one_coin` `CryptoSwap.calc_withdraw_one_coin(token_amount: uint256, i: uint256) -> uint256:` Method to calculate the amount of output token `i` when burning `token_amount` of lp tokens, taking fees into condsideration. Returns: amount of token received (`uint256`). | Input | Type | Description | | --- | --- | --- | | `token_amount` | `uint256` | amount of lp tokens burned | | `i` | `uint256` | index of the coin to withdraw | note This method takes fees into consideration. **<>Source code▼** ```vyper N_COINS: constant(int128) = 2 @view @external def calc_withdraw_one_coin(token_amount: uint256, i: uint256) -> uint256: return self._calc_withdraw_one_coin(self._A_gamma(), token_amount, i, True, False)[0] @internal @view def _calc_withdraw_one_coin(A_gamma: uint256[2], token_amount: uint256, i: uint256, update_D: bool, calc_price: bool) -> (uint256, uint256, uint256, uint256[N_COINS]): token_supply: uint256 = CurveToken(self.token).totalSupply() assert token_amount <= token_supply # dev: token amount more than supply assert i < N_COINS # dev: coin out of range xx: uint256[N_COINS] = self.balances D0: uint256 = 0 precisions: uint256[2] = self._get_precisions() price_scale_i: uint256 = self.price_scale * precisions[1] xp: uint256[N_COINS] = [xx[0] * precisions[0], xx[1] * price_scale_i / PRECISION] if i == 0: price_scale_i = PRECISION * precisions[0] if update_D: D0 = self.newton_D(A_gamma[0], A_gamma[1], xp) else: D0 = self.D D: uint256 = D0 # Charge the fee on D, not on y, e.g. reducing invariant LESS than charging the user fee: uint256 = self._fee(xp) dD: uint256 = token_amount * D / token_supply D -= (dD - (fee * dD / (2 * 10**10) + 1)) y: uint256 = self.newton_y(A_gamma[0], A_gamma[1], xp, D, i) dy: uint256 = (xp[i] - y) * PRECISION / price_scale_i xp[i] = y # Price calc p: uint256 = 0 if calc_price and dy > 10**5 and token_amount > 10**5: # p_i = dD / D0 * sum'(p_k * x_k) / (dy - dD / D0 * y0) S: uint256 = 0 precision: uint256 = precisions[0] if i == 1: S = xx[0] * precisions[0] precision = precisions[1] else: S = xx[1] * precisions[1] S = S * dD / D0 p = S * PRECISION / (dy * precision - dD * xx[i] * precision / D0) if i == 0: p = (10**18)**2 / p return dy, p, D, xp ``` **▶Example▼** ```shell >>> CryptoSwap.calc_withdraw_one_coin(1000000000000000000, 0) # withdraw 1 LP token in coin[0] 43347133051647883 ``` <a id="oracles-methods"></a> ## Oracles Methods Oracle prices are updated whenever the `tweak_price` function is called. This occurs when any of the `_exchange()`, `add_liquidity()`, or `remove_liquidity_one_coin()` functions are called. **<>Source code▼** ```vyper @internal def tweak_price(A_gamma: uint256[2],_xp: uint256[N_COINS], p_i: uint256, new_D: uint256): price_oracle: uint256 = self._price_oracle last_prices: uint256 = self.last_prices price_scale: uint256 = self.price_scale last_prices_timestamp: uint256 = self.last_prices_timestamp p_new: uint256 = 0 if last_prices_timestamp < block.timestamp: # MA update required ma_half_time: uint256 = self.ma_half_time alpha: uint256 = self.halfpow((block.timestamp - last_prices_timestamp) * 10**18 / ma_half_time) price_oracle = (last_prices * (10**18 - alpha) + price_oracle * alpha) / 10**18 self._price_oracle = price_oracle self.last_prices_timestamp = block.timestamp D_unadjusted: uint256 = new_D # Withdrawal methods know new D already if new_D == 0: # We will need this a few times (35k gas) D_unadjusted = self.newton_D(A_gamma[0], A_gamma[1], _xp) if p_i > 0: last_prices = p_i else: # calculate real prices __xp: uint256[N_COINS] = _xp dx_price: uint256 = __xp[0] / 10**6 __xp[0] += dx_price last_prices = price_scale * dx_price / (_xp[1] - self.newton_y(A_gamma[0], A_gamma[1], __xp, D_unadjusted, 1)) self.last_prices = last_prices total_supply: uint256 = CurveToken(self.token).totalSupply() old_xcp_profit: uint256 = self.xcp_profit old_virtual_price: uint256 = self.virtual_price # Update profit numbers without price adjustment first xp: uint256[N_COINS] = [D_unadjusted / N_COINS, D_unadjusted * PRECISION / (N_COINS * price_scale)] xcp_profit: uint256 = 10**18 virtual_price: uint256 = 10**18 if old_virtual_price > 0: xcp: uint256 = self.geometric_mean(xp, True) virtual_price = 10**18 * xcp / total_supply xcp_profit = old_xcp_profit * virtual_price / old_virtual_price t: uint256 = self.future_A_gamma_time if virtual_price < old_virtual_price and t == 0: raise "Loss" if t == 1: self.future_A_gamma_time = 0 self.xcp_profit = xcp_profit norm: uint256 = price_oracle * 10**18 / price_scale if norm > 10**18: norm -= 10**18 else: norm = 10**18 - norm adjustment_step: uint256 = max(self.adjustment_step, norm / 5) needs_adjustment: bool = self.not_adjusted # if not needs_adjustment and (virtual_price-10**18 > (xcp_profit-10**18)/2 + self.allowed_extra_profit): # (re-arrange for gas efficiency) if not needs_adjustment and (virtual_price * 2 - 10**18 > xcp_profit + 2*self.allowed_extra_profit) and (norm > adjustment_step) and (old_virtual_price > 0): needs_adjustment = True self.not_adjusted = True if needs_adjustment: if norm > adjustment_step and old_virtual_price > 0: p_new = (price_scale * (norm - adjustment_step) + adjustment_step * price_oracle) / norm # Calculate balances*prices xp = [_xp[0], _xp[1] * p_new / price_scale] # Calculate "extended constant product" invariant xCP and virtual price D: uint256 = self.newton_D(A_gamma[0], A_gamma[1], xp) xp = [D / N_COINS, D * PRECISION / (N_COINS * p_new)] # We reuse old_virtual_price here but it's not old anymore old_virtual_price = 10**18 * self.geometric_mean(xp, True) / total_supply # Proceed if we've got enough profit # if (old_virtual_price > 10**18) and (2 * (old_virtual_price - 10**18) > xcp_profit - 10**18): if (old_virtual_price > 10**18) and (2 * old_virtual_price - 10**18 > xcp_profit): self.price_scale = p_new self.D = D self.virtual_price = old_virtual_price return else: self.not_adjusted = False # Can instead do another flag variable if we want to save bytespace self.D = D_unadjusted self.virtual_price = virtual_price self._claim_admin_fees() return # If we are here, the price_scale adjustment did not happen # Still need to update the profit counter and D self.D = D_unadjusted self.virtual_price = virtual_price # norm appeared < adjustment_step after if needs_adjustment: self.not_adjusted = False self._claim_admin_fees() ``` <a id="lp_price"></a> ### `lp_price` `CryptoSwap.lp_price() -> uint256:` Getter for the approximate LP token price with regard to the token at index 0. Returns: LP token price (`uint256`). **<>Source code▼** ```vyper @external @view def lp_price() -> uint256: """ Approximate LP token price """ return 2 * self.virtual_price * self.sqrt_int(self.internal_price_oracle()) / 10**18 @internal @view def internal_price_oracle() -> uint256: price_oracle: uint256 = self._price_oracle last_prices_timestamp: uint256 = self.last_prices_timestamp if last_prices_timestamp < block.timestamp: ma_half_time: uint256 = self.ma_half_time last_prices: uint256 = self.last_prices alpha: uint256 = self.halfpow((block.timestamp - last_prices_timestamp) * 10**18 / ma_half_time) return (last_prices * (10**18 - alpha) + price_oracle * alpha) / 10**18 else: return price_oracle ``` **▶Example▼** ```shell >>> CryptoSwap.lp_price() 41793722011818265 ``` <a id="price_oracle"></a> ### `price_oracle` `CryptoSwap.price_oracle() -> uint256:` Getter for the oracle price of the coin at index `k` with regard to coin at index 0. Returns: oracle price (`uint256`). **<>Source code▼** ```vyper @external @view def price_oracle() -> uint256: return self.internal_price_oracle() @internal @view def internal_price_oracle() -> uint256: price_oracle: uint256 = self._price_oracle last_prices_timestamp: uint256 = self.last_prices_timestamp if last_prices_timestamp < block.timestamp: ma_half_time: uint256 = self.ma_half_time last_prices: uint256 = self.last_prices alpha: uint256 = self.halfpow((block.timestamp - last_prices_timestamp) * 10**18 / ma_half_time) return (last_prices * (10**18 - alpha) + price_oracle * alpha) / 10**18 else: return price_oracle ``` **▶Example▼** ```shell >>> CryptoSwap.price_oracle() 409798289826499 ``` <a id="last_prices"></a> ### `last_prices` `CryptoSwap.last_prices() -> uint256: view` Getter for the last price of the coin at index `k` with regard to the coin at index 0. `last_price` stores the last price when calling the functions `_exchange()`, `add_liquidity()` or `remove_liquitiy_one_coin()`. Returns: last price (`uint256`). **<>Source code▼** ```vyper last_prices: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.last_prices() 409119503867160 ``` <a id="last_prices_timestamp"></a> ### `last_prices_timestamp` `CryptoSwap.last_prices_timestamp() -> uint256: view` Getter for the timestamp of the most recent update for `last_prices`. Returns: timestamp (`uint256`). **<>Source code▼** ```vyper last_prices_timestamp: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.last_prices_timestamp() 1700314907 ``` <a id="price_scale"></a> ### `price_scale` `CryptoSwap.price_scale -> uint256: view` 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 `_exchange()`, `add_liquidity()` or `remove_liquitiy_one_coin()`. Returns: last price (`uint256`). **<>Source code▼** ```vyper price_scale: public(uint256) # Internal price scale ``` **▶Example▼** ```shell >>> CryptoSwap.price_scale() 410228896677145 ``` <a id="ma_half_time"></a> ### `ma_half_time` `CryptoSwap.ma_half_time() -> uint256: view` Getter for the moving-average (ma) half time in seconds. Returns: ma half time (`uint256`). **<>Source code▼** ```vyper ma_half_time: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.ma_half_time() 600 ``` <a id="virtual_price"></a> ### `virtual_price` `CryptoSwap.geometric_mean(unsorted_x: uint256[N_COINS], sort: bool) -> uint256:` Getter for the virtual price. This variable is cached, fast to read and mostly used internally. Returns: virtual price (`uint256`). **<>Source code▼** ```vyper virtual_price: public(uint256) # Cached (fast to read) virtual price also used internally ``` **▶Example▼** ```shell >>> CryptoSwap.virtual_price() 1032276363484815360 ``` <a id="get_virtual_price"></a> ### `get_virtual_price` `CryptoSwap.geometric_mean(unsorted_x: uint256[N_COINS], sort: bool) -> uint256:` Getter for the virtual price. Returns: virtual price (`uint256`). **<>Source code▼** ```vyper @external @view def get_virtual_price() -> uint256: return 10**18 * self.get_xcp(self.D) / CurveToken(self.token).totalSupply() ``` **▶Example▼** ```shell >>> CryptoSwap.get_virtual_price() 1032276363484815360 ``` <a id="fee-methods"></a> ## Fee Methods Fees are charged based on the balance/imbalance of the pool. Fee is low when the pool is balanced and increases the more it is imbalanced. <a id="fee"></a> ### `fee` `CryptoSwap.fee() -> uint256:` Getter for the fee charged by the pool at the current state. Returns: fee (`uint256`). **<>Source code▼** ```vyper @external @view def fee() -> uint256: return self._fee(self.xp()) @internal @view def _fee(xp: uint256[N_COINS]) -> uint256: """ f = fee_gamma / (fee_gamma + (1 - K)) where K = prod(x) / (sum(x) / N)**N (all normalized to 1e18) """ fee_gamma: uint256 = self.fee_gamma f: uint256 = xp[0] + xp[1] # sum f = fee_gamma * 10**18 / ( fee_gamma + 10**18 - (10**18 * N_COINS**N_COINS) * xp[0] / f * xp[1] / f ) return (self.mid_fee * f + self.out_fee * (10**18 - f)) / 10**18 ``` **▶Example▼** ```shell >>> CryptoSwap.fee() 26417626 ``` <a id="mid_fee"></a> ### `mid_fee` `CryptoSwap.mid_fee() -> uint256: view` Getter for the current 'mid-fee'. This is the minimum fee and is charged when the pool is completely balanced. Returns: mid fee (`uint256`). **<>Source code▼** ```vyper mid_fee: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.mid_fee() 26000000 ``` <a id="out_fee"></a> ### `out_fee` `CryptoSwap.out_fee() -> uint256: view` Getter for the 'out-fee'. This is the maximum fee and is charged when the pool is completely imbalanced. Returns: out fee (`uint256`). **<>Source code▼** ```vyper out_fee: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.out_fee() 45000000 ``` <a id="fee_gamma"></a> ### `fee_gamma` `CryptoSwap.fee_gamma() -> uint256: view` Getter for the 'fee-gamma'. This parameter modifies the rate at which fees rise as imbalance intensifies. Smaller values result in rapid fee hikes with growing imbalances, while larger values lead to more gradual increments in fees as imbalance expands. Returns: fee gamma (`uint256`). **<>Source code▼** ```vyper fee_gamma: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.fee_gamma() 230000000000000 ``` <a id="xcp_profit"></a> ### `xcp_profit` `CryptoSwap.xcp_profit() -> uint256: view` Getter for the current pool profits. Returns: current profits (`uint256`). **<>Source code▼** ```vyper xcp_profit: public(uint256) ``` **▶Example▼** ```shell >>> CryptoSwap.xcp_profit() 1058938494058326335 ``` <a id="xcp_profit_a"></a> ### `xcp_profit_a` `CryptoSwap.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
프로젝트로 돌아가기