bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 30쪽
|
| `min_mint_amount` | `uint256` | Minimum amount of LP tokens to mint from the deposit |
Emits: AddLiquidity
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def add_liquidity(amounts: uint256[N_COINS], min_mint_amount: uint256) -> uint256:
"""
@notice Deposit coins into the pool
@param amounts List of amounts of coins to deposit
@param min_mint_amount Minimum amount of LP tokens to mint from the deposit
@return Amount of LP tokens received by depositing
"""
assert not self.is_killed # dev: is killed
amp: uint256 = self._A()
_lp_token: address = self.lp_token
token_supply: uint256 = ERC20(_lp_token).totalSupply()
# Initial invariant
D0: uint256 = 0
old_balances: uint256[N_COINS] = self.balances
if token_supply > 0:
D0 = self.get_D_mem(old_balances, amp)
new_balances: uint256[N_COINS] = old_balances
for i in range(N_COINS):
if token_supply == 0:
assert amounts[i] > 0 # dev: initial deposit requires all coins
# balances store amounts of c-tokens
new_balances[i] = old_balances[i] + amounts[i]
# Invariant after change
D1: uint256 = self.get_D_mem(new_balances, amp)
assert D1 > D0
# We need to recalculate the invariant accounting for fees
# to calculate fair user's share
D2: uint256 = D1
fees: uint256[N_COINS] = empty(uint256[N_COINS])
if token_supply > 0:
# Only account for fees if we are not the first to deposit
_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1))
_admin_fee: uint256 = self.admin_fee
for i in range(N_COINS):
ideal_balance: uint256 = D1 * old_balances[i] / D0
difference: uint256 = 0
if ideal_balance > new_balances[i]:
difference = ideal_balance - new_balances[i]
else:
difference = new_balances[i] - ideal_balance
fees[i] = _fee * difference / FEE_DENOMINATOR
self.balances[i] = new_balances[i] - (fees[i] * _admin_fee / FEE_DENOMINATOR)
new_balances[i] -= fees[i]
D2 = self.get_D_mem(new_balances, amp)
else:
self.balances = new_balances
# Calculate, how much pool tokens to mint
mint_amount: uint256 = 0
if token_supply == 0:
mint_amount = D1 # Take the dust if there was any
else:
mint_amount = token_supply * (D2 - D0) / D0
assert mint_amount >= min_mint_amount, "Slippage screwed you"
# Take coins from the sender
for i in range(N_COINS):
if amounts[i] > 0:
# "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(amounts[i], bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool)
# Mint pool tokens
CurveToken(_lp_token).mint(msg.sender, mint_amount)
log AddLiquidity(msg.sender, amounts, fees, D1, token_supply + mint_amount)
return mint_amount
```
**▶Example▼**
```shell
>>> todo: add_liquidity console output example
```
<a id="remove_liquidity"></a>
### `remove_liquidity`
`StableSwap.remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS]) → uint256[N_COINS]`
Withdraw coins from the pool. Returns a list of the amounts for each coin that was withdrawn.
| Input | Type | Description |
| --- | --- | --- |
| `_amount` | `uint256` | Quantity of LP tokens to burn in the withdrawal |
| `min_amounts` | \`uint256\[N\_COINS\]\`\` | Minimum amounts of underlying coins to receive |
Emits: RemoveLiquidity
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def remove_liquidity(_amount: uint256, min_amounts: uint256[N_COINS]) -> uint256[N_COINS]:
"""
@notice Withdraw coins from the pool
@dev Withdrawal amounts are based on current deposit ratios
@param _amount Quantity of LP tokens to burn in the withdrawal
@param min_amounts Minimum amounts of underlying coins to receive
@return List of amounts of coins that were withdrawn
"""
_lp_token: address = self.lp_token
total_supply: uint256 = ERC20(_lp_token).totalSupply()
amounts: uint256[N_COINS] = empty(uint256[N_COINS])
fees: uint256[N_COINS] = empty(uint256[N_COINS]) # Fees are unused but we've got them historically in event
for i in range(N_COINS):
value: uint256 = self.balances[i] * _amount / total_supply
assert value >= min_amounts[i], "Withdrawal resulted in fewer coins than expected"
self.balances[i] -= value
amounts[i] = value
_response: Bytes[32] = raw_call(
self.coins[i],
concat(
method_id("transfer(address,uint256)"),
convert(msg.sender, bytes32),
convert(value, bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool)
CurveToken(_lp_token).burnFrom(msg.sender, _amount) # dev: insufficient funds
log RemoveLiquidity(msg.sender, amounts, fees, total_supply - _amount)
return amounts
```
**▶Example▼**
```shell
>>> todo: remove_liquidity console output example
```
<a id="remove_liquidity_imbalance"></a>
### `remove_liquidity_imbalance`
`StableSwap.remove_liquidity_imbalance(amounts: uint256[N_COINS], max_burn_amount: uint256) → uint256`
Withdraw coins from the pool in an imbalanced amount. Returns a list of the amounts for each coin that was withdrawn.
| Input | Type | Description |
| --- | --- | --- |
| `amounts` | `uint256[N_COINS]` | List of amounts of underlying coins to withdraw |
| `max_burn_amount` | `uint256` | Maximum amount of LP token to burn in the withdrawal |
Emits: RemoveLiquidityImbalance
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def remove_liquidity_imbalance(amounts: uint256[N_COINS], max_burn_amount: uint256) -> 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
@return Actual amount of the LP token burned in the withdrawal
"""
assert not self.is_killed # dev: is killed
amp: uint256 = self._A()
old_balances: uint256[N_COINS] = self.balances
new_balances: uint256[N_COINS] = old_balances
D0: uint256 = self.get_D_mem(old_balances, amp)
for i in range(N_COINS):
new_balances[i] -= amounts[i]
D1: uint256 = self.get_D_mem(new_balances, amp)
_lp_token: address = self.lp_token
token_supply: uint256 = ERC20(_lp_token).totalSupply()
assert token_supply != 0 # dev: zero total supply
_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1))
_admin_fee: uint256 = self.admin_fee
fees: uint256[N_COINS] = empty(uint256[N_COINS])
for i in range(N_COINS):
ideal_balance: uint256 = D1 * old_balances[i] / D0
difference: uint256 = 0
if ideal_balance > new_balances[i]:
difference = ideal_balance - new_balances[i]
else:
difference = new_balances[i] - ideal_balance
fees[i] = _fee * difference / FEE_DENOMINATOR
self.balances[i] = new_balances[i] - (fees[i] * _admin_fee / FEE_DENOMINATOR)
new_balances[i] -= fees[i]
D2: uint256 = self.get_D_mem(new_balances, amp)
token_amount: uint256 = (D0 - D2) * token_supply / D0
assert token_amount != 0 # dev: zero tokens burned
token_amount += 1 # In case of rounding errors - make it unfavorable for the "attacker"
assert token_amount <= max_burn_amount, "Slippage screwed you"
CurveToken(_lp_token).burnFrom(msg.sender, token_amount) # dev: insufficient funds
for i in range(N_COINS):
if amounts[i] != 0:
_response: Bytes[32] = raw_call(
self.coins[i],
concat(
method_id("transfer(address,uint256)"),
convert(msg.sender, bytes32),
convert(amounts[i], bytes32),
),
max_outsize=32,
) # dev: failed transfer
if len(_response) > 0:
assert convert(_response, bool)
log RemoveLiquidityImbalance(msg.sender, amounts, fees, D1, token_supply - token_amount)
return token_amount
```
**▶Example▼**
```shell
>>> todo: remove_liquidity_imbalance console output example
```
<a id="calc_withdraw_one_coin"></a>
### `calc_withdraw_one_coin`
`StableSwap.calc_withdraw_one_coin(_token_amount: uint256, i: int128) → uint256`
Calculate the amount received when withdrawing a single coin.
| Input | Type | Description |
| --- | --- | --- |
| `_token_amount` | `uint256` | Amount of LP tokens to burn in the withdrawal |
| `i` | `int128` | Index value of the coin to withdraw |
**<>Source code▼**
```vyper
@view
@internal
def _calc_withdraw_one_coin(_token_amount: uint256, i: int128) -> (uint256, uint256, uint256):
# First, need to calculate
# * Get current D
# * Solve Eqn against y_i for D - _token_amount
amp: uint256 = self._A()
xp: uint256[N_COINS] = self._xp()
D0: uint256 = self.get_D(xp, amp)
total_supply: uint256 = ERC20(self.lp_token).totalSupply()
D1: uint256 = D0 - _token_amount * D0 / total_supply
new_y: uint256 = self.get_y_D(amp, i, xp, D1)
xp_reduced: uint256[N_COINS] = xp
_fee: uint256 = self.fee * N_COINS / (4 * (N_COINS - 1))
for j in range(N_COINS):
dx_expected: uint256 = 0
if j == i:
dx_expected = xp[j] * D1 / D0 - new_y
else:
dx_expected = xp[j] - xp[j] * D1 / D0
xp_reduced[j] -= _fee * dx_expected / FEE_DENOMINATOR
dy: uint256 = xp_reduced[i] - self.get_y_D(amp, i, xp_reduced, D1)
precisions: uint256[N_COINS] = PRECISION_MUL
dy = (dy - 1) / precisions[i] # Withdraw less to account for rounding errors
dy_0: uint256 = (xp[i] - new_y) / precisions[i] # w/o fees
return dy, dy_0 - dy, total_supply
@view
@external
def calc_withdraw_one_coin(_token_amount: uint256, i: int128) -> uint256:
"""
@notice Calculate the amount received when withdrawing a single coin
@param _token_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(_token_amount, i)[0]
```
**▶Example▼**
```shell
>>> todo: calculate_withdraw_one_coin console output example
```
<a id="remove_liquidity_one_coin"></a>
### `remove_liquidity_one_coin`
`StableSwap.remove_liquidity_one_coin(_token_amount: uint256, i: int128, _min_amount: uint256) → uint256`
Withdraw a single coin from the pool. Returns the amount of coin `i` received.
| Input | Type | Description |
| --- | --- | --- |
| `_token_amount` | `uint256` | Amount of LP tokens to burn in the withdrawal |
| `i` | `int128` | Index value of the coin to withdraw |
| `_min_amount` | `uint256` | Minimum amount of coin to receive |
Emits: RemoveLiquidityOne
**<>Source code▼**
```vyper
@external
@nonreentrant('lock')
def remove_liquidity_one_coin(_token_amount: uint256, i: int128, _min_amount: uint256) -> uint256:
"""
@notice Withdraw a single coin from the pool
@param _token_amount Amount of LP tokens to burn in the withdrawal
@param i Index value of the coin to withdraw
@param _min_amount Minimum amount of coin to receive
@return Amount of coin received
"""
assert not self.is_killed # dev: is killed
dy: uint256 = 0
dy_fee: uint256 = 0
total_supply: uint256 = 0
dy, dy_fee, total_supply = self._calc_withdraw_one_coin(_token_amount, i)
assert dy >= _min_amount, "Not enough coins removed"
self.balances[i] -= (dy + dy_fee * self.admin_fee / FEE_DENOMINATOR)
CurveToken(self.lp_token).burnFrom(msg.sender, _token_amount) # dev: insufficient funds
_response: Bytes[32] = raw_call(
self.coins[i],
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 RemoveLiquidityOne(msg.sender, _token_amount, dy, total_supply - _token_amount)
return dy
```
**▶Example▼**
```shell
>>> todo: remove_liquidity_one_coin console output example
```
---
# Curve Registry Exchange Contract
Source: [https://docs.curve.finance/developer/amm/router/curve-registry-exchange](https://docs.curve.finance/developer/amm/router/curve-registry-exchange)
The `CurveRegistryExchange` contract serves as a router for Curve liquidity pools. Users can utilize this contract to find pools, query exchange rates, and execute swaps directly.
Outdated: Does not consider all liquidity pools
The `CurveRegistryExchange` contract was deployed in December 2022 at [`0x99a58482bd75cbab83b27ec03ca68ff489b5788f`](https://etherscan.io/address/0x99a58482bd75cbab83b27ec03ca68ff489b5788f#code) on the Ethereum Mainnet. This contract does not support all pools due to newer versions of exchange contracts.
A new and updated version is available here: [`CurveRouterNG`](https://docs.curve.finance/developer/amm/router/curve-router-ng.md).
* * *
<a id="exchanging-tokens"></a>
## Exchanging Tokens
warning
This contract only considers liquidity sources that have been added to it. These sources are primarily the liquidity pools registered in `factory_registry` and `crypto_registry`.
*The contract offers three distinct functions to facilitate token exchanges:*
- [`exchange`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#exchange_multiple): Conducts a regular exchange using a specified pool.
- [`exchange_with_best_rate`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#exchange_with_best_rate): Executes a token exchange using the pool that offers the best rate.
- [`exchange_multiple`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#exchange_multiple): Allows up to four token exchanges in a single transaction.
Additionally, there are helper functions available to retrieve essential data, such as [`get_exchange_amount`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#get_exchange_amount), [`get_best_rate`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#get_best_rate), or [`get_exchange_multiple_amount`](https://docs.curve.finance/developer/amm/router/curve-registry-exchange.md#get_exchange_multiple_amount).
<a id="exchange"></a>
### `exchange`
`CurveRegistryExchange.exchange(_pool: address, _from: address, _to: address, _amount: uint256, _expected: uint256, _receiver: address = msg.sender) -> uint256`
Function to perform a token exchange using a specific pool. Prior to calling this function, the caller must approve this contract to transfer `_amount` of coins from `_from`.
| Input | Type | Description |
| --- | --- | --- |
| `_pool` | `address` | Address of the pool to use for the token exchange. |
| `_from` | `address` | Address of the coin being sent. |
| `_to` | `address` | Address of the coin being received. |
| `_amount` | `uint256` | Amount of coins to exchange. |
| `_expected` | `uint256` | Minimum amount of coins to receive. |
| `_receiver` | `address` | Receiver of the tokens. Defaults to `msg.sender`. |
Returns: amount received (`uint256`)
Emits: `TokenExchange`
**<>Source code▼**
```vyper
event TokenExchange:
buyer: indexed(address)
receiver: indexed(address)
pool: indexed(address)
token_sold: address
token_bought: address
amount_sold: uint256
amount_bought: uint256
@payable
@external
@nonreentrant("lock")
def exchange(
_pool: address,
_from: address,
_to: address,
_amount: uint256,
_expected: uint256,
_receiver: address = msg.sender,
) -> uint256:
"""
@notice Perform an exchange using a specific pool
@dev Prior to calling this function, the caller must approve
this contract to transfer `_amount` coins from `_from`
Works for both regular and factory-deployed pools
@param _pool Address of the pool to use for the swap
@param _from Address of coin being sent
@param _to Address of coin being received
@param _amount Quantity of `_from` being sent
@param _expected Minimum quantity of `_from` received
in order for the transaction to succeed
@param _receiver Address to transfer the received tokens to
@return uint256 Amount received
"""
if _from == ETH_ADDRESS:
assert _amount == msg.value, "Incorrect ETH amount"
else:
assert msg.value == 0, "Incorrect ETH amount"
if Registry(self.crypto_registry).get_lp_token(_pool) != ZERO_ADDRESS:
return self._crypto_exchange(_pool, _from, _to, _amount, _expected, msg.sender, _receiver)
registry: address = self.registry
if Registry(registry).get_lp_token(_pool) == ZERO_ADDRESS:
registry = self.factory_registry
return self._exchange(registry, _pool, _from, _to, _amount, _expected, msg.sender, _receiver)
@internal
def _crypto_exchange(
_pool: address,
_from: address,
_to: address,
_amount: uint256,
_expected: uint256,
_sender: address,
_receiver: address,
) -> uint256:
assert not self.is_killed
initial: address = _from
target: address = _to
if _from == ETH_ADDRESS:
initial = WETH_ADDRESS
if _to == ETH_ADDRESS:
target = WETH_ADDRESS
eth_amount: uint256 = 0
received_amount: uint256 = 0
i: uint256 = 0
j: uint256 = 0
i, j = CryptoRegistry(self.crypto_registry).get_coin_indices(_pool, initial, target) # dev: no market
# perform / verify input transfer
if _from == ETH_ADDRESS:
eth_amount = _amount
else:
response: Bytes[32] = raw_call(
_from,
_abi_encode(
_sender,
self,
_amount,
method_id=method_id("transferFrom(address,address,uint256)"),
),
max_outsize=32,
)
if len(response) != 0:
assert convert(response, bool)
# approve input token
if not self.is_approved[_from][_pool]:
response: Bytes[32] = raw_call(
_from,
_abi_encode(
_pool,
MAX_UINT256,
method_id=method_id("approve(address,uint256)"),
),
max_outsize=32,
)
if len(response) != 0:
assert convert(response, bool)
self.is_approved[_from][_pool] = True
# perform coin exchange
if ETH_ADDRESS in [_from, _to]:
CryptoPoolETH(_pool).exchange(i, j, _amount, _expected, True, value=eth_amount)
else:
CryptoPool(_pool).exchange(i, j, _amount, _expected)
# perform output transfer
if _to == ETH_ADDRESS:
received_amount = self.balance
raw_call(_receiver, b"", value=self.balance)
else:
received_amount = ERC20(_to).balanceOf(self)
response: Bytes[32] = raw_call(
_to,
_abi_encode(
_receiver,
received_amount,
method_id=method_id("transfer(address,uint256)"),
),
max_outsize=32,
)
if len(response) != 0:
assert convert(response, bool)
log TokenExchange(_sender, _receiver, _pool, _from, _to, _amount, received_amount)
return received_amount
@internal
def _exchange(
_registry: address,
_pool: address,
_from: address,
_to: address,
_amount: uint256,
_expected: uint256,
_sender: address,
_receiver: address,
) -> uint256:
assert not self.is_killed
eth_amount: uint256 = 0
received_amount: uint256 = 0
i: int128 = 0
j: int128 = 0
is_underlying: bool = False
i, j, is_underlying = Registry(_registry).get_coin_indices(_pool, _from, _to) # dev: no market
if is_underlying and _registry == self.factory_registry:
if Registry(_registry).is_meta(_pool):
base_coins: address[2] = self.base_coins[_pool]
if base_coins[0] == empty(address) and base_coins[1] == empty(address):
base_coins = [CurvePool(_pool).coins(0), CurvePool(_pool).coins(1)]
self.base_coins[_pool] = base_coins
# we only need to use exchange underlying if the input or output is not in the base coins
is_underlying = _from not in base_coins or _to not in base_coins
else:
# not a metapool so no underlying exchange method
is_underlying = False
# perform / verify input transfer
if _from == ETH_ADDRESS:
eth_amount = _amount
else:
response: Bytes[32] = raw_call(
_from,
_abi_encode(
_sender,
self,
_amount,
method_id=method_id("transferFrom(address,address,uint256)"),
),
max_outsize=32,
)
if len(response) != 0:
assert convert(response, bool)
# approve input token
if _from != ETH_ADDRESS and not self.is_approved[_from][_pool]:
response: Bytes[32] = raw_call(
_from,
_abi_encode(
_pool,
MAX_UINT256,
method_id=method_id("approve(address,uint256)"),
),
max_outsize=32,
)
if len(response) != 0:
assert convert(response, bool)
self.is_approved[_from][_pool] = True
# perform coin exchange
if is_underlying:
CurvePool(_pool).exchange_underlying(i, j, _amount, _expected, value=eth_amount)
else:
CurvePool(_pool).exchange(i, j, _amount, _expected, value=eth_amount)
# perform output transfer
if _to == ETH_ADDRESS:
received_amount = self.balance
raw_call(_receiver, b"", value=self.balance)
e프로젝트로 돌아가기