> ## Documentation Index
> Fetch the complete documentation index at: https://docs.chainstack.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Solana: How to perform token swaps using Raydium

> Swap tokens on Solana with Raydium's Trade API and Chainstack in TypeScript — get a quote, set priority fees, then build, sign, and send a SOL to USDC swap with versioned transactions.

<Frame>
  <iframe width="100%" height="420" src="https://www.youtube.com/embed/NT-oYdV67u4" title="Token swaps with Raydium SDK on Solana" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" referrerpolicy="strict-origin-when-cross-origin" allowfullscreen />
</Frame>

**TLDR:**

* Raydium is a leading Solana AMM. Its hosted **Trade API** quotes and builds a swap for you, routing across Raydium's pool types (AMM v4, CPMM, CLMM) so you don't manage pool data yourself.
* The flow: fetch a priority fee, get a quote, build the transaction, then sign it with `@solana/web3.js` and send it through your own Solana node.
* This guide swaps SOL → USDC in TypeScript using a Chainstack Solana node for the broadcast.

<Warning>
  The old Raydium SDK v1 (`@raydium-io/raydium-sdk`) is end-of-life — its repository was archived in June 2025 and it never supported CPMM or CLMM pools. For new code, use the current [Trade API](https://docs.raydium.io/raydium/build/developer-guides/overview) shown here (simplest for a basic swap), or the [`@raydium-io/raydium-sdk-v2`](https://github.com/raydium-io/raydium-sdk-V2) library for on-chain control. The canonical examples are in [raydium-sdk-V2-demo](https://github.com/raydium-io/raydium-sdk-V2-demo).
</Warning>

## Main article

The Solana blockchain is at the forefront of DeFi, known for its speed and cost-efficiency. Central to this ecosystem is Raydium, an automated market maker (AMM) that provides deep liquidity across several pool types — legacy AMM v4, constant-product CPMM, and concentrated-liquidity CLMM.

You don't need to know which pool a pair trades in. Raydium's **Trade API** computes the best route across all of them, returns a quote, and builds a ready-to-sign transaction. This guide walks through a SOL → USDC swap in TypeScript, signing and broadcasting through a Chainstack Solana node.

## Prerequisites

### Deploy a Chainstack Solana node

Deploy a [Solana RPC endpoint on Chainstack](https://chainstack.com/build-better-with-solana/):

<CardGroup>
  <Card title="Sign up with Chainstack" href="https://console.chainstack.com/user/account/create" icon="angle-right" horizontal />

  <Card title="Deploy a node" href="/docs/manage-your-networks" icon="angle-right" horizontal />

  <Card title="View node access and credentials" href="/docs/manage-your-node#view-node-access-and-credentials" icon="angle-right" horizontal />
</CardGroup>

### Local setup

* [Node.js](https://nodejs.org/en/download/current) 18 or above (for the global `fetch` used below)
* A Solana wallet with some SOL to cover the swap and fees

Install the dependencies:

<CodeGroup>
  ```shell Shell theme={"system"}
  npm install @solana/web3.js bs58
  ```
</CodeGroup>

## Implementation

The Trade API exposes two hosts: `https://api-v3.raydium.io` for general data (including the priority-fee endpoint) and `https://transaction-v1.raydium.io` for the swap compute and build endpoints. The flow is fetch fee → quote → build → sign → send.

```typescript raydium_swap.ts theme={"system"}
import { Connection, Keypair, VersionedTransaction } from '@solana/web3.js'
import bs58 from 'bs58'

// Your Chainstack Solana node and wallet
const RPC_ENDPOINT = 'YOUR_CHAINSTACK_SOLANA_NODE'
const PRIVATE_KEY = 'YOUR_PRIVATE_KEY' // base58-encoded

const SWAP_HOST = 'https://transaction-v1.raydium.io'
const BASE_HOST = 'https://api-v3.raydium.io'

const INPUT_MINT = 'So11111111111111111111111111111111111111112'  // SOL
const OUTPUT_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v' // USDC
const AMOUNT = 1_000_000   // 0.001 SOL, in lamports
const SLIPPAGE_BPS = 50    // 0.5%
const TX_VERSION = 'V0'

async function swap() {
  const connection = new Connection(RPC_ENDPOINT, 'confirmed')
  const wallet = Keypair.fromSecretKey(bs58.decode(PRIVATE_KEY))

  // 1) Priority fee tiers from Raydium (vh / h / m).
  const { data: fee } = await (await fetch(`${BASE_HOST}/main/auto-fee`)).json()
  const computeUnitPriceMicroLamports = String(fee.default.h) // 'h' = high tier

  // 2) Quote — Raydium routes across its pool types for you.
  const swapResponse = await (
    await fetch(
      `${SWAP_HOST}/compute/swap-base-in?inputMint=${INPUT_MINT}&outputMint=${OUTPUT_MINT}` +
        `&amount=${AMOUNT}&slippageBps=${SLIPPAGE_BPS}&txVersion=${TX_VERSION}`,
    )
  ).json()
  console.log(`Quote: ${AMOUNT} -> ${swapResponse.data.outputAmount} (out)`)

  // 3) Build the swap transaction. wrapSol because the input is native SOL.
  const { data: txs } = await (
    await fetch(`${SWAP_HOST}/transaction/swap-base-in`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        computeUnitPriceMicroLamports,
        swapResponse,
        txVersion: TX_VERSION,
        wallet: wallet.publicKey.toBase58(),
        wrapSol: true,
        unwrapSol: false,
      }),
    })
  ).json()

  // 4) Deserialize, sign, and send each returned transaction through your node.
  for (const { transaction } of txs) {
    const tx = VersionedTransaction.deserialize(Buffer.from(transaction, 'base64'))
    tx.sign([wallet])
    const sig = await connection.sendRawTransaction(tx.serialize(), { skipPreflight: true })
    console.log(`Sent: https://solscan.io/tx/${sig}`)
  }
}

swap()
```

Run it with a TypeScript runner such as [`tsx`](https://www.npmjs.com/package/tsx):

<CodeGroup>
  ```shell Shell theme={"system"}
  npx tsx raydium_swap.ts
  ```
</CodeGroup>

### How it works

* **Priority fee.** `GET /main/auto-fee` returns suggested compute-unit prices in three tiers — `vh` (very high), `h` (high), and `m` (medium). Pass the chosen tier as `computeUnitPriceMicroLamports` in the build request; Raydium adds the compute-budget instructions for you.
* **Quote.** `GET /compute/swap-base-in` takes the input/output mints, the input `amount` (in the input token's smallest unit), and `slippageBps`. `swap-base-in` means you fix the input amount; use `swap-base-out` to fix the output amount instead. Raydium returns the best route and the expected `outputAmount`.
* **Build.** `POST /transaction/swap-base-in` returns one or more base64 transactions. Set `wrapSol: true` when the input is native SOL (it wraps to WSOL) and `unwrapSol: true` when the output is SOL. For SPL-to-SPL swaps, pass your input/output token account addresses.
* **Versioned transactions.** With `txVersion: 'V0'`, Raydium returns `VersionedTransaction`s; deserialize, sign, and broadcast each through your node. The build can return more than one transaction (for example, when an account needs to be created first), so loop over all of them.

<Note>
  For on-chain control instead of the hosted API — building the swap locally, managing pool state, or working with a specific pool — use [`@raydium-io/raydium-sdk-v2`](https://github.com/raydium-io/raydium-sdk-V2) and its `raydium.cpmm.swap` / `raydium.liquidity.swap` modules. See the [raydium-sdk-V2-demo](https://github.com/raydium-io/raydium-sdk-V2-demo) `src/api/swap.ts` (API path) and `src/cpmm/swap.ts` (on-chain path).
</Note>

## Conclusion

Raydium's Trade API gets you a working Solana swap with minimal code: it handles routing and pool selection, and hands you a transaction to sign and send through your own node. From here you can fix the output amount with `swap-base-out`, swap arbitrary SPL pairs by supplying token accounts, or drop down to `@raydium-io/raydium-sdk-v2` when you need on-chain control. Pair it with a Chainstack Solana node for reliable, low-latency broadcasting.
