Prerequisites
Before starting, make sure you have:- Completed our TypeScript and Node.js Setup Guide.
- Got your API key from the Bags Developer Portal.
- A Solana wallet with tokens to swap and SOL for transaction fees.
- Installed the additional dependencies for this guide:
Transaction Fees: Trading tokens requires Solana transactions. Make sure your wallet has sufficient SOL balance to pay for transaction fees.
1. Set Up Environment Variables
This guide requires your wallet’s private key. Add it to your base.env file:
You can export your private key from wallets like Bags, Phantom, or Backpack.
2. The Token Trading Script
Here is a complete script to get a trade quote and execute a swap. Save it astrade-tokens.ts.
The script follows this flow:
- Get a trade quote
- Review the quote details
- Create a swap transaction
- Sign and send the transaction
Endpoints Used Under the Hood
This guide uses:GET /trade/quoteviasdk.trade.getQuote()POST /trade/swapviasdk.trade.createSwapTransaction()
3. Understanding Trade Quotes
A trade quote provides information about a potential swap before you execute it:Quote Parameters
- inputMint: The token you want to swap from (PublicKey)
- outputMint: The token you want to swap to (PublicKey)
- amount: The amount to swap (in the token’s smallest unit, e.g., lamports for SOL)
- slippageMode: Either
"auto"(automatic slippage calculation) or"manual"(you specify slippage) - slippageBps: Basis points for slippage tolerance (0-10000, where 10000 = 100%). Required when
slippageModeis"manual"
Quote Response
The quote response includes:- inAmount: The input amount (as string)
- outAmount: The expected output amount (as string)
- minOutAmount: The minimum output amount considering slippage
- priceImpactPct: The price impact percentage (as string)
- slippageBps: The slippage tolerance in basis points
- routePlan: Array of route legs showing the swap path through different venues
- platformFee: Optional platform fee information
- requestId: Unique identifier for the quote request
Route Plan
The route plan shows how your swap will be executed across different venues (DEXs, liquidity pools, etc.). Each leg represents one step in the swap path.4. Slippage Modes
Auto Slippage
When usingslippageMode: "auto", the SDK automatically calculates an appropriate slippage tolerance based on market conditions. This is recommended for most use cases.
Manual Slippage
When usingslippageMode: "manual", you must specify slippageBps. This gives you full control over slippage tolerance.
50= 0.5% slippage tolerance100= 1% slippage tolerance500= 5% slippage tolerance1000= 10% slippage tolerance
5. Swap Transaction Details
When you create a swap transaction, you receive:- transaction: A
VersionedTransactionready to be signed and sent - computeUnitLimit: The compute unit limit for the transaction
- lastValidBlockHeight: The last valid block height for the transaction
- prioritizationFeeLamports: The prioritization fee in lamports
6. Running the Script
To execute a swap, edit the script with your token mint addresses and amount:- Set
INPUT_MINTto the token you want to swap from - Set
OUTPUT_MINTto the token you want to swap to - Set
AMOUNTto the amount in the token’s smallest unit (consider token decimals)
7. Getting a Quote Only
If you just want to check a quote without executing a swap:Alternative: Using the Bags CLI
This section requires the Bags CLI. See Install and Set Up the Bags CLI to get started.
--json to get machine-readable output for scripting.
8. Error Handling
The script includes comprehensive error handling for:- Invalid Token Mints: Ensure the mint addresses are valid Solana public keys
- Insufficient Liquidity: The quote may fail if there’s not enough liquidity for the swap
- Invalid Amount: The amount must be a positive number
- Slippage Errors: If using manual slippage, ensure
slippageBpsis between 0 and 10000 - Transaction Failures: Network issues or insufficient SOL for fees
9. Troubleshooting
Common issues include:- No Quote Available: Check that both tokens have sufficient liquidity and are tradeable
- High Price Impact: Large swaps may have high price impact. Consider splitting into smaller swaps
- Insufficient SOL: Your wallet needs SOL for transaction fees
- Invalid Amount: Make sure the amount is in the token’s smallest unit (not in human-readable format)
