Skip to main content

SwapUtils

A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities.

Contracts relying on this library must initialize SwapUtils.Swap struct then use this library for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. Admin functions should be protected within contracts using this library.

Functions#

getA#

function getA(
struct SwapUtils.Swap self
) external returns (uint256)

Return A, the amplification coefficient n (n - 1)

See the StableSwap paper for details

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
Astruct SwapUtils.Swapparameter

_getA#

function _getA(
struct SwapUtils.Swap self
) internal returns (uint256)

Return A, the amplification coefficient n (n - 1)

See the StableSwap paper for details

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
Astruct SwapUtils.Swapparameter

getAPrecise#

function getAPrecise(
struct SwapUtils.Swap self
) external returns (uint256)

Return A in its raw precision

See the StableSwap paper for details

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
Astruct SwapUtils.Swapparameter in its raw precision form

_getAPrecise#

function _getAPrecise(
struct SwapUtils.Swap self
) internal returns (uint256)

Calculates and returns A based on the ramp settings

See the StableSwap paper for details

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
Astruct SwapUtils.Swapparameter in its raw precision form

getDepositTimestamp#

function getDepositTimestamp(
struct SwapUtils.Swap self
) external returns (uint256)

Retrieves the timestamp of last deposit made by the given address

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
timestampstruct SwapUtils.Swapof last deposit

calculateWithdrawOneToken#

function calculateWithdrawOneToken(
struct SwapUtils.Swap account,
address tokenAmount,
uint256 tokenIndex,
uint8 self
) public returns (uint256, uint256)

Calculate the dy, the amount of selected token that user receives and the fee of withdrawing in one token

Parameters:#

NameTypeDescription
accountstruct SwapUtils.Swapthe address that is withdrawing
tokenAmountaddressthe amount to withdraw in the pool's precision
tokenIndexuint256which token will be withdrawn
selfuint8Swap struct to read from

Return Values:#

NameTypeDescription
thestruct SwapUtils.Swapamount of token user will receive and the associated swap fee

calculateWithdrawOneTokenDY#

function calculateWithdrawOneTokenDY(
struct SwapUtils.Swap self,
uint8 tokenIndex,
uint256 tokenAmount
) internal returns (uint256, uint256)

Calculate the dy of withdrawing in one token

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
tokenIndexuint8which token will be withdrawn
tokenAmountuint256the amount to withdraw in the pools precision

Return Values:#

NameTypeDescription
thestruct SwapUtils.Swapd and the new y after withdrawing one token

getYD#

function getYD(
uint256 a,
uint8 tokenIndex,
uint256[] xp,
uint256 d
) internal returns (uint256)

Calculate the price of a token in the pool with given precision-adjusted balances and a particular D.

This is accomplished via solving the invariant iteratively. See the StableSwap paper and Curve.fi implementation for further details.

x_12 + x1 (sum' - (Ann - 1) D / (A nn)) = D (n + 1) / (n (2 n) prod' * A) x_12 + bx_1 = c x_1 = (x_1**2 + c) / (2x_1 + b)

Parameters:#

NameTypeDescription
auint256the amplification coefficient n (n - 1). See the StableSwap paper for details.
tokenIndexuint8Index of token we are calculating for.
xpuint256[]a precision-adjusted set of pool balances. Array should be

the same cardinality as the pool. |d | uint256 | the stableswap invariant

Return Values:#

NameTypeDescription
theuint256price of the token, in the same precision as in xp

getD#

function getD(
uint256[] xp,
uint256 a
) internal returns (uint256)

Get D, the StableSwap invariant, based on a set of balances and a particular A.

Parameters:#

NameTypeDescription
xpuint256[]a precision-adjusted set of pool balances. Array should be the same cardinality

as the pool. |a | uint256 | the amplification coefficient n (n - 1) in A_PRECISION. See the StableSwap paper for details

Return Values:#

NameTypeDescription
theuint256[]invariant, at the precision of the pool

getD#

function getD(
struct SwapUtils.Swap self
) internal returns (uint256)

Get D, the StableSwap invariant, based on self Swap struct

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
Thestruct SwapUtils.Swapinvariant, at the precision of the pool

_xp#

function _xp(
uint256[] balances,
uint256[] precisionMultipliers
) internal returns (uint256[])

Given a set of balances and precision multipliers, return the precision-adjusted balances.

Parameters:#

NameTypeDescription
balancesuint256[]an array of token balances, in their native precisions.

These should generally correspond with pooled tokens.

|precisionMultipliers | uint256[] | an array of multipliers, corresponding to the amounts in the balances array. When multiplied together they should yield amounts at the pool's precision.

Return Values:#

NameTypeDescription
anuint256[]array of amounts "scaled" to the pool's precision

_xp#

function _xp(
struct SwapUtils.Swap self,
uint256[] balances
) internal returns (uint256[])

Return the precision-adjusted balances of all tokens in the pool

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
balancesuint256[]array of balances to scale

Return Values:#

NameTypeDescription
balancesstruct SwapUtils.Swaparray "scaled" to the pool's precision, allowing

