Increment
Search
K

Smart Contract API

Create a Pair

createPair

/// SwapFactory.cdc
pub fun createPair(
token0Vault: @FungibleToken.Vault,
token1Vault: @FungibleToken.Vault,
accountCreationFee: @FungibleToken.Vault,
stableMode: Bool
): Address
  • Example transaction create_pair_usdc_fusd.cdc
import FlowToken from 0x1654653399040a61
import FungibleToken from 0xf233dcee88fe0abe
import SwapFactory from 0xb063c16cac85dbd1
// Deploy a SwapPair given token{0|1}'s TokenName and contract address.
//`stableMode` specifies whether the pair uses Uniswap-V2 algorithm (stableMode:false) or Solidly-Stableswap algorithm (stableMode:true).
transaction(Token0Name: String, Token0Addr: Address, Token1Name: String, Token1Addr: Address, stableMode: Bool) {
prepare(userAccount: AuthAccount) {
let flowVaultRef = userAccount.borrow<&FlowToken.Vault>(from: /storage/flowTokenVault)!
assert(flowVaultRef.balance >= 0.002, message: "Insufficient balance to create pair, minimum balance requirement: 0.002 flow")
let accountCreationFeeVault <- flowVaultRef.withdraw(amount: 0.001)
let token0Vault <- getAccount(Token0Addr).contracts.borrow<&FungibleToken>(name: Token0Name)!.createEmptyVault()
let token1Vault <- getAccount(Token1Addr).contracts.borrow<&FungibleToken>(name: Token1Name)!.createEmptyVault()
SwapFactory.createPair(token0Vault: <-token0Vault, token1Vault: <-token1Vault, accountCreationFee: <-accountCreationFeeVault, stableMode: stableMode)
}
}

Get Pair & LpToken Info

Get Pairs' Addresses

/// SwapFactory.cdc && StableSwapFactory.cdc
pub fun getPairAddress(token0Key: String, token1Key: String): Address?
pub fun getAllPairsLength(): Int
pub fun getAllStableSwapPairsLength(): Int
pub fun getSlicedPairs(from: UInt64, to: UInt64): [Address]
Param
Type
Comments
from
UInt64
Start Index
to
UInt64
End Index
Return Value
[Address]
An array of deployed trading pair addresses
  • Get number of all deployed trading pairs and an array of deployed trading pair addresses.
  • Example script get_all_pair_addresses.cdc:
import SwapFactory from 0xb063c16cac85dbd1
pub fun main(): [Address] {
let len = SwapFactory.getAllPairsLength()
if (len == 0) {
return []
} else {
return SwapFactory.getSlicedPairs(from: 0, to: UInt64.max)
}
}

getPairInfo

/// SwapFactory.cdc && StableSwapFactory.cdc
pub fun getPairInfo(token0Key: String, token1Key: String): AnyStruct?
pub fun getSlicedPairInfos(from: UInt64, to: UInt64): [AnyStruct]
Param
Type
Comments
token0Key
String
token0's unique identifier, e.g.: A.3c5959b568896393.FUSD
token1Key
String
token1's unique identifier, e.g.: A.b19436aae4d94622.FiatToken
Return Value
AnyStruct?
nil if the pair doesn't exist, otherwise returns detailed pair info, e.g.:
[
token0Key,
token1Key,
token0Balance,
token1Balance,
pairAddress,
lpTokenBalance,
swapFeeBps,
isStableswap,
stableCurveP
]
/// SwapPair.cdc
pub resource PairPublic: SwapInterfaces.PairPublic {
pub fun getPairInfo(): [AnyStruct] {}
}
  • Example script to get PairInfo given the pair address:
import SwapInterfaces from 0xb78ef7afa52ff906
import SwapConfig from 0xb78ef7afa52ff906
pub fun main(pairAddr: Address): [AnyStruct] {
let pairPublicRef = getAccount(pairAddr)
.getCapability<&{SwapInterfaces.PairPublic}>(SwapConfig.PairPublicPath)
.borrow()
?? panic("cannot borrow reference to PairPublic resource")
return pairPublicRef.getPairInfo()
}
  • Example script `get_all_pair_infos.cdc`:
