Curve DAO 백서

Curve DAO

원문

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

and output_token == FRXETH_ADDRESS): # ETH <--> WETH rate is 1:1 # ETH ---> stETH rate is 1:1 # ETH ---> frxETH rate is 1:1 pass elif input_token == WSTETH_ADDRESS: amount = wstETH(swap).getWstETHByStETH(amount) elif output_token == WSTETH_ADDRESS: amount = wstETH(swap).getStETHByWstETH(amount) elif input_token == SFRXETH_ADDRESS: amount = sfrxETH(swap).convertToShares(amount) elif output_token == SFRXETH_ADDRESS: amount = sfrxETH(swap).convertToAssets(amount) elif output_token == WBETH_ADDRESS: amount = amount * wBETH(swap).exchangeRate() / 10**18 else: raise "Swap type 8 is only for ETH <-> WETH, ETH -> stETH or ETH -> frxETH, stETH <-> wstETH, frxETH <-> sfrxETH, ETH -> wBETH" elif params[2] == 9: snx_exchanger: address = SynthetixAddressResolver(SNX_ADDRESS_RESOLVER).getAddress(SNX_EXCHANGER_NAME) atomic_amount_and_fee: AtomicAmountAndFee = SynthetixExchanger(snx_exchanger).getAmountsForAtomicExchange( 10**18, self.snx_currency_keys[input_token], self.snx_currency_keys[output_token] ) amount = amount * 10**18 / atomic_amount_and_fee.amountReceived else: raise "Bad swap type" return amount ``` **▶Example▼** ```shell >>> Router.get_dx( ['0x34635280737b5BFe6c7DC2FC3065D60d66e78185', # crxPRISMA '0x3b21C2868B6028CfB38Ff86127eF22E68d16d53B', # cvxPRISMA/PRISMA pool '0xdA47862a83dac0c112BA89c6abC2159b95afd71C', # PRISMA '0x322135Dd9cBAE8Afa84727d9aE1434b5B3EBA44B', # PRISMA/ETH pool '0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE', # ETH '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000'], [[1, 0, 1, 1, 2], # first swap: cvxPRISMA &lt;&gt; PRISMA [1, 0, 1, 2, 2], # second swap: PRISMA &lt;&gt; ETH [0, 0, 0, 0, 0], [0, 0, 0, 0, 0], [0, 0, 0, 0, 0]], 100000000000000000000, # _out_amount ['0x3b21C2868B6028CfB38Ff86127eF22E68d16d53B', # cvxPRISMA/PRISMA pool '0x322135Dd9cBAE8Afa84727d9aE1434b5B3EBA44B', # PRISMA/ETH pool '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000', '0x0000000000000000000000000000000000000000']) 18597416260226417 # expected input ``` --- # Plain and Meta-Pool Implementation with Custom Admin Controls Source: [https://docs.curve.finance/developer/amm/stableswap-ng/implementations/custom1](https://docs.curve.finance/developer/amm/stableswap-ng/implementations/custom1) This implementation enables \*\*arbitrary assignment of an `admin` and `admin_fee`\*\*for a specific pool. The `Factory.admin()` is, and will always remain, one of the pool’s owners—ensuring full control via the DAO. Contract Implementations The source code for the implementation can be found on GitHub in the [admin-implementation branch](https://github.com/curvefi/stableswap-ng/tree/admin-implementation). This implementation is initially used by CrossCurve on Sonic. The implementations were added to the StableSwapFactory on Sonic via [Vote ID #1010](https://curve.fi/dao/ethereum/proposals/1010-OWNERSHIP/) and are deployed at `index = 710420`. ```py >>> Factory.metapool_implementations(710420) '0x8663426e8713922D81e44d73295759e74Afc230F' >>> Factory.pool_implementations(710420) '0xA7c2DD4356168153792EF05D27922064b3c71A26' ``` The implementation introduces the ability to designate an additional admin with the following permissions: - The admin has the authority to set the contract’s admin fee, which can range from 0% to 100%. Previously, this fee was hardcoded at 50%. - Once an `admin` is set, their address replaces the `fee_receiver` and starts receiving all pool admin fees. If no admin is set, the `fee_receiver` remains the default recipient. At contract initialization, the admin is set to `ZERO_ADDRESS`. This means assigning a new admin requires a DAO vote via the `set_admin` function. The `admin_fee` defaults to 50% but can be updated later. * * * <a id="admin"></a> ### `admin` `CurveStableSwap.admin() -> address: view` Getter for the admin of the contract. At contract initialization, the address of the admin is always set to `ZERO_ADDRESS`. Returns: admin of the contract (`address`). **<>Source code▼** ```vyper @external def __init__( ... ): ... self.admin = empty(address) ... admin: public(address) ``` **▶Example▼** This example returns the current admin of the contract. ```shell >>> CurveStableSwap.admin() '0x0000000000000000000000000000000000000000' ``` <a id="set_admin"></a> ### `set_admin` `CurveStableSwap.set_admin(_new_admin: address)` Guarded Method This function is only callable by the `admin` of the `Factory`. Function to set the admin of the contract. Setting the admin will revert if its not called by the admin of the `Factory`. Emits: `SetAdmin` event. | Input | Type | Description | | --- | --- | --- | | `_new_admin` | `address` | New admin address. | **<>Source code▼** ```vyper interface Factory: def fee_receiver() -> address: view event SetAdmin: admin: address admin: public(address) @external def set_admin(_new_admin: address): assert msg.sender == factory.admin() # dev: only owner self.admin = _new_admin log SetAdmin(_new_admin) @view @internal def _check_admins(): assert msg.sender == factory.admin() or msg.sender == self.admin # dev: only admin ``` **▶Example▼** This example sets the admin of the contract. ```shell >>> CurveStableSwap.admin() '0x0000000000000000000000000000000000000000' >>> CurveStableSwap.set_admin('0x7a16ff8270133f063aab6c9977183d9e72835428') >>> CurveStableSwap.admin() '0x7a16ff8270133f063aab6c9977183d9e72835428' ``` * * * <a id="admin_fee"></a> ### `admin_fee` `CurveStableSwap.admin_fee() -> uint256: view` Getter for the admin fee of the pool. At contract initialization, the admin fee is set to 50%. Returns: admin fee (`uint256`). **<>Source code▼** ```vyper @external def __init__( ... ): ... self.admin_fee = 5000000000 ... admin_fee: public(uint256) ``` **▶Example▼** This example returns the current admin fee of the contract. ```shell >>> CurveStableSwap.admin() '0x0000000000000000000000000000000000000000' ``` <a id="set_new_admin_fee"></a> ### `set_new_admin_fee` `CurveStableSwap.set_new_admin_fee(_new_admin_fee: uint256):` Guarded Method This function is only callable by the `admin` of the `Pool` or the `Factory`. Function to set the admin fee of the pool. Emits: `SetAdmin` event. | Input | Type | Description | | --- | --- | --- | | `_new_admin_fee` | `uint256` | New admin fee value. | **<>Source code▼** ```vyper interface Factory: def fee_receiver() -> address: view event ApplyNewAdminFee: admin_fee: uint256 admin_fee: public(uint256) FEE_DENOMINATOR: constant(uint256) = 10 **10 @external def set_new_admin_fee(_new_admin_fee: uint256): self._check_admins() # FEE_DENOMINATOR = 1 = 100% assert _new_admin_fee <= FEE_DENOMINATOR # dev: more than 100% self.admin_fee = _new_admin_fee log ApplyNewAdminFee(_new_admin_fee) @view @internal def _check_admins(): assert msg.sender == factory.admin() or msg.sender == self.admin # dev: only admin ``` **▶Example▼** This example sets the admin of the contract. ```shell >>> StableSwapNG.admin_fee() 5000000000 >>> StableSwapNG.set_new_admin_fee(0) >>> StableSwapNG.admin_fee() 0 ``` --- # Stableswap-NG: Overview Source: [https://docs.curve.finance/developer/amm/stableswap-ng/overview](https://docs.curve.finance/developer/amm/stableswap-ng/overview) Contract Source & Deployment Source code is available on [GitHub](https://github.com/curvefi/stableswap-ng). The following documentation covers source code up until commit number [`5f582a6`](https://github.com/curvefi/stableswap-ng/commit/5f582a6b8f709d863825c5fbe026cd3b4fa2d840). All stableswap-ng deployments can be found in the "Deployment Addresses" section. [↗](https://docs.curve.finance/developer/deployments.md) For an in-depth understanding of the Stableswap invariant design, please refer to the official [Stableswap whitepaper](https://docs.curve.finance/assets/files/whitepaper_stableswap-fc0bb370db9fe3a91afdde8662e78206.pdf). A Curve pool is essentially a smart contract that implements the Stableswap invariant, housing the logic for exchanging stable tokens. While all Curve pools share this core implementation, they come in various pool flavors. In its simplest form, a Curve pool is an implementation of the Stableswap invariant involving two or more tokens, often referred to as a 'plain pool.' Alternatively, Curve offers more complex pool variants, including pools with rebasing tokens and metapools. Metapools facilitate the exchange of one or more tokens with those from one or more underlying tokens. **New features:** - price and D oracles - dynamic fees - [**`exchange_received`**](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool.md#exchange_received) - [**`get_dx`**](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool.md#get_dx) * * * <a id="supported-assets"></a> ## Supported Assets Stableswap-NG pools support the following asset types: | Asset Type | Description | | --- | --- | | `0` | **Standard ERC20** token with no additional features | | `1` | **Oracle** - token with rate oracle (e.g. wstETH) | | `2` | **Rebasing** - token with rebase (e.g. stETH) | | `3` | **ERC4626** - token with *`convertToAssets`* method (e.g. sDAI) | *Consequently, supported tokens include:* - ERC20 support for return True/revert, return True/False, return None - ERC20 tokens can have arbitrary decimals (<=18) - ERC20 tokens that rebase (either positive or fee on transfer) - ERC20 tokens that have a rate oracle (e.g. wstETH, cbETH, sDAI, etc.) Oracle precision *must* be 10^18 - ERC4626 tokens with arbitrary precision (<=18) of Vault token and underlying asset Rebasing Tokens Pools including rebasing tokens work a bit differently compared to others. The internal **`_balance()`** function - which is used to calculate the coin balances within the pool - makes sure that **LP's keep all rebases**. **▶\`\_balances()\`▼** ```vyper @view @internal def _balances() -> DynArray[uint256, MAX_COINS]: """ @notice Calculates the pool's balances _excluding_ the admin's balances. @dev If the pool contains rebasing tokens, this method ensures LPs keep all rebases and admin only claims swap fees. This also means that, since admin's balances are stored in an array and not inferred from read balances, the fees in the rebasing token that the admin collects is immune to slashing events. """ result: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) balances_i: uint256 = 0 for i in range(MAX_COINS_128): if i == N_COINS_128: break if POOL_IS_REBASING_IMPLEMENTATION: balances_i = ERC20(coins[i]).balanceOf(self) - self.admin_balances[i] else: balances_i = self.stored_balances[i] - self.admin_balances[i] result.append(balances_i) return result ``` * * * <a id="dynamic-fees"></a> ## Dynamic Fees Stableswap-NG introduces dynamic fees. The use of the **`offpeg_fee_multiplier`** allows the system to dynamically adjust fees based on the pool's state. The internal **`_dynamic_fee()`** function calculates the fee **based on the balances and rates** of the tokens being exchanged. If the balances of the tokens being exchanged are highly imbalanced or significantly differ from its peg, the fee is adjusted using the **`offpeg_fee_multiplier`**. info If the formulas below do not render, please make sure to refresh the site. A solution is being worked on. *Let's define some terms and variables for clarity:* - Let $fee$ represent the fee, as retrieved by the method **`StableSwap.fee()`** - Let $fee_m$ denote the off-peg fee multiplier, sourced from **`StableSwap.offpeg_fee_multiplier()`** - **`FEE_DENOMINATOR`** is a constant with a value of $10^{10}$, representing the precision of the fee - The terms $rate_{i}$ and $balance{i}$ refer to the specific rate and balance for coin $i$, respectively, and similarly, $rate_j$ and $balance_j$ for coin $j$ - $PRECISION_{i}$ and $PRECISION_{j}$ are the precision constants for the respective coins *Given these, we define:* $xp_{i} = \frac{{rate_{i} \times balance_{i}}}{{PRECISION_{i}}}$ $xp_{j} = \frac{{rate_{j} \times balance_{j}}}{{PRECISION_{j}}}$ $xp_{i}$ and $xp_{j}$ are the token balances of the pool adjusted for decimals and the pool's internal rates (stored in `stored_rates`). *And we also have:* $xps2 = (xp_{i} + xp_{j})^2$ **The dynamic fee is calculated by the following formula:**$\text{dynamic fee} = \frac{{fee_{m} \times fee}}{\frac{(fee_{m} - 10^{10}) \times 4 \times xp_{i} \times xp_{j}}{xps2}+ 10^{10}}$ **▶\`dynamic\_fee\` method▼** ```vyper A_PRECISION: constant(uint256) = 100 MAX_COINS: constant(uint256) = 8 PRECISION: constant(uint256) = 10 **18 FEE_DENOMINATOR: constant(uint256) = 10 **10 @view @external def dynamic_fee(i: int128, j: int128, pool:address) -> uint256: """ @notice Return the fee for swapping between `i` and `j` @param i Index value for the coin to send @param j Index value of the coin to recieve @return Swap fee expressed as an integer with 1e10 precision """ N_COINS: uint256 = StableSwapNG(pool).N_COINS() fee: uint256 = StableSwapNG(pool).fee() fee_multiplier: uint256 = StableSwapNG(pool).offpeg_fee_multiplier() rates: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) balances: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) xp: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) rates, balances, xp = self._get_rates_balances_xp(pool, N_COINS) return self._dynamic_fee(xp[i], xp[j], fee, fee_multiplier) @view @internal def _dynamic_fee(xpi: uint256, xpj: uint256, _fee: uint256) -> uint256: _offpeg_fee_multiplier: uint256 = self.offpeg_fee_multiplier if _offpeg_fee_multiplier <= FEE_DENOMINATOR: return _fee xps2: uint256 = (xpi + xpj) **2 return ( (_offpeg_fee_multiplier * _fee) / ((_offpeg_fee_multiplier - FEE_DENOMINATOR) * 4 * xpi * xpj / xps2 + FEE_DENOMINATOR) ) @view @internal def _get_rates_balances_xp(pool: address, N_COINS: uint256) -> ( DynArray[uint256, MAX_COINS], DynArray[uint256, MAX_COINS], DynArray[uint256, MAX_COINS], ): rates: DynArray[uint256, MAX_COINS] = StableSwapNG(pool).stored_rates() balances: DynArray[uint256, MAX_COINS] = StableSwapNG(pool).get_balances() xp: DynArray[uint256, MAX_COINS] = empty(DynArray[uint256, MAX_COINS]) for idx in range(MAX_COINS): if idx == N_COINS: break xp.append(rates[idx] * balances[idx] / PRECISION) return rates, balances, xp ``` <a id="interactive-graph"></a> ### Interactive Graph The embedded graph has limited features, such as the inability to modify the axis. However, by clicking the *"edit graph on desmos"* button at the bottom right, one is redirected to the main Desmos site. There, a wider range of functionalities is available, allowing for further adjustments and detailed exploration of the graph. * * * <a id="oracles"></a> ## Oracles The new generation (NG) of stableswap introduces two new pool-built-in oracles: - **price oracle** (spot and moving-average price) - moving average **D oracle** More on oracles [here](https://docs.curve.finance/developer/amm/stableswap-ng/pools/oracles.md). * * * <a id="exchange_received"></a> ## `exchange_received` This new function **allows the exchange of tokens without actually transferring tokens in**, as the exchange is based on the change of the coins balances within the pool. Users of this method are dex aggregators, arbitrageurs, or other users who **do not wish to grant approvals to the contract**. They can instead send tokens directly to the contract and call **`exchange_received()`**. Article Explore the `exchange_received` function's role in streamlining swaps without approvals, its efficiency benefits, and security considerations in a succinct article. Learn more about this innovative feature for cost-effective, secure trading through Curve pools: [How to Do Cheaper, Approval-Free Swaps](https://blog.curvemonitor.com/posts/exchange-received/). * * * **The Stableswap-NG AMM infrastructure represents a technically enhanced iteration of the previous stableswap implementation. It comprises the following key components:** `AMM Blueprint Contracts` * * * Stableswap-NG has two main implementations: [**Plain Pools**](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool.md) and [**Metapools**](https://docs.curve.finance/developer/amm/stableswap-ng/pools/metapool.md). [→ Plain Pools](https://docs.curve.finance/developer/amm/stableswap-ng/pools/plainpool.md) `CurveStableSwapFactoryNG.vy` * * * The Pool Factory is used to **permissionlessly deploy new plain and metapools**, as well as **liquidity gauges**. It also acts as a registry for finding the deployed pools and querying information about them. [→ CurveStableSwapFactoryNG.vy](https://docs.curve.finance/developer/factory/stableswap-ng/overview) `CurveStableSwapNGMath.vy` * * * Contract which provides **mathematical utilities** for the AMM blueprint contracts. [→ CurveStableSwapNGMath.vy](https://docs.curve.finance/developer/amm/stableswap-ng/utility-contracts/math.md) `CurveStableSwapNGViews.vy` * * * Contract targeted at **integrators**. Contains **view-only external methods** for the AMMs. [→ CurveStableSwapNGViews.vy](https://docs.curve.finance/developer/amm/stableswap-ng/utility-contracts/views.md) `Liquidity Gauge Blueprint` * * * A liquidity gauge blueprint implementation which deploys a liquidity gauge of a pool on Ethereum. Gauges on sidechains must be deployed via the `RootChainGaugeFactory`. `Oracles` * * * Exponential moving-average oracles for the `D` invariant and for the prices of coins within the AMM. [→ Oracles](https://docs.curve.finance/developer/amm/stableswap-ng/pools/oracles.md) --- # metapool Source: [https://docs.curve.finance/developer/amm/stableswap-ng/pools/metapool](https://docs.curve.finance/developer/amm/stableswap-ng/pools/metapool) A metapool is a pool where a stablecoin is paired against the LP token from another pool, a so-called base pool. Contract Source & Deployment Source code available on [Github](https://github.com/curvefi/stableswap-ng/blob/bff1522b30819b7b240af17ccfb72b0effbf6c47/contracts/main/CurveStableSwapMetaNG.vy). The deployment of metapools is permissionless and can be done via the [**`deploy_metapool`**](https://docs.curve.finance/developer/amm/factory/stableswap-ng/deployer-api.md#deploy_metapool) 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. The examples are based on the USDV<>3CRV metapool: [0xc273fd237F23cb13296D0Cc2897F0B7A61e83387](https://etherscan.io/address/0xc273fd237F23cb13296D0Cc2897F0B7A61e83387#code). **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 metapool contract implementation utilizes two internal functions to transfer tokens/coins in and out of the pool and then accordingly update `stored_balances`.* *These function slightly differ to the ones from plain pools, as there needs to be some additional logic because of the basepools:* - **`_transfer_in()`** **▶\`\_transfer\_in(coin\_metapool\_idx: int128, coin\_basepool\_idx: int128, dx: uint256, sender: address, expect\_optimistic\_transfer: bool, is\_base\_pool\_swap: bool = False) -> uint256:\`▼** | Input | Type |
프로젝트로 돌아가기