SwapFlashLoan

Swap - A StableSwap implementation in solidity.

This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens in desired ratios for an exchange of the pool token that represents their share of the pool. Users can burn pool tokens and withdraw their share of token(s). Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets distributed to the LPs. In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which stops the ratio of the tokens in the pool from changing. Users can always withdraw their tokens via multi-asset withdraws.

Most of the logic is stored as a library SwapUtils for the sake of reducing contract's deployment size.

Methods

MAX_BPS

function MAX_BPS() external view returns (uint256)

Returns

NameTypeDescription

_0

uint256

undefined

addLiquidity

function addLiquidity(uint256[] amounts, uint256 minToMint, uint256 deadline) external nonpayable returns (uint256)

Add liquidity to the pool with the given amounts of tokens

Parameters

NameTypeDescription

amounts

uint256[]

the amounts of each token to add, in their native precision

minToMint

uint256

the minimum LP tokens adding this amount of liquidity should mint, otherwise revert. Handy for front-running mitigation

deadline

uint256

latest timestamp to accept this transaction

Returns

NameTypeDescription

_0

uint256

amount of LP token user minted and received

calculateRemoveLiquidity

function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[])

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

Parameters

NameTypeDescription

amount

uint256

the amount of LP tokens that would be burned on withdrawal

Returns

NameTypeDescription

_0

uint256[]

array of token balances that the user will receive

calculateRemoveLiquidityOneToken

function calculateRemoveLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex) external view returns (uint256 availableTokenAmount)

Calculate the amount of underlying token available to withdraw when withdrawing via only single token

Parameters

NameTypeDescription

tokenAmount

uint256

the amount of LP token to burn

tokenIndex

uint8

index of which token will be withdrawn

Returns

NameTypeDescription

availableTokenAmount

uint256

calculated amount of underlying token available to withdraw

calculateSwap

function calculateSwap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx) external view returns (uint256)

Calculate amount of tokens you receive on swap

Parameters

NameTypeDescription

tokenIndexFrom

uint8

the token the user wants to sell

tokenIndexTo

uint8

the token the user wants to buy

dx

uint256

the amount of tokens the user wants to sell. If the token charges a fee on transfers, use the amount that gets transferred after the fee.

Returns

NameTypeDescription

_0

uint256

amount of tokens the user will receive

calculateTokenAmount

function calculateTokenAmount(uint256[] amounts, bool deposit) external view 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

amounts

uint256[]

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

Returns

NameTypeDescription

_0

uint256

token amount the user will receive

flashLoan

function flashLoan(address receiver, contract IERC20 token, uint256 amount, bytes params) external nonpayable

Borrow the specified token from this pool for this transaction only. This function will call IFlashLoanReceiver(receiver).executeOperation and the receiver must return the full amount of the token and the associated fee by the end of the callback transaction. If the conditions are not met, this call is reverted.

Parameters

NameTypeDescription

receiver

address

the address of the receiver of the token. This address must implement the IFlashLoanReceiver interface and the callback function executeOperation.

token

contract IERC20

the protocol fee in bps to be applied on the total flash loan fee

amount

uint256

the total amount to borrow in this transaction

params

bytes

optional data to pass along to the callback function

flashLoanFeeBPS

function flashLoanFeeBPS() external view returns (uint256)

Returns

NameTypeDescription

_0

uint256

undefined

getA

function getA() external view returns (uint256)

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

See the StableSwap paper for details

Returns

NameTypeDescription

_0

uint256

A parameter

getAPrecise

function getAPrecise() external view returns (uint256)

Return A in its raw precision form

See the StableSwap paper for details

Returns

NameTypeDescription

_0

uint256

A parameter in its raw precision form

getAdminBalance

function getAdminBalance(uint256 index) external view returns (uint256)

This function reads the accumulated amount of admin fees of the token with given index

Parameters

NameTypeDescription

index

uint256

Index of the pooled token

Returns

NameTypeDescription

_0

uint256

admin's token balance in the token's precision

getToken

function getToken(uint8 index) external view returns (contract IERC20)

Return address of the pooled token at given index. Reverts if tokenIndex is out of range.

Parameters

NameTypeDescription

index

uint8

the index of the token

Returns

NameTypeDescription

_0

contract IERC20

address of the token at given index

getTokenBalance

function getTokenBalance(uint8 index) external view returns (uint256)

Return current balance of the pooled token at given index

Parameters

NameTypeDescription

index

uint8

the index of the token

Returns

NameTypeDescription

_0

uint256

current balance of the pooled token at given index with token's native precision

getTokenIndex

