Curve DAO 백서

Curve DAO

원문

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

calc_fee_get_dy"></a> ### `calc_fee_get_dy` `Views.calc_fee_get_dy(i: uint256, j: uint256, dx: uint256, swap: address) -> uint256: view` Returns the fee component, denominated in raw `coins(j)` units, for the exact-input quote described by `get_dy`. It uses the same index and positive-input guards. This is an analytical helper. Swap execution emits the realized fee in `TokenExchange`. <a id="liquidity-methods"></a> ## Liquidity Methods <a id="calc_token_amount"></a> ### `calc_token_amount` `Views.calc_token_amount(amounts: uint256[2], deposit: bool, swap: address, donation: bool = False) -> uint256: view` Estimates LP tokens minted for a deposit or burned for a withdrawal, including the applicable liquidity fee. | Input | Description | | --- | --- | | `amounts` | Raw amounts ordered as `[coins(0), coins(1)]` | | `deposit` | `true` for adding liquidity; `false` for removing liquidity | | `swap` | FXSwap pool address | | `donation` | Immutable ABI name; set `true` only when estimating a refuel | For user liquidity, prefer `pool.calc_token_amount(amounts, deposit)`. Call the Views contract directly only when the refuel flag or a separate fee breakdown is required. <a id="calc_withdraw_one_coin"></a> ### `calc_withdraw_one_coin` `Views.calc_withdraw_one_coin(token_amount: uint256, i: uint256, swap: address) -> uint256: view` Returns the estimated raw amount of `coins(i)` received for burning `token_amount` LP units in a one-coin withdrawal, after the approximate fee. The call requires `i < 2` and `token_amount <= pool.totalSupply()`. Prefer `pool.calc_withdraw_one_coin(token_amount, i)` for normal integrations. <a id="calc_fee_withdraw_one_coin"></a> ### `calc_fee_withdraw_one_coin` `Views.calc_fee_withdraw_one_coin(token_amount: uint256, i: uint256, swap: address) -> uint256: view` Returns the approximate fee component for the same one-coin withdrawal. The value is denominated in raw `coins(i)` units and uses the same guards as `calc_withdraw_one_coin`. <a id="calc_fee_token_amount"></a> ### `calc_fee_token_amount` `Views.calc_fee_token_amount(amounts: uint256[2], deposit: bool, swap: address, donation: bool = False) -> uint256: view` Returns the liquidity-fee component expressed in LP-token units for a deposit or withdrawal quote. `donation=true` selects the immutable contract path used to estimate a refuel. <a id="integration-guidance"></a> ## Integration guidance - Read `VIEW()` from each allowlisted pool and version the pool and periphery together. - Prefer the pool-native wrappers for `get_dy`, `get_dx`, `calc_token_amount`, and `calc_withdraw_one_coin`. - Use direct Views calls for fee breakdowns or the refuel-specific `donation` flag. - Batch offchain calls at one block number so balances, parameters, prices, and supply are consistent. - Simulate state-changing calldata immediately before submission; a view quote does not reserve pool state. --- # CryptoSwap Exchange: Overview Source: [https://docs.curve.finance/developer/amm/legacy/cryptoswap-overview](https://docs.curve.finance/developer/amm/legacy/cryptoswap-overview) The *Automatic Market-Making with Dynamic Peg (CryptoSwap)* algorithm introduces a new approach for creating liquidity for assets which are not necessarily pegged to each other. The core of this algorithm lies in its ability to **concentrate liquidity around a price point determined by an internal oracle**, adjusting this price in a way that balances potential losses and system profits. Key features include the use of **transformed pegged invariants**, a method for quantifying profits and losses, and the **CurveCrypto invariant**, specifically designed for efficient execution on the EVM. The algorithm also incorporates a **dynamic fee structure**that responds to changing market conditions. This approach seeks to enhance liquidity provision and optimize returns for liquidity providers. Whitepaper For a detailed overview of the design, please read the official [whitepaper](https://docs.curve.finance/assets/files/whitepaper_cryptoswap-de196d8f95aae3164a1226234d6d96ca.pdf). * * * <a id="implementations"></a> ## Implementations *There have been several implementations of the CryptoSwap algorithm:* Contract Source *Source code is available on GitHub:* - genesis contracts: [https://github.com/curvefi/curve-crypto-contract](https://github.com/curvefi/curve-crypto-contract) - twocrypto-ng: [https://github.com/curvefi/twocrypto-ng](https://github.com/curvefi/twocrypto-ng) - tricrypto-ng: [https://github.com/curvefi/tricrypto-ng](https://github.com/curvefi/tricrypto-ng) | Type | Description | | --- | --- | | **`CryptoSwap`** | Genesis two-coin volatile asset pool integration. | | **`Tricrypto`** | Genesis three-coin volatile asset pool integration. | | **`TwoCrypto-NG`** | Improved version of `CryptoSwap`, more [here](https://docs.curve.finance/developer/amm/twocrypto-ng/overview.md). | | **`Tricrypto-NG`** | Improved version of `Tricrypto`, more [here](https://docs.curve.finance/developer/amm/tricrypto-ng/overview.md). | * * * <a id="parameters"></a> ## Parameters Because different trading pairs can exhibit drastically different price dynamics, Curve v2 offers a variety of tunable parameters that can be used to optimize for different types of assets. **The CryptoSwap market-making algorithm contains of three different classes of parameters:**\- *Bonding Curve:* `A` and `gamma` - *Price Scaling:* `ma_time`, `allowed_extra_profit` and `adjustment_step` - *Fees:* `mid_fee`, `out_fee` and `fee_gamma` Explainer for Parameters An excellent deep-dive article on the parameters: [https://nagaking.substack.com/p/deep-dive-curve-v2-parameters](https://nagaking.substack.com/p/deep-dive-curve-v2-parameters). <a id="bonding-curve-parameters"></a> ## Bonding Curve Parameters Similar to many AMMs, Curve v2 employs a bonding curve to determine asset prices according to the pool's supply of each asset. To centralize liquidity around the midpoint of the bonding curve, Curve v2 adopts an invariant that falls between the StableSwap (Curve v1) approach and the constant-product method used by platforms like Uniswap and Balancer. - **`A`**: regulates the concentration of liquidity at the core of the bonding curve - **`gamma`**: regulates the overall breadth of the curve <a id="price-scaling"></a> ## Price Scaling Curve v2 pools automatically adjust liquidity to optimize depth close to the prevailing market rates, reducing slippage. This is achieved by tracking a continuous EMA (exponential moving average) of the pool's latest exchange rates (referred to as an "internal oracle") and reallocating liquidity around this EMA only when it's economically beneficial for LPs. - **`ma_time`**: regulates the duration of the EMA price oracle - **`allowed_extra_profit`**: excess profit required to allow price re-pegging - **`adjustment_step`**: minimum size of price scale adjustments <a id="fees"></a> ## Fees 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. *There are three different kind of fees:* - **`fee_mid`**: charged fee when pool is perfectly balanced (minimum possible fee). - **`out_fee`**: charged fee when pools is completely imbalanced (maximum possible fee). - **`fee_gamma`**: determines the speed at which the fee increases when the pool becomes imbalanced. A low value leads to a more rapid fee increase, while a high value causes the fee to rise more gradually. ![](https://docs.curve.finance/assets/images/curveV2_fee-5cbae28492636cf9c088642c571f44bd.png) --- # lp-token-v5 Source: [https://docs.curve.finance/developer/amm/legacy/cryptoswap/lp-tokens/lp-token-v5](https://docs.curve.finance/developer/amm/legacy/cryptoswap/lp-tokens/lp-token-v5) The LP token and exchange contract for two-coin CryptoSwap pools are two separate contracts from each other. Newer versions, like Tricrypto-NG, combine both the LP token and exchange contract into a single contract. The LP token contract is created from the \*\*`token_implementation`\*\*using the [**`create_forwarder_to()`**](https://docs.vyperlang.org/en/stable/built-in-functions.html?highlight=create_forwarder_to#chain-interaction) function, which is a built-in function in Vyper. After deployment, the LP token contract is then initialized through the \*\*`initialize()`\*\*function. info Newer deployments might make use of blueprint contracts ([EIP-5202](https://eips.ethereum.org/EIPS/eip-5202)), eliminating the need for an \*\*`initialize()`\*\*function. *To query the currently implemented LP token contract:* ```shell >>> Factory.token_implementation() '0xc08550A4cc5333f40e593eCc4C4724808085D304' ``` <a id="lp-token-info-methods"></a> ## LP Token Info Methods <a id="name"></a> ### `name` `LPTokenV5.name() -> String[64]: view` Getter for the name of the LP token. Returns: name (`String[64]`). **<>Source code▼** ```vyper name: public(String[64]) @external def initialize(_name: String[64], _symbol: String[32], _pool: address): assert self.minter == ZERO_ADDRESS # dev: check that we call it from factory self.name = _name self.symbol = _symbol self.minter = _pool self.DOMAIN_SEPARATOR = keccak256( _abi_encode(EIP712_TYPEHASH, keccak256(_name), keccak256(VERSION), chain.id, self) ) # fire a transfer event so block explorers identify the contract as an ERC20 log Transfer(ZERO_ADDRESS, msg.sender, 0) ``` **▶Example▼** ```shell >>> LPTokenV5.name() 'Curve.fi Factory Crypto Pool: LDO/ETH' ``` <a id="symbol"></a> ### `symbol` `LPTokenV5.symbol() -> String[32]: view` Getter for the symbol of the LP token. Returns: symbol (`String[32]`). **<>Source code▼** ```vyper symbol: public(String[32]) @external def initialize(_name: String[64], _symbol: String[32], _pool: address): assert self.minter == ZERO_ADDRESS # dev: check that we call it from factory self.name = _name self.symbol = _symbol self.minter = _pool self.DOMAIN_SEPARATOR = keccak256( _abi_encode(EIP712_TYPEHASH, keccak256(_name), keccak256(VERSION), chain.id, self) ) # fire a transfer event so block explorers identify the contract as an ERC20 log Transfer(ZERO_ADDRESS, msg.sender, 0) ``` **▶Example▼** ```shell >>> LPTokenV5.symbol() 'LDOETH-f' ``` <a id="decimals"></a> ### `decimals` `LPTokenV5.decimals() -> uint8` Getter for the decimals of the LP token. Returns: decimals (`uint8`). **<>Source code▼** ```vyper @view @external def decimals() -> uint8: """ @notice Get the number of decimals for this token @dev Implemented as a view method to reduce gas costs @return uint8 decimal places """ return 18 ``` **▶Example▼** ```shell >>> LPTokenV5.decimals() 18 ``` <a id="version"></a> ### `version` `LPTokenV5.version() -> String[8]:` Getter for the version of the LP token. Returns: version (`String[8]`). **<>Source code▼** ```vyper VERSION: constant(String[8]) = "v5.0.0" @view @external def version() -> String[8]: """ @notice Get the version of this token contract """ return VERSION ``` **▶Example▼** ```shell >>> LPTokenV5.version() 'v5.0.0' ``` <a id="balanceof"></a> ### `balanceOf` `LPTokenV5.balanceOf(arg0: address) -> uint256: view` Getter for the LP token balance of an address. Returns: token balance (`uint256`). | Input | Type | Description | | --- | --- | --- | | `arg0` | `address` | Address to get the balance for | **<>Source code▼** ```vyper balanceOf: public(HashMap[address, uint256]) ``` **▶Example▼** ```shell >>> LPTokenV5.balanceOf("0xe5d5Aa1Bbe72F68dF42432813485cA1Fc998DE32") 74284034901658384235023 ``` <a id="totalsupply"></a> ### `totalSupply` `LPTokenV5.totalSupply() -> uint256: view` Getter for the total supply of the LP token. Returns: total supply (`uint256`). **<>Source code▼** ```vyper totalSupply: public(uint256) ``` **▶Example▼** ```shell >>> LPTokenV5.totalSupply() 74357443715423884544842 ``` <a id="minter"></a> ### `minter` `LPTokenV5.totalSupply() -> uint256: view` Getter for the minter contract of the LP token. Minter contract address is the liquidity pool itself. Returns: minter (`address`). **<>Source code▼** ```vyper minter: public(address) @external def __init__(): self.minter = 0x0000000000000000000000000000000000000001 @external def initialize(_name: String[64], _symbol: String[32], _pool: address): assert self.minter == ZERO_ADDRESS # dev: check that we call it from factory self.name = _name self.symbol = _symbol self.minter = _pool self.DOMAIN_SEPARATOR = keccak256( _abi_encode(EIP712_TYPEHASH, keccak256(_name), keccak256(VERSION), chain.id, self) ) # fire a transfer event so block explorers identify the contract as an ERC20 log Transfer(ZERO_ADDRESS, msg.sender, 0) ``` **▶Example▼** ```shell >>> LPTokenV5.minter() '0x9409280DC1e6D33AB7A8C6EC03e5763FB61772B5' ``` <a id="allowance-and-transfer-methods"></a> ## Allowance and Transfer Methods <a id="transfer"></a> ### `transfer` `LPTokenV5.transfer(_to: address, _value: uint256) -> bool` Function to transfer `_value` token from `msg.sender` to `_to`. Returns: True (`bool`). Emits: `Transfer` | Input | Type | Description | | --- | --- | --- | | `_to` | `address` | Address to transfer to | | `_value` | `uint256` | Amount to transfer | **<>Source code▼** ```vyper event Transfer: _from: indexed(address) _to: indexed(address) _value: uint256 @external def transfer(_to: address, _value: uint256) -> bool: """ @dev Transfer token for a specified address @param _to The address to transfer to. @param _value The amount to be transferred. """ # NOTE: vyper does not allow underflows # so the following subtraction would revert on insufficient balance self.balanceOf[msg.sender] -= _value self.balanceOf[_to] += _value log Transfer(msg.sender, _to, _value) return True ``` **▶Example▼** ```shell >>> LPToken.transfer("0xbabe61887f1de2713c6f97e567623453d3C79f67", 100) True ``` <a id="transferfrom"></a> ### `transferFrom` `LPTokenV5.transfer(_to: address, _value: uin256) -> bool:` Function to transfer `_value` token from `msg.sender` to `_to`. Needs [`allowance`](https://docs.curve.finance/developer/amm/legacy/cryptoswap/lp-tokens/lp-token-v5.md#allowance) to successfully transfer on behalf of someone else. Returns: True or False (`bool`). Emits: `Transfer` | Input | Type | Description | | --- | --- | --- | | `_to` | `address` | Address to transfer to | | `_value` | `uint256` | Amount to transfer | **<>Source code▼** ```vyper event Transfer: _from: indexed(address) _to: indexed(address) _value: uint256 @external def transferFrom(_from: address, _to: address, _value: uint256) -> bool: """ @dev Transfer tokens from one address to another. @param _from address The address which you want to send tokens from @param _to address The address which you want to transfer to @param _value uint256 the amount of tokens to be transferred """ self.balanceOf[_from] -= _value self.balanceOf[_to] += _value _allowance: uint256 = self.allowance[_from][msg.sender] if _allowance != MAX_UINT256: self.allowance[_from][msg.sender] = _allowance - _value log Transfer(_from, _to, _value) return True ``` **▶Example▼** ```shell >>> LPToken.transferFrom("0xbabe61887f1de2713c6f97e567623453d3C79f67", 100) True ``` <a id="approve"></a> ### `approve` `LPTokenV5.approve(_spender: address, _value: uint256) -> bool:` Function to approve `_spender` to transfer `_value` on behalf of msg.sender. Returns: True (`bool`). Emits: `Approval` | Input | Type | Description | | --- | --- | --- | | `_spender` | `address` | Address approved to spend funds | | `_value` | `uint256` | Amount of tokens allowed to spend | **<>Source code▼** ```vyper event Approval: _owner: indexed(address) _spender: indexed(address) _value: uint256 @external def approve(_spender: address, _value: uint256) -> bool: """ @notice Approve the passed address to transfer the specified amount of tokens on behalf of msg.sender @dev Beware that changing an allowance via this method brings the risk that someone may use both the old and new allowance by unfortunate transaction ordering. This may be mitigated with the use of {increaseAllowance} and {decreaseAllowance}. https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 @param _spender The address which will transfer the funds @param _value The amount of tokens that may be transferred @return bool success """ self.allowance[msg.sender][_spender] = _value log Approval(msg.sender, _spender, _value) return True ``` **▶Example▼** ```shell >>> LPToken.approve("todo") "todo" ``` <a id="permit"></a> ### `permit` `LPTokenV5.permit(_owner: address, _spender: address, _value: uint256, _deadline: uint256, _v: uint8, _r: bytes32, _s: bytes32) -> bool::` Function to approve the spender by the owner's signature to expend the owner's tokens. Returns: True (`bool`). Emits: `Approval` | Input | Type | Description | | --- | --- | --- | | `_to` | `address` | Address to transfer to | | `_value` | `uint256` | Amount to transfer | **<>Source code▼** ```vyper event Approval: _owner: indexed(address) _spender: indexed(address) _value: uint256 @external def permit( _owner: address, _spender: address, _value: uint256, _deadline: uint256, _v: uint8, _r: bytes32, _s: bytes32 ) -> bool: """ @notice Approves spender by owner's signature to expend owner's tokens. See https://eips.ethereum.org/EIPS/eip-2612. @dev Inspired by https://github.com/yearn/yearn-vaults/blob/main/contracts/Vault.vy#L753-L793 @dev Supports smart contract wallets which implement ERC1271 https://eips.ethereum.org/EIPS/eip-1271 @param _owner The address which is a source of funds and has signed the Permit. @param _spender The address which is allowed to spend the funds. @param _value The amount of tokens to be spent. @param _deadline The timestamp after which the Permit is no longer valid. @param _v The bytes[64] of the valid secp256k1 signature of permit by owner @param _r The bytes[0:32] of the valid secp256k1 signature of permit by owner @param _s The bytes[32:64] of the valid secp256k1 signature of permit by owner @return True, if transaction completes successfully """ assert _owner != ZERO_ADDRESS assert block.timestamp <= _deadline nonce: uint256 = self.nonces[_owner] digest: bytes32 = keccak256( concat( b"\x19\x01", self.DOMAIN_SEPARATOR, keccak256(_abi_encode(PERMIT_TYPEHASH, _owner, _spender, _value, nonce, _deadline)) ) ) if _owner.is_contract: sig: Bytes[65] = concat(_abi_encode(_r, _s), slice(convert(_v, bytes32), 31, 1)) # reentrancy not a concern since this is a staticcall assert ERC1271(_owner).isValidSignature(digest, sig) == ERC1271_MAGIC_VAL else: assert ecrecover(digest, convert(_v, uint256), convert(_r, uint256), convert(_s, uint256)) == _owner self.allowance[_owner][_spender] = _value self.nonces[_owner] = nonce + 1 log Approval(_owner, _spender, _value) return True ``` **▶Example▼** ```shell >>> LPTokenV5.permit() "todo" ``` <a id="allowance"></a> ### `allowance` `LPTokenV5.allowance(arg0: address, arg1: address) -> uint256: view` Getter method to check the allowance of `arg0` for funds of `arg1`. Returns: allowed amount (`uint256`). | Input | Type | Description | | --- | --- | --- | | `arg0` | `address` | Address of the spender | | `arg0` | `address` | Address to the token owner | **<>Source code▼** ```vyper allowance: public(HashMap[address, HashMap[address, uint256]]) ``` **▶Example▼** ```shell >>> LPTokenV5.allowance("todo") "todo" ``` <a id="increaseallowance"></a> ### `increaseAllowance` `LPTokenV5.increaseAllowance(_spender: address, _added_value: uint256) -> bool:` Function to increase the allowance granted to `_spender`. Returns: True or False (`bool`). Emits: `Approval` | Input | Type | Description | | --- | --- | --- | | `_spender` | `address` | Address to increase the allowance of | | `_added_v
프로젝트로 돌아가기