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:
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
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
Create a new directory for your project:
mkdir solana-swap && cd solana-swap
Initialize a Node.js project:
npm init -y
Create a new file named swap.js and open it in your code editor.
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).
Add the necessary imports or required libraries and initialize the wallet with your private key:
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