SolanaPortal
  • ✨Welcome to SolanaPortal
  • Getting Started
    • ⭐Why SolanaPortal?
    • 📖Guide
    • 🗺️Best Practices
    • ❓FAQ
  • API Documentation
    • Swapping
      • Swapping with Node.js
      • Swapping with Python
      • Swapping with Rust
    • Token Creation
      • Pump.fun Token
      • Standard Token
  • Market Creation
  • ‼️Troubleshooting
  • Support
Powered by GitBook
On this page
  • Overview
  • Installing Prerequisites
  • Setting Up the Environment
  • Performing a Standard Token Swap
  • Performing a Jito Bundle Swap
  • Running the Code
  • Key Notes
  1. API Documentation
  2. Swapping

Swapping with Node.js

Overview

This guide provides a step-by-step explanation for using the SolanaPortal API to execute token swaps with Node.js. Whether you're performing a standard token swap or a more complex Jito bundle transaction, this tutorial walks you through the process on how to swap using Node.js. We'll break down everything from setting up your environment to sending transactions.

Installing Prerequisites

Before you begin, ensure the following:

  1. Node.js and npm installed:

Download and install Node.js from nodejs.org. Ensure you are using Node.js version 18 or later for native fetch support. Check your version with:

node -v                                  
  1. Private Key:

Obtain the private key for your Solana wallet (Phantom Wallet). Keep this key secure as it is required to sign transactions.

Setting Up the Environment

  1. Create a new directory for your project:

mkdir solana-swap && cd solana-swap
  1. Initialize a Node.js project:

npm init -y
  1. Create a new file named swap.js and open it in your code editor.

  2. Install the required libraries:

npm install @solana/web3.js bs58 node-fetch
  • @solana/web3.js: For interacting with the Solana blockchain.

  • bs58: For decoding wallet private keys.

  • node-fetch: For making HTTP requests (only needed if using Node.js versions prior to 18).

  1. Add the necessary imports or required libraries and initialize the wallet with your private key:

const { Keypair, VersionedTransaction } = require("@solana/web3.js");
const bs58 = require("bs58").default;

// Initialize Wallet
const privateKey = "your-private-key-here"; // Replace with your wallet's private key
const wallet = Keypair.fromSecretKey(bs58.decode(privateKey));

console.log("Wallet Address:", wallet.publicKey.toBase58());

Performing a Standard Token Swap

A standard token swap involves using a single wallet to trade one token on a supported decentralized exchange (DEX).

Full code example
const { Keypair, VersionedTransaction } = require("@solana/web3.js");
const bs58 = require("bs58").default;

const swap = async () => {
  try {
    // Initialize wallet
    const private_key = "your-private-key-here"; // Replace with your private key
    const wallet = Keypair.fromSecretKey(bs58.decode(private_key));
    const mint = "3jzdrXXKxwkBk82u2eCWASZLCKoZs1LQTg87HBEAmBJw"; // Replace with token mint address

    console.log("Wallet Address:", wallet.publicKey.toBase58());

    // Parameters for the swap
    const param = {
      wallet_address: wallet.publicKey.toBase58(), // Your wallet public key
      action: "buy", // "buy" or "sell"
      mint, // Mint address of the token to trade
      dex: "raydium", // Supported values: "raydium", "jupiter", "pumpfun", "moonshot"
      amount: 0.0001, // Amount of tokens to trade
      slippage: 100, // Maximum slippage allowed (in percentage)
      tip: 0.0001, // Priority fee
      type: "jito", // Use "jito" for prioritized execution
    };

    const url = "https://api.solanaportal.io/api/trading";

    // Send the POST request to the API
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(param),
    });

    if (response.status === 200) {
      // Successfully generated transaction
      const data = await response.json();
      const txnBuffer = Buffer.from(data, "base64");
      const txn = VersionedTransaction.deserialize(txnBuffer);

      // Sign the transaction
      txn.sign([wallet]);
      const signedTxnBuffer = bs58.encode(txn.serialize());

      // Broadcast the signed transaction
      const jitoResponse = await fetch(
        `https://tokyo.mainnet.block-engine.jito.wtf/api/v1/transactions`,
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({
            jsonrpc: "2.0",
            id: 1,
            method: "sendTransaction",
            params: [signedTxnBuffer],
          }),
        }
      );

      if (jitoResponse.status === 200) {
        const signature = (await jitoResponse.json()).result;
        console.log("Transaction succeeded:", `https://solscan.io/tx/${signature}`);
      } else {
        console.log("Transaction failed. Please check the parameters.");
      }
    } else {
      console.error("API Error:", response.statusText);
    }
  } catch (error) {
    console.error("Error during swap:", error.message);
  }
};

