### Install SDK and Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Commands to install the SDK, required peer dependencies, and optional math libraries. ```bash npm install @cetusprotocol/aggregator-sdk # or yarn add @cetusprotocol/aggregator-sdk # or pnpm add @cetusprotocol/aggregator-sdk ``` ```bash npm install @mysten/sui bip39 dotenv ``` ```bash npm install bn.js decimal.js # For advanced math operations ``` -------------------------------- ### Install Aggregator SDK Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Install the package via npm. ```bash npm install @cetusprotocol/aggregator-sdk ``` -------------------------------- ### Overlay Fee Calculation Example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Example calculation for a fixed input swap with an overlay fee applied. ```typescript // Fixed input: 1000 SUI swap with 0.5% overlay fee // Expected USDC output: 5000 // Overlay fee: 5000 * 0.005 = 25 USDC // Net output: 4975 USDC // User receives: 4975 USDC // Fee recipient receives: 25 USDC ``` -------------------------------- ### Basic Transaction Setup with Aggregator SDK Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Initializes the transaction builder and executes a swap using the fast router method. ```typescript import { Transaction } from "@mysten/sui/transactions" import { AggregatorClient } from "@cetusprotocol/aggregator-sdk" const txb = new Transaction() const client = new AggregatorClient({ signer: "0x..." }) // Build swap await client.fastRouterSwap({ router: routerData, slippage: 0.01, txb }) // Execute const result = await client.sendTransaction(txb, userSigner) ``` -------------------------------- ### Example API Response Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/api-integration.md Sample JSON response from the router discovery endpoint. ```json { "code": 200, "msg": "success", "data": { "request_id": "quote-abc123", "amount_in": "1000000", "amount_out": "5234567", "deviation_ratio": 0.02, "paths": [ { "id": "0xpool123", "direction": true, "provider": "CETUS", "from": "0x2::sui::SUI", "target": "0x123::token::COIN", "fee_rate": 0.003, "amount_in": "1000000", "amount_out": "5234567", "published_at": "0xpublished...", "extended_details": { "afterSqrtPrice": "123456789" } } ], "packages": { "aggregator_v3": "0xpackage..." } } } ``` -------------------------------- ### Sponsored transaction workflow example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Demonstrates the end-to-end flow for a sponsored swap, including building the kind, adding gas, and executing. ```typescript // Remote gas station case const sender = userSigner.toSuiAddress() const sponsor = sponsorSigner.toSuiAddress() const txb = new Transaction() await client.fastRouterSwap({ router, slippage: 0.01, txb, sponsored: true }) // Send kind to gas station const txKindBytes = await client.buildTransactionKind(txb, sender) // Gas station receives txKindBytes, adds gas: const sponsoredTx = client.buildSponsoredTransaction({ txKindBytes, sender, sponsor, sponsorCoins: [...], gasBudget: "100000000" }) // Both sign and execute const result = await client.signAndExecuteSponsoredTransaction( sponsoredTx, userSigner, sponsorSigner ) ``` -------------------------------- ### CalculateAmountLimit Usage Example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md Demonstrates calculating slippage limits for both fixed-input and fixed-output swap scenarios. ```typescript import BN from "bn.js" import { CalculateAmountLimit } from "@cetusprotocol/aggregator-sdk" // Fixed input swap: expect 1000 output tokens, allow 1% slippage const minOutput = CalculateAmountLimit( new BN(1000), // expect 1000 tokens true, // fixed input 0.01 // 1% slippage ) // Result: 990 (minimum tokens to accept) // Fixed output swap: need exactly 1000 output, allow max 1% slippage on input const maxInput = CalculateAmountLimit( new BN(1000), // need 1000 tokens false, // fixed output 0.01 // 1% slippage ) // Result: 1010 (maximum input to spend) ``` -------------------------------- ### GET /deepbook_v3_config Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/api-integration.md Fetches DeepBook V3 trading parameters and payment configuration. ```APIDOC ## GET /deepbook_v3_config ### Description Fetches DeepBook V3 trading parameters and payment configuration. ### Method GET ### Endpoint /deepbook_v3_config ### Response #### Success Response (200) - **code** (number) - Status code. - **msg** (string) - Response message. - **data** (object) - Contains configuration details including id, is_alternative_payment, trade_cap, balance_manager, and whitelist_pools. ``` -------------------------------- ### CalculateAmountLimitBN Usage Example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md Demonstrates high-precision slippage calculation using BN objects. ```typescript import BN from "bn.js" import { CalculateAmountLimitBN } from "@cetusprotocol/aggregator-sdk" const maxInput = CalculateAmountLimitBN( new BN("1000000000000"), // High precision amount false, // Fixed output 0.005 // 0.5% slippage ) // Returns: BN("1005000000000") ``` -------------------------------- ### Execute router swap with explicit input Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Defines the signature for routerSwap and provides an example of its usage with a transaction builder. ```typescript async routerSwap(params: BuildRouterSwapParamsV3): Promise ``` ```typescript import { Transaction } from "@mysten/sui/transactions" const txb = new Transaction() const inputCoin = txb.object("0x...") // Your input coin const outputCoin = await client.routerSwap({ router: routerData, inputCoin: inputCoin, slippage: 0.01, txb: txb }) // Now use outputCoin in further PTB operations ``` -------------------------------- ### Create DEX Router Instances Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/dex-routers-overview.md Demonstrates initializing the AggregatorClient and creating routers for different DEX providers. ```typescript import { AggregatorClient, CETUS, TURBOS } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient({ env: Env.Mainnet }) // Create a Cetus router const cetusRouter = client.newDexRouterV3(CETUS, new Map()) // Create a Turbos router with Pyth prices const pythPrices = new Map([ ["some_price_id", "0x...price_info_object"] ]) const turbosRouter = client.newDexRouterV3(TURBOS, pythPrices) // Create a Cetus DLMM router with partner const dlmmRouter = client.newDexRouterV3( "CETUSDLMM", new Map(), undefined, "partner_address" ) ``` -------------------------------- ### Build and Publish with Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Use the --dependencies-are-root flag to bypass version check failures caused by incomplete interface definitions. ```bash sui move build --dependencies-are-root && sui client publish --dependencies-are-root ``` -------------------------------- ### Get coin balance Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md Retrieves the balance of a specific coin object as a bigint. ```typescript static getBalance(obj: SuiMoveObject): bigint ``` -------------------------------- ### Initialize Client with API Key Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/api-integration.md Use an API key during client instantiation to enable authentication and per-user rate limiting. ```typescript const client = new AggregatorClient({ apiKey: "your-api-key" }) ``` -------------------------------- ### Execute a Basic Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/00-START-HERE.md Initializes the client and executes a standard swap transaction using the fast router swap method. ```typescript const client = new AggregatorClient({ env: Env.Mainnet, signer }) const router = await client.findRouters({ from, target, amount, byAmountIn: true }) const txb = new Transaction() await client.fastRouterSwap({ router, slippage: 0.01, txb }) await client.sendTransaction(txb, signer) ``` -------------------------------- ### Get DEEP fee token type Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Returns the DEEP token type for the current environment. ```typescript deepbookv3DeepFeeType(): string ``` -------------------------------- ### Setting Gas Budget in TypeScript Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Demonstrates manual gas budget configuration for a transaction using the Sui SDK. ```typescript // SDK doesn't set gas budget automatically // Sui SDK uses smart gas estimation // Manual setting: const txb = new Transaction() // ... build transaction txb.setGasBudget(5000000) // 5M MIST // Or let SDK estimate (recommended) ``` -------------------------------- ### Handle API server errors Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/errors-and-constants.md Example of checking for specific server-side error codes returned by the aggregator API. ```typescript import { AggregatorServerErrorCode } from "@cetusprotocol/aggregator-sdk" const router = await client.findRouters(params) if (router?.error?.code === AggregatorServerErrorCode.InsufficientLiquidity) { console.log("No liquidity available for this pair") } ``` -------------------------------- ### Configure Overlay Fees Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Initialize the client with an overlay fee rate and receiver address. Ensure the rate is between 0 and 0.1 and the receiver is a valid address. ```typescript const client = new AggregatorClient({ overlayFeeRate: 0.005, // 0.5% overlayFeeReceiver: "0x123...fee_wallet" // Where fees go }) ``` -------------------------------- ### Handle SDK errors Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/errors-and-constants.md Example of catching and identifying specific SDK error codes using the AggregatorError helper. ```typescript import { AggregatorError, TypesErrorCode } from "@cetusprotocol/aggregator-sdk" try { // SDK operation } catch (e) { if (AggregatorError.isAggregatorErrorCode(e, TypesErrorCode.InvalidType)) { console.log("Invalid type error:", e.message) } } ``` -------------------------------- ### AggregatorClient Initialization Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/api-integration.md How to initialize the AggregatorClient with an API key and custom endpoint. ```APIDOC ## AggregatorClient Initialization ### Description Initialize the SDK client to interact with the aggregator service. You can provide an API key for authentication and a custom endpoint URL. ### Usage ```typescript const client = new AggregatorClient({ apiKey: "your-api-key", endpoint: "https://custom-aggregator.example.com/router" }) ``` ``` -------------------------------- ### Get Default Sqrt Price Limit Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md Retrieves the default sqrt price limit based on the swap direction. Returns a BN representing the boundary for A->B or B->A swaps. ```typescript function GetDefaultSqrtPriceLimit(a2b: boolean): BN ``` ```typescript import { GetDefaultSqrtPriceLimit } from "@cetusprotocol/aggregator-sdk" // Get price limit for A->B swap const limitA2B = GetDefaultSqrtPriceLimit(true) // Result: BN("4295048016") - minimum price to prevent extreme slippage // Get price limit for B->A swap const limitB2A = GetDefaultSqrtPriceLimit(false) // Result: BN("79226673515401279992447579055") - maximum price ``` -------------------------------- ### Initialize Client with Dotenv Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Load environment variables using the dotenv package to initialize the AggregatorClient. ```typescript import * as dotenv from "dotenv" dotenv.config() const client = new AggregatorClient({ env: process.env.SUI_NETWORK === "mainnet" ? Env.Mainnet : Env.Testnet, signer: process.env.WALLET_ADDRESS!, endpoint: process.env.AGGREGATOR_ENDPOINT, apiKey: process.env.AGGREGATOR_API_KEY, partner: process.env.PARTNER_ADDRESS, overlayFeeRate: parseFloat(process.env.OVERLAY_FEE_RATE || "0"), overlayFeeReceiver: process.env.FEE_RECEIVER, pythUrls: (process.env.PYTH_URLS || "").split(","), cetusDlmmPartner: process.env.CETUS_DLMM_PARTNER }) ``` -------------------------------- ### Swap Methods Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/README.md The SDK provides several methods for executing swaps, ranging from manual control to automated end-to-end processes. ```APIDOC ## Swap Methods ### routerSwap - **Type**: Manual - **Description**: Provides full control over the output coin during the swap process. ### fastRouterSwap - **Type**: Automatic - **Description**: Performs a simple end-to-end swap. ### mergeSwap - **Type**: Manual - **Description**: Used for multiple inputs with explicit control over the swap execution. ### fastMergeSwap - **Type**: Automatic - **Description**: Handles multiple inputs automatically. ### routerSwapWithMaxAmountIn - **Type**: Manual - **Description**: Used when input limit enforcement is required. ``` -------------------------------- ### Handle Client Initialization Errors Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Use try-catch blocks to manage errors during client instantiation, such as invalid fee rates. ```typescript try { const client = new AggregatorClient({ env: Env.Mainnet, signer: userAddress, overlayFeeRate: 0.15 // Invalid: > 0.1 }) } catch (error) { console.error("Invalid overlay fee rate:", error.message) } ``` -------------------------------- ### Create a new swap context Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md Initializes a swap context for fixed-amount swaps using the provided transaction builder and parameters. ```typescript import { newSwapContext } from "@cetusprotocol/aggregator-sdk" import { Transaction } from "@mysten/sui/transactions" const txb = new Transaction() const swapCtx = newSwapContext({ quoteID: "quote-123", fromCoinType: "0x2::sui::SUI", targetCoinType: "0x...::CETUS", expectAmountOut: "1000", amountOutLimit: "990", // 1% slippage inputCoin: txb.object("0x..."), feeRate: 0, feeRecipient: "0x0", packages: new Map([ ["aggregator_v3", "0x..."] ]) }, txb) ``` -------------------------------- ### Initialize AggregatorClient for Mainnet or Testnet Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Configure the client for specific network environments by setting the env property. ```typescript // Mainnet (production) const client = new AggregatorClient({ env: Env.Mainnet, signer: "0x..." }) // Testnet (development) const client = new AggregatorClient({ env: Env.Testnet, signer: "0x..." }) ``` -------------------------------- ### Define Environment Variables Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Required environment variables for network, wallet, and aggregator configuration. ```bash # Network configuration SUI_RPC="https://fullnode.mainnet.sui.io:443" SUI_NETWORK="mainnet" # Wallet SUI_WALLET_SECRET="base64_encoded_secret" WALLET_ADDRESS="0x123..." # Aggregator SDK AGGREGATOR_ENDPOINT="https://api-sui.cetus.zone/router_v3" AGGREGATOR_API_KEY="sk_live_..." # Partner/Fee configuration PARTNER_ADDRESS="0x456..." FEE_RECEIVER="0x789..." OVERLAY_FEE_RATE="0.001" # Pyth configuration PYTH_URLS="https://hermes.pyth.network,https://hermes2.pyth.network" # Cetus DLMM CETUS_DLMM_PARTNER="0xabc..." ``` -------------------------------- ### Initialize Aggregator Client Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Create a new instance of the AggregatorClient. ```typescript const client = new AggregatorClient({}) ``` -------------------------------- ### Initialize AggregatorClient with Keypair Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Derive a Sui address from a secret key to initialize the AggregatorClient. ```typescript import { Ed25519Keypair } from "@mysten/sui/keypairs/ed25519" // From keypair const keypair = Ed25519Keypair.fromSecretKey(secretKeyBytes) const address = keypair.toSuiAddress() const client = new AggregatorClient({ signer: address }) ``` -------------------------------- ### Simulate Liquidity Changes Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Perform backtesting by simulating LP position changes during route discovery. ```typescript interface PreSwapLpChangeParams { poolID: string ticklower: number tickUpper: number deltaLiquidity: number } const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x...::TOKEN", amount: new BN(1000000), byAmountIn: true, liquidityChanges: [ { poolID: "0xpool123", ticklower: -1000, tickUpper: 1000, deltaLiquidity: 1000000 } ] }) ``` -------------------------------- ### Fetch DeepBook V3 configuration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Retrieves the DeepBook V3 configuration, including alternative payment settings. ```typescript async getDeepbookV3Config(): Promise ``` -------------------------------- ### Run Sponsored Transaction Test Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Environment variables for running the sponsored transaction unit test. ```bash SUI_WALLET_SECRET="user_base64_secret" \ SUI_SPONSOR_SECRET="sponsor_base64_secret" \ npx vitest run tests/unit/sponsored.test.ts ``` ```bash SPONSORED_SWAP_AMOUNT=1000000 SPONSORED_GAS_BUDGET=100000000 SUI_RPC="https://fullnode.mainnet.sui.io:443" ``` -------------------------------- ### Build a Sponsored Swap Transaction Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Constructs a swap transaction with the sponsored flag enabled and demonstrates both remote gas station and local signing flows. ```typescript const sender = userSigner.toSuiAddress() const sponsor = sponsorSigner.toSuiAddress() const txb = new Transaction() // Build swap with sponsored flag await client.fastRouterSwap({ router: routerData, slippage: 0.01, txb, sponsored: true // Don't use gas coin }) // For gas station (remote): extract kind bytes const txKindBytes = await client.buildTransactionKind(txb, sender) // Send txKindBytes to gas station... // For local sponsor: sign together const sponsoredTx = client.buildSponsoredTransaction({ txKindBytes: await client.buildTransactionKind(txb, sender), sender, sponsor, sponsorCoins: [{ objectId: "0x...", version: "1", digest: "0x..." }], gasBudget: "100000000" }) const result = await client.signAndExecuteSponsoredTransaction( sponsoredTx, userSigner, sponsorSigner ) ``` -------------------------------- ### CoinUtils SDK Methods Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/mathematics-utilities.md A collection of static methods for coin asset management, including extraction, validation, selection, and balance calculation. ```APIDOC ## CoinUtils.getCoinTypeArg(obj: SuiMoveObject) ### Description Extracts the coin type argument from a given SuiMoveObject. ### Signature `static getCoinTypeArg(obj: SuiMoveObject): string | null` ## CoinUtils.isSUI(obj: SuiMoveObject) ### Description Checks if a provided SuiMoveObject represents a SUI coin. ### Signature `static isSUI(obj: SuiMoveObject): boolean` ## CoinUtils.getCoinSymbol(coinTypeArg: string) ### Description Extracts the symbol string from a coin type argument. ### Signature `static getCoinSymbol(coinTypeArg: string): string` ## CoinUtils.getBalance(obj: SuiMoveObject) ### Description Retrieves the balance of a specific coin object. ### Signature `static getBalance(obj: SuiMoveObject): bigint` ## CoinUtils.isSuiCoin(coinAddress: SuiAddress) ### Description Checks if a specific coin address represents a SUI coin. ### Signature `static isSuiCoin(coinAddress: SuiAddress): boolean` ## CoinUtils.getCoinAssets(coinType: string, allSuiObjects: CoinAsset[]) ### Description Filters a list of coin objects based on the provided coin type. ### Signature `static getCoinAssets(coinType: string, allSuiObjects: CoinAsset[]): CoinAsset[]` ## CoinUtils.selectCoinAssetGreaterThanOrEqual(coins: CoinAsset[], amount: bigint, exclude?: string[]) ### Description Selects a subset of coins that sum to at least the required amount, optionally excluding specific coin IDs. ### Signature `static selectCoinAssetGreaterThanOrEqual(coins: CoinAsset[], amount: bigint, exclude?: string[]): { selectedCoins: CoinAsset[]; remainingCoins: CoinAsset[] }` ## CoinUtils.selectCoinObjectIdGreaterThanOrEqual(coins: CoinAsset[], amount: bigint, exclude?: string[]) ### Description Selects coins that sum to at least the required amount and returns their object IDs and amount arrays. ### Signature `static selectCoinObjectIdGreaterThanOrEqual(coins: CoinAsset[], amount: bigint, exclude?: string[]): { objectArray: string[]; remainCoins: CoinAsset[]; amountArray: string[] }` ## CoinUtils.sortByBalance(coins: CoinAsset[]) ### Description Sorts an array of coins by balance in ascending order. ### Signature `static sortByBalance(coins: CoinAsset[]): CoinAsset[]` ## CoinUtils.sortByBalanceDes(coins: CoinAsset[]) ### Description Sorts an array of coins by balance in descending order. ### Signature `static sortByBalanceDes(coins: CoinAsset[]): CoinAsset[]` ## CoinUtils.calculateTotalBalance(coins: CoinAsset[]) ### Description Calculates the sum of balances for a list of coin objects. ### Signature `static calculateTotalBalance(coins: CoinAsset[]): bigint` ## CoinUtils.totalBalance(objs: CoinAsset[], coinAddress: SuiAddress) ### Description Calculates the total balance for a specific coin type within a list of coin assets. ### Signature `static totalBalance(objs: CoinAsset[], coinAddress: SuiAddress): bigint` ``` -------------------------------- ### Manage API Key via Environment Variables Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Store API keys in environment variables and access them securely within the application. ```bash # .env AGGREGATOR_API_KEY=sk_live_abc123... ``` ```typescript const client = new AggregatorClient({ apiKey: process.env.AGGREGATOR_API_KEY || "" }) ``` -------------------------------- ### Configure Pyth Oracle URLs Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Provide a list of Pyth Hermes endpoints for price feeds. ```typescript const client = new AggregatorClient({ pythUrls: [ "https://hermes.pyth.network", "https://hermes2.pyth.network", "https://hermes3.pyth.network" ] }) ``` -------------------------------- ### Implement CoinUtils helper class Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/types-and-interfaces.md Provides static methods for coin operations and asset management. ```typescript class CoinUtils { static getCoinTypeArg(obj: SuiMoveObject): string | null static isSUI(obj: SuiMoveObject): boolean static getCoinSymbol(coinTypeArg: string): string static getBalance(obj: SuiMoveObject): bigint static totalBalance(objs: CoinAsset[], coinAddress: SuiAddress): bigint static getID(obj: SuiMoveObject): string static getCoinTypeFromArg(coinTypeArg: string): string static getCoinAssets(coinType: string, allSuiObjects: CoinAsset[]): CoinAsset[] static isSuiCoin(coinAddress: SuiAddress): boolean static selectCoinObjectIdGreaterThanOrEqual( coins: CoinAsset[], amount: bigint, exclude?: string[] ): { objectArray: string[]; remainCoins: CoinAsset[]; amountArray: string[] } static selectCoinAssetGreaterThanOrEqual( coins: CoinAsset[], amount: bigint, exclude?: string[] ): { selectedCoins: CoinAsset[]; remainingCoins: CoinAsset[] } static sortByBalance(coins: CoinAsset[]): CoinAsset[] static sortByBalanceDes(coins: CoinAsset[]): CoinAsset[] static calculateTotalBalance(coins: CoinAsset[]): bigint } ``` -------------------------------- ### getDeepbookV3Config Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Fetches DeepBook V3 configuration including alternative payment settings. ```APIDOC ## getDeepbookV3Config ### Description Fetches DeepBook V3 configuration including alternative payment settings. ### Signature `async getDeepbookV3Config(): Promise` ``` -------------------------------- ### getDeepbookV3Config Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/INDEX.md Fetches DeepBook V3 trading parameters. ```APIDOC ## getDeepbookV3Config() ### Description Fetches DeepBook V3 trading parameters. ### Signature `async getDeepbookV3Config(): Promise` ``` -------------------------------- ### Calculating Swap and Gas Fees Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Shows the logic for calculating swap fees based on fee rates and the total cost including network gas fees. ```typescript // Swap fee = (amount * feeRate) const feeRate = path.feeRate // e.g., 0.003 = 0.3% const swapFee = amount * feeRate // Plus gas fees (paid to Sui network) const gasFee = gasUnits * gasPrice // Varies by network // Total cost = input + swapFees + gasFees ``` -------------------------------- ### Execute fast router swap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Defines the signature for fastRouterSwap and demonstrates how to execute a swap with automatic coin handling. ```typescript async fastRouterSwap(params: BuildFastRouterSwapParamsV3): Promise ``` ```typescript const txb = new Transaction() await client.fastRouterSwap({ router: routerData, slippage: 0.01, txb: txb, sponsored: false // Set true if sponsor pays gas }) // Execute transaction const result = await client.sendTransaction(txb, userSigner) ``` -------------------------------- ### fastRouterSwap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Automatically builds input coin using coinWithBalance and delivers output coin, handling coin merging/destruction. ```APIDOC ## fastRouterSwap ### Description Automatically builds input coin using `coinWithBalance` and delivers output coin. Handles coin merging/destruction. ### Signature `async fastRouterSwap(params: BuildFastRouterSwapParamsV3): Promise` ### Parameters - **router** (RouterDataV3) - Required - Router from findRouters - **slippage** (number) - Required - Slippage tolerance - **txb** (Transaction) - Required - Transaction builder - **partner** (string) - Optional - Partner address - **cetusDlmmPartner** (string) - Optional - Cetus DLMM partner - **refreshAllCoins** (boolean) - Optional - Refresh coin balances - **payDeepFeeAmount** (number) - Optional - Deep token amount for fees - **sponsored** (boolean) - Optional - Build for sponsored transaction (default: false) ``` -------------------------------- ### GET/POST /router_v3 Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/api-integration.md Retrieves optimal swap routes between two coins based on specified parameters such as amount, direction, and liquidity providers. ```APIDOC ## GET/POST /router_v3 ### Description Retrieves optimal swap routes between two coins based on specified parameters such as amount, direction, and liquidity providers. ### Method GET or POST ### Endpoint /router_v3 ### Parameters #### Query/Body Parameters - **from** (string) - Required - Source coin type - **target** (string) - Required - Destination coin type - **amount** (string) - Required - Amount as string (for precision) - **byAmountIn** (boolean) - Required - Fixed input/output - **depth** (number) - Optional - Route depth - **splitAlgorithm** (string) - Optional - Algorithm name - **splitFactor** (number) - Optional - Split configuration - **splitCount** (number) - Optional - Path count - **providers** (string[]) - Optional - Filtered DEX list - **liquidityChanges** (PreSwapLpChangeParams[]) - Optional - For simulation ### Response #### Success Response (200) - **code** (number) - Response code (200 = success) - **msg** (string) - Status message - **data** (object) - Aggregator response data containing request_id, amounts, and path details #### Response Example { "code": 200, "msg": "success", "data": { "request_id": "quote-abc123", "amount_in": "1000000", "amount_out": "5234567", "deviation_ratio": 0.02, "paths": [ { "id": "0xpool123", "direction": true, "provider": "CETUS", "from": "0x2::sui::SUI", "target": "0x123::token::COIN", "fee_rate": 0.003, "amount_in": "1000000", "amount_out": "5234567", "published_at": "0xpublished...", "extended_details": { "afterSqrtPrice": "123456789" } } ], "packages": { "aggregator_v3": "0xpackage..." } } } ``` -------------------------------- ### routerSwap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/INDEX.md Executes a swap with an explicit input coin and returns the output coin. ```APIDOC ## routerSwap(params: BuildRouterSwapParamsV3) ### Description Executes swap with explicit input coin, returns output coin. ### Signature `async routerSwap(params: BuildRouterSwapParamsV3): Promise` ``` -------------------------------- ### Router Selection with Provider Filtering Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/dex-routers-overview.md Demonstrates how to filter router selection by explicitly including or excluding specific DEX providers. ```typescript // Use only specific DEXs const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x...::CETUS", amount: new BN(1000000), byAmountIn: true, providers: ["CETUS", "TURBOS", "AFTERMATH"] // Only these DEXs }) // Exclude certain DEXs const providers = getProvidersExcluding(["SEVENK", "STEAMM"]) const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x...::CETUS", amount: new BN(1000000), byAmountIn: true, providers }) ``` -------------------------------- ### Default Pyth Configuration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Default settings for Pyth oracle connectivity. ```typescript const PYTH_DEFAULT = ["https://hermes.pyth.network"] const PYTH_TIMEOUT = 3000 // milliseconds ``` -------------------------------- ### routerSwap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Executes a swap with an explicit input coin and returns the output coin transaction object. ```APIDOC ## routerSwap ### Description Executes a swap with explicit input coin. Returns the output coin object. ### Signature `async routerSwap(params: BuildRouterSwapParamsV3): Promise` ### Parameters - **router** (RouterDataV3) - Required - Router data from findRouters - **inputCoin** (TransactionObjectArgument) - Required - Input coin transaction object - **slippage** (number) - Required - Slippage tolerance (0-1, e.g., 0.01 = 1%) - **txb** (Transaction) - Required - Transaction builder - **partner** (string) - Optional - Partner address override - **cetusDlmmPartner** (string) - Optional - Cetus DLMM partner override - **deepbookv3DeepFee** (TransactionObjectArgument) - Optional - Deep token for DeepBook V3 fees ### Return Value Returns `TransactionObjectArgument` representing the output coin from the swap. ``` -------------------------------- ### Find Swap Routes Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Retrieve the optimal swap route for a specific coin pair and amount. ```typescript import BN from "bn.js" const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS", amount: new BN(1000000), byAmountIn: true }) if (router && !router.insufficientLiquidity) { console.log("Best route found:", router) } ``` -------------------------------- ### getAllProviders Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/INDEX.md Retrieves a list of all supported DEX providers. ```APIDOC ## getAllProviders() ### Description Returns all supported DEX providers available in the aggregator. ### Returns - **string[]** - List of provider names. ``` -------------------------------- ### Execute a Sponsored Transaction Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/00-START-HERE.md Configures a swap transaction as sponsored and builds the transaction kind bytes for external gas station processing. ```typescript const txb = new Transaction() await client.fastRouterSwap({ router, slippage: 0.01, txb, sponsored: true }) const txKindBytes = await client.buildTransactionKind(txb, sender) // Pass txKindBytes to gas station... ``` -------------------------------- ### AggregatorClient Constructor Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Initializes a new instance of the AggregatorClient with the specified configuration parameters. ```APIDOC ## Constructor ### Description Initializes the AggregatorClient to interact with the Cetus aggregator service. ### Signature `new AggregatorClient(params: AggregatorClientParams)` ### Parameters - **endpoint** (string) - Optional - Aggregator API endpoint URL (default: "https://api-sui.cetus.zone/router_v3") - **signer** (string) - Optional - Wallet address for signing transactions - **client** (SuiGrpcClient) - Optional - Sui gRPC client instance - **env** (Env) - Optional - Network environment (Mainnet or Testnet) - **pythUrls** (string[]) - Optional - URLs for Pyth price oracle nodes - **apiKey** (string) - Optional - API key for aggregator service - **partner** (string) - Optional - Partner address for revenue sharing - **overlayFeeRate** (number) - Optional - Custom overlay fee rate (0 to 0.1) - **overlayFeeReceiver** (string) - Optional - Address receiving overlay fees - **cetusDlmmPartner** (string) - Optional - Partner identifier for Cetus DLMM pools ``` -------------------------------- ### Find multi-DEX routes with the SDK Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/dex-routers-overview.md Configures a router search with specific token paths and hop depth. The SDK automatically manages internal routing and execution logic. ```typescript const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x...::RARE_TOKEN", amount: new BN(1000000), byAmountIn: true, depth: 3 // Allow 3-hop routes }) // Router might suggest: SUI -> USDC (Cetus) -> USDT (Turbos) -> RARE_TOKEN (Aftermath) // The SDK handles all internal routing and execution ``` -------------------------------- ### Configure Aggregator Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Add these definitions to your Move.toml dependencies to include the specific aggregator packages. ```toml CetusAggregatorV2 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2/mainnet", rev = "mainnet-v1.63.0", override = true } CetusAggregatorV2ExtendV1 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2-extend-v1", rev = "mainnet-v1.63.0", override = true } CetusAggregatorV2ExtendV2 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2-extend-v2", rev = "mainnet-v1.63.0", override = true } ``` ```toml CetusAggregatorSimple = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2/simple-mainnet", rev = "mainnet-v1.63.0", override = true } ``` -------------------------------- ### Authenticate with API Key Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Provide an API key during client initialization for authentication. ```typescript const client = new AggregatorClient({ apiKey: "your-api-key-here" }) ``` -------------------------------- ### Configure DeepBook V3 Partner Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/configuration-and-setup.md Set a specific partner address for Cetus DLMM pools. ```typescript const client = new AggregatorClient({ cetusDlmmPartner: "0x..." // DLMM-specific partner }) ``` -------------------------------- ### Instantiate DEX Router V3 Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/dex-routers-overview.md Defines the factory method signature for creating a new DEX router instance. ```typescript function newDexRouterV3( provider: string, pythPriceIDs: Map, partner?: string, cetusDlmmPartner?: string ): DexRouter ``` -------------------------------- ### Execute Fixed Output Swaps Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Perform a swap for an exact output amount by setting the byAmountIn flag to false. ```typescript const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x...::USDC", amount: new BN(1000), // Need exactly 1000 USDC byAmountIn: false // This is the key flag }) await client.fastRouterSwap({ router, slippage: 0.01, txb }) ``` -------------------------------- ### Execute with signatures Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md Executes a transaction using pre-built bytes and a collection of signatures. ```typescript async executeWithSignatures(bytes: Uint8Array, signatures: string[]) ``` -------------------------------- ### client.getDeepbookV3Config Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Retrieves the configuration for DeepBook V3, including whitelisted pools. ```APIDOC ## getDeepbookV3Config ### Description Fetches the current DeepBook V3 configuration to determine if specific pools require DEEP token fee payments. ``` -------------------------------- ### Fee Configuration Constants Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/errors-and-constants.md Configuration for aggregator fees and overlay constraints. ```typescript // Aggregator V3 fee constants const AGGREGATOR_V3_CONFIG = { FEE_DENOMINATOR: 1000000, // Divisor for fee calculations MAX_FEE_RATE: 100000, // Maximum fee rate (10%) MAX_AMOUNT_IN: "18446744073709551615", // Maximum input amount DEFAULT_PUBLISHED_AT: { Mainnet: "0xde5d696a79714ca5cb910b9aed99d41f67353abb00715ceaeb0663d57ee39640", Testnet: "0x61da681cf2af95cb214a71596b49e662290065536984ed7e06b47e701ef547e3" } } ``` ```typescript const CLIENT_CONFIG = { MAX_OVERLAY_FEE_RATE: 0.1, // Maximum 10% overlay fee MAX_OVERLAY_FEE_RATE_NUMERATOR: 100000, // 0.1 * 1000000 FEE_RATE_MULTIPLIER: 1000000, // Convert to contract units DEFAULT_OVERLAY_FEE_RECEIVER: "0x0" // No fee receiver by default } ``` -------------------------------- ### CoinUtils Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/INDEX.md Static utility class providing methods for coin operations and balance calculations. ```APIDOC ## CoinUtils ### Description Static utility class for coin operations. ### Methods - `getCoinTypeArg(obj: SuiMoveObject): string | null` - `isSUI(obj: SuiMoveObject): boolean` - `getCoinSymbol(coinTypeArg: string): string` - `getBalance(obj: SuiMoveObject): bigint` - `totalBalance(objs: CoinAsset[], coinAddress: SuiAddress): bigint` - `getID(obj: SuiMoveObject): string` - `getCoinTypeFromArg(coinTypeArg: string): string` - `getCoinAssets(coinType: string, allSuiObjects: CoinAsset[]): CoinAsset[]` - `isSuiCoin(coinAddress: SuiAddress): boolean` - `selectCoinObjectIdGreaterThanOrEqual(coins, amount, exclude?): {...}` - `selectCoinAssetGreaterThanOrEqual(coins, amount, exclude?): {...}` - `sortByBalance(coins: CoinAsset[]): CoinAsset[]` - `sortByBalanceDes(coins: CoinAsset[]): CoinAsset[]` - `calculateTotalBalance(coins: CoinAsset[]): bigint` ``` -------------------------------- ### Execute Sponsored Transaction Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Perform a swap where a sponsor pays the gas fees. ```typescript import { Transaction } from "@mysten/sui/transactions" import { SUI_TYPE_ARG } from "@mysten/sui/utils" const sender = userSigner.toSuiAddress() const sponsor = sponsorSigner.toSuiAddress() const txb = new Transaction() await client.fastRouterSwap({ router: routerRes, txb, slippage: 0.01, sponsored: true, }) // Build command-only bytes. Pass sender so CoinWithBalance can resolve // the user's input coins before the sponsor adds gas data. const txKindBytes = await client.buildTransactionKind(txb, sender) const { objects: gasCoins } = await client.client.listCoins({ owner: sponsor, coinType: SUI_TYPE_ARG, limit: 1, }) const sponsorCoins = gasCoins.map((coin) => ({ objectId: coin.objectId, version: coin.version, digest: coin.digest, })) const sponsoredTx = client.buildSponsoredTransaction({ txKindBytes, sender, sponsor, sponsorCoins, gasBudget: "100000000", }) const result = await client.signAndExecuteSponsoredTransaction( sponsoredTx, userSigner, sponsorSigner ) ``` -------------------------------- ### Execute Fast Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Perform a swap using the identified routers and simulate the transaction. ```typescript const txb = new Transaction() if (routerRes != null) { await client.fastRouterSwap({ routers, txb, slippage: 0.01, }) const result = await client.devInspectTransactionBlock(txb, keypair) if (result.effects.status.status === "success") { console.log("Sim exec transaction success") const result = await client.signAndExecuteTransaction(txb, keypair) } console.log("result", result) } ``` -------------------------------- ### Build PTB and Return Target Coin Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Build a Programmable Transaction Block (PTB) using the swap result. ```typescript const txb = new Transaction() const byAmountIn = true if (routerRes != null) { const targetCoin = await client.routerSwap({ router: routerRes, txb, inputCoin, slippage: 0.01, }) // you can use this target coin object argument to build your ptb. client.transferOrDestoryCoin(txb, targetCoin, targetCoinType) const result = await client.devInspectTransactionBlock(txb, keypair) if (result.effects.status.status === "success") { console.log("Sim exec transaction success") const result = await client.signAndExecuteTransaction(txb, keypair) } console.log("result", result) } ``` -------------------------------- ### Configure Partner Revenue Sharing Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Route a portion of swap fees to a specified partner address. ```typescript await client.fastRouterSwap({ router: routerData, slippage: 0.01, txb, partner: "0x1234..." // Partner address }) ``` -------------------------------- ### Automatic Fast Router Swap Execution Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/transaction-building.md Simplifies swap execution by automatically handling coin building and delivery. ```typescript await client.fastRouterSwap({ router: routerData, slippage: 0.01, txb }) ``` -------------------------------- ### Provider Constants and Utility Functions Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/aggregator-client.md The SDK provides constants for supported DEX providers and utility functions to filter the provider list. ```APIDOC ## Provider Constants and Utilities ### Description Access supported DEX providers and filter them using utility functions. ### Available Providers CETUS, KRIYA, FLOWXV2, FLOWXV3, KRIYAV3, TURBOS, AFTERMATH, HAEDAL, VOLO, AFSUI, BLUEMOVE, DEEPBOOKV3, SCALLOP, SUILEND, BLUEFIN, HAEDALPMM, ALPHAFI, SPRINGSUI, STEAMM, METASTABLE, OBRIC, HAWAL, MOMENTUM, STEAMM_OMM, STEAMM_OMM_V2, MAGMA, SEVENK, HAEDALHMMV2, FULLSAIL, CETUSDLMM, FERRADLMM, FERRACLMM, BOLT, MAGMAPROPAMM, HAEDALPROPAMM ### Methods - **getAllProviders()**: Returns an array of all supported provider strings. - **getProvidersExcluding(excludeProviders: string[])**: Returns providers excluding the specified list. - **getProvidersIncluding(includeProviders: string[])**: Returns providers including only the specified list. ```