In the rapidly evolving world of decentralized finance (DeFi), accessing accurate and efficient token swap quotes is fundamental. This guide delves into the core functionality of a Swap API, explaining how it processes requests to deliver the best possible trade execution across various decentralized exchanges (DEXs). By understanding its parameters and responses, developers and traders can integrate powerful swap capabilities into their applications.
Core Request Parameters for a Swap Quote
To fetch a quote, your API request must include several key parameters that define the trade you wish to execute.
Essential Trading Parameters
chainIndex(String, Required): A unique identifier for the blockchain network you are operating on. For instance,1typically represents the Ethereum network.chainId(String, Required): Another unique chain identifier. Note that this parameter is marked for future deprecation, so it is advisable to prioritize usingchainIndex.amount(String, Required): This is the input token quantity, specified in its smallest divisible units (e.g., Wei for ETH, or the smallest decimal for an ERC-20 token). The meaning of this amount depends on theswapMode.swapMode(String, Required): This dictates the type of swap you want to perform. The two modes are:exactIn: You specify the exact amount of a token you want to sell. The API returns the estimated amount of the token you will receive.exactOut: You specify the exact amount of a token you want to buy. The API calculates the estimated amount of the token you need to sell. In this mode, slippage tolerance applies to the input amount.
fromTokenAddress(String, Required): The smart contract address of the token you are selling. Use the standard null address (e.g.,0xeee...eee) for the network's native gas token (like ETH or BNB).toTokenAddress(String, Required): The smart contract address of the token you wish to purchase.
Optional Configuration Parameters
dexIds(String, Optional): If you want to limit the quote to specific liquidity pools, you can provide their DEX identifiers, separated by commas (e.g.,1,50,180).directRoute(Boolean, Optional): When set totrue, this restricts the routing algorithm to use only a single liquidity pool for the swap, potentially simplifying the transaction. This feature is currently specific to the Solana blockchain.priceImpactProtectionPercentage(String, Optional): A safety feature to prevent unfavorable trades. This value (between 0 and 1.0) sets the maximum acceptable price impact. If the estimated impact exceeds this percentage, the API returns an error. The default is0.9(90%), and setting it to1.0disables the protection.feePercent(String, Optional): Allows a referrer fee to be deducted from thefromTokenamount before the swap. The remaining amount is then used as the effective input for the trade. Fees are chain-specific.
Understanding the API Response Data
A successful API response returns a detailed JSON object containing the optimal quote and a wealth of information to help you analyze the proposed trade.
Primary Quote Information
The top level of the response provides a summary of the best available swap route.
chainIndex&chainId: Echo back the network identifiers from your request.swapMode: Confirms the mode used for the quote.fromTokenAmount: The input amount to be sold, in minimal units.toTokenAmount: The resulting amount to be bought, in minimal units.tradeFee: The estimated network fee for the transaction, quoted in USD.estimateGasFee: The estimated gas consumption for the transaction, denoted in the chain's smallest unit (e.g., Wei).
Detailed Routing Breakdown
The dexRouterList array contains objects that break down the main paths used for the token swap.
router: Indicates one of the main paths for the swap.routerPercent: The percentage of the total trade volume that is routed through this path.subRouterList: Provides further details on the DEX routers involved.dexProtocol: An array listing the specific liquidity protocols (e.g., Uniswap V3, Curve) used in this path, along with thepercentof assets they handle and theirdexName.
Comprehensive Token Information
The response includes full details for both tokens involved in the swap.
fromToken&toTokenObjects:tokenContractAddress: The token's on-chain address.tokenSymbol: The ticker symbol (e.g., USDT, WBTC).tokenUnitPrice: An estimated real-time USD price sourced from on-chain and third-party data. This is for reference and may sometimes benull.decimal: The number of decimals defining the token's divisibility. Note: This can change due to contract owner adjustments.isHoneyPot: A boolean (true/false) indicating if the token is identified as a honeypot scam.taxRate: The buy or sell tax rate applied by the token's contract, common in certain tokenomics models. Represented as a decimal (e.g.,0.01for a 1% tax).
Route Comparison Data
The quoteCompareList array offers a comparison of alternative quote routes from different DEXs, allowing for easy analysis.
dexName&dexLogo: The name and logo of the DEX providing the alternative quote.tradeFee: The estimated network fee in USD for this route.amountOut: The amount oftoTokenyou would receive via this route.priceImpactPercentage: The estimated percentage change in price caused by your trade's size within the liquidity pool. ๐ Explore more strategies for analyzing price impact
Frequently Asked Questions
What is the difference between exactIn and exactOut swap modes?ExactIn is used when you know the amount you want to spend; the API tells you what you'll get. ExactOut is for when you have a target amount to receive; the API calculates the cost. Slippage tolerance applies to the input token in exactOut mode.
How do I find the correct minimal unit (e.g., Wei) for the amount parameter?
A token's minimal unit is determined by its decimal places. For example, USDT (6 decimals) has a minimal unit of 0.000001, so 1 USDT is 1000000. You can often fetch this data from a token list API or the token's contract itself.
What does a honeypot token mean, and why is it important?
A honeypot token is a scam where you can buy the token but cannot sell it due to malicious code in its contract. The isHoneyPot flag helps identify such risks before you execute a trade, protecting your funds.
How does price impact protection work?
This optional parameter lets you set a maximum acceptable price impact percentage. If the system estimates your trade would cause a price change beyond this limit (e.g., 25%), it will return an error instead of a quote, preventing a potentially bad trade.
Can I use this API to compare prices across different DEXs?
Yes, the quoteCompareList in the response provides a side-by-side comparison of estimated output amounts and fees from different decentralized exchanges, helping you find the most favorable rate for your swap.
What happens if the token unit price returns as 'null'?
A null unit price typically occurs for very new, illiquid, or custom tokens where reliable pricing data is unavailable. In such cases, you should exercise caution and seek price information from other sources before proceeding.