### Install Swap.coffee SDK using npm Source: https://github.com/swapcoffee/sdk/blob/main/README.md This command installs the Swap.coffee SDK package from npm, making it available for use in your project. It's the first step to integrating the SDK into your application. ```bash npm install @swap-coffee/sdk ``` -------------------------------- ### End-to-End Swap Execution - TypeScript Source: https://context7.com/swapcoffee/sdk/llms.txt A complete example demonstrating wallet connection, route building, transaction execution, and result tracking for a swap. It utilizes `RoutingApi`, `ApiTokenAddress`, and `waitForRouteResults` from '@swap-coffee/sdk', along with '@tonconnect/sdk'. The process involves finding routes, building transactions, sending them via a TON wallet, and waiting for confirmation. ```typescript import { RoutingApi, ApiTokenAddress, waitForRouteResults } from '@swap-coffee/sdk'; import TonConnect from '@tonconnect/sdk'; async function executeSwap() { // Initialize API and wallet const routingApi = new RoutingApi(); const connector = new TonConnect({ manifestUrl: 'https://example.com/tonconnect-manifest.json', }); // Wait for wallet connection await connector.connect(); // Define swap parameters const assetIn: ApiTokenAddress = { blockchain: 'ton', address: 'native', // TON }; const assetOut: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', // CES }; try { // Step 1: Find optimal route console.log('Finding optimal route...'); const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, output_amount: 200, }); console.log('Expected input:', route.data.input_amount); console.log('Expected output:', route.data.output_amount); console.log('Price impact:', route.data.price_impact); // Step 2: Build transactions console.log('Building transactions...'); const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account!.address, slippage: 0.1, // 10% slippage paths: route.data.paths, }); // Step 3: Execute transactions console.log('Sending transactions...'); const messages = transactions.data.transactions.map(tx => ({ address: tx.address, amount: tx.value, payload: tx.cell, })); await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: messages, }); // Step 4: Wait for completion console.log('Waiting for execution...'); const results = await waitForRouteResults( transactions.data.route_id, routingApi ); console.log('Swap completed!'); console.log('Results:', results); } catch (error) { console.error('Swap failed:', error); throw error; } } executeSwap(); ``` -------------------------------- ### Get Route Result Status - TypeScript Source: https://context7.com/swapcoffee/sdk/llms.txt Retrieves the current status of a route without blocking, useful for custom polling logic. It imports `RoutingApi` from '@swap-coffee/sdk' and uses `getRouteResult` to fetch status details, checking for completion or failures in splits. ```typescript import { RoutingApi } from '@swap-coffee/sdk'; const routingApi = new RoutingApi(); // Get current route status const result = await routingApi.getRouteResult(routeId); console.log('Terminal:', result.data.terminal); // True if final console.log('Splits:', result.data.splits); // Check if all splits are complete const allComplete = result.data.splits.every( split => split.status === 'completed' ); const anyFailed = result.data.splits.some( split => split.status === 'failed' ); if (anyFailed) { console.error('Some transactions failed'); result.data.splits.forEach((split, i) => { if (split.status === 'failed') { console.error(`Split ${i} failed:`, split.steps); } }); } ``` -------------------------------- ### Build Multi-Asset Route for Swaps Source: https://context7.com/swapcoffee/sdk/llms.txt Finds optimal routes for swapping multiple input tokens to a single output token using the RoutingApi. This is useful for complex swap scenarios involving several input currencies. ```typescript import { RoutingApi, ApiTokenAddress } from '@swap-coffee/sdk'; const routingApi = new RoutingApi(); const ton: ApiTokenAddress = { blockchain: 'ton', address: 'native', }; const usdt: ApiTokenAddress = { blockchain: 'ton', address: 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs', }; const ces: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', }; // Swap both TON and USDT for CES in a single route const multiRoute = await routingApi.buildMultiAssetRoute({ input_tokens: [ { token: ton, amount: 5 }, { token: usdt, amount: 100 }, ], output_token: ces, }); console.log('Total output:', multiRoute.data.output_amount); console.log('Paths:', multiRoute.data.paths); ``` -------------------------------- ### Build Optimal Swap Route Source: https://context7.com/swapcoffee/sdk/llms.txt Finds the best trading path between two tokens, considering liquidity, fees, and price impact across available DEX protocols. You can specify either the input amount or the desired output amount. ```APIDOC ## POST /buildRoute ### Description Builds an optimal trading route between two tokens on the TON blockchain. ### Method POST ### Endpoint /buildRoute ### Parameters #### Request Body - **input_token** (ApiTokenAddress) - Required - The token to swap from. - **output_token** (ApiTokenAddress) - Required - The token to swap to. - **input_amount** (number) - Optional - The amount of the input token to swap. If not provided, `output_amount` must be specified. - **output_amount** (number) - Optional - The desired amount of the output token. If not provided, `input_amount` must be specified. ### Request Example ```json { "input_token": { "blockchain": "ton", "address": "native" }, "output_token": { "blockchain": "ton", "address": "EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1" }, "input_amount": 5 } ``` ### Response #### Success Response (200) - **output_amount** (number) - The expected amount of the output token. - **paths** (Array) - An array of optimal trading paths. - **price_impact** (number) - The estimated price impact of the swap. #### Response Example ```json { "output_amount": 250.75, "paths": [ { "dex": "DeDust", "pool": "TON-CES", "input_amount": 5, "output_amount": 250.75, "fee": 0.005 } ], "price_impact": 0.02 } ``` ``` -------------------------------- ### Build Optimal Swap Route (TypeScript) Source: https://context7.com/swapcoffee/sdk/llms.txt Constructs the most efficient trading path between two tokens on the TON blockchain using the `buildRoute` method. It considers liquidity, fees, and price impact across various DEX protocols. Inputs include token addresses and either the input or output amount. Outputs include expected amounts, paths, and price impact. ```typescript import { RoutingApi, ApiTokenAddress } from '@swap-coffee/sdk'; const routingApi = new RoutingApi(); // Define tokens - 'native' represents TON const assetIn: ApiTokenAddress = { blockchain: 'ton', address: 'native', }; const assetOut: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', // CES token }; // Build route for swapping 5 TON for CES tokens const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, input_amount: 5, // Amount in tokens (not nano) }); // Response contains optimal paths with expected output console.log('Expected output:', route.data.output_amount); console.log('Paths:', route.data.paths); console.log('Price impact:', route.data.price_impact); // Alternative: specify desired output amount instead const routeByOutput = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, output_amount: 200, // Get exactly 200 CES tokens }); ``` -------------------------------- ### Swap Assets with Swap.coffee SDK and TonConnect SDK (TypeScript) Source: https://github.com/swapcoffee/sdk/blob/main/README.md This TypeScript code snippet demonstrates how to swap assets using the Swap.coffee SDK and TonConnect SDK. It includes setting up TonConnect, defining input and output assets, building a transaction route, and sending the transaction. The `waitForRouteResults` function is used to monitor the transaction's progress. ```typescript import { waitForRouteResults } from './transactions'; const connector = await setupTonConnect(); const routingApi = new RoutingApi(); const assetIn: ApiTokenAddress = { blockchain: 'ton', address: 'native', // stands for TON }; const assetOut: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', // CES }; const input_amount = 5; // 5 TON const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, output_amount: 200, // desired amount of output token }); const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, slippage: 0.1, paths: route.data.paths, // note: use route.data here }); let messages = []; for (const transaction of transactions.data.transactions) { messages.push({ address: transaction.address, amount: transaction.value, payload: transaction.cell, }); } await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: messages, }); const results = await waitForRouteResults(transactions.data.route_id, routingApi); ``` -------------------------------- ### Configure API Authentication with API Key Source: https://context7.com/swapcoffee/sdk/llms.txt Sets up API key authentication for the SDK to access premium features and increased rate limits. Requires an API key and optionally allows overriding the base API endpoint. ```typescript import { Configuration, RoutingApi } from '@swap-coffee/sdk'; // Create configuration with API key const config = new Configuration({ apiKey: 'your-api-key-here', basePath: 'https://api.swap.coffee', // Optional: override API endpoint }); // Use configuration with API instances const routingApi = new RoutingApi(config); // All requests will now include authentication const route = await routingApi.buildRoute({ input_token: { blockchain: 'ton', address: 'native' }, output_token: { blockchain: 'ton', address: 'EQC...' }, input_amount: 5, }); ``` -------------------------------- ### Convert Route to Blockchain Transactions (TypeScript) Source: https://context7.com/swapcoffee/sdk/llms.txt Converts a previously built optimal swap route into ready-to-sign blockchain transactions. This method incorporates slippage protection and gas estimation. It requires the sender's address, slippage tolerance, and the paths from the route. The output is a list of formatted messages suitable for wallet integration, along with a route ID for tracking. ```typescript import { RoutingApi, ApiTokenAddress } from '@swap-coffee/sdk'; import TonConnect from '@tonconnect/sdk'; const routingApi = new RoutingApi(); const connector = new TonConnect(/* config */); const assetIn: ApiTokenAddress = { blockchain: 'ton', address: 'native', }; const assetOut: ApiTokenAddress = { blockchain: 'ton', address: 'EQCl0S4xvoeGeFGijTzicSA8j6GiiugmJW5zxQbZTUntre-1', }; // First, build the route const route = await routingApi.buildRoute({ input_token: assetIn, output_token: assetOut, output_amount: 200, }); // Convert route to executable transactions const transactions = await routingApi.buildTransactionsV2({ sender_address: connector.account?.address!!, slippage: 0.1, // 10% slippage tolerance paths: route.data.paths, // Use paths from route response }); // Format transactions for TonConnect const messages = transactions.data.transactions.map(tx => ({ address: tx.address, amount: tx.value, payload: tx.cell, })); // Send transaction through wallet await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: messages, }); // Save route_id for tracking console.log('Route ID:', transactions.data.route_id); ``` -------------------------------- ### Convert Route to Blockchain Transactions Source: https://context7.com/swapcoffee/sdk/llms.txt Converts a previously built route into ready-to-sign blockchain transactions, including slippage protection and gas estimation. This method is suitable for executing swaps through wallets like TonConnect. ```APIDOC ## POST /buildTransactionsV2 ### Description Converts a given trading route into a series of blockchain transactions suitable for signing and broadcasting. ### Method POST ### Endpoint /buildTransactionsV2 ### Parameters #### Request Body - **sender_address** (string) - Required - The public address of the sender. - **slippage** (number) - Required - The maximum acceptable slippage percentage (e.g., 0.01 for 1%). - **paths** (Array) - Required - The trading paths obtained from the `buildRoute` method. ### Request Example ```json { "sender_address": "UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "slippage": 0.01, "paths": [ { "dex": "DeDust", "pool": "TON-CES", "input_amount": 5, "output_amount": 250.75, "fee": 0.005 } ] } ``` ### Response #### Success Response (200) - **route_id** (string) - A unique identifier for the executed route, used for tracking. - **transactions** (Array) - An array of transaction objects ready to be signed. - **address** (string) - The destination address for the transaction. - **value** (string) - The amount of TON to send (in nano). - **cell** (string) - The transaction payload in BOC format. #### Response Example ```json { "route_id": "abc123xyz789", "transactions": [ { "address": "UQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA", "value": "5000000000", "cell": "BOCq..." } ] } ``` ``` -------------------------------- ### Build TON Staking/Unstaking Transactions - TypeScript Source: https://context7.com/swapcoffee/sdk/llms.txt Creates transactions for liquid staking and unstaking TON tokens using `buildTonStakeTransaction` and `buildTonUnstakeTransaction` from `RoutingApi` in '@swap-coffee/sdk'. It requires sender and validator addresses, along with the amount in nanotons. The generated transaction details (address, value, cell) can then be sent using a wallet connector. ```typescript import { RoutingApi } from '@swap-coffee/sdk'; const routingApi = new RoutingApi(); // Stake 10 TON tokens const stakeTransaction = await routingApi.buildTonStakeTransaction({ sender_address: 'UQC4...', amount: '10000000000', // 10 TON in nanotons validator_address: 'EQD...', // Validator address }); // Send transaction await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: [{ address: stakeTransaction.data.address, amount: stakeTransaction.data.value, payload: stakeTransaction.data.cell, }], }); // Later: unstake tokens const unstakeTransaction = await routingApi.buildTonUnstakeTransaction({ sender_address: 'UQC4...', amount: '10000000000', validator_address: 'EQD...', }); ``` -------------------------------- ### Fetch DEX Pools Information - TypeScript Source: https://context7.com/swapcoffee/sdk/llms.txt Retrieves liquidity pool information using the `getDexPools` method from `DEXApi` in '@swap-coffee/sdk'. This is useful for displaying pool statistics or finding trading pairs. The method can filter pools by specific tokens or fetch all available pools. ```typescript import { DEXApi, ApiTokenAddress } from '@swap-coffee/sdk'; const dexApi = new DEXApi(); // Get all pools for specific tokens const tonAddress = 'native'; const usdtAddress = 'EQCxE6mUtQJKFnGfaROTKOt1lZbDiiX1kCixRv7Nw2Id_sDs'; const pools = await dexApi.getDexPools([tonAddress, usdtAddress]); pools.data.forEach(pool => { console.log('Pool address:', pool.address); console.log('DEX:', pool.dex); console.log('Token0:', pool.token0.symbol); console.log('Token1:', pool.token1.symbol); console.log('Reserves0:', pool.reserves0); console.log('Reserves1:', pool.reserves1); console.log('TVL:', pool.tvl_usd); console.log('24h volume:', pool.volume_24h_usd); console.log('---'); }); // Get all pools (no filter) const allPools = await dexApi.getDexPools(); ``` -------------------------------- ### Handle Errors and Retries in Transactions Source: https://context7.com/swapcoffee/sdk/llms.txt Implements robust error handling for transaction processes, including network issues, slippage failures, and user rejections. Uses a try-catch block and checks for specific error types. ```typescript import { RoutingApi, waitForRouteResults } from '@swap-coffee/sdk'; import { AxiosError } from 'axios'; const routingApi = new RoutingApi(); try { const route = await routingApi.buildRoute({ input_token: { blockchain: 'ton', address: 'native' }, output_token: { blockchain: 'ton', address: 'EQC...' }, input_amount: 5, }); const transactions = await routingApi.buildTransactionsV2({ sender_address: walletAddress, slippage: 0.05, // Tighter slippage paths: route.data.paths, }); await connector.sendTransaction({ validUntil: Date.now() + 5 * 60 * 1000, messages: transactions.data.transactions.map(tx => ({ address: tx.address, amount: tx.value, payload: tx.cell, })), }); const results = await waitForRouteResults( transactions.data.route_id, routingApi ); // Check for failures const failed = results.filter(r => r.status === 'failed'); if (failed.length > 0) { throw new Error('Some transactions failed'); } } catch (error) { if (error instanceof AxiosError) { console.error('API error:', error.response?.status); console.error('Details:', error.response?.data); } else if (error.message?.includes('User rejected')) { console.error('User rejected transaction'); } else { console.error('Unknown error:', error); } } ``` -------------------------------- ### Monitor Transaction Execution Source: https://context7.com/swapcoffee/sdk/llms.txt Polls the Swap.Coffee API to track the status of transactions associated with a specific route ID until they are completed or fail. This provides real-time updates on swap execution. ```APIDOC ## GET /waitForRouteResults ### Description Polls the API for the status of all transactions within a given route ID until they are completed or fail. Allows for custom polling intervals. ### Method GET ### Endpoint /waitForRouteResults ### Parameters #### Query Parameters - **routeId** (string) - Required - The unique identifier of the route to monitor. - **routingApi** (RoutingApi) - Required - An instance of the RoutingApi client. - **pollIntervalMs** (number) - Optional - The interval in milliseconds between polls (defaults to 10000ms). ### Response #### Success Response (200) - **Array** - An array of objects, each representing the status of a transaction split within the route. - **status** (string) - The status of the split ('completed', 'failed', 'pending'). - **input** (Object) - Details about the input for this split. - **amount** (number) - The amount of input tokens. - **output** (Object) - Details about the output for this split. - **amount** (number) - The amount of output tokens. - **steps** (Array) - Details about individual steps within the split. - **dex** (string) - The DEX used in this step. - **status** (string) - The status of this specific step. #### Response Example ```json [ { "status": "completed", "input": { "amount": 5 }, "output": { "amount": 250.75 }, "steps": [ { "dex": "DeDust", "status": "completed" } ] } ] ``` ``` -------------------------------- ### Monitor Transaction Execution (TypeScript) Source: https://context7.com/swapcoffee/sdk/llms.txt Polls the Swap.Coffee API to track the status of transactions associated with a specific route ID until completion. This helper function allows for real-time updates on each split and step within the route. It takes the route ID, the RoutingApi instance, and an optional polling interval as input. The output provides detailed status and amount information for each transaction component, or an error if the transaction fails. ```typescript import { RoutingApi, waitForRouteResults } from '@swap-coffee/sdk'; const routingApi = new RoutingApi(); // After sending transactions, wait for results const routeId = transactions.data.route_id; try { const results = await waitForRouteResults( routeId, routingApi, 5000 // Poll every 5 seconds (default: 10000) ); // Check each split's status results.forEach((split, index) => { console.log(`Split ${index}:`); console.log(' Status:', split.status); // 'completed', 'failed', 'pending' console.log(' Input:', split.input?.amount); console.log(' Output:', split.output?.amount); split.steps.forEach((step, stepIndex) => { console.log(` Step ${stepIndex}: ${step.dex} - ${step.status}`); }); }); } catch (error) { console.error('Transaction failed:', error); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.