use anyhow::{anyhow, Result};
use bs58;
use config::Config;
use futures_util::{SinkExt, StreamExt};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::json;
use solana_client::rpc_client::RpcClient;
use solana_sdk::hash::Hash;
use solana_sdk::signer::keypair::Keypair;
use solana_sdk::transaction::Transaction;
use std::collections::HashMap;
use std::fs::{File, OpenOptions};
use std::io::{Read, Write};
use std::sync::Arc;
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex;
use tokio::time::interval;
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message as WsMessage};
use tracing::{debug, error, info, instrument, trace, warn};
use tracing_subscriber::{self, fmt::format::FmtSpan, EnvFilter};
// Configuration Constants
const WSOL_MINT: &str = "So11111111111111111111111111111111111111112";
const RAYDIUM_AMM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const MAX_ACTIVE_TRADES: usize = 5;
const MAX_BUY_ATTEMPTS: u32 = 3;
const BUY_ATTEMPT_DELAY: Duration = Duration::from_millis(200);
const PRICE_CHECK_INTERVAL: Duration = Duration::from_secs(1);
const STATE_FILE: &str = "bot_state.json";
const MIN_LIQUIDITY: f64 = 1000.0; // 1k SOL
const MAX_LIQUIDITY: f64 = 10000.0; // 10k SOL
#[derive(Clone, Serialize, Deserialize)]
struct Trade {
token_address: String,
amount: u64,
buy_price: f64,
take_profit_price: f64,
stop_loss_price: f64,
timestamp: u64,
}
struct PriceCache {
prices: HashMap<String, (f64, Instant)>,
ttl: Duration,
}
impl PriceCache {
fn new(ttl: u64) -> Self {
Self {
prices: HashMap::new(),
ttl: Duration::from_secs(ttl),
}
}
fn get(&self, token_address: &str) -> Option<f64> {
self.prices
.get(token_address)
.and_then(|(price, timestamp)| {
if timestamp.elapsed() < self.ttl {
Some(*price)
} else {
None
}
})
}
fn set(&mut self, token_address: String, price: f64) {
self.prices
.insert(token_address.clone(), (price, Instant::now()));
debug!("Price for {} set to {}.", token_address, price);
}
fn clear_expired(&mut self) {
self.prices
.retain(|_, (_, timestamp)| timestamp.elapsed() < self.ttl);
debug!("Cleared expired prices from the cache.");
}
}
struct Bot {
config: Config,
rpc_client: RpcClient,
keypair: Keypair,
price_cache: Arc<Mutex>,
active_trades: Arc<Mutex<HashMap<String, Trade>>>,
last_blockhash: Arc<Mutex<(Hash, Instant)>>,
metadata_limiter: Arc<Mutex<()>>,
swap_limiter: Arc<Mutex<()>>,
http_client: Client,
}
impl Bot {
#[instrument]
async fn new(config_path: &str) -> Result {
let config = Config::builder()
.add_source(config::File::with_name(config_path))
.build()?;
let rpc_url = config.get_string("rpc_url")?;
let rpc_client = RpcClient::new(rpc_url);
let keypair = Self::load_keypair(&config)?;
let price_cache = Arc::new(Mutex::new(PriceCache::new(60)));
let active_trades = Arc::new(Mutex::new(HashMap::new()));
let last_blockhash = Arc::new(Mutex::new((Hash::default(), Instant::now())));
let metadata_limiter = Arc::new(Mutex::new(()));
let swap_limiter = Arc::new(Mutex::new(()));
let http_client = Client::new();
let mut bot = Self {
config,
rpc_client,
keypair,
price_cache,
active_trades,
last_blockhash,
metadata_limiter,
swap_limiter,
http_client,
};
bot.load_state().await?;
info!("Bot initialized successfully.");
Ok(bot)
}
fn load_keypair(config: &Config) -> Result<Keypair> {
if let Ok(keypair_58) = config.get_string("keypair_58") {
let bytes = bs58::decode(&keypair_58)
.into_vec()
.map_err(|e| anyhow!("Base58 decode error: {}", e))?;
Keypair::from_bytes(&bytes)
.map_err(|e| anyhow!("Invalid keypair bytes: {}", e))
} else if let Ok(keypair_json_path) = config.get_string("keypair_json") {
let json_content = std::fs::read_to_string(keypair_json_path)?;
let secret_key: Vec<u8> = serde_json::from_str(&json_content)?;
Keypair::from_bytes(&secret_key)
.map_err(|e| anyhow!("Invalid JSON keypair bytes: {}", e))
} else if let Ok(keypair_64) = config.get_string("keypair_64") {
let bytes: Vec<u8> = keypair_64
.split(',')
.map(|s| s.trim().parse::<u8>().map_err(|e| anyhow!("Failed to parse byte '{}': {}", s.trim(), e)))
.collect::<Result<Vec<u8>>>()?;
let bytes_array: [u8; 64] = bytes[..].try_into().map_err(|_| {
anyhow!("Keypair must be exactly 64 bytes long, but got {}", bytes.len())
})?;
Keypair::from_bytes(&bytes_array).map_err(|e| anyhow!("Invalid 64-byte keypair: {}", e))
} else {
Err(anyhow!("No valid keypair found in config"))
}
}
#[instrument(skip(self))]
async fn fetch_and_cache_token_price(&self, token_address: &str) -> Result<f64> {
info!("Attempting to fetch price for token {}", token_address);
if let Some(price) = self.price_cache.lock().await.get(token_address) {
trace!(
"Price for {} retrieved from cache: {}.",
token_address,
price
);
return Ok(price);
}
let _guard = self.metadata_limiter.lock().await;
let price = self.fetch_token_price(token_address).await?;
self.price_cache
.lock()
.await
.set(token_address.to_string(), price);
info!("Fetched and cached price for {}: {}", token_address, price);
Ok(price)
}
#[instrument(skip(self))]
async fn fetch_token_price(&self, token_address: &str) -> Result<f64> {
debug!("Fetching price for token {}.", token_address);
let metadata = self.fetch_metadata(token_address).await?;
metadata
.get("price")
.and_then(serde_json::Value::as_f64)
.ok_or_else(|| {
error!("No price found for token {}", token_address);
anyhow!("No price found for token {}", token_address)
})
}
#[instrument(skip(self))]
async fn fetch_metadata(&self, token_address: &str) -> Result<serde_json::Value> {
let url = format!(
"https://api.helius.xyz/v0/metadata/accounts?account={}",
token_address
);
let response = self
.http_client
.get(&url)
.header(
"Authorization",
format!("Bearer {}", self.config.get_string("helius_api_key")?),
)
.send()
.await?
.json::<serde_json::Value>()
.await?;
trace!("Metadata for {} fetched: {:?}", token_address, response);
Ok(response)
}
#[instrument(skip(self))]
async fn run(&self) -> Result<()> {
let mut reconnect_interval = interval(Duration::from_secs(5));
let mut clear_cache_interval = interval(Duration::from_secs(300)); // Every 5 minutes
loop {
info!("Establishing WebSocket connection...");
match self.connect_and_listen().await {
Ok(_) => {
error!("WebSocket connection closed unexpectedly");
}
Err(e) => {
error!("Error in WebSocket connection: {}", e);
}
}
info!("WebSocket connection ended. Waiting before reconnecting...");
tokio::select! {
_ = reconnect_interval.tick() => {},
_ = clear_cache_interval.tick() => {
self.price_cache.lock().await.clear_expired();
},
}
}
}
#[instrument(skip(self))]
async fn connect_and_listen(&self) -> Result<()> {
let (ws_stream, _) =
connect_async(&self.config.get_string("helius_websocket_url")?).await?;
let (mut write, mut read) = ws_stream.split();
write
.send(WsMessage::Text(
serde_json::json!({
"jsonrpc": "2.0",
"id": 1,
"method": "subscribePoolCreations",
"params": []
})
.to_string(),
))
.await?;
info!("Connected to Helius WebSocket. Subscribed to pool creations.");
let mut price_check_interval = interval(PRICE_CHECK_INTERVAL);
let mut clear_cache_interval = interval(Duration::from_secs(300)); // Every 5 minutes
loop {
tokio::select! {
Some(msg) = read.next() => {
match msg {
Ok(WsMessage::Text(text)) => {
if let Err(e) = self.handle_event(&text).await {
error!("Error handling event: {}", e);
}
}
Ok(WsMessage::Close(_)) => {
info!("WebSocket connection closed by server");
return Ok(());
}
Ok(_) => {},
Err(e) => {
error!("WebSocket error: {}", e);
return Err(e.into());
}
}
}
_ = price_check_interval.tick() => {
if !self.active_trades.lock().await.is_empty() {
debug!("Performing scheduled trade checks...");
if let Err(e) = self.check_active_trades().await {
error!("Error executing scheduled trade checks: {}", e);
}
}
}
_ = clear_cache_interval.tick() => {
self.price_cache.lock().await.clear_expired();
}
}
}
}
#[instrument(skip(self))]
async fn handle_event(&self, text: &str) -> Result<()> {
let event: serde_json::Value = serde_json::from_str(text)?;
if let Some(params) = event.get("params") {
if let Some(token_address) = params.get("tokenAddress").and_then(serde_json::Value::as_str) {
info!("Token {} detected from WebSocket event.", token_address);
if self.is_valid_pool(token_address).await? {
self.attempt_buy(token_address).await?;
} else {
info!("Token {} failed validation checks. Skipping.", token_address);
}
} else {
warn!("No token address found in event params.");
}
}
Ok(())
}
#[instrument(skip(self))]
async fn is_valid_pool(&self, token_address: &str) -> Result<bool> {
debug!(
"Validating if token {} belongs to a Raydium pool.",
token_address
);
let metadata = self.fetch_metadata(token_address).await?;
let is_raydium_pool = metadata
.get("updateAuthority")
.and_then(serde_json::Value::as_str)
.map_or(false, |auth| auth == RAYDIUM_AMM_PROGRAM_ID);
if !is_raydium_pool {
info!("Token {} is not a Raydium pool.", token_address);
return Ok(false);
}
let is_spl_token = metadata.get("tokenStandard").and_then(serde_json::Value::as_str) == Some("SPL");
if !is_spl_token {
info!("Token {} is not an SPL standard token.", token_address);
return Ok(false);
}
let liquidity = metadata
.get("liquidity")
.and_then(serde_json::Value::as_f64)
.unwrap_or(0.0);
if liquidity < MIN_LIQUIDITY || liquidity > MAX_LIQUIDITY {
info!("Token {} liquidity {} is outside the acceptable range ({} - {}).", token_address, liquidity, MIN_LIQUIDITY, MAX_LIQUIDITY);
return Ok(false);
}
info!("Token {} passed all validation checks.", token_address);
Ok(true)
}
#[instrument(skip(self))]
async fn attempt_buy(&self, token_address: &str) -> Result<()> {
info!("Attempting to buy token {}.", token_address);
let mut attempts = 0;
while attempts < MAX_BUY_ATTEMPTS {
match self.execute_buy(token_address).await {
Ok(_) => {
info!("Successfully bought token {}.", token_address);
return Ok(());
}
Err(e) => {
warn!("Failed to buy token {}: {}. Attempt {} of {}.", token_address, e, attempts + 1, MAX_BUY_ATTEMPTS);
attempts += 1;
tokio::time::sleep(BUY_ATTEMPT_DELAY).await;
}
}
}
error!("Failed to buy token {} after {} attempts.", token_address, MAX_BUY_ATTEMPTS);
Ok(())
}
#[instrument(skip(self))]
async fn execute_buy(&self, token_address: &str) -> Result<()> {
let _guard = self.swap_limiter.lock().await;
let amount = self.config.get_int("buy_amount")? as u64;
let slippage = self.config.get_float("slippage")?;
let swap_response = self.http_client
.post("https://api.raydium.io/v2/main/swap")
.json(&json!({
"inToken": WSOL_MINT,
"outToken": token_address,
"amount": amount,
"fixedSide": "in",
"slippage": slippage
}))
.send()
.await?
.json::<serde_json::Value>()
.await?;
let transaction_data = base64::decode(swap_response["swapTransaction"].as_str().unwrap())?;
let transaction: Transaction = bincode::deserialize(&transaction_data)?;
// Use the existing message from the transaction
let message = transaction.message.clone();
// Create a new transaction with the existing message and sign it
let mut new_transaction = Transaction::new_unsigned(message);
let recent_blockhash = self.get_recent_blockhash().await?;
new_transaction.sign(&[&self.keypair], recent_blockhash);
// Use the new_transaction for further processing
let _serialized_transaction = bincode::serialize(&new_transaction)?;
let signature = self.rpc_client.send_transaction(&new_transaction)?;
info!("Buy transaction sent for token {}. Signature: {}", token_address, signature);
let buy_price = self.fetch_and_cache_token_price(token_address).await?;
let take_profit_price = buy_price * (1.0 + self.config.get_float("take_profit_percentage")? / 100.0);
let stop_loss_price = buy_price * (1.0 - self.config.get_float("stop_loss_percentage")? / 100.0);
let trade = Trade {
token_address: token_address.to_string(),
amount,
buy_price,
take_profit_price,
stop_loss_price,
timestamp: SystemTime::now()
.duration_since(UNIX_EPOCH)?
.as_secs(),
};
self.active_trades.lock().await.insert(token_address.to_string(), trade);
self.save_state().await?;
info!("Trade added for token {}. Buy price: {}, Take profit: {}, Stop loss: {}",
token_address, buy_price, take_profit_price, stop_loss_price);
Ok(())
}
#[instrument(skip(self))]
async fn check_active_trades(&self) -> Result<()> {
let mut trades_to_remove = Vec::new();
for (token_address, trade) in self.active_trades.lock().await.iter() {
let current_price = self.fetch_and_cache_token_price(token_address).await?;
if current_price >= trade.take_profit_price || current_price <= trade.stop_loss_price {
if let Err(e) = self.execute_sell(token_address, trade.amount).await {
error!("Failed to sell token {}: {}", token_address, e);
} else {
trades_to_remove.push(token_address.clone());
}
}
}
for token_address in trades_to_remove {
self.active_trades.lock().await.remove(&token_address);
}
self.save_state().await?;
Ok(())
}
#[instrument(skip(self))]
async fn execute_sell(&self, token_address: &str, amount: u64) -> Result<()> {
let _guard = self.swap_limiter.lock().await;
let slippage = self.config.get_float("slippage")?;
let swap_response = self.http_client
.post("https://api.raydium.io/v2/main/swap")
.json(&json!({
"inToken": token_address,
"outToken": WSOL_MINT,
"amount": amount,
"fixedSide": "in",
"slippage": slippage
}))
.send()
.await?
.json::<serde_json::Value>()
.await?;
let transaction_data = base64::decode(swap_response["swapTransaction"].as_str().unwrap())?;
let transaction: Transaction = bincode::deserialize(&transaction_data)?;
// Use the existing message from the transaction
let message = transaction.message.clone();
// Create a new transaction with the existing message and sign it
let mut new_transaction = Transaction::new_unsigned(message);
let recent_blockhash = self.get_recent_blockhash().await?;
new_transaction.sign(&[&self.keypair], recent_blockhash);
// Use the new_transaction for further processing
let _serialized_transaction = bincode::serialize(&new_transaction)?;
let signature = self.rpc_client.send_transaction(&new_transaction)?;
info!("Sell transaction sent for token {}. Signature: {}", token_address, signature);
Ok(())
}
#[instrument(skip(self))]
async fn get_recent_blockhash(&self) -> Result<Hash> {
let mut last_blockhash = self.last_blockhash.lock().await;
if last_blockhash.1.elapsed() > Duration::from_secs(120) {
*last_blockhash = (
self.rpc_client.get_latest_blockhash()?,
Instant::now(),
);
}
Ok(last_blockhash.0)
}
#[instrument(skip(self))]
async fn save_state(&self) -> Result<()> {
let active_trades = self.active_trades.lock().await;
let serialized = serde_json::to_string(&*active_trades)?;
let mut file = OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(STATE_FILE)?;
file.write_all(serialized.as_bytes())?;
Ok(())
}
#[instrument(skip(self))]
async fn load_state(&mut self) -> Result<()> {
let mut file = match File::open(STATE_FILE) {
Ok(file) => file,
Err(_) => return Ok(()), // File doesn't exist, which is fine for first run
};
let mut contents = String::new();
file.read_to_string(&mut contents)?;
let trades: HashMap<String, Trade> = serde_json::from_str(&contents)?;
*self.active_trades.lock().await = trades;
Ok(())
}
}
#[tokio::main]
async fn main() -> Result<()> {
setup_logging()?;
info!("Starting Solana Sniper Bot...");
// Here, I've hardcoded the path to the configuration file
let bot = Bot::new("C:\\solana_rust_bot\\config.toml").await?;
bot.run().await
}
fn setup_logging() -> Result<()> {
let file_appender = tracing_appender::rolling::daily("log", "output.log");
let (non_blocking, _guard) = tracing_appender::non_blocking(file_appender);
tracing_subscriber::fmt()
.with_env_filter(EnvFilter::from_default_env())
.with_writer(non_blocking)
.with_span_events(FmtSpan::CLOSE)
.init();
Ok(())
} WILL THIS ERROR GO AWAY ON ITS OWN OR WHAT DO I GOTTA DO AND IS THE SCRIPT CORRECT NOW ??? Compiling solana-sniper-bot v0.1.0 (C:\solana_rust_bot)
warning: constant MAX_ACTIVE_TRADES is never used
--> src/main.rs:26:7
|
26 | const MAX_ACTIVE_TRADES: usize = 5;
| ^^^^^^^^^^^^^^^^^
|
= note: #[warn(dead_code)] on by default
warning: solana-sniper-bot (bin "solana-sniper-bot") generated 1 warning
Finished release profile [optimized] target(s) in 4.19s
PS C:\solana_rust_bot>