29th August 2024
44 min read
Solana is widely used for building decentralized applications due to its high transaction throughput, low fees, and fast finality. These features make it a suitable platform for real-time, automation-driven tools like Solana sniper bots, crypto sniper bots, and Solana dex bots.
A Solana sniper bot is designed to monitor the blockchain and automatically execute token purchases the moment liquidity is added to a decentralized exchange (DEX). This is especially valuable during new token launches or other time-sensitive events, where timing can significantly impact outcomes.
This guide provides a step-by-step walkthrough for building a Solana token sniping tool, with a focus on Raydium's CLMM (Concentrated Liquidity Market Maker) pools. It covers key setup steps, core logic, and best practices for handling transactions efficiently and securely.
A sniper bot on Solana is a tool that automatically buys tokens as soon as they become available on a decentralized exchange (DEX), such as Raydium, PumpFun, Jupiter, or Orca.
To build a robust sniper bot, you need to understand Solana's ecosystem, including its RPC (Remote Procedure Call) API, smart contracts (also known as programs), and key technical components such as transactions and signatures.
If you've ever tried to manually buy a newly launched token on Solana, you know how fast things move by the time you've clicked "confirm", the price may have already pumped or the liquidity is gone. Sniper bots solve that.
They monitor the blockchain in real time and execute a trade the instant liquidity is added to a token. No hesitation. No manual steps. This gives you a massive edge in early-stage opportunities like token launches, meme coin listings, or NFT-associated tokens.
Solana is especially suited for sniper bots because of its high throughput, sub-second finality, and near-zero transaction fees. You can scan logs, catch pool creation events, and trigger swaps within milliseconds without breaking the bank.
Whether you're a solo trader, bot developer, or automating a crypto strategy, sniper bots give you precision timing in a market where seconds mean everything.
Sniper bots give you speed, but they come with serious technical and legal risks.
Treat your sniper bot as a serious software considering all the legal aspects.
Before starting, make sure you have the following in place:
You may also like | How to Build a Grid Trading Bot | A Step-by-Step Guide
Start by creating a new Node.js project:
mkdir solana-sniper-bot
cd solana-sniper-bot
npm init -y
Then, install the necessary packages:
npm i @raydium-io/raydium-sdk-v2 @solana/web3.js axios bn.js bs58
Create a .env file in the project root to store sensitive information, such as your private key and RPC endpoint:
PRIVATE_KEY=your_private_key_here
SOL_RPC=https://api.mainnet-beta.solana.com
This script listens to the Raydium CLMM program logs and detects when a new pool is created.
// index.js
import {
Raydium,
PoolUtils,
TxVersion,
} from '@raydium-io/raydium-sdk-v2'
import {
Connection,
PublicKey,
Keypair,
} from '@solana/web3.js'
import bs58 from 'bs58'
import BN from 'bn.js'
import 'dotenv/config'
// === CONFIG ===
const RPC_URL = process.env.SOL_RPC
const secretKey = bs58.decode(process.env.PRIVATE_KEY)
const wallet = Keypair.fromSecretKey(secretKey)
const connection = new Connection(RPC_URL, { commitment: 'confirmed' })
const SOL_MINT = 'So11111111111111111111111111111111111111112'
const CLMM_PROGRAM_ID = 'CAMMCzo5YL8w4VFF8KVHrK22GGUsp5VTaW7grrKgrWqK'
const BUY_AMOUNT_SOL = 0.01
const SLIPPAGE = 0.03
Also, Read | Understanding the Impact of AI Crypto Trading Bots
async function buyWithClmm(poolId, tokenMint) {
const raydium = await Raydium.load({ connection, owner: wallet })
const Pooldata = await raydium.clmm.getPoolInfoFromRpc(poolId)
const poolInfo = Pooldata.poolInfo
const poolKeys = Pooldata.poolKeys
const clmmPoolInfo = Pooldata.computePoolInfo
const tickCache = Pooldata.tickData
const baseIn = tokenMint === poolInfo.mintA.address
const inputAmount = new BN(Math.floor(BUY_AMOUNT_SOL * 1e9))
const { minAmountOut, remainingAccounts } = PoolUtils.computeAmountOutFormat({
poolInfo: clmmPoolInfo,
tickArrayCache: tickCache[poolId],
amountIn: inputAmount,
tokenOut: poolInfo[baseIn ? 'mintB' : 'mintA'],
slippage: SLIPPAGE,
epochInfo: await raydium.fetchEpochInfo(),
})
const { execute, transaction } = await raydium.clmm.swap({
poolInfo,
poolKeys,
inputMint: poolInfo[baseIn ? 'mintA' : 'mintB'].address,
amountIn: inputAmount,
amountOutMin: minAmountOut.amount.raw,
observationId: clmmPoolInfo.observationId,
ownerInfo: { useSOLBalance: true },
remainingAccounts,
txVersion: TxVersion.V0,
})
console.log('ðŸ" Transaction prepared. Executing swap...', transaction)
const { txId } = await execute()
console.log(`âœ"¦ Swap executed: https://explorer.solana.com/tx/${txId}`)
}
let isProcessing = false;
async function listenForNewPools() {
console.log('🚀 Listening for new Raydium CLMM pools...')
connection.onLogs(
new PublicKey(CLMM_PROGRAM_ID),
async (logInfo) => {
if (isProcessing) return
isProcessing = true
try {
const { signature, logs } = logInfo
if (!logs.some(log => log.includes('CreatePool'))) {
isProcessing = false
return
}
const tx = await connection.getParsedTransaction(signature, {
maxSupportedTransactionVersion: 0,
})
if (!tx) {
isProcessing = false
return
}
for (const ix of tx.transaction.message.instructions) {
if (
ix.programId?.toBase58?.() === CLMM_PROGRAM_ID &&
ix.accounts?.length >= 5
) {
const accounts = ix.accounts.map((a) => a.toBase58())
const tokenA = accounts[3]
const tokenB = accounts[4]
const poolId = accounts[0]
let targetMint = null
if (tokenA === SOL_MINT) targetMint = tokenB
else if (tokenB === SOL_MINT) targetMint = tokenA
else {
console.log('⠌ Skipping non-SOL pair')
continue
}
console.log('ðŸ" "¢ New CLMM pool found! Token:', targetMint)
await buyWithClmm(poolId, targetMint)
break
}
}
} catch (err) {
console.warn('âš ï ¸ Error:', err.message)
}
isProcessing = false
},
'confirmed'
)
}
listenForNewPools()
For further reference, explore the Raydium SDK V2 Demo.
Before deploying your bot on the mainnet, it's crucial to test it thoroughly on Solana's devnet. Modify your .env file to use the devnet RPC endpoint:
SOL_RPC=https://api.devnet.solana.com
Also, Explore | How To Create My Scalping Bot Using Node.js
Once the bot is ready, deploy it to a secure server:
Once your sniper bot is functional, it's not ready yet. Real-world trading on Solana is messy. You're racing against other bots, navigating scam tokens, and reacting to volatile conditions. This section covers the essential optimizations to make your bot safer, smarter, and more reliable.
Avoid pools with low initial liquidity. Rugs often launch with under 1 SOL to bait bots. Set a minimum liquidity requirement before proceeding with any buy logic.
if (poolLiquidityInSol < 1) return;
Check that the token has a valid symbol, name, and decimal count. Tokens with missing or weird metadata are red flags.
if (!tokenMeta.symbol || tokenMeta.symbol.length > 10) return;
Maintain a list of known scam tokens or deployers and skip them instantly.
if (BLACKLIST.includes(targetMint)) return;
Use simulateTransaction() to preview the swap or query a route via Jupiter. If it fails or no route exists, don't buy.
Introduce a short delay (e.g., 2-5 seconds) after pool creation. This gives time to detect sketchy behavior like immediate liquidity removal or fake metadata updates.
Set up a list of RPC endpoints (e.g., Helius, Triton, QuickNode). Load them from .env or config file.
const RPCS = [RPC1, RPC2, RPC3];
If one RPC fails, retry with another. Rotate through the list to maintain uptime and reduce failure points.
for (const rpc of RPCS) {
try {
const conn = new Connection(rpc);
// test or send tx
break;
} catch (err) {
continue;
}
}
Log what matters: detected pools, attempted buys, successful swaps, token details.
console.log(`[POOL] ${poolId} | Token: ${tokenMint}`);
Use try/catch around every major async operation and log failures with stack traces.
console.error(`[ERROR] ${err.message}`);
Use tools like:
Set a target percentage (e.g., 2x from entry) and auto-sell when the token reaches that price.
if (currentPrice >= buyPrice * 2) {
await sell();
}
Protect your downside. If price drops below a defined floor, exit.
if (currentPrice <= buyPrice * 0.7) {
await sell();
}
If the price doesn't move after a certain duration (e.g., 3 minutes), exit anyway to avoid being stuck.
Future Extensions
These optimizations turn your bot from a proof-of-concept into something stable and reliable in real conditions. You don't need them all on day one"”but without them, you're flying blind.
Building a sniper bot is one part logic, one part infrastructure. Once you go live, unexpected failures are common. Here's what usually goes wrong"”and how to fix it without guessing:
If the bot isn't picking up events, double-check you're subscribed to the correct program ID (e.g. Raydium CLMM). Also verify you're using the confirmed or finalized commitment level"”not processed, which can miss orphans.
This typically means your RPC is rate-limited or too slow. Use a premium provider (Helius, Triton, QuickNode) and avoid free shared endpoints. Also, wrap your sendTransaction logic with retry and timeout handling.
Most often caused by too-tight slippage, incorrect token metadata, or race conditions where the pool state changes before execution. Validate slippage settings and simulate trades with mock inputs before going live.
If the script throws on wallet load, your key may be malformed or improperly encoded. Ensure it's base58 and single-line (no [] or extra JSON formatting). Load it using bs58.decode() and test it with a small transfer.
This is likely a honeypot. To avoid it, always validate:
The bot crashes randomly
Use try/catch blocks around all async calls"”especially in listeners. Log every error. Run the bot with a process manager like PM2 or Docker health checks so it auto-restarts on failures.
Logs show "CreatePool" but no buy happens
Check if your isProcessing flag is stuck or the transaction failed silently. Add more detailed logging per step, and track execution time for each transaction to find where it stalls.
Building a sniper bot on Solana requires a solid grasp of how the blockchain works, especially its transaction model, smart contract architecture (programs), and RPC interactions. This guide walked through each step: from setting up the environment, listening to liquidity events, executing token swaps, and handling real-time conditions.
Before moving to mainnet, it's essential to thoroughly test your bot on devnet. This helps catch logic errors, slippage issues, or RPC failures without risking real assets. Always secure your wallet keys and credentials using proper secret management practices.
With proper filtering, real-time logging, and infrastructure improvements, this bot can become a reliable component in automated crypto trading workflows. Whether you're experimenting, building trading tools, or exploring automation at scale, Solana provides the speed and flexibility needed to execute on-chain trades with minimal delay.