bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 29쪽
eing exchanged |
| `_min_dy` | `uint256` | Minimum amount of `j` to receive |
Emits: TokenExchangeUnderlying
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def exchange_underlying(i: int128, j: int128, dx: uint256, min_dy: uint256) -> uint256:
"""
@notice Perform an exchange between two underlying coins
@dev Index values can be found via the `underlying_coins` public getter method
@param i Index value for the underlying coin to send
@param j Index valie of the underlying coin to recieve
@param dx Amount of `i` being exchanged
@param min_dy Minimum amount of `j` to receive
@return Actual amount of `j` received
"""
assert not self.is_killed # dev: is killed
rates: uint256[N_COINS] = RATES
rates[MAX_COIN] = self._vp_rate()
_base_pool: address = self.base_pool
# Use base_i or base_j if they are >= 0
base_i: int128 = i - MAX_COIN
base_j: int128 = j - MAX_COIN
meta_i: int128 = MAX_COIN
meta_j: int128 = MAX_COIN
if base_i < 0:
meta_i = i
if base_j < 0:
meta_j = j
dy: uint256 = 0
# Addresses for input and output coins
input_coin: address = ZERO_ADDRESS
if base_i < 0:
input_coin = self.coins[i]
else:
input_coin = self.base_coins[base_i]
output_coin: address = ZERO_ADDRESS
if base_j < 0:
output_coin = self.coins[j]
else:
output_coin = self.base_coins[base_j]
# Handle potential Tether fees
dx_w_fee: uint256 = dx
if input_coin == FEE_ASSET:
dx_w_fee = ERC20(FEE_ASSET).balanceOf(self)
# "safeTransferFrom" which works for ERC20s which return bool or not
_response: Bytes[32] = raw_call(
input_coin,
concat(
method_id("transferFrom(address,address,uint256)"),
convert(msg.sender, bytes32),
convert(self, bytes32),
convert(dx, bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool) # dev: failed transfer
# end "safeTransferFrom"
# Handle potential Tether fees
if input_coin == FEE_ASSET:
dx_w_fee = ERC20(FEE_ASSET).balanceOf(self) - dx_w_fee
if base_i < 0 or base_j < 0:
old_balances: uint256[N_COINS] = self.balances
xp: uint256[N_COINS] = self._xp_mem(rates[MAX_COIN], old_balances)
x: uint256 = 0
if base_i < 0:
x = xp[i] + dx_w_fee * rates[i] / PRECISION
else:
# i is from BasePool
# At first, get the amount of pool tokens
base_inputs: uint256[BASE_N_COINS] = empty(uint256[BASE_N_COINS])
base_inputs[base_i] = dx_w_fee
coin_i: address = self.coins[MAX_COIN]
# Deposit and measure delta
x = ERC20(coin_i).balanceOf(self)
Curve(_base_pool).add_liquidity(base_inputs, 0)
# Need to convert pool token to "virtual" units using rates
# dx is also different now
dx_w_fee = ERC20(coin_i).balanceOf(self) - x
x = dx_w_fee * rates[MAX_COIN] / PRECISION
# Adding number of pool tokens
x += xp[MAX_COIN]
y: uint256 = self.get_y(meta_i, meta_j, x, xp)
# Either a real coin or token
dy = xp[meta_j] - y - 1 # -1 just in case there were some rounding errors
dy_fee: uint256 = dy * self.fee / FEE_DENOMINATOR
# Convert all to real units
# Works for both pool coins and real coins
dy = (dy - dy_fee) * PRECISION / rates[meta_j]
dy_admin_fee: uint256 = dy_fee * self.admin_fee / FEE_DENOMINATOR
dy_admin_fee = dy_admin_fee * PRECISION / rates[meta_j]
# Change balances exactly in same way as we change actual ERC20 coin amounts
self.balances[meta_i] = old_balances[meta_i] + dx_w_fee
# When rounding errors happen, we undercharge admin fee in favor of LP
self.balances[meta_j] = old_balances[meta_j] - dy - dy_admin_fee
# Withdraw from the base pool if needed
if base_j >= 0:
out_amount: uint256 = ERC20(output_coin).balanceOf(self)
Curve(_base_pool).remove_liquidity_one_coin(dy, base_j, 0)
dy = ERC20(output_coin).balanceOf(self) - out_amount
assert dy >= min_dy, "Too few coins in result"
else:
# If both are from the base pool
dy = ERC20(output_coin).balanceOf(self)
Curve(_base_pool).exchange(base_i, base_j, dx_w_fee, min_dy)
dy = ERC20(output_coin).balanceOf(self) - dy
# "safeTransfer" which works for ERC20s which return bool or not
_response = raw_call(
output_coin,
concat(
method_id("transfer(address,uint256)"),
convert(msg.sender, bytes32),
convert(dy, bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool) # dev: failed transfer
# end "safeTransfer"
log TokenExchangeUnderlying(msg.sender, i, dx, j, dy)
return dy
```
**▶Example▼**
```shell
>>> lending_pool.exchange_underlying()
todo: console output
```
---
# overview
Source: [https://docs.curve.finance/developer/amm/legacy/stableswap/pools/overview](https://docs.curve.finance/developer/amm/legacy/stableswap/pools/overview)
A Curve pool is a smart contract that implements the Stableswap invariant and thereby allows for the exchange of two or more tokens.
More broadly, Curve pools can be split into three categories:
1. `Plain Pools`: A pool where two or more stablecoins are paired against each other.
2. `Lending Pools`: A pool where two or more *wrapped* tokens (e.g. `cDAI`) are paired against one another, while the underlying is lent out on some other protocol.
3. `Metapools`: A pool where a stablecoin is paired against the LP token from another pool.
Source code for Curve pools may be viewed on [GitHub](https://github.com/curvefi/curve-contract/tree/master/contracts).
warning
The API for plain, lending and metapools applies to all pools that are implemented based on [pool templates](https://github.com/curvefi/curve-contract/tree/master/contracts/pool-templates). When interacting with older Curve pools, there may be differences in terms of visibility, gas efficiency and/or variable naming. Furthermore, note that older contracts use `vyper 0.1.x...` and that the getters generated for public arrays changed between `0.1.x` and `0.2.x` to accept `uint256` instead of `int128` in order to handle the lookups.
Please **do not**assume for a Curve pool to implement the API outlined in this section but verify this before interacting with a pool contract.
For information on code style please refer to the official [style guide](https://vyper.readthedocs.io/en/stable/style-guide.html).
---
# plain-pools
Source: [https://docs.curve.finance/developer/amm/legacy/stableswap/pools/plain-pools](https://docs.curve.finance/developer/amm/legacy/stableswap/pools/plain-pools)
The simplest Curve pool is a plain pool, which is an implementation of the Stableswap invariant for two or more tokens. The key characteristic of a plain pool is that the pool contract holds all deposited assets at **all**times.
An example of a Curve plain pool is [3Pool](https://github.com/curvefi/curve-contract/tree/master/contracts/pools/3pool), which contains the tokens `DAI`, `USDC` and `USDT`.
note
The API of plain pools is also implemented by lending and metapools.
The following Brownie console interaction examples are using [EURS](https://etherscan.io/address/0x0Ce6a5fF5217e38315f87032CF90686C96627CAA) Pool. The template source code for plain pools may be viewed on [GitHub](https://github.com/curvefi/curve-contract/blob/master/contracts/pool-templates/base/SwapTemplateBase.vy).
<a id="pool-info-methods"></a>
## Pool Info Methods
<a id="coins"></a>
### `coins`
`StableSwap.coins(i: uint256) → address: view`
Getter for the array of swappable coins within the pool.
Returns: coin address (`address`) for coin index `i`.
| Input | Type | Description |
| --- | --- | --- |
| `i` | `uint256` | Coin index |
**<>Source code▼**
```vyper
coins: public(address[N_COINS])
...
@external
def __init__(
_owner: address,
_coins: address[N_COINS],
_pool_token: address,
_A: uint256,
_fee: uint256,
_admin_fee: uint256
):
"""
@notice Contract constructor
@param _owner Contract owner address
@param _coins Addresses of ERC20 contracts of coins
@param _pool_token Address of the token representing LP share
@param _A Amplification coefficient multiplied by n * (n - 1)
@param _fee Fee to charge for exchanges
@param _admin_fee Admin fee
"""
for i in range(N_COINS):
assert _coins[i] != ZERO_ADDRESS
self.coins = _coins
self.initial_A = _A * A_PRECISION
self.future_A = _A * A_PRECISION
self.fee = _fee
self.admin_fee = _admin_fee
self.owner = _owner
self.kill_deadline = block.timestamp + KILL_DEADLINE_DT
self.lp_token = _pool_token
```
**▶Example▼**
```shell
>>> pool.coin(0)
'0xdB25f211AB05b1c97D595516F45794528a807ad8'
```
<a id="balances"></a>
### `balances`
`StableSwap.balances(i: uint256) → uint256: view`
Getter for the pool balances array.
Returns: Balance of coin (`uint256`) at index `i`.
| Input | Type | Description |
| --- | --- | --- |
| `i` | `uint256` | Coin index |
**▶Example▼**
```shell
>>> pool.balances(0)
2918187395
```
<a id="owner"></a>
### `owner`
`StableSwap.owner() → address: view`
Getter for the admin/owner of the pool contract.
Returns: `address` of the admin of the pool contract.
**<>Source code▼**
```vyper
owner: public(address)
...
@external
def __init__(
_owner: address,
_coins: address[N_COINS],
_pool_token: address,
_A: uint256,
_fee: uint256,
_admin_fee: uint256
):
"""
@notice Contract constructor
@param _owner Contract owner address
@param _coins Addresses of ERC20 contracts of coins
@param _pool_token Address of the token representing LP share
@param _A Amplification coefficient multiplied by n * (n - 1)
@param _fee Fee to charge for exchanges
@param _admin_fee Admin fee
"""
for i in range(N_COINS):
assert _coins[i] != ZERO_ADDRESS
self.coins = _coins
self.initial_A = _A * A_PRECISION
self.future_A = _A * A_PRECISION
self.fee = _fee
self.admin_fee = _admin_fee
self.owner = _owner
self.kill_deadline = block.timestamp + KILL_DEADLINE_DT
self.lp_token = _pool_token
```
**▶Example▼**
```shell
>>> pool.owner()
'0xeCb456EA5365865EbAb8a2661B0c503410e9B347'
```
<a id="lp_token"></a>
### `lp_token`
`StableSwap.lp_token() → address: view`
Getter for the LP token of the pool.
Returns: `address` of the `lp_token`.
**▶Example▼**
```shell
>>> pool.lp_token()
'0x194eBd173F6cDacE046C53eACcE9B953F28411d1'
```
note
In older Curve pools `lp_token` may not be `public` and thus not visible.
<a id="a-amplification-factor"></a>
### `A (Amplification factor)`
`StableSwap.A() → uint256: view`
Getter for the amplification coefficient of the pool.
**<>Source code▼**
```vyper
A_PRECISION: constant(uint256) = 100
...
@view
@external
def A() -> uint256:
return self._A() / A_PRECISION
```
**▶Example▼**
```shell
>>> pool.A()
100
```
note
The amplification coefficient is scaled by `A_PRECISION` (`=100`)
<a id="a_precise"></a>
### `A_precise`
`StableSwap.A_precise() → uint256: view`
Getter for the unscaled amplification coefficient of the pool.
**<>Source code▼**
```vyper
@view
@external
def A_precise() -> uint256:
return self._A()
```
**▶Example▼**
```shell
>>> pool.A()
10000
```
<a id="get_virtual_price"></a>
### `get_virtual_price`
`StableSwap.get_virtual_price() → uint256: view`
Current virtual price of the pool LP token relative to the underlying pool assets.
**<>Source code▼**
```vyper
@view
@external
def get_virtual_price() -> uint256:
"""
@notice The current virtual price of the pool LP token
@dev Useful for calculating profits
@return LP token virtual price normalized to 1e18
"""
D: uint256 = self.get_D(self._xp(), self._A())
# D is in the units similar to DAI (e.g. converted to precision 1e18)
# When balanced, D = n * x_u - total virtual value of the portfolio
token_supply: uint256 = ERC20(self.lp_token).totalSupply()
return D * PRECISION / token_supply
```
**▶Example▼**
```shell
>>> pool.get_virtual_price()
1001692838188850782
```
note
- The method returns `virtual_price` as an integer with `1e18` precision.
- `virtual_price` returns a price relative to the underlying. You can get the absolute price by multiplying it with the price of the underlying assets.
<a id="fee"></a>
### `fee`
`StableSwap.fee() → uint256: view`
The pool swap fee.
**<>Source code▼**
```vyper
fee: public(uint256) # fee * 1e10
...
@external
def __init__(
_owner: address,
_coins: address[N_COINS],
_pool_token: address,
_A: uint256,
_fee: uint256,
_admin_fee: uint256
):
"""
@notice Contract constructor
@param _owner Contract owner address
@param _coins Addresses of ERC20 conracts of coins
@param _pool_token Address of the token representing LP share
@param _A Amplification coefficient multiplied by n * (n - 1)
@param _fee Fee to charge for exchanges
@param _admin_fee Admin fee
"""
for i in range(N_COINS):
assert _coins[i] != ZERO_ADDRESS
self.coins = _coins
self.initial_A = _A * A_PRECISION
self.future_A = _A * A_PRECISION
self.fee = _fee
self.admin_fee = _admin_fee
self.owner = _owner
self.kill_deadline = block.timestamp + KILL_DEADLINE_DT
self.lp_token = _pool_token
```
**▶Example▼**
```shell
>>> pool.fee()
4000000
```
note
The method returns `fee` as an integer with `1e10` precision.
<a id="admin_fee"></a>
### `admin_fee`
`StableSwap.admin_fee() → uint256: view`
The percentage of the swap fee that is taken as an admin fee.
**<>Source code▼**
```vyper
admin_fee: public(uint256) # admin_fee * 1e10
...
@external
def __init__(
_owner: address,
_coins: address[N_COINS],
_pool_token: address,
_A: uint256,
_fee: uint256,
_admin_fee: uint256
):
"""
@notice Contract constructor
@param _owner Contract owner address
@param _coins Addresses of ERC20 conracts of coins
@param _pool_token Address of the token representing LP share
@param _A Amplification coefficient multiplied by n * (n - 1)
@param _fee Fee to charge for exchanges
@param _admin_fee Admin fee
"""
for i in range(N_COINS):
assert _coins[i] != ZERO_ADDRESS
self.coins = _coins
self.initial_A = _A * A_PRECISION
self.future_A = _A * A_PRECISION
self.fee = _fee
self.admin_fee = _admin_fee
self.owner = _owner
self.kill_deadline = block.timestamp + KILL_DEADLINE_DT
self.lp_token = _pool_token
```
**▶Example▼**
```shell
>>> pool.admin_fee()
5000000000
```
note
- The method returns an integer with with `1e10` precision.
- Admin fee is set at 50% (`5000000000`) and is paid out to veCRV holders.
<a id="exchange-methods"></a>
## Exchange Methods
<a id="get_dy"></a>
### `get_dy`
`StableSwap.get_dy(i: int128, j: int128, _dx: uint256) → uint256: view`
Get the amount of coin `j` one would receive for swapping `dx` of coin `i`.
| Input | Type | Description |
| --- | --- | --- |
| `i` | `uint128` | Index of coin to swap from |
| `j` | `uint128` | Index of coin to swap to |
| `dx` | `uint256` | Amount of coin `i` to swap |
**<>Source code▼**
```vyper
@view
@external
def get_dy(i: int128, j: int128, dx: uint256) -> uint256:
xp: uint256[N_COINS] = self._xp()
rates: uint256[N_COINS] = RATES
x: uint256 = xp[i] + (dx * rates[i] / PRECISION)
y: uint256 = self.get_y(i, j, x, xp)
dy: uint256 = (xp[j] - y - 1)
_fee: uint256 = self.fee * dy / FEE_DENOMINATOR
return (dy - _fee) * PRECISION / rates[j]
```
**▶Example▼**
```shell
>>> pool.get_dy(0, 1, 100)
996307731416690125
```
note
Note: In this example, the `EURS Pool` coins decimals for `coins(0)` and `coins(1)` are `2` and `18`, respectively.
<a id="exchange"></a>
### `exchange`
`StableSwap.exchange(i: int128, j: int128, dx: uint256, min_dy: uint256) → uint256`
Perform an exchange between two coins.
| Input | Type | Description |
| --- | --- | --- |
| `i` | `uint128` | Index of coin to swap from |
| `j` | `uint128` | Index of coin to swap to |
| `dx` | `uint256` | Amount of coin `i` to swap |
| `min_dy` | `uint256` | Minimum amount of `j` to receive |
Returns the actual amount of coin `j` received. Index values can be found via the `coins` public getter method.
Emits: TokenExchange
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def exchange(i: int128, j: int128, dx: uint256, min_dy: uint256) -> uint256:
"""
@notice Perform an exchange between two coins
@dev Index values can be found via the `coins` public getter method
@param i Index value for the coin to send
@param j Index valie of the coin to recieve
@param dx Amount of `i` being exchanged
@param min_dy Minimum amount of `j` to receive
@return Actual amount of `j` received
"""
assert not self.is_killed # dev: is killed
old_balances: uint256[N_COINS] = self.balances
xp: uint256[N_COINS] = self._xp_mem(old_balances)
rates: uint256[N_COINS] = RATES
x: uint256 = xp[i] + dx * rates[i] / PRECISION
y: uint256 = self.get_y(i, j, x, xp)
dy: uint256 = xp[j] - y - 1 # -1 just in case there were some rounding errors
dy_fee: uint256 = dy * self.fee / FEE_DENOMINATOR
# Convert all to real units
dy = (dy - dy_fee) * PRECISION / rates[j]
assert dy >= min_dy, "Exchange resulted in fewer coins than expected"
dy_admin_fee: uint256 = dy_fee * self.admin_fee / FEE_DENOMINATOR
dy_admin_fee = dy_admin_fee * PRECISION / rates[j]
# Change balances exactly in same way as we change actual ERC20 coin amounts
self.balances[i] = old_balances[i] + dx
# When rounding errors happen, we undercharge admin fee in favor of LP
self.balances[j] = old_balances[j] - dy - dy_admin_fee
# "safeTransferFrom" which works for ERC20s which return bool or not
_response: Bytes[32] = raw_call(
self.coins[i],
concat(
method_id("transferFrom(address,address,uint256)"),
convert(msg.sender, bytes32),
convert(self, bytes32),
convert(dx, bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool)
_response = raw_call(
self.coins[j],
concat(
method_id("transfer(address,uint256)"),
convert(msg.sender, bytes32),
convert(dy, bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool)
log TokenExchange(msg.sender, i, dx, j, dy)
return dy
```
**▶Example▼**
```shell
>>> expected = pool.get_dy(0, 1, 10**2) * 0.99
>>> pool.exchange(0, 1, 10**2, expected, {"from": alice})
```
<a id="addremove-liquidity-methods"></a>
## Add/Remove Liquidity Methods
<a id="calc_token_amount"></a>
### `calc_token_amount`
`StableSwap.calc_token_amount(_amounts: uint256[N_COINS], _: bool) → uint256: view`
Calculate addition or reduction in token supply from a deposit or withdrawal. Returns the expected amount of LP tokens received. This calculation accounts for slippage, but not fees.
`N_COINS`: Number of coins in the pool.
| Input | Type | Description |
| --- | --- | --- |
| `amounts` | `uint256[N_COINS]` | Amount of each coin being deposited |
| `is_deposit` | `bool` | Set True for deposits, False for withdrawals |
**<>Source code▼**
```vyper
@view
@external
def calc_token_amount(amounts: uint256[N_COINS], is_deposit: bool) -> uint256:
"""
@notice Calculate addition or reduction in token supply from a deposit or withdrawal
@dev This calculation accounts for slippage, but not fees.
Needed to prevent front-running, not for precise calculations!
@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 = self._A()
_balances: uint256[N_COINS] = self.balances
D0: uint256 = self.get_D_mem(_balances, amp)
for i in range(N_COINS):
if is_deposit:
_balances[i] += amounts[i]
else:
_balances[i] -= amounts[i]
D1: uint256 = self.get_D_mem(_balances, amp)
token_amount: uint256 = ERC20(self.lp_token).totalSupply()
diff: uint256 = 0
if is_deposit:
diff = D1 - D0
else:
diff = D0 - D1
return diff * token_amount / D0
```
**▶Example▼**
```shell
>>> pool.calc_token_amount([10**2, 10**18], True)
1996887509167925969
```
<a id="add_liquidity"></a>
### `add_liquidity`
`StableSwap.add_liquidity(amounts: uint256[N_COINS], min_mint_amount: uint256) → uint256`
Deposit coins into the pool. Returns the amount of LP tokens received in exchange for the deposited tokens.
| Input | Type | Description |
| --- | --- | --- |
| `amounts` | `uint256[N_COINS]` | Amount of each coin being deposited 프로젝트로 돌아가기