can u help me please fix this use {
    anyhow::{anyhow, Result},
    base64::Engine,
    colored::*,
    futures_util::{SinkExt, StreamExt},
    serde::{Deserialize, Serialize},
    serde_json::{json, Value},
    solana_client::rpc_client::RpcClient,
    solana_sdk::{
        commitment_config::CommitmentConfig,
        compute_budget::ComputeBudgetInstruction,
        pubkey::Pubkey,
        signature::{read_keypair_file, Keypair},
        signer::Signer,
        system_instruction,
        transaction::Transaction,
    },
    spl_token::instruction as spl_token_instruction,
    std::{collections::HashMap, error::Error, str::FromStr, sync::Arc, time::Duration},
    tokio::sync::Mutex,
    tokio_tungstenite::{connect_async, tungstenite::Message as WsMessage},
};

#[derive(Debug, Deserialize, Clone)]
struct RpcConfig {
    primary_url: String,
    fallback_url: String,
    ws_url: String,
}

#[derive(Debug, Deserialize, Clone)]
struct UrlConfig {
    ws_endpoint: String,
    backup_ws_url: String,
}

#[derive(Debug, Deserialize, Clone)]
struct WalletConfig {
    keypair_path: String,
    public_key: String,
    wsol_account: String,
}

impl WalletConfig {
    fn transfer(&self, wsol_account: &Pubkey, amount: u64) -> solana_sdk::instruction::Instruction {
    system_instruction::transfer(&self.keypair.pubkey(), wsol_account, amount)
    }
}
#[derive(Debug, Deserialize, Clone)]
struct ApiKeys {
    helius_api_key: String,
}

#[derive(Debug, Deserialize, Clone)]
struct TradingConfig {
    snipe_amount: u64,
    slippage: f64,
    priority_fee: u64,
    max_retry_attempts: u32,
    min_sol_balance: f64,
}

#[derive(Debug, Deserialize, Clone)]
use {
    anyhow::{anyhow, Result},
    solana_sdk::{
        signature::{read_keypair_file, Keypair},
        system_instruction,
    },
    std::sync::Arc,
};

struct TokenRequirements {
    min_supply: u64,
    max_age_seconds: u64,
    mutable: bool,
    burnt: bool,
    frozen: bool,
}

#[derive(Debug, Deserialize, Clone)]
struct LoggingConfig {
    debug: bool,
    log_level: String,
    show_scanning: bool,
    show_trades: bool,
    show_balances: bool,
    reconnect: u64,
}

#[derive(Debug, Deserialize, Clone)]
struct BotConfig {
    rpc: RpcConfig,
    urls: UrlConfig,
    wallet: WalletConfig,
    api_keys: ApiKeys,
    trading: TradingConfig,
    token_requirements: TokenRequirements,
    logging: LoggingConfig,
}

#[derive(Clone, Serialize, Deserialize, Debug)]
struct Trade {
    token_address: String,
    amount: u64,
    buy_price: f64,
    take_profit_price: f64,
    stop_loss_price: f64,
    timestamp: u64,
    status: TradeStatus,
    initial_buy_amount: u64,
}

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

struct Bot {
    config: BotConfig,
    rpc_client: Arc<RpcClient>,
    fallback_rpc: Arc<RpcClient>,
    keypair: Arc<Keypair>,
    active_trades: Arc<Mutex<HashMap<String, Trade>>>,
    http_client: reqwest::Client,
}

