### Initialize and Run BNB Sniper Bot with Lifecycle Management Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Complete bot lifecycle example demonstrating initialization of the SniperBot instance, configuration validation, setup of graceful shutdown handlers for SIGINT/SIGTERM signals, and comprehensive error handling for uncaught exceptions and unhandled promise rejections. The bot creates a logs directory, displays a banner, and manages the entire bot lifecycle from startup through graceful termination. ```typescript import { SniperBot } from './bot/sniperBot'; import { config, validateConfig } from './config'; import { logger } from './utils/logger'; import * as fs from 'fs'; import * as path from 'path'; async function runBot() { // Create logs directory const logsDir = path.join(process.cwd(), 'logs'); if (!fs.existsSync(logsDir)) { fs.mkdirSync(logsDir, { recursive: true }); } // Display banner console.log('╔═══════════════════════════════════════════════════════════╗'); console.log('║ 🎯 BNB SNIPER BOT - FOUR.MEME 🎯 ║'); console.log('║ High-Speed Token Sniper with MEV Support ║'); console.log('╚═══════════════════════════════════════════════════════════╝'); // Validate configuration validateConfig(); logger.info('✅ Configuration valid'); // Create bot instance const bot = new SniperBot(); // Setup signal handlers const shutdown = async (signal: string) => { logger.info(`Received ${signal}, shutting down gracefully...`); await bot.stop(); process.exit(0); }; process.on('SIGINT', () => shutdown('SIGINT')); process.on('SIGTERM', () => shutdown('SIGTERM')); // Error handlers process.on('uncaughtException', (error) => { logger.error('Uncaught Exception:', error); process.exit(1); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled Rejection:', { promise, reason }); }); // Start trading await bot.start(); } runBot().catch((error) => { console.error('Fatal error:', error); process.exit(1); }); ``` -------------------------------- ### Environment Configuration Example (Bash) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Lists essential environment variables required for the bot's operation, covering blockchain, wallet, trading, DEX addresses, MEV, and logging configurations. ```bash # Blockchain Configuration BSC_RPC_URL=https://bsc-dataseed.binance.org/ BSC_WSS_URL=wss://bsc-dataseed.binance.org/ CHAIN_ID=56 # Wallet Configuration PRIVATE_KEY=0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef WALLET_ADDRESS=0x1234567890123456789012345678901234567890 # Trading Configuration BUY_AMOUNT=0.1 SLIPPAGE_BPS=100 GAS_LIMIT=500000 MAX_GAS_PRICE=10 GAS_PRICE_MULTIPLIER=1.2 # DEX Addresses FOUR_MEME_FACTORY_ADDRESS=0x... FOUR_MEME_ROUTER_ADDRESS=0x... PANCAKE_ROUTER_ADDRESS=0x10ED43C718714eb63d5aA57B78B54704E256024E PANCAKE_FACTORY_ADDRESS=0xBCfCcbde45cE874adCB698cC183deBcF17952812 WBNB_ADDRESS=0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c # MEV Configuration ENABLE_FRONTRUN=true ENABLE_BACKRUN=true MEV_SHARE_PERCENTAGE=80 # Logging LOG_LEVEL=info ``` -------------------------------- ### Sniper Bot Main Orchestrator and Lifecycle Management (TypeScript) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Initializes and starts the main SniperBot class, handling configuration validation and graceful shutdown. It sets up event listeners for SIGINT and SIGTERM signals to stop the bot and exit cleanly. The script also includes handlers for uncaught exceptions and unhandled rejections to ensure robust error management. ```typescript import { SniperBot } from './bot/sniperBot'; import { config, validateConfig } from './config'; import { logger } from './utils/logger'; // Initialize and start the bot async function main() { try { // Validate configuration logger.info('Validating configuration...'); validateConfig(); logger.info('✅ Configuration valid'); // Create bot instance const bot = new SniperBot(); // Handle graceful shutdown process.on('SIGINT', async () => { logger.info('Received SIGINT signal, shutting down gracefully...'); await bot.stop(); process.exit(0); }); process.on('SIGTERM', async () => { logger.info('Received SIGTERM signal, shutting down gracefully...'); await bot.stop(); process.exit(0); }); // Handle uncaught errors process.on('uncaughtException', (error) => { logger.error('Uncaught Exception:', error); process.exit(1); }); process.on('unhandledRejection', (reason, promise) => { logger.error('Unhandled Rejection at:', promise, 'reason:', reason); }); // Start the bot await bot.start(); } catch (error) { logger.error('Fatal error:', error); process.exit(1); } } main(); ``` -------------------------------- ### Monitor New Tokens with TypeScript Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt This snippet demonstrates how to use the TokenMonitor service to detect new tokens in real-time from the four.meme factory and mempool. It defines a callback function to handle detected token information and starts the monitoring process. The service can be stopped, and its active status can be checked. ```typescript import { TokenMonitor } from './services/tokenMonitor'; import { TokenInfo } from './types'; import { logger } from './utils/logger'; // Initialize token monitor const tokenMonitor = new TokenMonitor(); // Define callback for new token detection async function handleNewToken(tokenInfo: TokenInfo): Promise { logger.info('════════════════════════════════════════════════════════════'); logger.info(`🎯 NEW TOKEN DETECTED!`); logger.info(` Name: ${tokenInfo.name}`); logger.info(` Symbol: ${tokenInfo.symbol}`); logger.info(` Address: ${tokenInfo.address}`); logger.info(` Creator: ${tokenInfo.creator}`); logger.info(` Block: ${tokenInfo.blockNumber || 'PENDING'}`); logger.info('════════════════════════════════════════════════════════════'); // Your trading logic here } // Start monitoring for new tokens await tokenMonitor.startMonitoring(handleNewToken); // Stop monitoring when done tokenMonitor.stopMonitoring(); // Check monitoring status const isActive = tokenMonitor.isActive(); console.log(`Token monitoring active: ${isActive}`); ``` -------------------------------- ### Execute MEV Transactions with TypeScript and Ethers Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt This snippet demonstrates the MEVExecutor service for advanced transaction strategies like front-running and back-running. It utilizes the ethers.js library for transaction data formatting. The code shows how to prepare target and own transactions, execute front-run and back-run strategies, and calculate optimal gas prices for specific block inclusions. ```typescript import { MEVExecutor } from './services/mevExecutor'; import { ethers } from 'ethers'; import { PendingTransaction } from './types'; import { logger } from './utils/logger'; // Initialize MEV executor const mevExecutor = new MEVExecutor(); // Example pending transaction to front-run const targetTx: PendingTransaction = { hash: '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', from: '0x1234567890123456789012345678901234567890', to: '0x0987654321098765432109876543210987654321', value: '1000000000000000000', gasPrice: '5000000000', gasLimit: '300000', data: '0x...', nonce: 123, }; // Prepare our transaction data const ourTxData: ethers.PopulatedTransaction = { to: '0x10ED43C718714eb63d5aA57B78B54704E256024E', data: '0x7ff36ab5000000000000000000000000000000000000000000000000000000000000000', value: ethers.utils.parseEther('0.1'), }; // Execute front-run (10% higher gas price) const frontrunTxHash = await mevExecutor.executeFrontrun(targetTx, ourTxData); logger.info(`✅ Frontrun transaction sent: ${frontrunTxHash}`); // Execute back-run (5% higher gas price) const backrunTxHash = await mevExecutor.executeBackrun(targetTx, ourTxData); logger.info(`✅ Backrun transaction sent: ${backrunTxHash}`); // Execute with precision timing for optimal block inclusion const precisionTxHash = await mevExecutor.executeWithPrecisionTiming(ourTxData); logger.info(`✅ Precision transaction sent: ${precisionTxHash}`); // Calculate optimal gas for specific block const currentBlock = await web3Provider.getCurrentBlock(); const targetBlock = currentBlock + 1; const optimalGas = await mevExecutor.calculateOptimalGas(targetBlock); logger.info(`Optimal gas price for block ${targetBlock}: ${ethers.utils.formatUnits(optimalGas, 'gwei')} GWEI`); ``` -------------------------------- ### Execute Token Trades with TypeScript Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt This code illustrates the TradeExecutor service for buying and selling tokens, featuring automatic retries and slippage protection. It shows how to initialize the executor, buy a token, handle success or failure responses, sell tokens back, and retrieve the current token price in BNB. Dependencies include TokenInfo and TradeResult types. ```typescript import { TradeExecutor } from './services/tradeExecutor'; import { TokenInfo, TradeResult } from './types'; import { logger } from './utils/logger'; // Initialize trade executor const tradeExecutor = new TradeExecutor(); // Example token info const tokenInfo: TokenInfo = { address: '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb', name: 'TestToken', symbol: 'TEST', decimals: 18, creator: '0x1234567890123456789012345678901234567890', blockNumber: 12345678, timestamp: Math.floor(Date.now() / 1000), txHash: '0xabcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890', }; // Buy token with automatic retry const buyResult: TradeResult = await tradeExecutor.buyToken(tokenInfo); if (buyResult.success) { logger.info('🎉 TRADE SUCCESSFUL!'); logger.info(` Transaction: ${buyResult.txHash}`); logger.info(` Tokens Bought: ${buyResult.tokensBought} ${tokenInfo.symbol}`); logger.info(` Gas Used: ${buyResult.gasUsed}`); } else { logger.error('❌ TRADE FAILED!'); logger.error(` Reason: ${buyResult.error}`); } // Sell tokens back to BNB const sellResult: TradeResult = await tradeExecutor.sellToken( tokenInfo.address, '1000.0', // Amount to sell 18 // Token decimals ); if (sellResult.success) { logger.info(`✅ Sell successful: ${sellResult.txHash}`); logger.info(` Gas Used: ${sellResult.gasUsed}`); } // Get current token price const priceInBNB = await tradeExecutor.getTokenPrice(tokenInfo.address); console.log(`Current price: ${priceInBNB} BNB per token`); ``` -------------------------------- ### Environment Configuration and Validation (TypeScript) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Loads environment variables for bot configuration using dotenv and provides validation for essential parameters. It defines the BotConfig interface and exports a configuration object populated from process.env, with default values. The validateConfig function ensures that critical settings like privateKey and walletAddress are present and correctly formatted. ```typescript import dotenv from 'dotenv'; import { BotConfig } from '../types'; dotenv.config(); // Complete configuration object export const config: BotConfig = { bscRpcUrl: process.env.BSC_RPC_URL || 'https://bsc-dataseed.binance.org/', bscWssUrl: process.env.BSC_WSS_URL || 'wss://bsc-dataseed.binance.org/', chainId: parseInt(process.env.CHAIN_ID || '56'), privateKey: process.env.PRIVATE_KEY || '', walletAddress: process.env.WALLET_ADDRESS || '', buyAmount: process.env.BUY_AMOUNT || '0.1', gasLimit: parseInt(process.env.GAS_LIMIT || '500000'), gasPriceMultiplier: parseFloat(process.env.GAS_PRICE_MULTIPLIER || '1.2'), maxGasPrice: process.env.MAX_GAS_PRICE || '10', slippageBps: parseInt(process.env.SLIPPAGE_BPS || '100'), fourMemeFactoryAddress: process.env.FOUR_MEME_FACTORY_ADDRESS || '', fourMemeRouterAddress: process.env.FOUR_MEME_ROUTER_ADDRESS || '', pancakeRouterAddress: process.env.PANCAKE_ROUTER_ADDRESS || '0x10ED43C718714eb63d5aA57B78B54704E256024E', pancakeFactoryAddress: process.env.PANCAKE_FACTORY_ADDRESS || '0xBCfCcbde45cE874adCB698cC183deBcF17952812', wbnbAddress: process.env.WBNB_ADDRESS || '0xbb4CdB9CBd36B01bD1cBaEBF2De08d9173bc095c', enableFrontrun: process.env.ENABLE_FRONTRUN === 'true', enableBackrun: process.env.ENABLE_BACKRUN === 'true', mevSharePercentage: parseInt(process.env.MEV_SHARE_PERCENTAGE || '80'), logLevel: process.env.LOG_LEVEL || 'info', }; // Validate required configuration export function validateConfig(): void { const required = ['privateKey', 'walletAddress', 'bscRpcUrl']; for (const key of required) { if (!config[key as keyof BotConfig]) { throw new Error(`Missing required configuration: ${key}`); } } if (!config.privateKey.startsWith('0x')) { throw new Error('Private key must start with 0x'); } if (config.privateKey.length !== 66) { throw new Error('Invalid private key length'); } } ``` -------------------------------- ### Balance Checking Utility (TypeScript) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Checks the wallet balance in BNB and Wei, and calculates the maximum number of trades possible based on a configured buy amount. Logs warnings if the balance is insufficient for even one trade. Dependencies: './utils/web3Provider', './config', 'ethers'. ```typescript import { web3Provider } from './utils/web3Provider'; import { config } from './config'; import { ethers } from 'ethers'; async function checkBalance() { console.log('\ud83d\udcb0 Checking Wallet Balance...\n'); try { // Get wallet balance const balance = await web3Provider.wallet.getBalance(); const balanceBNB = ethers.utils.formatEther(balance); console.log(`Wallet Address: ${config.walletAddress}`); console.log(`Balance: ${balanceBNB} BNB`); console.log(`Balance (Wei): ${balance.toString()}`); // Calculate how many trades possible const buyAmount = parseFloat(config.buyAmount); const maxTrades = Math.floor(parseFloat(balanceBNB) / buyAmount); console.log(`\nWith buy amount of ${config.buyAmount} BNB:`); console.log(`Maximum possible trades: ${maxTrades}`); if (parseFloat(balanceBNB) < buyAmount) { console.log('\n\u26a0\ufe0f WARNING: Insufficient balance for even one trade!'); } } catch (error) { console.error('Error:', error); } } checkBalance(); ``` -------------------------------- ### Honeypot Detection Service (TypeScript) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Checks if a given token address is a honeypot. It utilizes a HoneypotDetector utility and logs warnings if a potential honeypot is found. Includes a simulation of a buy transaction to check tradeability. Dependencies: './utils/honeypotDetector', './utils/logger', 'ethers'. ```typescript import { HoneypotDetector } from './utils/honeypotDetector'; import { logger } from './utils/logger'; import { ethers } from 'ethers'; // Initialize honeypot detector const honeypotDetector = new HoneypotDetector(); // Check if token is a honeypot const tokenAddress = '0x742d35Cc6634C0532925a3b844Bc9e7595f0bEb'; const result = await honeypotDetector.checkToken(tokenAddress); if (result.isHoneypot) { logger.warn(`\u26a0\ufe0f Potential honeypot detected: ${tokenAddress}`); result.reasons.forEach(reason => { logger.warn(` - ${reason}`); }); // Do not trade this token } else { logger.info(`\u2705 Token appears safe: ${tokenAddress}`); // Proceed with trading } // Simulate a buy transaction before executing const amountIn = ethers.utils.parseEther('0.1'); const canBuy = await honeypotDetector.simulateBuy(tokenAddress, amountIn); if (canBuy) { logger.info('\u2705 Buy simulation successful'); } else { logger.error('❌ Buy simulation failed - token may not be tradeable'); } ``` -------------------------------- ### Core Type Definitions (TypeScript) Source: https://context7.com/vladmeer/fourmeme-sniper/llms.txt Defines essential TypeScript interfaces used throughout the bot for configuration, token information, trade results, pending transactions, and MEV bundles. ```typescript export interface BotConfig { bscRpcUrl: string; bscWssUrl: string; chainId: number; privateKey: string; walletAddress: string; buyAmount: string; gasLimit: number; gasPriceMultiplier: number; maxGasPrice: string; slippageBps: number; fourMemeFactoryAddress: string; fourMemeRouterAddress: string; pancakeRouterAddress: string; pancakeFactoryAddress: string; wbnbAddress: string; enableFrontrun: boolean; enableBackrun: boolean; mevSharePercentage: number; logLevel: string; } export interface TokenInfo { address: string; name: string; symbol: string; decimals: number; creator: string; blockNumber: number; timestamp: number; txHash: string; } export interface TradeResult { success: boolean; txHash?: string; error?: string; gasUsed?: string; tokensBought?: string; price?: string; } export interface PendingTransaction { hash: string; from: string; to: string; value: string; gasPrice: string; gasLimit: string; data: string; nonce: number; } export interface MEVBundle { transactions: string[]; blockNumber: number; minTimestamp?: number; maxTimestamp?: number; } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.