chainstacklabs / raydium-sdk-swap-example-typescript

An example to swap tokens on Solana using the Raydium SDK, TypeScript, and Chainstack
MIT License
119 stars 39 forks source link
chainstack raydium solana swap typescript
Labs

Chainstack is the leading suite of services connecting developers with Web3 infrastructure

         

Supported protocolsChainstack blogChainstack docsBlockchain API referenceStart for free

TLDR quick run

Download the latest Raydium mainnet.json to the project root (it's a ~500 MB file):

wget https://api.raydium.io/v2/sdk/liquidity/mainnet.json

Set the tokenA and tokenB in src/swapConfig.ts.

Now that you have the the 500 MB mainnet.json that has the entrirety of info on liquidity pairs, and you have the correct pairs set in swapConfig.ts, you want to trim the mainnet.json file to have only the necessary liquidity info pertaining to your tokenA & tokenB. So run:

ts-node src/trimMainnet.ts

This will produce src/trimmed_mainnet.json that takes less than a second to load vs minutes for mainnet.json.

Make sure you have the Chainstack node & your private key set in .env. Make sure you have all dependencies installed with yarn.

Run the swap:

yarn swap

Raydium SDK Swap Example

This project demonstrates how to perform a token swap on the Solana blockchain using Raydium and Chainstack. The example specifically illustrates swapping SOL (native Solana token) for USDC (a stablecoin).

Find the full guide on the Chainstack Developer Portal.

Shoutout to precious-void for the the base code used for this project!

Features

Prerequisites

Before you begin, ensure you have met the following requirements:

Chainstack Solana node

Deploy a Solana node on Chainstack; the following steps will guide you:

  1. Sign up with Chainstack.
  2. Deploy a node.
  3. View node access and credentials.

Environment variables

Add your RPC endoint and private key to a .env file:

RPC_URL=YOUR_RPC_URL
WALLET_PRIVATE_KEY=YOUR_PRIVATE_KEY

Installation

Clone the repository locally and install the dependencies:

git clone https://github.com/soos3d/raydium-sdk-swap-example.git
cd raydium-sdk-swap-example
yarn

Usage

Edit the configuration in src/swapConfig.ts editing:

export const swapConfig = {
  executeSwap: false, // Send tx when true, simulate tx when false
  useVersionedTransaction: true,
  tokenAAmount: 0.01, // Swap 0.01 SOL for USDT in this example
  tokenAAddress: "So11111111111111111111111111111111111111112", // Token to swap for the other, SOL in this case
  tokenBAddress: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC 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",
  maxRetries: 10
};

Then run:

yarn swap