current location:Home >> Blockchain knowledge >> Solana: How to perform token swaps using the Raydium SDK

Solana: How to perform token swaps using the Raydium SDK

admin Blockchain knowledge 1056

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

  1. Solana: How to perform token swaps using the Raydium SDK

    Install required packages:

npm install @raydium-io/raydium-sdk @solana/web3.js
  1. 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

  1. Error Handling: Add proper error handling for failed transactions

  2. Wallet Management: In production, use a secure wallet provider like Phantom or Backpack

  3. RPC Selection: Choose a reliable RPC provider for better performance

  4. Slippage: Adjust slippage based on token volatility

  5. 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.

If you have any questions or uncertainties, please join the official Telegram group: https://t.me/GToken_EN

GTokenTool

GTokenTool is the most comprehensive one click coin issuance tool, supporting multiple public chains such as TON, SOL, BSC, etc. Function: Create tokensmarket value managementbatch airdropstoken pre-sales IDO、 Lockpledge mining, etc. Provide a visual interface that allows users to quickly create, deploy, and manage their own cryptocurrencies without writing code.

Similar recommendations