use {
anyhow::{anyhow, Result},
base64::{engine::general_purpose::STANDARD as base64_engine, Engine},
bincode,
colored::,
config::{Config, File},
dashmap::DashMap,
futures_util::{SinkExt, StreamExt},
log::{debug, error, info, warn},
rustacuda::prelude::,
serde::{Deserialize, Serialize},
serde_json::json,
solana_client::rpc_client::RpcClient,
solana_sdk::{
commitment_config::CommitmentConfig,
compute_budget::ComputeBudgetInstruction,
instruction::AccountMeta,
message::Message,
pubkey::Pubkey,
signer::{keypair::Keypair, Signer},
transaction::Transaction,
},
std::{
fs,
str::FromStr,
sync::Arc,
time::{Duration, SystemTime, UNIX_EPOCH},
},
tokio::{sync::Mutex, time::interval},
};
const WSOL_MINT: &str = "So11111111111111111111111111111111111111112";
const MAX_ACTIVE_TRADES: usize = 5;
const MAX_RETRY_ATTEMPTS: u32 = 5;
const MIN_PRIORITY_FEE: u64 = 10000;
const PRICE_CHECK_INTERVAL: Duration = Duration::from_secs(1);
const SAVE_STATE_INTERVAL: Duration = Duration::from_secs(30);
#[derive(Clone, Serialize, Deserialize, Debug)]
struct Trade {
token_address: String,
amount: u64,
initial_amount: u64,
buy_price: f64,
take_profit_price: f64,
stop_loss_price: f64,
retry_count: u32,
timestamp: u64,
}
#[derive(Clone, Serialize, Deserialize)]
struct BotState {
active_trades: Vec,
wsol_balance: f64,
sol_balance: f64,
last_update: u64,
}
struct CudaValidator {
context: Context,
stream: Stream,
module: Module,
}
impl CudaValidator {
fn new() -> Result {
rustacuda::init(CudaFlags::empty())?;
let device = Device::get_device(0)?;
let context =
Context::create_and_push(ContextFlags::MAP_HOST | ContextFlags::SCHED_AUTO, device)?;
let module = Module::load_from_string(include_str!("../kernels/token_validator.ptx"))?;
let stream = Stream::new(StreamFlags::NON_BLOCKING, None)?;
Ok(Self {
context,
stream,
module,
})
}
fn validate(&self, token_data: &[f32]) -> Result<bool> {
let input_size = token_data.len();
let mut input_buffer = unsafe { DeviceBuffer::uninitialized(input_size)? };
let mut output_buffer = unsafe { DeviceBuffer::uninitialized(1)? };
input_buffer.copy_from(token_data)?;
let func = self.module.get_function("validate_token")?;
let params = vec![
input_buffer.as_device_ptr(),
&(input_size as i32),
output_buffer.as_device_ptr(),
];
unsafe {
func.launch(LaunchConfig::for_num_elements(1), ¶ms)?;
}
self.stream.synchronize()?;
let mut result = vec![0u8; 1];
output_buffer.copy_to(&mut result)?;
Ok(result[0] != 0)
}
}
struct Bot {
config: BotConfig,
rpc_client: Arc,
keypair: Arc,
wsol_account: Pubkey,
active_trades: Arc<DashMap<String, Trade>>,
http_client: reqwest::Client,
cuda_validator: Arc,
}
impl Bot {
async fn execute_buy(&self, token_address: &str) -> Result<()> {
if self.active_trades.len() >= MAX_ACTIVE_TRADES {
info!("❌ Maximum active trades reached (5)");
return Ok(());
}
println!("{}", "\n🎯 EXECUTING BUY".bright_green().bold());
info!("Token: {}", token_address);
let priority_fee = self.get_helius_priority_fee(token_address).await?;
info!("⚡ Priority Fee: {}", priority_fee);
// Check WSOL balance before trade
let wsol_balance = self.get_wsol_balance().await?;
if wsol_balance < (self.config.trading.snipe_amount as f64 / 1e9) {
return Err(anyhow!("Insufficient WSOL balance"));
}
// Get Jupiter quote
let quote = self
.http_client
.get(&format!(
"https://quote-api.jup.ag/v6/quote?\
inputMint={}&\
outputMint={}&\
amount={}&\
slippageBps={}&\
platformFeeBps=0",
WSOL_MINT,
token_address,
self.config.trading.snipe_amount,
self.config.trading.slippage
))
.send()
.await?
.json::<serde_json::Value>()
.await?;
debug!("📊 Quote received: {:?}", quote);
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": priority_fee,
"asLegacyTransaction": true
});
let swap_response = self
.http_client
.post("https://quote-api.jup.ag/v6/swap")
.json(&swap_request)
.send()
.await?
.json::<serde_json::Value>()
.await?;
let tx_data = base64_engine.decode(swap_response["swapTransaction"].as_str().unwrap())?;
let mut transaction: Transaction = bincode::deserialize(&tx_data)?;
// Add compute budget instructions
let compute_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(200_000);
let priority_fee_ix = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
let mut final_instructions = vec![compute_limit_ix, priority_fee_ix];
final_instructions.extend(transaction.message.instructions.iter().cloned());
let message = Message::new(&final_instructions, Some(&self.keypair.pubkey()));
let blockhash = self.rpc_client.get_latest_blockhash()?;
transaction = Transaction::new(&[&self.keypair], message, blockhash);
println!("{}", "🚀 Sending buy transaction...".bright_yellow());
let signature = self
.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!(
"{}",
format!("✅ Buy confirmed: {}", signature).bright_green()
);
// Get entry price and save trade
let entry_price = self.get_token_price(token_address).await?;
let trade = Trade {
token_address: token_address.to_string(),
amount: self.config.trading.snipe_amount,
initial_amount: self.config.trading.snipe_amount,
buy_price: entry_price,
take_profit_price: entry_price * 1.30, // 30% profit target
stop_loss_price: entry_price * 0.93, // 7% stop loss
retry_count: 0,
timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
};
self.active_trades.insert(token_address.to_string(), trade);
println!("💰 Entry Price: {} SOL", entry_price);
println!("📈 Take Profit: {} SOL", entry_price * 1.30);
println!("📉 Stop Loss: {} SOL", entry_price * 0.93);
Ok(())
}
async fn execute_sell(
&self,
token_address: &str,
trade: &Trade,
is_profit: bool,
) -> Result<()> {
println!(
"{}",
if is_profit {
"🎯 EXECUTING PROFIT TAKE (30%)".bright_green()
} else {
"⚠️ EXECUTING STOP LOSS".bright_red()
}
);
let priority_fee = self.get_helius_priority_fee(token_address).await?;
info!("⚡ Priority Fee: {}", priority_fee);
// Get token balance
let token_pubkey = Pubkey::from_str(token_address)?;
let token_account = self
.rpc_client
.get_token_accounts_by_owner(
&self.keypair.pubkey(),
spl_token::instruction::TokenAccountsFilter::Mint(token_pubkey),
)?
.first()
.ok_or_else(|| anyhow!("No token account found"))?
.pubkey
.clone();
let token_balance = self
.rpc_client
.get_token_account_balance(&token_account)?
.ui_amount
.ok_or_else(|| anyhow!("Failed to get token balance"))?;
let quote = self
.http_client
.get(&format!(
"https://quote-api.jup.ag/v6/quote?\
inputMint={}&\
outputMint={}&\
amount={}&\
slippageBps={}&\
platformFeeBps=0",
token_address, WSOL_MINT, token_balance, self.config.trading.slippage
))
.send()
.await?
.json::<serde_json::Value>()
.await?;
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": priority_fee,
"asLegacyTransaction": true
});
let swap_response = self
.http_client
.post("https://quote-api.jup.ag/v6/swap")
.json(&swap_request)
.send()
.await?
.json::<serde_json::Value>()
.await?;
let tx_data = base64_engine.decode(swap_response["swapTransaction"].as_str().unwrap())?;
let mut transaction: Transaction = bincode::deserialize(&tx_data)?;
let compute_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(200_000);
let priority_fee_ix = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
let mut final_instructions = vec![compute_limit_ix, priority_fee_ix];
final_instructions.extend(transaction.message.instructions.iter().cloned());
let blockhash = self.rpc_client.get_latest_blockhash()?;
let message = Message::new(&final_instructions, Some(&self.keypair.pubkey()));
transaction = Transaction::new(&[&self.keypair], message, blockhash);
println!("{}", "🚀 Sending sell transaction...".bright_yellow());
let signature = self
.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!(
"{}",
format!("✅ Sell confirmed: {}", signature).bright_green()
);
// Calculate profit/loss
let exit_price = self.get_token_price(token_address).await?;
let profit_percent = ((exit_price - trade.buy_price) / trade.buy_price * 100.0).round();
println!("{}", format!("💰 Exit Price: {} SOL", exit_price).yellow());
println!(
"{}",
format!("📊 P/L: {}%", profit_percent).if_else(
profit_percent >= 0.0,
|s| s.green(),
|s| s.red()
)
);
// Remove trade from active trades
self.active_trades.remove(token_address);
self.save_state().await?;
Ok(())
}
async fn get_token_price(&self, token_address: &str) -> Result<f64> {
let price = self
.http_client
.get(&format!(
"https://price.jup.ag/v6/price?ids={}&vsToken=SOL",
token_address
))
.send()
.await?
.json::<serde_json::Value>()
.await?["data"][token_address]["price"]
.as_f64()
.ok_or_else(|| anyhow!("Price not found"))?;
Ok(price)
}
async fn get_wsol_balance(&self) -> Result<f64> {
self.rpc_client
.get_token_account_balance(&self.wsol_account)?
.ui_amount
.ok_or_else(|| anyhow!("Failed to get WSOL balance"))
}
async fn wrap_sol(&self, amount: f64) -> Result<()> {
let lamports = (amount * 1e9) as u64;
let create_ix = system_instruction::create_account(
&self.keypair.pubkey(),
&self.wsol_account,
lamports,
165,
&spl_token::id(),
);
let init_ix = spl_token::instruction::initialize_account(
&spl_token::id(),
&self.wsol_account,
&Pubkey::from_str(WSOL_MINT)?,
&self.keypair.pubkey(),
)?;
let transaction = Transaction::new_signed_with_payer(
&[create_ix, init_ix],
Some(&self.keypair.pubkey()),
&[&self.keypair],
self.rpc_client.get_latest_blockhash()?,
);
self.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!("✅ Wrapped {} SOL to WSOL", amount);
Ok(())
}
async fn unwrap_sol(&self, amount: f64) -> Result<()> {
let ix = spl_token::instruction::close_account(
&spl_token::id(),
&self.wsol_account,
&self.keypair.pubkey(),
&self.keypair.pubkey(),
&[&self.keypair.pubkey()],
)?;
let transaction = Transaction::new_signed_with_payer(
&[ix],
Some(&self.keypair.pubkey()),
&[&self.keypair],
self.rpc_client.get_latest_blockhash()?,
);
self.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!("✅ Unwrapped {} WSOL to SOL", amount);
Ok(())
}
async fn monitor_tokens(&self) -> Result<()> {
println!("{}", "\n🔍 MONITORING NEW TOKEN LAUNCHES".bright_blue());
let ws_url = url::Url::parse(&self.config.urls.ws_endpoint)?;
loop {
match connect_async(&ws_url).await {
Ok((ws_stream, _)) => {
let (mut write, mut read) = ws_stream.split();
write
.send(WsMessage::Text(
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "programSubscribe",
"params": [
RAYDIUM_AMM_PROGRAM_ID,
{"encoding": "jsonParsed", "commitment": "confirmed"}
]
})
.to_string(),
))
.await?;
while let Some(msg) = read.next().await {
if let Ok(WsMessage::Text(text)) = msg {
if let Some(token_address) = self.extract_token_address(&text) {
if self.validate_new_token(&token_address).await? {
self.execute_buy(&token_address).await?;
}
}
}
}
}
Err(e) => {
error!("WebSocket error: {}", e);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
}
async fn execute_buy(&self, token_address: &str) -> Result<()> {
if self.active_trades.len() >= MAX_ACTIVE_TRADES {
info!("❌ Maximum active trades reached (5)");
return Ok(());
}
println!("{}", "\n🎯 EXECUTING BUY".bright_green().bold());
info!("Token: {}", token_address);
let priority_fee = self.get_helius_priority_fee(token_address).await?;
info!("⚡ Priority Fee: {}", priority_fee);
// Check WSOL balance before trade
let wsol_balance = self.get_wsol_balance().await?;
if wsol_balance < (self.config.trading.snipe_amount as f64 / 1e9) {
return Err(anyhow!("Insufficient WSOL balance"));
}
// Get Jupiter quote
let quote = self
.http_client
.get(&format!(
"https://quote-api.jup.ag/v6/quote?\
inputMint={}&\
outputMint={}&\
amount={}&\
slippageBps={}&\
platformFeeBps=0",
WSOL_MINT,
token_address,
self.config.trading.snipe_amount,
self.config.trading.slippage
))
.send()
.await?
.json::<serde_json::Value>()
.await?;
debug!("📊 Quote received: {:?}", quote);
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": priority_fee,
"asLegacyTransaction": true
});
let swap_response = self
.http_client
.post("https://quote-api.jup.ag/v6/swap")
.json(&swap_request)
.send()
.await?
.json::<serde_json::Value>()
.await?;
let tx_data = base64_engine.decode(swap_response["swapTransaction"].as_str().unwrap())?;
let mut transaction: Transaction = bincode::deserialize(&tx_data)?;
// Add compute budget instructions
let compute_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(200_000);
let priority_fee_ix = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
let mut final_instructions = vec![compute_limit_ix, priority_fee_ix];
final_instructions.extend(transaction.message.instructions.iter().cloned());
let message = Message::new(&final_instructions, Some(&self.keypair.pubkey()));
let blockhash = self.rpc_client.get_latest_blockhash()?;
transaction = Transaction::new(&[&self.keypair], message, blockhash);
println!("{}", "🚀 Sending buy transaction...".bright_yellow());
let signature = self
.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!(
"{}",
format!("✅ Buy confirmed: {}", signature).bright_green()
);
// Get entry price and save trade
let entry_price = self.get_token_price(token_address).await?;
let trade = Trade {
token_address: token_address.to_string(),
amount: self.config.trading.snipe_amount,
initial_amount: self.config.trading.snipe_amount,
buy_price: entry_price,
take_profit_price: entry_price * 1.30, // 30% profit target
stop_loss_price: entry_price * 0.93, // 7% stop loss
retry_count: 0,
timestamp: SystemTime::now().duration_since(UNIX_EPOCH)?.as_secs(),
};
self.active_trades.insert(token_address.to_string(), trade);
println!("💰 Entry Price: {} SOL", entry_price);
println!("📈 Take Profit: {} SOL", entry_price * 1.30);
println!("📉 Stop Loss: {} SOL", entry_price * 0.93);
Ok(())
}
async fn execute_sell(
&self,
token_address: &str,
trade: &Trade,
is_profit: bool,
) -> Result<()> {
println!(
"{}",
if is_profit {
"🎯 EXECUTING PROFIT TAKE (30%)".bright_green()
} else {
"⚠️ EXECUTING STOP LOSS".bright_red()
}
);
let priority_fee = self.get_helius_priority_fee(token_address).await?;
info!("⚡ Priority Fee: {}", priority_fee);
// Get token balance
let token_pubkey = Pubkey::from_str(token_address)?;
let token_account = self
.rpc_client
.get_token_accounts_by_owner(
&self.keypair.pubkey(),
spl_token::instruction::TokenAccountsFilter::Mint(token_pubkey),
)?
.first()
.ok_or_else(|| anyhow!("No token account found"))?
.pubkey
.clone();
let token_balance = self
.rpc_client
.get_token_account_balance(&token_account)?
.ui_amount
.ok_or_else(|| anyhow!("Failed to get token balance"))?;
let quote = self
.http_client
.get(&format!(
"https://quote-api.jup.ag/v6/quote?\
inputMint={}&\
outputMint={}&\
amount={}&\
slippageBps={}&\
platformFeeBps=0",
token_address, WSOL_MINT, token_balance, self.config.trading.slippage
))
.send()
.await?
.json::<serde_json::Value>()
.await?;
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": self.keypair.pubkey().to_string(),
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": priority_fee,
"asLegacyTransaction": true
});
let swap_response = self
.http_client
.post("https://quote-api.jup.ag/v6/swap")
.json(&swap_request)
.send()
.await?
.json::<serde_json::Value>()
.await?;
let tx_data = base64_engine.decode(swap_response["swapTransaction"].as_str().unwrap())?;
let mut transaction: Transaction = bincode::deserialize(&tx_data)?;
let compute_limit_ix = ComputeBudgetInstruction::set_compute_unit_limit(200_000);
let priority_fee_ix = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
let mut final_instructions = vec![compute_limit_ix, priority_fee_ix];
final_instructions.extend(transaction.message.instructions.iter().cloned());
let blockhash = self.rpc_client.get_latest_blockhash()?;
let message = Message::new(&final_instructions, Some(&self.keypair.pubkey()));
transaction = Transaction::new(&[&self.keypair], message, blockhash);
println!("{}", "🚀 Sending sell transaction...".bright_yellow());
let signature = self
.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!(
"{}",
format!("✅ Sell confirmed: {}", signature).bright_green()
);
// Calculate profit/loss
let exit_price = self.get_token_price(token_address).await?;
let profit_percent = ((exit_price - trade.buy_price) / trade.buy_price * 100.0).round();
println!("{}", format!("💰 Exit Price: {} SOL", exit_price).yellow());
println!(
"{}",
format!("📊 P/L: {}%", profit_percent).if_else(
profit_percent >= 0.0,
|s| s.green(),
|s| s.red()
)
);
// Remove trade from active trades
self.active_trades.remove(token_address);
self.save_state().await?;
Ok(())
}
async fn get_token_price(&self, token_address: &str) -> Result<f64> {
let price = self
.http_client
.get(&format!(
"https://price.jup.ag/v6/price?ids={}&vsToken=SOL",
token_address
))
.send()
.await?
.json::<serde_json::Value>()
.await?["data"][token_address]["price"]
.as_f64()
.ok_or_else(|| anyhow!("Price not found"))?;
Ok(price)
}
async fn get_wsol_balance(&self) -> Result<f64> {
self.rpc_client
.get_token_account_balance(&self.wsol_account)?
.ui_amount
.ok_or_else(|| anyhow!("Failed to get WSOL balance"))
}
async fn wrap_sol(&self, amount: f64) -> Result<()> {
let lamports = (amount * 1e9) as u64;
let create_ix = system_instruction::create_account(
&self.keypair.pubkey(),
&self.wsol_account,
lamports,
165,
&spl_token::id(),
);
let init_ix = spl_token::instruction::initialize_account(
&spl_token::id(),
&self.wsol_account,
&Pubkey::from_str(WSOL_MINT)?,
&self.keypair.pubkey(),
)?;
let transaction = Transaction::new_signed_with_payer(
&[create_ix, init_ix],
Some(&self.keypair.pubkey()),
&[&self.keypair],
self.rpc_client.get_latest_blockhash()?,
);
self.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!("✅ Wrapped {} SOL to WSOL", amount);
Ok(())
}
async fn unwrap_sol(&self, amount: f64) -> Result<()> {
let ix = spl_token::instruction::close_account(
&spl_token::id(),
&self.wsol_account,
&self.keypair.pubkey(),
&self.keypair.pubkey(),
&[&self.keypair.pubkey()],
)?;
let transaction = Transaction::new_signed_with_payer(
&[ix],
Some(&self.keypair.pubkey()),
&[&self.keypair],
self.rpc_client.get_latest_blockhash()?,
);
self.rpc_client
.send_and_confirm_transaction_with_spinner(&transaction)?;
println!("✅ Unwrapped {} WSOL to SOL", amount);
Ok(())
}
async fn monitor_tokens(&self) -> Result<()> {
println!("{}", "\n🔍 MONITORING NEW TOKEN LAUNCHES".bright_blue());
let ws_url = url::Url::parse(&self.config.urls.ws_endpoint)?;
loop {
match connect_async(&ws_url).await {
Ok((ws_stream, _)) => {
let (mut write, mut read) = ws_stream.split();
write
.send(WsMessage::Text(
json!({
"jsonrpc": "2.0",
"id": 1,
"method": "programSubscribe",
"params": [
RAYDIUM_AMM_PROGRAM_ID,
{"encoding": "jsonParsed", "commitment": "confirmed"}
]
})
.to_string(),
))
.await?;
while let Some(msg) = read.next().await {
if let Ok(WsMessage::Text(text)) = msg {
if let Some(token_address) = self.extract_token_address(&text) {
if self.validate_new_token(&token_address).await? {
self.execute_buy(&token_address).await?;
}
}
}
}
}
Err(e) => {
error!("WebSocket error: {}", e);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
}
}
#[derive(Debug, Clone)]
struct TradeStats {
total_trades: u64,
successful_trades: u64,
failed_trades: u64,
total_profit: f64,
}
async fn print_stats(&self) {
let stats = {
let trades = self.active_trades.iter();
let mut stats = TradeStats {
total_trades: 0,
successful_trades: 0,
failed_trades: 0,
total_profit: 0.0,
};
for trade in trades {
stats.total_trades += 1;
let current_price = self
.get_token_price(&trade.token_address)
.await
.unwrap_or(0.0);
let profit = (current_price - trade.buy_price) * trade.amount as f64;
stats.total_profit += profit;
}
stats
};
println!("\n{}", "📊 TRADING STATISTICS".bright_blue().bold());
println!("Active Trades: {}/5", self.active_trades.len());
println!("Total Trades: {}", stats.total_trades);
println!("Successful Trades: {}", stats.successful_trades);
println!("Failed Trades: {}", stats.failed_trades);
println!("Total Profit: {} SOL", stats.total_profit);
}
async fn shutdown(&self) -> Result<()> {
println!(
"{}",
"\n💾 GRACEFUL SHUTDOWN INITIATED".bright_yellow().bold()
);
// Save final state
self.save_state().await?;
// Print final stats
self.print_stats().await;
// Close any remaining trades if requested
if !self.active_trades.is_empty() {
println!("Warning: {} active trades remain", self.active_trades.len());
println!("Press Ctrl+C again to force exit or wait for trades to complete");
// Wait for active trades to complete
while !self.active_trades.is_empty() {
self.check_active_trades().await?;
tokio::time::sleep(Duration::from_secs(1)).await;
}
}
Ok(())
}
async fn run_with_recovery(&self) -> Result<()> {
let mut retry_count = 0;
let max_retries = 3;
loop {
match self.run().await {
Ok(_) => {
retry_count = 0;
continue;
}
Err(e) => {
error!("Bot error: {}", e);
retry_count += 1;
if retry_count >= max_retries {
error!("Max retries reached, shutting down");
self.shutdown().await?;
break;
}
warn!(
"Restarting bot in 5 seconds... (attempt {}/{})",
retry_count, max_retries
);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
Ok(())
}
#[tokio::main]
async fn main() -> Result<()> {
// Initialize logging
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.format(|buf, record| {
use std::io::Write;
let level_color = match record.level() {
log::Level::Error => "31",
log::Level::Warn => "33",
log::Level::Info => "32",
log::Level::Debug => "36",
log::Level::Trace => "37",
};
writeln!(
buf,
"\x1B[{}m{}\x1B[0m [{}] {}",
level_color,
record.level(),
chrono::Local::now().format("%H:%M:%S"),
record.args()
)
})
.init();
println!("{}", "=====================================".bright_blue());
println!(
"{}",
"🚀 MARGA FAST SNIPER ELITE v2.0 🎯".bright_green().bold()
);
println!("{}", "=====================================".bright_blue());
let bot = Arc::new(Bot::new().await?);
// Print initial configuration
println!("{}", "\n🔧 CONFIGURATION:".bright_blue());
println!("💰 Wallet: {}", bot.keypair.pubkey());
println!("💎 WSOL Account: {}", bot.wsol_account);
println!(
"📊 Initial Balance: {} SOL",
bot.rpc_client.get_balance(&bot.keypair.pubkey())? as f64 / 1e9
);
println!(
"🎯 Snipe Amount: {} WSOL",
bot.config.trading.snipe_amount as f64 / 1e9
);
println!("📈 Take Profit: 30%");
println!("📉 Stop Loss: 7%");
println!("⚡ Base Priority Fee: {}", bot.config.trading.priority_fee);
println!("🔄 Max Retries: {}", MAX_RETRY_ATTEMPTS);
// Load any saved state
if let Ok(state_data) = tokio::fs::read_to_string("bot_state.json").await {
if let Ok(state) = serde_json::from_str::<BotState>(&state_data) {
println!("\n📥 LOADED PREVIOUS STATE:");
println!("Active Trades: {}", state.active_trades.len());
println!(
"Last Update: {}",
chrono::DateTime::<chrono::Utc>::from_timestamp(state.last_update as i64, 0)
.unwrap()
);
}
}
// Set up cleanup on Ctrl+C
let bot_clone = Arc::clone(&bot);
let (tx, rx) = tokio::sync::oneshot::channel();
ctrlc::set_handler(move || {
let bot = Arc::clone(&bot_clone);
tokio::runtime::Runtime::new().unwrap().block_on(async {
if let Err(e) = bot.shutdown().await {
error!("Error during shutdown: {}", e);
}
let _ = tx.send(());
});
})?;
// Run monitoring tasks
let monitoring_task = tokio::spawn({
let bot = Arc::clone(&bot);
async move {
let mut interval = tokio::time::interval(Duration::from_secs(300)); // 5 minutes
loop {
interval.tick().await;
bot.print_stats().await;
}
}
});
// Run main bot loop with recovery
let main_task = tokio::spawn({
let bot = Arc::clone(&bot);
async move { bot.run_with_recovery().await }
});
// Wait for shutdown signal or completion
tokio::select! {
_ = rx => {
println!("Received shutdown signal");
}
result = main_task => {
if let Err(e) = result {
error!("Bot task error: {}", e);
}
}
_ = monitoring_task => {
error!("Monitoring task unexpectedly ended");
}
}
println!("{}", "\n👋 Bot shutdown complete".bright_yellow());
Ok(())
}