facebook

How to Build a Solana Sniper Bot

Calender

29th August 2024

Clock

44 min read

Author
Ankit Mishra

Sr. Associate Consultant L2 - Development

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 Basics

 

What 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 Solana  

 

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.

 

Common Use Cases 

 

  • Token Launches Say 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 Speculation Some 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 Plays You'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 Monitoring Sometimes 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 Relaunches If 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 up

Risks & Legal Considerations

Sniper bots give you speed, but they come with serious technical and legal risks.

  • Rug Pulls & Honeypots
    Many 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 Positives
    Bots 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-Running
    Competing 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 Risks
    Storing 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 Areas
    Depending 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.


Prerequisites

 

Before 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 Guide

 

 

Step 1: Setting Up the Project

 

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

 

 

Step 2: Setting Up Environment Variables

 

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

 

 

Step 3: Create the CLMM Pool Listener

 

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

 

Step 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 Swap

 

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.

 

Step 6: Testing the Bot

 

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

 

Step 7: Deployment and Security

 

Once the bot is ready, deploy it to a secure server:

 

  1. Use a VPS to ensure the bot runs continuously with minimal downtime.
  2. Secure Your Private Key: Always use environment variables or a secure vault service to store sensitive information.

Real-World Optimizations

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.

Filtering Bad Tokens (Pre-Buy Checks)

  1. Minimum Liquidity Threshold

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;

 

  1. Token Metadata Validation

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;

 

  1. Token Blacklist

Maintain a list of known scam tokens or deployers and skip them instantly.

 

if (BLACKLIST.includes(targetMint)) return;

 

  1. Optional: Simulate Swap or Check Route

Use simulateTransaction() to preview the swap or query a route via Jupiter. If it fails or no route exists, don't buy.

 

  1. Delay-Based Decision Making

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.

 

Using Multiple RPCs (Failover Strategy)

  1. RPC List Configuration

Set up a list of RPC endpoints (e.g., Helius, Triton, QuickNode). Load them from .env or config file.

 

const RPCS = [RPC1, RPC2, RPC3];

 

  1. Retry and Fallback Mechanism

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;
  }
}

 

Logging and Monitoring

  1. Event Logging

Log what matters: detected pools, attempted buys, successful swaps, token details.

 

console.log(`[POOL] ${poolId} | Token: ${tokenMint}`);

 

  1. Error Tracking

Use try/catch around every major async operation and log failures with stack traces.

 

console.error(`[ERROR] ${err.message}`);

 

  1. Optional Integration

   Use tools like:

  • PM2 to auto-restart the bot on crash
  • Winston for structured logging
  • Cloud services like Logtail or Datadog for remote log collection

     

Optional: Sell Logic and Exit Strategy

 

  1. Take-Profit Threshold

Set a target percentage (e.g., 2x from entry) and auto-sell when the token reaches that price.

 

if (currentPrice >= buyPrice * 2) {
  await sell();
}

 

  1. Stop-Loss Setup

Protect your downside. If price drops below a defined floor, exit.

 

if (currentPrice <= buyPrice * 0.7) {
  await sell();
}

 

  1. Time-Based Exits

If the price doesn't move after a certain duration (e.g., 3 minutes), exit anyway to avoid being stuck.

Future Extensions

  • Re-entry after dips
  • Multi-wallet rotation for stealth
  • Discord/Telegram alert triggers
  • Token sell simulation before actual sell

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.

 

Troubleshooting & Common Errors

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:

  • Bot doesn't detect new pools


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.

 

  • Transaction isn't sent or gets stuck


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.

 

  • Buy transaction fails or reverts


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.

 

  • Private key or wallet errors


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.

 

  • Bought tokens but can't sell

This is likely a honeypot. To avoid it, always validate:

  1. Token has a valid symbol and name
  2. Sufficient liquidity (avoid pools under 1 SOL)
  3. No known blacklist flags or scam patterns

 

  • 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.

 

 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.

 

Conclusion

 

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.

 

 

Author Ankit Mishra

Ankit Mishra is an experienced backend developer with 2.5 years of industry expertise. He is well-versed in using Nodejs, Express, Sequelize, PHP, Laraval, Apache, HTML, CSS, JavaScript, jQuery, and various databases, and stays up-to-date with the latest technologies. Ankit has worked on various projects, including Oodles Blockchain internal site, Duel Deal, and Distincts, and is always eager to explore new technologies and think critically. His creative and analytical abilities make him a valuable asset to any organization he works with.

Sr. Associate Consultant L2 - Development

bg bg

What's Trending in Tech

bg

Our Offices

India

INDIA

DG-18-009, Tower B,
Emaar Digital Greens, Sector 61,
Gurugram, Haryana
122011.
Unit- 117-120, First Floor,
Welldone Tech Park,
Sector 48, Sohna road,
Gurugram, Haryana
122018.
USA

USA

30N, Gloud St STR E, Sheridan, Wyoming (USA) - 82801
Singapore

SINGAPORE

10 Anson Road, #13-09, International Plaza Singapore 079903.

By using this site, you allow our use of cookies. For more information on the cookies we use and how to delete or block them, please read our cookie notice.