impl Bot {
    pub async fn new(config: BotConfig) -> Result<Self> {
        let keypair = Arc::new(read_keypair_file(&config.wallet.keypair_path)
            .map_err(|e| anyhow!("Failed to read keypair: {}", e))?);

        println!(
            "{}",
            format!("💰 Loaded wallet: {}", keypair.pubkey()).yellow()
        );

        let rpc_client = Arc::new(RpcClient::new_with_commitment(
            config.rpc.primary_url.clone(),
            CommitmentConfig::confirmed(),
        ));

        let fallback_rpc = Arc::new(RpcClient::new_with_commitment(
            config.rpc.fallback_url.clone(),
            CommitmentConfig::confirmed(),
        ));

        let http_client = reqwest::Client::builder()
            .timeout(Duration::from_secs(5))
            .build()?;

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

    fn create_transfer(&self, wsol_account: &Pubkey, amount: u64) -> Instruction {
        system_instruction::transfer(
            &self.keypair.pubkey(),
            wsol_account,
            amount
        )
    }

    async fn get_jupiter_swap_ix(
        &self,
        input_token: &Pubkey,
        output_token: &Pubkey,
        amount: u64,
    ) -> Result<Vec<solana_sdk::instruction::Instruction>> {
        let quote_response = self.http_client
            .get(&format!(
                "https://quote-api.jup.ag/v4/quote?inputMint={}&outputMint={}&amount={}&slippageBps=50",
                input_token, output_token, amount
            ))
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        let swap_response = self
            .http_client
            .post("https://quote-api.jup.ag/v4/swap")
            .json(&json!({
                "quoteResponse": quote_response,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "wrapUnwrapSOL": true
            }))
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        use base64::Engine;
        let setup_ix: Vec<u8> = base64::engine::general_purpose::STANDARD
            .decode(&swap_response["setupTransaction"].as_str().unwrap())?;
        let swap_ix: Vec<u8> = base64::engine::general_purpose::STANDARD
            .decode(&swap_response["swapTransaction"].as_str().unwrap())?;

        let mut instructions: Vec<solana_sdk::instruction::Instruction> =
            bincode::deserialize(&setup_ix)?;
        let decoded_instructions: Vec<solana_sdk::instruction::Instruction> =
            bincode::deserialize(&swap_ix)?;
        instructions.extend(decoded_instructions);

        Ok(instructions)
    }

    async fn execute_swap(&self) -> Result<()> {
        let swap_response = self.http_client
            .post("https://quote-api.jup.ag/v4/swap")
            .json(&json!({
                "quoteResponse": quote_response,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "wrapUnwrapSOL": true
            }))
            .send()
            .await?
            .json::<Value>()
            .await?;

        let setup_ix = base64::engine::general_purpose::STANDARD
            .decode(swap_response["setupTransaction"].as_str().unwrap())?;
    }

    fn extract_token_address(&self, data: &Value) -> Option<String> {
        if let Some(accounts) = data["result"]["value"]["accountData"].as_array() {
            for account in accounts {
                if account["program"].as_str()? == "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8" {
                    let token_data = account["parsed"]["info"]["mint"].as_str()?;
                    return Some(token_data.to_string());
                }
            }
        }
        None
    }
    async fn track_profits(&self) -> Result<()> {
        let trades = self.active_trades.lock().await;
        let mut total_profit = 0.0;

        for trade in trades.values() {
            if let TradeStatus::Completed = trade.status {
                let profit = trade.take_profit_price - trade.buy_price;
                total_profit += profit;
            }
        }

        if self.config.logging.show_trades {
            println!("💎 Total Profit: {:.2} SOL", total_profit);
        }
        Ok(())
    }
    async fn process_message(&self, msg: &str) -> Result<()> {
        let data: Value = serde_json::from_str(msg)?;

        if let Some(token_address) = self.extract_token_address(&data) {
            println!("🎯 NEW TOKEN DETECTED: {}", token_address.bright_yellow());
            self.execute_instant_snipe(&token_address).await?;
        }
        Ok(())
    }

    async fn monitor_trades(&self) -> Result<()> {
        let mut trades = self.active_trades.lock().await;
        for (token_address, trade) in trades.iter_mut() {
            match trade.status {
                TradeStatus::Active => {
                    if trade.buy_price >= trade.take_profit_price {
                        let setup_ix: Vec<u8> = base64::engine::general_purpose::STANDARD
                            .decode(&swap_response["setupTransaction"].as_str().unwrap())?;
                        trade.status = TradeStatus::Completed;
                    }
                }
                _ => continue,
            }
        }
        Ok(())
    }

    async fn get_helius_priority_fee(&self) -> Result<u64> {
        let helius_api_key = &self.config.api_keys.helius_api_key;
        let helius_url = format!(
            "https://rpc-helius.mainnet.helius.xyz/?api-key={}",
            helius_api_key
        );
        let helius_client = reqwest::Client::new();

        let response = helius_client
            .get(&helius_url)
            .send()
            .await?
            .json::<serde_json::Value>()
            .await?;

        let priority_fee = response["result"]["priorityFee"]
            .as_f64()
            .ok_or_else(|| anyhow!("Failed to parse priority fee"))?;

        Ok((priority_fee * 1e9) as u64)
    }
    async fn execute_instant_snipe(&self, token_address: &str) -> Result<()> {
        println!("{}", "⚡ INSTANT EXECUTION INITIATED".bright_yellow());

        let priority_fee = self.get_helius_priority_fee().await?;
        let wsol_pubkey = Pubkey::from_str("So11111111111111111111111111111111111111112")?;
        let token_pubkey = Pubkey::from_str(token_address)?;

        // Get Jupiter swap instructions
        let mut instructions = self
            .get_jupiter_swap_ix(
                &wsol_pubkey,
                &token_pubkey,
                self.config.trading.snipe_amount,
            )
            .await?;

        // Add priority fee instruction at the start
        instructions.insert(
            0,
            ComputeBudgetInstruction::set_compute_unit_price(priority_fee),
        );
        instructions.insert(
            0,
            ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
        );

        let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
        let transaction = Transaction::new_signed_with_payer(
            &instructions,
            Some(&self.keypair.pubkey()),
            &[&self.keypair],
            recent_blockhash,
        );

        self.rpc_client
            .send_and_confirm_transaction_with_spinner(&transaction)?;
        use colored::Colorize;
        println!("{}", "🚀 EXECUTION COMPLETE".bright_green());
        Ok(())
    }

    async fn execute_sell(&self, token_address: &str, amount: u64) -> Result<()> {
        println!("{}", "💰 EXECUTING SELL".bright_yellow());

        let priority_fee = self.get_helius_priority_fee().await?;
        let wsol_pubkey = Pubkey::from_str("So11111111111111111111111111111111111111112")?;
        let token_pubkey = Pubkey::from_str(token_address)?;

        // Get Jupiter swap instructions (reversed from buy)
        let mut instructions = self
            .get_jupiter_swap_ix(&token_pubkey, &wsol_pubkey, amount)
            .await?;

        instructions.insert(
            0,
            ComputeBudgetInstruction::set_compute_unit_price(priority_fee),
        );
        instructions.insert(
            0,
            ComputeBudgetInstruction::set_compute_unit_limit(1_400_000),
        );

        let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
        let transaction = Transaction::new_signed_with_payer(
            &instructions,
            Some(&self.keypair.pubkey()),
            &[&self.keypair],
            recent_blockhash,
        );

        self.rpc_client
            .send_and_confirm_transaction_with_spinner(&transaction)?;
        println!("{}", "✅ SELL EXECUTED SUCCESSFULLY".bright_green());
        Ok(())
    }

    async fn get_wsol_balance(&self) -> Result<u64> {
        let wsol_account = Pubkey::from_str(&self.config.wallet.wsol_account)?;
        let balance = self.rpc_client.get_token_account_balance(&wsol_account)?;
        Ok(balance.amount.parse::<u64>()?) // Fixed to use the correct method
    }
    async fn wrap_sol(&self, amount: u64) -> Result<()> {
        println!("{}", "💫 Wrapping SOL...".bright_yellow());

        let wsol_account = Pubkey::from_str(&self.config.wallet.wsol_account)?;

        let instructions = vec![
            ComputeBudgetInstruction::set_compute_unit_price(self.config.trading.priority_fee),
            SystemProgram::transfer(&self.keypair.pubkey(), &wsol_account, amount),
            spl_token::instruction::sync_native(&spl_token::id(), &wsol_account)?,
        ];

        let recent_blockhash = self.rpc_client.get_latest_blockhash()?;
        let transaction = Transaction::new_signed_with_payer(
            &instructions,
            Some(&self.keypair.pubkey()),
            &[&self.keypair],
            recent_blockhash,
        );

        self.rpc_client
            .send_and_confirm_transaction_with_spinner(&transaction)?;
        println!("{}", "✅ SOL wrapped successfully!".bright_green());

        Ok(())
    }

    async fn run(&self) -> Result<()> {
        println!("{}", "🚀 SNIPER ACTIVATED".bright_green());

        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": [
                                    "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
                                    {"encoding": "jsonParsed", "commitment": "confirmed"}
                                ]
                            })
                            .to_string(),
                        ))
                        .await?;

                    while let Some(msg) = read.next().await {
                        if let Ok(msg) = msg {
                            self.process_message(&msg.to_string()).await?;
                        }
                        self.monitor_trades().await?;
                        self.track_profits().await?;
                    }
                }
                Err(_) => continue,
            }
        }
    }
}

#[tokio::main]
async fn main() -> Result<()> {
    let bot = Bot::new().await?;

    ctrlc::set_handler(move || {
        println!("{}", "\n💾 GRACEFUL SHUTDOWN INITIATED".bright_red());
        std::process::exit(0);
    })?;

    bot.run().await
}