### Get User Wallet Balances (JavaScript) Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Fetches the native TON balance and all associated jetton balances for a given wallet address. It utilizes TON API services for TON balance and jetton data, and a token service for account-specific jetton information. Note: Address conversion is handled by `@tonconnect/ui`. ```javascript import { tokenService, tonApiService } from '@/api/coffeeApi/services'; import { toUserFriendlyAddress } from '@tonconnect/ui'; async function getUserBalances(walletAddress) { try { // Get TON balance const tonBalance = await tonApiService.getBalance(walletAddress); console.log('TON balance (nanotons):', tonBalance.data); // Get all jetton balances const jettons = await tonApiService.getTonJettons( toUserFriendlyAddress(walletAddress) ); const balances = jettons.balances.map(item => ({ token: item.jetton.symbol, address: item.jetton.address, balance: item.balance, balanceFormatted: item.balance / Math.pow(10, item.jetton.decimals), price: item.price?.usd || 0 })); console.log('Jetton balances:', balances); // Get account jettons via tokens API const accountJettons = await tokenService.getAccountBalance(walletAddress); console.log('Account jettons:', accountJettons); return { ton: tonBalance.data, jettons: balances }; } catch (error) { console.error('Balance query failed:', error); throw error; } } ``` -------------------------------- ### Initialize Swap Widget with TonConnect Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Initializes and mounts the swap widget using TonConnect for wallet authentication. It configures theme, locale, TonConnect details, referral ID, initial token amount, and preferred liquidity sources. Dependencies include '@swap-coffee/ui-sdk' and '@tonconnect/ui'. ```javascript import { createSwapWidget, SWAP_WIDGET_THEME, SWAP_WIDGET_LOCALE, SWAP_WIDGET_LIQUIDITY_SOURCES } from '@swap-coffee/ui-sdk'; import { TonConnectUI, THEME } from '@tonconnect/ui'; // Create TonConnect UI instance const tonConnectUiInstance = new TonConnectUI({ manifestUrl: "https://your-app.com/tonconnect-manifest.json", uiPreferences: { theme: THEME.DARK, }, }); // Initialize widget with TonConnect mode createSwapWidget('#swap-widget-component', { theme: SWAP_WIDGET_THEME.DARK, locale: SWAP_WIDGET_LOCALE.EN, injectionMode: "tonConnect", tonConnectManifest: { url: "https://your-app.com/tonconnect-manifest.json", }, tonConnectUi: tonConnectUiInstance, widgetReferral: "your-referral-id", firstTokenAmount: 50, limitDcaVisibility: false, liquiditySourcesList: [ SWAP_WIDGET_LIQUIDITY_SOURCES.DEDUST, SWAP_WIDGET_LIQUIDITY_SOURCES.STONFI_V2, SWAP_WIDGET_LIQUIDITY_SOURCES.TONCO, ], enableCommunityTokens: true, sendReceiveTokenAddresses: [ "0:0000000000000000000000000000000000000000000000000000000000000000", "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs" ], customFeeSettings: { fixed_fee: null, percentage_fee: 3000, // 0.3% in basis points min_percentage_fee_fixed: '500000000', // 0.5 TON in nanotons max_percentage_fee_fixed: '4000000000', // 4 TON in nanotons }, }); ``` -------------------------------- ### Create Limit Order (JavaScript) Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Facilitates the creation of a limit order on the Swapcoffee platform. This function first verifies user eligibility for strategies and the existence of a strategy wallet, creating one if necessary. It then constructs and sends a transaction for the limit order. Requires `tonConnectUi` for transaction signing. ```javascript import { strategiesService } from '@/api/coffeeApi/services'; import { useLimitStore } from '@/stores/limit'; async function createLimitOrder(tonConnectUi) { const limitStore = useLimitStore(); // Check if user is eligible for strategies const wallet = { address: "0:abc123...", publicKey: "1aa6150..." }; const verification = { public_key: wallet.publicKey, wallet_state_init: "te6cckEC...", proof: { timestamp: Date.now(), domain_val: "swap.coffee", payload: "xyz...", signature: "abc..." } }; const eligible = await strategiesService.checkUserIsEligible( wallet.address, verification ); if (!eligible.is_eligible) { console.log('User not eligible for limit orders'); return; } // Check if strategy wallet exists const walletExists = await strategiesService.checkWalletAddress( wallet.address, verification ); if (!walletExists.data) { // Create strategy wallet first const createWalletTx = await strategiesService.createStrategiesWallet( wallet.address, verification ); await tonConnectUi.sendTransaction({ validUntil: Math.floor(Date.now() / 1000) + 300, messages: [{ address: createWalletTx.data.address, amount: createWalletTx.data.value, payload: createWalletTx.data.payload_cell }] }); } // Create limit order const orderBody = { type: 'limit', from_token: "0:0000000000000000000000000000000000000000000000000000000000000000", to_token: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", from_amount: "5000000000", // 5 TON target_rate: "6.5", // Target price: 6.5 USDT per TON suborders_count: 3 // Split into 3 sub-orders }; const orderTx = await strategiesService.createOrder( wallet.address, verification, orderBody ); await tonConnectUi.sendTransaction({ validUntil: Math.floor(Date.now() / 1000) + 300, messages: [{ address: orderTx.data.address, amount: orderTx.data.value, payload: orderTx.data.payload_cell }] }); console.log('Limit order created successfully'); } ``` -------------------------------- ### Configure and Create DCA Order - JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Configures Dollar-Cost Averaging (DCA) settings including execution interval, price range, and number of suborders. It then retrieves supported tokens, constructs the DCA order payload, and sends the transaction for order creation using the TON Connect UI and provided wallet verification. Dependencies include '@/api/coffeeApi/services' and '@/stores/dca'. ```javascript import { strategiesService } from '@/api/coffeeApi/services'; import { useDcaStore } from '@/stores/dca'; async function createDcaOrder(tonConnectUi, wallet, verification) { const dcaStore = useDcaStore(); // Configure DCA settings dcaStore.DCA_EVERY_TIME(3600); // Execute every hour (3600 seconds) dcaStore.DCA_ENABLE_RANGE(true); dcaStore.DCA_MIN_RANGE(5.0); // Execute only if price >= 5.0 dcaStore.DCA_MAX_RANGE(7.0); // Execute only if price <= 7.0 // Get supported tokens for DCA const fromTokens = await strategiesService.getSupportedFromTokens('dca'); const toTokens = await strategiesService.getSupportedToTokens( fromTokens[0].address, 'dca' ); console.log('DCA from tokens:', fromTokens); console.log('DCA to tokens:', toTokens); // Create DCA order const dcaOrderBody = { type: 'dca', from_token: "0:0000000000000000000000000000000000000000000000000000000000000000", to_token: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", from_amount: "10000000000", // 10 TON total interval_seconds: dcaStore.GET_DCA_EVERY_TIME, min_price: dcaStore.GET_MIN_RANGE?.toString(), max_price: dcaStore.GET_MAX_RANGE?.toString(), suborders_count: 10 // Split into 10 equal purchases }; try { const dcaTx = await strategiesService.createOrder( wallet.address, verification, dcaOrderBody ); await tonConnectUi.sendTransaction({ validUntil: Math.floor(Date.now() / 1000) + 300, messages: [{ address: dcaTx.data.address, amount: dcaTx.data.value, payload: dcaTx.data.payload_cell }] }); console.log('DCA order created successfully'); console.log(`Will execute ${dcaOrderBody.suborders_count} purchases every ${dcaOrderBody.interval_seconds}s`); } catch (error) { console.error('DCA order creation failed:', error); } } ``` -------------------------------- ### Initialize Swap Widget with Payload Authentication Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Initializes the swap widget using a pre-authenticated wallet payload, suitable for embedded wallets. Configuration includes theme, locale, payload details, and referral ID. Dependencies include '@swap-coffee/ui-sdk'. ```javascript import { createSwapWidget, SWAP_WIDGET_THEME, SWAP_WIDGET_LOCALE } from '@swap-coffee/ui-sdk'; // Payload structure from wallet authentication const payload = { wallet_meta: { address: "0:e867df1c40a11d2aa28ee003b6da58cec7518df463f93b72185c8aabbcbe3b1a", }, verify: { public_key: "1aa6150cea2170a5a850892318425279fcb79db2d1d77130230d8e30c2abbb35", wallet_state_init: "te6cckECFgEAAwQAAgE0ARUBFP8A9KQT9LzyyAsCAgEgAxACAUgEBwLm...", proof: { timestamp: 1733138437, domain_len: 11, domain_val: "swap.coffee", payload: "0MllhaYxFCsNZAcZnlyr4ZPImsPL1wsY", signature: "uq6/e/RANyred6NzWZ8Rd/AeJPZwzym/srIDytfz/VPk6V9jQ+LrmeVQigD0KYH6ACAa..." } } }; // Initialize widget in payload mode (for embedded wallets) createSwapWidget('#swap-widget-component', { theme: SWAP_WIDGET_THEME.LIGHT, locale: SWAP_WIDGET_LOCALE.EN, injectionMode: 'payload', payload: payload, widgetReferral: 'embedded-wallet-app', firstTokenAmount: 100, }); ``` -------------------------------- ### Listen to SDK Events with JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Provides a function to set up event listeners for various widget events from the Swapcoffee UI SDK. This allows for analytics tracking and custom handling of events like swap initiation, route calculation, transaction completion, wallet connections, and more. ```javascript import { ReadonlySdkEvent } from '@swap-coffee/ui-sdk'; function setupEventListeners() { // Listen for swap initiation window.addEventListener(ReadonlySdkEvent.SWAP_STARTED, (event) => { console.log('Swap started:', event.detail); console.log('Send token:', event.detail.sendToken); console.log('Receive token:', event.detail.receiveToken); console.log('Send amount:', event.detail.sendAmount); console.log('Expected receive:', event.detail.receiveAmount); }); // Listen for route calculation window.addEventListener(ReadonlySdkEvent.ROUTE_BUILT, (event) => { console.log('Route calculated:', event.detail); }); // Listen for transaction build completion window.addEventListener(ReadonlySdkEvent.TRANSACTIONS_BUILT, (event) => { console.log('Transactions built:', event.detail); console.log('Route ID:', event.detail.route_id); console.log('Transaction count:', event.detail.transactions.length); }); // Listen for swap completion window.addEventListener(ReadonlySdkEvent.SWAP_COMPLETED, (event) => { console.log('Swap completed:', event.detail); }); // Listen for wallet connection window.addEventListener(ReadonlySdkEvent.WALLET_CONNECTED, (event) => { console.log('Wallet connected:', event.detail); }); // Listen for wallet disconnection window.addEventListener(ReadonlySdkEvent.WALLET_DISCONNECTED, (event) => { console.log('Wallet disconnected:', event.detail.reason); }); // Listen for token selection changes window.addEventListener(ReadonlySdkEvent.TOKEN_CHANGED, (event) => { console.log('Token changed:', event.detail); }); // Listen for settings updates window.addEventListener(ReadonlySdkEvent.SWAP_SETTINGS_UPDATED, (event) => { console.log('Settings updated:', event.detail); }); // Listen for token imports window.addEventListener(ReadonlySdkEvent.TOKEN_IMPORTED, (event) => { console.log('Token imported:', event.detail); }); } // Setup listeners when widget is initializedsetupEventListeners(); ``` -------------------------------- ### Execute Multi-Asset Swap using JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Execute a swap involving multiple input tokens to a single output token. This function first retrieves the optimal multi-asset swap route using `dexService.getMultiRoute` and then executes the transaction via `multiTransaction`. It requires `tonConnectUi` and allows configuration of slippage, tracking data, and custom fees. ```javascript import { dexService } from '@/api/coffeeApi/services'; import { multiTransaction } from '@/helpers/swap-interface/send-transaction'; async function executeMultiSwap(tonConnectUi) { // Get route for multi-asset swap const multiRoute = await dexService.getMultiRoute({ input_tokens: [ { address: "0:0000000000000000000000000000000000000000000000000000000000000000", amount: "500000000" // 0.5 TON }, { address: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", amount: "1000000" // 1 USDT } ], output_token_address: "EQBlqsm144Dq6SjbPI4jjZvA1hqTIP3CvHovbIfW_t-SCALE", slippage: 0.015 // 1.5% slippage }); const compareAsset = { tokens: new Map([ ['first', { address: "0:0000...", symbol: 'TON' }], ['second', { address: "EQCX...", symbol: 'USDT' }] ]), amounts: new Map([ ['first', 0.5], ['second', 1.0] ]) }; const trackingData = { tokens: compareAsset.tokens, amounts: compareAsset.amounts }; try { await multiTransaction({ updateProcessing: (processing, mode) => console.log(`Multi-swap ${mode}: ${processing}`), compareAsset, wallet: { address: "0:abc123...", version: 4 }, dealConditions: multiRoute, slippage: 1.5, tonConnectUi, trackingData, mevProtection: false, customFeeSettings: null, widgetReferral: 'my-app' }); console.log('Multi-asset swap completed'); } catch (error) { console.error('Multi-swap failed:', error); } } ``` -------------------------------- ### Perform TON Liquid Staking Source: https://context7.com/swapcoffee/ui-sdk/llms.txt This Javascript function demonstrates how to stake TON for liquid staking tokens using the `stakeTransaction` helper. It requires wallet information, token details for TON and the liquid staking token, and the amount to stake. It also utilizes a `tonConnectUi` instance for wallet interaction and an `updateProcessing` callback to show transaction status. ```javascript import { stakeTransaction } from '@/helpers/swap-interface/send-transaction'; import { tokenService } from '@/api/coffeeApi/services'; async function performStaking(tonConnectUi) { // Get available staking pools const stakingPool = await tokenService.getStakingPool('tonstakers-pool-id'); console.log('Staking pool:', stakingPool); console.log('APY:', stakingPool.apy); console.log('Liquid token:', stakingPool.liquid_token); const wallet = { address: "0:abc123...", version: 4 }; const tokens = { first: { // TON (input) address: "0:0000000000000000000000000000000000000000000000000000000000000000", symbol: "TON", decimals: 9 }, second: { // Liquid staking token (output, e.g., tsTON) address: stakingPool.liquid_token.address, symbol: stakingPool.liquid_token.symbol, decimals: 9 } }; const amounts = { first: "5000000000", // 5 TON to stake second: "5000000000" // Expected ~5 tsTON }; const updateProcessing = (isProcessing, mode) => { console.log(`${mode}: ${isProcessing ? 'Processing...' : 'Complete'}`); }; try { // Stake TON for liquid staking tokens await stakeTransaction({ updateProcessing, wallet, tokens, amounts, tonConnectUi }); console.log('Staking successful! Received liquid staking tokens.'); } catch (error) { console.error('Staking failed:', error); } } ``` -------------------------------- ### Calculate Optimal Swap Route Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Calculates the most efficient swap route across specified DEX protocols. It takes input and output token addresses, amount, slippage tolerance, and preferred DEXs as input. Outputs include the optimal route details, output amount, price impact, and path information. Depends on the 'dexService' from '@/api/coffeeApi/services'. ```javascript import { dexService } from '@/api/coffeeApi/services'; async function calculateSwapRoute() { try { const route = await dexService.getRoute({ input_token_address: "0:0000000000000000000000000000000000000000000000000000000000000000", output_token_address: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", input_amount: "1000000000", // 1 TON in nanotons slippage: 0.01, // 1% slippage pool_selector: { dexes: ["dedust", "stonfi_v2", "tonco"] } }); console.log('Best route:', route); console.log('Output amount:', route.output_amount); console.log('Price impact:', route.price_impact); console.log('Paths:', route.paths); // route.paths contains the optimal path through DEX pools return route; } catch (error) { console.error('Route calculation failed:', error); throw error; } } ``` -------------------------------- ### Execute DEX Swap Transaction using JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Build and send a DEX swap transaction through an optimal route. This function handles the comparison of assets, wallet information, and deal conditions to execute a swap. It utilizes the `dextransaction` helper function and requires a `tonConnectUi` instance. Slippage and custom fee settings can be configured. ```javascript import { dexTransaction } from '@/helpers/swap-interface/send-transaction'; import { useDexStore } from '@/stores/dex'; async function executeSwap(tonConnectUi) { const dexStore = useDexStore(); const compareAsset = { tokens: { first: dexStore.GET_SEND_TOKEN, second: dexStore.GET_RECEIVE_TOKEN }, amounts: { first: dexStore.GET_SEND_AMOUNT, second: dexStore.GET_RECEIVE_AMOUNT } }; const wallet = { address: dexStore.GET_DEX_WALLET.address, version: dexStore.GET_DEX_WALLET_VERSION }; const updateProcessing = (isProcessing, mode) => { console.log(`Transaction ${mode}: ${isProcessing ? 'started' : 'completed'}`); }; try { await dexTransaction({ updateProcessing, compareAsset, wallet, dealConditions: dexStore.GET_DEAL_CONDITIONS, slippage: 1.0, // 1% slippage widgetReferral: 'my-app', customFeeSettings: { percentage_fee: 2500, // 0.25% min_percentage_fee_fixed: '300000000', max_percentage_fee_fixed: '3000000000' }, tonConnectUi, mevProtection: false }); console.log('Swap transaction sent successfully'); } catch (error) { console.error('Swap transaction failed:', error); throw error; } } ``` -------------------------------- ### Token Management using JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Fetch and manage token lists with various filtering options. This function demonstrates how to retrieve paginated lists of whitelisted tokens, specific tokens by address, and tokens by label. It uses the `tokenService` API and handles potential errors during the loading process. ```javascript import { tokenService } from '@/api/coffeeApi/services'; async function loadTokens() { try { // Get whitelisted tokens (paginated) const tokenList = await tokenService.getTokenListV2({ page: 1, size: 50 }, false, false); console.log(`Loaded ${tokenList.items.length} tokens`); console.log('First token:', tokenList.items[0]); // Get tokens by specific addresses const specificTokens = await tokenService.getTokensByAddress([ "0:0000000000000000000000000000000000000000000000000000000000000000", "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs" ]); // Get single token details const tonToken = await tokenService.getTokenByAddress( "0:0000000000000000000000000000000000000000000000000000000000000000" ); console.log('TON token:', tonToken); // Get tokens by label (e.g., "DeFi", "Meme", etc.) const defiTokens = await tokenService.getTokensByLabel( 'defi', false, // addCommunity false, // onlyCommunity 1, // page 100, // size 'stake' // search term ); return tokenList.items; } catch (error) { console.error('Token loading failed:', error); throw error; } } ``` -------------------------------- ### Manage Order History - JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Retrieves and manages both active limit orders and completed DCA orders for a given wallet. It fetches active limit orders and completed DCA orders using the `strategiesService.getOrders` function. The function also retrieves details for the first active limit order and updates the respective stores (`useLimitStore`). Dependencies include '@/api/coffeeApi/services' and '@/stores/limit'. ```javascript import { strategiesService } from '@/api/coffeeApi/services'; import { useLimitStore } from '@/stores/limit'; async function manageOrders(wallet, verification) { const limitStore = useLimitStore(); try { // Get active limit orders const activeLimitOrders = await strategiesService.getOrders( wallet.address, verification, 'limit', false // finished = false for active orders ); console.log('Active limit orders:', activeLimitOrders.data); limitStore.LIMIT_HISTORY(activeLimitOrders.data); // Get completed DCA orders const completedDcaOrders = await strategiesService.getOrders( wallet.address, verification, 'dca', true // finished = true for completed orders ); console.log('Completed DCA orders:', completedDcaOrders.data); // Get order details if (activeLimitOrders.data.length > 0) { const firstOrder = activeLimitOrders.data[0]; limitStore.LIMIT_TRANSACTION_DETAILS(firstOrder); console.log('Order ID:', firstOrder.id); console.log('Status:', firstOrder.status); console.log('Progress:', firstOrder.executed_suborders, '/', firstOrder.total_suborders); console.log('From token:', firstOrder.from_token.symbol); console.log('To token:', firstOrder.to_token.symbol); } return { activeLimitOrders: activeLimitOrders.data, completedDcaOrders: completedDcaOrders.data }; } catch (error) { console.error('Failed to fetch orders:', error); throw error; } } ``` -------------------------------- ### Perform TON Liquid Unstaking Source: https://context7.com/swapcoffee/ui-sdk/llms.txt This Javascript function demonstrates how to unstake liquid staking tokens back into TON using the `unstakeTransaction` helper. It requires wallet information, token details for the liquid staking token and TON, and the amount to unstake. It also utilizes a `tonConnectUi` instance for wallet interaction and an `updateProcessing` callback to show transaction status. ```javascript import { unstakeTransaction } from '@/helpers/swap-interface/send-transaction'; async function performUnstaking(tonConnectUi) { const wallet = { address: "0:abc123...", version: 4 }; const tokens = { first: { // Liquid staking token (input, e.g., tsTON) address: "EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs", symbol: "tsTON", decimals: 9 }, second: { // TON (output) address: "0:0000000000000000000000000000000000000000000000000000000000000000", symbol: "TON", decimals: 9 } }; const amounts = { first: "3000000000", // 3 tsTON to unstake second: "3000000000" // Expected ~3 TON }; const updateProcessing = (isProcessing, mode) => { console.log(`${mode}: ${isProcessing ? 'Processing...' : 'Complete'}`); }; try { // Unstake liquid tokens back to TON await unstakeTransaction({ updateProcessing, wallet, tokens, amounts, tonConnectUi }); console.log('Unstaking successful! TON will be available after unbonding period.'); } catch (error) { console.error('Unstaking failed:', error); } } ``` -------------------------------- ### Cancel Order with JavaScript Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Demonstrates how to cancel an active limit or DCA order using the strategiesService. This function requires order details, wallet information, verification, and TON Connect UI. It prepares and sends a cancellation transaction, then refreshes the order history. ```javascript import { strategiesService } from '@/api/coffeeApi/services'; async function cancelOrder(orderId, wallet, verification, tonConnectUi) { try { // Get cancellation transaction const cancelTx = await strategiesService.cancelOrderById( wallet.address, verification, orderId ); console.log('Cancellation transaction prepared for order:', orderId); // Send cancellation transaction await tonConnectUi.sendTransaction({ validUntil: Math.floor(Date.now() / 1000) + 300, messages: [{ address: cancelTx.data.address, amount: cancelTx.data.value, payload: cancelTx.data.payload_cell }] }); console.log(`Order ${orderId} cancelled successfully`); // Refresh order history const updatedOrders = await strategiesService.getOrders( wallet.address, verification, 'limit', false ); return updatedOrders.data; } catch (error) { console.error('Order cancellation failed:', error); throw error; } } ``` -------------------------------- ### Track Swap Transaction Status (JavaScript) Source: https://context7.com/swapcoffee/ui-sdk/llms.txt Monitors the status of a swap transaction by periodically fetching updates. It logs transaction details, handles completion and failure states, and uses a polling mechanism with a 5-second interval. Dependencies include '@/api/coffeeApi/services' for API calls and '@/stores/transaction' for state management. ```javascript import { dexService } from '@/api/coffeeApi/services'; import { useTransactionStore } from '@/stores/transaction'; async function trackTransactionStatus(routeId) { const transactionStore = useTransactionStore(); const checkStatus = async () => { try { const status = await dexService.getTransactions(routeId); transactionStore.SAVE_SWAP_TRANSACTION_STATUS(status); console.log('Transaction status:', status.status); console.log('Route ID:', status.route_id); console.log('Transactions:', status.transactions); status.transactions.forEach((tx, index) => { console.log(`Transaction ${index + 1}:`, { status: tx.status, hash: tx.hash, timestamp: tx.timestamp }); }); // Status values: 'pending', 'processing', 'completed', 'failed' if (status.status === 'completed') { console.log('Swap completed successfully!'); console.log('Output amount:', status.output_amount); clearInterval(statusInterval); } else if (status.status === 'failed') { console.error('Swap failed:', status.error_message); clearInterval(statusInterval); } return status; } catch (error) { console.error('Status check failed:', error); } }; // Check status every 5 seconds const statusInterval = setInterval(checkStatus, 5000); // Initial check await checkStatus(); return statusInterval; } // Usage after swap transaction async function executeAndTrackSwap(tonConnectUi, routeId) { try { // ... execute swap transaction ... // Start tracking const statusInterval = await trackTransactionStatus(routeId); // Cleanup function return () => clearInterval(statusInterval); } catch (error) { console.error('Swap execution failed:', error); } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.