favor please help me out use {
    anyhow::{anyhow, Result},
    base64::{engine::general_purpose::STANDARD as BASE64, Engine},
    chrono::Utc,
    dashmap::DashMap,
    log::{error, info, warn},
    reqwest::Client,
    serde::{Deserialize, Serialize},
    serde_json::{json, Value},
    solana_client::nonblocking::rpc_client::RpcClient,
    solana_sdk::{
        commitment_config::CommitmentConfig,
        compute_budget::ComputeBudgetInstruction,
        instruction::Instruction,
        message::Message,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    std::{str::FromStr, time::Instant},
    tokio::time::{sleep, Duration},
};

// Constants remain the same...

pub struct Bot {
    pub keypair: Keypair,
    pub http_client: Client,
    pub active_trades: DashMap<String, Trade>,
    pub rpc_client: RpcClient,
    pub jupiter_program_id: Pubkey,
}

impl Bot {
    pub fn new(keypair: Keypair) -> Self {
        info!("🚀 Initializing trading bot with enhanced timing...");
        
        Self {
            keypair,
            http_client: Client::new(),
            active_trades: DashMap::new(),
            rpc_client: RpcClient::new_with_commitment(
                HELIUS_RPC.to_string(),
                CommitmentConfig::confirmed(),
            ),
            jupiter_program_id: Pubkey::from_str("JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB")
                .expect("Invalid Jupiter program ID"),
        }
    }

    pub async fn execute_rapid_trade(&self, token: &str, is_buy: bool) -> Result<String> {
        let start = Instant::now();
        info!("🚀 Executing {} trade for {}", if is_buy { "BUY" } else { "SELL" }, token);

        // Fixed async calls
        let quote = self.get_jupiter_quote(token, is_buy).await?;
        let blockhash = self.rpc_client.get_latest_blockhash().await?;

        let priority_ix = ComputeBudgetInstruction::set_compute_unit_price(PRIORITY_FEE);
        let swap_data = self.prepare_swap_data(&quote).await?;
        let tx_data = BASE64.decode(&swap_data)?;

        let swap_ix = Instruction {
            program_id: self.jupiter_program_id,
            accounts: vec![],
            data: tx_data,
        };

        let message = Message::new(
            &[priority_ix, swap_ix],
            Some(&self.keypair.pubkey())
        );

        let mut transaction = Transaction::new_unsigned(message);
        transaction.sign(&[&self.keypair], blockhash);

        let signature = self.rpc_client.send_and_confirm_transaction(&transaction).await?;
        
        if is_buy {
            self.add_trade(token, TRADE_AMOUNT, quote).await?;
        } else {
            self.active_trades.remove(token);
        }

        info!("⚡ Trade executed in {:?}", start.elapsed());
        Ok(signature.to_string())
    }

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

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

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

        Ok(response)
    }

    async fn add_trade(&self, token: &str, amount: u64, quote: Value) -> Result<()> {
        let entry_price = quote["outAmount"]
            .as_str()
            .and_then(|s| s.parse::<f64>().ok())
            .ok_or_else(|| anyhow!("Invalid price data"))? / 1e9;

        let trade = Trade::new(entry_price, amount);
        self.active_trades.insert(token.to_string(), trade);
        Ok(())
    }

    pub async fn validate_pool_requirements(&self, token: &str) -> Result<bool> {
        let token_pubkey = Pubkey::from_str(token)?;
        
        // Sequential validations with proper async
        let supply = self.rpc_client.get_token_supply(&token_pubkey).await?;
        let supply_amount = supply.ui_amount.unwrap_or(0.0) as u64;

        let account_data = self.rpc_client.get_account_data(&token_pubkey).await?;
        let liquidity = if account_data.len() >= 16 {
            let liquidity_bytes = &account_data[8..16];
            u64::from_le_bytes(liquidity_bytes.try_into()?) as f64 / 1e6
        } else {
            0.0
        };

        let token_account = self.rpc_client.get_token_account(&token_pubkey).await?;
        let burnt = token_account
            .map(|acc| acc.token_amount.amount == "0")
            .unwrap_or(false);

        let account = self.rpc_client.get_account(&token_pubkey).await?;
        let has_authority = account.data.len() > 4;

        let valid = (MIN_LIQUIDITY..=MAX_LIQUIDITY).contains(&liquidity)
            && (1_000_000..=1_000_000_000_000).contains(&supply_amount)
            && burnt
            && !has_authority;

        if valid {
            info!("✅ Pool validation successful");
        } else {
            warn!("❌ Pool validation failed");
        }

        Ok(valid)
    }

    async fn prepare_swap_data(&self, quote: &Value) -> Result<String> {
        let swap_request = json!({
            "quoteResponse": quote,
            "userPublicKey": self.keypair.pubkey().to_string(),
            "computeUnitPriceMicroLamports": PRIORITY_FEE,
            "priorityFeeLamports": PRIORITY_FEE,
            "asLegacyTransaction": false,
            "maxAccounts": 64
        });

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

        response["swapTransaction"]
            .as_str()
            .ok_or_else(|| anyhow!("Invalid swap data"))
            .map(String::from)
    }

    pub async fn health_check(&self) -> Result<bool> {
        Ok(self.rpc_client.get_health().await.is_ok())
    }

    pub async fn monitor_positions(&self) -> Result<()> {
        for item in self.active_trades.iter() {
            let (token, trade) = item.pair();
            
            if trade.should_close() {
                match self.execute_rapid_trade(token, false).await {
                    Ok(sig) => info!("Position closed: {} ({})", token, sig),
                    Err(e) => error!("Failed to close position: {}", e),
                }
            }
        }
        Ok(())
    }
}  combine these 2 use {
    anyhow::{anyhow, Result},
    base64::{engine::general_purpose::STANDARD as BASE64, Engine},
    chrono::Utc,
    dashmap::DashMap,
    log::{error, info, warn},
    reqwest::Client,
    serde::{Deserialize, Serialize},
    serde_json::{json, Value},
    solana_client::nonblocking::rpc_client::RpcClient,
    solana_sdk::{
        commitment_config::CommitmentConfig,
        compute_budget::ComputeBudgetInstruction,
        instruction::Instruction,
        message::Message,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    std::{str::FromStr, time::Instant},
    tokio::time::{sleep, Duration},
};

// Core constants with optimal values
pub const HELIUS_WS: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com/";
pub const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
pub const HELIUS_API_KEY: &str = "1ea5843b-9daa-4926-a97a-be021922da2f";
pub const RAYDIUM_AMM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
pub const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
pub const SOL_MINT: &str = "So11111111111111111111111111111111111111112";

// Performance-tuned constants
const INITIAL_VALIDATION_DELAY: u64 = 800;  // ms delay before first validation
const BASE_RETRY_DELAY: u64 = 400;          // Base delay for retries
const RETRY_BACKOFF_STEP: u64 = 200;        // Incremental backoff step
const MAX_VALIDATION_ATTEMPTS: u8 = 5;       // Maximum validation attempts
const EXECUTION_TIMEOUT: u64 = 2000;         // Trading window timeout
const PRIORITY_FEE: u64 = 1_000_000;        // 0.001 SOL priority fee
const COMPUTE_UNITS: u32 = 200_000;         // Compute unit limit

// Trading parameters
const TRADE_AMOUNT: u64 = 10_000_000;       // 0.01 SOL per trade
const TAKE_PROFIT: f64 = 20.0;              // 20% profit target
const STOP_LOSS: f64 = -5.0;                // 5% stop loss
const MIN_LIQUIDITY: f64 = 1000.0;          // Minimum pool liquidity in USD
const MAX_LIQUIDITY: f64 = 20000.0;         // Maximum pool liquidity in USD
const MAX_CONCURRENT_TRADES: usize = 5;      // Maximum simultaneous trades
const PRICE_IMPACT_LIMIT: f64 = 2.5;        // Maximum acceptable price impact %

#[derive(Clone, Debug)]
pub struct Trade {
    pub entry_price: f64,
    pub current_price: f64,
    pub amount: u64,
    pub timestamp: i64,
    pub take_profit: f64,
    pub stop_loss: f64,
    pub attempts: u8,
    pub token_address: String,
    pub last_update: i64,
}

impl Trade {
    pub fn new(entry_price: f64, amount: u64, token_address: String) -> Self {
        let now = Utc::now().timestamp();
        Self {
            entry_price,
            current_price: entry_price,
            amount,
            timestamp: now,
            take_profit: TAKE_PROFIT,
            stop_loss: STOP_LOSS,
            attempts: 0,
            token_address,
            last_update: now,
        }
    }

    pub fn calculate_pl(&self) -> f64 {
        ((self.current_price - self.entry_price) / self.entry_price) * 100.0
    }

    pub fn should_close(&self) -> bool {
        let pl = self.calculate_pl();
        pl >= self.take_profit || pl <= self.stop_loss
    }

    pub fn is_stale(&self) -> bool {
        Utc::now().timestamp() - self.last_update > 300 // 5 minutes without update
    }
}

pub struct Bot {
    pub keypair: Keypair,
    pub http_client: Client,
    pub active_trades: DashMap<String, Trade>,
    pub rpc_client: RpcClient,
    pub jupiter_program_id: Pubkey,
}

impl Bot {
    pub fn new(keypair: Keypair) -> Self {
        info!("🚀 Initializing trading bot with enhanced timing...");
        
        Self {
            keypair,
            http_client: Client::new(),
            active_trades: DashMap::new(),
            rpc_client: RpcClient::new_with_commitment(
                HELIUS_RPC.to_string(),
                CommitmentConfig::confirmed(),
            ),
            jupiter_program_id: Pubkey::from_str("JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB")
                .expect("Invalid Jupiter program ID"),
        }
    }

    // Enhanced trade execution with parallel processing
    pub async fn execute_trade(&self, token: &str, is_buy: bool) -> Result<String> {
        let start = Instant::now();
        let operation = if is_buy { "BUY" } else { "SELL" };
        
        info!("🎯 Executing {} for {}", operation, token);

        // Parallel execution of pre-trade checks
        if is_buy {
            let (pool_valid, price_check) = tokio::join!(
                self.validate_pool_requirements(token),
                self.check_price_impact(token)
            );

            if let (Ok(true), Ok(impact)) = (pool_valid, price_check) {
                if impact > PRICE_IMPACT_LIMIT {
                    return Err(anyhow!("Price impact too high: {:.2}%", impact));
                }
            } else {
                return Err(anyhow!("Pre-trade validation failed"));
            }
        }

        // Parallel execution of trade components
        let (quote, blockhash) = tokio::join!(
            self.get_jupiter_quote(token, is_buy),
            self.rpc_client.get_latest_blockhash()
        );

        let quote = quote?;
        let blockhash = blockhash?;

        // Transaction construction
        let priority_ix = ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS);
        let compute_price_ix = ComputeBudgetInstruction::set_compute_unit_price(PRIORITY_FEE);
        let swap_ix = self.build_swap_instruction(&quote).await?;

        let message = Message::new(
            &[priority_ix, compute_price_ix, swap_ix],
            Some(&self.keypair.pubkey())
        );

        let mut tx = Transaction::new_unsigned(message);
        tx.sign(&[&self.keypair], blockhash);

        // Send transaction with monitoring
        match self.rpc_client.send_and_confirm_transaction(&tx) {
            Ok(sig) => {
                let duration = start.elapsed();
                info!(
                    "✅ {} executed in {:.2}ms ({})",
                    operation,
                    duration.as_millis(),
                    sig
                );
                
                // Update metrics and state
                self.update_metrics(operation, true);
                if is_buy {
                    self.add_trade(token, TRADE_AMOUNT).await?;
                } else {
                    self.active_trades.remove(token);
                }

                Ok(sig.to_string())
            }
            Err(e) => {
                error!("❌ {} failed: {}", operation, e);
                self.update_metrics(operation, false);
                Err(anyhow!(e))
            }
        }
    }
    // Continuing Bot implementation...

    async fn build_swap_instruction(&self, quote: &Value) -> Result<Instruction> {
        let swap_request = json!({
            "quoteResponse": quote,
            "userPublicKey": self.keypair.pubkey().to_string(),
            "dynamicComputeUnitLimit": true,
            "computeUnitPriceMicroLamports": PRIORITY_FEE,
            "priorityFeeLamports": PRIORITY_FEE,
            "asLegacyTransaction": false,
            "restrictIntermediateTokens": true,
            "maxAccounts": 64
        });

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

        let swap_data = response["swapTransaction"]
            .as_str()
            .ok_or_else(|| anyhow!("Invalid swap data"))?;

        let decoded_data = BASE64.decode(swap_data)?;

        Ok(Instruction {
            program_id: Pubkey::from_str("JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB")?,
            accounts: vec![],
            data: decoded_data,
        })
    }

    pub async fn validate_pool_requirements(&self, token: &str) -> Result<bool> {
        let start = Instant::now();
        let token_pubkey = Pubkey::from_str(token)?;

        // Advanced parallel validation with timing constraints
        let validation_result = tokio::select! {
            result = self.perform_validations(&token_pubkey) => result,
            _ = sleep(Duration::from_millis(EXECUTION_TIMEOUT)) => {
                Err(anyhow!("Validation timeout exceeded"))
            }
        };

        match validation_result {
            Ok((supply, liquidity, burnt, is_locked)) => {
                let elapsed = start.elapsed();
                let validation_success = self.verify_requirements(supply, liquidity, burnt, is_locked);
                
                self.log_validation_metrics(token, validation_success, elapsed, supply, liquidity);
                
                Ok(validation_success)
            }
            Err(e) => {
                warn!("❌ Validation failed for {}: {}", token, e);
                Ok(false)
            }
        }
    }

    async fn perform_validations(&self, token_pubkey: &Pubkey) -> Result<(u64, f64, bool, bool)> {
        let (supply, liquidity, burnt, lock_check) = tokio::join!(
            self.get_token_supply(token_pubkey),
            self.get_pool_liquidity(token_pubkey),
            self.check_tokens_burnt(&token_pubkey.to_string()),
            self.verify_pool_lock(token_pubkey)
        );

        Ok((
            supply?,
            liquidity?,
            burnt?,
            lock_check?,
        ))
    }

    fn verify_requirements(&self, supply: u64, liquidity: f64, burnt: bool, is_locked: bool) -> bool {
        (MIN_LIQUIDITY..=MAX_LIQUIDITY).contains(&liquidity)
            && (1_000_000..=1_000_000_000_000).contains(&supply)
            && burnt
            && is_locked
    }

    async fn check_price_impact(&self, token: &str) -> Result<f64> {
        let quote = self.get_jupiter_quote(token, true).await?;
        
        quote["priceImpactPct"]
            .as_f64()
            .ok_or_else(|| anyhow!("Invalid price impact data"))
    }

    pub async fn monitor_positions(&self) -> Result<()> {
        let mut updates = Vec::new();
        
        for item in self.active_trades.iter() {
            let (token, trade) = item.pair();
            
            if trade.is_stale() {
                warn!("Stale trade detected for {}", token);
                continue;
            }

            if let Ok(new_price) = self.get_token_price(token).await {
                let mut trade = trade.clone();
                trade.current_price = new_price;
                trade.last_update = Utc::now().timestamp();

                let pl = trade.calculate_pl();
                
                if trade.should_close() {
                    info!("🎯 Close condition met for {} (P/L: {:.2}%)", token, pl);
                    updates.push((token.clone(), true));
                } else {
                    updates.push((token.clone(), false));
                }
            }
        }

        // Batch process updates
        for (token, should_close) in updates {
            if should_close {
                match self.execute_trade(&token, false).await {
                    Ok(sig) => info!("Position closed: {} ({})", token, sig),
                    Err(e) => error!("Failed to close position: {}", e),
                }
            }
        }

        Ok(())
    }

    async fn verify_pool_lock(&self, token_pubkey: &Pubkey) -> Result<bool> {
        let account = self.rpc_client.get_account(token_pubkey).await?;
        
        // Advanced lock verification logic
        let lock_data = &account.data[64..96];
        let authority = Pubkey::new(lock_data);
        
        Ok(authority == Pubkey::default())
    }

    fn log_validation_metrics(
        &self,
        token: &str,
        success: bool,
        elapsed: Duration,
        supply: u64,
        liquidity: f64,
    ) {
        let status = if success { "✅" } else { "❌" };
        info!(
            "{} Validation {} ({:.2}ms)\n\
             ├─ Token: {}\n\
             ├─ Supply: {}\n\
             ├─ Liquidity: ${:.2}\n\
             └─ Timing: {:.2}ms",
            status,
            if success { "passed" } else { "failed" },
            elapsed.as_millis(),
            token,
            supply,
            liquidity,
            elapsed.as_millis()
        );
    }

    pub async fn health_check(&self) -> Result<bool> {
        let now = Utc::now().timestamp();
        let last = self.last_health_check.load(std::sync::atomic::Ordering::Relaxed);
        
        if now - last < 60 {  // Only check once per minute
            return Ok(true);
        }

        let result = self.rpc_client.get_health().await.is_ok();
        self.last_health_check.store(now, std::sync::atomic::Ordering::Relaxed);
        
        Ok(result)
    }

    fn update_metrics(&self, operation: &str, success: bool) {
        let mut entry = self.metrics
            .entry(operation.to_string())
            .or_insert((0, 0));
        
        if success {
            entry.0 += 1;
        } else {
            entry.1 += 1;
        }
    }
}