Curve DAO 백서

Curve DAO

원문

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

es[i] # unsafe math is safu here: if ideal_balance > new_balance: difference = unsafe_sub(ideal_balance, new_balance) else: difference = unsafe_sub(new_balance, ideal_balance) # fee[i] = _dynamic_fee(i, j) * difference / FEE_DENOMINATOR xs = unsafe_div(rates[i] * (old_balances[i] + new_balance), PRECISION) _dynamic_fee_i = self._dynamic_fee(xs, ys, base_fee) fees.append( unsafe_div( _dynamic_fee_i * difference, FEE_DENOMINATOR ) ) # fees[i] * admin_fee / FEE_DENOMINATOR self.admin_balances[i] += unsafe_div(fees[i] * admin_fee, FEE_DENOMINATOR) new_balances[i] -= fees[i] xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, new_balances) D1 = math.get_D(xp, amp, N_COINS) # <------ Reuse D1 for new D value. mint_amount = total_supply * (D1 - D0) / D0 self.upkeep_oracles(xp, amp, D1) else: mint_amount = D1 # Take the dust if there was any # (re)instantiate D oracle if totalSupply is zero. self.last_D_packed = self.pack_2(D1, D1) assert mint_amount >= _min_mint_amount, "Slippage screwed you" # Mint pool tokens total_supply += mint_amount self.balanceOf[_receiver] += mint_amount self.total_supply = total_supply log Transfer(empty(address), _receiver, mint_amount) log AddLiquidity(msg.sender, _amounts, fees, D1, total_supply) return mint_amount ``` **▶Example▼** ```shell >>> StableSwap.get_balances() [4183467888075, 2556883713184291687567176] >>> StableSwap.add_liquidity([10**6, 0], 0) 9992841836391963157 >>> StableSwap.get_balances() [4183477887978, 2556883713089250297597078] ``` <a id="remove_liquidity"></a> ### `remove_liquidity` `StableSwap.remove_liquidity(_burn_amount: uint256, _min_amounts: DynArray[uint256, MAX_COINS], _receiver: address = msg.sender, _claim_admin_fees: bool = True) -> DynArray[uint256, MAX_COINS]:` info When removing liquidity in a balanced ratio, there is no need to update the price oracle, as this function does not alter the balance ratio within the pool. Calling this function only updates `D_oracle`. The calculation of `D` does not use Newton methods, ensuring that `remove_liquidity` should always work, even if the pool gets borked. Function to remove `_min_amount` coins from the liquidity pool based on the pools current ratios by burning `_burn_amount` of LP tokens. Admin fees might be claimed after liquidity is removed. Returns: amount of coins withdrawn (`DynArray[uint256, MAX_COINS]`). Emits: `RemoveLiquidity` | Input | Type | Description | | --- | --- | --- | | `_burn_amount` | `uint256` | Amount of LP tokens to be burned. | | `_min_amounts` | `DynArray[uint256, MAX_COINS]` | Minimum amounts of coins to receive. | | `_receiver` | `address` | Receiver of the coins; defaults to `msg.sender`. | | `_claim_admin_fees` | `bool` | If admin fees should be claimed; defaults to `true`. | **<>Source code▼** ```vyper event RemoveLiquidity: provider: indexed(address) token_amounts: DynArray[uint256, MAX_COINS] fees: DynArray[uint256, MAX_COINS] token_supply: uint256 @external @nonreentrant('lock') def remove_liquidity( _burn_amount: uint256, _min_amounts: DynArray[uint256, MAX_COINS], _receiver: address = msg.sender, _claim_admin_fees: bool = True, ) -> DynArray[uint256, MAX_COINS]: """ @notice Withdraw coins from the pool @dev Withdrawal amounts are based on current deposit ratios @param _burn_amount Quantity of LP tokens to burn in the withdrawal @param _min_amounts Minimum amounts of underlying coins to receive @param _receiver Address that receives the withdrawn coins @return List of amounts of coins that were withdrawn """ total_supply: uint256 = self.total_supply assert _burn_amount > 0 # dev: invalid _burn_amount amounts: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) balances: DynArray[uint256, MAX_COINS] = self._balances() value: uint256 = 0 for i in range(N_COINS_128): value = unsafe_div(balances[i] * _burn_amount, total_supply) assert value >= _min_amounts[i], "Withdrawal resulted in fewer coins than expected" amounts.append(value) self._transfer_out(i, value, _receiver) self._burnFrom(msg.sender, _burn_amount) # dev: insufficient funds # --------------------------- Upkeep D_oracle ---------------------------- ma_last_time_unpacked: uint256[2] = self.unpack_2(self.ma_last_time) last_D_packed_current: uint256 = self.last_D_packed old_D: uint256 = last_D_packed_current & (2**128 - 1) self.last_D_packed = self.pack_2( old_D - unsafe_div(old_D * _burn_amount, total_supply), # new_D = proportionally reduce D. self._calc_moving_average( last_D_packed_current, self.D_ma_time, ma_last_time_unpacked[1] ) ) if ma_last_time_unpacked[1] < block.timestamp: ma_last_time_unpacked[1] = block.timestamp self.ma_last_time = self.pack_2(ma_last_time_unpacked[0], ma_last_time_unpacked[1]) # ------------------------------- Log event ------------------------------ log RemoveLiquidity( msg.sender, amounts, empty(DynArray[uint256, MAX_COINS]), total_supply - _burn_amount ) # ------- Withdraw admin fees if _claim_admin_fees is set to True -------- if _claim_admin_fees: self._withdraw_admin_fees() return amounts ``` **▶Example▼** ```shell >>> StableSwap.get_balances() [4183477887978, 2556883713089250297628878] >>> StableSwap.remove_liquidity(10**18, [0, 0]) 614190, 375384835097322069 >>> StableSwap.get_balances() [4183477273788, 2556883337704415200306809] ``` <a id="remove_liquidity_one_coin"></a> ### `remove_liquidity_one_coin` `StableSwap.remove_liquidity_one_coin(_burn_amount: uint256, i: int128, _min_received: uint256, _receiver: address = msg.sender) -> uint256:` Function to remove a minimum of `_min_received` of coin `i` by burning `_burn_amount` of LP tokens. Returns: coins received (`uint256`). Emits: `RemoveLiquidityOne` | Input | Type | Description | | --- | --- | --- | | `_burn_amount` | `uint256` | Amount of LP tokens to burn/withdraw. | | `i` | `int128` | Index value of the coin to withdraw. | | `_min_received` | `uint256` | Minimum amount of coin to receive. | | `_receiver` | `address` | Receiver of the coins; defaults to `msg.sender`. | **<>Source code▼** ```vyper event RemoveLiquidityOne: provider: indexed(address) token_id: int128 token_amount: uint256 coin_amount: uint256 token_supply: uint256 @external @nonreentrant('lock') def remove_liquidity_one_coin( _burn_amount: uint256, i: int128, _min_received: uint256, _receiver: address = msg.sender, ) -> uint256: """ @notice Withdraw a single coin from the pool @param _burn_amount Amount of LP tokens to burn in the withdrawal @param i Index value of the coin to withdraw @param _min_received Minimum amount of coin to receive @param _receiver Address that receives the withdrawn coins @return Amount of coin received """ assert _burn_amount > 0 # dev: do not remove 0 LP tokens dy: uint256 = 0 fee: uint256 = 0 xp: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) amp: uint256 = empty(uint256) D: uint256 = empty(uint256) dy, fee, xp, amp, D = self._calc_withdraw_one_coin(_burn_amount, i) assert dy >= _min_received, "Not enough coins removed" # fee * admin_fee / FEE_DENOMINATOR self.admin_balances[i] += unsafe_div(fee * admin_fee, FEE_DENOMINATOR) self._burnFrom(msg.sender, _burn_amount) log Transfer(msg.sender, empty(address), _burn_amount) self._transfer_out(i, dy, _receiver) log RemoveLiquidityOne(msg.sender, i, _burn_amount, dy, self.total_supply) self.upkeep_oracles(xp, amp, D) return dy @view @internal def _calc_withdraw_one_coin( _burn_amount: uint256, i: int128 ) -> ( uint256, uint256, DynArray[uint256, MAX_COINS], uint256, uint256 ): # First, need to: # * Get current D # * Solve Eqn against y_i for D - _token_amount # get pool state amp: uint256 = self._A() rates: DynArray[uint256, MAX_COINS] = self._stored_rates() xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, self._balances()) D0: uint256 = math.get_D(xp, amp, N_COINS) total_supply: uint256 = self.total_supply D1: uint256 = D0 - _burn_amount * D0 / total_supply new_y: uint256 = math.get_y_D(amp, i, xp, D1, N_COINS) xp_reduced: DynArray[uint256, MAX_COINS] = xp ys: uint256 = (D0 + D1) / (2 * N_COINS) base_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1)) dx_expected: uint256 = 0 xp_j: uint256 = 0 xavg: uint256 = 0 dynamic_fee: uint256 = 0 for j in range(N_COINS_128): dx_expected = 0 xp_j = xp[j] if j == i: dx_expected = xp_j * D1 / D0 - new_y xavg = (xp_j + new_y) / 2 else: dx_expected = xp_j - xp_j * D1 / D0 xavg = xp_j # xp_j - dynamic_fee * dx_expected / FEE_DENOMINATOR dynamic_fee = self._dynamic_fee(xavg, ys, base_fee) xp_reduced[j] = xp_j - unsafe_div(dynamic_fee * dx_expected, FEE_DENOMINATOR) dy: uint256 = xp_reduced[i] - math.get_y_D(amp, i, xp_reduced, D1, N_COINS) dy_0: uint256 = (xp[i] - new_y) * PRECISION / rates[i] # w/o fees dy = (dy - 1) * PRECISION / rates[i] # Withdraw less to account for rounding errors # calculate state price xp[i] = new_y return dy, dy_0 - dy, xp, amp, D1 ``` **▶Example▼** ```shell >>> StableSwap.remove_liquidity_one_coin(10**18, 0, 0) 1000638 >>> StableSwap.remove_liquidity_one_coin(10**18, 1, 0) 971872609646322618 ``` <a id="remove_liquidity_imbalance"></a> ### `remove_liquidity_imbalance` `StableSwap.remove_liquidity_imbalance(_amounts: DynArray[uint256, MAX_COINS], _max_burn_amount: uint256, _receiver: address = msg.sender) -> uint256:` Function to burn a maximum of `_max_burn_amount` of LP tokens in order to receive `_amounts` of underlying tokens. Returns: amount of LP tokens burned (`uint256`). Emits: `RemoveLiquidityImbalance` | Input | Type | Description | | --- | --- | --- | | `_amounts` | `DynArray[uint256, MAX_COINS]` | List of amounts of coins to withdraw. | | `_max_burn_amount` | `uint256` | Maximum amount of LP tokens to burn. | | `_receiver` | `address` | Receiver of the coins; defaults to `msg.sender`. | **<>Source code▼** ```vyper event RemoveLiquidityImbalance: provider: indexed(address) token_amounts: DynArray[uint256, MAX_COINS] fees: DynArray[uint256, MAX_COINS] invariant: uint256 token_supply: uint256 @external @nonreentrant('lock') def remove_liquidity_imbalance( _amounts: DynArray[uint256, MAX_COINS], _max_burn_amount: uint256, _receiver: address = msg.sender ) -> uint256: """ @notice Withdraw coins from the pool in an imbalanced amount @param _amounts List of amounts of underlying coins to withdraw @param _max_burn_amount Maximum amount of LP token to burn in the withdrawal @param _receiver Address that receives the withdrawn coins @return Actual amount of the LP token burned in the withdrawal """ amp: uint256 = self._A() rates: DynArray[uint256, MAX_COINS] = self._stored_rates() old_balances: DynArray[uint256, MAX_COINS] = self._balances() D0: uint256 = self.get_D_mem(rates, old_balances, amp) new_balances: DynArray[uint256, MAX_COINS] = old_balances for i in range(N_COINS_128): if _amounts[i] != 0: new_balances[i] -= _amounts[i] self._transfer_out(i, _amounts[i], _receiver) D1: uint256 = self.get_D_mem(rates, new_balances, amp) base_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1)) ys: uint256 = (D0 + D1) / N_COINS fees: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) dynamic_fee: uint256 = 0 xs: uint256 = 0 ideal_balance: uint256 = 0 difference: uint256 = 0 new_balance: uint256 = 0 for i in range(N_COINS_128): ideal_balance = D1 * old_balances[i] / D0 new_balance = new_balances[i] if ideal_balance > new_balance: difference = ideal_balance - new_balance else: difference = new_balance - ideal_balance # base_fee * difference / FEE_DENOMINATOR xs = unsafe_div(rates[i] * (old_balances[i] + new_balance), PRECISION) dynamic_fee = self._dynamic_fee(xs, ys, base_fee) fees.append(unsafe_div(dynamic_fee * difference, FEE_DENOMINATOR)) # fees[i] * admin_fee / FEE_DENOMINATOR self.admin_balances[i] += unsafe_div(fees[i] * admin_fee, FEE_DENOMINATOR) new_balances[i] -= fees[i] D1 = self.get_D_mem(rates, new_balances, amp) # dev: reuse D1 for new D. self.upkeep_oracles(self._xp_mem(rates, new_balances), amp, D1) total_supply: uint256 = self.total_supply burn_amount: uint256 = ((D0 - D1) * total_supply / D0) + 1 assert burn_amount > 1 # dev: zero tokens burned assert burn_amount <= _max_burn_amount, "Slippage screwed you" self._burnFrom(msg.sender, burn_amount) log RemoveLiquidityImbalance(msg.sender, _amounts, fees, D1, total_supply) return burn_amount ``` **▶Example▼** ```shell >>> StableSwap.remove_liquidity_imbalance([2000000, 10**18], 50**18) 3027537955031682593 ``` note This method removes liquidity in an imbalanced portion (2 USDV and one 3CRV) by burning a `burn_amount` of LP tokens (3027537955031682593). <a id="calc_token_amount"></a> ### `calc_token_amount` `StableSwap.calc_token_amount(_amounts: DynArray[uint256, MAX_COINS], _is_deposit: bool) -> uint256:` Function to calculate the addition or reduction of token supply from a deposit (add liquidity) or withdrawal (remove liquidity). This function does take fees into consideration. Returns: amount of LP tokens (`uint256`). | Input | Type | Description | | --- | --- | --- | | `_amounts` | `DynArray[uint256, MAX_COINS]` | Amount of coins being deposited/withdrawn. | | `_is_deposit` | `bool` | `true` = deposit, `false` = withdraw. | **<>Source code▼** ```vyper interface StableSwapViews: def get_dx(i: int128, j: int128, dy: uint256, pool: address) -> uint256: view def get_dy(i: int128, j: int128, dx: uint256, pool: address) -> uint256: view def get_dx_underlying(i: int128, j: int128, dy: uint256, pool: address) -> uint256: view def get_dy_underlying(i: int128, j: int128, dx: uint256, pool: address) -> uint256: view def dynamic_fee(i: int128, j: int128, pool: address) -> uint256: view def calc_token_amount( _amounts: DynArray[uint256, MAX_COINS], _is_deposit: bool, _pool: address ) -> uint256: view @view @external def calc_token_amount( _amounts: DynArray[uint256, MAX_COINS], _is_deposit: bool ) -> uint256: """ @notice Calculate addition or reduction in token supply from a deposit or withdrawal @param _amounts Amount of each coin being deposited @param _is_deposit set True for deposits, False for withdrawals @return Expected amount of LP tokens received """ return StableSwapViews(factory.views_implementation()).calc_token_amount(_amounts, _is_deposit, self) ``` ```vyper @view @external def calc_token_amount( _amounts: DynArray[uint256, MAX_COINS], _is_deposit: bool, pool: address ) -> uint256: """ @notice Calculate addition or reduction in token supply from a deposit or withdrawal @param _amounts Amount of each coin being deposited @param _is_deposit set True for deposits, False for withdrawals @return Expected amount of LP tokens received """ amp: uint256 = StableSwapNG(pool).A() * A_PRECISION N_COINS: uint256 = StableSwapNG(pool).N_COINS() rates: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) old_balances: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) xp: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) rates, old_balances, xp = self._get_rates_balances_xp(pool, N_COINS) # Initial invariant D0: uint256 = self.get_D(xp, amp, N_COINS) total_supply: uint256 = StableSwapNG(pool).totalSupply() new_balances: DynArray[uint256, MAX_COINS] = old_balances for i in range(MAX_COINS): if i == N_COINS: break amount: uint256 = _amounts[i] if _is_deposit: new_balances[i] += amount else: new_balances[i] -= amount # Invariant after change for idx in range(MAX_COINS): if idx == N_COINS: break xp[idx] = rates[idx] * new_balances[idx] / PRECISION D1: uint256 = self.get_D(xp, amp, N_COINS) # We need to recalculate the invariant accounting for fees # to calculate fair user's share D2: uint256 = D1 if total_supply > 0: # Only account for fees if we are not the first to deposit base_fee: uint256 = StableSwapNG(pool).fee() * N_COINS / (4 * (N_COINS - 1)) fee_multiplier: uint256 = StableSwapNG(pool).offpeg_fee_multiplier() _dynamic_fee_i: uint256 = 0 xs: uint256 = 0 ys: uint256 = (D0 + D1) / N_COINS for i in range(MAX_COINS): if i == N_COINS: break ideal_balance: uint256 = D1 * old_balances[i] / D0 difference: uint256 = 0 new_balance: uint256 = new_balances[i] if ideal_balance > new_balance: difference = ideal_balance - new_balance else: difference = new_balance - ideal_balance xs = old_balances[i] + new_balance _dynamic_fee_i = self._dynamic_fee(xs, ys, base_fee, fee_multiplier) new_balances[i] -= _dynamic_fee_i * difference / FEE_DENOMINATOR for idx in range(MAX_COINS): if idx == N_COINS: break xp[idx] = rates[idx] * new_balances[idx] / PRECISION D2 = self.get_D(xp, amp, N_COINS) else: return D1 # Take the dust if there was any diff: uint256 = 0 if _is_deposit: diff = D2 - D0 else: diff = D0 - D2 return diff * total_supply / D0 ``` **▶Example▼** ```shell >>> StableSwap.calc_token_amount([10**6, 10**18], False) 2028274156743388789 ``` <a id="calc_withdraw_one_coin"></a> ### `calc_withdraw_one_coin` `StableSwap.calc_withdraw_one_coin(_burn_amount: uint256, i: int128) -> uint256:` Function to calculate the amount of single token `i` withdrawn when burning `_burn_amount` LP tokens. Returns: amount of tokens withdrawn (`uint256`). | Input | Type | Description | | --- | --- | --- | | `_burn_amount` | `uint256` | Amount of LP tokens to burn. | | `i` | `int128` | Index value of the coin to withdraw. | **<>Source code▼** ```vyper @view @external def calc_withdraw_one_coin(_burn_amount: uint256, i: int128) -> uint256: """ @notice Calculate the amount received when withdrawing a single coin @param _burn_amount Amount of LP tokens to burn in the withdrawal @param i Index value of the coin to withdraw @return Amount of coin received """ return self._calc_withdraw_one_coin(_burn_amount, i)[0] @view @internal def _calc_withdraw_one_coin( _burn_amount: uint256, i: int128 ) -> ( uint256, uint256, DynArray[uint256, MAX_COINS], uint256, uint256 ): # First, need to: # * Get current D # * Solve Eqn against y_i for D - _token_amount # get pool state amp: uint256 = self._A() rates: DynArray[uint256, MAX_COINS] = self._stored_rates() xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, self._balances()) D0: uint256 = math.get_D(xp, amp, N_COINS) total_supply: uint256 = self.total_supply D1: uint256 = D0 - _burn_amount * D0 / total_supply new_y: uint256 = math.get_y_D(amp, i, xp, D1, N_COINS) xp_reduced: DynArray[uint256, MAX_COINS] = xp ys: uint256 = (D0 + D1) / (2 * N_COINS) base_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1)) dx_expected: uint256 = 0 xp_j: uint256 = 0 xavg: uint256 = 0 dynamic_fee: uint256 = 0 for j in range(N_COINS_128): dx_expected = 0 xp_j = xp[j] if j == i: dx_expected = xp_j * D1 / D0 - new_y xavg = (xp_j + new_y) / 2 else: dx_expected = xp_j - xp_j * D1 / D0 xavg = xp_j # xp_j - dynamic_fee * dx_expected / FEE_DENOMINATOR dynamic_fee = self._dynamic_fee(xavg, ys, base_fee) xp_reduced[j] = xp_j - unsafe_div(dynamic_fee * dx_expected, FEE_DENOMINATOR) dy: uint256 = xp_reduced[i] - math.get_y_D(amp, i, xp_reduced, D1, N_COINS) dy_0: uint256 = (xp[i] - new_y) * PRECISION / rates[i] # w/o fees dy = (dy - 1) * PRECISION / rates[i] # Withdraw less to account for rounding errors # calculate state price xp[i] = new_y return dy, dy_0 - dy, xp, amp, D1 ``` **▶Example▼** ```shell >>> StableSwap.calc_withdraw_one_coin(10**18, 0) 1000638 >>> StableSwap.calc_withdraw_one_coin(10**18, 1) 971872610064262793 >>> StableSwap.get_balances() [4183467888075, 2556883713184291687567176] # [coin[0], coin[1]] ``` * * * <a id="fee-methods"></a> ## Fee Methods Stableswap-ng introduces a dynamic fee based on the imbalance of the coins within the pool and their pegs: **▶\`\_dynamic\_fee\`▼** ```vype
프로젝트로 돌아가기