whats wrong with this scipt use {
    anyhow::{anyhow, Result},
    base64::{engine::general_purpose::STANDARD as base64_engine, Engine},
    chrono::Utc,
    colored::*,
    futures_util::{SinkExt, StreamExt},
    log::{debug, error, info, warn},
    reqwest::Client as HttpClient,
    serde::{Deserialize, Serialize},
    serde_json::{json, Value},
    solana_client::{
        rpc_client::RpcClient,
        rpc_request::TokenAccountsFilter,
    },
    solana_sdk::{
        commitment_config::CommitmentConfig,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    std::{
        collections::HashMap,
        fs,
        str::FromStr,
        sync::Arc,
        time::{Duration, Instant},
    },
    tokio::{
        net::TcpStream,
        sync::Mutex,
        time::{interval, sleep},
    },
    tokio_tungstenite::{
        tungstenite::protocol::Message as WsMessage,
        WebSocketStream,
        MaybeTlsStream,
    },
};



// Constants
const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const HELIUS_WS: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com";
const HELIUS_API_KEY: &str = "your-api-key";
const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const WSOL_MINT: &str = "So11111111111111111111111111111111111111112";
const JUPITER_V6_API: &str = "https://quote-api.jup.ag/v6";
const MIN_PRIORITY_FEE: u64 = 10_000;
const MAX_RETRIES: u8 = 3;
const RETRY_DELAY_MS: u64 = 500;
const MIN_LIQUIDITY_USD: f64 = 50.0;
const MAX_LIQUIDITY_USD: f64 = 20_000.0;
const TAKE_PROFIT: f64 = 20.0;
const STOP_LOSS: f64 = -3.0;
const TRADE_SIZE_SOL: f64 = 0.01;

#[derive(Clone)]
struct Bot {
    rpc_client: Arc<RpcClient>,
    http_client: HttpClient,
    keypair: Arc<Keypair>,
    active_trades: Arc<Mutex<HashMap<String, TradeState>>>,
    market_data: Arc<Mutex<HashMap<String, MarketData>>>,
    config: Config,
}

#[derive(Clone, Debug)]
pub struct Config {
    pub rpc_url: String,
    pub ws_url: String,
    pub fallback_ws: String,
    pub helius_api_key: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct TradeState {
    token_address: String,
    entry_price: f64,
    amount: u64,
    timestamp: i64,
    take_profit_price: f64,
    stop_loss_price: f64,
    status: TradeStatus,
    attempts: u8,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
enum TradeStatus {
    Active,
    PendingBuy,
    PendingSell,
    Completed,
    Failed(String),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
struct MarketData {
    liquidity: f64,
    volume_24h: f64,
    price: f64,
    last_update: i64,
}

pub struct BotMonitor {
    bot: Arc<Bot>,
}
impl Bot {
    pub async fn new(config: Config, keypair: Keypair) -> Result<Self> {
        println!(
            "{}",
            "🚀 Initializing Professional Trading Engine"
                .bright_green()
                .bold()
        );

        let rpc_client = Arc::new(RpcClient::new_with_commitment(
            &config.rpc_url,
            CommitmentConfig::confirmed(),
        ));

        let http_client = HttpClient::builder()
            .timeout(Duration::from_secs(5))
            .pool_idle_timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(32)
            .build()?;

        Ok(Self {
            rpc_client,
            http_client,
            keypair: Arc::new(keypair),
            active_trades: Arc::new(Mutex::new(HashMap::new())),
            market_data: Arc::new(Mutex::new(HashMap::new())),
            config,
        })
    }

    // In Bot impl
    pub fn load_keypair(path: &str) -> Result<Keypair> {
        let keypair_bytes = fs::read(path)?;
        Ok(Keypair::from_bytes(&keypair_bytes)?)
    }

    async fn get_jupiter_quote(
        &self,
        token_address: &str,
        is_buy: bool,
        amount: u64,
    ) -> Result<Value> {
        let (input_mint, output_mint) = if is_buy {
            (WSOL_MINT, token_address)
        } else {
            (token_address, WSOL_MINT)
        };

        let quote_url = format!(
            "{}/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50",
            JUPITER_V6_API, input_mint, output_mint, amount
        );

        Ok(self
            .http_client
            .get(&quote_url)
            .send()
            .await?
            .json()
            .await?)
    }

    async fn build_swap_transaction(&self, quote: Value) -> Result<Vec<u8>> {
        let swap_request = json!({
            "quoteResponse": quote,
            "userPublicKey": self.keypair.pubkey().to_string(),
            "wrapUnwrapSOL": true
        });

        let response = self
            .http_client
            .post(format!("{}/swap", JUPITER_V6_API))
            .json(&swap_request)
            .send()
            .await?
            .json::<Value>()
            .await?;

        Ok(base64_engine.decode(
            response["swapTransaction"]
                .as_str()
                .ok_or_else(|| anyhow!("Invalid swap transaction"))?,
        )?)
    }
    async fn send_priority_transaction(
        &self,
        transaction_data: &[u8],
        _priority_fee: u64,
    ) -> Result<String> {
        let transaction: Transaction = bincode::deserialize(transaction_data)?;
        let blockhash = self.rpc_client.get_latest_blockhash()?;

        let mut final_tx = transaction.clone();
        final_tx.message.recent_blockhash = blockhash;
        final_tx.sign(&[&self.keypair], blockhash);

        Ok(self
            .rpc_client
            .send_and_confirm_transaction_with_spinner(&final_tx)?
            .to_string())
    }

    async fn validate_token(&self, token_address: &str) -> Result<bool> {
        let pubkey = Pubkey::from_str(token_address)?;

        let mint_info = self.rpc_client.get_account(&pubkey)?;
        if mint_info.owner != Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA")? {
            return Ok(false);
        }

        let lp_accounts = self.rpc_client.get_token_accounts_by_owner(
            &Pubkey::from_str(RAYDIUM_PROGRAM_ID)?,
            TokenAccountsFilter::Mint(pubkey),
        )?;

        if lp_accounts.is_empty() {
            return Ok(false);
        }

        let market_data = self.get_market_data(token_address).await?;

        if market_data.liquidity < MIN_LIQUIDITY_USD || market_data.liquidity > MAX_LIQUIDITY_USD {
            return Ok(false);
        }

        Ok(true)
    }

    async fn get_market_data(&self, token_address: &str) -> Result<MarketData> {
        let mut market_data = self.market_data.lock().await;

        let now = Utc::now().timestamp();
        if let Some(data) = market_data.get(token_address) {
            if now - data.last_update < 60 {
                return Ok(data.clone());
            }
        }

        let jupiter_url = format!(
            "{}/quote?inputMint={}&outputMint={}&amount=1000000000",
            JUPITER_V6_API, WSOL_MINT, token_address
        );

        let response = self
            .http_client
            .get(&jupiter_url)
            .send()
            .await?
            .json::<Value>()
            .await?;

        let price = response["price"]
            .as_f64()
            .ok_or_else(|| anyhow!("Invalid price data"))?;

        let data = MarketData {
            liquidity: response["inAmount"].as_f64().unwrap_or(0.0) * price,
            volume_24h: response["volume24h"].as_f64().unwrap_or(0.0),
            price,
            last_update: now,
        };

        market_data.insert(token_address.to_string(), data.clone());
        Ok(data)
    }
    async fn execute_trade(&self, token_address: &str, is_buy: bool) -> Result<String> {
        let start = Instant::now();
        let priority_fee = self.get_optimal_priority_fee(token_address).await?;

        let amount = if is_buy {
            (TRADE_SIZE_SOL * 1e9) as u64
        } else {
            let trade = self
                .active_trades
                .lock()
                .await
                .get(token_address)
                .cloned()
                .ok_or_else(|| anyhow!("No active trade found"))?;
            trade.amount
        };

        let quote = self
            .get_jupiter_quote(token_address, is_buy, amount)
            .await?;
        let swap_data = self.build_swap_transaction(quote).await?;

        for attempt in 1..=MAX_RETRIES {
            match self
                .send_priority_transaction(&swap_data, priority_fee)
                .await
            {
                Ok(signature) => {
                    info!("Trade executed in {:?}", start.elapsed());
                    return Ok(signature);
                }
                Err(e) if attempt < MAX_RETRIES => {
                    warn!("Attempt {} failed: {}", attempt, e);
                    sleep(Duration::from_millis(RETRY_DELAY_MS)).await;
                }
                Err(e) => return Err(e),
            }
        }

        Err(anyhow!("Max retries exceeded"))
    }

    async fn get_optimal_priority_fee(&self, token_address: &str) -> Result<u64> {
        let response = self
            .http_client
            .post(&self.config.rpc_url)
            .json(&json!({
                "jsonrpc": "2.0",
                "id": "priority-fee",
                "method": "getPriorityFeeEstimate",
                "params": [{
                    "accountKeys": [token_address],
                    "options": {
                        "includeAllPriorityFeeLevels": true
                    }
                }]
            }))
            .send()
            .await?
            .json::<Value>()
            .await?;

        Ok(response["result"]["priorityFeeLevels"]["high"]
            .as_u64()
            .unwrap_or(MIN_PRIORITY_FEE)
            .max(MIN_PRIORITY_FEE))
    }

    pub async fn handle_market_feed(
        ws_stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
        bot: Arc<Bot>,
    ) -> Result<()> {
        let (mut write, mut read) = ws_stream.split();
        
        write.send(WsMessage::Text(
            json!({
                "jsonrpc": "2.0",
                "id": 1,
                "method": "programSubscribe",
                "params": [
                    RAYDIUM_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 Ok(event) = serde_json::from_str::<Value>(&text) {
                    if let Err(e) = bot.process_pool_event(event).await {
                        error!("Failed to process event: {}", e);
                    }
                }
            }
        }
        Ok(())
    }
    async fn process_pool_event(&self, event: Value) -> Result<()> {
        let token_address = event
            .get("params")
            .and_then(|p| p.get("result"))
            .and_then(|r| r.get("value"))
            .and_then(|v| v.get("pubkey"))
            .and_then(|p| p.as_str())
            .ok_or_else(|| anyhow!("Invalid token address structure"))?;
    
        if !self.validate_token(token_address).await? {
            debug!("⚠️  {} {}", "Invalid Token:".red().bold(), token_address.dimmed());
            return Ok(());
        }
    
        let market_data = self.get_market_data(token_address).await?;
        info!(
            "\n╔══════════ {} NEW POOL DETECTED {} ══════════╗\n\
             ║                                               ║\n\
             ║  {} Token    : {}              ║\n\
             ║  {} Price    : ${:<12.6}                ║\n\
             ║  {} Liquidity: ${:<12.2}                ║\n\
             ║  {} Volume   : ${:<12.2}                ║\n\
             ║  {} Time     : {}                    ║\n\
             ║                                               ║\n\
             ╚═══════════════════════════════════════════════╝",
            "🚀".bright_green(), "🚀".bright_green(),
            "🔸".cyan(), token_address.bright_yellow(),
            "💎".cyan(), market_data.price.to_string().bright_blue(),
            "💰".cyan(), market_data.liquidity.to_string().bright_green(),
            "📊".cyan(), format!("{:.2}", market_data.price * market_data.liquidity).bright_magenta(),
            "🕒".cyan(), Utc::now().format("%H:%M:%S").to_string().bright_white()
        );
    
        // Trade execution logic
        let trade_result = self.execute_trade(token_address, true).await;
        match trade_result {
            Ok(_) => info!("🎯 {} {}", "Trade Executed:".green().bold(), "Success".bright_green()),
            Err(e) => warn!("💥 {} {}", "Trade Failed:".red().bold(), e.to_string().red()),
        }
    
        let mut trades = self.active_trades.lock().await;
        trades.insert(
            token_address.to_string(),
            TradeState {
                token_address: token_address.to_string(),
                entry_price: market_data.price,
                amount: (TRADE_SIZE_SOL * 1e9) as u64,
                timestamp: Utc::now().timestamp(),
                take_profit_price: market_data.price * (1.0 + TAKE_PROFIT / 100.0),
                stop_loss_price: market_data.price * (1.0 + STOP_LOSS / 100.0),
                status: TradeStatus::Active,
                attempts: 0,
            },
        );
    
        Ok(())
    }
    
    

    async fn monitor_trades(&self) -> Result<()> {
        let mut interval = interval(Duration::from_secs(1));
        loop {
            interval.tick().await;
            let trades = self.active_trades.lock().await.clone();

            for (token_address, trade) in trades {
                let market_data = self.get_market_data(&token_address).await?;
                let profit_percent =
                    (market_data.price - trade.entry_price) / trade.entry_price * 100.0;

                if profit_percent >= TAKE_PROFIT || profit_percent <= STOP_LOSS {
                    info!(
                        "Executing sell for {} at {:.2}%",
                        token_address, profit_percent
                    );
                    self.execute_trade(&token_address, false).await?;

                    let mut trades = self.active_trades.lock().await;
                    trades.remove(&token_address);
                }
            }
        }
    }
}

impl BotMonitor {
    pub(crate) fn new(bot: Arc<Bot>) -> Self {
        Self { bot }
    }

    pub async fn start_monitoring(&self) -> Result<()> {
        let mut interval = interval(Duration::from_secs(1));
        loop {
            interval.tick().await;
            if let Err(e) = self.bot.monitor_trades().await {
                error!("Trade monitoring error: {}", e);
            }
        }
    }
}
#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();
    
    let config = Config {
        rpc_url: HELIUS_RPC.to_string(),
        ws_url: HELIUS_WS.to_string(),
        fallback_ws: HELIUS_WS.to_string(),
        helius_api_key: HELIUS_API_KEY.to_string(),
    };
    
    // In main(), update this line to use the explicit path:
    let keypair = Bot::load_keypair("keypair.bin")?;
    let bot = Arc::new(Bot::new(config, keypair).await?);
    let monitor = BotMonitor::new(bot.clone());

    let ws_stream = connect_websocket(&bot.config.ws_url).await?;
    
    let market_feed = Bot::handle_market_feed(ws_stream, bot.clone());
    let trade_monitor = bot.monitor_trades();
    let system_monitor = monitor.start_monitoring();
    
    let (market_result, trade_result, monitor_result) = tokio::join!(market_feed, trade_monitor, system_monitor);
    market_result?;
    trade_result?;
    monitor_result?;
    
    Ok(())
}


async fn connect_websocket(url: &str) -> Result<WebSocketStream<MaybeTlsStream<TcpStream>>> {
    let (ws_stream, _) = tokio_tungstenite::connect_async(url).await?;
    Ok(ws_stream)
}