The Solana Swap Instruction API is a powerful tool for developers building decentralized exchange (DEX) aggregators or trading interfaces. It provides the necessary transaction instruction data required to execute token swaps or request quotes on the Solana blockchain. This data is essential for constructing transactions that can be signed and broadcast to the network, enabling seamless token conversions.
Core API Request Structure
To utilize this API, you must structure a GET request to the endpoint https://web3.okx.com/api/v5/dex/aggregator/swap-instruction with a specific set of parameters. Each parameter plays a critical role in defining the swap operation.
Essential Request Parameters
The following parameters are mandatory for a successful API call:
- chainIndex: A unique identifier for the blockchain. For Solana, this value is
501. - amount: The amount of the
fromTokenyou wish to swap. This value must include the token's decimals (e.g., to swap 1.0 USDC, which has 6 decimals, you would input1000000). - fromTokenAddress: The contract address of the token you are selling.
- toTokenAddress: The contract address of the token you want to buy.
- userWalletAddress: The wallet address that will initiate and sign the transaction.
- slippage: The maximum acceptable slippage tolerance for the trade, expressed as a decimal (e.g.,
0.005for 0.5%). On Solana, the minimum is0and the maximum must be less than1.
Advanced and Optional Parameters
For more complex trading strategies and risk management, you can leverage several optional parameters:
- autoSlippage: When set to
true, the API will automatically calculate an optimal slippage value based on current market conditions, overriding any manually providedslippagevalue. - maxAutoSlippage: Used with
autoSlippage=trueto set a cap on the automatically calculated slippage, providing an extra layer of risk control. - swapReceiverAddress: An alternate address to receive the swapped tokens. If not provided, tokens are sent to the
userWalletAddress. - feePercent: A commission fee percentage (0-10) to be sent to a referrer address.
- fromTokenReferrerWalletAddress / toTokenReferrerWalletAddress: The wallet address that will receive the commission fee, denominated in either the input or output token.
- positiveSlippagePercent: A feature for Solana that allows a protocol to capture a percentage (0-10) of any positive slippage a user experiences (i.e., getting more tokens than quoted due to favorable market moves).
- dexIds: A comma-separated list of specific DEX IDs to restrict the quote to only those liquidity sources.
- directRoute: When set to
true, limits the swap route to a single liquidity pool, which can sometimes reduce complexity and fees. - priceImpactProtectionPercentage: A safety feature (default 0.9) that will return an error if the estimated price impact of the trade exceeds this threshold (e.g., 0.25 for 25%).
- computeUnitPrice: Similar to gas price on Ethereum, this sets the priority fee for the transaction on Solana, influencing how quickly it is processed.
- computeUnitLimit: Analogous to gas limit on Ethereum, this defines the maximum computational resources the transaction can consume on Solana.
👉 Explore advanced API strategies
Understanding the API Response
A successful API response contains a detailed breakdown of the transaction instructions and the proposed swap.
Transaction Instruction Data
The core of the response is the instructionLists array, which contains the serialized data needed to build the transaction.
- data: The serialized instruction data for the Solana virtual machine.
- accounts: An array of accounts required by the instruction, each with properties indicating its
pubkey, whether it is aisSigner, and if it isisWritable. - programId: The address of the program that will execute this instruction.
- addressLookupTableAccount: An array containing addresses for Solana Address Lookup Tables (ALTs), which optimize transaction size and efficiency.
Quote and Routing Information
The response also provides a summary of the proposed swap, allowing you to verify the details before execution.
routerResult: The overall result of the quote request.
fromTokenAmount/toTokenAmount: The input and expected output amounts.tradeFee: The estimated network fee for the transaction, quoted in USD.estimateGasFee: The estimated gas fee in the blockchain's smallest unit (e.g., lamports on Solana).
- dexRouterList: An array detailing the pathways (routers) that will be used for the swap and the percentage of the trade each will handle.
- fromToken / toToken: Objects detailing the tokens involved, including their contract addresses, symbols, current unit prices, decimals, and security flags like
isHoneyPot(indicating a scam token) andtaxRate. - quoteCompareList: An array useful for comparing this quote against other potential DEX aggregators or routes, showing output amount, fees, and price impact.
- tx: Critical information for constructing the transaction, including the
minReceiveAmount(the minimum amount you will receive based on your slippage tolerance).
Practical Implementation and Best Practices
Implementing the Swap Instruction API involves a two-step process: first calling the API to get the instruction data, and then using a Solana library like @solana/web3.js to build, sign, and send the transaction.
Always validate the response data. Check the toTokenAmount against your expectations and pay close attention to the priceImpactPercentage and isHoneyPot flags to avoid unfavorable trades or scam tokens. Using the priceImpactProtectionPercentage parameter is a highly recommended best practice to protect users.
Frequently Asked Questions
What is the purpose of the Swap Instruction API?
This API provides the raw transaction instructions needed to execute a token swap on the Solana blockchain. It handles the complex process of finding the best trade route across multiple DEXs and returns the data required to build a secure transaction. It is designed for developers integrating swap functionality into their applications.
How do I handle token decimals when using the 'amount' parameter?
You must provide the amount in the token's smallest unit. First, retrieve the token's decimal precision from a token list. Then, multiply the desired amount by 10 raised to the power of the decimals. For example, to swap 2.5 tokens with 9 decimals, calculate 2.5 * (10^9) = 2500000000.
What is the difference between 'slippage' and 'autoSlippage'?
The slippage parameter is a fixed, user-defined tolerance for price movement. autoSlippage, when enabled, dynamically calculates a suggested slippage value based on real-time market volatility, which can often lead to a higher transaction success rate. You can use maxAutoSlippage to limit the auto-calculated value.
When should I use the 'directRoute' parameter?
Use directRoute=true when you want to force the swap to use a single liquidity pool instead of splitting the trade across multiple pools. This can simplify the transaction and is useful for testing specific pools, though it may not always provide the best available price.
How does the price impact protection feature work?
The priceImpactProtectionPercentage parameter is a safety toggle. If the system calculates that your trade would cause the price to move against you by more than the set percentage (e.g., 25%), the API will return an error instead of a quote. This prevents users from submitting trades with excessively high hidden costs due to low liquidity.
What should I do if the API returns an 'isHoneyPot: true' flag?
If the isHoneyPot flag is true for a token, it strongly indicates that the token might be a scam designed to prevent selling. You should immediately halt any transaction involving that token and warn the user. Proceeding with a swap could result in a complete loss of funds.