### Basic SDK Usage: Swap Example Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Demonstrates initializing the SDK, getting a trade quote, building the transaction, and sending it for execution. Ensure your API key is set in the environment variables. ```typescript import { SoroswapSDK, TradeType, SupportedProtocols } from '@soroswap/sdk'; // Initialize the SDK const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY! }); // Get a quote const quote = await soroswapClient.quote({ assetIn: 'CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA', assetOut: 'CDTKPWPLOURQA2SGTKTUQOWRCBZEORB4BWBOMJ3D3ZTQQSGE5F6JBQLV', amount: 10000000n, tradeType: TradeType.EXACT_IN, protocols: [SupportedProtocols.SOROSWAP] }); // Build the transaction const buildResponse = await soroswapClient.build({ quote, from: 'YOUR_WALLET_ADDRESS' }); // Sign and send const signedXdr = await yourSigner.sign(buildResponse.xdr); const result = await soroswapClient.send(signedXdr); ``` -------------------------------- ### Install Soroswap SDK Source: https://github.com/soroswap/sdk/blob/main/README.md Install the SDK using pnpm. Ensure you have pnpm installed. ```bash pnpm install soroswap-sdk ``` -------------------------------- ### Install Soroswap SDK Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Install the Soroswap SDK using npm, pnpm, or yarn. ```bash npm install @soroswap/sdk # or pnpm install @soroswap/sdk # or yarn add @soroswap/sdk ``` -------------------------------- ### Install Soroswap SDK and Stellar SDK Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Install the Soroswap SDK for DEX operations and the Stellar SDK if you plan to sign transactions server-side. ```bash pnpm add @soroswap/sdk # If signing server-side: pnpm add @stellar/stellar-sdk ``` -------------------------------- ### Example Integration Test Run Output Source: https://github.com/soroswap/sdk/blob/main/tests/integration/README.md An example of the console output when running Soroswap integration tests, showing test progress and completion status. ```bash $ pnpm run test:integration > soroswap-sdk@1.0.0 test:integration > jest --config=jest.integration.config.js [2024-01-15T10:30:00.000Z] 🚀 Starting integration tests against Soroswap API... [2024-01-15T10:30:00.000Z] 📧 Using email: test@example.com [2024-01-15T10:30:00.000Z] 🔒 Password: [HIDDEN] SoroswapSDK - Integration Tests Authentication Flow ✓ should authenticate and get user info (2345ms) Health and System Info ✓ should fetch health status (1234ms) ✓ should fetch testnet tokens (987ms) [... more tests ...] [2024-01-15T10:35:00.000Z] ✅ Integration tests completed Test Suites: 1 passed, 1 total Tests: 15 passed, 15 total Time: 45.123s ``` -------------------------------- ### Backend API Setup with Soroswap SDK Source: https://github.com/soroswap/sdk/blob/main/examples/frontend-widget/README.md Example of setting up an Express.js backend to handle quote requests and transaction submissions using the Soroswap SDK. Sensitive credentials are kept server-side. ```typescript import express from 'express'; import { SoroswapSDK } from 'soroswap-sdk'; const app = express(); const sdk = new SoroswapSDK({ email: process.env.SOROSWAP_EMAIL!, password: process.env.SOROSWAP_PASSWORD! }); app.post('/api/quote', async (req, res) => { try { const quote = await sdk.quote(req.body); // Only return necessary data to frontend res.json({ trade: quote.trade, priceImpact: quote.priceImpact, xdr: quote.xdr // Safe to send XDR to frontend for signing }); } catch (error) { res.status(500).json({ error: error.message }); } }); app.post('/api/send', async (req, res) => { try { const { signedXdr, network } = req.body; const result = await sdk.send(signedXdr, 100, network); res.json(result); } catch (error) { res.status(500).json({ error: error.message }); } }); ``` -------------------------------- ### Get Protocols Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Lists all available trading protocols supported by the SDK. ```APIDOC ## getProtocols() ### Description Lists all available trading protocols supported by the SDK. ### Method `getProtocols()` ### Parameters None ### Request Example ```typescript const protocols = await soroswapClient.getProtocols(); ``` ### Response #### Success Response An array of supported protocol identifiers. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Initialize SDK and Perform Swap Source: https://github.com/soroswap/sdk/blob/main/README.md Initialize the SDK with an API key and perform a swap by getting a quote, building the transaction, signing it, and sending it. Amounts must be BigInt. ```typescript import { SoroswapSDK, SupportedNetworks, SupportedProtocols, TradeType } from '@soroswap/sdk'; // Initialize the SDK const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here' }); // Get a quote for a swap const quote = await soroswapClient.quote({ assetIn: 'CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA', assetOut: 'CDTKPWPLOURQA2SGTKTUQOWRCBZEORB4BWBOMJ3D3ZTQQSGE5F6JBQLV', amount: 10000000n, // Note: Amount must be a BigInt tradeType: TradeType.EXACT_IN, protocols: [SupportedProtocols.SDEX, SupportedProtocols.SOROSWAP, SupportedProtocols.AQUA], }); // Build the transaction XDR from the quote const buildResponse = await soroswapClient.build({ quote, from: 'YOUR_WALLET_ADDRESS', to: 'RECIPIENT_ADDRESS' }); // Sign the transaction with your preferred signer const signedXdr = await yourSigner.sign(buildResponse.xdr); // Send the signed transaction const result = await soroswapClient.send(signedXdr); console.log('Transaction result:', result); ``` -------------------------------- ### Configure Soroswap SDK for Testnet Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Example of initializing the Soroswap SDK for the Testnet environment, specifying the network and potentially a different base URL. ```typescript const testnetClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, defaultNetwork: SupportedNetworks.TESTNET, baseUrl: 'https://testnet-api.soroswap.finance' // If available }); ``` -------------------------------- ### Next.js API Route Example for Quote Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Example of a Next.js API route to proxy SDK quote calls, handling request parsing and error responses. ```typescript // src/app/api/quote/route.ts import { NextResponse } from "next/server"; import { soroswapClient } from "@/shared/lib/server/soroswapClient"; export async function POST(request: Request) { try { const body = await request.json(); const quote = await soroswapClient.quote(body); return NextResponse.json(quote); } catch (error: unknown) { const statusCode = typeof error === "object" && error !== null && "statusCode" in error ? (error as { statusCode: number }).statusCode : 500; return NextResponse.json(error, { status: statusCode }); } } ``` -------------------------------- ### get() Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/http-client.md Performs an HTTP GET request to a specified endpoint relative to the client's baseURL. It includes API key authentication and returns the parsed JSON response. ```APIDOC ## get() ### Description Performs an HTTP GET request to the specified endpoint with API key authentication. The response body is automatically parsed and returned. ### Method GET ### Endpoint /{url} ### Parameters #### Path Parameters - **url** (string) - Required - Endpoint URL (relative to baseURL) #### Query Parameters - **config** (AxiosRequestConfig) - Optional - Optional Axios request configuration for custom headers, params, etc. ### Return Type Promise resolving to the parsed JSON response of type T ### Response #### Success Response (200) - **T** - The parsed JSON response body ``` -------------------------------- ### Get Price Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Fetches the current prices for a list of assets on a specific network. ```APIDOC ## getPrice() ### Description Fetches the current prices for a list of assets on a specific network. ### Method `getPrice(assets: string[], network: SupportedNetworks)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const prices = await soroswapClient.getPrice( ['TOKEN_A', 'TOKEN_B'], SupportedNetworks.MAINNET ); ``` ### Response #### Success Response An object containing price data for the requested assets. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Configure Soroswap SDK for Mainnet Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Example of initializing the Soroswap SDK specifically for the Mainnet environment, including API key, network, and base URL. ```typescript const mainnetClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, defaultNetwork: SupportedNetworks.MAINNET, baseUrl: 'https://api.soroswap.finance' }); ``` -------------------------------- ### Get Balances Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Retrieves all token balances for a given wallet address. ```APIDOC ## getBalances() ### Description Retrieves all token balances for a given wallet address. ### Method `getBalances(walletAddress: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const allBalances = await soroswapClient.getBalances(walletAddress); ``` ### Response #### Success Response An object containing token balances. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Get Wallet Balances Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Fetch all wallet balances or the balance for a single token. ```typescript // All balances const balances = await sdk.getBalances("GWALLET...", SupportedNetworks.MAINNET); // balances.balances[].asset.code, .amount, .rawAmount, .available // Single token balance const balance = await sdk.getTokenBalance( "GWALLET...", "TOKEN_CONTRACT", // Contract ID (C...) or CODE:ISSUER format SupportedNetworks.MAINNET ); ``` -------------------------------- ### Get Available Protocols Source: https://github.com/soroswap/sdk/blob/main/README.md Retrieves a list of supported trading protocols for a given network. ```APIDOC ## Get Available Protocols ### Description Retrieves a list of supported trading protocols for a given network. ### Method `getProtocols(network: SupportedNetworks)` ### Parameters #### Path Parameters - **network** (SupportedNetworks) - Required - The network to query protocols for (e.g., `SupportedNetworks.MAINNET`). ### Response #### Success Response - An array of strings representing the supported protocol identifiers (e.g., `['sdex', 'soroswap', 'phoenix', 'aqua']`). ### Request Example ```typescript const protocols = await soroswapClient.getProtocols(SupportedNetworks.MAINNET); // Returns: ['sdex', 'soroswap', 'phoenix', 'aqua'] ``` ``` -------------------------------- ### Get Protocols Source: https://github.com/soroswap/sdk/blob/main/llms.txt Retrieves a list of available trading protocols supported by Soroswap. ```APIDOC ## Get Protocols ### Description Retrieve available trading protocols. ### Method `getProtocols(network?: SupportedNetworks)` ### Parameters - **network** (SupportedNetworks) - Optional - The network to query (MAINNET or TESTNET). ### Returns `string[]` - An array of protocol names (e.g., `['sdex', 'soroswap', 'phoenix', 'aqua']`). ``` -------------------------------- ### Get Asset List Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Fetches a list of supported assets based on a specified asset list type. ```APIDOC ## getAssetList() ### Description Fetches a list of supported assets based on a specified asset list type. ### Method `getAssetList(assetListType: SupportedAssetLists)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const assets = await soroswapClient.getAssetList(SupportedAssetLists.SOROSWAP); ``` ### Response #### Success Response An array of asset identifiers. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Get Token Prices Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Fetch the price for a single token or multiple tokens on the mainnet. ```typescript const prices = await sdk.getPrice("TOKEN_CONTRACT", SupportedNetworks.MAINNET); // prices[0].price: number | null // prices[0].asset: string // prices[0].timestamp: string const batchPrices = await sdk.getPrice( ["TOKEN_A", "TOKEN_B", "TOKEN_C"], SupportedNetworks.MAINNET ); ``` -------------------------------- ### Get Asset Lists with Soroswap SDK Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Retrieve metadata for all supported asset lists or a specific list. Logs the metadata or the number of assets and their details. ```typescript const listMetadata = await soroswapClient.getAssetList(); console.log(listMetadata); // [{ name: 'soroswap', url: '...' }, ...] const soroswapAssets = await soroswapClient.getAssetList(SupportedAssetLists.SOROSWAP); console.log(soroswapAssets.assets.length); // Number of assets soroswapAssets.assets.forEach(asset => { console.log(`${asset.name} (${asset.symbol}): ${asset.contract}`); }); ``` -------------------------------- ### Get All Pools by Supported Protocols Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Fetches all available liquidity pools for a given network, filtering by specified protocols. Useful for an overview of available liquidity. ```typescript const pools = await soroswapClient.getPools( SupportedNetworks.MAINNET, [SupportedProtocols.SOROSWAP, SupportedProtocols.AQUA] ); pools.forEach(pool => { console.log(`Pool: ${pool.tokenA} / ${pool.tokenB}`); console.log(`Protocol: ${pool.protocol}`); console.log(`Reserve A: ${pool.reserveA}, Reserve B: ${pool.reserveB}`); }); ``` -------------------------------- ### Docker Environment Soroswap SDK Configuration Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Configure the Soroswap SDK for Docker environments using environment variables. This example shows how to initialize the SDK and set corresponding Docker environment variables. ```typescript // src/soroswap-client.ts import { SoroswapSDK, SupportedNetworks } from '@soroswap/sdk'; export function initializeSoroswapSDK() { const config = { apiKey: process.env.SOROSWAP_API_KEY!, baseUrl: process.env.SOROSWAP_API_URL || 'https://api.soroswap.finance', defaultNetwork: (process.env.SOROSWAP_NETWORK || 'mainnet') === 'testnet' ? SupportedNetworks.TESTNET : SupportedNetworks.MAINNET, timeout: parseInt(process.env.SOROSWAP_TIMEOUT || '30000', 10) }; return new SoroswapSDK(config); } export const soroswapClient = initializeSoroswapSDK(); ``` ```dockerfile # Dockerfile ENV SOROSWAP_API_KEY=sk_prod_key ENV SOROSWAP_API_URL=https://api.soroswap.finance ENV SOROSWAP_NETWORK=mainnet ENV SOROSWAP_TIMEOUT=30000 ``` -------------------------------- ### Get Asset Lists Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Retrieve all available asset list metadata or a specific asset list with full token information. ```typescript import { SupportedAssetLists } from "@soroswap/sdk"; // Get all available asset list metadata const lists = await sdk.getAssetList(); // Get a specific asset list with full token info const soroswapTokens = await sdk.getAssetList(SupportedAssetLists.SOROSWAP); ``` -------------------------------- ### Get Available Trading Protocols Source: https://github.com/soroswap/sdk/blob/main/README.md Fetch a list of available trading protocols for a specified network. This helps in selecting which protocols to include when requesting quotes. ```typescript const protocols = await soroswapClient.getProtocols(SupportedNetworks.MAINNET); // Returns: ['sdex', 'soroswap', 'phoenix', 'aqua'] ``` -------------------------------- ### React Frontend Integration for Quote Requests Source: https://github.com/soroswap/sdk/blob/main/examples/frontend-widget/README.md Example of a React component making a POST request to the backend API to fetch a trade quote. It demonstrates state management for quote data. ```jsx import React, { useState } from 'react'; const SwapWidget = () => { const [quote, setQuote] = useState(null); const getQuote = async (params) => { const response = await fetch('/api/quote', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(params) }); const quoteData = await response.json(); setQuote(quoteData); }; // ... rest of component }; ``` -------------------------------- ### Get User Positions Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Retrieves all active liquidity positions for a given wallet address. It returns details about the user's LP token balance, share percentage, and equivalent token amounts. ```typescript const positions = await soroswapClient.getUserPositions( 'GBSWZ4YYAKDJBZLTJ3MYZV4K2PXL2UNJL6HVZPZ6NVYWQ33T5JJKZPJ', SupportedNetworks.MAINNET ); positions.forEach(position => { console.log(`Pool: ${position.poolInformation.tokenA.symbol}/${position.poolInformation.tokenB.symbol}`); console.log(`User shares: ${position.userShares}%`); console.log(`Token A value: ${position.tokenAAmountEquivalent}`); }); ``` -------------------------------- ### Get All Pools for Specific Protocols Source: https://github.com/soroswap/sdk/blob/main/README.md Fetches all pools associated with specified protocols and asset lists. Useful for getting an overview of available trading pairs. ```typescript // Get all pools for specific protocols const pools = await soroswapClient.getPools( SupportedNetworks.MAINNET, [SupportedProtocols.SOROSWAP, SupportedProtocols.AQUA], [SupportedAssetLists.SOROSWAP] // Optional asset list filter ); ``` -------------------------------- ### Initialize and Use HTTP Client Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Instantiate the HttpClient with your API key and URL. Use it to fetch pools or create quotes. ```typescript import { HttpClient } from '@soroswap/sdk'; const httpClient = new HttpClient( 'https://api.soroswap.finance', 'sk_your_api_key', 30000 ); const pools = await httpClient.get('/pools?network=mainnet'); const quote = await httpClient.post('/quote', quoteData); ``` -------------------------------- ### Initialize SDK with API Key Authentication Source: https://github.com/soroswap/sdk/blob/main/README.md Initialize the SoroswapSDK using only an API key for authentication. This is the simplest method for initializing the client. ```typescript // Simply initialize with your API key const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here' }); ``` -------------------------------- ### Basic SDK Initialization Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the SDK with a required API key. Uses default settings for network, base URL, and timeout. ```typescript import { SoroswapSDK } from '@soroswap/sdk'; const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here' }); // Uses defaults: MAINNET, https://api.soroswap.finance, 30s timeout ``` -------------------------------- ### Get Soroswap Pools Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Retrieves all pools matching the specified network and protocols. Use this to discover available liquidity pools or to get pool information for analysis and liquidity operations. ```typescript const pools = await soroswapClient.getPools( SupportedNetworks.MAINNET, ['soroswap', 'aqua'] ); ``` -------------------------------- ### Execute a Swap: Step-by-Step Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md A breakdown of the swap execution process: first obtaining a quote, then building the transaction with the quote and sender address, and finally signing and sending the transaction. ```typescript // 1. Get quote const quote = await soroswapClient.quote({ assetIn: 'TOKEN_A', assetOut: 'TOKEN_B', amount: 1000000n, tradeType: TradeType.EXACT_IN, protocols: [SupportedProtocols.SOROSWAP] }); // 2. Build transaction const txn = await soroswapClient.build({ quote, from: address }); // 3. Sign and send const signed = await signer.sign(txn.xdr); const result = await soroswapClient.send(signed); ``` -------------------------------- ### SDK Initialization Source: https://github.com/soroswap/sdk/blob/main/README.md Initializes the Soroswap SDK with configuration options including API key, base URL, default network, and timeout. ```APIDOC ## SDK Initialization ### Description Initializes the Soroswap SDK with configuration options including API key, base URL, default network, and timeout. ### Configuration Options ```typescript interface SoroswapSDKConfig { apiKey: string; // Your Soroswap API key (starts with 'sk_') baseUrl?: string; // Custom API base URL (defaults to 'https://api.soroswap.finance') defaultNetwork?: SupportedNetworks; // SupportedNetworks.MAINNET | SupportedNetworks.TESTNET timeout?: number; // Request timeout in ms (defaults to 30000) } ``` ### Example Usage ```typescript import { SoroswapSDK } from '@soroswap/sdk'; const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here', baseUrl: 'https://api.soroswap.finance', defaultNetwork: SupportedNetworks.MAINNET, timeout: 30000 }); ``` ``` -------------------------------- ### Perform HTTP GET Request Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/http-client.md Performs an HTTP GET request to a specified endpoint. The response is automatically parsed. Optional Axios request configuration can be provided for custom headers or parameters. ```typescript // Get pool information const pools = await httpClient.get('/pools?network=mainnet&protocol=soroswap'); // Get contract address with custom config const contract = await httpClient.get<{address: string}> ('/api/mainnet/router', { timeout: 5000 } ); ``` -------------------------------- ### Initialize SDK with SOROSWAP_API_URL Environment Variable Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the Soroswap SDK, allowing the base URL to be dynamically set from the SOROSWAP_API_URL environment variable. Falls back to localhost if the variable is not set. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, baseUrl: process.env.SOROSWAP_API_URL }); ``` -------------------------------- ### Get Asset Prices Source: https://github.com/soroswap/sdk/blob/main/llms.txt Retrieves current prices for one or more assets. ```APIDOC ## Get Asset Prices ### Description Retrieves current asset prices. ### Method `getPrice(assets: string | string[], network?: SupportedNetworks)` ### Parameters #### Path Parameters - **assets** (string | string[]) - Required - Single asset or array of asset addresses. - **network** (SupportedNetworks) - Optional - Target network. ### Returns `PriceData[]` - Array of price information. ``` -------------------------------- ### Initialize Soroswap SDK Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Initialize the Soroswap SDK with your API key and optional configuration for base URL, network, and timeout. The API key is required and should be kept secure. ```typescript import { SoroswapSDK, SupportedNetworks } from "@soroswap/sdk"; const sdk = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY as string, // Required: starts with 'sk_' baseUrl: process.env.SOROSWAP_API_URL, // Optional: defaults to 'https://api.soroswap.finance' defaultNetwork: SupportedNetworks.MAINNET, // Optional: defaults to MAINNET timeout: 30000, // Optional: defaults to 30000ms }); ``` -------------------------------- ### Get Contract Address Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Retrieves the contract address for a given asset or service. ```APIDOC ## getContractAddress() ### Description Retrieves the contract address for a given asset or service. ### Method `getContractAddress(assetOrService: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const address = await soroswapClient.getContractAddress('USDC'); ``` ### Response #### Success Response The contract address (string). #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Initialize SDK with SOROSWAP_API_KEY Environment Variable Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the Soroswap SDK using the API key stored in the SOROSWAP_API_KEY environment variable. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, }); ``` -------------------------------- ### Get Pools Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Retrieves a list of available pools for specified protocols and network. ```APIDOC ## getPools() ### Description Retrieves a list of available pools for specified protocols and network. ### Method `getPools(network: SupportedNetworks, protocols: SupportedProtocols[])` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const pools = await soroswapClient.getPools( SupportedNetworks.MAINNET, [SupportedProtocols.SOROSWAP] ); ``` ### Response #### Success Response An array of pool objects. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Initialize SDK with Environment Variables Source: https://github.com/soroswap/sdk/blob/main/README.md Initialize the SDK using environment variables for API key, base URL, and network. This is a more secure approach for sensitive credentials. Ensure environment variables are properly set. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, baseUrl: process.env.SOROSWAP_API_URL, // Optional: for localhost or custom API defaultNetwork: process.env.NODE_ENV === 'production' ? SupportedNetworks.MAINNET : SupportedNetworks.TESTNET }); // Example for local development: const localClient = new SoroswapSDK({ apiKey: 'sk_local_api_key', baseUrl: 'http://localhost:3000', defaultNetwork: SupportedNetworks.TESTNET }); ``` -------------------------------- ### SoroswapSDK Constructor Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Initializes a new SoroswapSDK instance with the provided configuration. The SDK sets up an internal HTTP client with the given API key for all subsequent API calls. If no baseUrl is provided, defaults to the public Soroswap API endpoint. ```APIDOC ## SoroswapSDK Constructor ### Description Initializes a new SoroswapSDK instance with the provided configuration. The SDK sets up an internal HTTP client with the given API key for all subsequent API calls. If no baseUrl is provided, defaults to the public Soroswap API endpoint. ### Parameters - **config** (SoroswapSDKConfig) - Required - SDK configuration object - **config.apiKey** (string) - Required - API key for authentication (must start with 'sk_') - **config.baseUrl** (string) - Optional - Custom API base URL for localhost or custom deployments (defaults to 'https://api.soroswap.finance') - **config.defaultNetwork** (SupportedNetworks) - Optional - Default network for API calls (TESTNET or MAINNET) (defaults to SupportedNetworks.MAINNET) - **config.timeout** (number) - Optional - HTTP request timeout in milliseconds (defaults to 30000) ### Example ```typescript import { SoroswapSDK, SupportedNetworks } from '@soroswap/sdk'; const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, baseUrl: 'https://api.soroswap.finance', defaultNetwork: SupportedNetworks.MAINNET, timeout: 30000 }); ``` ``` -------------------------------- ### Get Contract Addresses Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Fetch the contract addresses for the router, factory, or aggregator. ```typescript const router = await sdk.getContractAddress(SupportedNetworks.MAINNET, "router"); const factory = await sdk.getContractAddress(SupportedNetworks.MAINNET, "factory"); const aggregator = await sdk.getContractAddress(SupportedNetworks.MAINNET, "aggregator"); ``` -------------------------------- ### Initialize SDK with NODE_ENV for Network Selection Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the Soroswap SDK, dynamically selecting the network (MAINNET or TESTNET) based on the NODE_ENV environment variable. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, defaultNetwork: process.env.NODE_ENV === 'production' ? SupportedNetworks.MAINNET : SupportedNetworks.TESTNET }); ``` -------------------------------- ### Get Token Balance Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Retrieves the balance for a specific token for a given wallet address. ```APIDOC ## getTokenBalance() ### Description Retrieves the balance for a specific token for a given wallet address. ### Method `getTokenBalance(walletAddress: string, tokenAddress: string)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript const usdcBalance = await soroswapClient.getTokenBalance( walletAddress, 'USDC_CONTRACT_ADDRESS' ); ``` ### Response #### Success Response The balance of the specified token. #### Response Example (Response structure not specified in source) ``` -------------------------------- ### Full Soroswap SDK Configuration Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initialize the SoroswapSDK with all available configuration options, including API key, base URL, default network, and timeout. ```typescript import { SoroswapSDK, SupportedNetworks } from '@soroswap/sdk'; const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here', baseUrl: 'https://api.soroswap.finance', defaultNetwork: SupportedNetworks.MAINNET, timeout: 30000 }); ``` -------------------------------- ### Get Specific Asset List Source: https://github.com/soroswap/sdk/blob/main/README.md Retrieves a specific asset list, such as the one for Soroswap. ```typescript // Get specific asset list const soroswapAssets = await soroswapClient.getAssetList(SupportedAssetLists.SOROSWAP); ``` -------------------------------- ### Full Swap Flow: Quote, Build, Sign, Send Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Demonstrates the complete process of executing a swap using the Soroswap SDK, from obtaining a quote to sending the signed transaction. ```typescript import { SoroswapSDK, QuoteRequest, BuildQuoteRequest, TradeType, SupportedNetworks, SupportedProtocols, } from "@soroswap/sdk"; // 1. Get a quote const quoteRequest: QuoteRequest = { assetIn: "CCW67TSZV3SSS2HXMBQ5JFGCKJNXKZM7UQUWUZPUTHXSTZLEO7SJMI75", // USDC contract assetOut: "CAS3J7GYLGXMF6TDJBBYYSE3HQ6BBSMLNUQ34T6TZMYMW2EVH34XOWMA", // XLM contract amount: 1000000000n, // 100 USDC (7 decimals) - MUST be BigInt tradeType: TradeType.EXACT_IN, // or TradeType.EXACT_OUT protocols: [SupportedProtocols.SOROSWAP, SupportedProtocols.AQUA], slippageBps: 50, // 0.5% slippage in basis points maxHops: 2, // Optional: max routing hops }; const quote = await sdk.quote(quoteRequest, SupportedNetworks.MAINNET); // quote.amountIn, quote.amountOut, quote.priceImpactPct, quote.routePlan // 2. Build transaction XDR from quote const buildRequest: BuildQuoteRequest = { quote, from: "GXXXXXXX...", // Sender wallet address to: "GXXXXXXX...", // Optional: recipient (defaults to 'from') }; const buildResponse = await sdk.build(buildRequest, SupportedNetworks.MAINNET); // buildResponse.xdr - unsigned transaction XDR // 3. Sign the XDR (see Transaction Signing section above) const signedXdr = signTransaction(buildResponse.xdr); // 4. Send signed transaction const result = await sdk.send(signedXdr, false, SupportedNetworks.MAINNET); if (result.success && result.result?.type === "swap") { console.log(`Swapped ${result.result.amountIn} for ${result.result.amountOut}`); } ``` -------------------------------- ### Minimal Soroswap SDK Configuration Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initialize the SoroswapSDK with only the required API key. This is the most basic configuration. ```typescript import { SoroswapSDK } from '@soroswap/sdk'; const soroswapClient = new SoroswapSDK({ apiKey: 'sk_your_api_key_here' }); ``` -------------------------------- ### Get Pools Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Retrieve all pools for specific protocols or a pool for a specific token pair. ```typescript // All pools for specific protocols const pools = await sdk.getPools( SupportedNetworks.MAINNET, [SupportedProtocols.SOROSWAP, SupportedProtocols.AQUA] ); // Pool for specific token pair const tokenPools = await sdk.getPoolByTokens( "TOKEN_A", "TOKEN_B", SupportedNetworks.MAINNET, [SupportedProtocols.SOROSWAP] ); ``` -------------------------------- ### Configure SoroSwap SDK with Environment Variables Source: https://github.com/soroswap/sdk/blob/main/_autodocs/README.md Set environment variables for API key, URL, and timeout. These are crucial for secure and proper SDK configuration. ```bash # Required SOROSWAP_API_KEY=sk_your_api_key_here # Optional SOROSWAP_API_URL=https://api.soroswap.finance NODE_ENV=production SOROSWAP_TIMEOUT=30000 ``` -------------------------------- ### Production SDK Initialization Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the SDK for production use with an API key from environment variables, specifying the mainnet and a default timeout. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, defaultNetwork: SupportedNetworks.MAINNET, timeout: 30000 }); ``` -------------------------------- ### Development/Testing SDK Initialization Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the SDK for development or testing environments. It uses an API key and a base URL from environment variables, defaulting to localhost if not specified. It also sets the testnet and a longer timeout. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY!, baseUrl: process.env.SOROSWAP_API_URL || 'http://localhost:3000', defaultNetwork: SupportedNetworks.TESTNET, timeout: 60000 // Allow more time for local development }); ``` -------------------------------- ### Get Contract Address Source: https://github.com/soroswap/sdk/blob/main/llms.txt Retrieves the contract address for a specific network and contract name. ```APIDOC ## Get Contract Address ### Description Gets contract addresses for a specific network. ### Method `getContractAddress(network: SupportedNetworks, contractName: 'factory' | 'router' | 'aggregator')` ### Parameters #### Path Parameters - **network** (SupportedNetworks) - Required - Target network. - **contractName** (string) - Required - Contract type ('factory', 'router', or 'aggregator'). ### Returns `{address: string}` - Contract address. ``` -------------------------------- ### Get Contract Addresses Source: https://github.com/soroswap/sdk/blob/main/README.md Retrieves the contract addresses for the factory, router, and aggregator on a specified network. ```APIDOC ## Get Contract Addresses ### Description Retrieves the on-chain contract addresses for key Soroswap components like the factory, router, and aggregator for a given network. ### Method `getContractAddress` ### Parameters - `network` (SupportedNetworks) - The network to query. - `contractName` (string) - The name of the contract ('factory', 'router', or 'aggregator'). ### Request Example ```typescript const factoryAddress = await soroswapClient.getContractAddress(SupportedNetworks.MAINNET, 'factory'); const routerAddress = await soroswapClient.getContractAddress(SupportedNetworks.MAINNET, 'router'); const aggregatorAddress = await soroswapClient.getContractAddress(SupportedNetworks.MAINNET, 'aggregator'); ``` ``` -------------------------------- ### Server-Side SDK Initialization Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initialize the Soroswap SDK on the backend using a secure API key from environment variables. This prevents exposing keys to the frontend. ```typescript // Backend API endpoint app.post('/api/quote', async (req, res) => { const soroswapClient = new SoroswapSDK({ apiKey: process.env.SOROSWAP_API_KEY! // Secure server-side only }); const quote = await soroswapClient.quote(req.body); res.json(quote); }); ``` -------------------------------- ### Local Development SDK Initialization with Custom API Source: https://github.com/soroswap/sdk/blob/main/_autodocs/configuration.md Initializes the SDK for local development using a specific local API URL and testnet configuration. ```typescript const soroswapClient = new SoroswapSDK({ apiKey: 'sk_local_test_key', baseUrl: 'http://localhost:3000', defaultNetwork: SupportedNetworks.TESTNET, timeout: 60000 }); ``` -------------------------------- ### Get Asset Lists Source: https://github.com/soroswap/sdk/blob/main/llms.txt Fetches asset list metadata or a specific asset list by name. ```APIDOC ## Get Asset Lists ### Description Gets asset list metadata or a specific asset list. ### Method `getAssetList(name?: SupportedAssetLists)` ### Parameters #### Path Parameters - **name** (SupportedAssetLists) - Optional - Specific asset list name. ### Returns `AssetList[]` or `AssetListInfo[]` depending on parameters. ``` -------------------------------- ### Initialize HttpClient Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/http-client.md Creates a new HttpClient instance. Use this for direct HTTP access. For most use cases, the SoroswapSDK class is recommended as it manages the HttpClient internally. ```typescript import { HttpClient } from '@soroswap/sdk'; const httpClient = new HttpClient( 'https://api.soroswap.finance', 'sk_your_api_key_here', 30000 ); // For most use cases, use SoroswapSDK instead which manages this internally const sdk = new SoroswapSDK({ apiKey: 'sk_your_api_key_here' }); ``` -------------------------------- ### Get User Positions Source: https://github.com/soroswap/sdk/blob/main/llms.txt Retrieves a user's liquidity positions based on their wallet address. ```APIDOC ## Get User Positions ### Description Retrieves a user's liquidity positions. ### Method `getUserPositions(address: string, network?: SupportedNetworks)` ### Parameters #### Path Parameters - **address** (string) - Required - User wallet address. - **network** (SupportedNetworks) - Optional - Target network. ### Returns `UserPosition[]` - Array of user positions. ``` -------------------------------- ### build() Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/soroswap-sdk.md Constructs a transaction for a swap operation based on a previous quote and wallet information. It allows specifying sender, recipient, and referral details. ```APIDOC ## build() ### Description Builds a transaction for a swap operation based on a quote. This method takes the quote object and optional wallet/recipient information to construct the necessary transaction details for execution. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **buildQuoteRequest** (BuildQuoteRequest) - Required - Build request with quote and wallet information - **buildQuoteRequest.quote** (QuoteResponse) - Required - Quote object returned from quote() method - **buildQuoteRequest.from** (string) - Optional - Wallet address sending the tokens (required for proper transaction construction) - **buildQuoteRequest.to** (string) - Optional - Recipient address for output tokens (defaults to 'from' if not specified) - **buildQuoteRequest.referralId** (string) - Optional - Wallet address to receive referral fees (required if feeBps was set in the quote) - **buildQuoteRequest.sponsor** (string) - Optional - Optional fee sponsor address for fee-bump transactions - **buildQuoteRequest.signedUserXdr** (string) - Optional - Optional pre-signed user XDR for advanced transaction construction - **network** (SupportedNetworks) - Optional - Override the default network ### Request Example None provided in source. ### Response #### Success Response (200) - **BuildQuoteResponse** - The response type is not explicitly detailed in the source, but it is expected to contain transaction construction details. #### Response Example None provided in source. ``` -------------------------------- ### Get All Available Asset Lists Metadata Source: https://github.com/soroswap/sdk/blob/main/README.md Fetches metadata for all asset lists supported by the Soroswap protocol. ```typescript // Get all available asset lists metadata const assetListsInfo = await soroswapClient.getAssetList(); ``` -------------------------------- ### SDK Configuration Interface Source: https://github.com/soroswap/sdk/blob/main/README.md Defines the configuration options for initializing the SoroswapSDK, including API key, base URL, default network, and timeout. The API key is mandatory. ```typescript interface SoroswapSDKConfig { apiKey: string; // Your Soroswap API key (starts with 'sk_') baseUrl?: string; // Custom API base URL (defaults to 'https://api.soroswap.finance') defaultNetwork?: SupportedNetworks; // SupportedNetworks.MAINNET | SupportedNetworks.TESTNET timeout?: number; // Request timeout in ms (defaults to 30000) } ``` -------------------------------- ### Get Multiple Asset Prices Source: https://github.com/soroswap/sdk/blob/main/README.md Retrieves the current market prices for a list of token contract addresses. ```typescript // Multiple asset prices const prices = await soroswapClient.getPrice([ 'TOKEN_A_CONTRACT', 'TOKEN_B_CONTRACT' ], SupportedNetworks.MAINNET); ``` -------------------------------- ### Build Project with pnpm Source: https://github.com/soroswap/sdk/blob/main/README.md Executes the build script for the project using the pnpm package manager. ```bash pnpm run build ``` -------------------------------- ### Initialize Swap Widget Source: https://github.com/soroswap/sdk/blob/main/examples/frontend-widget/swap-widget.html Basic initialization of the Swap Widget. Ensure the necessary DOM element exists before calling this. ```javascript const widget = new SwapWidget({ target: document.getElementById('swap-widget-container'), props: { tokenList: [ { address: '0x...', symbol: 'ETH', decimals: 18 }, { address: '0x...', symbol: 'USDC', decimals: 6 } ], defaultSlippage: 0.5, onSwapSuccess: (txHash) => { console.log('Swap successful:', txHash); } } }); ``` -------------------------------- ### Get Pool by Tokens Source: https://github.com/soroswap/sdk/blob/main/llms.txt Fetches a specific liquidity pool for a given pair of token contract addresses. ```APIDOC ## Get Pool by Tokens ### Description Get specific pool for token pair. ### Method `getPoolByTokens(assetA: string, assetB: string, network: SupportedNetworks, protocols: string[])` ### Parameters - **assetA** (string) - Required - First token contract address. - **assetB** (string) - Required - Second token contract address. - **network** (SupportedNetworks) - Required - Target network (MAINNET/TESTNET). - **protocols** (string[]) - Required - Array of protocol names. ### Returns `Pool[]` - Array of matching pools. ``` -------------------------------- ### Get Pools Source: https://github.com/soroswap/sdk/blob/main/llms.txt Retrieves a list of liquidity pools for specified protocols and optionally filters by asset list. ```APIDOC ## Get Pools ### Description Retrieve pools for specific protocols. ### Method `getPools(network: SupportedNetworks, protocols: string[], assetList?: (SupportedAssetLists | string)[])` ### Parameters - **network** (SupportedNetworks) - Required - Target network (MAINNET/TESTNET). - **protocols** (string[]) - Required - Array of protocol names. - **assetList** (Array) - Optional - Optional asset list filter. ### Returns `Pool[]` - Array of pool information. ``` -------------------------------- ### Get Single Asset Price Source: https://github.com/soroswap/sdk/blob/main/README.md Fetches the current market price for a single specified token contract address. ```typescript // Single asset price const prices = await soroswapClient.getPrice( 'TOKEN_CONTRACT_ADDRESS', SupportedNetworks.MAINNET ); ``` -------------------------------- ### Lint Project with pnpm Source: https://github.com/soroswap/sdk/blob/main/README.md Runs the linter to check for code style issues. Use the fix flag to automatically resolve some issues. ```bash pnpm run lint pnpm run lint:fix ``` -------------------------------- ### Get User Positions Source: https://github.com/soroswap/sdk/blob/main/README.md Retrieves all liquidity positions held by a specific user wallet address on a given network. ```typescript const positions = await soroswapClient.getUserPositions( 'USER_WALLET_ADDRESS', SupportedNetworks.MAINNET ); ``` -------------------------------- ### HttpClient Constructor Source: https://github.com/soroswap/sdk/blob/main/_autodocs/api-reference/http-client.md Creates a new HttpClient instance. This client is configured with a base URL and an API key for authentication, and it automatically handles BigInt serialization for requests. ```APIDOC ## HttpClient Constructor ### Description Creates a new HTTP client instance configured with the specified API endpoint and authentication key. The client automatically includes the Authorization header with Bearer token on all requests and handles BigInt serialization for JSON payloads. ### Parameters #### Path Parameters - **baseURL** (string) - Required - API base URL (e.g., 'https://api.soroswap.finance') - **apiKey** (string) - Required - API key for Bearer token authentication - **timeout** (number) - Optional - Request timeout in milliseconds (Default: 30000) ``` -------------------------------- ### Get User Liquidity Positions Source: https://github.com/soroswap/sdk/blob/main/soroswap-sdk-skill.md Retrieves all liquidity positions for a given Stellar wallet address across all pools. ```typescript const positions = await sdk.getUserPositions("GWALLET...", SupportedNetworks.MAINNET); for (const pos of positions) { console.log(`Pool: ${pos.poolInformation.address}`); console.log(`Position: ${pos.userPosition}`); // LP token amount (raw) console.log(`Share of pool: ${pos.userShares}`); // Percentage (0-100) console.log(`Token A equivalent: ${pos.tokenAAmountEquivalent}`); console.log(`Token B equivalent: ${pos.tokenBAmountEquivalent}`); } ```