How to Build a Solana Sniper Bot (Complete Guide with Code)Introduction to Solana Sniper Bots
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.Understanding the BasicsWhat is a sniper bot on Solana?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.Key Variants of Solana trading bots.Solana sniper bot code: Custom-built scripts that developers can run using Node.js and Solana Web3 libraries.Pumpfun sniper bot: Specifically designed to snipe tokens the moment they go live on Pumpfun.Raydium sniper bot: Targets liquidity events on Raydium's AMM or CLMM pools.Solana liquidity sniper: Monitors all liquidity events across the chain, not tied to a specific platform.Solana memecoin bot: Optimized for fast-entry trades on low-cap meme tokens.Solana trading bot: Broader than sniping, it handles full buy/sell logic, often including stop-loss and take-profit setups.Why Use Sniper Bots on SolanaIf 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.Common Use CasesToken LaunchesSay a new meme coin drops on PumpFun. Within seconds of liquidity being added, prices can jump 2x or more. A sniper bot lets you detect the pool creation and buy before the masses.Early-Stage SpeculationSome traders monitor wallets of known devs or influencers. If a known wallet creates a pool, the bot buys immediately, before the token appears on aggregators like Birdeye or Dexscreener.Community Alpha PlaysYou're in a private alpha group. Someone posts a contract address. Your bot is hooked to Telegram or Discord and instantly buys based on that input.Low Liquidity MonitoringSometimes devs quietly add small liquidity to test their token. A bot can watch for this pattern like pools created with just 0.5 SOL and get in before announcements go live.Re-entry on RelaunchesIf a token rug pulls and relaunches, some bots monitor the same dev wallet or reuse of token metadata. They auto-buy the "second chance" version before hype catches upRisks & Legal ConsiderationsSniper bots give you speed, but they come with serious technical and legal risks.Rug Pulls & HoneypotsMany tokens launched on Solana DEXs are scams. Some prevent selling after buying (honeypots). Others drain liquidity right after launch. Without proper filters, your bot becomes easy prey.False PositivesBots can misfire on low-liquidity or bait pools. If your logic isn't strict,checking metadata, LP amount, token supply - you'll waste funds or get stuck in illiquid tokens.Front-RunningCompeting bots are monitoring the same logs. Your transaction might get front-run or stuck in a failed block. You need good RPCs, retries, and priority fee strategies.Wallet Drain RisksStoring private keys in.env files on a VPS without protection? That's asking for trouble. A single server compromise can drain your wallet.Legal Grey AreasDepending on your country, automated trading, especially around token launches might fall into regulatory gray zones. Some jurisdictions treat this as front-running or market manipulation.Treat your sniper bot as a serious software considering all the legal aspects.PrerequisitesBefore starting, make sure you have the following in place:Development Environment: Install Node.js, npm, and the Solana CLI.Solana Wallet: Create a wallet using Phantom, Sollet, or any compatible wallet.RPC Endpoint: Get access to a Solana RPC endpoint to communicate with the blockchain.Basic Knowledge of JavaScript: The bot will be written in JavaScript, so some familiarity is needed.You may also like |
How to Build a Grid Trading Bot | A Step-by-Step GuideStep 1: Setting Up the ProjectStart by creating a new Node.js project:mkdir solana-sniper-bot
cd solana-sniper-bot
npm init -yThen, install the necessary packages:npm i @raydium-io/raydium-sdk-v2 @solana/web3.js axios bn.js bs58Step 2: Setting Up Environment VariablesCreate 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.comStep 3: Create the CLMM Pool ListenerThis 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.03Also, Read |
Understanding the Impact of AI Crypto Trading BotsStep 4: Create the Buy Function (Auto Swap)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}`)
}Step 5: Listen for New Pools and Trigger Swaplet 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.Step 6: Testing the BotBefore 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.comAlso, Explore |
How To Create My Scalping Bot UsingNode.jsStep 7: Deployment and SecurityOnce the bot is ready, deploy it to a secure server:Use a VPS to ensure the bot runs continuously with minimal downtime.Secure Your Private Key: Always use environment variables or a secure vault service to store sensitive information.Real-World OptimizationsOnce 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.Filtering Bad Tokens (Pre-Buy Checks)Minimum Liquidity ThresholdAvoid 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;Token Metadata ValidationCheck 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;Token BlacklistMaintain a list of known scam tokens or deployers and skip them instantly.if (BLACKLIST.includes(targetMint)) return;Optional: Simulate Swap or Check RouteUsesimulateTransaction() to preview the swap or query a route via Jupiter. If it fails or no route exists, don't buy.Delay-Based Decision MakingIntroduce 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.Using Multiple RPCs (Failover Strategy)RPC List ConfigurationSet up a list of RPC endpoints (e.g., Helius, Triton, QuickNode). Load them from.env or config file.const RPCS = [RPC1, RPC2, RPC3];Retry and Fallback MechanismIf 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;
}
}Logging and MonitoringEvent LoggingLog what matters: detected pools, attempted buys, successful swaps, token details.console.log(`[POOL] ${poolId} | Token: ${tokenMint}`);Error TrackingUsetry/catch around every major async operation and log failures with stack traces.console.error(`[ERROR] ${err.message}`);Optional IntegrationUse tools like:PM2 to auto-restart the bot on crashWinston for structured loggingCloud services like Logtail or Datadog for remote log collectionOptional: Sell Logic and Exit StrategyTake-Profit ThresholdSet a target percentage (e.g., 2x from entry) and auto-sell when the token reaches that price.if (currentPrice >= buyPrice * 2) {
await sell();
}Stop-Loss SetupProtect your downside. If price drops below a defined floor, exit.if (currentPrice <= buyPrice * 0.7) {
await sell();
}Time-Based ExitsIf the price doesn't move after a certain duration (e.g., 3 minutes), exit anyway to avoid being stuck.Future ExtensionsRe-entry after dipsMulti-wallet rotation for stealthDiscord/Telegram alert triggersToken sell simulation before actual sellThese 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.Troubleshooting & Common ErrorsBuilding 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:Bot doesn't detect new poolsIf 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 theconfirmed orfinalized commitment level—notprocessed, which can miss orphans.Transaction isn't sent or gets stuckThis typically means your RPC is rate-limited or too slow. Use a premium provider (Helius, Triton, QuickNode) and avoid free shared endpoints. Also, wrap yoursendTransaction logic with retry and timeout handling.Buy transaction fails or revertsMost 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.Private key or wallet errorsIf 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 usingbs58.decode() and test it with a small transfer.Bought tokens but can't sellThis is likely a honeypot. To avoid it, always validate:Token has a valid symbol and nameSufficient liquidity (avoid pools under 1 SOL)No known blacklist flags or scam patternsThe bot crashes randomlyUsetry/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 happensCheck if yourisProcessing 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.Official Solana & Raydium Docs
Solana Developer Docs – Core concepts, transaction structure, RPC methods, and program architecture.
Solana Cookbook – Developer-friendly guides for common Solana tasks.
Raydium SDK v2 – Reference for CLMM pool interaction, swap logic, and liquidity provisioning.ConclusionBuilding 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.