bitpro가 원문에서 글자만 모은 내용이에요. 표·그림·수식은 빠지거나 깨질 수 있어요. 전체 75쪽 중 46쪽
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
```
<a id="name"></a>
### `name`
`StableSwap.name() -> String[64]: view`
Getter for the name of the LP token.
Returns: name (`String[64]`).
**<>Source code▼**
```vyper
name: public(immutable(String[64]))
@external
def __init__(
_name: String[32],
_symbol: String[10],
_A: uint256,
_fee: uint256,
_offpeg_fee_multiplier: uint256,
_ma_exp_time: uint256,
_coins: DynArray[address, MAX_COINS],
_rate_multipliers: DynArray[uint256, MAX_COINS],
_asset_types: DynArray[uint8, MAX_COINS],
_method_ids: DynArray[bytes4, MAX_COINS],
_oracles: DynArray[address, MAX_COINS],
):
...
name = _name
...
```
**▶Example▼**
```shell
>>> StableSwap.name()
'USDV-crvUSD'
```
<a id="symbol"></a>
### `symbol`
`StableSwap.symbol() -> String[32]: view`
Getter for the symbol of the LP token.
Returns: symbol (`String[32]`).
**<>Source code▼**
```vyper
symbol: public(immutable(String[32]))
@external
def __init__(
_name: String[32],
_symbol: String[10],
_A: uint256,
_fee: uint256,
_offpeg_fee_multiplier: uint256,
_ma_exp_time: uint256,
_coins: DynArray[address, MAX_COINS],
_rate_multipliers: DynArray[uint256, MAX_COINS],
_asset_types: DynArray[uint8, MAX_COINS],
_method_ids: DynArray[bytes4, MAX_COINS],
_oracles: DynArray[address, MAX_COINS],
):
...
symbol = _symbol
...
```
**▶Example▼**
```shell
>>> StableSwap.symbol()
'USDVcrvUSD'
```
<a id="decimals"></a>
### `decimals`
`StableSwap.decimals() -> uint8: view`
Getter for the decimals of the LP token.
Returns: decimals (uint8).
**<>Source code▼**
```vyper
decimals: public(constant(uint8)) = 18
```
**▶Example▼**
```shell
>>> StableSwap.decimals()
18
```
<a id="version"></a>
### `version`
`StableSwap.version() -> String[8]: view`
Getter for the version of the LP token.
Returns: version (`String[8]`).
**<>Source code▼**
```vyper
version: public(constant(String[8])) = "v7.0.0"
```
**▶Example▼**
```shell
>>> StableSwap.version()
"v7.0.0"
```
<a id="balanceof"></a>
### `balanceOf`
`StableSwap.balanceOf(arg0: address) -> uint256: view`
Getter for the LP token balance of `arg0`.
Returns: token balance (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `arg0` | `address` | address to check the balance of |
**<>Source code▼**
```vyper
balanceOf: public(HashMap[address, uint256])
```
**▶Example▼**
```shell
>>> StableSwap.balanceOf("0x7a16fF8270133F063aAb6C9977183D9e72835428")
999808484451757093697730
```
<a id="nonces"></a>
### `nonces`
`StableSwap.nonces(arg0: address) -> uint256: view`
Getter for the nonce.
Returns: nonces (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `arg0` | `address` | address |
**<>Source code▼**
```vyper
nonces: public(HashMap[address, uint256])
```
<a id="salt"></a>
### `salt`
`StableSwap.salt() -> bytes32: view`
Getter for the salt of the LP token.
Returns: salt (`bytes32`).
**<>Source code▼**
```vyper
salt: public(immutable(bytes32))
@external
def __init__(
_name: String[32],
_symbol: String[10],
_A: uint256,
_fee: uint256,
_offpeg_fee_multiplier: uint256,
_ma_exp_time: uint256,
_coins: DynArray[address, MAX_COINS],
_rate_multipliers: DynArray[uint256, MAX_COINS],
_asset_types: DynArray[uint8, MAX_COINS],
_method_ids: DynArray[bytes4, MAX_COINS],
_oracles: DynArray[address, MAX_COINS],
):
...
# EIP712 related params -----------------
NAME_HASH = keccak256(name)
salt = block.prevhash
CACHED_CHAIN_ID = chain.id
CACHED_DOMAIN_SEPARATOR = keccak256(
_abi_encode(
EIP712_TYPEHASH,
NAME_HASH,
VERSION_HASH,
chain.id,
self,
salt,
)
)
...
```
**▶Example▼**
```shell
>>> StableSwap.salt()
HexBytes('0x814188b56f08130fe7b283343b64baa08f4d207229dc52776968b62b977c8f46')
```
<a id="domain_separator"></a>
### `DOMAIN_SEPARATOR`
`StableSwap.DOMAIN_SEPARATOR() -> bytes32: view`
Getter for the domain separator.
Returns: domain separator (`bytes32`).
**<>Source code▼**
```vyper
CACHED_DOMAIN_SEPARATOR: immutable(bytes32)
@view
@external
def DOMAIN_SEPARATOR() -> bytes32:
"""
@notice EIP712 domain separator.
@return bytes32 Domain Separator set for the current chain.
"""
return self._domain_separator()
@view
@internal
def _domain_separator() -> bytes32:
if chain.id != CACHED_CHAIN_ID:
return keccak256(
_abi_encode(
EIP712_TYPEHASH,
NAME_HASH,
VERSION_HASH,
chain.id,
self,
salt,
)
)
return CACHED_DOMAIN_SEPARATOR
```
**▶Example▼**
```shell
>>> StableSwap.DOMAIN_SEPARATOR()
HexBytes('0xf60903716a331f2ad023b28477aceee88e5180cab4694c497f4f9cefac657989')
```
* * *
<a id="admin-controls"></a>
## Admin Controls
The following methods are guarded and may only be called by the **`admin`** of the Stableswap-NG Factory.
<a id="ramp_a"></a>
### `ramp_A`
`StableSwap.ramp_A(_future_A: uint256, _future_time: uint256):`
Guarded Method
This function is only callable by the `admin` of the Factory.
Function to ramp amplification coefficient A. Minimum ramp time is 86400 (24h).
*Limitations when ramping A:*
- `block.timestamp` >= `initial_A_time` + `MIN_RAMP_TIME`
- `_future_time` >= `block.timestamp` + `MIN_RAMP_TIME`
- `future_A` > 0
- `future_A` < `MAX_A (1000000)`
Emits: `RampA`
| Input | Type | Description |
| --- | --- | --- |
| `_future_A` | `uint256` | future A value |
| `_future_time` | `uint256` | timestamp until ramping should occur; needs to be at least 24h (`MIN_RAMP_TIME`) |
**<>Source code▼**
```vyper
A_PRECISION: constant(uint256) = 100
MAX_A: constant(uint256) = 10 **6
MAX_A_CHANGE: constant(uint256) = 10
MIN_RAMP_TIME: constant(uint256) = 86400
event RampA:
old_A: uint256
new_A: uint256
initial_time: uint256
future_time: uint256
@external
def ramp_A(_future_A: uint256, _future_time: uint256):
assert msg.sender == factory.admin() # dev: only owner
assert block.timestamp >= self.initial_A_time + MIN_RAMP_TIME
assert _future_time >= block.timestamp + MIN_RAMP_TIME # dev: insufficient time
_initial_A: uint256 = self._A()
_future_A_p: uint256 = _future_A * A_PRECISION
assert _future_A > 0 and _future_A < MAX_A
if _future_A_p < _initial_A:
assert _future_A_p * MAX_A_CHANGE >= _initial_A
else:
assert _future_A_p <= _initial_A * MAX_A_CHANGE
self.initial_A = _initial_A
self.future_A = _future_A_p
self.initial_A_time = block.timestamp
self.future_A_time = _future_time
log RampA(_initial_A, _future_A_p, block.timestamp, _future_time)
```
<a id="stop_ramp_a"></a>
### `stop_ramp_A`
`StableSwap.stop_ramp_A():`
Guarded Method
This function is only callable by the `admin` of the Factory.
Function to immediately stop the ramping A. The current value during the ramping process will be finalized as `A`.
Emits: `StopRampA`
**<>Source code▼**
```vyper
event StopRampA:
A: uint256
t: uint256
@external
def stop_ramp_A():
assert msg.sender == factory.admin() # dev: only owner
current_A: uint256 = self._A()
self.initial_A = current_A
self.future_A = current_A
self.initial_A_time = block.timestamp
self.future_A_time = block.timestamp
# now (block.timestamp < t1) is always False, so we return saved A
log StopRampA(current_A, block.timestamp)
```
<a id="set_new_fee"></a>
### `set_new_fee`
`StableSwap.set_new_fee(_new_fee: uint256, _new_offpeg_fee_multiplier: uint256):`
Guarded Method
This function is only callable by the `admin` of the Factory.
Function to set new values for `fee` and `offpeg_fee_multiplier`.
*Limitations when setting new parameters:*
- `_new_fee` <= `MAX_FEE` (5000000000)
- `_new_offpeg_fee_multiplier` \* `_new_fee` <= `MAX_FEE` \* `FEE_DENOMINATOR`
Emits: `ApplyNewFee`
| Input | Type | Description |
| --- | --- | --- |
| `_new_fee` | `uint256` | new fee |
| `_new_offpeg_fee_multiplier` | `uint256` | new off-peg fee multiplier |
**<>Source code▼**
```vyper
MAX_FEE: constant(uint256) = 5 * 10 **9
FEE_DENOMINATOR: constant(uint256) = 10 **10
event ApplyNewFee:
fee: uint256
offpeg_fee_multiplier: uint256
@external
def set_new_fee(_new_fee: uint256, _new_offpeg_fee_multiplier: uint256):
assert msg.sender == factory.admin()
# set new fee:
assert _new_fee <= MAX_FEE
self.fee = _new_fee
# set new offpeg_fee_multiplier:
assert _new_offpeg_fee_multiplier * _new_fee <= MAX_FEE * FEE_DENOMINATOR # dev: offpeg multiplier exceeds maximum
self.offpeg_fee_multiplier = _new_offpeg_fee_multiplier
log ApplyNewFee(_new_fee, _new_offpeg_fee_multiplier)
```
<a id="set_ma_exp_time"></a>
### `set_ma_exp_time`
`StableSwap.set_ma_exp_time(_ma_exp_time: uint256, _D_ma_time: uint256):`
Guarded Method
This function is only callable by the `admin` of the Factory.
Function to set the moving average window for `ma_exp_time` and `D_ma_time`.
*Limitations when setting new fee parameters:*
- `_ma_exp_time` and `_D_ma_time` > 0
| Input | Type | Description |
| --- | --- | --- |
| `_ma_exp_time` | `uint256` | new ma exp time |
| `_D_ma_time` | `uint256` | new D ma time |
**<>Source code▼**
```vyper
@external
def set_ma_exp_time(_ma_exp_time: uint256, _D_ma_time: uint256):
"""
@notice Set the moving average window of the price oracles.
@param _ma_exp_time Moving average window. It is time_in_seconds / ln(2)
"""
assert msg.sender == factory.admin() # dev: only owner
assert 0 not in [_ma_exp_time, _D_ma_time]
self.ma_exp_time = _ma_exp_time
self.D_ma_time = _D_ma_time
```
---
# Math Contract
Source: [https://docs.curve.finance/developer/amm/stableswap-ng/utility-contracts/math](https://docs.curve.finance/developer/amm/stableswap-ng/utility-contracts/math)
The Math Contract provides **AMM Math** for Stableswap-NG Pools.
Contract Source & Deployment
Source code available on [GitHub](https://github.com/curvefi/stableswap-ng/blob/bff1522b30819b7b240af17ccfb72b0effbf6c47/contracts/main/CurveStableSwapNGMath.vy).
All Math contract deployments can be found in the [Deployment Addresses](https://docs.curve.finance/developer/deployments.md) section.
<a id="get_y"></a>
### `get_y`
`Math.get_y(i: int128, j: int128, x: uint256, xp: DynArray[uint256, MAX_COINS], _amp: uint256, _D: uint256, _n_coins: uint256) -> uint256:`
Function to calculate how much coins `j` a user receives when providing `x` amount of coin `i`. This is done by solving quadratic equations iteratively.
Returns: amount of output coins to receive (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `i` | `int128` | index value of input coin |
| `j` | `int128` | index value of output coin |
| `x` | `uint256` | amount of input coin |
| `xp` | `DynArray[uint256, MAX_COINS]` | current balances of the coins in the pool |
| `_amp` | `uint256` | amplification coefficient |
| `_D` | `uint256` | D invariant |
| `_n_coins` | `uint256` | number of coins |
**<>Source code▼**
```vyper
MAX_COINS: constant(uint256) = 8
MAX_COINS_128: constant(int128) = 8
A_PRECISION: constant(uint256) = 100
@external
@pure
def get_y(
i: int128,
j: int128,
x: uint256,
xp: DynArray[uint256, MAX_COINS],
_amp: uint256,
_D: uint256,
_n_coins: uint256
) -> uint256:
"""
Calculate x[j] if one makes x[i] = x
Done by solving quadratic equation iteratively.
x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D **(n + 1) / (n **(2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
"""
# x in the input is converted to the same price/precision
n_coins_128: int128 = convert(_n_coins, int128)
assert i != j # dev: same coin
assert j >= 0 # dev: j below zero
assert j < n_coins_128 # dev: j above N_COINS
# should be unreachable, but good for safety
assert i >= 0
assert i < n_coins_128
amp: uint256 = _amp
D: uint256 = _D
S_: uint256 = 0
_x: uint256 = 0
y_prev: uint256 = 0
c: uint256 = D
Ann: uint256 = amp * _n_coins
for _i in range(MAX_COINS_128):
if _i == n_coins_128:
break
if _i == i:
_x = x
elif _i != j:
_x = xp[_i]
else:
continue
S_ += _x
c = c * D / (_x * _n_coins)
c = c * D * A_PRECISION / (Ann * _n_coins)
b: uint256 = S_ + D * A_PRECISION / Ann # - D
y: uint256 = D
for _i in range(255):
y_prev = y
y = (y*y + c) / (2 * y + b - D)
# Equality with the precision of 1
if y > y_prev:
if y - y_prev <= 1:
return y
else:
if y_prev - y <= 1:
return y
raise
```
**▶Example▼**
```shell
>>> Math.get_y('todo')
'todo'
```
<a id="get_d"></a>
### `get_D`
`Math.get_D(_xp: DynArray[uint256, MAX_COINS], _amp: uint256, _n_coins: uint256) -> uint256:`
Function to iteratively calculate the D invariant in non-overflowing integer operations.
Returns: D invariant (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `_xp` | `DynArray[uint256, MAX_COINS]` | current balances of the coins in the pool |
| `_amp` | `uint256` | amplification coefficient |
| `_n_coins` | `uint256` | number of coins |
**<>Source code▼**
```vyper
@external
@pure
def get_D(
_xp: DynArray[uint256, MAX_COINS],
_amp: uint256,
_n_coins: uint256
) -> uint256:
"""
D invariant calculation in non-overflowing integer operations
iteratively
A * sum(x_i) * n**n + D = A * D * n**n + D**(n+1) / (n**n * prod(x_i))
Converging solution:
D[j+1] = (A * n**n * sum(x_i) - D[j]**(n+1) / (n**n prod(x_i))) / (A * n**n - 1)
"""
S: uint256 = 0
for x in _xp:
S += x
if S == 0:
return 0
D: uint256 = S
Ann: uint256 = _amp * _n_coins
D_P: uint256 = 0
Dprev: uint256 = 0
for i in range(255):
D_P = D
for x in _xp:
D_P = D_P * D / (x * _n_coins) # If division by 0, this will be borked: only withdrawal will work. And that is good
Dprev = D
# (Ann * S / A_PRECISION + D_P * _n_coins) * D / ((Ann - A_PRECISION) * D / A_PRECISION + (_n_coins + 1) * D_P)
D = (
(unsafe_div(Ann * S, A_PRECISION) + D_P * _n_coins) *
D / (
unsafe_div((Ann - A_PRECISION) * D, A_PRECISION) +
unsafe_add(_n_coins, 1) * D_P
)
)
# Equality with the precision of 1
if D > Dprev:
if D - Dprev <= 1:
return D
else:
if Dprev - D <= 1:
return D
# convergence typically occurs in 4 rounds or less, this should be unreachable!
# if it does happen the pool is borked and LPs can withdraw via `remove_liquidity`
raise
```
**▶Example▼**
```shell
>>> Math.get_D('todo')
'todo'
```
<a id="get_y_d"></a>
### `get_y_D`
`Math.get_y_D(A: uint256, i: int128, xp: DynArray[uint256, MAX_COINS], D: uint256, _n_coins: uint256) -> uint256:`
Function to calculate how much of coin `i` will be in the pool when invariant `D` decreases.
Returns: balance of coin `i` (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `A` | `uint256` | amplification coefficient |
| `i` | `int128` | index value of coin |
| `xp` | `DynArray[uint256, MAX_COINS]` | current balances of the coins in the pool |
| `D` | `uint256` | D invariant |
| `_n_coins` | `uint256` | number of coins |
**<>Source code▼**
```vyper
@external
@pure
def get_y_D(
A: uint256,
i: int128,
xp: DynArray[uint256, MAX_COINS],
D: uint256,
_n_coins: uint256
) -> uint256:
"""
Calculate x[i] if one reduces D from being calculated for xp to D
Done by solving quadratic equation iteratively.
x_1**2 + x_1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D **(n + 1) / (n **(2 * n) * prod' * A)
x_1**2 + b*x_1 = c
x_1 = (x_1**2 + c) / (2*x_1 + b)
"""
# x in the input is converted to the same price/precision
n_coins_128: int128 = convert(_n_coins, int128)
assert i >= 0 # dev: i below zero
assert i < n_coins_128 # dev: i above N_COINS
S_: uint256 = 0
_x: uint256 = 0
y_prev: uint256 = 0
c: uint256 = D
Ann: uint256 = A * _n_coins
for _i in range(MAX_COINS_128):
if _i == n_coins_128:
break
if _i != i:
_x = xp[_i]
else:
continue
S_ += _x
c = c * D / (_x * _n_coins)
c = c * D * A_PRECISION / (Ann * _n_coins)
b: uint256 = S_ + D * A_PRECISION / Ann
y: uint256 = D
for _i in range(255):
y_prev = y
y = (y*y + c) / (2 * y + b - D)
# Equality with the precision of 1
if y > y_prev:
if y - y_prev <= 1:
return y
else:
if y_prev - y <= 1:
return y
raise
```
**▶Example▼**
```shell
>>> Math.get_y_D('todo')
'todo'
```
<a id="exp"></a>
### `exp`
`Math.exp(x: int256) -> uint256:`
Function to calculate the natural exponential function of a signed integer with a precision of 1e18.
Returns: calculation result (`uint256`).
| Input | Type | Description |
| --- | --- | --- |
| `x` | `int256` | 32-byte variable |
**<>Source code▼**
```vyper
@external
@pure
def exp(x: int256) -> uint256:
"""
@dev Calculates the natural exponential function of a signed integer with
a precision of 1e18.
@notice Note that this function consumes about 810 gas units. The implementation
is inspired by Remco Bloemen's implementation under the MIT license here:
https://xn--2-umb.com/22/exp-ln.
@dev This implementation is derived from Snekmate, which is authored
by pcaversaccio (Snekmate), distributed under the AGPL-3.0 license.
https://github.com/pcaversaccio/snekmate
@param x The 32-byte variable.
@return int256 The 32-byte calculation result.
"""
value: int256 = x
# If the result is `< 0.5`, we return zero. This happens when we have the following:
# "x <= floor(log(0.5e18) * 1e18) ~ -42e18".
if (x <= -42139678854452767551):
return empty(uint256)
# When the result is "> (2 **255 - 1) / 1e18" we cannot represent it as a signed integer.
# This happens when "x >= floor(log((2 **255 - 1) / 1e18) * 1e18) ~ 135".
assert x < 135305999368893231589, "wad_exp overflow"
# `x` is now in the range "(-42, 136) * 1e18". Convert to "(-42, 136) * 2 **96" for higher
# intermediate precision and a binary base. This base conversion is a multiplication with
# "1e18 / 2 **96 = 5 **18 / 2 **78".
value = unsafe_div(x << 78, 5 **18)
# Reduce the range of `x` to "(-½ ln 2, ½ ln 2) * 2 **96" by factoring out powers of two
# so that "exp(x) = exp(x') * 2 **k", where `k` is a signer integer. Solving this gives
# "k = round(x / log(2))" and "x' = x - k * log(2)". Thus, `k` is in the range "[-61, 195]".
k: int256 = unsafe_add(unsafe_div(value << 96, 54916777467707473351141471128), 2 **95) >> 96
value = unsafe_sub(value, unsafe_mul(k, 54916777467707473351141471128))
# Evaluate using a "(6, 7)"-term rational approximation. Since `p` is monic,
# we will multiply by a scaling factor later.
y: int256 = unsafe_add(unsafe_mul(unsafe_add(value, 1346386616545796478920950773328), value) >> 96, 57155421227552351082224309758442)
p: int256 = unsafe_add(unsafe_mul(unsafe_add(unsafe_mul(unsafe_sub(unsafe_add(y, value), 94201549194550492254356042504812), y) >> 96,\
28719021644029726153956944680412240), value), 4385272521454847904659076985693276 << 96)
# We leave `p` in the "2 **192" base so that we do not have to scale it up
# again for the division.
q: int256 = unsafe_add(unsafe_mul(unsafe_sub(value, 2855989394907223263936484059900), value) >> 96, 50020603652535783019961831881945)
q = unsafe_sub(unsafe_mul(q, value) >> 96, 533845033583426703283633433725380)
q = unsafe_add(unsafe_mul(q, value) >> 96, 3604857256930695427073651918091429)
q = unsafe_sub(unsafe_mul(q, value) >> 96, 14423608567350463180887372962807573)
q = unsafe_add(unsafe_mul(q, value) >> 96, 26449188498355588339934803723976023)
# The polynomial `q` has no zeros in the range because all its roots are complex.
# No scaling is required, as `p` is already "2 **96" too large. Also,
# `r` is in the range "(0.09, 0.25) * 2**96" after the division.
r: int256 = unsafe_div(p, q)
# To finalise the calculation, we have to multiply `r` by:
# - the scale factor "s = ~6.031367120",
# - the factor "2 **k" from the range reduction, and
# - the factor "1e18 / 2 **96" for the base conversion.
# We do this all at once, with an intermediate result in "2**213" base,
# so that the final right shift alwa프로젝트로 돌아가기