use solana_sdk::{
pubkey::Pubkey,
instruction::Instruction,
signature::Signature,
};
use {
anyhow::{anyhow, Result},
dashmap::DashMap,
futures_util::{SinkExt, StreamExt},
log::{info, warn},
serde_json::{json, Value},
std::{sync::Arc, time::{Duration, Instant}},
tokio::{
fs::File,
io::{AsyncReadExt, AsyncWriteExt},
sync::Mutex,
time::interval
},
tokio_tungstenite::{connect_async, tungstenite::protocol::Message as WsMessage},
url::Url,
};
// Configuration Constants
const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com";
const WALLET_PUBLIC_KEY: &str = "YOUR_WALLET_PUBLIC_KEY";
const HELIUS_API_KEY: &str = "YOUR_HELIUS_API_KEY";
const SOL_MINT: &str = "So11111111111111111111111111111111111111112";
// Trading Parameters
const MIN_SUPPLY: u64 = 900_000_000;
const REQUIRED_MUTABLE: bool = false;
const REQUIRED_BURNT: bool = true;
const REQUIRED_FROZEN: bool = false;
const TRADE_AMOUNT: u64 = 5_000_000;
const PRIORITY_FEE: u64 = 15000;
const MAX_CONCURRENT_TRADES: usize = 5;
const PROFIT_TARGET: f64 = 20.0;
const STOP_LOSS: f64 = -5.0;
const MAX_TOKEN_AGE_SECONDS: u64 = 3600; // 1 hour in seconds
#[derive(Debug, Clone)]
struct ActiveTrade {
token_mint: String,
entry_price: f64,
amount: u64,
start_time: Instant,
last_price: Arc<Mutex>,
}
#[derive(Debug)]
struct RaydiumPool {
amm_id: Pubkey,
price: f64,
}
#[derive(Debug)]
struct TradeManager {
active_trades: DashMap<String, ActiveTrade>,
token_blacklist: DashMap<String, ()>,
}
impl TradeManager {
fn new() -> Self {
Self {
active_trades: DashMap::new(),
token_blacklist: DashMap::new(),
}
}
async fn get_quote(&self, input_mint: &str, output_mint: &str, amount: u64) -> Result<Value> {
let url = format!(
"{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50&onlyDirectRoutes=true&wrapUnwrapSOL=true",
JUPITER_API, input_mint, output_mint, amount
);
let response = reqwest::get(&url)
.await?
.json::<Value>()
.await?;
info!("💫 Quote received: {}", serde_json::to_string_pretty(&response)?);
Ok(response)
}
async fn get_swap_data(&self, quote: Value) -> Result<String> {
let swap_request = json!({
"quoteResponse": quote,
"userPublicKey": WALLET_PUBLIC_KEY,
"wrapUnwrapSOL": true,
"computeUnitPriceMicroLamports": PRIORITY_FEE,
"priorityFeeLamports": PRIORITY_FEE,
"asLegacyTransaction": false,
"maxAccounts": 64,
"verifyWallet": true
});
let response = reqwest::Client::new()
.post(format!("{}/swap", JUPITER_API))
.json(&swap_request)
.send()
.await?
.json::<Value>()
.await?;
info!("🚀 Swap response: {}", serde_json::to_string_pretty(&response)?);
// Check for market not found error
if let Some(error) = response.get("error") {
if error.as_str().unwrap_or("").contains("Market") {
info!("🔄 Market setup in progress, waiting...");
return Ok("retry".to_string());
}
}
match response.get("swapTransaction") {
Some(tx) => Ok(tx.as_str().unwrap_or_default().to_string()),
None => Ok("retry".to_string()) // Return retry signal instead of error
}
}
async fn send_priority_tx(&self, swap_data: String) -> Result<String> {
// Skip if we got a retry signal
if swap_data == "retry" {
return Ok("waiting_for_market".to_string());
}
let helius_request = json!({
"jsonrpc": "2.0",
"id": "helius-priority",
"method": "sendTransaction",
"params": [
swap_data,
{
"encoding": "base64",
"maxRetries": 0,
"skipPreflight": true,
"preflightCommitment": "processed",
"priorityFee": PRIORITY_FEE
}
]
});
let response = reqwest::Client::new()
.post(HELIUS_RPC)
.header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
.json(&helius_request)
.send()
.await?
.json::<Value>()
.await?;
info!("💎 Transaction response: {}", serde_json::to_string_pretty(&response)?);
match response.get("result") {
Some(result) => Ok(result.as_str().unwrap_or_default().to_string()),
None => Ok("transaction_pending".to_string()) // Keep the beast running!
}
}
async fn fetch_price(&self, token_mint: &str) -> Result<f64> {
let request = json!({
"jsonrpc": "2.0",
"id": "price-check",
"method": "getAsset",
"params": {
"id": token_mint,
"displayOptions": {
"showFungible": true
}
}
});
let response = reqwest::Client::new()
.post(HELIUS_RPC)
.json(&request)
.send()
.await?
.json::<Value>()
.await?;
let price = response["result"]["token_info"]["price_info"]["price_per_token"]
.as_f64()
.ok_or_else(|| anyhow!("Failed to get price"))?;
Ok(price)
}
async fn monitor_trades(&self) {
let mut interval = interval(Duration::from_millis(100));
let mut last_trade_count = 0;
let last_prices: DashMap<String, f64> = DashMap::new();
loop {
interval.tick().await;
let current_trades = self.active_trades.len();
if current_trades != last_trade_count {
info!("💫 Active Trades: {}", current_trades);
last_trade_count = current_trades;
}
for trade in self.active_trades.iter() {
let mint = &trade.token_mint;
if let Ok(current_price) = self.fetch_price(mint).await {
let profit_percent = (current_price - trade.entry_price) / trade.entry_price * 100.0;
// Check for significant price movement
if let Some(last_price) = last_prices.get(mint) {
if (current_price - *last_price).abs() > (current_price * 0.005) {
info!("🔄 Token: {} | Price: {} | Profit: {:.2}%", mint, current_price, profit_percent);
last_prices.insert(mint.to_string(), current_price);
}
} else {
last_prices.insert(mint.to_string(), current_price);
info!("🆕 New Token Tracked: {} | Initial Price: {}", mint, current_price);
}
if profit_percent >= PROFIT_TARGET {
info!("🎯 Take profit hit for {}", mint);
if let Err(e) = self.execute_sell(mint, current_price).await {
warn!("❌ Take profit sell failed: {}", e);
}
} else if profit_percent <= STOP_LOSS {
warn!("⚠️ Stop loss hit for {}", mint);
if let Err(e) = self.execute_sell(mint, current_price).await {
warn!("❌ Stop loss sell failed: {}", e);
}
}
*trade.last_price.lock().await = current_price;
}
}
}
}
async fn execute_buy(&self, token_mint: &str) -> Result<()> {
// Check if token is tradeable first
let quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
// If we get an error about token not being tradeable, we'll wait and retry
if quote.get("error").is_some() {
info!("🔄 Token {} not tradeable yet, waiting for liquidity...", token_mint);
// Retry loop for 30 seconds
for _ in 0..30 {
tokio::time::sleep(Duration::from_secs(1)).await;
let retry_quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
if retry_quote.get("error").is_none() {
info!("✅ Token {} now tradeable!", token_mint);
// Get swap transaction data
let swap_data = self.get_swap_data(retry_quote).await?;
// Execute the swap with priority
let signature = self.send_priority_tx(swap_data).await?;
// Get initial price
let entry_price = self.fetch_price(token_mint).await?;
// Add to active trades
self.active_trades.insert(
token_mint.to_string(),
ActiveTrade {
token_mint: token_mint.to_string(),
entry_price,
amount: TRADE_AMOUNT,
start_time: Instant::now(),
last_price: Arc::new(Mutex::new(entry_price)),
}
);
info!("💎 Bought {} at price {} - TX: {}", token_mint, entry_price, signature);
return Ok(());
}
}
info!("⏱️ Timeout waiting for {} to become tradeable", token_mint);
return Ok(());
}
// If token is already tradeable, execute immediately
let swap_data = self.get_swap_data(quote).await?;
let signature = self.send_priority_tx(swap_data).await?;
let entry_price = self.fetch_price(token_mint).await?;
self.active_trades.insert(
token_mint.to_string(),
ActiveTrade {
token_mint: token_mint.to_string(),
entry_price,
amount: TRADE_AMOUNT,
start_time: Instant::now(),
last_price: Arc::new(Mutex::new(entry_price)),
}
);
info!("💎 Bought {} at price {} - TX: {}", token_mint, entry_price, signature);
Ok(())
}
async fn execute_sell(&self, token_mint: &str, price: f64) -> Result<()> {
let trade = self.active_trades.get(token_mint)
.ok_or_else(|| anyhow!("Trade not found"))?;
let quote = self.get_quote(token_mint, SOL_MINT, trade.amount).await?;
let swap_data = self.get_swap_data(quote).await?;
let signature = self.send_priority_tx(swap_data).await?;
info!("💰 Sold {} at price {} - TX: {}", token_mint, price, signature);
self.active_trades.remove(token_mint);
Ok(())
}
async fn validate_token(&self, value: &Value) -> Result<bool, Box<dyn std::error::Error>> {
let token_info = value["params"]["result"]["value"]["account"]["data"]["parsed"]["info"].as_object().ok_or("Invalid token info")?;
let supply = token_info["supply"].as_str().ok_or("Supply not found")?.parse::<u64>()?;
let decimals = token_info["decimals"].as_u64().ok_or("Decimals not found")?;
let is_frozen = token_info["freezeAuthority"].is_null();
let is_burnt = token_info["mintAuthority"].is_null();
let is_mutable = !token_info["mintAuthority"].is_null();
let name = token_info["name"].as_str().ok_or("Name not found")?;
let symbol = token_info["symbol"].as_str().ok_or("Symbol not found")?;
let actual_supply = supply as f64 / 10f64.powi(decimals as i32);
if actual_supply < MIN_SUPPLY as f64 {
return Ok(false);
}
if !is_frozen {
return Ok(false);
}
if !is_burnt {
return Ok(false);
}
if !is_mutable {
return Ok(false);
}
// Additional custom criteria checks here
Ok(true)
}
async fn fetch_raydium_pool(&self, _token_mint: &str) -> Result<RaydiumPool> {
let pool = RaydiumPool {
amm_id: Pubkey::new_unique(),
price: 1.0,
};
Ok(pool)
}
fn create_swap_instruction(&self, _token_mint: &str, _amm_id: &Pubkey, _price: f64) -> Result<Instruction> {
let ix = Instruction {
program_id: Pubkey::new_unique(),
accounts: vec![],
data: vec![],
};
Ok(ix)
}
async fn send_transaction(&self, _instructions: &[Instruction]) -> Result<Signature> {
let signature = Signature::new_unique();
Ok(signature)
}
async fn handle_new_token(&self, token_mint: &str) -> Result<()> {
info!("🎯 Analyzing token for tradeability: {}", token_mint);
// Check if token is tradeable
let quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
if quote.get("error").is_some() {
info!("⛔ Token {} is not tradeable, skipping...", token_mint);
return Ok(());
}
// Check token age
let token_request = json!({
"jsonrpc": "2.0",
"id": "token-check",
"method": "getAsset",
"params": {
"id": token_mint
}
});
let response = reqwest::Client::new()
.post(HELIUS_RPC)
.header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
.json(&token_request)
.send()
.await?
.json::<Value>()
.await?;
let creation_time = response["result"]["creationTime"].as_u64().unwrap_or(0);
let current_time = Instant::now().elapsed().as_secs();
if current_time - creation_time > MAX_TOKEN_AGE_SECONDS {
info!("⏳ Token {} is too old, skipping...", token_mint);
return Ok(());
}
info!("✅ Token {} is tradeable and within age limit, proceeding with trade setup...", token_mint);
// Execute Jupiter buy
self.execute_buy(token_mint).await?;
// Get Raydium pool info as backup
let pool = self.fetch_raydium_pool(token_mint).await?;
// Create backup swap transaction
let swap_ix = self.create_swap_instruction(
token_mint,
&pool.amm_id,
pool.price
)?;
// Send and confirm backup transaction if needed
let signature = self.send_transaction(&[swap_ix]).await?;
info!("🚀 Backup swap ready! Signature: {}", signature);
// Add token to blacklist to avoid processing again
self.token_blacklist.insert(token_mint.to_string(), ());
Ok(())
}
async fn save_state(&self) -> Result<()> {
let state = self.active_trades.iter()
.map(|trade| {
let last_price = *trade.last_price.blocking_lock(); // Use blocking_lock instead of await
json!({
"token_mint": trade.token_mint,
"entry_price": trade.entry_price,
"amount": trade.amount,
"start_time": trade.start_time.elapsed().as_secs(),
"last_price": last_price
})
})
.collect::<Vec<_>>();
let mut file = File::create("trade_state.json").await?;
file.write_all(serde_json::to_string(&state)?.as_bytes()).await?;
Ok(())
}
async fn load_state(&self) -> Result<()> {
if let Ok(mut file) = File::open("trade_state.json").await {
let mut contents = String::new();
file.read_to_string(&mut contents).await?;
let states: Vec<Value> = serde_json::from_str(&contents)?;
for state in states {
self.active_trades.insert(
state["token_mint"].as_str().unwrap().to_string(),
ActiveTrade {
token_mint: state["token_mint"].as_str().unwrap().to_string(),
entry_price: state["entry_price"].as_f64().unwrap(),
amount: state["amount"].as_u64().unwrap(),
start_time: Instant::now(),
last_price: Arc::new(Mutex::new(state["last_price"].as_f64().unwrap())),
}
);
}
}
Ok(())
}
async fn validate_and_execute_trade(&self, token_mint: &str, amount: u64) -> Result<String, Box<dyn std::error::Error>> {
let start = Instant::now();
// Check liquidity first - fastest filter
println!("🔍 Checking liquidity...");
let quote = self.get_quote(SOL_MINT, token_mint, amount).await?;
if quote.get("error").is_some() {
println!("⚡ Skipping - No liquidity");
return Ok("no_liquidity".to_string());
}
// Get token data
let token_request = json!({
"jsonrpc": "2.0",
"id": "token-check",
"method": "getAsset",
"params": {
"id": token_mint
}
});
let response = reqwest::Client::new()
.post(HELIUS_RPC)
.header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
.json(&token_request)
.send()
.await?
.json::<Value>()
.await?;
// Validate token criteria
let token_info = &response["result"];
let supply = token_info["token_info"]["supply"]
.as_str()
.unwrap_or("0")
.parse::<u64>()?;
let is_frozen = token_info["ownership"]["frozen"].as_bool().unwrap_or(true);
let is_burnt = token_info["burnt"].as_bool().unwrap_or(false);
let is_mutable = token_info["mutable"].as_bool().unwrap_or(true);
if supply < MIN_SUPPLY || is_frozen || !is_burnt || is_mutable {
println!("⚡ Token doesn't meet criteria");
return Ok("invalid_token".to_string());
}
println!("✅ Token validated! Executing trade...");
// Execute the proven fast trade
println!("🚀 Building swap...");
let swap_data = self.get_swap_data(quote).await?;
println!("💨 Sending priority transaction...");
let signature = self.send_priority_tx(swap_data).await?;
println!("✨ Total execution time: {:?}", start.elapsed());
Ok(signature)
}
}
#[tokio::main]
async fn main() -> Result<()> {
env_logger::init();
info!("🚀 Trading bot initialized!");
loop {
match run_bot().await {
Ok(_) => info!("🔄 Bot cycle completed, continuing the hunt..."),
Err(e) => {
warn!("⚠️ Bot encountered error: {}. Restarting in 5 seconds...", e);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
}
async fn run_bot() -> Result<()> {
let trade_manager = Arc::new(TradeManager::new());
trade_manager.load_state().await?;
let shutdown_manager = trade_manager.clone();
ctrlc::set_handler(move || {
let shutdown_clone = shutdown_manager.clone();
tokio::runtime::Runtime::new().unwrap().block_on(async move {
info!("🛑 Gracefully shutting down...");
shutdown_clone.save_state().await.unwrap();
std::process::exit(0);
});
})?;
let ws_url = Url::parse(WS_URL)?;
loop { // Infinite WebSocket reconnection loop
info!("📡 Connecting to WebSocket...");
match connect_async(ws_url.clone()).await {
Ok((ws_stream, _)) => {
let (mut write, mut read) = ws_stream.split();
let monitor_manager = trade_manager.clone();
tokio::spawn(async move {
monitor_manager.monitor_trades().await;
});
let subscribe_msg = json!({
"jsonrpc": "2.0",
"id": "1",
"method": "programSubscribe",
"params": [
"TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
{
"encoding": "jsonParsed",
"filters": [
{
"dataSize": 82
}
]
}
]
});
if let Err(e) = write.send(WsMessage::Text(subscribe_msg.to_string())).await {
warn!("⚠️ WebSocket subscription error: {}. Reconnecting...", e);
continue;
}
info!("📡 WebSocket subscription active!");
while let Some(msg_result) = read.next().await {
match msg_result {
Ok(WsMessage::Text(text)) => {
let value: Value = match serde_json::from_str(&text) {
Ok(v) => v,
Err(e) => {
info!("⚡ Skipping non-token message: {}", e);
continue;
}
};
if let Some(params) = value.get("params") {
if let Some(result) = params.get("result") {
if let Some(token_value) = result.get("value") {
if let Some(account) = token_value.get("account") {
if let Some(data) = account.get("data") {
if let Some(parsed) = data.get("parsed") {
if let Some(info) = parsed.get("info") {
let token_mint = token_value["pubkey"].as_str().unwrap_or("unknown");
let supply = info["supply"].as_str().unwrap_or("0");
let decimals = info["decimals"].as_u64().unwrap_or(0);
let freeze_authority = info["freezeAuthority"].is_null();
let mint_authority = info["mintAuthority"].is_null();
info!("🎯 Analyzing Token:");
info!("📍 Mint: {}", token_mint);
info!("💰 Supply: {}", supply);
info!("🔢 Decimals: {}", decimals);
info!("🔒 Burnt: {}", mint_authority);
info!("❄️ Frozen: {}", freeze_authority);
if let Ok(true) = trade_manager.validate_token(&value).await {
info!("✅ Token VALIDATED! Starting trade sequence!");
if let Err(e) = trade_manager.handle_new_token(token_mint).await {
info!("⚡ Trade attempt complete: {}", e);
}
} else {
info!("⏭️ Token didn't meet criteria, continuing hunt...");
}
}
}
}
}
}
}
}
}
Err(e) => {
info!("📡 WebSocket message error: {}. Reconnecting...", e);
break;
}
_ => {
info!("⚡ Non-text message received, continuing...");
}
}
}
}
Err(e) => {
warn!("⚠️ WebSocket connection error: {}. Retrying in 5 seconds...", e);
tokio::time::sleep(Duration::from_secs(5)).await;
}
}
}
} whats the problem?