function getTokenIndex(address tokenAddress) external view returns (uint8)

Return the index of the given token address. Reverts if no matching token is found.

Parameters

NameTypeDescription

tokenAddress

address

address of the token

Returns

NameTypeDescription

_0

uint8

the index of the given token address

getVirtualPrice

function getVirtualPrice() external view returns (uint256)

Get the virtual price, to help calculate profit

Returns

NameTypeDescription

_0

uint256

the virtual price, scaled to the POOL_PRECISION_DECIMALS

initialize

function initialize(contract IERC20[] _pooledTokens, uint8[] decimals, string lpTokenName, string lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress) external nonpayable

Initializes this Swap contract with the given parameters. This will also clone a LPToken contract that represents users' LP positions. The owner of LPToken will be this contract - which means only this contract is allowed to mint/burn tokens.

Parameters

NameTypeDescription

_pooledTokens

contract IERC20[]

an array of ERC20s this pool will accept

decimals

uint8[]

the decimals to use for each pooled token, eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS

lpTokenName

string

the long-form name of the token to be deployed

lpTokenSymbol

string

the short symbol for the token to be deployed

_a

uint256

the amplification coefficient * n * (n - 1). See the StableSwap paper for details

_fee

uint256

default swap fee to be initialized with

_adminFee

uint256

default adminFee to be initialized with

lpTokenTargetAddress

address

the address of an existing LPToken contract to use as a target

owner

function owner() external view returns (address)

Returns the address of the current owner.

Returns

NameTypeDescription

_0

address

undefined

pause

function pause() external nonpayable

Pause the contract. Revert if already paused.

paused

function paused() external view returns (bool)

Returns true if the contract is paused, and false otherwise.

Returns

NameTypeDescription

_0

bool

undefined

protocolFeeShareBPS

function protocolFeeShareBPS() external view returns (uint256)

Returns

NameTypeDescription

_0

uint256

undefined

rampA

function rampA(uint256 futureA, uint256 futureTime) external nonpayable

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

futureA

uint256

the new A to ramp towards

futureTime

uint256

timestamp when the new A should be reached

removeLiquidity

function removeLiquidity(uint256 amount, uint256[] minAmounts, uint256 deadline) external nonpayable returns (uint256[])

Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly over period of 4 weeks since last deposit will apply.

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

Parameters

NameTypeDescription

amount

uint256

the amount of LP tokens to burn

minAmounts

uint256[]

the minimum amounts of each token in the pool acceptable for this burn. Useful as a front-running mitigation

deadline

uint256

latest timestamp to accept this transaction

Returns

NameTypeDescription

_0

uint256[]

amounts of tokens user received

removeLiquidityImbalance

function removeLiquidityImbalance(uint256[] amounts, uint256 maxBurnAmount, uint256 deadline) external nonpayable returns (uint256)

Remove liquidity from the pool, weighted differently than the pool's current balances. Withdraw fee that decays linearly over period of 4 weeks since last deposit will apply.

Parameters

NameTypeDescription

amounts

uint256[]

how much of each token to withdraw

maxBurnAmount

uint256

the max LP token provider is willing to pay to remove liquidity. Useful as a front-running mitigation.

deadline

uint256

latest timestamp to accept this transaction

Returns

NameTypeDescription

_0

uint256

amount of LP tokens burned

removeLiquidityOneToken

function removeLiquidityOneToken(uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline) external nonpayable returns (uint256)

Remove liquidity from the pool all in one token. Withdraw fee that decays linearly over period of 4 weeks since last deposit will apply.

Parameters

NameTypeDescription

tokenAmount

uint256

the amount of the token you want to receive

tokenIndex

uint8

the index of the token you want to receive

minAmount

uint256

the minimum amount to withdraw, otherwise revert

deadline

uint256

latest timestamp to accept this transaction

Returns

NameTypeDescription

_0

uint256

amount of chosen token user received

renounceOwnership

function renounceOwnership() external nonpayable

Leaves the contract without owner. It will not be possible to call onlyOwner functions anymore. Can only be called by the current owner. NOTE: Renouncing ownership will leave the contract without an owner, thereby removing any functionality that is only available to the owner.

setAdminFee

function setAdminFee(uint256 newAdminFee) external nonpayable

Update the admin fee. Admin fee takes portion of the swap fee.

Parameters

NameTypeDescription

newAdminFee

uint256

new admin fee to be applied on future transactions

setFlashLoanFees

function setFlashLoanFees(uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS) external nonpayable

Updates the flash loan fee parameters. This function can only be called by the owner.

Parameters

NameTypeDescription