them to be more easily compared.

_xp#

function _xp(
struct SwapUtils.Swap self
) internal returns (uint256[])

Return the precision-adjusted balances of all tokens in the pool

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
thestruct SwapUtils.Swappool balances "scaled" to the pool's precision, allowing

them to be more easily compared.

getVirtualPrice#

function getVirtualPrice(
struct SwapUtils.Swap self
) external returns (uint256)

Get the virtual price, to help calculate profit

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

Return Values:#

NameTypeDescription
thestruct SwapUtils.Swapvirtual price, scaled to precision of POOL_PRECISION_DECIMALS

getY#

function getY(
struct SwapUtils.Swap self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 x,
uint256[] xp
) internal returns (uint256)

Calculate the new balances of the tokens given the indexes of the token that is swapped from (FROM) and the token that is swapped to (TO). This function is used as a helper function to calculate how much TO token the user should receive on swap.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
tokenIndexFromuint8index of FROM token
tokenIndexTouint8index of TO token
xuint256the new total amount of FROM token
xpuint256[]balances of the tokens in the pool

Return Values:#

NameTypeDescription
thestruct SwapUtils.Swapamount of TO token that should remain in the pool

calculateSwap#

function calculateSwap(
struct SwapUtils.Swap self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) external returns (uint256 dy)

Externally calculates a swap between two tokens.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
tokenIndexFromuint8the token to sell
tokenIndexTouint8the token to buy
dxuint256the number of tokens to sell. If the token charges a fee on transfers,

use the amount that gets transferred after the fee.

Return Values:#

NameTypeDescription
dystruct SwapUtils.Swapthe number of tokens the user will get

_calculateSwap#

function _calculateSwap(
struct SwapUtils.Swap self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx
) internal returns (uint256 dy, uint256 dyFee)

Internally calculates a swap between two tokens.

The caller is expected to transfer the actual amounts (dx and dy) using the token contracts.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
tokenIndexFromuint8the token to sell
tokenIndexTouint8the token to buy
dxuint256the number of tokens to sell. If the token charges a fee on transfers,

use the amount that gets transferred after the fee.

Return Values:#

NameTypeDescription
dystruct SwapUtils.Swapthe number of tokens the user will get
dyFeeuint8the associated fee

calculateRemoveLiquidity#

function calculateRemoveLiquidity(
struct SwapUtils.Swap account,
address amount
) external returns (uint256[])

A simple method to calculate amount of each underlying tokens that is returned upon burning given amount of LP tokens

Parameters:#

NameTypeDescription
accountstruct SwapUtils.Swapthe address that is removing liquidity. required for withdraw fee calculation
amountaddressthe amount of LP tokens that would to be burned on

withdrawal

Return Values:#

NameTypeDescription
arraystruct SwapUtils.Swapof amounts of tokens user will receive

_calculateRemoveLiquidity#

function _calculateRemoveLiquidity(
) internal returns (uint256[])

calculateCurrentWithdrawFee#

function calculateCurrentWithdrawFee(
struct SwapUtils.Swap user
) public returns (uint256)

Calculate the fee that is applied when the given user withdraws. Withdraw fee decays linearly over 4 weeks.

Parameters:#

NameTypeDescription
userstruct SwapUtils.Swapaddress you want to calculate withdraw fee of

Return Values:#

NameTypeDescription
currentstruct SwapUtils.Swapwithdraw fee of the user

calculateTokenAmount#

function calculateTokenAmount(
struct SwapUtils.Swap self,
address account,
uint256[] amounts,
bool deposit
) external returns (uint256)

A simple method to calculate prices from deposits or withdrawals, excluding fees but including slippage. This is helpful as an input into the various "min" parameters on calls to fight front-running

This shouldn't be used outside frontends for user estimates.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
accountaddressaddress of the account depositing or withdrawing tokens
amountsuint256[]an array of token amounts to deposit or withdrawal,

corresponding to pooledTokens. The amount should be in each pooled token's native precision. If a token charges a fee on transfers, use the amount that gets transferred after the fee. |deposit | bool | whether this is a deposit or a withdrawal

Return Values:#

NameTypeDescription
ifstruct SwapUtils.Swapdeposit was true, total amount of lp token that will be minted and if

deposit was false, total amount of lp token that will be burned

getAdminBalance#

function getAdminBalance(
struct SwapUtils.Swap self,
uint256 index
) external returns (uint256)

return accumulated amount of admin fees of the token with given index

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from
indexuint256Index of the pooled token

Return Values:#

NameTypeDescription
adminstruct SwapUtils.Swapbalance in the token's precision

_feePerToken#

function _feePerToken(
struct SwapUtils.Swap self
) internal returns (uint256)

internal helper function to calculate fee per token multiplier used in swap fee calculations

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from

swap#

function swap(
struct SwapUtils.Swap self,
uint8 tokenIndexFrom,
uint8 tokenIndexTo,
uint256 dx,
uint256 minDy
) external returns (uint256)