// Run the function
swap();

Performing a Jito Bundle Swap

For Jito bundles, you can batch multiple swaps into a single transaction. Each swap must have its own parameters, and you can use one or more wallets.

A single failed transaction in a Jito Bundle swap will cause the entire bundle to fail. Ensure all parameters and wallets are correctly configured to avoid issues

Full code example
const { Keypair, VersionedTransaction } = require("@solana/web3.js");
const bs58 = require("bs58").default;

const testJitoBundleAPI = async () => {
  try {
    const wallets = [
      Keypair.fromSecretKey(bs58.decode("private key 1")),
      Keypair.fromSecretKey(bs58.decode("private key 2")),
      Keypair.fromSecretKey(bs58.decode("private key 3")),
      Keypair.fromSecretKey(bs58.decode("private key 4")),
    ];

    const param = [
      {
        wallet_address: wallets[0].publicKey.toBase58(),
        mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        action: "sell",
        dex: "raydium",
        amount: 0.01,
        tip: 0.0001,
      },
      {
        wallet_address: wallets[1].publicKey.toBase58(),
        mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        action: "buy",
        dex: "raydium",
        tip: 0.0001,
        amount: 0.0001,
      },
      {
        wallet_address: wallets[2].publicKey.toBase58(),
        mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        action: "buy",
        dex: "raydium",
        amount: 0.0001,
      },
      {
        wallet_address: wallets[3].publicKey.toBase58(),
        mint: "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
        action: "buy",
        dex: "raydium",
        amount: 0.0001,
      },
    ];

    const url = "https://api.solanaportal.io/api/jito-bundle";
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(param),
    });


    if (response.status === 200) {
      const data = await response.json();


      const encodedSignedTxns = [];
      const signatures = [];

      for (let i = 0; i < data.length; i++) {
        const txnBuffer = Buffer.from(data[i], "base64");
        const txn = VersionedTransaction.deserialize(txnBuffer);
        txn.sign([wallets[i]]);
        signatures.push(bs58.encode(txn.signatures[0]));
        const signedTxnBuffer = txn.serialize();
        encodedSignedTxns.push(bs58.encode(signedTxnBuffer));
      }


      try {
        const jitoResponse = await fetch(
          "https://tokyo.mainnet.block-engine.jito.wtf/api/v1/bundles",
          {
            method: "POST",
            headers: {
              "Content-Type": "application/json",
            },
            body: JSON.stringify({
              jsonrpc: "2.0",
              id: 1,
              method: "sendBundle",
              params: [encodedSignedTxns],
            }),
          }
        );


        if (jitoResponse.status === 200) {
          for (let i = 0; i < signatures.length; i++) {
            console.log(
              `Transaction ${i}: https://solscan.io/tx/${signatures[i]}`
            );
          }
        } else {
          console.log("Jito Error Response:", await jitoResponse.text());
        }
      } catch (e) {
        console.error("Error during Jito submission:", e.message);
      }
    } else {
      const errorText = await response.text();
      console.error("Error from API:", response.statusText, errorText);
    }
  } catch (e) {
    console.error("Unexpected error:", e.message);
  }
};

testJitoBundleAPI();

```

Running the Code

To run the code, follow these steps:

  1. Save the code in a file named swap.js inside your project directory.

  2. Run the file using Node.js:

node swap.js

Ensure your Node.js version is 18 or later for native fetch support. If using an earlier version, ensure node-fetch is installed and imported.

Key Notes

  1. Environment Setup: Ensure you are connected to the Solana mainnet.

  2. Security: Never hardcode sensitive information like private keys in production code. Use environment variables or secret management tools.

  3. Error Handling: Always validate API responses and handle errors gracefully.

To learn how to implement swaps programmatically, visit the language-specific guides:

PreviousSwappingNextSwapping with Python

Last updated 16 days ago

Swapping with Python
Swapping with Rust