Sniping Bot
A real-time token sniper that listens for new PumpFun token launches and executes instant buys.
git clone https://github.com/darkfibre-dev/darkfibre-examples.gitcd darkfibre-examples/03-sniping-botnpm installcp .env.example .envEdit .env with your credentials:
DARKFIBRE_API_KEY=your-api-keySOLANA_PRIVATE_KEY=your-base58-private-keynpm startimport { DarkfibreSDK, APIError } from '@darkfibre/sdk';import WebSocket from 'ws';import 'dotenv/config';
// Configurationconst SOL_AMOUNT = 0.005; // SOL per snipeconst SLIPPAGE = 0.1; // 10% slippage toleranceconst PRIORITY = 'fast' as const; // Transaction priorityconst MAX_SNIPES: number = 5; // -1 for unlimitedconst WS_URL = 'wss://ws.darkfibre.dev/v1';
// Validate Environmentconst { DARKFIBRE_API_KEY, SOLANA_PRIVATE_KEY } = process.env;
if (!DARKFIBRE_API_KEY) { console.error('Missing DARKFIBRE_API_KEY in .env'); process.exit(1);}
if (!SOLANA_PRIVATE_KEY) { console.error('Missing SOLANA_PRIVATE_KEY in .env'); process.exit(1);}
// SDK Setupconst sdk = new DarkfibreSDK({ apiKey: DARKFIBRE_API_KEY, privateKey: SOLANA_PRIVATE_KEY,});
// Statelet ws: WebSocket;let reconnectAttempt = 0;let snipesStarted = 0;let snipesCompleted = 0;
// Check if we should exit (all snipes started AND completed)function checkExit() { if (MAX_SNIPES !== -1 && snipesStarted >= MAX_SNIPES && snipesCompleted >= snipesStarted) { console.log(`\n[DONE] Completed ${snipesCompleted} snipes. Exiting.`); ws.close(); process.exit(0); }}
// Snipe Handlerasync function handleCreate(mint: string, symbol: string) { if (MAX_SNIPES !== -1 && snipesStarted >= MAX_SNIPES) return; snipesStarted++;
const snipeNum = snipesStarted; console.log(`\n[SNIPE #${snipeNum}] ${symbol} (${mint})`);
try { // Buy const buyResult = await sdk.buy({ mint, solAmount: SOL_AMOUNT, slippage: SLIPPAGE, priority: PRIORITY, });
console.log(`[BUY #${snipeNum}] ${buyResult.tradeResult.outputAmount} tokens`); console.log(` https://solscan.io/tx/${buyResult.signature}`);
// Demo: Wait and sell immediately (for testing only) // In production, replace with your exit strategy await new Promise((resolve) => setTimeout(resolve, 1000));
const sellResult = await sdk.sell({ mint, tokenAmount: buyResult.tradeResult.outputAmount, slippage: SLIPPAGE, priority: PRIORITY, });
console.log(`[SELL #${snipeNum}] ${sellResult.tradeResult.outputAmount} SOL`); console.log(` https://solscan.io/tx/${sellResult.signature}`);
} catch (err) { if (err instanceof APIError) { console.log(`[ERROR #${snipeNum}] ${err.code}: ${err.message}`); } else { console.log(`[ERROR #${snipeNum}] ${err}`); } }
// Mark this snipe as completed and check if we should exit snipesCompleted++; checkExit();}
// WebSocket Connectionfunction connect() { const wsUrl = `${WS_URL}?apiKey=${DARKFIBRE_API_KEY}`; ws = new WebSocket(wsUrl);
ws.onopen = () => { reconnectAttempt = 0;
// Subscribe to PumpFun create events ws.send(JSON.stringify({ type: 'subscribe', filters: { platform: ['pump_fun'], eventType: ['create'], }, }));
console.log(`[WS] Connected`); console.log(`[WS] Listening for new tokens...`); console.log(`[WS] Config: ${SOL_AMOUNT} SOL | ${SLIPPAGE * 100}% slippage | ${PRIORITY} priority`); if (MAX_SNIPES !== -1) { console.log(`[WS] Will stop after ${MAX_SNIPES} snipes`); } };
ws.onmessage = (event) => { const msg = JSON.parse(event.data.toString());
// Handle transaction events if (msg.type === 'transaction' && msg.data?.eventType === 'create') { // Skip mayhem mode tokens if (msg.data.isMayhemMode) return;
handleCreate(msg.data.mint, msg.data.symbol); } };
ws.onerror = (err) => { console.log('[WS] Error:', err.message); };
ws.onclose = () => { const delay = Math.min(1000 * Math.pow(2, reconnectAttempt++), 30000); console.log(`[WS] Disconnected. Reconnecting in ${delay / 1000}s...`); setTimeout(connect, delay); };}
// Startconsole.log('Starting Darkfibre Sniping Bot...\n');connect();What It Does
Section titled “What It Does”- Connects to the Darkfibre WebSocket feed
- Subscribes to PumpFun
createevents - Auto-buys newly created tokens
- (Demo) Immediately sells back for testing
- Reconnects with exponential backoff on disconnect
Configuration
Section titled “Configuration”Edit index.ts to change:
| Variable | Description | Default |
|---|---|---|
SOL_AMOUNT | SOL to spend per snipe | 0.005 |
SLIPPAGE | Slippage tolerance (0.1 = 10%) | 0.1 |
PRIORITY | Transaction priority | 'fast' |
MAX_SNIPES | Maximum snipes before exit (-1 for unlimited) | 5 |
Expected Output
Section titled “Expected Output”Starting Darkfibre Sniping Bot...
[WS] Connected[WS] Listening for new tokens...[WS] Config: 0.005 SOL | 10% slippage | fast priority[WS] Will stop after 5 snipes
[SNIPE #1] NEWTOKEN (7xK9m...mint123)[BUY #1] 50000000 tokens https://solscan.io/tx/5xK7j...abc123[SELL #1] 0.00495 SOL https://solscan.io/tx/3mN8p...def456
[SNIPE #2] ANOTHERTOKEN (8yL0n...mint456)...Production Notes
Section titled “Production Notes”Example: Filter by Symbol
Section titled “Example: Filter by Symbol”ws.onmessage = (event) => { const msg = JSON.parse(event.data.toString());
if (msg.type === 'transaction' && msg.data?.eventType === 'create') { // Skip mayhem mode tokens if (msg.data.isMayhemMode) return;
// Only snipe tokens with specific keywords const symbol = msg.data.symbol.toLowerCase(); if (symbol.includes('pepe') || symbol.includes('doge')) { handleCreate(msg.data.mint, msg.data.symbol); } }};Related
Section titled “Related”- SDK Overview - Installation and setup
- WebSocket Guide - Real-time data streaming
- Subscribe Filters - Filter options
- Error Handling - Handle all error types