swap two tokens in the pool

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
tokenIndexFromuint8the token the user wants to sell
tokenIndexTouint8the token the user wants to buy
dxuint256the amount of tokens the user wants to sell
minDyuint256the min amount the user would like to receive, or revert.

Return Values:#

NameTypeDescription
amountstruct SwapUtils.Swapof token user received on swap

addLiquidity#

function addLiquidity(
struct SwapUtils.Swap self,
uint256[] amounts,
uint256 minToMint
) external returns (uint256)

Add liquidity to the pool

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
amountsuint256[]the amounts of each token to add, in their native precision
minToMintuint256the minimum LP tokens adding this amount of liquidity

should mint, otherwise revert. Handy for front-running mitigation allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored.

Return Values:#

NameTypeDescription
amountstruct SwapUtils.Swapof LP token user received

updateUserWithdrawFee#

function updateUserWithdrawFee(
struct SwapUtils.Swap self,
address user,
uint256 toMint
) external

Update the withdraw fee for user. If the user is currently not providing liquidity in the pool, sets to default value. If not, recalculate the starting withdraw fee based on the last deposit's time & amount relative to the new deposit.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
useraddressaddress of the user depositing tokens
toMintuint256amount of pool tokens to be minted

_updateUserWithdrawFee#

function _updateUserWithdrawFee(
) internal

removeLiquidity#

function removeLiquidity(
struct SwapUtils.Swap self,
uint256 amount,
uint256[] minAmounts
) external returns (uint256[])

Burn LP tokens to remove liquidity from the pool.

Liquidity can always be removed, even when the pool is paused.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
amountuint256the amount of LP tokens to burn
minAmountsuint256[]the minimum amounts of each token in the pool

acceptable for this burn. Useful as a front-running mitigation

Return Values:#

NameTypeDescription
amountsstruct SwapUtils.Swapof tokens the user received

removeLiquidityOneToken#

function removeLiquidityOneToken(
struct SwapUtils.Swap self,
uint256 tokenAmount,
uint8 tokenIndex,
uint256 minAmount
) external returns (uint256)

Remove liquidity from the pool all in one token.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
tokenAmountuint256the amount of the lp tokens to burn
tokenIndexuint8the index of the token you want to receive
minAmountuint256the minimum amount to withdraw, otherwise revert

Return Values:#

NameTypeDescription
amountstruct SwapUtils.Swapchosen token that user received

removeLiquidityImbalance#

function removeLiquidityImbalance(
struct SwapUtils.Swap self,
uint256[] amounts,
uint256 maxBurnAmount
) public returns (uint256)

Remove liquidity from the pool, weighted differently than the pool's current balances.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to read from and write to
amountsuint256[]how much of each token to withdraw
maxBurnAmountuint256the max LP token provider is willing to pay to

remove liquidity. Useful as a front-running mitigation.

Return Values:#

NameTypeDescription
actualstruct SwapUtils.Swapamount of LP tokens burned in the withdrawal

withdrawAdminFees#

function withdrawAdminFees(
struct SwapUtils.Swap self,
address to
) external

withdraw all admin fees to a given address

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to withdraw fees from
toaddressAddress to send the fees to

setAdminFee#

function setAdminFee(
struct SwapUtils.Swap self,
uint256 newAdminFee
) external

Sets the admin fee

adminFee cannot be higher than 100% of the swap fee

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to update
newAdminFeeuint256new admin fee to be applied on future transactions

setSwapFee#

function setSwapFee(
struct SwapUtils.Swap self,
uint256 newSwapFee
) external

update the swap fee

fee cannot be higher than 1% of each swap

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to update
newSwapFeeuint256new swap fee to be applied on future transactions

setDefaultWithdrawFee#

function setDefaultWithdrawFee(
struct SwapUtils.Swap self,
uint256 newWithdrawFee
) external

update the default withdraw fee. This also affects deposits made in the past as well.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to update
newWithdrawFeeuint256new withdraw fee to be applied

rampA#

function rampA(
struct SwapUtils.Swap self,
uint256 futureA_,
uint256 futureTime_
) external

Start ramping up or down A parameter towards given futureA and futureTime Checks if the change is too rapid, and commits the new A value only when it falls under the limit range.

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to update
futureA_uint256the new A to ramp towards
futureTime_uint256timestamp when the new A should be reached

stopRampA#

function stopRampA(
struct SwapUtils.Swap self
) external

Stops ramping A immediately. Once this function is called, rampA() cannot be called for another 24 hours

Parameters:#

NameTypeDescription
selfstruct SwapUtils.SwapSwap struct to update

Events#

TokenSwap#

event TokenSwap(
)

AddLiquidity#

event AddLiquidity(
)

RemoveLiquidity#

event RemoveLiquidity(
)

RemoveLiquidityOne#

event RemoveLiquidityOne(
)

RemoveLiquidityImbalance#

event RemoveLiquidityImbalance(
)

NewAdminFee#

event NewAdminFee(
)

NewSwapFee#

event NewSwapFee(
)

NewWithdrawFee#

event NewWithdrawFee(
)

RampA#

event RampA(
)

StopRampA#

event StopRampA(
)