Token Swapping Tutorial

Learn how to swap tokens using the Saros SDK with this comprehensive step-by-step guide.

Overview

This tutorial will guide you through the process of swapping tokens using the Saros SDK. We'll cover everything from setting up your environment to executing a real token swap on the Solana blockchain.

30 min
Estimated Time
Intermediate
Difficulty
Solana
Blockchain

1. Prerequisites

Before starting this tutorial, ensure you have the following:

  • Node.js 16+ and npm/yarn installed
  • Basic knowledge of TypeScript/JavaScript
  • A Solana wallet with some SOL for transaction fees
  • Token accounts for the tokens you want to swap
Install Dependencies
// Install the required packages
npm install @saros-finance/sdk @solana/web3.js

// Import the necessary modules
import { getSwapAmountSaros, swapSaros, genConnectionSolana } from '@saros-finance/sdk';
import { PublicKey } from '@solana/web3.js';

2. Set up Connection

First, we need to establish a connection to the Solana network and configure our wallet.

Connection Setup
// Generate a connection to the Solana network
const connection = genConnectionSolana();

// Define your wallet address (in a real app, this would come from a connected wallet)
const accountSol = 'YOUR_WALLET_PUBLIC_KEY';

// Define the payer account object
const payerAccount = { publicKey: new PublicKey(accountSol) };

3. Configure Tokens

Define the tokens you want to swap, including their mint addresses and SPL token accounts.

Token Configuration
// Configure the tokens you want to swap
// Example: Swapping C98 for USDC

const USDC_TOKEN = {
  id: 'usd-coin',
  mintAddress: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  symbol: 'usdc',
  name: 'USD Coin',
  decimals: '6',
  addressSPL: 'FXRiEosEvHnpc3XZY1NS7an2PB1SunnYW1f5zppYhXb3',
};

const C98_TOKEN = {
  id: 'coin98',
  mintAddress: 'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
  symbol: 'C98',
  name: 'Coin98',
  decimals: '6',
  addressSPL: 'EKCdCBjfQ6t5FBfDC2zvmr27PgfVVZU37C8LUE4UenKb',
};

4. Configure Pool

Set up the pool parameters for the swap. You'll need to know the pool address and token information.

Pool Configuration
// Configure the pool parameters
const poolParams = {
  address: '2wUvdZA8ZsY714Y5wUL9fkFmupJGGwzui2N74zqJWgty',
  tokens: {
    C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9: {
      ...C98_TOKEN,
    },
    EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v: {
      ...USDC_TOKEN,
    },
  },
  tokenIds: [
    'C98A4nkJXhpVZNAZdHUA95RpTF3T4whtQubL3YobiUX9',
    'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
  ],
};

5. Get Swap Quote

Before executing a swap, get a quote to see the expected output amount and price impact.

Get Swap Quote
// Get a quote for the swap
const fromTokenAccount = C98_TOKEN.addressSPL;
const toTokenAccount = USDC_TOKEN.addressSPL;
const fromMint = C98_TOKEN.mintAddress;
const toMint = USDC_TOKEN.mintAddress;
const fromAmount = 1; // 1 C98
const SLIPPAGE = 0.5; // 0.5% slippage tolerance

// Get swap quote
const estSwap = await getSwapAmountSaros(
  connection,
  fromMint,
  toMint,
  fromAmount,
  SLIPPAGE,
  poolParams
);

console.log('Estimated swap:', estSwap);

6. Execute Swap

Finally, execute the swap transaction with the parameters from the quote.

Execute Swap
// Execute the swap
const { amountOutWithSlippage } = estSwap;

const result = await swapSaros(
  connection,
  fromTokenAccount.toString(),
  toTokenAccount.toString(),
  parseFloat(fromAmount),
  parseFloat(amountOutWithSlippage),
  null, // referral account (optional)
  new PublicKey(poolParams.address),
  new PublicKey('SSwapUtytfBdBn1b9NUGG6foMVPtcWgpRU32HToDUZr'), // Program address
  accountSol,
  fromMint,
  toMint
);

// Handle the result
if (result.isError) {
  console.log(`Swap failed: ${result.mess}`);
} else {
  console.log(`Swap successful! Transaction hash: ${result.hash}`);
}
Understanding the Swap Process
1. Get Quote: We call getSwapAmountSaros to calculate the expected output amount and apply slippage protection.
2. Execute Swap: We use swapSaros to perform the actual token exchange on-chain.
3. Handle Result: The function returns a result object with transaction hash or error information.
📚 Next Steps
Continue learning with these related tutorials
💡 Key Takeaways
Wallet Connection: In a real application, you'll need to connect a wallet like Phantom to get the user's public key.
Token Accounts: Ensure you have valid SPL token accounts for both the input and output tokens.
Slippage Protection: Always use slippage protection to prevent unfavorable trades due to price changes.
Error Handling: Implement proper error handling to manage transaction failures gracefully.
Network Configuration: Use the correct RPC endpoints for devnet, testnet, or mainnet depending on your environment.