Integrating decentralized exchange (DEX) trading into your application or wallet? The Solana Swap Instruction API enables developers to programmatically retrieve fully assembled transaction instructions for token swaps across multiple liquidity sources. Whether you're building a custom trading interface, integrating DEX aggregation, or enabling cross-protocol routing, this API delivers secure, efficient, and flexible swap data tailored for the Solana blockchain.
This comprehensive guide walks through the endpoint, request parameters, response structure, and practical use cases—optimized for developers seeking reliable DEX API, swap API, and Solana transaction instruction integration.
How to Fetch Solana Swap Instructions
To retrieve transaction instructions for a token swap on Solana, make a GET request to the following endpoint:
GET https://web3.okx.com/api/v5/dex/aggregator/swap-instructionThis endpoint returns all necessary data to construct and sign a valid Solana transaction, including program IDs, account lists, instruction data, and routing details from integrated decentralized exchanges.
Required & Optional Request Parameters
Below is a breakdown of all available parameters you can pass when querying the API.
🔹 Mandatory Parameters
chainIndex(String): Chain identifier. Use501for Solana.amount(String): Amount of the source token to swap, including decimals (e.g., 1 USDT = 1000000).fromTokenAddress(String): Contract address of the input token (e.g.,So11111111111111111111111111111111111111112for WSOL).toTokenAddress(String): Contract address of the output token.slippage(String): Maximum allowed slippage as a decimal (e.g.,0.005= 0.5%). Must be less than1.userWalletAddress(String): Public key of the user’s wallet initiating the swap.
🔹 Optional Parameters
autoSlippage(Boolean): Iftrue, automatically calculates optimal slippage based on market conditions.maxAutoSlippage(String): Sets an upper cap on auto-generated slippage to manage risk.swapReceiverAddress: Custom address to receive swapped tokens (defaults to user wallet).feePercent: Affiliate fee percentage (0–10%), applied to either input or output token.fromTokenReferrerWalletAddress/toTokenReferrerWalletAddress: Referral addresses for commission collection. Only one type allowed per request.positiveSlippagePercent: Capture positive price movement (up to 10%) on Solana trades.positiveSlippageFeeAddress: Wallet receiving positive slippage earnings.dexIds: Restrict quotes to specific DEXes (comma-separated IDs).directRoute: Enforce single-pool routing (Solana only).priceImpactProtectionPercentage: Reject trades with price impact above threshold (0–1.0). Default: 0.9 (90%).computeUnitPrice: Priority fee for faster Solana transaction processing.computeUnitLimit: Computation budget limit to prevent excessive fees.
👉 Generate optimized swap instructions with real-time routing and slippage control
Understanding the Response Structure
The API returns a rich JSON object containing everything needed to build and execute a Solana transaction.
🔹 Core Response Fields
addressLookupTableAccount
Array of lookup tables used in modern Solana transactions to compress account lists and reduce transaction size—critical for high-performance dApps.
instructionLists
List of serialized instructions, each containing:
data: Encoded instruction payload.accounts: List of required accounts with:pubkey: Account public key.isSigner: Whether this account must sign.isWritable: Whether this account will be modified.
programId: ID of the program executing the instruction.
_routerResult – Swap Route Details
Contains full routing metadata:
fromTokenAmount,toTokenAmount: Input/output amounts (with decimals).tradeFee,estimateGasFee: Estimated network cost in USD and native units (e.g., lamports)._dexRouterList: Breakdown of multi-route paths, including percentages handled by each leg._subRouterList: Nested routing within complex paths._dexProtocol: Specific DEX protocols involved (e.g., Orca, Raydium).
Token Information Objects
Both _fromToken and _toToken include:
tokenContractAddress,tokenSymboltokenUnitPrice: Real-time USD valuation from aggregated sources.decimal: Token precision (e.g., 9 for most SPL tokens).isHoneyPot: Detects scam tokens that restrict selling (true= risky).taxRate: Sell/buy tax rate (e.g., SafeMoon-style taxed tokens).
_quoteCompareList
Comparison of alternative routes by:
- DEX name and logo
- Output amount
- Network fee
- Price impact percentage
_tx
Transaction metadata:
from,to: Wallet and router contract addresses.minReceiveAmount: Minimum output after applying slippage tolerance.slippage: Effective slippage used in calculation.
Practical Use Case: Building a Custom Solana Swap UI
Imagine you're developing a non-custodial wallet that supports token swaps. By calling this API:
- User selects input/output tokens and enters amount.
- Your app calls the
/swap-instructionendpoint with user wallet, slippage settings, and optional referral info. - The API returns optimized route(s), fees, and complete instruction set.
- You display estimated output, price impact, and network cost.
- After confirmation, your app constructs the transaction using the returned instructions and signs it locally.
This ensures full decentralization while leveraging intelligent routing across top Solana DEXes.
👉 Access real-time Solana swap instructions with dynamic route optimization
FAQ: Common Developer Questions
Q: What is the difference between chainIndex and chainId?
A: Use chainIndex (e.g., 501 for Solana). The chainId parameter is deprecated and should not be used.
Q: How do I handle token decimals correctly?
A: Always multiply the human-readable amount by 10^decimals. For example, 1 USDC (6 decimals) = "1000000". You can retrieve decimal values via the token list API.
Q: Can I earn referral fees on Solana swaps?
A: Yes. Set feePercent and either fromTokenReferrerWalletAddress or toTokenReferrerWalletAddress. Note: The referrer address must hold SOL to be active on-chain.
Q: Why is my transaction failing even with correct instructions?
A: Common causes include insufficient SOL for fees, incorrect compute budget (computeUnitLimit), or expired lookup tables. Always validate account states before signing.
Q: Is positive slippage supported on all chains?
A: No. Only Solana currently supports capturing positive slippage via positiveSlippagePercent. On other chains, excess tokens go directly to the user.
Q: How does price impact protection work?
A: If the estimated price impact exceeds your specified percentage (e.g., 25%), the API returns an error. This helps avoid bad trades during high volatility.
Best Practices for Integration
- Always validate token addresses against known lists to prevent scams.
- Use
isHoneyPotandtaxRatechecks to warn users about risky tokens. - Implement fallback logic if auto-slippage fails under extreme market moves.
- Monitor changes in lookup table accounts—they may expire or rotate.
Developers are encouraged to test in devnet environments before going live.
👉 Start integrating powerful DEX swap capabilities today
By leveraging the Solana Swap Instruction API, developers gain access to smart routing, secure transaction assembly, and monetization features—all essential for modern Web3 applications. With clean responses, robust safety checks, and support for affiliate models, this API streamlines DEX integration without compromising control or transparency.