bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 58쪽
ce_scale_i = p * xp[i]
xp[k] = xp[k] * xx[k] * p / PRECISION
if Curve(swap).future_A_gamma_time() > block.timestamp:
D0 = math.newton_D(A, gamma, xp, 0)
else:
D0 = Curve(swap).D()
D: uint256 = D0
fee: uint256 = self._fee(xp, swap)
dD: uint256 = token_amount * D / token_supply
D_fee: uint256 = fee * dD / (2 * 10**10) + 1
approx_fee: uint256 = N_COINS * D_fee * xx[i] / D
D -= (dD - D_fee)
y_out: uint256[2] = math.get_y(A, gamma, xp, D, i)
dy: uint256 = (xp[i] - y_out[0]) * PRECISION / price_scale_i
xp[i] = y_out[0]
return dy, approx_fee
```
**▶Example▼**
```shell
>>> ViewMethodContract.calc_fee_withdraw_one_coin(10000000000, 2, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4")
1176331
```
<a id="calc_fee_token_amount"></a>
### `calc_fee_token_amount`
`ViewMethodContract.calc_fee_token_amount(amounts: uint256[N_COINS], deposit: bool, swap: address) -> uint256:`
Function to calculate the fees for `calc_token_amount`.
| Input | Type | Description |
| --- | --- | --- |
| `amounts` | `uint256[N_COINS]` | LP token amount |
| `deposit` | `bool` | `True` = deposit, `False` = withdraw |
| `swap` | `address` | Pool contract address |
Returns: fee (`uint256`).
**<>Source code▼**
```vyper
@view
@external
def calc_fee_token_amount(
amounts: uint256[N_COINS], deposit: bool, swap: address
) -> uint256:
d_token: uint256 = 0
amountsp: uint256[N_COINS] = empty(uint256[N_COINS])
xp: uint256[N_COINS] = empty(uint256[N_COINS])
d_token, amountsp, xp = self._calc_dtoken_nofee(amounts, deposit, swap)
return Curve(swap).calc_token_fee(amountsp, xp) * d_token / 10**10 + 1
@internal
@view
def _calc_dtoken_nofee(
amounts: uint256[N_COINS], deposit: bool, swap: address
) -> (uint256, uint256[N_COINS], uint256[N_COINS]):
math: Math = Curve(swap).MATH()
xp: uint256[N_COINS] = empty(uint256[N_COINS])
precisions: uint256[N_COINS] = empty(uint256[N_COINS])
price_scale: uint256[N_COINS-1] = empty(uint256[N_COINS-1])
D0: uint256 = 0
token_supply: uint256 = 0
A: uint256 = 0
gamma: uint256 = 0
xp, D0, token_supply, price_scale, A, gamma, precisions = self._prep_calc(swap)
amountsp: uint256[N_COINS] = amounts
if deposit:
for k in range(N_COINS):
xp[k] += amounts[k]
else:
for k in range(N_COINS):
xp[k] -= amounts[k]
xp[0] *= precisions[0]
amountsp[0] *= precisions[0]
for k in range(N_COINS - 1):
p: uint256 = price_scale[k] * precisions[k + 1]
xp[k + 1] = xp[k + 1] * p / PRECISION
amountsp[k + 1] = amountsp[k + 1] * p / PRECISION
D: uint256 = math.newton_D(A, gamma, xp, 0)
d_token: uint256 = token_supply * D / D0
if deposit:
d_token -= token_supply
else:
d_token = token_supply - d_token
return d_token, amountsp, xp
```
**▶Example▼**
```shell
>>> ViewMethodContract.calc_fee_token_amount([1,1,1], 0, "0xf5f5B97624542D72A9E06f04804Bf81baA15e2B4")
48166379
```
---
# overview
Source: [https://docs.curve.finance/developer/amm/twocrypto-ng/overview](https://docs.curve.finance/developer/amm/twocrypto-ng/overview)
The **Twocrypto-NG contract infrastructure** represents an **optimized version of Curve Finance Crypto pools**.
Contract Source & Deployment
Source code is available on [GitHub](https://github.com/curvefi/twocrypto-ng).
* * *
**The AMM infrastructure involves the following parts:**
`AMM Blueprint Contracts`
* * *
The AMM is a **2-coin, auto-rebalancing Cryptoswap implementation** (version 2.0.0) with several optimizations. Unlike the older version, the **pool contract is an ERC20-compliant LP token**. The AMMs have a hardcoded `ADMIN_FEE`, set to 50% of the earned profits.
[→ CurveTwocryptoOptimized.vy](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/twocrypto.md)
`CurveTwocryptoFactory.vy`
* * *
The Factory allows the permissionless deployment of liquidity pools and gauges. It can accommodate **multiple blueprints of the AMM** contract. The admin can implement parameter changes, change the fee recipient, and upgrade implementations.
[→ CurveTwocryptoFactory.vy](https://docs.curve.finance/developer/factory/twocrypto-ng/overview)
`Views Contract`
* * *
Contains **view methods relevant for integrators** and users. The address of the deployed Views contract is stored in the Factory and is upgradeable by the Factory's admin.
[→ CurveCryptoViews2Optimized.vy](https://docs.curve.finance/developer/amm/twocrypto-ng/utility-contracts/views.md)
`Math Contract`
* * *
A contract which contains different **math functions used in the AMM**.
[→ CurveCryptoMathOptimized2.vy](https://docs.curve.finance/developer/amm/twocrypto-ng/utility-contracts/math.md)
`Liquidity Gauge Blueprint`
* * *
A liquidity gauge blueprint contract which deploys a liquidity gauge of a pool on Ethereum. On sidechains, gauges need to be deployed via the [`RootChainGaugeFactory`](https://docs.curve.finance/developer/gauges/xchain-gauges/root-gauge-factory.md).
* * *
<a id="new-features"></a>
## New Features
**New features over the regular two-coin CryptoSwap implementation:**
- New fee claiming approach
- [**`exchange_received`**](https://docs.curve.finance/developer/amm/twocrypto-ng/overview.md#exchange_received)
- Overall gas optimizations
<a id="fee-claiming"></a>
### Fee Claiming
Admin fees of a Curve pool are usually claimed through an external function, callable by anyone. **Twocrypto-NG does not have any external function to directly claim fees**. Admin fees are claimed through an internal function, which is called when liquidity is removed single-sidedly via the `_remove_liquidity_one_coin` function, and then sent to the fee receiver determined within the Factory contract.
**▶\`\_claim\_admin\_fees()\`▼**
```vyper
@internal
def _claim_admin_fees():
"""
@notice Claims admin fees and sends it to fee_receiver set in the factory.
@dev Functionally similar to:
1. Calculating admin's share of fees,
2. minting LP tokens,
3. admin claims underlying tokens via remove_liquidity.
"""
# --------------------- Check if fees can be claimed ---------------------
# Disable fee claiming if:
# 1. If time passed since last fee claim is less than
# MIN_ADMIN_FEE_CLAIM_INTERVAL.
# 2. Pool parameters are being ramped.
last_claim_time: uint256 = self.last_admin_fee_claim_timestamp
if (
unsafe_sub(block.timestamp, last_claim_time) < MIN_ADMIN_FEE_CLAIM_INTERVAL or
self.future_A_gamma_time > block.timestamp
):
return
xcp_profit: uint256 = self.xcp_profit # <---------- Current pool profits.
xcp_profit_a: uint256 = self.xcp_profit_a # <- Profits at previous claim.
current_lp_token_supply: uint256 = self.totalSupply
# Do not claim admin fees if:
# 1. insufficient profits accrued since last claim, and
# 2. there are less than 10**18 (or 1 unit of) lp tokens, else it can lead
# to manipulated virtual prices.
if xcp_profit <= xcp_profit_a or current_lp_token_supply < 10**18:
return
# ---------- Conditions met to claim admin fees: compute state. ----------
A_gamma: uint256[2] = self._A_gamma()
D: uint256 = self.D
vprice: uint256 = self.virtual_price
price_scale: uint256 = self.cached_price_scale
fee_receiver: address = factory.fee_receiver()
balances: uint256[N_COINS] = self.balances
# Admin fees are calculated as follows.
# 1. Calculate accrued profit since last claim. `xcp_profit`
# is the current profits. `xcp_profit_a` is the profits
# at the previous claim.
# 2. Take out admin's share, which is hardcoded at 5 * 10**9.
# (50% => half of 100% => 10**10 / 2 => 5 * 10**9).
# 3. Since half of the profits go to rebalancing the pool, we
# are left with half; so divide by 2.
fees: uint256 = unsafe_div(
unsafe_sub(xcp_profit, xcp_profit_a) * ADMIN_FEE, 2 * 10**10
)
# ------------------------------ Claim admin fees by minting admin's share
# of the pool in LP tokens.
# This is the admin fee tokens claimed in self.add_liquidity. We add it to
# the LP token share that the admin needs to claim:
admin_share: uint256 = self.admin_lp_virtual_balance
frac: uint256 = 0
if fee_receiver != empty(address) and fees > 0:
# -------------------------------- Calculate admin share to be minted.
frac = vprice * 10**18 / (vprice - fees) - 10**18
admin_share += current_lp_token_supply * frac / 10**18
# ------ Subtract fees from profits that will be used for rebalancing.
xcp_profit -= fees * 2
# ------------------- Recalculate virtual_price following admin fee claim.
total_supply_including_admin_share: uint256 = (
current_lp_token_supply + admin_share
)
vprice = (
10**18 * self.get_xcp(D, price_scale) /
total_supply_including_admin_share
)
# Do not claim fees if doing so causes virtual price to drop below 10**18.
if vprice < 10**18:
return
# ---------------------------- Update State ------------------------------
# Set admin virtual LP balances to zero because we claimed:
self.admin_lp_virtual_balance = 0
self.xcp_profit = xcp_profit
self.last_admin_fee_claim_timestamp = block.timestamp
# Since we reduce balances: virtual price goes down
self.virtual_price = vprice
# Adjust D after admin seemingly removes liquidity
self.D = D - unsafe_div(D * admin_share, total_supply_including_admin_share)
if xcp_profit > xcp_profit_a:
self.xcp_profit_a = xcp_profit # <-------- Cache last claimed profit.
# --------------------------- Handle Transfers ---------------------------
admin_tokens: uint256[N_COINS] = empty(uint256[N_COINS])
if admin_share > 0:
for i in range(N_COINS):
admin_tokens[i] = (
balances[i] * admin_share /
total_supply_including_admin_share
)
# _transfer_out tokens to admin and update self.balances. State
# update to self.balances occurs before external contract calls:
self._transfer_out(i, admin_tokens[i], fee_receiver)
log ClaimAdminFee(fee_receiver, admin_tokens)
```
<a id="exchange_received"></a>
### `exchange_received`
This 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()`**.
**▶Transfer logic when using \`exchange\_received()\`▼**
```vyper
@internal
def _transfer_in(
_coin_idx: uint256,
_dx: uint256,
sender: address,
expect_optimistic_transfer: bool,
) -> uint256:
"""
@notice Transfers `_coin` from `sender` to `self` and calls `callback_sig`
if it is not empty.
@params _coin_idx uint256 Index of the coin to transfer in.
@params dx amount of `_coin` to transfer into the pool.
@params sender address to transfer `_coin` from.
@params expect_optimistic_transfer bool True if pool expects user to transfer.
This is only enabled for exchange_received.
@return The amount of tokens received.
"""
coin_balance: uint256 = ERC20(coins[_coin_idx]).balanceOf(self)
if expect_optimistic_transfer: # Only enabled in exchange_received:
# it expects the caller of exchange_received to have sent tokens to
# the pool before calling this method.
# If someone donates extra tokens to the contract: do not acknowledge.
# We only want to know if there are dx amount of tokens. Anything extra,
# we ignore. This is why we need to check if received_amounts (which
# accounts for coin balances of the contract) is atleast dx.
# If we checked for received_amounts == dx, an extra transfer without a
# call to exchange_received will break the method.
dx: uint256 = coin_balance - self.balances[_coin_idx]
assert dx >= _dx # dev: user didn't give us coins
# Adjust balances
self.balances[_coin_idx] += dx
return dx
# ----------------------------------------------- ERC20 transferFrom flow.
# EXTERNAL CALL
assert ERC20(coins[_coin_idx]).transferFrom(
sender,
self,
_dx,
default_return_value=True
)
dx: uint256 = ERC20(coins[_coin_idx]).balanceOf(self) - coin_balance
self.balances[_coin_idx] += dx
return dx
```
* * *
info
Lets say a user wants to swap **`GOV-TOKEN↔USDC`** through an aggregator. For simplicity we assume, **`GOV-TOKEN↔USDT`** exchange is done via a uniswap pool, **`USDT↔USDC`** via a Curve pool.
1. User gives approval the `AGGREGATOR`, which then transfers tokens into the aggregator contract
2. Aggregator exchanges `GOV-TOKEN` for `USDT` using Uniswap
3. Transfers the `USDT` directly from Uniswap into the Curve pool
4. Perform a swap on the Curve pool (`USDT↔USDC`) via **`exchange_received`**
5. Transfer `USDC` to the user
info
This method saves aggregators one redundant ERC-20 transfer and eliminates the need to grant approval to a curve pool. Without this function, the aggregator would have to conduct an additional transaction, transferring USDT from the Uniswap pool to their aggregator contract after the exchange, and then sending it to the Curve pool for another exchange (USDT↔USDC). However, with this method in place, the aggregator can transfer the output tokens directly into the next pool and perform an exchange.
---
# Pool: Admin Controls
Source: [https://docs.curve.finance/developer/amm/twocrypto-ng/pools/admin-controls](https://docs.curve.finance/developer/amm/twocrypto-ng/pools/admin-controls)
<a id="pool-ownership"></a>
## Pool Ownership
Liquidity pools are deployed via the [Factory](https://docs.curve.finance/developer/amm/factory/twocrypto-ng/deployer-api.md). All pools deployed **share the same admin**defined within the Factory contract.
Transfering the ownership of a pool is only possible by changing the ownership of the Factory. Admin is the Curve DAO (OwnershipAdmin).
The same applies to the fee receiver of the pools.
[Factory Ownership](https://docs.curve.finance/developer/amm/factory/overview.md#contract-ownership)
* * *
<a id="parameter-changes"></a>
## Parameter Changes
For more information about parameters: [https://nagaking.substack.com/p/deep-dive-curve-v2-parameters](https://nagaking.substack.com/p/deep-dive-curve-v2-parameters).
The appropriate value for `A` and `gamma` is dependent upon the type of coin being used within the pool, and is subject to optimization and pool-parameter update based on the market history of the trading pair.
It is possible to modify the parameters for a pool after it has been deployed. Again, only the admin of the pool (= Factory admin) can do so.
<a id="ramp_a_gamma"></a>
### `ramp_A_gamma`
`TwoCrypto.ramp_A_gamma(future_A: uint256, future_gamma: uint256, future_time: uint256):`
Guarded Method
This function can only be called by the `admin` of the Factory contract.
Function to linearly ramp the values of `A` and `gamma`.
Emits: `RampAgamma`
| Input | Type | Description |
| --- | --- | --- |
| `future_A` | `uint256` | Future value of `A` |
| `future_gamma` | `uint256` | Future value of `gamma` |
| `future_time` | `uint256` | Timestamp at which the ramping will end |
**<>Source code▼**
```vyper
event RampAgamma:
initial_A: uint256
future_A: uint256
initial_gamma: uint256
future_gamma: uint256
initial_time: uint256
future_time: uint256
@external
def ramp_A_gamma(
future_A: uint256, future_gamma: uint256, future_time: uint256
):
"""
@notice Initialise Ramping A and gamma parameter values linearly.
@dev Only accessible by factory admin, and only
@param future_A The future A value.
@param future_gamma The future gamma value.
@param future_time The timestamp at which the ramping will end.
"""
assert msg.sender == factory.admin() # dev: only owner
assert block.timestamp > self.initial_A_gamma_time + (MIN_RAMP_TIME - 1) # dev: ramp undergoing
assert future_time > block.timestamp + MIN_RAMP_TIME - 1 # dev: insufficient time
A_gamma: uint256[2] = self._A_gamma()
initial_A_gamma: uint256 = A_gamma[0] << 128
initial_A_gamma = initial_A_gamma | A_gamma[1]
assert future_A > MIN_A - 1
assert future_A < MAX_A + 1
assert future_gamma > MIN_GAMMA - 1
assert future_gamma < MAX_GAMMA + 1
ratio: uint256 = 10**18 * future_A / A_gamma[0]
assert ratio < 10**18 * MAX_A_CHANGE + 1
assert ratio > 10**18 / MAX_A_CHANGE - 1
ratio = 10**18 * future_gamma / A_gamma[1]
assert ratio < 10**18 * MAX_A_CHANGE + 1
assert ratio > 10**18 / MAX_A_CHANGE - 1
self.initial_A_gamma = initial_A_gamma
self.initial_A_gamma_time = block.timestamp
future_A_gamma: uint256 = future_A << 128
future_A_gamma = future_A_gamma | future_gamma
self.future_A_gamma_time = future_time
self.future_A_gamma = future_A_gamma
log RampAgamma(
A_gamma[0],
future_A,
A_gamma[1],
future_gamma,
block.timestamp,
future_time,
)
```
**▶Example▼**
```shell
>>> soon
```
<a id="stop_ramp_a_gamma"></a>
### `stop_ramp_A_gamma`
`TwoCrypto.stop_ramp_A_gamma():`
Guarded Method
This function can only be called by the `admin` of the Factory contract.
Function to immediately stop the ramping of A and gamma parameters and set them to their current values.
Emits: `StopRampA`
**<>Source code▼**
```vyper
event StopRampA:
current_A: uint256
current_gamma: uint256
time: uint256
@external
def stop_ramp_A_gamma():
"""
@notice Stop Ramping A and gamma parameters immediately.
@dev Only accessible by factory admin.
"""
assert msg.sender == factory.admin() # dev: only owner
A_gamma: uint256[2] = self._A_gamma()
current_A_gamma: uint256 = A_gamma[0] << 128
current_A_gamma = current_A_gamma | A_gamma[1]
self.initial_A_gamma = current_A_gamma
self.future_A_gamma = current_A_gamma
self.initial_A_gamma_time = block.timestamp
self.future_A_gamma_time = block.timestamp
# ------ Now (block.timestamp < t1) is always False, so we return saved A.
log StopRampA(A_gamma[0], A_gamma[1], block.timestamp)
```
**▶Example▼**
```shell
>>> soon
```
<a id="apply_new_parameters"></a>
### `apply_new_parameters`
`TwoCrypto.apply_new_parameters(_new_mid_fee: uint256, _new_out_fee: uint256, _new_fee_gamma: uint256, _new_allowed_extra_profit: uint256, _new_adjustment_step: uint256, _new_ma_time: uint256, _new_xcp_ma_time: uint256):`
Guarded Method
This function can only be called by the `admin` of the Factory contract.
Function to commit new parameters. The new parameters are applied immediately.
Emits: `NewParameters`
| Input | Type | Description |
| --- | --- | --- |
| `_new_mid_fee` | `uint256` | New `mid_fee` value. |
| `_new_out_fee` | `uint256` | New `out_fee` value. |
| `_new_fee_gamma` | `uint256` | New `fee_gamma` value. |
| `_new_allowed_extra_profit` | `uint256` | New `allowed_extra_profit` value. |
| `_new_adjustment_step` | `uint256` | New `adjustment_step` value. |
| `_new_ma_time` | `uint256` | New `ma_time` value, which is time\_in\_seconds/ln(2). |
| `_new_xcp_ma_time` | `uint256` | New ma time for xcp oracles. |
**<>Source code▼**
```vyper
event NewParameters:
mid_fee: uint256
out_fee: uint256
fee_gamma: uint256
allowed_extra_profit: uint256
adjustment_step: uint256
ma_time: uint256
xcp_ma_time: uint256
@external
@nonreentrant('lock')
def apply_new_parameters(
_new_mid_fee: uint256,
_new_out_fee: uint256,
_new_fee_gamma: uint256,
_new_allowed_extra_profit: uint256,
_new_adjustment_step: uint256,
_new_ma_time: uint256,
_new_xcp_ma_time: uint256,
):
"""
@notice Commit new parameters.
@dev Only accessible by factory admin.
@param _new_mid_fee The new mid fee.
@param _new_out_fee The new out fee.
@param _new_fee_gamma The new fee gamma.
@param _new_allowed_extra_profit The new allowed extra profit.
@param _new_adjustment_step The new adjustment step.
@param _new_ma_time The new ma time. ma_time is time_in_seconds/ln(2).
@param _new_xcp_ma_time The new ma time for xcp oracle.
"""
assert msg.sender == factory.admin() # dev: only owner
# ----------------------------- Set fee params ---------------------------
new_mid_fee: uint256 = _new_mid_fee
new_out_fee: uint256 = _new_out_fee
new_fee_gamma: uint256 = _new_fee_gamma
current_fee_params: uint256[3] = self._unpack_3(self.packed_fee_params)
if new_out_fee < MAX_FEE + 1:
assert new_out_fee > MIN_FEE - 1 # dev: fe프로젝트로 돌아가기