Raydium is a popular Automated Market Maker (AMM) on Solana that provides an SDK for performing token swaps programmatically. Here's how to use the Raydium SDK to execute token swaps:
Prerequisites

Install required packages:
npm install @raydium-io/raydium-sdk @solana/web3.js
You'll need:
A Solana wallet with SOL and tokens
Connection to a Solana RPC endpoint
Basic Swap Implementation
import { Connection, Keypair, PublicKey } from '@solana/web3.js';
import {
swap,
Liquidity,
Token,
TokenAmount,
Percent,
} from '@raydium-io/raydium-sdk';
async function performSwap() {
// 1. Establish connection
const connection = new Connection('https://api.mainnet-beta.solana.com');
// 2. Define wallet (in production, use a secure method to load your keypair)
const wallet = Keypair.generate(); // Replace with your actual wallet
// 3. Define tokens (example: SOL to USDC)
const SOL = new Token(
'So11111111111111111111111111111111111111112',
9,
'SOL',
'SOL'
);
const USDC = new Token(
'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
6,
'USDC',
'USDC'
);
// 4. Define swap parameters
const inputToken = SOL;
const outputToken = USDC;
const inputAmount = new TokenAmount(inputToken, 0.1 * 10 ** inputToken.decimals); // 0.1 SOL
const slippage = new Percent(1, 100); // 1% slippage
// 5. Get pool info
const poolInfo = await Liquidity.fetchInfo({
connection,
poolKeys: await Liquidity.getAssociatedPoolKeys({
version: 4, // Raydium v4
marketVersion: 3,
baseMint: inputToken.mint,
quoteMint: outputToken.mint,
}),
});
// 6. Calculate swap quote
const { amountOut, minAmountOut } = await swap.computeAmountOut({
poolInfo,
amountIn: inputAmount,
currencyOut: outputToken,
slippage,
});
console.log(`Expected to receive: ${amountOut.toFixed()} ${outputToken.symbol}`);
console.log(`Minimum after slippage: ${minAmountOut.toFixed()} ${outputToken.symbol}`);
// 7. Execute swap
const { txids } = await swap({
connection,
poolInfo,
userKeys: {
owner: wallet.publicKey,
payer: wallet.publicKey,
},
amountIn: inputAmount,
amountOut: minAmountOut,
fixedSide: 'in', // fixed input amount
});
console.log('Swap transaction IDs:', txids);
}
performSwap().catch(console.error);Key Considerations
Error Handling: Add proper error handling for failed transactions
Wallet Management: In production, use a secure wallet provider like Phantom or Backpack
RPC Selection: Choose a reliable RPC provider for better performance
Slippage: Adjust slippage based on token volatility
Versioning: Raydium has different pool versions - ensure you're using the correct one
Advanced Features
Price Impact Calculation: Check price impact before executing large swaps
Route Optimization: For better prices, consider splitting swaps across multiple pools
Jupiter Integration: For complex swaps, you might want to use Jupiter's API which aggregates across multiple DEXs including Raydium
Resources
Remember to test your implementation with small amounts first and handle all edge cases appropriately.