newFlashLoanFeeBPS

uint256

the total fee in bps to be applied on future flash loans

newProtocolFeeShareBPS

uint256

the protocol fee in bps to be applied on the total flash loan fee

setSwapFee

function setSwapFee(uint256 newSwapFee) external nonpayable

Update the swap fee to be applied on swaps

Parameters

NameTypeDescription

newSwapFee

uint256

new swap fee to be applied on future transactions

stopRampA

function stopRampA() external nonpayable

Stop ramping A immediately. Reverts if ramp A is already stopped.

swap

function swap(uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline) external nonpayable returns (uint256)

Swap two tokens using this pool

Parameters

NameTypeDescription

tokenIndexFrom

uint8

the token the user wants to swap from

tokenIndexTo

uint8

the token the user wants to swap to

dx

uint256

the amount of tokens the user wants to swap from

minDy

uint256

the min amount the user would like to receive, or revert.

deadline

uint256

latest timestamp to accept this transaction

Returns

NameTypeDescription

_0

uint256

undefined

swapStorage

function swapStorage() external view returns (uint256 initialA, uint256 futureA, uint256 initialATime, uint256 futureATime, uint256 swapFee, uint256 adminFee, contract LPToken lpToken)

Returns

NameTypeDescription

initialA

uint256

undefined

futureA

uint256

undefined

initialATime

uint256

undefined

futureATime

uint256

undefined

swapFee

uint256

undefined

adminFee

uint256

undefined

lpToken

contract LPToken

undefined

transferOwnership

function transferOwnership(address newOwner) external nonpayable

Transfers ownership of the contract to a new account (newOwner). Can only be called by the current owner.

Parameters

NameTypeDescription

newOwner

address

undefined

unpause

function unpause() external nonpayable

Unpause the contract. Revert if already unpaused.

withdrawAdminFees

function withdrawAdminFees() external nonpayable

Withdraw all admin fees to the contract owner

Events

AddLiquidity

event AddLiquidity(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)

Parameters

NameTypeDescription

provider indexed

address

undefined

tokenAmounts

uint256[]

undefined

fees

uint256[]

undefined

invariant

uint256

undefined

lpTokenSupply

uint256

undefined

FlashLoan

event FlashLoan(address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee)

Parameters

NameTypeDescription

receiver indexed

address

undefined

tokenIndex

uint8

undefined

amount

uint256

undefined

amountFee

uint256

undefined

protocolFee

uint256

undefined

NewAdminFee

event NewAdminFee(uint256 newAdminFee)

Parameters

NameTypeDescription

newAdminFee

uint256

undefined

NewSwapFee

event NewSwapFee(uint256 newSwapFee)

Parameters

NameTypeDescription

newSwapFee

uint256

undefined

OwnershipTransferred

event OwnershipTransferred(address indexed previousOwner, address indexed newOwner)

Parameters

NameTypeDescription

previousOwner indexed

address

undefined

newOwner indexed

address

undefined

Paused

event Paused(address account)

Parameters

NameTypeDescription

account

address

undefined

RampA

event RampA(uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime)

Parameters

NameTypeDescription

oldA

uint256

undefined

newA

uint256

undefined

initialTime

uint256

undefined

futureTime

uint256

undefined

RemoveLiquidity

event RemoveLiquidity(address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply)

Parameters

NameTypeDescription

provider indexed

address

undefined

tokenAmounts

uint256[]

undefined

lpTokenSupply

uint256

undefined

RemoveLiquidityImbalance

event RemoveLiquidityImbalance(address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply)

Parameters

NameTypeDescription

provider indexed

address

undefined

tokenAmounts

uint256[]

undefined

fees

uint256[]

undefined

invariant

uint256

undefined

lpTokenSupply

uint256

undefined

RemoveLiquidityOne

event RemoveLiquidityOne(address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought)

Parameters

NameTypeDescription

provider indexed

address

undefined

lpTokenAmount

uint256

undefined

lpTokenSupply

uint256

undefined

boughtId

uint256

undefined

tokensBought

uint256

undefined

StopRampA

event StopRampA(uint256 currentA, uint256 time)

Parameters

NameTypeDescription

currentA

uint256

undefined

time

uint256

undefined

TokenSwap

event TokenSwap(address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId)

Parameters

NameTypeDescription

buyer indexed

address

undefined

tokensSold

uint256

undefined

tokensBought

uint256

undefined

soldId

uint128

undefined

boughtId

uint128

undefined

Unpaused

event Unpaused(address account)

Parameters

NameTypeDescription

account

address

undefined

Last updated