### Complete AggregatorClient Configuration Example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Provides a comprehensive example of configuring the AggregatorClient with all available options, including network, RPC, signer, API key, Pyth URLs, fee settings, and partner IDs. ```typescript const client = new AggregatorClient({ // Network and RPC env: Env.Mainnet, endpoint: "https://api-sui.cetus.zone/router_v3", // Signer address signer: "0x1234567890abcdef...", // Custom Sui RPC client client: suiJsonRpcClient, // API key for rate limit increases apiKey: "your-api-key", // Pyth oracle for price feeds pythUrls: [ "https://hermes.pyth.network", "https://hermes.pyth.network/api" // fallback ], // Fee configuration overlayFeeRate: 0.01, // 1% - multiplied by 1,000,000 internally overlayFeeReceiver: "0xfeereceiver...", // Partner configuration (deprecated in favor of method params) partner: "partner-id", cetusDlmmPartner: "dlmm-partner-id" }) ``` -------------------------------- ### Install Cetus Aggregator SDK Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Install the SDK using npm. This is the first step to integrate the aggregator into your project. ```bash npm install @cetusprotocol/aggregator-sdk ``` -------------------------------- ### Development Setup (Testnet) Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Configure the Aggregator client for development on the testnet. This setup is simpler, typically not requiring an API key or fee collection. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" const devClient = new AggregatorClient({ env: Env.Testnet, signer: "0xdev...", pythUrls: ["https://hermes.pyth.network"] }) export default devClient ``` -------------------------------- ### Initialize AggregatorClient Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/00-index.md Example of initializing the AggregatorClient with mainnet environment and a signer address. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient({ env: Env.Mainnet, signer: "0x..." }) ``` -------------------------------- ### Minimal Setup (Use All Defaults) Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Initialize the Aggregator client using all default settings. This uses the mainnet, a default API endpoint, no fee collection, and requires the signer to be set before use. ```typescript import { AggregatorClient } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient() // Uses: // - Mainnet // - Default endpoint: https://api-sui.cetus.zone/router_v3 // - No fee collection // - No signer (set before calling methods) // - Default Sui RPC export default client ``` -------------------------------- ### Complete Example: Simple Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Demonstrates a full swap execution flow using the AggregatorClient. This includes finding the best swap route, building the transaction, and sending it for execution. Ensure you have the necessary imports and a valid signer address. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" import { Transaction } from "@mysten/sui/transactions" import BN from "bn.js" const client = new AggregatorClient({ env: Env.Mainnet, signer: "0x123..." // Your Sui address }) async function executeSwap() { // Find best swap route const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS", amount: new BN(1000000), byAmountIn: true, }) if (!router || router.error) { console.error("Route not found:", router?.error?.msg) return } // Build transaction const txb = new Transaction() const outputCoin = await client.routerSwap({ router, inputCoin: txb.splitCoins(txb.gas, [txb.pure.u64(1000000)])[0], slippage: 0.01, // 1% slippage tolerance txb, }) // Send transaction const result = await client.sendTransaction(txb, signer) console.log("Swap result:", result) } ``` -------------------------------- ### Example of Multiple Swap Paths Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/02-types.md Illustrates a potential structure for the 'paths' array within a RouterDataV3 object, showing sequential swap steps across different DEX providers. ```typescript // router.paths might be: // [ // { provider: "CETUS", from: "SUI", target: "USDC", amountIn: "1000000", amountOut: "2100" }, // { provider: "TURBOS", from: "USDC", target: "CETUS", amountIn: "2100", amountOut: "500" } // ] ``` -------------------------------- ### Complete Coin Management Example Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/05-utilities.md Demonstrates a full workflow for managing coins, including filtering for a specific asset (USDC), calculating the total balance, selecting coins for a swap, finding the best swap route across all providers, and calculating the minimum output amount with slippage. ```typescript import { CoinUtils, CalculateAmountLimitBN, getAllProviders } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" // Assume we have user's coins const userCoins = await client.client.getCoins({ owner: "0xuser...", }) // Filter to USDC only const usdcCoins = CoinUtils.getCoinAssets( "0x5d4b302506645c37ff133b98c4b50864d503d656915860ce7d3a6736d6c0ea5a::usdc::USDC", userCoins.data.map(coin => ({ coinObjectId: coin.coinObjectId, coinAddress: coin.coinType, balance: BigInt(coin.balance) })) ) // Calculate total USDC const totalUsdc = CoinUtils.calculateTotalBalance(usdcCoins) console.log(`Total USDC: ${totalUsdc}`) // Select coins for swap const swapAmount = BigInt(1000000) // 1 USDC const { selectedCoins } = CoinUtils.selectCoinAssetGreaterThanOrEqual( usdcCoins, swapAmount ) if (selectedCoins.length === 0) { console.error("Insufficient USDC balance") return } // Find best swap using all providers const router = await client.findRouters({ from: "0x5d4b302506645c37ff133b98c4b50864d503d656915860ce7d3a6736d6c0ea5a::usdc::USDC", target: "0x2::sui::SUI", amount: new BN(swapAmount.toString()), byAmountIn: true, providers: getAllProviders() }) // Calculate minimum output with 1% slippage const minAmountOut = CalculateAmountLimitBN( router.amountOut, true, 0.01 ) console.log(`Expected SUI: ${router.amountOut.toString()}`) console.log(`Minimum SUI (1% slippage): ${minAmountOut.toString()}`) ``` -------------------------------- ### Module Dependencies Overview Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Provides a hierarchical view of the project's module dependencies, starting from the main entry point. ```plaintext client.ts (main entry point) ├─ types/shared.ts (type definitions) ├─ api.ts (route finding) │ ├─ types/shared.ts │ ├─ const.ts │ ├─ errors.ts │ └─ utils/coin.ts ├─ config.ts (Env enum) ├─ math.ts (slippage calculation) ├─ const.ts (constants) ├─ movecall/router.ts (swap context) │ ├─ movecall/* (DEX routers) │ └─ const.ts ├─ movecall/* (30+ DEX implementations) ├─ pyth/adapter.ts (Pyth oracle) ├─ utils/ (coin, config, UUID utilities) └─ types/CoinAssist.ts (CoinUtils) ``` -------------------------------- ### Production Setup with Fee Collection Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Configure the Aggregator client for production use on the mainnet. This includes setting an API key, collecting a fee, and specifying multiple Pyth URLs for redundancy. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient({ env: Env.Mainnet, signer: process.env.SIGNER_ADDRESS, apiKey: process.env.AGGREGATOR_API_KEY, // Collect 0.5% fee on all swaps overlayFeeRate: 0.005, overlayFeeReceiver: process.env.FEE_RECIPIENT, // Multiple Pyth URLs for redundancy pythUrls: [ "https://hermes.pyth.network", "https://hermes-beta.pyth.network" ], // Partner for analytics partner: "my-platform" }) export default client ``` -------------------------------- ### Implement Fallback Strategy for Swap Errors Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/06-examples.md This example demonstrates how to handle potential API errors, such as rate limits or insufficient liquidity, by implementing fallback mechanisms to find alternative routes. It includes a delay before retrying with a subset of providers. ```typescript import { AggregatorClient, AggregatorServerErrorCode } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" const client = new AggregatorClient() async function swapWithFallback(from: string, target: string, amount: BN) { // Primary: All providers let router = await client.findRouters({ from, target, amount, byAmountIn: true }) // If rate limited, retry with fewer providers if (router?.error?.code === AggregatorServerErrorCode.RateLimitExceeded) { console.warn("Rate limited, trying with subset of providers...") await new Promise(r => setTimeout(r, 5000)) router = await client.findRouters({ from, target, amount, byAmountIn: true, providers: ["CETUS", "TURBOS", "KRIYAV3"] }) } // If insufficient liquidity, try reduced amount if (router?.insufficientLiquidity) { console.warn("Insufficient liquidity at full amount, trying 80%...") const reducedAmount = amount.mul(new BN(80)).div(new BN(100)) router = await client.findRouters({ from, target, amount: reducedAmount, byAmountIn: true }) } // Final check if (!router || router.error) { throw new Error(`No route found: ${router?.error?.msg}`) } return router } swapWithFallback( "0x2::sui::SUI", "0xcetus::CETUS", new BN(1000000) ).then(router => { console.log("Found route:", router.amountOut.toString()) }).catch(err => { console.error("Swap failed:", err.message) }) ``` -------------------------------- ### Runtime Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Lists the runtime dependencies that the Aggregator SDK relies on to function. These will be automatically installed when you add the SDK to your project. ```json { "@mysten/sui": "^2.6.0", "@pythnetwork/hermes-client": "^3.1.0", "bip39": "^3.1.0", "dotenv": "^16.4.5", "json-bigint": "^1.0.0", "node-fetch": "^3.3.2" } ``` -------------------------------- ### Get DeepBook V3 Configuration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Retrieves the current DeepBook V3 configuration, including whitelisted pools and fee settings. Returns configuration data or null on error. ```typescript async getDeepbookV3Config(): Promise ``` ```typescript const config = await client.getDeepbookV3Config() if (config && config.data) { console.log("Whitelisted pools:", config.data.whitelist_pools) } ``` -------------------------------- ### Handle Invalid Router for Merge Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/04-errors.md This example shows how to handle an 'Invalid Router for Merge Swap' error, which occurs when `router.allRoutes` is empty. Verify that merge swap routes are found before building the transaction. ```typescript await client.mergeSwap({ router: { quoteID: "", totalAmountOut: new BN(0), allRoutes: [], // Empty! packages }, inputCoins: [], slippage: 0.01, txb }) // throws Error: "No routes found in merge swap response" ``` ```typescript const mergeRouter = await client.findMergeSwapRouters(params) if (!mergeRouter || mergeRouter.allRoutes.length === 0) { console.error("No merge routes found") return } await client.mergeSwap({ router: mergeRouter, inputCoins, slippage: 0.01, txb }) ``` -------------------------------- ### Build PTB and Get Target Coin for Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Build a transaction block (PTB) for a swap and retrieve the target coin object. This target coin can then be used for further operations like transferring or destroying. ```typescript const txb = new Transaction() const byAmountIn = true if (routerRes != null) { 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, 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) } ``` -------------------------------- ### Validation: Fee Receiver Not Set Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Example of an error thrown when 'overlayFeeRate' is greater than 0 but 'overlayFeeReceiver' is not provided. ```typescript // Error: fee receiver not set when fee rate > 0 new AggregatorClient({ overlayFeeRate: 0.01 // overlayFeeReceiver defaults to "0x0" }) // → throws: "Overlay fee rate is set, but overlay fee receiver is not set" ``` -------------------------------- ### Initialize AggregatorClient and Perform Basic Swap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/00-index.md Demonstrates how to initialize the AggregatorClient, find the best swap route for a token exchange, and execute the swap transaction. Requires importing AggregatorClient and BN. ```typescript import { AggregatorClient } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" // Initialize client const client = new AggregatorClient() // Find best swap route const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true }) // Execute swap const txb = new Transaction() const outputCoin = await client.routerSwap({ router, inputCoin: txb.splitCoins(txb.gas, [txb.pure.u64("1000000")])[0], slippage: 0.01, txb }) // Send transaction const result = await client.sendTransaction(txb, signer) ``` -------------------------------- ### Instantiate AggregatorClient with Basic Configuration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Demonstrates how to instantiate the AggregatorClient with minimal configuration for mainnet, using a custom RPC client, or for the testnet environment. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" // Mainnet with minimal config (uses defaults) const client = new AggregatorClient() // Mainnet with custom RPC client const client = new AggregatorClient({ client: new SuiJsonRpcClient({ network: 'mainnet', url: 'YOUR_RPC_URL' }) }) // Testnet const testClient = new AggregatorClient({ env: Env.Testnet, signer: "0x123..." }) ``` -------------------------------- ### Validation: Fee Rate Out of Range Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Example of an error thrown when 'overlayFeeRate' is set outside the valid range of 0 to 0.1. ```typescript // Error: overlayFeeRate outside valid range new AggregatorClient({ overlayFeeRate: 0.15 // Max is 0.1 }) // → throws: "Overlay fee rate must be between 0 and 0.1" ``` -------------------------------- ### Get Providers Including Function Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/05-utilities.md Returns only the specified providers if they are supported. Useful for targeting specific DEXs for route finding. ```typescript function getProvidersIncluding(includeProviders: string[]): string[] ``` ```typescript // Find routes using only specific DEXs const providers = getProvidersIncluding([ "CETUS", "TURBOS", "KRIYAV3" ]) const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true, providers }) ``` -------------------------------- ### Get All Providers Function Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/05-utilities.md Returns an array of all supported DEX provider names. Useful for iterating through all available liquidity sources. ```typescript function getAllProviders(): string[] ``` ```typescript const providers = getAllProviders() console.log(providers.length) // 30+ console.log(providers.includes("CETUS")) // true ``` -------------------------------- ### Get Aggregator Server Error Message Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/04-errors.md Converts `AggregatorServerErrorCode` to human-readable messages. Optionally includes additional details for more context. ```typescript export function getAggregatorServerErrorMessage( code: AggregatorServerErrorCode, msg?: string ): string ``` ```typescript getAggregatorServerErrorMessage(AggregatorServerErrorCode.RateLimitExceeded) // → "Rate limit exceeded" ``` ```typescript getAggregatorServerErrorMessage( AggregatorServerErrorCode.InsufficientLiquidity, "USDC-CETUS pool has 100 CETUS available" ) // → "Insufficient liquidity: USDC-CETUS pool has 100 CETUS available" ``` -------------------------------- ### Required Peer Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Lists the peer dependencies required for the Aggregator SDK, primarily focusing on TypeScript. These must be installed in your project. ```json { "typescript": "^5.0.0" } ``` -------------------------------- ### AggregatorClient Initialization with Env Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/02-types.md Demonstrates how to initialize the AggregatorClient for different network environments using the Env enum. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient({ env: Env.Mainnet }) const testClient = new AggregatorClient({ env: Env.Testnet }) ``` -------------------------------- ### Env Enumeration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Defines the network environments for client initialization. ```APIDOC ## Enumeration: Env ### Description Specifies the network environment for initializing the Aggregator client. ### Members - **`Mainnet`**: Represents the mainnet network. - **`Testnet`**: Represents the testnet network. ``` -------------------------------- ### Get Providers Excluding Function Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/05-utilities.md Returns all providers except those specified in the exclude list. Use this to avoid certain DEXs when finding routes. ```typescript function getProvidersExcluding(excludeProviders: string[]): string[] ``` ```typescript // Find routes using all DEXs except Scallop and Suilend const providers = getProvidersExcluding(["SCALLOP", "SUILEND"]) const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true, providers // 28 providers }) ``` -------------------------------- ### Validation: Slippage Out of Range in Method Call Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Example of an error thrown when the 'slippage' parameter in a method call is outside the valid range of 0 to 1. ```typescript // Error: slippage out of range in method call await client.routerSwap({ router, inputCoin, slippage: 1.5 // Must be 0-1 txb }) // → throws: "Invalid slippage value. Must be between 0 and 1" ``` -------------------------------- ### Full-Featured AggregatorClient Import Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Shows how to import and initialize the AggregatorClient with specific environment and signer configurations. Includes a comprehensive list of commonly used SDK utilities. ```typescript import { AggregatorClient, Env, AggregatorServerErrorCode, CoinUtils, CalculateAmountLimitBN, getProvidersIncluding, RouterDataV3, FindRouterParams, } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" const client = new AggregatorClient({ env: Env.Mainnet, signer: "0x..." }) ``` -------------------------------- ### Instantiate AggregatorClient Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Create a new AggregatorClient instance. Default settings use Mainnet. Custom configurations can be provided for environment, signer, fee rates, and Pyth oracle URLs. ```typescript const client = new AggregatorClient() ``` ```typescript const testnetClient = new AggregatorClient({ env: Env.Testnet, signer: "0x123...", overlayFeeRate: 0.01, overlayFeeReceiver: "0x456...", pythUrls: ["https://hermes.pyth.network"] }) ``` -------------------------------- ### Aggregator Contract Dependencies Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Example of how to define dependencies for Cetus Aggregator V2 and its extensions in a project configuration. These are typically used in build systems or package managers. ```rust CetusAggregatorV2 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2/mainnet", rev = "mainnet-v1.60.0", override = true } CetusAggregatorV2ExtendV1 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2-extend-v1", rev = "mainnet-v1.60.0", override = true } CetusAggregatorV2ExtendV2 = { git = "https://github.com/CetusProtocol/aggregator.git", subdir = "packages/cetus-aggregator-v2-extend-v2", rev = "mainnet-v1.60.0", override = true } ``` -------------------------------- ### Transaction Building Flow Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Illustrates the sequence of operations for building a swap transaction, from user input to returning the output coin. ```plaintext User calls routerSwap(params) ↓ Validate router, slippage, packages ↓ Find Pyth price IDs from extended details ↓ updatePythPriceIDs() - update oracle prices if needed ↓ processFlattenRoutes(RouterDataV3) → ProcessedRouterData ↓ newSwapContext() - initialize swap state/balance tracking ↓ For each flattened path: ├─ Create DEX router (newDexRouterV3) ├─ Call dex.swap() to add swap steps to transaction └─ Update swap context with intermediate results ↓ confirmSwap() - finalize output coin ↓ Return output coin to user ``` -------------------------------- ### Configure AggregatorClient with API Key Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Shows how to provide an API key to the AggregatorClient for increased rate limits and priority routing. Use a production key for live environments. ```typescript new AggregatorClient({ apiKey: "sk_live_..." // or undefined for public API }) ``` -------------------------------- ### Create New DEX Router V3 Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Creates a DEX-specific router instance for manual swap building. Supports various DEX providers and requires Pyth price IDs. Used internally but available for advanced use. ```typescript newDexRouterV3(provider: string, pythPriceIDs: Map, partner?: string, cetusDlmmPartner?: string): DexRouter ``` -------------------------------- ### Get DeepBook V3 Fee Type Address Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Returns the coin type address for Deep tokens used as fees in DeepBook V3 non-whitelisted pools. The address differs between mainnet and testnet. ```typescript deepbookv3DeepFeeType(): string ``` -------------------------------- ### newDexRouterV3 Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Creates a DEX-specific router instance for manual swap building. This is an advanced method intended for users who need fine-grained control over swap construction. ```APIDOC ## newDexRouterV3(provider, pythPriceIDs, partner, cetusDlmmPartner) ### Description Creates a DEX-specific router instance for manual swap building. Used internally but available for advanced use. ### Parameters - **provider** (string) - Required - DEX name (e.g., "CETUS", "KRIYAV3", "TURBOS") - **pythPriceIDs** (Map) - Required - Map of price feed IDs (from `updatePythPriceIDs()`) - **partner** (string) - Optional - Partner ID for this DEX - **cetusDlmmPartner** (string) - Optional - DLMM partner ID ### Returns `DexRouter` instance with `swap()` method. ### Throws Error if provider not supported. ``` -------------------------------- ### Minimal AggregatorClient Import Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Demonstrates the most basic import of the AggregatorClient, suitable for simple use cases. Initializes the client with default settings. ```typescript import { AggregatorClient } from "@cetusprotocol/aggregator-sdk" const client = new AggregatorClient() ``` -------------------------------- ### Get Default Sqrt Price Limit Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/05-utilities.md Retrieves the default square root price limit for Concentrated Liquidity Market Maker (CLMM) swaps. Use 'a2b' to specify the direction of the price movement. ```typescript function GetDefaultSqrtPriceLimit(a2b: boolean): BN ``` ```typescript const limitA2B = GetDefaultSqrtPriceLimit(true) const limitB2A = GetDefaultSqrtPriceLimit(false) ``` -------------------------------- ### Env Enumeration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Defines the network environment for client initialization. Use `Mainnet` or `Testnet` to specify the target network. ```typescript import { Env } from "@cetusprotocol/aggregator-sdk" enum Env { Mainnet = 0, Testnet = 1, } ``` -------------------------------- ### Get Coin for Merging Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Fetches one existing coin of a specified type from the signer's account. This is used internally to merge output coins. Returns the coin object ID or null if none is found. ```typescript async getOneCoinUsedToMerge(coinType: string): Promise ``` -------------------------------- ### Swap Execution Data Flow: Route Finding Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Illustrates the sequence of calls and interactions involved in finding optimal swap routes using the AggregatorClient and its API communication layer. ```text User calls findRouters(params) ↓ AggregatorClient.findRouters() ↓ getRouter() / postRouterWithLiquidityChanges() ↓ Fetch from API endpoint: GET /find_routes?... ↓ API returns RouterDataV3 (or error) ↓ Return to user ``` -------------------------------- ### Initialize AggregatorClient for Mainnet Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Configure the AggregatorClient to use Mainnet endpoints and network configurations. ```typescript new AggregatorClient({ env: Env.Mainnet }) ``` -------------------------------- ### Configure AggregatorClient with Custom SuiJsonRpcClient Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Illustrates how to provide a pre-configured SuiJsonRpcClient instance to the AggregatorClient. This allows for reusing existing RPC clients or customizing their network and URL settings. ```typescript import { SuiJsonRpcClient } from "@mysten/sui/jsonRpc" const suiClient = new SuiJsonRpcClient({ network: 'mainnet', url: 'https://fullnode.mainnet.sui.io:443' }) new AggregatorClient({ client: suiClient }) ``` -------------------------------- ### Configure AggregatorClient with Pyth URLs Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Demonstrates setting an array of Pyth Hermes API URLs for the AggregatorClient. This is necessary for DEXs that rely on Pyth price feeds. ```typescript new AggregatorClient({ pythUrls: [ "https://hermes.pyth.network", "https://api.pyth.network" // fallback ] }) ``` -------------------------------- ### Swap Context Initialization Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Shows how the swap context is created at the beginning of a swap operation, including essential parameters. This object tracks state across multiple swap steps. ```typescript // Created at the beginning const swapContext = newSwapContext( { quoteID, fromCoinType, targetCoinType, expectAmountOut, amountOutLimit, inputCoin, feeRate, feeRecipient, packages }, txb ) ``` -------------------------------- ### Find Optimal Swap Routes Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Query the aggregator service to find the best swap routes for a given token amount. Specify source and target token types, amount, and whether the amount is input or output. Optional parameters control routing depth, split algorithms, and specific DEX providers. ```typescript const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS", amount: new BN(1000000), byAmountIn: true, providers: ["CETUS", "KRIYAV3", "TURBOS"] }) if (router && !router.error) { console.log(`Amount out: ${router.amountOut.toString()}`) } ``` -------------------------------- ### AggregatorClient Constructor Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Initializes a new instance of the AggregatorClient. This is the entry point for all client-side interactions with the aggregator service. ```APIDOC ## new AggregatorClient(params) ### Description Creates a new client instance to interact with the aggregator service. This client provides access to various functions for querying routes and executing swaps. ### Parameters - **params** (object) - Required - Configuration parameters for the client, such as API endpoints and network settings. ``` -------------------------------- ### Using RouterDataV3 with routerSwap Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/02-types.md Demonstrates how to use the RouterDataV3 object obtained from findRouters() with the routerSwap function. Ensure the router is valid and has sufficient liquidity before proceeding. ```typescript const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true, }) if (router && !router.error && !router.insufficientLiquidity) { const outputCoin = await client.routerSwap({ router, // Pass the entire RouterDataV3 inputCoin: txCoin, slippage: 0.01, txb, }) } ``` -------------------------------- ### Configure Client for Fee Collection Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/06-examples.md Set up the AggregatorClient to automatically collect overlay fees on swaps. The fee rate and receiver address are configured during client initialization. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" const FEE_RATE = 0.005 // 0.5% const FEE_RECEIVER = "0xfeereceiver..." const client = new AggregatorClient({ env: Env.Mainnet, signer: "0xuser...", overlayFeeRate: FEE_RATE, overlayFeeReceiver: FEE_RECEIVER }) // Fee is automatically applied to all swaps async function swapWithFeeCollection() { const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true }) if (router && !router.error) { // For byAmountIn swaps: // output = expectedOutput - (expectedOutput * 0.005) const effectiveOutput = router.amountOut console.log(`Effective output (after 0.5% fee): ${effectiveOutput.toString()}`) if (router.overlayFee) { console.log(`Fee collected: ${router.overlayFee} CETUS to ${FEE_RECEIVER}`) } } } swapWithFeeCollection().catch(console.error) ``` -------------------------------- ### Configure AggregatorClient with Overlay Fee Rate Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Illustrates setting a protocol fee rate for swaps using the overlayFeeRate parameter. The fee is specified as a decimal and must be within the range [0, 0.1]. ```typescript new AggregatorClient({ overlayFeeRate: 0.01 // 1% fee }) ``` -------------------------------- ### Utility-Only Import Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Illustrates importing only utility functions from the SDK, such as CoinUtils for coin symbol retrieval. This is useful when you don't need the main client instance. ```typescript import { CoinUtils, CalculateAmountLimit, CalculateAmountLimitBN, } from "@cetusprotocol/aggregator-sdk" const symbol = CoinUtils.getCoinSymbol("0x2::sui::SUI") ``` -------------------------------- ### Initialize AggregatorClient with Overlay Fee Receiver Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Set the overlay fee rate and specify the Sui address to receive collected fees. This is required if overlayFeeRate is greater than 0. ```typescript new AggregatorClient({ overlayFeeRate: 0.01, overlayFeeReceiver: "0xfeerecipient..." // Required when rate > 0 }) ``` ```typescript // If you want to collect fees: new AggregatorClient({ overlayFeeRate: 0.01, overlayFeeReceiver: "0x1234567890abcdef..." // Your address }) ``` ```typescript // Error if not set with positive rate: new AggregatorClient({ overlayFeeRate: 0.01 // overlayFeeReceiver defaults to "0x0" → throws error }) ``` -------------------------------- ### Initialize Aggregator Client Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Initialize the AggregatorClient with an empty configuration object. This client is used to interact with the aggregator service. ```typescript const client = new AggregatorClient({}) ``` -------------------------------- ### Mainnet Deployment Configuration Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/07-architecture.md Configuration details for deploying the Aggregator service on the mainnet, including service endpoints, RPC, Pyth network, and package addresses. ```text Aggregator Service: https://api-sui.cetus.zone/router_v3 RPC Endpoint: https://fullnode.mainnet.sui.io:443 Pyth Network: https://hermes.pyth.network Aggregator V3 Pkg: 0xde5d696a79714ca5cb910b9aed99d41f67353abb00715ceaeb0663d57ee39640 Cetus V3 Pkg: 0xd7b0cfc33a3b46c0ae0e2584c44028385da11724d4c94ec5b21a78117c5c1ab9 ``` -------------------------------- ### Find Best Router Swap Result Source: https://github.com/cetusprotocol/aggregator/blob/main/README.md Find the optimal swap route by providing input token, target token, and amount. Set `byAmountIn` to true for fixed input amount or false for fixed output amount. ```typescript 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 }) ``` -------------------------------- ### Route with Specific DEX Providers Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/06-examples.md Demonstrates how to exclude specific DEX providers or include only a predefined set when finding swap routes. This allows for fine-grained control over which liquidity pools are considered. ```typescript import { AggregatorClient, getProvidersExcluding, getProvidersIncluding } from "@cetusprotocol/aggregator-sdk" import BN from "bn.js" const client = new AggregatorClient() async function routeWithSpecificProviders() { // Option 1: Exclude providers const noScallopRoute = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true, providers: getProvidersExcluding(["SCALLOP", "SUILEND"]) }) if (!noScallopRoute?.error) { console.log(`Route without Scallop/Suilend: ${noScallopRoute.amountOut.toString()} CETUS`) } // Option 2: Use only specific providers const standardRoute = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true, providers: getProvidersIncluding([ "CETUS", "KRIYAV3", "TURBOS", "AFTERMATH" ]) }) if (!standardRoute?.error) { console.log(`Route with standard DEXs: ${standardRoute.amountOut.toString()} CETUS`) } // Compare results if (noScallopRoute && standardRoute && !noScallopRoute.error && !standardRoute.error) { const diff = standardRoute.amountOut.sub(noScallopRoute.amountOut) console.log(`Difference: ${diff.toString()} CETUS`) } } routeWithSpecificProviders().catch(console.error) ``` -------------------------------- ### Configuration Objects Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/08-exports.md Exports for various configuration objects used by the SDK, such as client, aggregator, and Pyth network configurations. These objects define default values and network-specific settings. ```typescript import { CLIENT_CONFIG, AGGREGATOR_V3_CONFIG, PYTH_CONFIG, PUBLISHED_ADDRESSES, DEEPBOOK_V3_DEEP_FEE_TYPES, PACKAGE_NAMES } from "@cetusprotocol/aggregator-sdk" export const CLIENT_CONFIG = { DEFAULT_PYTH_URL: string PYTH_TIMEOUT: number MAX_OVERLAY_FEE_RATE: number MAX_OVERLAY_FEE_RATE_NUMERATOR: number FEE_RATE_MULTIPLIER: number DEFAULT_OVERLAY_FEE_RECEIVER: string ERRORS: Record } export const AGGREGATOR_V3_CONFIG = { FEE_DENOMINATOR: number MAX_FEE_RATE: number MAX_AMOUNT_IN: string DEFAULT_PUBLISHED_AT: { Mainnet: string Testnet: string } } export const PYTH_CONFIG = { Testnet: { wormholeStateId: string; pythStateId: string } Mainnet: { wormholeStateId: string; pythStateId: string } } export const PUBLISHED_ADDRESSES = { V2: { Mainnet: string; Testnet: string } V2_EXTEND: { Mainnet: string; Testnet: string } V2_EXTEND2: { Mainnet: string; Testnet: string } } export const DEEPBOOK_V3_DEEP_FEE_TYPES = { Mainnet: string Testnet: string } export const PACKAGE_NAMES = { AGGREGATOR_V3: "aggregator_v3" } ``` -------------------------------- ### AggregatorClient Constructor Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/01-aggregator-client.md Initializes a new AggregatorClient instance. This client is the main entry point for interacting with the Cetus Plus Swap Aggregator SDK to find optimal swap routes and execute trades. ```APIDOC ## AggregatorClient(params) ### Description Creates a new AggregatorClient instance with the specified configuration. This client is used to interact with the Cetus Plus Swap Aggregator SDK. ### Parameters #### Constructor Parameters - **endpoint** (string) - Optional - The aggregator service endpoint URL. Defaults to `https://api-sui.cetus.zone/router_v3`. - **signer** (string) - Optional - The Sui address of the transaction signer. Defaults to `""`. - **client** (SuiJsonRpcClient) - Optional - An existing Sui JSON-RPC client instance. Defaults to auto-created. - **env** (Env) - Optional - The network environment. Defaults to `Env.Mainnet`. Can be `Env.Mainnet` or `Env.Testnet`. - **pythUrls** (string[]) - Optional - URLs for Pyth price feed oracles. Defaults to `[]`. - **apiKey** (string) - Optional - API key for aggregator service authentication. Defaults to `""`. - **partner** (string) - Optional - Partner identifier for swap execution (deprecated). Defaults to `undefined`. - **overlayFeeRate** (number) - Optional - Overlay fee rate (0 to 0.1). Will be multiplied internally by 1,000,000. Defaults to `undefined`. - **overlayFeeReceiver** (string) - Optional - Sui address that receives overlay fees. Defaults to `"0x0"`. - **cetusDlmmPartner** (string) - Optional - Partner identifier for Cetus DLMM pools. Defaults to `undefined`. ### Throws - Error if `overlayFeeRate` is not between 0 and 0.1. - Error if `overlayFeeRate` > 0 but `overlayFeeReceiver` is "0x0". ### Example ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" // Mainnet with default settings const client = new AggregatorClient() // Testnet with custom configuration const testnetClient = new AggregatorClient({ env: Env.Testnet, signer: "0x123...", overlayFeeRate: 0.01, overlayFeeReceiver: "0x456...", pythUrls: ["https://hermes.pyth.network"] }) ``` ``` -------------------------------- ### Build Basic Token Swap Transaction Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/06-examples.md Manually build a transaction to swap SUI for CETUS. This involves querying for the best route, splitting gas coins, executing the swap, and transferring the output. Ensure you have the necessary imports and a configured AggregatorClient. ```typescript import { AggregatorClient, Env } from "@cetusprotocol/aggregator-sdk" import { Transaction } from "@mysten/sui/transactions" import BN from "bn.js" import { Ed25519Keypair } from "@mysten/sui/cryptography" const client = new AggregatorClient({ env: Env.Mainnet, signer: "0x1234..." // Your address }) async function swapSuiForCetus() { // Query for best route const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0x06864a6f921804860930db6ddbe2e16acdf8504495ea7481637a1c8b9a8fe54b::cetus::CETUS", amount: new BN(1000000), // 0.001 SUI byAmountIn: true }) if (!router || router.error) { console.error("Route not found:", router?.error?.msg) return } console.log(`Output: ${router.amountOut.toString()} CETUS`) // Build transaction const txb = new Transaction() // Split gas coin for input const inputCoin = txb.splitCoins(txb.gas, [txb.pure.u64("1000000")])[0] // Execute swap const outputCoin = await client.routerSwap({ router, inputCoin, slippage: 0.01, // 1% slippage tolerance txb }) // Transfer result to user (or merge with existing coin) txb.transferObjects([outputCoin], client.signer) // Sign and execute const keypair = Ed25519Keypair.fromSecretKey(/* your secret key */) const result = await client.sendTransaction(txb, keypair) console.log("Swap completed:", result.digest) } swapSuiForCetus().catch(console.error) ``` -------------------------------- ### Initialize AggregatorClient for Testnet Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/03-configuration.md Configure the AggregatorClient to use Testnet endpoints and network configurations. ```typescript new AggregatorClient({ env: Env.Testnet }) ``` -------------------------------- ### Simulate Transaction Before Execution Source: https://github.com/cetusprotocol/aggregator/blob/main/_autodocs/06-examples.md Use `devInspectTransactionBlock` to test transactions before sending them to the network. This helps in validating the transaction and estimating gas costs. ```typescript import { AggregatorClient } from "@cetusprotocol/aggregator-sdk" import { Transaction } from "@mysten/sui/transactions" import BN from "bn.js" const client = new AggregatorClient({ signer: "0x1234..." }) async function simulateThenExecute() { // Find route const router = await client.findRouters({ from: "0x2::sui::SUI", target: "0xcetus::CETUS", amount: new BN(1000000), byAmountIn: true }) if (router?.error) { console.error("No route found") return } // Build transaction const txb = new Transaction() const inputCoin = txb.splitCoins(txb.gas, [txb.pure.u64("1000000")])[0] const outputCoin = await client.routerSwap({ router, inputCoin, slippage: 0.01, txb }) txb.transferObjects([outputCoin], client.signer) // Simulate first console.log("Simulating transaction...") const simulation = await client.devInspectTransactionBlock(txb) if (simulation.error) { console.error("Simulation failed:", simulation.error) return } console.log("Simulation successful!") console.log(`Gas used: ${simulation.effects?.gasUsed?.computationCost}`) // Check for events if (simulation.events?.length) { console.log(`Emitted ${simulation.events.length} events`) simulation.events.forEach(evt => { console.log(` - ${evt.type}`) }) } // Now safe to execute console.log("Executing transaction...") const keypair = Ed25519Keypair.fromSecretKey(/* your secret key */) const result = await client.sendTransaction(txb, keypair) console.log("Transaction completed:", result.digest) } simulateThenExecute().catch(console.error) ```