I’m currently working on implementing a swap function that exchanges 0.01 SOL for USDC using the Raydium SDK on the Solana mainnet with TypeScript. I’ve set up the environment, connection, and wallet, but I’m unsure how to proceed with the swap itself. Below is the code I’ve written so far.
import bs58 from 'bs58';
import dotenv from 'dotenv';
import { Liquidity } from '@raydium-io/raydium-sdk';
import { Connection, Keypair } from '@solana/web3.js';
// Load environment variables (RPC URL and private key from .env file)
dotenv.config();
// Create a connection to the Solana blockchain using the RPC URL from .env
const connection = new Connection(process.env.RPC_URL!, 'confirmed');
// Create a wallet using the private key stored in .env
const secretKey = bs58.decode(process.env.PRIVATE_KEY!);
const wallet = Keypair.fromSecretKey(secretKey);
// Log the wallet's public key to ensure the correct wallet is loaded
console.log("Wallet public key:", wallet.publicKey.toBase58());
// Swap configuration details
const swapConfig = {
tokenAAmount: 0.01, // Swap 0.01 SOL for USDC
tokenAAddress: "Ho2FQgg65oM1zpYuEnC8fULpBnWtqRCTrXRP56AeyCci", // SOL token address
tokenBAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC token address
maxLamports: 1000000, // Max lamports allowed for fees
direction: "in" as "in" | "out", // Swap direction: 'in' or 'out'
liquidityFile: "https://api.raydium.io/v2/sdk/liquidity/mainnet.json", // URL for Raydium liquidity info
maxRetries: 10 // Number of retries for failed swap attempts
};
Murodxon Ramazonov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.