### Install 0xSquid SDK Source: https://context7.com/0xsquid/squid-sdk/llms.txt Install the SDK using npm or yarn. ```bash npm install @0xsquid/sdk # or yarn add @0xsquid/sdk ``` -------------------------------- ### Approve Tokens for Cross-Chain Transactions Source: https://github.com/0xsquid/squid-sdk/blob/main-v2/docs/integration.md Run the approval script to approve tokens before initiating cross-chain transactions. Ensure dependencies are installed and .env is configured. ```typescript yarn ts-node approve.ts ``` -------------------------------- ### Poll Cross-Chain Transaction Status Source: https://context7.com/0xsquid/squid-sdk/llms.txt Queries the `/v2/status` endpoint to get the live status of a submitted cross-chain transaction. This should be polled after `executeRoute` until the transaction status is finalized as 'success' or 'failed'. ```typescript const status = await squid.getStatus({ transactionId: "0xabc123...", // source chain tx hash quoteId: route.estimate.feeCosts[0]?.token || "", // from route estimate requestId: requestId, // from getRoute response integratorId: "my-app-123abc", }); console.log("Status:", status.squidTransactionStatus); console.log("GMP status:", status.gasStatus); console.log("Axelar URL:", status.axelarTransactionUrl); // Status: "success" // GMP status: "gas_paid_enough_gas" // Axelar URL: https://axelarscan.io/gmp/0xabc123... ``` -------------------------------- ### Initialize Squid SDK and Fetch Data Source: https://context7.com/0xsquid/squid-sdk/llms.txt Initialize the Squid SDK and fetch chain and token data by calling the /v2/sdk-info endpoint. This must be awaited before using methods like getRoute or executeRoute. Error handling for initialization failure is included. ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ integratorId: "my-app-123abc" }); try { await squid.init(); console.log("SDK ready, axelarscan:", squid.axelarscanURL); } catch (err) { console.error("Initialization failed:", err.message); // "SDK initialization failed" } ``` -------------------------------- ### Initialize the SDK client Source: https://context7.com/0xsquid/squid-sdk/llms.txt Creates a new Squid instance with configuration options including base URL, integrator ID, execution settings, and timeout. The `init()` method must be called to populate chain and token data before using other SDK methods. ```APIDOC ## `new Squid(config)` — Initialize the SDK client Creates a new `Squid` instance. An `integratorId` (issued by the Squid team) is required. Optionally supply a custom `baseUrl` for staging/testnet environments, an `executionSettings` object to control approval behaviour, and a request `timeout` in milliseconds. ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ baseUrl: "https://apiplus.squidrouter.com/", // mainnet endpoint integratorId: "my-app-123abc", // required executionSettings: { infiniteApproval: false, // approve exact amounts only }, timeout: 10_000, // 10 s HTTP timeout }); // Must be called before any other method await squid.init(); console.log("Chains supported:", squid.chains.length); console.log("Tokens supported:", squid.tokens.length); console.log("Maintenance mode:", squid.isInMaintenanceMode); // Chains supported: 42 // Tokens supported: 630 // Maintenance mode: false ``` ``` -------------------------------- ### Perform EVM Cross-Chain Swap with 0xSquid SDK Source: https://context7.com/0xsquid/squid-sdk/llms.txt Combines initialization, route fetching, approval, execution, and status polling for an EVM-to-EVM swap. Requires setting up a provider, signer, and initializing the Squid SDK. ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; async function crossChainSwap() { // 1. Setup provider & signer const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const address = await signer.getAddress(); // 2. Initialize SDK const squid = new Squid({ baseUrl: "https://apiplus.squidrouter.com/", integratorId: process.env.INTEGRATOR_ID!, }); await squid.init(); // 3. Get route: swap 50 USDC on Ethereum → USDT on Polygon const { route, requestId } = await squid.getRoute({ fromChain: "1", toChain: "137", fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC toToken: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", // USDT fromAmount: "50000000", // 50 USDC (6 decimals) fromAddress: address, toAddress: address, slippage: 1.0, }); console.log("Route estimated output:", route.estimate.toAmount); // 4. Check if approval is needed const { isApproved } = await squid.isRouteApproved({ route, sender: address }); if (!isApproved) { const approveTx = await squid.approveRoute({ signer, route }); if (approveTx) await (approveTx as ethers.TransactionResponse).wait(); console.log("Token approved"); } // 5. Execute the cross-chain swap const tx = await squid.executeRoute({ signer, route }); const receipt = await (tx as ethers.TransactionResponse).wait(); const txHash = receipt!.hash; console.log("Swap submitted:", txHash); // 6. Poll status until final let finalStatus: string | undefined; do { await new Promise(r => setTimeout(r, 5000)); // wait 5 s const { squidTransactionStatus } = await squid.getStatus({ transactionId: txHash, requestId, integratorId: process.env.INTEGRATOR_ID!, quoteId: route.estimate.feeCosts[0]?.token ?? "", }); finalStatus = squidTransactionStatus; console.log("Status:", finalStatus); } while (finalStatus !== "success" && finalStatus !== "failed"); console.log("Done! Final status:", finalStatus); // Done! Final status: success } crossChainSwap().catch(console.error); ``` -------------------------------- ### Complete End-to-End EVM Cross-Chain Swap Source: https://context7.com/0xsquid/squid-sdk/llms.txt Demonstrates a full cross-chain swap process for EVM chains, including initialization, route fetching, approval, execution, and status polling. ```APIDOC ## Complete End-to-End EVM Cross-Chain Swap Full example combining initialization, route fetching, approval, execution, and status polling for an EVM-to-EVM swap. ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; async function crossChainSwap() { // 1. Setup provider & signer const provider = new ethers.JsonRpcProvider(process.env.ETH_RPC_URL); const signer = new ethers.Wallet(process.env.PRIVATE_KEY!, provider); const address = await signer.getAddress(); // 2. Initialize SDK const squid = new Squid({ baseUrl: "https://apiplus.squidrouter.com/", integratorId: process.env.INTEGRATOR_ID!, }); await squid.init(); // 3. Get route: swap 50 USDC on Ethereum → USDT on Polygon const { route, requestId } = await squid.getRoute({ fromChain: "1", toChain: "137", fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC toToken: "0xc2132D05D31c914a87C6611C10748AEb04B58e8F", // USDT fromAmount: "50000000", // 50 USDC (6 decimals) fromAddress: address, toAddress: address, slippage: 1.0, }); console.log("Route estimated output:", route.estimate.toAmount); // 4. Check if approval is needed const { isApproved } = await squid.isRouteApproved({ route, sender: address }); if (!isApproved) { const approveTx = await squid.approveRoute({ signer, route }); if (approveTx) await (approveTx as ethers.TransactionResponse).wait(); console.log("Token approved"); } // 5. Execute the cross-chain swap const tx = await squid.executeRoute({ signer, route }); const receipt = await (tx as ethers.TransactionResponse).wait(); const txHash = receipt!.hash; console.log("Swap submitted:", txHash); // 6. Poll status until final let finalStatus: string | undefined; do { await new Promise(r => setTimeout(r, 5000)); // wait 5 s const { squidTransactionStatus } = await squid.getStatus({ transactionId: txHash, requestId, integratorId: process.env.INTEGRATOR_ID!, quoteId: route.estimate.feeCosts[0]?.token ?? "", }); finalStatus = squidTransactionStatus; console.log("Status:", finalStatus); } while (finalStatus !== "success" && finalStatus !== "failed"); console.log("Done! Final status:", finalStatus); // Done! Final status: success } crossChainSwap().catch(console.error); ``` ``` -------------------------------- ### Initialize Squid SDK Client Source: https://context7.com/0xsquid/squid-sdk/llms.txt Create a new Squid instance with configuration including base URL, integrator ID, execution settings, and timeout. The init() method must be called before any other SDK methods. ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ baseUrl: "https://apiplus.squidrouter.com/", // mainnet endpoint integratorId: "my-app-123abc", // required executionSettings: { infiniteApproval: false, // approve exact amounts only }, timeout: 10_000, // 10 s HTTP timeout }); // Must be called before any other method await squid.init(); console.log("Chains supported:", squid.chains.length); console.log("Tokens supported:", squid.tokens.length); console.log("Maintenance mode:", squid.isInMaintenanceMode); // Chains supported: 42 // Tokens supported: 630 // Maintenance mode: false ``` -------------------------------- ### `squid.getFromAmount({ fromToken, toToken, toAmount, slippagePercentage? })` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Computes the required input amount of `fromToken` to receive a target `toAmount` of `toToken`, factoring in slippage. It fetches real-time prices internally and uses fallback prices from `init()` if the API call fails. ```APIDOC ## `squid.getFromAmount({ fromToken, toToken, toAmount, slippagePercentage? })` ### Description Computes how much of `fromToken` is needed to receive a target `toAmount` of `toToken`, including slippage. Fetches real-time prices for both tokens internally and falls back to prices from `init()` if the API call fails. ### Parameters #### Path Parameters - **fromToken** (Token) - Required - The token to send. - **toToken** (Token) - Required - The token to receive. - **toAmount** (string) - Required - The target amount of `toToken` to receive. - **slippagePercentage** (number) - Optional - The slippage tolerance in percentage. ### Request Example ```typescript await squid.init(); const usdcToken = squid.tokens.find( t => t.symbol === "USDC" && t.chainId === "1" )!; const maticToken = squid.tokens.find( t => t.symbol === "MATIC" && t.chainId === "137" )!; const fromAmount = await squid.getFromAmount({ fromToken: usdcToken, toToken: maticToken, toAmount: "100", // want 100 MATIC slippagePercentage: 1, // 1% slippage buffer }); console.log("Need to send (USDC):", fromAmount); // Need to send (USDC): 88.1505... (100 MATIC * $0.87 / $1.00 + 1%) ``` ``` -------------------------------- ### Run All Integration Tests Source: https://github.com/0xsquid/squid-sdk/blob/main-v2/docs/integration.md Execute all available integration tests for the Squid SDK. Ensure backend API is running before execution. ```bash yarn integration ``` -------------------------------- ### `squid.setConfig(config)` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Allows reconfiguring the SDK at runtime by replacing the current configuration, including the API base URL, integrator ID, and timeout. This is useful for switching between different network environments (e.g., mainnet and testnet) without needing to instantiate a new SDK object. ```APIDOC ## `squid.setConfig(config)` ### Description Replaces the current SDK configuration (API base URL, integrator ID, timeout) and rebuilds the underlying HTTP client. Useful for switching between mainnet and testnet environments without creating a new instance. ### Parameters #### Path Parameters - **config** (object) - Required - An object containing the new configuration settings. - **baseUrl** (string) - The new API base URL. - **integratorId** (string) - The new integrator ID. - **timeout** (number) - The new request timeout in milliseconds. ### Request Example ```typescript // Start with testnet const squid = new Squid({ baseUrl: "https://testnet.api.squidrouter.com/", integratorId: "test-integrator", }); await squid.init(); // Switch to mainnet later (e.g., based on user wallet network) squid.setConfig({ baseUrl: "https://apiplus.squidrouter.com/", integratorId: "my-app-123abc", }); await squid.init(); // re-fetch chain/token data for new environment ``` ``` -------------------------------- ### Reconfigure SDK at Runtime Source: https://context7.com/0xsquid/squid-sdk/llms.txt Allows updating the SDK's configuration, including the API base URL and integrator ID, after initialization. This is useful for switching between different network environments like testnet and mainnet. ```typescript // Start with testnet const squid = new Squid({ baseUrl: "https://testnet.api.squidrouter.com/", integratorId: "test-integrator", }); await squid.init(); // Switch to mainnet later (e.g., based on user wallet network) squid.setConfig({ baseUrl: "https://apiplus.squidrouter.com/", integratorId: "my-app-123abc", }); await squid.init(); // re-fetch chain/token data for new environment ``` -------------------------------- ### Compute a cross-chain swap route Source: https://context7.com/0xsquid/squid-sdk/llms.txt Returns a `RouteResponse` containing the optimal path, fee estimate, and a signed `transactionRequest` ready for execution. All token amounts are in the smallest denomination (e.g., wei for ETH). ```APIDOC ## `squid.getRoute(params)` — Compute a cross-chain swap route Returns a `RouteResponse` containing the optimal path, fee estimate, and a signed `transactionRequest` ready for execution. All token amounts are in the smallest denomination (wei / uATOM / lamports). ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ integratorId: "my-app-123abc" }); await squid.init(); const { route, requestId } = await squid.getRoute({ fromChain: "1", // Ethereum mainnet (chain ID) toChain: "56", // BNB Chain fromToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native ETH toToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native BNB fromAmount: "1000000000000000000", // 1 ETH in wei fromAddress: "0xYourWalletAddress", toAddress: "0xDestinationAddress", slippage: 1.5, // 1.5% slippage tolerance }); console.log("Request ID:", requestId); console.log("Estimated output:", route.estimate.toAmount); console.log("Estimated fees:", route.estimate.feeCosts); console.log("Tx type:", route.transactionRequest?.type); // Request ID: 1643a99ae59c3f5164ed120812f00e38 // Estimated output: 12345678900000000 // Tx type: "ON_CHAIN_EXECUTION" ``` ``` -------------------------------- ### Fetch Prices for All Supported Tokens Source: https://context7.com/0xsquid/squid-sdk/llms.txt Returns an array of `Token` objects, each including a `usdPrice` field. If `chainId` is provided, prices for tokens on that specific chain are returned. If omitted, prices for all supported tokens across all chains are fetched. ```typescript // All tokens on Polygon const polygonTokens = await squid.getMultipleTokensPrice({ chainId: "137" }); polygonTokens.forEach(token => { console.log(`${token.symbol}: $${token.usdPrice}`); }); // MATIC: $0.87 // USDC: $1.00 // WBTC: $68200.00 // All tokens across all chains const allTokens = await squid.getMultipleTokensPrice({}); console.log("Total tokens with prices:", allTokens.length); ``` -------------------------------- ### `squid.getAllBalances({ chainIds?, evmAddress?, cosmosAddresses? })` Source: https://context7.com/0xsquid/squid-sdk/llms.txt A convenience method that fetches both EVM and Cosmos balances concurrently. It returns a combined response containing `evmBalances` and `cosmosBalances`. Users specify `evmAddress` for EVM chains and `cosmosAddresses` for Cosmos chains, and the SDK handles the distribution of `chainIds` based on chain type. ```APIDOC ## `squid.getAllBalances({ chainIds?, evmAddress?, cosmosAddresses? })` ### Description Convenience wrapper that fetches EVM and Cosmos balances in parallel and returns both in a single response. Pass `evmAddress` for EVM chains and `cosmosAddresses` for Cosmos chains; the SDK automatically splits `chainIds` by chain type. ### Parameters #### Path Parameters - **chainIds** (string[]) - Optional - An array of chain IDs to fetch balances from. - **evmAddress** (string) - Optional - The EVM address to fetch balances for. - **cosmosAddresses** (Array<{ coinType: number, chainId: string, address: string }>) ### Request Example ```typescript const { evmBalances, cosmosBalances } = await squid.getAllBalances({ chainIds: ["1", "137", "osmosis-1"], evmAddress: "0xYourEvmAddress", cosmosAddresses: [ { coinType: 118, chainId: "osmosis-1", address: "cosmos1abc..." }, ], }); console.log("EVM balances:", evmBalances?.length); console.log("Cosmos balances:", cosmosBalances?.length); // EVM balances: 12 // Cosmos balances: 3 ``` ``` -------------------------------- ### Run Specific Integration Tests Source: https://github.com/0xsquid/squid-sdk/blob/main-v2/docs/integration.md Execute specific integration tests by name. This is useful for targeted testing of individual functionalities. ```bash yarn integration:sendtrade ``` ```bash yarn integration:tradesend ``` ```bash yarn integration:tradesendtrade ``` -------------------------------- ### Fetch chain and token data Source: https://context7.com/0xsquid/squid-sdk/llms.txt Populates `squid.chains` and `squid.tokens` by calling the `/v2/sdk-info` endpoint. This method must be awaited before calling `getRoute`, `executeRoute`, or any balance method. It also sets `isInMaintenanceMode`, `maintenanceMessage`, and `axelarscanURL`. ```APIDOC ## `squid.init()` — Fetch chain and token data Populates `squid.chains` and `squid.tokens` by calling the `/v2/sdk-info` endpoint. Must be awaited before calling `getRoute`, `executeRoute`, or any balance method. Also sets `isInMaintenanceMode`, `maintenanceMessage`, and `axelarscanURL`. ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ integratorId: "my-app-123abc" }); try { await squid.init(); console.log("SDK ready, axelarscan:", squid.axelarscanURL); } catch (err) { console.error("Initialization failed:", err.message); // "SDK initialization failed" } ``` ``` -------------------------------- ### Fetch All Balances in One Call Source: https://context7.com/0xsquid/squid-sdk/llms.txt A convenience function to fetch both EVM and Cosmos balances concurrently. It requires specifying the EVM address and/or Cosmos addresses and optionally filters by chain IDs. ```typescript const { evmBalances, cosmosBalances } = await squid.getAllBalances({ chainIds: ["1", "137", "osmosis-1"], evmAddress: "0xYourEvmAddress", cosmosAddresses: [ { coinType: 118, chainId: "osmosis-1", address: "cosmos1abc..." }, ], }); console.log("EVM balances:", evmBalances?.length); console.log("Cosmos balances:", cosmosBalances?.length); // EVM balances: 12 // Cosmos balances: 3 ``` -------------------------------- ### Fetch Cosmos Balances Source: https://context7.com/0xsquid/squid-sdk/llms.txt Fetches CosmosBalance objects for specified IBC-compatible addresses across given Cosmos chains. The SDK automatically derives bech32 addresses based on the provided coin type and chain ID. ```typescript const cosmosBalances = await squid.getCosmosBalances({ addresses: [ { coinType: 118, // Cosmos standard coin type chainId: "osmosis-1", address: "cosmos1abc...", // can be any bech32 address with same key }, ], chainIds: ["osmosis-1", "cosmoshub-4"], }); cosmosBalances.forEach(b => { console.log(`${b.denom} on ${b.chainId}: ${b.balance}`); }); // uosmo on osmosis-1: 5000000 // uatom on cosmoshub-4: 1000000 ``` -------------------------------- ### Compute Cross-Chain Swap Route Source: https://context7.com/0xsquid/squid-sdk/llms.txt Compute an optimal cross-chain swap route using the getRoute method. This returns a RouteResponse with the path, fee estimates, and a transaction request. All token amounts are in the smallest denomination. ```typescript import { Squid } from "@0xsquid/sdk"; const squid = new Squid({ integratorId: "my-app-123abc" }); await squid.init(); const { route, requestId } = await squid.getRoute({ fromChain: "1", // Ethereum mainnet (chain ID) toChain: "56", // BNB Chain fromToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native ETH toToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native BNB fromAmount: "1000000000000000000", // 1 ETH in wei fromAddress: "0xYourWalletAddress", toAddress: "0xDestinationAddress", slippage: 1.5, // 1.5% slippage tolerance }); console.log("Request ID:", requestId); console.log("Estimated output:", route.estimate.toAmount); console.log("Estimated fees:", route.estimate.feeCosts); console.log("Tx type:", route.transactionRequest?.type); // Request ID: 1643a99ae59c3f5164ed120812f00e38 // Estimated output: 12345678900000000 // Tx type: "ON_CHAIN_EXECUTION" ``` -------------------------------- ### `squid.getEvmBalances({ userAddress, chains? })` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Fetches an array of `TokenBalance` for all tracked EVM tokens associated with a given user address. It utilizes Multicall3 when available and falls back to individual RPC calls for unsupported chains. An optional list of chain IDs can be provided to filter the results. ```APIDOC ## `squid.getEvmBalances({ userAddress, chains? })` ### Description Returns an array of `TokenBalance` for all tracked EVM tokens belonging to the given address. Uses Multicall3 where available (falls back to individual RPC calls for unsupported chains such as Filecoin). Optionally filter by a list of chain IDs. ### Parameters #### Path Parameters - **userAddress** (string) - Required - The EVM address to fetch balances for. - **chains** (string[]) - Optional - An array of chain IDs to filter balances by. ### Request Example ```typescript const balances = await squid.getEvmBalances({ userAddress: "0xYourWalletAddress", chains: ["1", "137", "56"], // ETH, Polygon, BSC — omit for all chains }); balances .filter(b => Number(b.balance) > 0) .forEach(b => { console.log(`${b.symbol} on chain ${b.chainId}: ${b.balance}`); }); // USDC on chain 1: 5000000 (5 USDC, 6 decimals) // MATIC on chain 137: 1000000000000000000 (1 MATIC) ``` ``` -------------------------------- ### Execute Cross-Chain Swap with Squid SDK Source: https://context7.com/0xsquid/squid-sdk/llms.txt Submits a cross-chain swap transaction using a provided signer. Handles balance validation and ERC-20 approvals. Supports various signer types including EVM, Cosmos, Solana, and Sui. Returns a chain-specific transaction response. ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"); const signer = new ethers.Wallet("0xYOUR_PRIVATE_KEY", provider); const squid = new Squid({ integratorId: "my-app-123abc" }); await squid.init(); const { route } = await squid.getRoute({ fromChain: "1", toChain: "137", // Polygon fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on ETH toToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native MATIC fromAmount: "1000000", // 1 USDC (6 decimals) fromAddress: await signer.getAddress(), toAddress: await signer.getAddress(), slippage: 1.0, }); const tx = await squid.executeRoute({ signer, route, executionSettings: { infiniteApproval: false }, }); const receipt = await (tx as ethers.TransactionResponse).wait(); console.log("Tx hash:", receipt?.hash); // Tx hash: 0xabc123... ``` -------------------------------- ### squid.approveRoute Source: https://context7.com/0xsquid/squid-sdk/llms.txt Sends an ERC-20 `approve` transaction on the source chain, optionally allowing infinite spending or only the exact route amount. ```APIDOC ## `squid.approveRoute(data)` — Approve ERC-20 token spend Sends an ERC-20 `approve` transaction on the source chain. Respects the `executionSettings.infiniteApproval` flag — `false` approves only the exact route amount, `true` (default) approves `uint256.max`. Returns `null` for native-token routes. ```typescript import { ethers } from "ethers"; const signer = new ethers.Wallet("0xPRIVATE_KEY", provider); const { route } = await squid.getRoute({ /* ... */ }); const approveTx = await squid.approveRoute({ signer, route, executionSettings: { infiniteApproval: false }, // approve exact amount }); if (approveTx) { await (approveTx as ethers.TransactionResponse).wait(); console.log("Approved, tx:", approveTx.hash); // Approved, tx: 0xdef456... } ``` ``` -------------------------------- ### Calculate Required Input Amount with Slippage Source: https://context7.com/0xsquid/squid-sdk/llms.txt Use this function to determine the necessary amount of a 'fromToken' to acquire a target 'toAmount' of a 'toToken', accounting for slippage. It fetches real-time prices and falls back to initialized prices if the API call fails. ```typescript await squid.init(); const usdcToken = squid.tokens.find( t => t.symbol === "USDC" && t.chainId === "1" )!; const maticToken = squid.tokens.find( t => t.symbol === "MATIC" && t.chainId === "137" )!; const fromAmount = await squid.getFromAmount({ fromToken: usdcToken, toToken: maticToken, toAmount: "100", // want 100 MATIC slippagePercentage: 1, // 1% slippage buffer }); console.log("Need to send (USDC):", fromAmount); // Need to send (USDC): 88.1505... (100 MATIC * $0.87 / $1.00 + 1%) ``` -------------------------------- ### squid.getTokenPrice Source: https://context7.com/0xsquid/squid-sdk/llms.txt Fetches the real-time USD price for a specific token by querying the `/v2/tokens` endpoint. ```APIDOC ## `squid.getTokenPrice({ tokenAddress, chainId })` — Fetch single token USD price Fetches the real-time USD price for a single token by querying the `/v2/tokens` endpoint with `usdPrice=true`. Throws if no valid price is found. ```typescript const price = await squid.getTokenPrice({ tokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native ETH chainId: "1", }); console.log("ETH price (USD):", price); // ETH price (USD): 3420.55 ``` ``` -------------------------------- ### Approve ERC-20 Token Spend for Squid Route Source: https://context7.com/0xsquid/squid-sdk/llms.txt Sends an ERC-20 approve transaction on the source chain. The `infiniteApproval` flag in `executionSettings` determines if the approval is for the exact route amount (`false`) or `uint256.max` (`true`, default). Returns `null` for native token routes. ```typescript import { ethers } from "ethers"; const signer = new ethers.Wallet("0xPRIVATE_KEY", provider); const { route } = await squid.getRoute({ /* ... */ }); const approveTx = await squid.approveRoute({ signer, route, executionSettings: { infiniteApproval: false }, // approve exact amount }); if (approveTx) { await (approveTx as ethers.TransactionResponse).wait(); console.log("Approved, tx:", approveTx.hash); // Approved, tx: 0xdef456... ``` -------------------------------- ### Query Transaction and Send Tokens Cross-Chain Source: https://github.com/0xsquid/squid-sdk/blob/main-v2/docs/integration.md Execute the transaction script to query the /api/transaction endpoint and send tokens across different chains. This requires prior token approval. ```typescript yarn ts-node transaction.ts ``` -------------------------------- ### `squid.getRawTxHex({ route, nonce })` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Serializes an EVM transaction into its RLP-encoded hex format without requiring a signature. This is useful for hardware wallets, offline signing workflows, and gas estimation tools. ```APIDOC ## `squid.getRawTxHex({ route, nonce })` ### Description Returns the RLP-encoded hex of the EVM transaction that would be submitted, without requiring a signer. Useful for hardware wallets, off-line signing workflows, or gas estimation tools. ### Parameters #### Path Parameters - **route** (object) - Required - The route object obtained from `getRoute`. - **nonce** (number) - Required - The transaction nonce. - **overrides** (object) - Optional - Transaction overrides like `maxFeePerGas` and `maxPriorityFeePerGas`. ### Request Example ```typescript const { route } = await squid.getRoute({ /* ... */ }); const rawHex = squid.getRawTxHex({ route, nonce: 42, overrides: { maxFeePerGas: BigInt("30000000000"), // 30 gwei maxPriorityFeePerGas: BigInt("2000000000"), // 2 gwei }, }); console.log("Unsigned raw tx:", rawHex); // 0x02f87a018... ``` ``` -------------------------------- ### `squid.getCosmosBalances({ addresses, chainIds? })` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Retrieves `CosmosBalance[]` for specified IBC-compatible addresses across a given set of Cosmos chains. The SDK automatically derives the correct bech32 address format for each chain based on the provided `coinType`, `chainId`, and `address`. ```APIDOC ## `squid.getCosmosBalances({ addresses, chainIds? })` ### Description Returns `CosmosBalance[]` for each IBC-compatible address across the specified Cosmos chains. Addresses are provided as `{ coinType, chainId, address }` objects; the SDK derives the chain-specific bech32 address automatically. ### Parameters #### Path Parameters - **addresses** (Array<{ coinType: number, chainId: string, address: string }>) - **chainIds** (string[]) - Optional - An array of chain IDs to filter balances by. ### Request Example ```typescript const cosmosBalances = await squid.getCosmosBalances({ addresses: [ { coinType: 118, // Cosmos standard coin type chainId: "osmosis-1", address: "cosmos1abc...", // can be any bech32 address with same key }, ], chainIds: ["osmosis-1", "cosmoshub-4"], }); cosmosBalances.forEach(b => { console.log(`${b.denom} on ${b.chainId}: ${b.balance}`); }); // uosmo on osmosis-1: 5000000 // uatom on cosmoshub-4: 1000000 ``` ``` -------------------------------- ### squid.executeRoute Source: https://context7.com/0xsquid/squid-sdk/llms.txt Submits a cross-chain swap transaction to the blockchain using a provided signer. It handles necessary validations and approvals for various blockchain types. ```APIDOC ## `squid.executeRoute(data)` — Execute a cross-chain swap Submits the transaction to the blockchain using the provided signer. Automatically handles balance validation, ERC-20 approvals (for EVM), and supports EVM (`ethers` Wallet), Cosmos (`SigningStargateClient`), Solana (`Wallet` / Phantom), and Sui signers. Returns a chain-specific transaction response. ```typescript import { Squid } from "@0xsquid/sdk"; import { ethers } from "ethers"; const provider = new ethers.JsonRpcProvider("https://eth-mainnet.g.alchemy.com/v2/YOUR_KEY"); const signer = new ethers.Wallet("0xYOUR_PRIVATE_KEY", provider); const squid = new Squid({ integratorId: "my-app-123abc" }); await squid.init(); const { route } = await squid.getRoute({ fromChain: "1", toChain: "137", // Polygon fromToken: "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", // USDC on ETH toToken: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native MATIC fromAmount: "1000000", // 1 USDC (6 decimals) fromAddress: await signer.getAddress(), toAddress: await signer.getAddress(), slippage: 1.0, }); const tx = await squid.executeRoute({ signer, route, executionSettings: { infiniteApproval: false }, }); const receipt = await (tx as ethers.TransactionResponse).wait(); console.log("Tx hash:", receipt?.hash); // Tx hash: 0xabc123... ``` ``` -------------------------------- ### `squid.getTokenData(address, chainId)` Source: https://context7.com/0xsquid/squid-sdk/llms.txt Looks up token information by its contract address and chain ID from the SDK's locally cached token list, which is populated during `init()`. If no matching token is found, an error is thrown. ```APIDOC ## `squid.getTokenData(address, chainId)` ### Description Searches the locally cached token list (populated by `init()`) for a token matching the given contract address and chain ID. Throws if no match is found. ### Parameters #### Path Parameters - **address** (string) - Required - The contract address of the token. - **chainId** (string) - Required - The ID of the chain the token is on. ### Request Example ```typescript const usdc = squid.getTokenData( "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "1", // Ethereum ); console.log(usdc.symbol); // "USDC" console.log(usdc.decimals); // 6 console.log(usdc.usdPrice); // 1.0001 ``` ``` -------------------------------- ### Fetch EVM Token Balances Source: https://context7.com/0xsquid/squid-sdk/llms.txt Retrieves an array of TokenBalance objects for all tracked EVM tokens for a given address. It utilizes Multicall3 when available and can optionally filter balances by a list of chain IDs. ```typescript const balances = await squid.getEvmBalances({ userAddress: "0xYourWalletAddress", chains: ["1", "137", "56"], // ETH, Polygon, BSC — omit for all chains }); balances .filter(b => Number(b.balance) > 0) .forEach(b => { console.log(`${b.symbol} on chain ${b.chainId}: ${b.balance}`); }); // USDC on chain 1: 5000000 (5 USDC, 6 decimals) // MATIC on chain 137: 1000000000000000000 (1 MATIC) ``` -------------------------------- ### Fetch Single Token USD Price Source: https://context7.com/0xsquid/squid-sdk/llms.txt Retrieves the real-time USD price for a specific token by querying the `/v2/tokens` endpoint with `usdPrice=true`. This function will throw an error if a valid price cannot be found. ```typescript const price = await squid.getTokenPrice({ tokenAddress: "0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE", // native ETH chainId: "1", }); console.log("ETH price (USD):", price); // ETH price (USD): 3420.55 ``` -------------------------------- ### getChainData(chainId) Source: https://context7.com/0xsquid/squid-sdk/llms.txt Looks up a chain by its ID from the locally cached chain list. Throws an error if the chain is not supported. ```APIDOC ## `squid.getChainData(chainId)` — Look up a chain by ID Searches the locally cached chain list for the `ChainData` object matching the given chain ID. Throws if the chain is not supported. ```typescript const eth = squid.getChainData("1"); console.log(eth.networkName); // "Ethereum" console.log(eth.chainType); // "evm" console.log(eth.rpc); // "https://..." console.log(eth.nativeCurrency.symbol); // "ETH" ``` ``` -------------------------------- ### squid.getMultipleTokensPrice Source: https://context7.com/0xsquid/squid-sdk/llms.txt Retrieves an array of Token objects, each including a valid `usdPrice` field, for all supported tokens across all chains or a specific chain. ```APIDOC ## `squid.getMultipleTokensPrice({ chainId? })` — Fetch prices for all tokens Returns an array of `Token` objects that include a valid `usdPrice` field. If `chainId` is omitted, prices for all supported tokens across all chains are returned. ```typescript // All tokens on Polygon const polygonTokens = await squid.getMultipleTokensPrice({ chainId: "137" }); polygonTokens.forEach(token => { console.log(`${token.symbol}: $${token.usdPrice}`); }); // MATIC: $0.87 // USDC: $1.00 // WBTC: $68200.00 // All tokens across all chains const allTokens = await squid.getMultipleTokensPrice({}); console.log("Total tokens with prices:", allTokens.length); ``` ``` -------------------------------- ### Look Up Token Data by Address Source: https://context7.com/0xsquid/squid-sdk/llms.txt Retrieves detailed token information from the SDK's cached token list using its contract address and chain ID. An error is thrown if the token is not found in the cache. ```typescript const usdc = squid.getTokenData( "0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48", "1", // Ethereum ); console.log(usdc.symbol); // "USDC" console.log(usdc.decimals); // 6 console.log(usdc.usdPrice); // 1.0001 ``` -------------------------------- ### squid.getStatus Source: https://context7.com/0xsquid/squid-sdk/llms.txt Polls the `/v2/status` endpoint to retrieve the live status of a cross-chain transaction after it has been submitted. ```APIDOC ## `squid.getStatus(params)` — Poll cross-chain transaction status Queries the `/v2/status` endpoint for the live status of a submitted cross-chain transaction. Poll this after `executeRoute` until `squidTransactionStatus` is `"success"` or `"failed"`. ```typescript const status = await squid.getStatus({ transactionId: "0xabc123...", // source chain tx hash quoteId: route.estimate.feeCosts[0]?.token || "", // from route estimate requestId: requestId, // from getRoute response integratorId: "my-app-123abc", }); console.log("Status:", status.squidTransactionStatus); console.log("GMP status:", status.gasStatus); console.log("Axelar URL:", status.axelarTransactionUrl); // Status: "success" // GMP status: "gas_paid_enough_gas" // Axelar URL: https://axelarscan.io/gmp/0xabc123... ``` ``` -------------------------------- ### Check ERC-20 Allowance for Squid Route Source: https://context7.com/0xsquid/squid-sdk/llms.txt Verifies if the sender has sufficient ERC-20 allowance for the Squid router to execute a given route, without initiating a transaction. Returns an object indicating approval status and a message. ```typescript const { isApproved, message } = await squid.isRouteApproved({ route, sender: "0xYourWalletAddress", }); if (!isApproved) { console.log("Need approval:", message); // "Not enough allowance" } else { console.log("Ready to execute"); } ``` -------------------------------- ### Look up Chain Data by ID using squid.getChainData Source: https://context7.com/0xsquid/squid-sdk/llms.txt Searches the locally cached chain list for the ChainData object matching the given chain ID. Throws if the chain is not supported. ```typescript const eth = squid.getChainData("1"); console.log(eth.networkName); // "Ethereum" console.log(eth.chainType); // "evm" console.log(eth.rpc); // "https://..." console.log(eth.nativeCurrency.symbol); // "ETH" ``` -------------------------------- ### Serialize EVM Transaction Without Signing Source: https://context7.com/0xsquid/squid-sdk/llms.txt Generates the RLP-encoded hex of an EVM transaction without requiring a signature. This is useful for hardware wallets, offline signing, or gas estimation tools. ```typescript const { route } = await squid.getRoute({ /* ... */ }); const rawHex = squid.getRawTxHex({ route, nonce: 42, overrides: { maxFeePerGas: BigInt("30000000000"), // 30 gwei maxPriorityFeePerGas: BigInt("2000000000"), // 2 gwei }, }); console.log("Unsigned raw tx:", rawHex); // 0x02f87a018... ``` -------------------------------- ### squid.isRouteApproved Source: https://context7.com/0xsquid/squid-sdk/llms.txt Checks if the sender has sufficient ERC-20 allowance for the Squid router to execute a given route without initiating a transaction. ```APIDOC ## `squid.isRouteApproved({ route, sender })` — Check ERC-20 allowance Checks whether the sender's ERC-20 allowance for the Squid router is sufficient to execute a given route, without sending any transaction. Returns `{ isApproved: boolean, message: string }`. ```typescript const { isApproved, message } = await squid.isRouteApproved({ route, sender: "0xYourWalletAddress", }); if (!isApproved) { console.log("Need approval:", message); // "Not enough allowance" } else { console.log("Ready to execute"); } ``` ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.