import SwapFactory from 0xb063c16cac85dbd1
pub fun main(): [AnyStruct] {
let len = SwapFactory.getAllPairsLength()
if (len == 0) {
return []
} else {
return SwapFactory.getSlicedPairInfos(from: 0, to: UInt64.max)
}
}

LpTokenCollection

Liquidity Provider (LP) of a trading pair will receive corresponding FT (i.e. LpToken) representing LP's pro rata share of that pair. LP may provide liquidity to different trading pairs and receive multiple different LpTokens. All these LpTokens are grouped within the LpTokenCollection resource, with methods exposing LpToken details:
/// SwapFactory.cdc
pub resource LpTokenCollection: SwapInterfaces.LpTokenCollectionPublic {
pub fun getAllLPTokens(): [Address] {}
pub fun getLpTokenBalance(pairAddr: Address): UFix64 {}
pub fun deposit(pairAddr: Address, lpTokenVault: @FungibleToken.Vault) {}
pub fun withdraw(pairAddr: Address, amount: UFix64): @FungibleToken.Vault {}
}
  • Example script to check all the LPed pairs and liquidity shares of a given account:
/// lpinfo.cdc
import SwapConfig from 0xb78ef7afa52ff906
import SwapInterfaces from 0xb78ef7afa52ff906
import SwapFactory from 0xb063c16cac85dbd1
pub fun main(userAddr: Address): {Address: AnyStruct} {
var lpTokenCollectionPublicPath = SwapConfig.LpTokenCollectionPublicPath
let lpTokenCollectionCap = getAccount(userAddr).getCapability<&{SwapInterfaces.LpTokenCollectionPublic}>(lpTokenCollectionPublicPath)
if lpTokenCollectionCap.check() == false {
return {}
}
let lpTokenCollectionRef = lpTokenCollectionCap.borrow()!
let liquidityPairAddrs = lpTokenCollectionRef.getAllLPTokens()
var res: {Address: AnyStruct} = {}
for pairAddr in liquidityPairAddrs {
let pairRef = getAccount(pairAddr).getCapability<&{SwapInterfaces.PairPublic}>(SwapConfig.PairPublicPath).borrow()
?? panic("cannot borrow reference to PairPublic")
let pairInfo = pairRef.getPairInfo()
let token0Key = pairInfo[0] as! String
let token1Key = pairInfo[1] as! String
let token0Balance = pairInfo[2] as! UFix64
let token1Balance = pairInfo[3] as! UFix64
let totalLp = pairInfo[5] as! UFix64
let lpTokenAmount = lpTokenCollectionRef.getLpTokenBalance(pairAddr: pairAddr)
res[pairAddr] = {
"token0": token0Key,
"token1": token1Key,
"token0Amount": lpTokenAmount / totalLp * token0Balance,
"token1Amount": lpTokenAmount / totalLp * token1Balance,
"shareOfPool": lpTokenAmount / totalLp * 100.0
}
}
return res
}
/// $ flow scripts execute lpinfo.cdc <0xUserAccount> --network mainnet

Swap

A straightforward way to contruct a Swap transaction is to use the SwapRouter, which provides a set of useful methods below.

Calculate output / input amount

getAmountsOut

/// SwapRouter.cdc
pub fun getAmountsOut(
amountIn: UFix64,
tokenKeyPath: [String]
): [UFix64]
Param
Type
Comments
amountIn
UFix64
Input token amount for the FT tokenKeyPath[0], e.g. 50.0
tokenKeyPath
[String]
An array of FT identifiers denoting the chained-swap path, e.g.: [A.3c5959b568896393.FUSD, A.1654653399040a61.FlowToken, A.b19436aae4d94622.FiatToken] => denoting the swap path of [FUSD -> Flow -> USDC].
tokenKeyPath.length must be >= 2, pools for each consecutive pair of FTs must exist and have liquidity.
Return Vaule
[UFix64]
Calculated maximum output FT amounts following the given swap path, e.g. [50.0, 10.0, 48.0]
  • Given the input amount of a FT, with an array of FT identifiers denoting the chained-swap path, calculates all subsequent maximum output token amounts.
  • Useful for calculating output token amounts before calling Perform chained-swap

getAmountsIn

