DEV Community

Cover image for Swap API (Pump.fun, Moonshot, Raydium, ...): Trade Any Token on Solana, Including Memecoins, in Your Code
D3sperado
D3sperado

Posted on • Edited on

Swap API (Pump.fun, Moonshot, Raydium, ...): Trade Any Token on Solana, Including Memecoins, in Your Code

Ever tried to buy a popular new meme coin on Solana only to discover that it is not listed on major exchanges? Perhaps you have a token from a smaller project and are unsure how to sell it. This article will teach you how to purchase and sell almost any token on Solana, including those from Moonshot, Pump.fun, Raydium, and Jupiter.

What We Are Doing

We'll use the SolXtence Swap API to perform token swaps on Solana. This API manages the intricate routing through numerous liquidity pools and AMMs, allowing you to swap between any two tokens with only a few lines of code.

Useful for

  • Trading bots
  • Sniper bots
  • Volume booster bots
  • DeFi applications
  • Wallet integrations

The Code
Here is a simple JavaScript example to execute a swap:

import {
  Connection,
  Keypair,
  Transaction,
  VersionedTransaction,
  sendAndConfirmTransaction,
} from "@solana/web3.js";
import axios from "axios";
import bs58 from "bs58";

async function performSwap() {
  // Initialize connection and keypair
  const connection = new Connection("https://api.mainnet-beta.solana.com");
  const keypair = Keypair.fromSecretKey(bs58.decode("YOUR_PRIVATE_KEY"));

  // Swap parameters
  const params = new URLSearchParams({
    from: "So11111111111111111111111111111111111111112", // SOL
    to: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v", // USDC
    amount: 0.5, // From amount
    slip: 10, // Slippage
    payer: keypair.publicKey.toBase58(),
    fee: 0.00009, // Priority fee
    txType: "v0", // Change to "legacy" for legacy transactions
  });

  try {
    // Get swap transaction
    const response = await axios.get(
      `https://swap.solxtence.com/swap?${params}`
    );
    const { serializedTx, txType } = response.data.transaction;

    // Fetch the latest blockhash
    const { blockhash } = await connection.getLatestBlockhash();

    // Deserialize and sign the transaction
    let transaction;
    if (txType === "v0") {
      transaction = VersionedTransaction.deserialize(
        Buffer.from(serializedTx, "base64")
      );
      transaction.message.recentBlockhash = blockhash;
      transaction.sign([keypair]);
    } else {
      transaction = Transaction.from(Buffer.from(serializedTx, "base64"));
      transaction.recentBlockhash = blockhash;
      transaction.sign(keypair);
    }

    // Send and confirm the transaction
    const signature = await sendAndConfirmTransaction(connection, transaction);
    console.log("Swap successful! Transaction signature:", signature);
  } catch (error) {
    console.error("Error performing swap:", error);
  }
}

performSwap();
Enter fullscreen mode Exit fullscreen mode

Code Explanation
This script demonstrates how to swap SOL for USDC on the Solana blockchain. If you wanted to sell USDC instead, you’d simply swap the ‘from’ and ‘to’ token addresses in the parameters.

Let’s break down the key parts:

  1. Setup: We import necessary modules and initialize a connection to Solana’s mainnet. We also create a keypair from a private key (replace ‘YOUR_PRIVATE_KEY’ with your actual key).

  2. Swap Parameters: We set up parameters for the swap, including:
    — ‘from’ and ‘to’ token addresses (SOL and USDC in this case)
    — Amount to swap
    — Slippage tolerance
    — Payer’s public key
    — Priority fee
    — Transaction type (versioned or legacy)

  3. API Call: We make a GET request to the SolXtence Swap API with our parameters. This returns a serialized transaction.

  4. Transaction Handling: Depending on the transaction type (v0 or legacy), we deserialize the transaction differently. We then update it with the latest blockhash and sign it with our keypair.

  5. Execution: Finally, we send and confirm the transaction on the Solana network.

Remember to handle your private keys securely and never expose them in your code, especially in production environments.

Understanding Token Swaps
On Solana, there is no direct “buy” or “sell”; instead, you exchange one token for another. For example, if you want to buy USDC with SOL, you are essentially exchanging SOL for USDC. The same idea applies when you wish to “sell” — you just exchange back to SOL or another token.
This swap mechanism allows you to trade any token pair as long as liquidity exists in the Solana ecosystem. The SolXtence API determines the optimum path for your swap, whether it is via Moonshot, Pump.fun, Raydium, Jupiter, or a combination of these.

Resources
Want to go deeper or see more examples? Check out the following resources:

GitHub Repo
SolXtence Swap API Docs

With these tools, you may now trade any token on Solana. Happy trading!

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.