Features Available
1. Find router
Func client.findRouters()
Aggregator Client v2 (v0.x.x) vs v3 (v1.x.x) Compatibility:
Input: The
findRouterInput
parameter structure is identical for both versionsOutput Changes: v3 replaces the
router
field withpaths
Optimization: v3 consolidates duplicate pools in the response, resulting in significant gas savings for multi-path routes
Params
Required parameters
from
String
The coin type of input coin.
target
String
The coin type of output coin.
amount
BN
The amount of input or output,determined byAmountIn
byAmountIn
Boolean
true
means fixed the amount of input, false
means fixed the amount of output.
Optional parameters
In principle, we do not recommend adding these optimal parameters if you don't have any specific custon needs, because our aggregator service will automatically optimize these settings in each SDK update to pursue optimal pricing and performance of transactions.
providers
String Array
Now, support cetus, deepbook v2/v3, kriya v2/v3, flowx v2/v3, aftermath, turbos, afsui, volo, haedal, bluemove, scallop, suilend, bluefin. If not set, it's will default support best providers by sdk version.
depth
Number
now depths support betweent 1 and 3, default setting is 3, it means you can get 3 hops path.
splitAlgorithm
String
devide_equally or geometric, recommand just use default devide_equally.
splitFactor
Number
used to contral geometric split width.
splitCount
Number
this field represents the maximum number of splits for a transaction. If you do not want to split, set it to 1. The default value is 20.
ResponseV3
When using Aggregator SDK v3 (version 1.0.0 or higher), the findRouter
method will return data in the RouterV3 structure.
quoteID
string
A randomly generated ID from the aggregator service for tracking index transactions and quotes.
amountIn
BN
Total amount in.
amountOut
BN
Total amount out.
byAmountIn
Boolean
true
means fixed the amount of input, false
means fixed the amount of output. This is the same as request parameters.
paths
Path[]
All liquidity paths data.
insufficientLiquidity
Boolean
true
means liquidity insufficient, false
means liquidity enough.
deviationRatio
Number
Price deviation ratio, (0.01 means 1%), indicating the degree of difference between the aggregator result and market price. When the price deviation ratio is undefined (no reference market price available) or relatively large (significant deviation from existing market prices), provide users with a reference option on whether to execute the trade at the current price to avoid potential asset losses.
packages
Map<string, string>
When user pass new version parameters, it will return newest aggregator packages data.
overlayFee
Number
The amount for overlay fee.
totalDeepFee
Number
Calculated need deep fee for deep pools.
error
RouterError
Error code and msg for aggregator.
ResponseV2
quoteID
string
A randomly generated ID from the aggregator service for tracking index transactions and quotes.
amountIn
BN
Total amount in.
amountOut
BN
Total amount out.
byAmountIn
Boolean
true
means fixed the amount of input, false
means fixed the amount of output. This is the same as request parameters.
routes
Router[]
All liquidity routes data.
insufficientLiquidity
Boolean
true
means liquidity insufficient, false
means liquidity enough.
deviationRatio
Number
Price deviation ratio, (0.01 means 1%), indicating the degree of difference between the aggregator result and market price. When the price deviation ratio is undefined (no reference market price available) or relatively large (significant deviation from existing market prices), provide users with a reference option on whether to execute the trade at the current price to avoid potential asset losses.
packages
Map<string, string>
When user pass new version parameters, it will return newest aggregator packages data.
overlayFee
Number
The amount for overlay fee.
totalDeepFee
Number
Calculated need deep fee for deep pools.
error
RouterError
Error code and msg for aggregator.
Example
import { AggregatorClient, getAllProviders } from "@cetusprotocol/aggregator-sdk"
import BN from "bn.js"
const client = new AggregatorClient({})
const amount = new BN(1000000)
const from = "0x2::sui::SUI"
const target = "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"
const providers = getAllProviders()
const routers = await client.findRouters({
from,
target,
amount,
byAmountIn: true, // `true` means fix input amount, `false` means fix output amount
providers
})
2. Build fast swap transaction
This method will send swaped coins to user directly. Here are three type fast swap params:
BuildFastRouterSwapParamsV3
: The new SDK version only supports this parameter format. (Only support in aggregator v3 version, version ≥ v1.0.0)BuildFastRouterSwapParamsV2
: This legacy parameter is no longer supported in the latest SDK versions (v >= 1.0.0).. (Only support in aggregator v2 version, v1.0.0> version >= v0.0.0)BuildFastRouterSwapParams
: Here's the English translation: This legacy parameter is no longer supported in the latest SDK versions (v >= 1.0.0).(Only support in aggregator v2 version, v1.0.0> version >= v0.0.0)
We recommend using the V3 version of the parameters if you upgrade to the latest SDK versions (version > v1.1.1). This way, if a contract on any platform undergoes a breaking update in the future, you won't need to make any changes; the SDK will automatically update to the latest contract address through the response returned by find router methods, while also reducing gas costs by leveraging the most optimized contract versions
BuildFastRouterSwapParamsV3
Required Params
router
RouterDataV3 Object
returned by find router method in latest aggregator sdk version
slippage
Number
A value between 0 and 1, representing the maximum allowed price slippage as a percentage. A value of 0.01 allows up to 1% price slippage. This parameter is crucial for protecting your assets in a rapidly changing market.
txb
Transaction
The programmable transaction builder.
Optional parameters
partner
String
The partner address. Details about partner can be found here. You can now set the partner directly during client initialization. This parameter will soon be deprecated; please migrate your configuration.
refreshAllCoins
Boolean
If true, retrieves all coin types when setting up the swap; if false, uses the existing coins.
payDeepFeeAmount
Number
The deep amount for pay deep fee in deepbookv3 path. Currently, all pools that charge a swap fee are covered by Cetus.
Example
import { AggregatorClient } from "@cetusprotocol/aggregator-sdk"
import { Transaction } from '@mysten/sui/transactions';
const client = new AggregatorClient({})
const amount = new BN(1000000)
const from = "0x2::sui::SUI"
const target = "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"
const routers = await client.findRouters({
from,
target,
amount,
byAmountIn: true, // `true` means fix input amount, `false` means fix output amount
})
const txb = new Transaction()
await client.fastRouterSwap({
routers,
txb,
slippage: 0.01,
})
3. Build swap transaction and return target coin object
This method will build transaction and return coin objects, used to build ptb.
BuildRouterSwapParamsV3
: The new parameter types is more clear and can support dynamic update latest package by aggregator.BuildRouterSwapParamsV2
: The new parameter types is more clear and can support dynamic update latest package by aggregator.BuildRouterSwapParams
: The old parameter types will continue to be supported.
BuildRouterSwapParamsV2
Required Params
routers
RouterData Object
Returned by find router method
inputCoin
TransactionObjectArgument
This represents the input coin object. If you only support swaps with a fixed input, simply extract a fixed amount from the coin object. If you support fixed output, you need to extract an amount limited by the specified constraints from the coin object.
slippage
Number
A value between 0 and 1, representing the maximum allowed price slippage as a percentage. A value of 0.01 allows up to 1% price slippage. This parameter is crucial for protecting your assets in a rapidly changing market.
txb
Transaction
The programmable transaction builder.
Optional parameters
partner
String
The partner address. Details about partner can be found here. You can now set the partner directly during client initialization. This parameter will soon be deprecated; please migrate your configuration.
refreshAllCoins
Boolean
If true, retrieves all coin types when setting up the swap; if false, uses the existing coins.
deepbookv3DeepFee
TransactionObjectArgument
The deep fee obejct argument for pay deep fee in deepbookv3 path. Currently, all pools that charge a swap fee are covered by Cetus.
Example
import { AggregatorClient } from "@cetusprotocol/aggregator-sdk"
import { Transaction } from '@mysten/sui/transactions';
const client = new AggregatorClient({})
const amount = new BN(1000000)
const from = "0x2::sui::SUI"
const target = "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS"
const routers = await client.findRouters({
from,
target,
amount,
byAmountIn: true, // `true` means fix input amount, `false` means fix output amount
})
const txb = new Transaction()
const targetCoin = await client.routerSwap({
routers,
txb,
inputCoin,
slippage: 0.01,
})
// you can use this target coin object argument to build your ptb.
client.transferOrDestoryCoin(
txb,
targetCoin,
target
)
4. Why use v3 swap params?
1. Automatically merges duplicate paths
By combining the latest path merging and sorting algorithms, duplicate pools are consolidated, resulting in significant gas savings when dealing with multiple split paths.
2. Support dynamic use latest package version
The new parameters will pass the entire result from find router, which includes the latest contract address. However, this feature is only effective in SDK versions greater than 0.3.18.
In the future, we will continue to support the old version of swap parameters in both swap methods. However, upgrading to the new version will allow you to avoid mandatory SDK version updates.
3. Remove duplicate parameter byAmountIn
Now, the find router result will return the value based on the amount in, allowing you to directly obtain it from the find router result in the new swap parameters.
5. How to Migrate to Aggregator V3?
No code changes needed for basic usage:
Use the latest sdk version. (version >= v1.1.1)
Client initialization stays the same
findRouter
now returns V3 structure automaticallyfastRouterSwap
androuterSwap
accept the new format transparentlyUpdate display logic only if showing detailed
RouterDataV3
to users
6. How to set providers?
You can ignore the providers parameters; the aggregator server will automatically set all usable providers based on the SDK version.
You can use the
getAllProviders()
method to retrieve all providers. Additionally, you can use thegetProvidersIncluding()
andgetProvidersExcluding()
methods to filter out specific providers or select only certain ones from the complete list.
import { getAllProviders, getProvidersExcluding } from "@cetusprotocol/aggregator-sdk"
const allProviders = getAllProviders()
console.log(allProviders)
[
'CETUS', 'KRIYA',
...
'MOMENTUM', 'STEAMM_OMM',
'STEAMM_OMM_V2'
]
const providersExcept = getProvidersExcluding(["CETUS"])
console.log(providersExcept)
[
'KRIYA', 'FLOWX',
...
'STEAMM_OMM', 'STEAMM_OMM_V2'
]
While you can manually specify the providers you want to use, as the number of providers increases, manual configuration may lead to the omission of some providers, which could affect your price advantage."
7. Common Errors
1. How to fix error "All Pyth price nodes are unavailable. Cannot fetch price data. Please switch to or add new available Pyth nodes. Detailed error: aborted"?
Reason: Some providers, such as Headalpmm and Metastable, rely on Pyth oracle prices when building transactions. Currently, we have a default configuration that connects to Pyth's publicly available node. However, if you frequently build transactions, you may encounter limitations with the Pyth public nodes(https://hermes.pyth.network).
Solutions: We recommend setting up a private Pyth node interface as an additional backup. This will ensure uninterrupted access to HaedalHMM and Metastable, even if the public node experiences occasional downtime.
const client = new AggregatorClient({
// endpoint, // If you do not have a exclusive aggregator api domain,just use cetus default aggregator endpoints.
signer: wallet,
client: suiClient,
env: Env.Mainnet,
pythUrls: ["YOUR_PYTH_URL", "ANOTHER_PYTH_URL"],
})
Another way, you can opt not to use Headalpmm and Metastable, but this will require you to manually configure the provider when find router.
const routers = await client.findRouters({
from,
target,
amount,
byAmountIn: true,
providers=["CETUS","SCALLOP","AFTERMATH","FLOWXV3","AFSUI","STEAMM","VOLO","KRIYAV3","KRIYA","ALPHAFI","FLOWX","BLUEMOVE","DEEPBOOKV3","BLUEFIN","HAEDAL","TURBOS","SPRINGSUI","STEAMM","METASTABLE","HAWAL","OBRIC"]
})
Last updated