/// SwapRouter.cdc
pub fun getAmountsIn(
amountOut: UFix64,
tokenKeyPath: [String]
): [UFix64]
Param
Type
Comments
amountOut
UFix64
Expected output amount of the FT to receive, e.g. 48.0
tokenKeyPath
[String]
An array of FT identifiers denoting the chained-swap path, e.g.: [A.3c5959b568896393.FUSD, A.1654653399040a61.FlowToken, A.b19436aae4d94622.FiatToken] => denoting the swap path of [FUSD -> Flow -> USDC].
tokenKeyPath.length must be >= 2, pools for each consecutive pair of FTs must exist and have liquidity.
Return Value
[UFix64]
Calculated minimum input FT amounts following the given swap path, e.g. [50.0, 10.0, 48.0]
  • Given the expected output amount of a FT, with an array of FT identifiers denoting the chained-swap path, calculates the minimum input FT amounts required to buy the given amountOut.
  • Useful for calculating input token amounts before calling Perform chained-swap

Perform chained-swap

swapExactTokensForTokens

/// SwapRouter.cdc
pub fun swapExactTokensForTokens(
exactVaultIn: @FungibleToken.Vault,
amountOutMin: UFix64,
tokenKeyPath: [String],
deadline: UFix64
): @FungibleToken.Vault
Param
Type
Comments
exactVaultIn
@FT.Vault
Input FT to sell, its full balance will be used.
amountOutMin
UFix64
The minimum amount of output token that must be received, otherwise the tx will revert.
tokenKeyPath
[String]
An array of FT identifiers denoting the chained-swap path, e.g.: [A.3c5959b568896393.FUSD, A.1654653399040a61.FlowToken, A.b19436aae4d94622.FiatToken] => denoting the swap path of [FUSD -> Flow -> USDC].
tokenKeyPath.length must be >= 2, pools for each consecutive pair of FTs must exist and have liquidity.
deadline
UFix64
Unix timestamp after which the tx will revert.
Return Value
@FT.Vault
Output FT resource
  • To receive as many output FT as possible for swapping the exact amount of input FT, by following the given swap path.
  • Example transaction swap_exact_flow_to_usdc.cdc:
import FungibleToken from 0xf233dcee88fe0abe
import SwapRouter from 0xa6850776a94e6551
transaction(
exactAmountIn: UFix64,
amountOutMin: UFix64,
path: [String],
to: Address,
deadline: UFix64
) {
prepare(userAccount: AuthAccount) {
let tokenInVaultPath = /storage/flowTokenVault
let tokenOutReceiverPath = /public/USDCVaultReceiver
let inVaultRef = userAccount.borrow<&FungibleToken.Vault>(from: tokenInVaultPath)
?? panic("Could not borrow reference to the owner's in FT.Vault")
/// Note: Receiver (to) should already have out FT.Vault initialized, otherwise tx reverts.
let outReceiverRef = getAccount(to).getCapability(tokenOutReceiverPath)
.borrow<&{FungibleToken.Receiver}>()
?? panic("Could not borrow receiver reference to the recipient's out FT.Vault")
let exactVaultIn <- inVaultRef.withdraw(amount: exactAmountIn)
let vaultOut <- SwapRouter.swapExactTokensForTokens(
exactVaultIn: <-exactVaultIn,
amountOutMin: amountOutMin,
tokenKeyPath: path,
deadline: deadline
)
outReceiverRef.deposit(from: <-vaultOut)
}
}

swapTokensForExactTokens

