can u help me with the spacing in this script please mod config; mod pricefeed; mod…
- User
can u help me with the spacing in this script please mod config; mod price_feed; mod state_manager;
use { anyhow::{anyhow, Result}, chrono::{DateTime, Utc}, config::Config, dashmap::DashMap, parking_lot::RwLock, price_feed::{PriceFeed, TokenPrice}, serde::{Deserialize, Serialize}, solana_client::rpc_client::RpcClient, solana_program::instruction::Instruction, solana_sdk::{ commitment_config::CommitmentConfig, pubkey::Pubkey, signature::{Keypair, read_keypair_file, Signer}, transaction::Transaction, }, spl_associated_token_account::get_associated_token_address, state_manager::State, std::{ str::FromStr, sync::Arc, time::Duration, }, tracing::{error, info, warn}, uuid::Uuid, };
const WSOL_MINT: &str = "So11111111111111111111111111111111111111112"; const STATE_FILE: &str = "bot_state.json";
#[derive(Debug, Clone, Serialize, Deserialize)] pub struct Trade { pub id: String, pub token_mint: String, pub amount: f64, pub entry_price: f64, pub take_profit_price: f64, pub stop_loss_price: f64, pub timestamp: DateTime, pub status: TradeStatus, }
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum TradeStatus { Active, PendingBuy, PendingSell, Completed, Failed, }
pub struct MoneyPrinter { config: Config, rpc: Arc, keypair: Arc, wsol_account: Pubkey, price_feed: Arc, active_trades: Arc<DashMap<String, Trade>>, state: Arc<RwLock>, shutdown: Arc<RwLock>, }
impl MoneyPrinter { pub async fn new() -> Result { let config = Config::load()?; let state = State::load(STATE_FILE)?;
Ok(Self { rpc: Arc::new(RpcClient::new_with_commitment( config.rpc_url.clone(), CommitmentConfig::finalized(), )), keypair: Arc::new(read_keypair_file(&config.keypair_path).expect("Failed to read keypair")), wsol_account: Pubkey::from_str(&config.wsol_account)?, price_feed: Arc::new(PriceFeed::new(config.helius_api_key.clone())), active_trades: Arc::new(DashMap::new()), state: Arc::new(RwLock::new(state)), shutdown: Arc::new(RwLock::new(false)), config, }) } async fn initialize(&self) -> Result<()> { info!("🚀 Initializing Money Printer v1.0"); self.check_balances().await?; self.load_active_trades()?; Ok(()) } async fn check_balances(&self) -> Result<()> { let sol_balance = self.rpc.get_balance(&self.keypair.pubkey())? as f64 / 1e9; info!("💰 SOL Balance: {}", sol_balance); if sol_balance < self.config.min_sol_balance { warn!("⚠️ Low SOL balance!"); } Ok(()) } fn load_active_trades(&self) -> Result<()> { let state = self.state.read(); for trade in &state.active_trades { self.active_trades.insert(trade.id.clone(), trade.clone()); } info!("📊 Loaded {} active trades", self.active_trades.len()); Ok(()) } pub async fn start(self: Arc<Self>) -> Result<()> { let market_scanner = self.clone().spawn_market_scanner(); let trade_manager = self.clone().spawn_trade_manager(); let shutdown_handler = self.clone(); tokio::select! { _ = market_scanner => warn!("Market scanner stopped"), _ = trade_manager => warn!("Trade manager stopped"), _ = shutdown_handler.handle_shutdown() => info!("Shutdown complete"), } self.save_state()?; Ok(()) } fn spawn_market_scanner(self: Arc<Self>) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_millis(100)); while !*self.shutdown.read() { interval.tick().await; if let Err(e) = self.scan_market().await { error!("Market scanner error: {}", e); } } }) } fn spawn_trade_manager(self: Arc<Self>) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(1)); while !*self.shutdown.read() { interval.tick().await; if let Err(e) = self.manage_trades().await { error!("Trade manager error: {}", e); } } }) } async fn scan_market(&self) -> Result<()> { let url = format!( "https://api.helius.xyz/v0/token-metadata?api-key={}", self.config.helius_api_key ); let response = reqwest::Client::new() .post(&url) .json(&serde_json::json!({ "query": { "programs": ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"], "timeframe": "1d", "minLiquidity": 1000, "minVolume": 5000 } })) .send() .await?; let tokens = response.json::<Vec<serde_json::Value>>().await?; for token in tokens { if let Some(mint) = token["mint"].as_str() { if let Ok(price_data) = self.price_feed.fetch_price(mint).await { if self.is_good_opportunity(&price_data) { info!("🎯 Found opportunity: {} at ${:.6}", mint, price_data.price); self.create_trade(mint, price_data).await?; } } } } Ok(()) } fn is_good_opportunity(&self, price_data: &TokenPrice) -> bool { price_data.liquidity > 1000.0 && price_data.volume_24h > 5000.0 && price_data.price_change_24h > 5.0 } async fn create_trade(&self, mint: &str, price_data: TokenPrice) -> Result<()> { let position_size = (price_data.volume_24h * 0.001).min(0.1); let volatility_multiplier = if price_data.price_change_24h > 10.0 { 1.08 } else { 1.05 }; let trade_id = Uuid::new_v4().to_string(); let trade = Trade { id: trade_id.clone(), token_mint: mint.to_string(), amount: position_size, entry_price: price_data.price, take_profit_price: price_data.price * volatility_multiplier, stop_loss_price: price_data.price * 0.95, timestamp: Utc::now(), status: TradeStatus::Active, }; info!("🎯 Creating trade for {} with {}% target", mint, (volatility_multiplier - 1.0) * 100.0); self.active_trades.insert(trade_id, trade.clone()); self.state.write().active_trades.push(trade); Ok(()) } async fn manage_trades(&self) -> Result<()> { for trade in self.active_trades.iter() { if let Ok(price) = self.price_feed.fetch_price(&trade.token_mint).await { self.check_trade_conditions(&trade, &price).await?; } } Ok(()) } async fn check_trade_conditions(&self, trade: &Trade, price: &TokenPrice) -> Result<()> { if price.price >= trade.take_profit_price { info!("🎯 Take profit hit for trade {}", trade.id); self.execute_sell(trade).await?; } else if price.price <= trade.stop_loss_price { info!("🛑 Stop loss hit for trade {}", trade.id); self.execute_sell(trade).await?; } Ok(()) } fn spawn_trade_manager(self: Arc<Self>) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(1)); while !*self.shutdown.read() { interval.tick().await; if let Err(e) = self.manage_trades().await { error!("Trade manager error: {}", e); } } }) } async fn scan_market(&self) -> Result<()> { let url = format!( "https://api.helius.xyz/v0/token-metadata?api-key={}", self.config.helius_api_key ); let response = reqwest::Client::new() .post(&url) .json(&serde_json::json!({ "query": { "programs": ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"], "timeframe": "1d", "minLiquidity": 1000, "minVolume": 5000 } })) .send() .await?; let tokens = response.json::<Vec<serde_json::Value>>().await?; for token in tokens { if let Some(mint) = token["mint"].as_str() { if let Ok(price_data) = self.price_feed.fetch_price(mint).await { if self.is_good_opportunity(&price_data) { info!("🎯 Found opportunity: {} at ${:.6}", mint, price_data.price); self.create_trade(mint, price_data).await?; } } } } Ok(()) } fn is_good_opportunity(&self, price_data: &TokenPrice) -> bool { price_data.liquidity > 1000.0 && price_data.volume_24h > 5000.0 && price_data.price_change_24h > 5.0 } } async fn execute_sell(&self, trade: &Trade) -> Result<()> { info!("🔄 Executing sell for trade {}", trade.id); // Get current market price let price_data = self.price_feed.fetch_price(&trade.token_mint).await?; // Calculate optimal sell price with slippage protection let min_sell_price = price_data.price * (1.0 - self.config.max_slippage / 100.0); // Build sell transaction with priority fee let instructions = self.build_sell_instruction( &trade.token_mint, trade.amount, min_sell_price )?; let mut tx = Transaction::new_with_payer(&instructions, Some(&self.keypair.pubkey())); let recent_blockhash = self.rpc.get_latest_blockhash()?; tx.sign(&[&self.keypair], recent_blockhash); // Execute with retry logic for attempt in 1..=3 { match self.rpc.send_and_confirm_transaction_with_spinner(&tx) { Ok(sig) => { info!("✅ Sell executed! Signature: {}", sig); self.active_trades.remove(&trade.id); self.update_profit_stats(trade, price_data.price)?; return Ok(()); } Err(e) if attempt < 3 => { warn!("Sell attempt {} failed: {}", attempt, e); tokio::time::sleep(Duration::from_millis(500)).await; } Err(e) => return Err(e.into()), } } Err(anyhow!("Failed to execute sell after 3 attempts")) } fn build_sell_instruction( &self, mint: &str, quantity: f64, _min_sell_price: f64, ) -> Result<Vec<Instruction>> { let token_program_id = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")?; let token_mint = Pubkey::from_str(mint)?; // Get token accounts for EACH position let source_accounts = self.active_trades .iter() .filter(|trade| trade.token_mint == mint) .map(|_trade| { get_associated_token_address( &self.keypair.pubkey(), &token_mint ) }) .collect::<Vec<_>>(); // Build instructions for EACH position let mut instructions = Vec::new(); for source_account in source_accounts { instructions.push( spl_token::instruction::transfer( &token_program_id, &source_account, &self.wsol_account, &self.keypair.pubkey(), &[&self.keypair.pubkey()], (quantity * 1e9) as u64, )? ); } Ok(instructions) } fn update_profit_stats(&self, trade: &Trade, sell_price: f64) -> Result<()> { let profit = (sell_price - trade.entry_price) * trade.amount as f64; let mut state = self.state.write(); state.total_profit += profit; state.trade_count += 1; info!("💰 Trade profit: ${:.2}", profit); Ok(()) } fn save_state(&self) -> Result<()> { let mut state = self.state.write(); state.active_trades = self.active_trades.iter().map(|t| t.value().clone()).collect(); state.save(STATE_FILE)?; Ok(()) } async fn handle_shutdown(&self) { let shutdown = self.shutdown.clone(); tokio::signal::ctrl_c().await.unwrap(); *shutdown.write() = true; info!("💾 Saving state and shutting down..."); }}
#[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env() .add_directive(tracing::Level::INFO.into())) .init();
let printer = MoneyPrinter::new().await?; Arc::new(printer).start().await?; Ok(())} write the full script
- Assistant
Certainly! Below is the revised version of the provided script with improved spacing and formatting for better readability:
mod config; mod price_feed; mod state_manager; use { anyhow::{anyhow, Result}, chrono::{DateTime, Utc}, config::Config, dashmap::DashMap, parking_lot::RwLock, price_feed::{PriceFeed, TokenPrice}, serde::{Deserialize, Serialize}, solana_client::rpc_client::RpcClient, solana_program::instruction::Instruction, solana_sdk::{ commitment_config::CommitmentConfig, pubkey::Pubkey, signature::{Keypair, read_keypair_file, Signer}, transaction::Transaction, }, spl_associated_token_account::get_associated_token_address, state_manager::State, std::{ str::FromStr, sync::Arc, time::Duration, }, tracing::{error, info, warn}, uuid::Uuid, }; const WSOL_MINT: &str = "So11111111111111111111111111111111111111112"; const STATE_FILE: &str = "bot_state.json"; #[derive(Debug, Clone, Serialize, Deserialize)] pub struct Trade { pub id: String, pub token_mint: String, pub amount: f64, pub entry_price: f64, pub take_profit_price: f64, pub stop_loss_price: f64, pub timestamp: DateTime<Utc>, pub status: TradeStatus, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub enum TradeStatus { Active, PendingBuy, PendingSell, Completed, Failed, } pub struct MoneyPrinter { config: Config, rpc: Arc<RpcClient>, keypair: Arc<Keypair>, wsol_account: Pubkey, price_feed: Arc<PriceFeed>, active_trades: Arc<DashMap<String, Trade>>, state: Arc<RwLock<State>>, shutdown: Arc<RwLock<bool>>, } impl MoneyPrinter { pub async fn new() -> Result<Self> { let config = Config::load()?; let state = State::load(STATE_FILE)?; Ok(Self { rpc: Arc::new(RpcClient::new_with_commitment( config.rpc_url.clone(), CommitmentConfig::finalized(), )), keypair: Arc::new( read_keypair_file(&config.keypair_path) .expect("Failed to read keypair") ), wsol_account: Pubkey::from_str(&config.wsol_account)?, price_feed: Arc::new(PriceFeed::new(config.helius_api_key.clone())), active_trades: Arc::new(DashMap::new()), state: Arc::new(RwLock::new(state)), shutdown: Arc::new(RwLock::new(false)), config, }) } async fn initialize(&self) -> Result<()> { info!("🚀 Initializing Money Printer v1.0"); self.check_balances().await?; self.load_active_trades()?; Ok(()) } async fn check_balances(&self) -> Result<()> { let sol_balance = self.rpc.get_balance(&self.keypair.pubkey())? as f64 / 1e9; info!("💰 SOL Balance: {}", sol_balance); if sol_balance < self.config.min_sol_balance { warn!("⚠️ Low SOL balance!"); } Ok(()) } fn load_active_trades(&self) -> Result<()> { let state = self.state.read(); for trade in &state.active_trades { self.active_trades.insert(trade.id.clone(), trade.clone()); } info!("📊 Loaded {} active trades", self.active_trades.len()); Ok(()) } pub async fn start(self: Arc<Self>) -> Result<()> { let market_scanner = self.clone().spawn_market_scanner(); let trade_manager = self.clone().spawn_trade_manager(); let shutdown_handler = self.clone(); tokio::select! { _ = market_scanner => warn!("Market scanner stopped"), _ = trade_manager => warn!("Trade manager stopped"), _ = shutdown_handler.handle_shutdown() => info!("Shutdown complete"), } self.save_state()?; Ok(()) } fn spawn_market_scanner(self: Arc<Self>) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_millis(100)); while !*self.shutdown.read() { interval.tick().await; if let Err(e) = self.scan_market().await { error!("Market scanner error: {}", e); } } }) } fn spawn_trade_manager(self: Arc<Self>) -> tokio::task::JoinHandle<()> { tokio::spawn(async move { let mut interval = tokio::time::interval(Duration::from_secs(1)); while !*self.shutdown.read() { interval.tick().await; if let Err(e) = self.manage_trades().await { error!("Trade manager error: {}", e); } } }) } async fn scan_market(&self) -> Result<()> { let url = format!( "https://api.helius.xyz/v0/token-metadata?api-key={}", self.config.helius_api_key ); let response = reqwest::Client::new() .post(&url) .json(&serde_json::json!({ "query": { "programs": ["675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8"], "timeframe": "1d", "minLiquidity": 1000, "minVolume": 5000 } })) .send() .await?; let tokens = response.json::<Vec<serde_json::Value>>().await?; for token in tokens { if let Some(mint) = token["mint"].as_str() { if let Ok(price_data) = self.price_feed.fetch_price(mint).await { if self.is_good_opportunity(&price_data) { info!("🎯 Found opportunity: {} at ${:.6}", mint, price_data.price); self.create_trade(mint, price_data).await?; } } } } Ok(()) } fn is_good_opportunity(&self, price_data: &TokenPrice) -> bool { price_data.liquidity > 1000.0 && price_data.volume_24h > 5000.0 && price_data.price_change_24h > 5.0 } async fn create_trade(&self, mint: &str, price_data: TokenPrice) -> Result<()> { let position_size = (price_data.volume_24h * 0.001).min(0.1); let volatility_multiplier = if price_data.price_change_24h > 10.0 { 1.08 } else { 1.05 }; let trade_id = Uuid::new_v4().to_string(); let trade = Trade { id: trade_id.clone(), token_mint: mint.to_string(), amount: position_size, entry_price: price_data.price, take_profit_price: price_data.price * volatility_multiplier, stop_loss_price: price_data.price * 0.95, timestamp: Utc::now(), status: TradeStatus::Active, }; info!("🎯 Creating trade for {} with {}% target", mint, (volatility_multiplier - 1.0) * 100.0); self.active_trades.insert(trade_id, trade.clone()); self.state.write().active_trades.push(trade); Ok(()) } async fn manage_trades(&self) -> Result<()> { for trade in self.active_trades.iter() { if let Ok(price) = self.price_feed.fetch_price(&trade.token_mint).await { self.check_trade_conditions(&trade, &price).await?; } } Ok(()) } async fn check_trade_conditions(&self, trade: &Trade, price: &TokenPrice) -> Result<()> { if price.price >= trade.take_profit_price { info!("🎯 Take profit hit for trade {}", trade.id); self.execute_sell(trade).await?; } else if price.price <= trade.stop_loss_price { info!("🛑 Stop loss hit for trade {}", trade.id); self.execute_sell(trade).await?; } Ok(()) } async fn execute_sell(&self, trade: &Trade) -> Result<()> { info!("🔄 Executing sell for trade {}", trade.id); // Get current market price let price_data = self.price_feed.fetch_price(&trade.token_mint).await?; // Calculate optimal sell price with slippage protection let min_sell_price = price_data.price * (1.0 - self.config.max_slippage / 100.0); // Build sell transaction with priority fee let instructions = self.build_sell_instruction( &trade.token_mint, trade.amount, min_sell_price, )?; let mut tx = Transaction::new_with_payer(&instructions, Some(&self.keypair.pubkey())); let recent_blockhash = self.rpc.get_latest_blockhash()?; tx.sign(&[&self.keypair], recent_blockhash); // Execute with retry logic for attempt in 1..=3 { match self.rpc.send_and_confirm_transaction_with_spinner(&tx) { Ok(sig) => { info!("✅ Sell executed! Signature: {}", sig); self.active_trades.remove(&trade.id); self.update_profit_stats(trade, price_data.price)?; return Ok(()); } Err(e) if attempt < 3 => { warn!("Sell attempt {} failed: {}", attempt, e); tokio::time::sleep(Duration::from_millis(500)).await; } Err(e) => return Err(e.into()), } } Err(anyhow!("Failed to execute sell after 3 attempts")) } fn build_sell_instruction( &self, mint: &str, quantity: f64, _min_sell_price: f64, ) -> Result<Vec<Instruction>> { let token_program_id = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")?; let token_mint = Pubkey::from_str(mint)?; // Get token accounts for EACH position let source_accounts = self.active_trades .iter() .filter(|trade| trade.token_mint == mint) .map(|_trade| { get_associated_token_address( &self.keypair.pubkey(), &token_mint ) }) .collect::<Vec<_>>(); // Build instructions for EACH position let mut instructions = Vec::new(); for source_account in source_accounts { instructions.push( spl_token::instruction::transfer( &token_program_id, &source_account, &self.wsol_account, &self.keypair.pubkey(), &[&self.keypair.pubkey()], (quantity * 1e9) as u64, )? ); } Ok(instructions) } fn update_profit_stats(&self, trade: &Trade, sell_price: f64) -> Result<()> { let profit = (sell_price - trade.entry_price) * trade.amount as f64; let mut state = self.state.write(); state.total_profit += profit; state.trade_count += 1; info!("💰 Trade profit: ${:.2}", profit); Ok(()) } fn save_state(&self) -> Result<()> { let mut state = self.state.write(); state.active_trades = self.active_trades.iter().map(|t| t.value().clone()).collect(); state.save(STATE_FILE)?; Ok(()) } async fn handle_shutdown(&self) { let shutdown = self.shutdown.clone(); tokio::signal::ctrl_c().await.unwrap(); *shutdown.write() = true; info!("💾 Saving state and shutting down..."); } } #[tokio::main] async fn main() -> Result<()> { tracing_subscriber::fmt() .with_env_filter(tracing_subscriber::EnvFilter::from_default_env() .add_directive(tracing::Level::INFO.into())) .init(); let printer = MoneyPrinter::new().await?; Arc::new(printer).start().await?; Ok(()) }Notes on Formatting:
- Each code block is properly indented to enhance the readability.
- Functions are separated with an additional line for clarity.
- Comments remain aligned with the relevant code to provide context.
- Consistent use of spaces enhances the structure and flows of the logic blocks.
- Ensure that the
spl_tokenand any other necessary dependencies are imported correctly in your project’s configuration.