### Install and Run Dependencies Source: https://github.com/icon-project/sodax-frontend/blob/main/CONTRIBUTING.md Use these commands to install project dependencies and start the development server. ```shell pnpm i pnpm dev ``` -------------------------------- ### Quick Start: React Wallet Integration Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/wallet-sdk-react/README.md Demonstrates setting up SodaxWalletProvider, using hooks for wallet connection, and displaying connected account information. Requires QueryClientProvider and SodaxWalletProvider setup. ```typescript import { SodaxWalletProvider, useXConnectors, useXConnect, useXAccount } from '@sodax/wallet-sdk-react'; import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; import type { RpcConfig } from '@sodax/types'; // Create a QueryClient instance const queryClient = new QueryClient(); const rpcConfig: RpcConfig = { // EVM chains sonic: 'https://rpc.soniclabs.com', '0xa86a.avax': 'https://api.avax.network/ext/bc/C/rpc', '0xa4b1.arbitrum': 'https://arb1.arbitrum.io/rpc', '0x2105.base': 'https://mainnet.base.org', '0x38.bsc': 'https://bsc-dataseed1.binance.org', '0xa.optimism': 'https://mainnet.optimism.io', '0x89.polygon': 'https://polygon-rpc.com', // Other chains '0x1.icon': 'https://ctz.solidwallet.io/api/v3', solana: 'https://solana-mainnet.g.alchemy.com/v2/your-api-key', sui: 'https://fullnode.mainnet.sui.io', 'injective-1': 'https://sentry.tm.injective.network:26657', }; function App() { return ( ); } function WalletConnect() { // Get available connectors for EVM chain const connectors = useXConnectors('EVM'); // Get connect mutation const { mutateAsync: connect } = useXConnect(); // Get connected account info const account = useXAccount('EVM'); return (
{/* Display connected wallet address if connected */} {account?.address && (

Connected Wallet:

{account.address}

)} {/* Display available connectors */}
{connectors.map((connector) => ( ))}
); } ``` -------------------------------- ### Run the Node App Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/node/README.md Start the example Node.js application using the pnpm run dev command. ```bash pnpm run dev ``` -------------------------------- ### Local Installation of @sodax/sdk Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/README.md Steps to locally install the SDK by cloning the repository, installing dependencies, building the package, and referencing it via a file path in your application's package.json. ```bash # In your app repository package.json file, define dependency: # "@sodax/sdk": "file:" # Example: # "@sodax/sdk": "file:/Users/dev/operation-liquidity-layer/sdk-new/packages/sdk" ``` -------------------------------- ### Install @sodax/wallet-sdk-core Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/WALLET_PROVIDERS.md Install the `@sodax/wallet-sdk-core` package using npm, yarn, or pnpm to get ready-to-use wallet provider implementations. ```bash # Using npm npm install @sodax/wallet-sdk-core ``` ```bash # Using yarn yarn add @sodax/wallet-sdk-core ``` ```bash # Using pnpm pnpm add @sodax/wallet-sdk-core ``` -------------------------------- ### Install @sodax/wallet-sdk-react Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/wallet-sdk-react/README.md Install the SDK using npm, yarn, or pnpm. ```bash # Using npm npm install @sodax/wallet-sdk-react # Using yarn yarn add @sodax/wallet-sdk-react # Using pnpm pnpm add @sodax/wallet-sdk-react ``` -------------------------------- ### Install @sodax/dapp-kit with npm Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Use this command to install the dApp Kit library using npm. ```bash npm install @sodax/dapp-kit ``` -------------------------------- ### Complete Backend API Usage Example Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md A comprehensive example demonstrating initialization of the Sodax SDK with custom backend API configuration and making various API calls, including error handling. ```typescript import { Sodax } from '@sodax/sdk'; async function example() { // Initialize Sodax with custom backend API configuration const sodax = new Sodax({ backendApiConfig: { baseURL: 'https://api.sodax.com/v1/be', timeout: 60000, headers: { 'Authorization': 'Bearer your-api-token' } } }); try { // Get solver orderbook const orderbook = await sodax.backendApi.getOrderbook({ offset: '0', limit: '5' }); console.log('Orderbook:', orderbook); // Get user's money market position const userAddress = '0x789...ghi'; const position = await sodax.backendApi.getMoneyMarketPosition(userAddress); console.log('User Position:', position); // Get all money market assets const assets = await sodax.backendApi.getAllMoneyMarketAssets(); console.log('Available Assets:', assets); // Get intent by transaction hash const txHash = '0x123...abc'; const intent = await sodax.backendApi.getIntentByTxHash(txHash); console.log('Intent Details:', intent); } catch (error) { console.error('API Error:', error.message); } } example(); ``` -------------------------------- ### Install @sodax/dapp-kit with yarn Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Use this command to install the dApp Kit library using yarn. ```bash yarn add @sodax/dapp-kit ``` -------------------------------- ### Install @sodax/dapp-kit with pnpm Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Use this command to install the dApp Kit library using pnpm. ```bash pnpm add @sodax/dapp-kit ``` -------------------------------- ### Install @sodax/sdk with npm, yarn, or pnpm Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/README.md Use npm, yarn, or pnpm to install the @sodax/sdk package. Ensure you have the respective package manager installed. ```bash # Using npm npm install @sodax/sdk ``` ```bash # Using yarn yarn add @sodax/sdk ``` ```bash # Using pnpm pnpm add @sodax/sdk ``` -------------------------------- ### Install @sodax/sdk and Dependencies Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/installation/nextjs.md Install the Sodax SDK along with its required peer dependencies, @sodax/types and viem, using your preferred package manager. ```bash npm install @sodax/sdk @sodax/types viem ``` ```bash yarn add @sodax/sdk @sodax/types viem ``` ```bash pnpm add @sodax/sdk @sodax/types viem ``` -------------------------------- ### Run Demo App Development Server Source: https://github.com/icon-project/sodax-frontend/blob/main/CLAUDE.md Starts the Vite-based development server for the SDK demo application. ```bash pnpm dev:demo ``` -------------------------------- ### Fetch and Format Money Market Data Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/MONEY_MARKET.md This example demonstrates fetching humanized reserves and user reserves, then formatting them with USD conversions for display. It requires prior setup of the SDK and necessary variables like spokeChainId and userAddress. ```typescript // Fetch reserves data const reserves = await sodax.moneyMarket.data.getReservesHumanized(); // Format reserves with USD conversions const formattedReserves = sodax.moneyMarket.data.formatReservesUSD( sodax.moneyMarket.data.buildReserveDataWithPrice(reserves), ); // Fetch user reserves data const userReserves = await sodax.moneyMarket.data.getUserReservesHumanized(spokeChainId, userAddress); // Format user summary with USD conversions const userSummary = sodax.moneyMarket.data.formatUserSummary( sodax.moneyMarket.data.buildUserSummaryRequest(reserves, formattedReserves, userReserves), ); // Display formatted data console.log('formattedReserves:', formattedReserves); console.log('userSummary:', userSummary); ``` -------------------------------- ### Install Node App Dependencies Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/node/README.md Navigate to the Node app directory and install its dependencies using pnpm. ```bash cd apps/node pnpm install ``` -------------------------------- ### Install Sodax Dapp Kit Dependencies Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Install the necessary packages for Sodax Dapp Kit, React Query, and the wallet SDK. ```bash pnpm install @sodax/dapp-kit @tanstack/react-query @sodax/wallet-sdk-react ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/icon-project/sodax-frontend/blob/main/CLAUDE.md Installs all project dependencies using pnpm. Ensure pnpm 9.8.0 is used. ```bash pnpm i ``` -------------------------------- ### Run in Development Mode with pnpm Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Starts the project in development mode using pnpm. ```bash pnpm dev ``` -------------------------------- ### Run Money Market Example Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/node/README.md Execute the money market functionality of the Node app with a specified user address. ```bash pnpm run dev moneymarket ``` -------------------------------- ### Instantiate SuiSpokeProvider in Browser Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_CREATE_A_SPOKE_PROVIDER.md This example shows how to create a SuiSpokeProvider in a browser environment. The wallet provider is typically injected by a browser extension. ```typescript import { SuiSpokeProvider, SUI_MAINNET_CHAIN_ID, spokeChainConfig, type SuiSpokeChainConfig, type ISuiWalletProvider } from "@sodax/sdk"; // Wallet provider is typically injected by Sui wallet extension const suiWalletProvider: ISuiWalletProvider = /* injected by wallet */; // Get chain configuration const suiChainConfig = spokeChainConfig[SUI_MAINNET_CHAIN_ID] as SuiSpokeChainConfig; // Create Sui spoke provider const suiSpokeProvider = new SuiSpokeProvider( suiChainConfig, suiWalletProvider ); ``` -------------------------------- ### Run Web App Development Server Source: https://github.com/icon-project/sodax-frontend/blob/main/CLAUDE.md Starts the Next.js development server for the main web application on port 3001. ```bash pnpm dev:web ``` -------------------------------- ### Configure Private Key Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/node/README.md Create a .env file in the project root and add your account's private key. ```bash PRIVATE_KEY= ``` -------------------------------- ### Build the SDK Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/node/README.md Navigate to the SDK package directory and build the SDK using pnpm. ```bash cd packages/sdk pnpm build ``` -------------------------------- ### Install Dependencies with pnpm Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/dapp-kit/README.md Installs project dependencies using the pnpm package manager. ```bash pnpm install ``` -------------------------------- ### Start Development Server Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/installation/nextjs.md Launch the Next.js development server to see your application running locally. This command is available for npm, yarn, and pnpm. ```bash # Using npm npm run dev # Using yarn yarn dev # Using pnpm pnpm dev ``` -------------------------------- ### Money Market SDK Initialization and Configuration Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/MONEY_MARKET.md Demonstrates how to initialize the Sodax SDK and access configuration constants for supported chains, tokens, and reserves. ```APIDOC ## SDK Initialization and Configuration ### Description Initialize the Sodax SDK to use dynamic configurations (latest tokens) or default static configurations. Access supported chains, tokens, and reserves through the `sodax.config` and `sodax.moneyMarket` properties. ### Method `sodax.initialize()` ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```typescript import { Sodax, type SpokeChainId, type Token, type Address } from "@sodax/sdk"; const sodax = new Sodax(); await sodax.initialize(); // Initialize for dynamic config (optional) // All supported spoke chains (general config) const spokeChains: SpokeChainId[] = sodax.config.getSupportedSpokeChains(); // Get supported money market tokens for a specific chain const supportedMoneyMarketTokens: readonly Token[] = sodax.moneyMarket.getSupportedTokensByChainId(chainId); // Get all supported money market tokens per chain const allMoneyMarketTokens = sodax.moneyMarket.getSupportedTokens(); // Get all supported reserves (hub chain token addresses, i.e. money market on Sonic chain) const supportedReserves: readonly Address[] = sodax.moneyMarket.getSupportedReserves(); // Check if token address for given spoke chain id is supported (through config service) const isMoneyMarketSupportedToken: boolean = sodax.config.isMoneyMarketSupportedToken(chainId, token); // Alternative: Access through config service const moneyMarketTokensFromConfig: readonly Token[] = sodax.config.getSupportedMoneyMarketTokensByChainId(chainId); const allMoneyMarketTokensFromConfig = sodax.config.getSupportedMoneyMarketTokens(); ``` ### Response N/A (SDK methods return data directly) ### Response Example N/A ``` -------------------------------- ### Example IntentResponse JSON Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md An example JSON object illustrating the structure and typical values for an IntentResponse. ```json { "intentHash": "0x456...def", "txHash": "0x123...abc", "logIndex": 0, "chainId": 146, "blockNumber": 12345678, "open": true, "intent": { "intentId": "intent_123", "creator": "0x789...ghi", "inputToken": "0xabc...123", "outputToken": "0xdef...456", "inputAmount": "1000000000000000000", "minOutputAmount": "950000000000000000", "deadline": "1700000000", "allowPartialFill": true, "srcChain": 146, "dstChain": 1, "srcAddress": "0x789...ghi", "dstAddress": "0x789...ghi", "solver": "0x000...000", "data": "0x" }, "events": [] } ``` -------------------------------- ### Run Development Server Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/web/README.md Use these commands to start the development server for your Next.js application. Open http://localhost:3000 in your browser to view the result. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Initialize Sodax SDK with Default Configuration Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/CONFIGURE_SDK.md Use this for default Sonic mainnet configurations without any fees. No additional setup is required. ```typescript import { Sodax } from '@sodax/sdk'; const sodax = new Sodax(); ``` -------------------------------- ### Get Chain Configuration Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_CREATE_A_SPOKE_PROVIDER.md Retrieve pre-configured settings for supported chains using the `spokeChainConfig` object. Ensure Sodax is initialized before fetching configurations to get the latest data. ```typescript import { spokeChainConfig, ARBITRUM_MAINNET_CHAIN_ID, type EvmSpokeChainConfig } from "@sodax/sdk"; // Get chain configuration for a specific chain const arbChainConfig = spokeChainConfig[ARBITRUM_MAINNET_CHAIN_ID] as EvmSpokeChainConfig; ``` ```typescript import { Sodax } from "@sodax/sdk"; const sodax = new Sodax(); await sodax.initialize(); // Fetches latest configuration from backend API ``` -------------------------------- ### Initialize SolanaSpokeProvider (Node.js) Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_CREATE_A_SPOKE_PROVIDER.md Instantiate `SolanaSpokeProvider` for Node.js environments. Requires a wallet provider configured with a private key and RPC endpoint. ```typescript import { SolanaSpokeProvider, SOLANA_MAINNET_CHAIN_ID, spokeChainConfig, type SolanaChainConfig } from "@sodax/sdk"; import { SolanaWalletProvider } from "@sodax/wallet-sdk-core"; import { Keypair } from "@solana/web3.js"; // Create wallet provider with private key const privateKey = Buffer.from('your-private-key-hex-string', 'hex'); const keypair = Keypair.fromSecretKey(new Uint8Array(privateKey)); const solanaWalletProvider = new SolanaWalletProvider({ privateKey: keypair.secretKey, endpoint: 'https://api.mainnet-beta.solana.com', // Solana RPC endpoint }); // Get chain configuration const solanaChainConfig = spokeChainConfig[SOLANA_MAINNET_CHAIN_ID] as SolanaChainConfig; // Create Solana spoke provider const solanaSpokeProvider = new SolanaSpokeProvider( solanaWalletProvider, solanaChainConfig ); ``` -------------------------------- ### Token Selector Component Example Source: https://github.com/icon-project/sodax-frontend/blob/main/apps/web/docs/TOKEN_GROUPING.md A React component demonstrating how to fetch all supported tokens, group them by symbol, and render a TokenGroupLogo for each unique symbol. This example integrates multiple utility functions and components. ```tsx import { getAllSupportedSolverTokens } from '@/lib/utils'; import { getUniqueTokenSymbols } from '@/lib/token-utils'; import TokenGroupLogo from '@/components/shared/token-group-logo'; const TokenSelector = () => { const allTokens = getAllSupportedSolverTokens(); const uniqueTokenSymbols = getUniqueTokenSymbols(allTokens); return (
{uniqueTokenSymbols.map(({ symbol, tokens }) => (
{symbol}
))}
); }; ``` -------------------------------- ### GET /intent - Get Intent Order Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/SWAPS.md Retrieves intent data using a transaction hash from the hub chain (destination transaction hash). This is useful for obtaining intent details after it has been processed or created. ```APIDOC ## GET /intent - Get Intent Order ### Description Retrieves intent data using a transaction hash from the hub chain (destination transaction hash). This is useful for obtaining intent details after it has been processed or created. ### Method GET ### Endpoint /intent ### Parameters #### Query Parameters - **txHash** (string) - Required - The transaction hash on the hub chain. ### Response #### Success Response (200) - **Intent** (object) - The retrieved intent object. #### Response Example ```json { "ok": true, "value": { // Intent object structure } } ``` #### Error Response - **error** (object) - An error object if the request fails. ``` -------------------------------- ### Initialize SolanaSpokeProvider (Browser) Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_CREATE_A_SPOKE_PROVIDER.md Instantiate `SolanaSpokeProvider` for browser environments. The wallet provider is typically injected by a Solana wallet extension like Phantom. ```typescript import { SolanaSpokeProvider, SOLANA_MAINNET_CHAIN_ID, spokeChainConfig, type SolanaChainConfig, type ISolanaWalletProvider } from "@sodax/sdk"; // Wallet provider is typically injected by Solana wallet extension (e.g., Phantom) const solanaWalletProvider: ISolanaWalletProvider = /* injected by wallet */; // Get chain configuration const solanaChainConfig = spokeChainConfig[SOLANA_MAINNET_CHAIN_ID] as SolanaChainConfig; // Create Solana spoke provider const solanaSpokeProvider = new SolanaSpokeProvider( solanaWalletProvider, solanaChainConfig ); ``` -------------------------------- ### GET /filled-intent - Get Filled Intent Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/SWAPS.md Retrieves the intent state from a transaction hash on the hub chain. This method extracts the intent state from `IntentFilled` event logs emitted when an intent is filled by a solver. ```APIDOC ## GET /filled-intent - Get Filled Intent ### Description Retrieves the intent state from a transaction hash on the hub chain. This method extracts the intent state from `IntentFilled` event logs emitted when an intent is filled by a solver. ### Method GET ### Endpoint /filled-intent ### Parameters #### Query Parameters - **txHash** (string) - Required - The hub chain transaction hash where the intent was filled. ### Response #### Success Response (200) - **IntentState** (object) - The state of the filled intent. - **exists** (boolean) - Whether the intent exists. - **remainingInput** (bigint) - Remaining input amount that hasn't been filled. - **receivedOutput** (bigint) - Amount of output tokens received. - **pendingPayment** (boolean) - Whether there is a pending payment. #### Response Example ```json { "ok": true, "value": { "exists": true, "remainingInput": "1000000000000000000", "receivedOutput": "500000000000000000", "pendingPayment": false } } ``` #### Error Response - **error** (object) - An error object if the request fails or no filled intent is found. ``` -------------------------------- ### Complete Cross-Chain Swap Example Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_MAKE_A_SWAP.md This example demonstrates a full swap process from Arbitrum ETH to Polygon POL. It includes initialization, quote retrieval, allowance checks and approvals, and swap execution. Ensure you have a compatible EVM wallet provider configured. ```typescript import { Sodax, EvmSpokeProvider, ARBITRUM_MAINNET_CHAIN_ID, POLYGON_MAINNET_CHAIN_ID, spokeChainConfig, type CreateIntentParams, type SolverIntentQuoteRequest, type SolverIntentStatusRequest, SolverIntentStatusCode, isIntentCreationFailedError, isIntentSubmitTxFailedError, isIntentPostExecutionFailedError, isWaitUntilIntentExecutedFailed, type IEvmWalletProvider } from "@sodax/sdk"; async function executeSwap( evmWalletProvider: IEvmWalletProvider, inputAmount: bigint ): Promise { try { // Step 1: Initialize Sodax console.log('Step 1: Initializing Sodax...'); const sodax = new Sodax(); await sodax.initialize(); console.log('Sodax initialized'); // Step 2: Create Spoke Provider console.log('Step 2: Creating spoke provider...'); const arbSpokeProvider = new EvmSpokeProvider( evmWalletProvider, spokeChainConfig[ARBITRUM_MAINNET_CHAIN_ID] ); console.log('Spoke provider created'); // Get native token addresses from chain configuration const arbEthToken = spokeChainConfig[ARBITRUM_MAINNET_CHAIN_ID].nativeToken; // ETH on Arbitrum const polygonPolToken = spokeChainConfig[POLYGON_MAINNET_CHAIN_ID].nativeToken; // POL on Polygon // Step 3: Get Quote console.log('Step 3: Getting quote...'); const quoteRequest: SolverIntentQuoteRequest = { token_src: arbEthToken, token_dst: polygonPolToken, token_src_blockchain_id: ARBITRUM_MAINNET_CHAIN_ID, token_dst_blockchain_id: POLYGON_MAINNET_CHAIN_ID, amount: inputAmount, quote_type: 'exact_input', }; const quoteResult = await sodax.swaps.getQuote(quoteRequest); if (!quoteResult.ok) { console.error('Failed to get quote:', quoteResult.error); return; } const quotedAmount = quoteResult.value.quoted_amount; console.log('Quoted amount:', quotedAmount); // Step 4: Check Allowance console.log('Step 4: Checking allowance...'); const walletAddress = await evmWalletProvider.getWalletAddress(); // Five minutes in seconds (300 seconds) const fiveMinutesInSeconds = 300n; const deadline = await sodax.swaps.getSwapDeadline(fiveMinutesInSeconds); const createIntentParams: CreateIntentParams = { inputToken: arbEthToken, outputToken: polygonPolToken, inputAmount: inputAmount, minOutputAmount: (quotedAmount * 95n) / 100n, // 5% slippage tolerance deadline: deadline, allowPartialFill: false, srcChain: ARBITRUM_MAINNET_CHAIN_ID, dstChain: POLYGON_MAINNET_CHAIN_ID, srcAddress: walletAddress, dstAddress: walletAddress, solver: '0x0000000000000000000000000000000000000000', data: '0x', }; const allowanceResult = await sodax.swaps.isAllowanceValid({ intentParams: createIntentParams, spokeProvider: arbSpokeProvider, }); if (!allowanceResult.ok) { console.error('Failed to check allowance:', allowanceResult.error); return; } // Step 5: Approve if Needed if (!allowanceResult.value) { console.log('Step 5: Approving tokens...'); const approveResult = await sodax.swaps.approve({ intentParams: createIntentParams, spokeProvider: arbSpokeProvider, }); if (!approveResult.ok) { console.error('Failed to approve tokens:', approveResult.error); return; } const approvalTxHash = approveResult.value; console.log('Approval transaction hash:', approvalTxHash); // Wait for approval confirmation await arbSpokeProvider.walletProvider.waitForTransactionReceipt(approvalTxHash); console.log('Approval confirmed'); } else { console.log('Step 5: Approval not needed'); } // Step 6: Execute Swap console.log('Step 6: Executing swap...'); const swapResult = await sodax.swaps.swap({ intentParams: createIntentParams, spokeProvider: arbSpokeProvider, }); // Step 7: Handle Swap Result if (!swapResult.ok) { console.error('Step 7: Swap failed'); const error = swapResult.error; if (isIntentCreationFailedError(error)) { console.error('Intent creation failed'); console.error('Payload:', error.data.payload); console.error('Original error:', error.data.error); } else if (isIntentSubmitTxFailedError(error)) { console.error('Submit transaction failed'); console.error('Payload:', error.data.payload); console.error('Original error:', error.data.error); console.error('CRITICAL: Transaction created but not submitted to relay. Retry submission!'); } else if (isWaitUntilIntentExecutedFailed(error)) { ``` -------------------------------- ### Browser: Initialize StellarSpokeProvider Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/HOW_TO_CREATE_A_SPOKE_PROVIDER.md Use this in browser environments where a Stellar wallet provider is injected. Ensure the wallet provider is available before instantiation. ```typescript import { StellarSpokeProvider, STELLAR_MAINNET_CHAIN_ID, spokeChainConfig, type StellarSpokeChainConfig, type IStellarWalletProvider } from "@sodax/sdk"; // Wallet provider is typically injected by Stellar wallet extension const stellarWalletProvider: IStellarWalletProvider = /* injected by wallet */; // Get chain configuration const stellarChainConfig = spokeChainConfig[STELLAR_MAINNET_CHAIN_ID] as StellarSpokeChainConfig; // Create Stellar spoke provider const stellarSpokeProvider = new StellarSpokeProvider( stellarWalletProvider, stellarChainConfig ); ``` -------------------------------- ### Initialize Sodax SDK for DEX Operations Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/DEX.md Import and instantiate the Sodax SDK, then access the `dex` property to get services for asset and concentrated liquidity operations. ```typescript import { Sodax } from "@sodax/sdk"; const sodax = new Sodax(); // Asset operations (deposit/withdraw/allowance) const assetService = sodax.dex.assetService; // Concentrated liquidity operations (positions/pools/rewards) const clService = sodax.dex.clService; ``` -------------------------------- ### Get Orderbook Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md Retrieves the solver orderbook with pagination support. ```APIDOC ## GET /solver/orderbook ### Description Retrieves the solver orderbook with pagination support. ### Method GET ### Endpoint /solver/orderbook?offset={offset}&limit={limit} ### Parameters #### Query Parameters - **offset** (string) - Required - Starting position for pagination - **limit** (string) - Required - Maximum number of items to return ### Response #### Success Response (200) - **total** (number) - The total number of orderbook entries. - **data** (Array) - An array of orderbook entries. - **intentState** (object) - **exists** (boolean) - **remainingInput** (string) - **receivedOutput** (string) - **pendingPayment** (boolean) - **intentData** (object) - **intentId** (string) - **creator** (string) - **inputToken** (string) - **outputToken** (string) - **inputAmount** (string) - **minOutputAmount** (string) - **deadline** (string) - **allowPartialFill** (boolean) - **srcChain** (number) - **dstChain** (number) - **srcAddress** (string) - **dstAddress** (string) - **solver** (string) - **data** (string) - **intentHash** (string) - **txHash** (string) - **blockNumber** (number) ### Response Example { "total": 25, "data": [ { "intentState": { "exists": true, "remainingInput": "1000000000000000000", "receivedOutput": "0", "pendingPayment": false }, "intentData": { "intentId": "intent_123", "creator": "0x789...ghi", "inputToken": "0xabc...123", "outputToken": "0xdef...456", "inputAmount": "1000000000000000000", "minOutputAmount": "950000000000000000", "deadline": "1700000000", "allowPartialFill": true, "srcChain": 146, "dstChain": 1, "srcAddress": "0x789...ghi", "dstAddress": "0x789...ghi", "solver": "0x000...000", "data": "0x", "intentHash": "0x456...def", "txHash": "0x123...abc", "blockNumber": 12345678 } } ] } ``` -------------------------------- ### GET /intent/{intentHash} Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md Retrieves intent details using an intent hash. ```APIDOC ## GET /intent/{intentHash} ### Description Retrieves intent details using an intent hash. ### Method GET ### Endpoint `/intent/{intentHash}` ### Parameters #### Path Parameters - **intentHash** (string) - Required - The intent hash ### Response #### Success Response (200) - **intentHash** (string) - The hash of the intent. - **txHash** (string) - The transaction hash associated with the intent. - **logIndex** (number) - The log index of the event. - **chainId** (number) - The chain ID where the intent was created. - **blockNumber** (number) - The block number where the intent was confirmed. - **open** (boolean) - Indicates if the intent is still open for fulfillment. - **intent** (object) - Details of the intent itself. - **intentId** (string) - Unique identifier for the intent. - **creator** (string) - The address of the intent creator. - **inputToken** (string) - The address of the input token. - **outputToken** (string) - The address of the output token. - **inputAmount** (string) - The amount of input token. - **minOutputAmount** (string) - The minimum acceptable output amount. - **deadline** (string) - The deadline for fulfilling the intent. - **allowPartialFill** (boolean) - Whether partial fulfillment is allowed. - **srcChain** (number) - The source chain ID. - **dstChain** (number) - The destination chain ID. - **srcAddress** (string) - The source address. - **dstAddress** (string) - The destination address. - **solver** (string) - The address of the solver. - **data** (string) - Additional data for the intent. - **events** (unknown[]) - An array of associated events. ### Response Example ```json { "intentHash": "0x456...def", "txHash": "0x123...abc", "logIndex": 0, "chainId": 146, "blockNumber": 12345678, "open": true, "intent": { "intentId": "intent_123", "creator": "0x789...ghi", "inputToken": "0xabc...123", "outputToken": "0xdef...456", "inputAmount": "1000000000000000000", "minOutputAmount": "950000000000000000", "deadline": "1700000000", "allowPartialFill": true, "srcChain": 146, "dstChain": 1, "srcAddress": "0x789...ghi", "dstAddress": "0x789...ghi", "solver": "0x000...000", "data": "0x" }, "events": [] } ``` ``` -------------------------------- ### Checkout Release Branch Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/RELEASE_INSTRUCTIONS.md Use this command to switch to the 'release/sdk' branch for preparing a new release. ```bash git checkout release/sdk ``` -------------------------------- ### GET /intent/tx/{txHash} Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md Retrieves intent details using a transaction hash. ```APIDOC ## GET /intent/tx/{txHash} ### Description Retrieves intent details using a transaction hash. ### Method GET ### Endpoint `/intent/tx/{txHash}` ### Parameters #### Path Parameters - **txHash** (string) - Required - The transaction hash ### Response #### Success Response (200) - **intentHash** (string) - The hash of the intent. - **txHash** (string) - The transaction hash associated with the intent. - **logIndex** (number) - The log index of the event. - **chainId** (number) - The chain ID where the intent was created. - **blockNumber** (number) - The block number where the intent was confirmed. - **open** (boolean) - Indicates if the intent is still open for fulfillment. - **intent** (object) - Details of the intent itself. - **intentId** (string) - Unique identifier for the intent. - **creator** (string) - The address of the intent creator. - **inputToken** (string) - The address of the input token. - **outputToken** (string) - The address of the output token. - **inputAmount** (string) - The amount of input token. - **minOutputAmount** (string) - The minimum acceptable output amount. - **deadline** (string) - The deadline for fulfilling the intent. - **allowPartialFill** (boolean) - Whether partial fulfillment is allowed. - **srcChain** (number) - The source chain ID. - **dstChain** (number) - The destination chain ID. - **srcAddress** (string) - The source address. - **dstAddress** (string) - The destination address. - **solver** (string) - The address of the solver. - **data** (string) - Additional data for the intent. - **events** (unknown[]) - An array of associated events. ### Response Example ```json { "intentHash": "0x456...def", "txHash": "0x123...abc", "logIndex": 0, "chainId": 146, "blockNumber": 12345678, "open": true, "intent": { "intentId": "intent_123", "creator": "0x789...ghi", "inputToken": "0xabc...123", "outputToken": "0xdef...456", "inputAmount": "1000000000000000000", "minOutputAmount": "950000000000000000", "deadline": "1700000000", "allowPartialFill": true, "srcChain": 146, "dstChain": 1, "srcAddress": "0x789...ghi", "dstAddress": "0x789...ghi", "solver": "0x000...000", "data": "0x" }, "events": [] } ``` ``` -------------------------------- ### Estimate Gas for Money Market Transactions Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/MONEY_MARKET.md Use the `estimateGas` static method on `MoneyMarketService` to get gas cost estimates for raw transactions before execution. This applies to supply, borrow, withdraw, and repay operations, as well as approvals. Ensure the `true` flag is passed to intent creation functions to get the raw transaction. ```typescript import { MoneyMarketService, MoneyMarketSupplyParams } from "@sodax/sdk"; // Example: Estimate gas for a supply transaction const supplyResult = await sodax.moneyMarket.createSupplyIntent( supplyParams, spokeProvider, true, // true = get raw transaction ); if (supplyResult.ok) { const rawTx = supplyResult.value; // Estimate gas for the raw transaction (static method) // Note: MoneyMarketService.estimateGas is a static method const gasEstimate = await MoneyMarketService.estimateGas(rawTx, spokeProvider); if (gasEstimate.ok) { console.log('Estimated gas for supply:', gasEstimate.value); } else { console.error('Failed to estimate gas for supply:', gasEstimate.error); } } // Example: Estimate gas for an approval transaction const approveResult = await sodax.moneyMarket.approve( supplyParams, spokeProvider, true // true = get raw transaction ); if (approveResult.ok) { const rawTx = approveResult.value; // Estimate gas for the approval transaction (static method) const gasEstimate = await MoneyMarketService.estimateGas(rawTx, spokeProvider); if (gasEstimate.ok) { console.log('Estimated gas for approval:', gasEstimate.value); } else { console.error('Failed to estimate gas for approval:', gasEstimate.error); } } // Example: Estimate gas for a borrow transaction const borrowResult = await sodax.moneyMarket.createBorrowIntent( borrowParams, spokeProvider, true // true = get raw transaction ); if (borrowResult.ok) { const rawTx = borrowResult.value; // Estimate gas for the borrow transaction const gasEstimate = await MoneyMarketService.estimateGas(rawTx, spokeProvider); if (gasEstimate.ok) { console.log('Estimated gas for borrow:', gasEstimate.value); } else { console.error('Failed to estimate gas for borrow:', gasEstimate.error); } } // Example: Estimate gas for a withdraw transaction const withdrawResult = await sodax.moneyMarket.createWithdrawIntent( withdrawParams, spokeProvider, true // true = get raw transaction ); if (withdrawResult.ok) { const rawTx = withdrawResult.value; // Estimate gas for the withdraw transaction const gasEstimate = await MoneyMarketService.estimateGas(rawTx, spokeProvider); if (gasEstimate.ok) { console.log('Estimated gas for withdraw:', gasEstimate.value); } else { console.error('Failed to estimate gas for withdraw:', gasEstimate.error); } } // Example: Estimate gas for a repay transaction const repayResult = await sodax.moneyMarket.createRepayIntent( repayParams, spokeProvider, true // true = get raw transaction ); if (repayResult.ok) { const rawTx = repayResult.value; // Estimate gas for the repay transaction const gasEstimate = await MoneyMarketService.estimateGas(rawTx, spokeProvider); if (gasEstimate.ok) { console.log('Estimated gas for repay:', gasEstimate.value); } else { console.error('Failed to estimate gas for repay:', gasEstimate.error); } } ``` -------------------------------- ### Get Staking Configuration Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/STAKING.md Retrieves the current staking configuration parameters from the stakedSoda contract. ```APIDOC ## GET /api/staking/getStakingConfig ### Description Retrieves staking configuration from the stakedSoda contract. ### Method GET ### Endpoint /api/staking/getStakingConfig ### Parameters None ### Response #### Success Response (200) - **ok** (boolean) - Indicates if the operation was successful. - **value** (StakingConfig) - An object containing staking configuration details. - **unstakingPeriod** (bigint) - The duration of the unstaking period in seconds. - **minUnstakingPeriod** (bigint) - The minimum unstaking period in seconds. - **maxPenalty** (bigint) - The maximum penalty percentage. #### Error Response (400) - **ok** (boolean) - Indicates if the operation was successful (false). - **error** (StakingError<'INFO_FETCH_FAILED'>) - The error object detailing the failure. #### Response Example ```json { "ok": true, "value": { "unstakingPeriod": "2592000", "minUnstakingPeriod": "86400", "maxPenalty": "50" } } ``` ``` -------------------------------- ### Get All Money Market Borrowers Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BACKEND_API.md Retrieves a paginated list of all money market borrowers. ```APIDOC ## GET /moneymarket/borrowers ### Description Retrieves all money market borrowers with pagination. ### Method GET ### Endpoint `/moneymarket/borrowers?offset={offset}&limit={limit}` ### Parameters #### Query Parameters - **offset** (string) - Required - Starting position for pagination - **limit** (string) - Required - Maximum number of items to return ### Response #### Success Response (200) - **borrowers** (string[]) - List of borrower addresses. - **total** (number) - Total number of borrowers. - **offset** (number) - The offset used for pagination. - **limit** (number) - The limit used for pagination. ### Response Example ```json { "borrowers": [ "0x789...ghi", "0xabc...def", "0x123...456" ], "total": 75, "offset": 0, "limit": 10 } ``` ``` -------------------------------- ### Get Bridgeable Amount API Source: https://github.com/icon-project/sodax-frontend/blob/main/packages/sdk/docs/BRIDGE.md Retrieves the amount available to be bridged between two tokens. ```APIDOC ## GET /api/bridge/getBridgeableAmount ### Description Retrieves the amount available to be bridged between two tokens. ### Method GET ### Endpoint /api/bridge/getBridgeableAmount ### Parameters #### Query Parameters - **from** (XToken) - Required - Source X token (XToken object with address and xChainId) - **to** (XToken) - Required - Destination X token (XToken object with address and xChainId) ### Response #### Success Response (200) - **Result** (bigint | unknown) - Token amount available to be bridged. #### Response Example ```json { "ok": true, "value": "1000000000000000000" } ``` ### Notes This method handles different bridging scenarios: - **spoke → hub**: checks max deposit available on source chain - **hub → spoke**: checks asset manager balance on destination chain - **spoke → spoke**: returns minimum of available deposit and withdrawable balance ``` -------------------------------- ### Initialize Sodax SDK Source: https://context7.com/icon-project/sodax-frontend/llms.txt Initialize the Sodax SDK with default settings, custom partner fees, or a full custom configuration. Call `initialize()` to fetch the latest configurations from the backend API. ```typescript import { Sodax, getSolverConfig, getMoneyMarketConfig, getHubChainConfig, SONIC_MAINNET_CHAIN_ID, type PartnerFee } from '@sodax/sdk'; // Basic initialization with defaults (mainnet) const sodax = new Sodax(); await sodax.initialize(); // Fetches latest config from backend API // With partner fees const partnerFee: PartnerFee = { address: '0xYourFeeReceiverAddress', percentage: 100, // 100 = 1%, 10000 = 100% }; const sodaxWithFees = new Sodax({ swap: { partnerFee }, moneyMarket: { partnerFee }, }); // Full custom configuration const sodaxCustom = new Sodax({ swap: getSolverConfig(SONIC_MAINNET_CHAIN_ID), moneyMarket: getMoneyMarketConfig(SONIC_MAINNET_CHAIN_ID), hubProviderConfig: { hubRpcUrl: 'https://rpc.soniclabs.com', chainConfig: getHubChainConfig(SONIC_MAINNET_CHAIN_ID), }, backendApiConfig: { baseURL: 'https://api.sodax.com/v1/be', timeout: 60000, }, }); await sodaxCustom.initialize(); ```