bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 36쪽
Description |
| --- | --- | --- |
| `coin_metapool_idx` | `int128` | Metapool index of the input coin. |
| `coin_basepool_idx` | `int128` | Basepool index of the input coin. |
| `dx` | `uint256` | Amount to transfer in. |
| `sender` | `address` | Address to transfer coins from. |
| `expect_optimistic_transfer` | `bool` | `True` if the contract expects an optimistic coin transfer (see [`exchange_received()`](https://docs.curve.finance/developer/amm/stableswap-ng/pools/metapool.md#exchange_received)). |
| `is_base_pool_swap` | `bool` | If the exchange is a basepool swap (if `i and i > 0`); defaulted to `False`. |
```vyper
@internal
def _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:
"""
@notice Contains all logic to handle ERC20 token transfers.
@param coin_metapool_idx metapool index of input coin
@param coin_basepool_idx basepool index of input coin
@param dx amount of `_coin` to transfer into the pool.
@param sender address to transfer `_coin` from.
@param expect_optimistic_transfer True if contract expects an optimistic coin transfer
@param is_base_pool_swap Default is set to False.
@return amount of coins received
"""
_input_coin: ERC20 = ERC20(coins[coin_metapool_idx])
_stored_balance: uint256 = self.stored_balances[coin_metapool_idx]
_input_coin_is_in_base_pool: bool = False
# Check if _transfer_in is being called by _exchange_underlying:
if coin_basepool_idx >= 0 and coin_metapool_idx == 1:
_input_coin = ERC20(BASE_COINS[coin_basepool_idx])
_input_coin_is_in_base_pool = True
_dx: uint256 = _input_coin.balanceOf(self)
# ------------------------- Handle Transfers -----------------------------
if expect_optimistic_transfer:
if not _input_coin_is_in_base_pool:
_dx = _dx - _stored_balance
assert _dx >= dx # dev: pool did not receive tokens for swap
else:
assert dx > 0 # dev : do not transferFrom 0 tokens into the pool
assert _input_coin.transferFrom(
sender,
self,
dx,
default_return_value=True
)
_dx = _input_coin.balanceOf(self) - _dx
# ------------ Check if liquidity needs to be added somewhere ------------
if _input_coin_is_in_base_pool:
if is_base_pool_swap:
return _dx # <----- _exchange_underlying: all input goes to swap.
# So, we will not increment self.stored_balances for metapool_idx.
# Swap involves base <> meta pool interaction. Add incoming base pool
# token to the base pool, mint _dx base pool LP token (idx 1) and add
# that to self.stored_balances and return that instead.
_dx = self._meta_add_liquidity(_dx, coin_basepool_idx)
# ----------------------- Update Stored Balances -------------------------
self.stored_balances[coin_metapool_idx] += _dx
return _dx
@internal
def _meta_add_liquidity(dx: uint256, base_i: int128) -> uint256:
coin_i: address = coins[MAX_METAPOOL_COIN_INDEX]
x: uint256 = ERC20(coin_i).balanceOf(self)
if BASE_N_COINS == 2:
base_inputs: uint256[2] = empty(uint256[2])
base_inputs[base_i] = dx
StableSwap2(BASE_POOL).add_liquidity(base_inputs, 0)
if BASE_N_COINS == 3:
base_inputs: uint256[3] = empty(uint256[3])
base_inputs[base_i] = dx
StableSwap3(BASE_POOL).add_liquidity(base_inputs, 0)
return ERC20(coin_i).balanceOf(self) - x
```
- **`_transfer_out()`**
**▶\`\_transfer\_out(\_coin\_idx: int128, \_amount: uint256, receiver: address):\`▼**
| Input | Type | Description |
| --- | --- | --- |
| `coin_idx` | `int128` | Index value of the token to transfer out. |
| `_amount` | `uint256` | Amount to transfer out. |
| `receiver` | `address` | Address to send the tokens to. |
```vyper
stored_balances: DynArray[uint256, MAX_COINS]
@internal
def _transfer_out(
_coin_idx: int128, _amount: uint256, receiver: address
):
"""
@notice Transfer a single token from the pool to receiver.
@param _coin_idx Index of the token to transfer out
@param _amount Amount of token to transfer out
@param receiver Address to send the tokens to
"""
coin_balance: uint256 = ERC20(coins[_coin_idx]).balanceOf(self)
# ------------------------- Handle Transfers -----------------------------
assert ERC20(coins[_coin_idx]).transfer(
receiver, _amount, default_return_value=True
)
# ----------------------- Update Stored Balances -------------------------
self.stored_balances[_coin_idx] = coin_balance - _amount
```
Methods with underlying coins
In metapools, `coin[0]` is always the metapool token, and `coin[1]` is always the basepool token. When working with the basepool underlying tokens such as `exchange_underlying` and others, the coin indices of the basepool are appended after `coin[0]`, which is the metapool token.
E.g., in the USDV<>3CRV pool: `coin[0]` = USDV, `coin[1]` = DAI, `coin[2]` = USDC, and `coin[3]` = USDT.
* * *
<a id="exchange-methods"></a>
## Exchange Methods
*Three functions for token exchanges:*
- The regular `exchange` function.
- A novel `exchange_received` function that executes a token exchange based on the internal balances of the pool.
- Additionally, the metapool implementation includes an `exchange_underlying` function, which allows tokens to be exchanged with the underlying tokens the asset is paired against. For example, swapping USDV for USDT in the USDV<>3CRV pool.
<a id="exchange"></a>
### `exchange`
`StableSwap.exchange(i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address = msg.sender) -> uint256:`
warning
This exchange swaps between the metapool token and the basepool LP token. coin\[0\] is always the metapool token and coin\[1\] is the basepool LP token. To exchange the metapool token against underlying coins, one needs to use the `exchange_underlying` function.
Function to exchange `_dx` amount of coin `i` for coin `j` and receive a minimum amount of `_min_dy`.
Returns: amount of output coin received (`uint256`).
Emits: `TokenExchange`
| Input | Type | Description |
| --- | --- | --- |
| `i` | `int128` | Index value of the input coin. |
| `j` | `int128` | Index value of the output coin. |
| `_dx` | `uint256` | Amount of coin `i` being exchanged. |
| `_min_dy` | `uint256` | Minimum amount of coin `j` to receive. |
| `_receiver` | `address` | Receiver of the output tokens; defaults to msg.sender. |
**<>Source code▼**
```vyper
event TokenExchange:
buyer: indexed(address)
sold_id: int128
tokens_sold: uint256
bought_id: int128
tokens_bought: uint256
@external
@nonreentrant('lock')
def exchange(
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
_receiver: address = msg.sender,
) -> 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 value 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
"""
return self._exchange(
msg.sender,
i,
j,
_dx,
_min_dy,
_receiver,
False
)
@internal
def _exchange(
sender: address,
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
receiver: address,
expect_optimistic_transfer: bool
) -> uint256:
assert i != j # dev: coin index out of range
assert _dx > 0 # dev: do not exchange 0 coins
rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
old_balances: DynArray[uint256, MAX_COINS] = self._balances()
xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances)
# --------------------------- Do Transfer in -----------------------------
# `dx` is whatever the pool received after ERC20 transfer:
dx: uint256 = self._transfer_in(
i,
-1, # <----- we're not handling underlying coins here.
_dx,
sender,
expect_optimistic_transfer
)
# ------------------------------- Exchange -------------------------------
# xp[i] + dx * rates[i] / PRECISION
x: uint256 = xp[i] + unsafe_div(dx * rates[i], PRECISION)
dy: uint256 = self.__exchange(x, xp, rates, i, j)
assert dy >= _min_dy, "Exchange resulted in fewer coins than expected"
# --------------------------- Do Transfer out ----------------------------
self._transfer_out(j, dy, receiver)
# ------------------------------------------------------------------------
log TokenExchange(msg.sender, i, _dx, j, dy)
return dy
@internal
def __exchange(
x: uint256,
_xp: DynArray[uint256, MAX_COINS],
rates: DynArray[uint256, MAX_COINS],
i: int128,
j: int128,
) -> uint256:
amp: uint256 = self._A()
D: uint256 = math.get_D(_xp, amp, N_COINS)
y: uint256 = math.get_y(i, j, x, _xp, amp, D, N_COINS)
dy: uint256 = _xp[j] - y - 1 # -1 just in case there were some rounding errors
dy_fee: uint256 = dy * self._dynamic_fee((_xp[i] + x) / 2, (_xp[j] + y) / 2, self.fee) / FEE_DENOMINATOR
# Convert all to real units
dy = (dy - dy_fee) * PRECISION / rates[j]
self.admin_balances[j] += (
unsafe_div(dy_fee * admin_fee, FEE_DENOMINATOR) # dy_fee * admin_fee / FEE_DENOMINATOR
) * PRECISION / rates[j]
# Calculate and store state prices:
xp: DynArray[uint256, MAX_COINS] = _xp
xp[i] = x
xp[j] = y
# D is not changed because we did not apply a fee
self.upkeep_oracles(xp, amp, D)
return dy
```
**▶Example▼**
```shell
>>> StableSwap.get_balances()
[4183467888075, 2556883713184291687567176]
>>> StableSwap.exchange(0, 1, 10**6, 0)
971169724887534588
>>> StableSwap.get_balances()
[4183468888075, 2556882741963895491313748]
```
<a id="exchange_received"></a>
### `exchange_received`
`StableSwap.exchange_received(i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address) -> uint256:`
danger
`exchange_received` will revert if the pool contains a rebasing asset. A pool that contains a rebasing token should have an `asset_type` of 2. If this is not the case, the pool is using an incorrect implementation, and rebases can be stolen.
Function to exchange `_dx` amount of coin `i` for coin `j`, receiving a minimum amount of `_min_dy`. This is done without actually transferring the coins into the pool within the same call. The exchange is based on the change in the balance of coin `i`, eliminating the need to grant approval to the contract. This function does only swap between the token paird against the basepool and the basepool tokens. The method can not be used to exchange for underlying coins of the basepool.
\*\*A detailed article can be found here: [https://blog.curvemonitor.com/posts/exchange-received/.\*\*Returns](https://blog.curvemonitor.com/posts/exchange-received/.**Returns): amount of output coin received (`uint256`).
Emits: `TokenExchange`
| Input | Type | Description |
| --- | --- | --- |
| `i` | `int128` | Index value of input coin. |
| `j` | `int128` | Index value of output coin. |
| `_dx` | `uint256` | Amount of coin `i` being exchanged. |
| `_min_dy` | `uint256` | Minimum amount of coin `j` to receive. |
| `_receiver` | `address` | Receiver of the output tokens; defaults to `msg.sender`. |
**<>Source code▼**
```vyper
event TokenExchange:
buyer: indexed(address)
sold_id: int128
tokens_sold: uint256
bought_id: int128
tokens_bought: uint256
@external
@nonreentrant('lock')
def exchange_received(
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
_receiver: address,
) -> uint256:
"""
@notice Perform an exchange between two coins without transferring token in
@dev The contract swaps tokens based on a change in balance of coin[i]. The
dx = ERC20(coin[i]).balanceOf(self) - self.stored_balances[i]. Users of
this method are dex aggregators, arbitrageurs, or other users who do not
wish to grant approvals to the contract: they would instead send tokens
directly to the contract and call `exchange_received`.
Note: This is disabled if pool contains rebasing tokens.
@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 POOL_IS_REBASING_IMPLEMENTATION # dev: exchange_received not supported if pool contains rebasing tokens
return self._exchange(
msg.sender,
i,
j,
_dx,
_min_dy,
_receiver,
True, # <--------------------------------------- swap optimistically.
)
@internal
def _exchange(
sender: address,
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
receiver: address,
expect_optimistic_transfer: bool
) -> uint256:
assert i != j # dev: coin index out of range
assert _dx > 0 # dev: do not exchange 0 coins
rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
old_balances: DynArray[uint256, MAX_COINS] = self._balances()
xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances)
# --------------------------- Do Transfer in -----------------------------
# `dx` is whatever the pool received after ERC20 transfer:
dx: uint256 = self._transfer_in(
i,
-1, # <----- we're not handling underlying coins here.
_dx,
sender,
expect_optimistic_transfer
)
# ------------------------------- Exchange -------------------------------
# xp[i] + dx * rates[i] / PRECISION
x: uint256 = xp[i] + unsafe_div(dx * rates[i], PRECISION)
dy: uint256 = self.__exchange(x, xp, rates, i, j)
assert dy >= _min_dy, "Exchange resulted in fewer coins than expected"
# --------------------------- Do Transfer out ----------------------------
self._transfer_out(j, dy, receiver)
# ------------------------------------------------------------------------
log TokenExchange(msg.sender, i, _dx, j, dy)
return dy
@internal
def __exchange(
x: uint256,
_xp: DynArray[uint256, MAX_COINS],
rates: DynArray[uint256, MAX_COINS],
i: int128,
j: int128,
) -> uint256:
amp: uint256 = self._A()
D: uint256 = math.get_D(_xp, amp, N_COINS)
y: uint256 = math.get_y(i, j, x, _xp, amp, D, N_COINS)
dy: uint256 = _xp[j] - y - 1 # -1 just in case there were some rounding errors
dy_fee: uint256 = dy * self._dynamic_fee((_xp[i] + x) / 2, (_xp[j] + y) / 2, self.fee) / FEE_DENOMINATOR
# Convert all to real units
dy = (dy - dy_fee) * PRECISION / rates[j]
self.admin_balances[j] += (
unsafe_div(dy_fee * admin_fee, FEE_DENOMINATOR) # dy_fee * admin_fee / FEE_DENOMINATOR
) * PRECISION / rates[j]
# Calculate and store state prices:
xp: DynArray[uint256, MAX_COINS] = _xp
xp[i] = x
xp[j] = y
# D is not changed because we did not apply a fee
self.upkeep_oracles(xp, amp, D)
return dy
```
**▶Example▼**
```shell
>>> USDV.transfer("0xc273fd237F23cb13296D0Cc2897F0B7A61e83387", 10**6)
>>> StableSwap.received(0, 1, 10**6, 0)
998545692103751082
```
note
More information on this method [here](https://docs.curve.finance/developer/amm/stableswap-ng/overview.md#exchange_received).
<a id="exchange_underlying"></a>
### `exchange_underlying`
`StableSwap.exchange_underlying(i: int128, j: int128, _dx: uint256, _min_dy: uint256, _receiver: address = msg.sender) -> uint256:`
Function to exchange `_dx` amount of the underlying coin `i` for the underlying coin `j` and receive a minimum amount of `_min_dy`. Index values are the `coins` followed by the `base_coins`, where the base pool LP token is not included as a value.
Returns: amount of output coin received (`uint256`).
Emits: `TokenExchangeUnderlying`
| Input | Type | Description |
| --- | --- | --- |
| `i` | `int128` | Index value of underlying input coin. |
| `j` | `int128` | Index value of underlying output coin. |
| `_dx` | `uint256` | Amount of coin `i` being exchanged. |
| `_min_dy` | `uint256` | Minimum amount of coin `j` to receive. |
| `receiver` | `address` | Receiver of the output tokens; defaults to msg.sender. |
**<>Source code▼**
```vyper
event TokenExchangeUnderlying:
buyer: indexed(address)
sold_id: int128
tokens_sold: uint256
bought_id: int128
tokens_bought: uint256
@external
@nonreentrant('lock')
def exchange_underlying(
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
_receiver: address = msg.sender,
) -> uint256:
"""
@notice Perform an exchange between two underlying coins
@param i Index value for the underlying coin to send
@param j Index value of the underlying coin to receive
@param _dx Amount of `i` being exchanged
@param _min_dy Minimum amount of `j` to receive
@param _receiver Address that receives `j`
@return Actual amount of `j` received
"""
return self._exchange_underlying(
msg.sender,
i,
j,
_dx,
_min_dy,
_receiver,
False
)
@internal
def _exchange_underlying(
sender: address,
i: int128,
j: int128,
_dx: uint256,
_min_dy: uint256,
receiver: address,
expect_optimistic_transfer: bool = False
) -> uint256:
rates: DynArray[uint256, MAX_COINS] = self._stored_rates()
old_balances: DynArray[uint256, MAX_COINS] = self._balances()
xp: DynArray[uint256, MAX_COINS] = self._xp_mem(rates, old_balances)
dy: uint256 = 0
base_i: int128 = 0
base_j: int128 = 0
meta_i: int128 = 0
meta_j: int128 = 0
x: uint256 = 0
output_coin: address = empty(address)
# ------------------------ Determine coin indices ------------------------
# Get input coin indices:
if i > 0:
base_i = i - MAX_METAPOOL_COIN_INDEX
meta_i = 1
# Get output coin and indices:
if j == 0:
output_coin = coins[0]
else:
base_j = j - MAX_METAPOOL_COIN_INDEX
meta_j = 1
output_coin = BASE_COINS[base_j]
# --------------------------- Do Transfer in -----------------------------
# If incoming coin is supposed to go to the base pool, the _transfer_in
# method will add_liquidity in the base pool and return dx_w_fee LP tokens
dx_w_fee: uint256 = self._transfer_in(
meta_i,
base_i,
_dx,
sender,
expect_optimistic_transfer,
(i > 0 and j > 0), # <--- if True: do not add liquidity to base pool.
)
# ------------------------------- Exchange -------------------------------
if i == 0 or j == 0: # meta swap
if i == 0:
# xp[i] + dx_w_fee * rates[i] / PRECISION
x = xp[i] + unsafe_div(dx_w_fee * rates[i], PRECISION)
else:
# dx_w_fee is the number of base_pool LP tokens minted after
# base_pool.add_liquidity in self._transfer_in
# dx_w_fee * rates[MAX_METAPOOL_COIN_INDEX] / PRECISION
x = unsafe_div(dx_w_fee * rates[MAX_METAPOOL_COIN_INDEX], PRECISION)
x += xp[MAX_METAPOOL_COIN_INDEX]
dy = self.__exchange(x, xp, rates, meta_i, meta_j)
# Adjust stored balances of meta-level tokens:
self.stored_balances[meta_j] -= dy
# Withdraw from the base pool if needed
if j > 0:
out_amount: uint256 = ERC20(output_coin).balanceOf(self)
StableSwap(BASE_POOL).remove_liquidity_one_coin(dy, base_j, 0)
dy = ERC20(output_coin).balanceOf(self) - out_amount
assert dy >= _min_dy
else: # base pool swap (user should swap at base pool for better gas)
dy = ERC20(output_coin).balanceOf(self)
StableSwap(BASE_POOL).exchange(base_i, base_j, dx_w_fee, _min_dy)
dy = ERC20(output_coin).balanceOf(self) - dy
# --------------------------- Do Transfer out ----------------------------
assert ERC20(output_coin).transfer(receiver, dy, default_return_value=True)
# ------------------------------------------------------------------------
log TokenExchangeUnderlying(sender, i, _dx, j, dy)
return dy
@internal
def __exchange(
x: uint256,
_xp: DynArray[uint256, MAX_COINS],
rates: DynArray[uint256, MAX_COINS],
i: int128,
j: int128,
) -> uint256:
amp: uint256 = self._A()
D: uint256 = math.get_D(_xp, amp, N_COINS)
y: uint256 = math.get_y(i, j, x, _xp, amp, D, N_COINS)
dy: uint256 = _xp[j] - y - 1 # -1 just in case there were some rounding errors
dy_fee: uint256 = dy * self._dynamic_fee((_xp[i] + x) / 2, (_xp[j] + y) / 2, self.fee) / FEE_DENOMINATOR
# Convert all to real units
dy = (dy - dy_fee) * PRECISION / rates[j]
self.admin_balances[j] += (
unsafe_div(dy_fee * admin_fee, FEE_DENOMINATOR) # dy_fee * admin_fee / FEE_DENOMINATOR
) * PRECISION / rates[j]
# Calculate and store state prices:
xp: DynArray[uint256, MAX_COINS] = _xp
xp[i] = x
xp[j] = y
# D is not changed because we did not apply a fee
self.upkeep_oracles(xp, amp, D)
return dy
```
**▶Example▼**
```she프로젝트로 돌아가기