/// SwapRouter.cdc
pub fun swapTokensForExactTokens(
vaultInMax: @FungibleToken.Vault,
exactAmountOut: UFix64,
tokenKeyPath: [String],
deadline: UFix64
): @[FungibleToken.Vault] {
Param
Type
Comments
vaultInMax
@FT.Vault
Input FT to sell, whose balance is the maximum amount can be used before the tx reverts. Any remaining input token will be put in returnValue[1].
exactAmountOut
UFix64
The exact amount of output FT expected to receive.
tokenKeyPath
[String]
An array of FT identifiers denoting the chained-swap path, e.g.: [A.3c5959b568896393.FUSD, A.1654653399040a61.FlowToken, A.b19436aae4d94622.FiatToken] => denoting the swap path of [FUSD -> Flow -> USDC].
tokenKeyPath.length must be >= 2, pools for each consecutive pair of FTs must exist and have liquidity.
deadline
UFix64
Unix timestamp after which the tx will revert.
Return Value
@[FT.Vault]
2-element array of FT resources. * returnValue[0]: output token resource, whose balance will be exactAmountOut. * returnValue[1]: Any remaining input token resource.
  • To receive the exact amount of output FT for swapping as few input FT as possible, by following the given swap path.
  • Example transaction swap_flow_to_exact_usdc.cdc:
import FungibleToken from 0xf233dcee88fe0abe
import SwapRouter from 0xa6850776a94e6551
transaction(
amountInMax: UFix64,
exactAmountOut: UFix64,
path: [String],
to: Address,
deadline: UFix64
) {
prepare(userAccount: AuthAccount) {
let tokenInVaultPath = /storage/flowTokenVault
let tokenOutReceiverPath = /public/USDCVaultReceiver
let inVaultRef = userAccount.borrow<&FungibleToken.Vault>(from: tokenInVaultPath)
?? panic("Could not borrow reference to the owner's in FT.Vault")
/// Note: Receiver (to) should already have out FT.Vault initialized, otherwise tx reverts.
let outReceiverRef = getAccount(to).getCapability(tokenOutReceiverPath)
.borrow<&{FungibleToken.Receiver}>()
?? panic("Could not borrow receiver reference to the recipient's out FT.Vault")
let vaultInMax <- inVaultRef.withdraw(amount: amountInMax)
let swapResVault <- SwapRouter.swapTokensForExactTokens(
vaultInMax: <-vaultInMax,
exactAmountOut: exactAmountOut,
tokenKeyPath: path,
deadline: deadline
)
let vaultOut <- swapResVault.removeFirst()
let vaultInLeft <- swapResVault.removeLast()
destroy swapResVault
outReceiverRef.deposit(from: <-vaultOut)
/// Deposit any remaining input FT back
inVaultRef.deposit(from: <-vaultInLeft)
}
}
  • Note: Using flow-cli tool in the commandline environment, or fcl-js library as long with tx.cdc / script.cdc to interact with smart contracts directly.
  • *SwapRouter provides an easy way to perform chained swaps among non-stableswap pairs, but it won't work acrossing stableswap pairs: as for any two given tokens, there could be two SwapPair for them, the existing SwapRouter interfaces cannot easily support it. To perform chained swap among non-stableswap pairs and stableswap pairs, one needs to take an address array of pairs and understand SwapPair's raw apis (read below).

Helper functions and Raw apis

Helper functions in SwapConfig

/// SwapConfig.cdc
// For a non-stableswap pair (under the standard constant product formula x * y = k)
// Given pair reserves, swapFeeRateBps(0 ~ 10000), and the exact input amount of an asset, returns the maximum output amount of the other asset.
pub fun getAmountOutVolatile(amountIn: UFix64, reserveIn: UFix64, reserveOut: UFix64, swapFeeRateBps: UInt64): UFix64
// For a non-stableswap pair, given pair reserves, swapFeeRateBps, and the exact output amount of an asset wanted, returns the required (minimum) input amount of the other asset
pub fun getAmountInVolatile(amountOut: UFix64, reserveIn: UFix64, reserveOut: UFix64, swapFeeRateBps: UInt64): UFix64
// For a stableswap pair (under the solidly-stableswap formula: x^3 * y + x * y^3 = k)
// Given pair reserves, swapFeeRateBps, stableswap p-value(usually 1.0), and the exact input amount of an asset, returns the maximum output amount of the other asset
pub fun getAmountOutStable(amountIn: UFix64, reserveIn: UFix64, reserveOut: UFix64, p: UFix64, swapFeeRateBps: UInt64): UFix64
// For a stableswap pair, given pair reserves, swapFeeRateBps, stableswap p-value, and the exact input amount of an asset, returns the required (minimum) input amount of the other asset
pub fun getAmountInStable(amountOut: UFix64, reserveIn: UFix64, reserveOut: UFix64, p: UFix64, swapFeeRateBps: UInt64): UFix64
// Can be used to compute the spot price of a non-stableswap pair.
pub fun quote(amountA: UFix64, reserveA: UFix64, reserveB: UFix64): UFix64
// Can be used to compute the spot price of a stableswap pair.
pub fun quoteStable(amountA: UFix64, reserveA: UFix64, reserveB: UFix64, p: UFix64): UFix64
// Calculates the latest cumulative price of the given SwapPair, using the last cumulative record and current spot price.
// Usually a helper function in building dex-based TWAP oracle.
pub fun getCurrentCumulativePrices(pairAddr: Address): [UInt256; 3]

Raw apis in SwapPair

/// Each SwapPair.cdc
// The default rate is: 30 bps (0.3%) for non-stableswap pairs, and 4 bps (0.04%) for stableswap pairs.
pub fun getSwapFeeBps(): UInt64
pub fun isStableSwap(): Bool
// 1.0 for all non-stableswap pairs and most stableswap pairs. For now the only stableswap pair with a non-1.0 p-value is the `stFlow<>Flow` pair.
pub fun getStableCurveP(): UFix64
pub fun getAmountIn(amountOut: UFix64, tokenOutKey: String): UFix64
pub fun getAmountOut(amountIn: UFix64, tokenInKey: String): UFix64
// DEX-based TWAP oracle related helpful data, see twap oracle related section below for more examples.
pub fun getPrice0CumulativeLastScaled(): UInt256
pub fun getPrice1CumulativeLastScaled(): UInt256
pub fun getBlockTimestampLast(): UFix64
// Raw swap function, one can swap with pair contract directly and build any of the chained routes.
// If `exactAmountOut` is not-nil then a safety check ensures swapped output will not be smaller than the given value.
pub fun swap(vaultIn: @FungibleToken.Vault, exactAmountOut: UFix64?): @FungibleToken.Vault
// Request a flashloan from the current SwapPair, the default interest rate is 5 bps (0.05%).
// See flashloan related section below for explanations and examples.
pub fun flashloan(executorCap: Capability<&{SwapInterfaces.FlashLoanExecutor}>, requestedTokenVaultType: Type, requestedAmount: UFix64, params: {String: AnyStruct})

Add & Remove Liquidity

AddLiquidity

/// SwapPair.cdc
pub fun addLiquidity(
tokenAVault: @FungibleToken.Vault,
tokenBVault: @FungibleToken.Vault
): @FungibleToken.Vault
  • It's not recommended to use the low-level addLiquidity method directly, unless you're the 1st LP to set the initial price.
  • Use below example transaction to do slippage check and add liquidity at the ideal ratio:
import FungibleToken from 0xFungibleToken
import SwapFactory from 0xSwapFactory
import StableSwapFactory from 0xStableSwapFactory
import SwapInterfaces from 0xSwapInterfaces
import SwapConfig from 0xSwapConfig
import SwapError from 0xSwapError
transaction(
token0Key: String,
token1Key: String,
token0InDesired: UFix64,
token1InDesired: UFix64,
token0InMin: UFix64,
token1InMin: UFix64,
deadline: UFix64,
token0VaultPath: StoragePath,
token1VaultPath: StoragePath,
stableMode: Bool
) {
prepare(userAccount: AuthAccount) {
assert(deadline >= getCurrentBlock().timestamp, message:
SwapError.ErrorEncode(
msg: "AddLiquidity: expired ".concat(deadline.toString()).concat(" < ").concat(getCurrentBlock().timestamp.toString()),
err: SwapError.ErrorCode.EXPIRED
)
)
let pairAddr = (stableMode)?
StableSwapFactory.getPairAddress(token0Key: token0Key, token1Key: token1Key) ?? panic("AddLiquidity: nonexistent stable pair ".concat(token0Key).concat(" <-> ").concat(token1Key).concat(", create stable pair first"))
:
SwapFactory.getPairAddress(token0Key: token0Key, token1Key: token1Key) ?? panic("AddLiquidity: nonexistent pair ".concat(token0Key).concat(" <-> ").concat(token1Key).concat(", create pair first"))
let pairPublicRef = getAccount(pairAddr).getCapability<&{SwapInterfaces.PairPublic}>(SwapConfig.PairPublicPath).borrow()!
/*
pairInfo = [
SwapPair.token0Key,
SwapPair.token1Key,
SwapPair.token0Vault.balance,
SwapPair.token1Vault.balance,
SwapPair.account.address,
SwapPair.totalSupply
...
]
*/
let pairInfo = pairPublicRef.getPairInfo()
var token0In = 0.0
var token1In = 0.0
var token0Reserve = 0.0
var token1Reserve = 0.0
if token0Key == (pairInfo[0] as! String) {
token0Reserve = (pairInfo[2] as! UFix64)
token1Reserve = (pairInfo[3] as! UFix64)
} else {
token0Reserve = (pairInfo[3] as! UFix64)
token1Reserve = (pairInfo[2] as! UFix64)
}
if token0Reserve == 0.0 && token1Reserve == 0.0 {
token0In = token0InDesired
token1In = token1InDesired
} else {
var amount1Optimal = SwapConfig.quote(amountA: token0InDesired, reserveA: token0Reserve, reserveB: token1Reserve)
if (amount1Optimal <= token1InDesired) {
assert(amount1Optimal >= token1InMin, message:
SwapError.ErrorEncode(
msg: "SLIPPAGE_OFFSET_TOO_LARGE expect min".concat(token1InMin.toString()).concat(" got ").concat(amount1Optimal.toString()),
err: SwapError.ErrorCode.SLIPPAGE_OFFSET_TOO_LARGE
)
)
token0In = token0InDesired
token1In = amount1Optimal
} else {
var amount0Optimal = SwapConfig.quote(amountA: token1InDesired, reserveA: token1Reserve, reserveB: token0Reserve)
assert(amount0Optimal <= token0InDesired)
assert(amount0Optimal >= token0InMin, message:
SwapError.ErrorEncode(
msg: "SLIPPAGE_OFFSET_TOO_LARGE expect min".concat(token0InMin.toString()).concat(" got ").concat(amount0Optimal.toString()),
err: SwapError.ErrorCode.SLIPPAGE_OFFSET_TOO_LARGE
)
)
token0In = amount0Optimal
token1In = token1InDesired
}
}
let token0Vault <- userAccount.borrow<&FungibleToken.Vault>(from: token0VaultPath)!.withdraw(amount: token0In)
let token1Vault <- userAccount.borrow<&FungibleToken.Vault>(from: token1VaultPath)!.withdraw(amount: token1In)
let lpTokenVault <- pairPublicRef.addLiquidity(
tokenAVault: <- token0Vault,
tokenBVault: <- token1Vault
)
let lpTokenCollectionStoragePath = SwapConfig.LpTokenCollectionStoragePath
let lpTokenCollectionPublicPath = SwapConfig.LpTokenCollectionPublicPath
var lpTokenCollectionRef = userAccount.borrow<&SwapFactory.LpTokenCollection>(from: lpTokenCollectionStoragePath)
if lpTokenCollectionRef == nil {
destroy <- userAccount.load<@AnyResource>(from: lpTokenCollectionStoragePath)
userAccount.save(<-SwapFactory.createEmptyLpTokenCollection(), to: lpTokenCollectionStoragePath)
userAccount.link<&{SwapInterfaces.LpTokenCollectionPublic}>(lpTokenCollectionPublicPath, target: lpTokenCollectionStoragePath)
lpTokenCollectionRef = userAccount.borrow<&SwapFactory.LpTokenCollection>(from: lpTokenCollectionStoragePath)
}
lpTokenCollectionRef!.deposit(pairAddr: pairAddr, lpTokenVault: <- lpTokenVault)
}
}

RemoveLiquidity

/// SwapPair.cdc
pub fun removeLiquidity(
lpTokenVault: @FungibleToken.Vault
) : @[FungibleToken.Vault] {
  • Example transaction below to burn lpToken and deposit back removed two-sided liquidities:
import FungibleToken from 0xFungibleToken
import SwapFactory from 0xSwapFactory
import StableSwapFactory from 0xStableSwapFactory
import SwapInterfaces from 0xSwapInterfaces
import SwapConfig from 0xSwapConfig
import SwapError from 0xSwapError
transaction(
token0Key: String,
token1Key: String,
lpTokenAmount: UFix64,
token0OutMin: UFix64,
token1OutMin: UFix64,
deadline: UFix64,
token0VaultPath: StoragePath,
token1VaultPath: StoragePath,
stableMode: Bool
) {
prepare(userAccount: AuthAccount) {
assert(deadline >= getCurrentBlock().timestamp, message:
SwapError.ErrorEncode(
msg: "RemoveLiquidity: expired ".concat(deadline.toString()).concat(" < ").concat(getCurrentBlock().timestamp.toString()),
err: SwapError.ErrorCode.EXPIRED
)
)
let pairAddr = (stableMode)?
StableSwapFactory.getPairAddress(token0Key: token0Key, token1Key: token1Key) ?? panic("AddLiquidity: nonexistent stable pair ".concat(token0Key).concat(" <-> ").concat(token1Key).concat(", create stable pair first"))
:
SwapFactory.getPairAddress(token0Key: token0Key, token1Key: token1Key) ?? panic("AddLiquidity: nonexistent pair ".concat(token0Key).concat(" <-> ").concat(token1Key).concat(", create pair first"))
let lpTokenCollectionRef = userAccount.borrow<&SwapFactory.LpTokenCollection>(from: SwapConfig.LpTokenCollectionStoragePath)
?? panic("RemoveLiquidity: cannot borrow reference to LpTokenCollection")
let lpTokenRemove <- lpTokenCollectionRef.withdraw(pairAddr: pairAddr, amount: lpTokenAmount)
let tokens <- getAccount(pairAddr).getCapability<&{SwapInterfaces.PairPublic}>(SwapConfig.PairPublicPath).borrow()!.removeLiquidity(lpTokenVault: <-lpTokenRemove)
let token0Vault <- tokens[0].withdraw(amount: tokens[0].balance)
let token1Vault <- tokens[1].withdraw(amount: tokens[1].balance)
destroy tokens
assert(token0Vault.balance >= token0OutMin && token1Vault.balance >= token1OutMin, message:
SwapError.ErrorEncode(
msg: "RemoveLiquidity: INSUFFICIENT_REMOVE_LIQUIDITY_OUT_AMOUNT",
err: SwapError.ErrorCode.SLIPPAGE_OFFSET_TOO_LARGE
)
)
/// Here does not detect whether the local receiver vault exsit.
let localVault0Ref = userAccount.borrow<&FungibleToken.Vault>(from: token0VaultPath)!
let localVault1Ref = userAccount.borrow<&FungibleToken.Vault>(from: token1VaultPath)!
if token0Vault.isInstance(localVault0Ref.getType()) {
localVault0Ref.deposit(from: <-token0Vault)
localVault1Ref.deposit(from: <-token1Vault)
} else {
localVault0Ref.deposit(from: <-token1Vault)
localVault1Ref.deposit(from: <-token0Vault)
}
}
}

Build a TWAP Oracle

  • DEX-based TWAP (time-weighted-average-price) oracles can be built using the last cumulative prices recorded in each SwapPair.
  • However, to correctly use & integrate the twap-oracle into your projects, you must ensure the sampling of the cumulative price data are kept up to date. As long as your oracle is up to date, you can depend on it to produce average prices.
Check below 2 examples for the sampling (update()) and twap-data consuming (twap()).

Fixed-window TWAP oracle example:

import StableSwapFactory from 0xStableSwapFactoryAddr
import SwapFactory from 0xSwapFactoryAddr
import SwapInterfaces from 0xSwapInterfacesAddr
import SwapConfig from 0xSwapConfigAddr
/// Fixed window oracle
///
/// Calculate the average price for the entire period based on the on-chain dex swap pair.
/// note that the price average is only guaranteed to be over at least 1 period, but may be over a longer period
///
pub contract FixedWindowOracleExample {
/// Window period of the average in seconds
pub let PERIOD: UInt64
/// A.contractAddr.contractName: A.11111111.FlowToken, A.2222222.FUSD
pub let token0Key: String
pub let token1Key: String
pub let isStableswap: Bool
/// pair address in dex
pub let pairAddr: Address
/// Average price for each PERIOD, updated once per PERIOD (updating interval could be longer than 1 PERIOD)
pub var price0Average: UFix64
pub var price1Average: UFix64
/// Cumulative price/timestamp for the last update
pub var price0CumulativeLastScaled: UInt256
pub var price1CumulativeLastScaled: UInt256
pub var blockTimestampLast: UFix64
/// Sampling: update the accumulated price if it exceeds the period.
pub fun update() {
let now = getCurrentBlock().timestamp
let timeElapsed = now - self.blockTimestampLast
assert(timeElapsed >= UFix64(self.PERIOD), message: "PERIOD_NOT_ELAPSED ".concat(timeElapsed.toString().concat("s")))
let res = SwapConfig.getCurrentCumulativePrices(