Compiling solana_rust_bot v0.1.0 (C:\solana_rust_bot)
error[E0425]: cannot find value `priority_ix` in this scope
   --> src/lib.rs:425:43
    |
425 | ...                   accounts: priority_ix.accounts.iter()
    |                                 ^^^^^^^^^^^ help: a local variable with a similar name exists: `priority_fee`

error[E0425]: cannot find value `priority_ix` in this scope
   --> src/lib.rs:428:39
    |
428 | ...                   data: priority_ix.data,
    |                             ^^^^^^^^^^^ help: a local variable with a similar name exists: `priority_fee`

error[E0599]: no associated item named `RpcClientError` found for struct `solana_client::client_error::ClientError` in the current scope
    --> src/lib.rs:1340:26
     |
1340 |             ClientError::RpcClientError(_) |
     |                          ^^^^^^^^^^^^^^ associated item not found in `ClientError`

error[E0599]: no associated item named `TransactionConfirmationError` found for struct `solana_client::client_error::ClientError` in the current scope
    --> src/lib.rs:1341:26
     |
1341 |             ClientError::TransactionConfirmationError(_) |
     |                          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ associated item not found in `ClientError`

error[E0599]: no associated item named `CustomError` found for struct `solana_client::client_error::ClientError` in the current scope
    --> src/lib.rs:1342:26
     |
1342 |             ClientError::CustomError(_)
     |                          ^^^^^^^^^^^ associated item not found in `ClientError`

Some errors have detailed explanations: E0425, E0599.
For more information about an error, try `rustc --explain E0425`.
error: could not compile `solana_rust_bot` (lib) due to 5 previous errors use anyhow::{anyhow, Result};
use base64::engine::general_purpose::STANDARD as BASE64;
use base64::Engine;
use chrono::Utc;
use dashmap::DashMap;
use log::{debug, error, info, warn};
use reqwest::Client;
use serde::{Deserialize, Serialize};
use serde_json::{json, Value};
use solana_client::{
    nonblocking::rpc_client::RpcClient,
    client_error::ClientError,
};
use solana_sdk::{
    compute_budget::ComputeBudgetInstruction,
    hash::Hash,
    instruction::Instruction,
    message::Message as SolanaMessage,
    pubkey::Pubkey,
    signature::{Keypair, Signer},
    transaction::Transaction,
};
use std::{
    collections::HashMap,
    convert::TryInto,
    str::FromStr,
    sync::Arc,
    time::{Duration, Instant},
};
use tokio::{sync::RwLock, time::sleep};


// Core Constants
pub const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
pub const RAYDIUM_AMM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
pub const SOL_MINT: &str = "So11111111111111111111111111111111111111112";

#[allow(dead_code)]
const MIN_RETRIES: u32 = 3;

#[allow(dead_code)]
const CACHE_DURATION: i64 = 5; // seconds

// Trading Constants
const MAX_TRADES: usize = 5;
const TAKE_PROFIT: f64 = 20.0;
const STOP_LOSS: f64 = -3.0;
const MIN_LIQUIDITY: f64 = 50.0;
const MAX_LIQUIDITY: f64 = 20000.0;
const PRIORITY_FEE: u64 = 1_000_000;
const TRADE_AMOUNT: u64 = 10_000_000;

// Validation Constants
const MAX_RETRIES: u32 = 6;
const VALIDATION_TIMEOUT: Duration = Duration::from_secs(3);
const MIN_ACCOUNT_DATA_LEN: usize = 16;
const SUPPLY_MIN: u64 = 1_000_000;
const SUPPLY_MAX: u64 = 1_000_000_000_000;

// Performance Constants
const RPC_SWITCH_THRESHOLD: u32 = 5;
const INITIAL_RETRY_DELAY: u64 = 100;
const MAX_RETRY_DELAY: u64 = 1000;

// Implement Default for ValidationMetrics
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ValidationMetrics {
    pub token: String,
    pub attempts: u32,
    pub total_time_ms: u64,
    pub supply_check: Option<u64>,
    pub liquidity_check: Option<f64>,
    pub mint_authority_check: Option<bool>,
    pub tokens_burnt_check: Option<bool>,
    pub error_message: Option<String>,
    pub timestamp: chrono::DateTime<Utc>,
    pub validation_history: Vec<ValidationAttempt>,
}

impl Default for ValidationMetrics {
    fn default() -> Self {
        Self {
            token: String::new(),
            attempts: 0,
            total_time_ms: 0,
            supply_check: None,
            liquidity_check: None,
            mint_authority_check: None,
            tokens_burnt_check: None,
            error_message: None,
            timestamp: Utc::now(),
            validation_history: Vec::new(),
        }
    }
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ValidationAttempt {
    pub attempt_number: u32,
    pub timestamp: chrono::DateTime<Utc>,
    pub success: bool,
    pub response_time_ms: u64,
    pub metrics: HashMap<String, String>,
}

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

#[derive(Clone, Debug)]
pub enum TradeStatus {
    Active,
    PendingClose {
        reason: String,
        timestamp: chrono::DateTime<Utc>,
    },
    Closed {
        final_pl: f64,
        timestamp: chrono::DateTime<Utc>,
    },
    Failed {
        error: String,
        timestamp: chrono::DateTime<Utc>,
    },
}

#[derive(Clone, Debug)]
pub struct Trade {
    pub entry_price: f64,
    pub current_price: f64,
    pub amount: u64,
    pub profit_loss: f64,
    pub timestamp: i64,
    pub take_profit: f64,
    pub stop_loss: f64,
    pub attempts: u32,
    pub last_update: Instant,
    pub status: TradeStatus,
    pub execution_history: Vec<TradeExecution>,
}

#[derive(Clone, Debug)]
pub struct TradeExecution {
    pub timestamp: chrono::DateTime<Utc>,
    pub action: String,
    pub price: f64,
    pub amount: u64,
    pub success: bool,
    pub execution_time_ms: u64,
    pub error: Option<String>,
}

impl Trade {
    pub fn new(entry_price: f64, amount: u64) -> Self {
        Self {
            entry_price,
            current_price: entry_price,
            amount,
            profit_loss: 0.0,
            timestamp: Utc::now().timestamp(),
            take_profit: TAKE_PROFIT,
            stop_loss: STOP_LOSS,
            attempts: 0,
            last_update: Instant::now(),
            status: TradeStatus::Active,
            execution_history: Vec::new(),
        }
    }

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

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

    pub fn update_status(&mut self, new_price: f64) -> TradeStatus {
        self.current_price = new_price;
        self.profit_loss = self.calculate_pl();

        let status = if self.should_close() {
            TradeStatus::PendingClose {
                reason: if self.profit_loss >= self.take_profit {
                    "Take Profit".to_string()
                } else {
                    "Stop Loss".to_string()
                },
                timestamp: Utc::now(),
            }
        } else {
            TradeStatus::Active
        };

        self.status = status.clone();
        status
    }

    pub fn add_execution(&mut self, execution: TradeExecution) {
        self.execution_history.push(execution);
    }
}

#[derive(Clone, Debug)]
pub struct TradeMetrics {
    pub timestamp: i64,
    pub detection_time: Duration,
    pub validation_time: Duration,
    pub execution_time: Duration,
    pub total_time: Duration,
    pub attempts: u8,
    pub success: bool,
    pub error: Option<String>,
    pub price_impact: Option<f64>,
    pub network_latency: Duration,
}

#[derive(Clone)]
pub struct PoolStatus {
    pub token: String,
    pub creation_time: Instant,
    pub last_validation: Instant,
    pub validation_attempts: u8,
    pub liquidity: f64,
    pub is_tradeable: bool,
    pub has_failed: bool,
    pub error_reason: Option<String>,
    pub validation_history: Vec<ValidationAttempt>,
    pub market_metrics: MarketMetrics,
}

#[derive(Clone, Debug)]
pub struct MarketMetrics {
    pub volume_24h: f64,
    pub price_change_24h: f64,
    pub total_liquidity: f64,
    pub num_holders: u64,
    pub last_update: chrono::DateTime<Utc>,
}

pub struct Bot {
    pub config: Config,
    pub keypair: Keypair,
    pub http_client: Client,
    pub active_trades: DashMap<String, Trade>,
    pub rpc_client: RpcClient,
    pub fallback_rpc_client: RpcClient,
    pub jupiter_program_id: Pubkey,
    pub pool_status: Arc<DashMap<String, PoolStatus>>,
    pub trade_metrics: Arc<RwLock<Vec<TradeMetrics>>>,
    pub current_tps: Arc<RwLock<u32>>,
    pub validation_cache: Arc<DashMap<String, ValidationMetrics>>,
    pub performance_metrics: Arc<RwLock<PerformanceMetrics>>,
}

#[derive(Debug, Default)]
pub struct PerformanceMetrics {
    pub total_validations: u64,
    pub successful_validations: u64,
    pub total_trades: u64,
    pub successful_trades: u64,
    pub average_execution_time: Duration,
    pub peak_tps: u32,
    pub last_reset: chrono::DateTime<Utc>,
}

// First, define PreparedTradeData
#[derive(Debug, Clone)]
pub struct PreparedTradeData {
    pub trade_data: Vec<u8>,
    pub blockhash: Option<Hash>,
    pub priority_fee: u64,
}

impl Bot {
    pub async fn new(config: Config, keypair: Keypair) -> Result<Self> {
        let rpc_url = config.rpc_url.clone();
        let fallback_rpc = config.fallback_ws.replace("wss://", "https://");

        Ok(Self {
            config: config.clone(),
            keypair,
            http_client: Client::builder()
                .timeout(Duration::from_secs(5))
                .build()?,
            active_trades: DashMap::new(),
            rpc_client: RpcClient::new(rpc_url),
            fallback_rpc_client: RpcClient::new(fallback_rpc),
            jupiter_program_id: Pubkey::from_str("JUP4Fb2cqiRUcaTHdrPC8h2gNsA2ETXiPDD33WcGuJB")?,
            pool_status: Arc::new(DashMap::new()),
            trade_metrics: Arc::new(RwLock::new(Vec::new())),
            current_tps: Arc::new(RwLock::new(0)),
            validation_cache: Arc::new(DashMap::new()),
            performance_metrics: Arc::new(RwLock::new(PerformanceMetrics::default())),
        })
    }

    async fn get_latest_blockhash_with_retries(&self) -> Result<Hash> {
        for attempt in 0..3 {
            match self.rpc_client.get_latest_blockhash().await {
                Ok(hash) => return Ok(hash),
                Err(_e) if attempt < 2 => {
                    sleep(Duration::from_millis(50 * (attempt + 1) as u64)).await;
                    continue;
                }
                Err(e) => return Err(anyhow!("Failed to get blockhash: {}", e)),
            }
        }
        Err(anyhow!("Failed to get blockhash after retries"))
    }

    // Add missing validation methods
    async fn validate_pool_aggressive(&self, token: &str) -> Result<(bool, ValidationMetrics)> {
        let start = Instant::now();
        let token_pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;

        let (supply_result, liquidity_result) = tokio::join!(
            self.get_token_supply_with_retries(&token_pubkey, client),
            self.get_pool_liquidity_with_retries(&token_pubkey, client)
        );

        match (supply_result, liquidity_result) {
            (Ok(supply), Ok(liquidity)) => {
                let valid = supply >= (SUPPLY_MIN as f64 * 0.8) as u64 &&
                           liquidity >= MIN_LIQUIDITY * 0.6; // More aggressive check

                Ok((valid, ValidationMetrics {
                    token: token.to_string(),
                    attempts: 1,
                    total_time_ms: start.elapsed().as_millis() as u64,
                    supply_check: Some(supply),
                    liquidity_check: Some(liquidity),
                    tokens_burnt_check: None,
                    mint_authority_check: None,
                    error_message: None,
                    timestamp: Utc::now(),
                    validation_history: vec![],
                }))
            }
            (Err(e), _) | (_, Err(e)) => Err(anyhow!("Validation failed: {}", e)),
        }
    }

    async fn validate_pool_minimal(&self, token: &str) -> Result<(bool, ValidationMetrics)> {
        let start = Instant::now();
        let token_pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;

        if let Ok(liquidity) = self.get_pool_liquidity_with_retries(&token_pubkey, client).await {
            Ok((liquidity >= MIN_LIQUIDITY * 0.5, ValidationMetrics {
                token: token.to_string(),
                attempts: 1,
                total_time_ms: start.elapsed().as_millis() as u64,
                supply_check: None,
                liquidity_check: Some(liquidity),
                tokens_burnt_check: None,
                mint_authority_check: None,
                error_message: None,
                timestamp: Utc::now(),
                validation_history: vec![],
            }))
        } else {
            Ok((false, ValidationMetrics::default()))
        }
    }

    // Fix execute_rapid_trade_optimized signature and implementation
    async fn execute_rapid_trade_optimized(
        &self,
        token: &str,
        is_buy: bool,
        priority_fee: u64,
        rpc_type: &str,
        prepared_data: Option<&PreparedTradeData>,
    ) -> Result<String> {
        let start = Instant::now();
        info!("⚡ Executing {} trade on {} RPC", if is_buy { "buy" } else { "sell" }, rpc_type);

        // Handle prepared data and get quote/blockhash
        let (quote, blockhash) = match prepared_data {
            Some(data) => {
                // Convert prepared data to proper result types
                let quote_result = self.get_jupiter_quote_enhanced(token, SOL_MINT, if is_buy {
                    TRADE_AMOUNT
                } else {
                    0
                })
                .await?;
                let blockhash = match data.blockhash {
                    Some(hash) => hash,
                    None => self.get_latest_blockhash_with_retries().await?,
                };
                (Ok(quote_result), Ok(blockhash))
            }
            None => {
                tokio::join!(
                    self.get_jupiter_quote_enhanced(token, SOL_MINT, if is_buy {
                        TRADE_AMOUNT
                    } else {
                        0
                    }),
                    self.get_latest_blockhash_with_retries()
                )
            }
        };

        // Process results
        match (quote, blockhash) {
            (Ok(quote_data), Ok(hash)) => {
                let mut transaction = self.prepare_transaction(
                    &quote_data,
                    hash,
                    priority_fee,
                    is_buy,
                            )
                            .await?;
                            let compiled_ix = solana_program::instruction::CompiledInstruction {
                                program_id_index: transaction.message.instructions.len() as u8,
                                accounts: priority_ix.accounts.iter()
                                    .map(|meta| meta.pubkey.to_bytes().to_vec())
                                    .collect(),
                                data: priority_ix.data,
                            };
                            transaction.message.instructions.insert(0, compiled_ix);

                            match self.rpc_client.send_and_confirm_transaction(&transaction).await {
                    Ok(signature) => {
                        // Verify transaction
                        if self.verify_transaction(&signature.to_string()).await? {
                            let execution_time = start.elapsed();
                            self.update_trade_metrics(true, execution_time).await;
                            Ok(signature.to_string())
                        } else {
                            Err(anyhow!("Transaction verification failed"))
                        }
                    }
                    Err(e) => Err(anyhow!("Transaction failed: {}", e)),
                }
            }
            (Err(e), _) | (_, Err(e)) => Err(anyhow!("Failed to prepare transaction: {}", e)),
        }
    }

    // Fix process_market_event implementation
    pub async fn process_market_event(&self, event: &str) -> Result<()> {
        let start_time = Instant::now();
        let event_data = serde_json::from_str::<Value>(event)?;

        if let Some(token_address) = self.extract_early_token_fast(&event_data) {
            info!("🎯 Token Detection: {} (Time: {}ms)",
                token_address,
                start_time.elapsed().as_millis());

            let (quick_check, full_check) = tokio::join!(
                self.pre_validate_token(&token_address),
                self.validate_pool_comprehensive(&token_address)
            );

            if quick_check.unwrap_or(false) {
                let (price_result, blockhash_result) = tokio::join!(
                    self.get_token_price_parallel(&token_address),
                    self.get_latest_blockhash_with_retries()
                );

                if let Ok(initial_price) = price_result {
                    if self.should_execute_trade(&token_address, initial_price) {
                        let prepared_data = self.prepare_trade_data(
                            &token_address,
                            initial_price,
                            blockhash_result.ok()
                        ).await;

                        if let Ok((is_valid, _metrics)) = full_check {
                            if is_valid {
                                return self.execute_rapid_trade_optimized(
                                    &token_address,
                                    true,
                                    PRIORITY_FEE,
                                    "primary",
                                    prepared_data.as_ref()
                                ).await.map(|_| ());
                            }
                        }
                    }
                }
            }

            // Fallback validation attempts
            for attempt in 1..=3 {
                let validation_strategy = match attempt {
                    1 => self.validate_pool_aggressive(&token_address).await,
                    2 => self.validate_pool_quick(&token_address).await,
                    3 => self.validate_pool_minimal(&token_address).await,
                    _ => unreachable!()
                };

                if let Ok((is_valid, _metrics)) = validation_strategy {
                    if is_valid {
                        if let Ok(price) = self.get_token_price_with_enhanced_retries(&token_address).await {
                            if self.should_execute_trade(&token_address, price) {
                                return self.execute_rapid_trade_optimized(
                                    &token_address,
                                    true,
                                    PRIORITY_FEE * 2,
                                    "fallback",
                                    None
                                ).await.map(|_| ());
                            }
                        }
                    }
                }

                sleep(Duration::from_millis(50 * attempt as u64)).await;
            }
        }

        Ok(())
    }
    // Fix trade metrics update
    async fn update_trade_metrics(&self, success: bool, duration: Duration) {
        let mut metrics = self.performance_metrics.write().await;
        metrics.total_trades += 1;
        if success {
            metrics.successful_trades += 1;
        }
        
        let total_time = metrics.average_execution_time.as_nanos() as u64 * (metrics.total_trades - 1);
        let new_average = Duration::from_nanos(
            (total_time + duration.as_nanos() as u64) / metrics.total_trades
        );
        metrics.average_execution_time = new_average;
    }

    // Fix prepare_trade_data implementation
    async fn prepare_trade_data(
        &self,
        _token: &str,
        _price: f64,
        _blockhash: Option<Hash>
    ) -> Option<PreparedTradeData> {
        None // Placeholder implementation
    }

    // Fix quick validation with proper float conversions
    async fn validate_pool_quick(&self, token: &str) -> Result<(bool, ValidationMetrics)> {
        let start = Instant::now();

        let (supply_result, liquidity_result) = tokio::join!(
            self.get_token_supply_quick(token),
            self.get_pool_liquidity_quick(token)
        );

        match (supply_result, liquidity_result) {
            (Ok(supply), Ok(liquidity)) => {
                let min_supply = (SUPPLY_MIN as f64 * 0.8) as u64;
                let min_liquidity = MIN_LIQUIDITY * 0.8;
                
                let valid = supply >= min_supply && liquidity >= min_liquidity;

                Ok((valid, ValidationMetrics {
                    token: token.to_string(),
                    attempts: 1,
                    total_time_ms: start.elapsed().as_millis() as u64,
                    supply_check: Some(supply),
                    liquidity_check: Some(liquidity),
                    tokens_burnt_check: None,
                    mint_authority_check: None,
                    error_message: None,
                    timestamp: Utc::now(),
                    validation_history: vec![],
                }))
            }
            _ => Ok((false, ValidationMetrics::default()))
        }
    }

    // Fix delays array
    async fn get_token_price_with_enhanced_retries(&self, token: &str) -> Result<f64> {
        let delays = [0, 25, 50, 100]; // Remove mut as it's not needed
        let mut last_error = None;
        
        for (attempt, &delay) in delays.iter().enumerate() {
            if attempt > 0 {
                sleep(Duration::from_millis(delay)).await;
            }

            match self.get_token_price(token).await {
                Ok(price) => return Ok(price),
                Err(e) => {
                    match self.get_token_price_fallback(token).await {
                        Ok(price) => return Ok(price),
                        Err(fallback_e) => {
                            last_error = Some(format!("Primary: {}, Fallback: {}", e, fallback_e));
                        }
                    }
                }
            }
        }
        
        Err(anyhow!("Price fetch failed: {}", last_error.unwrap_or_default()))
    }
    fn extract_early_token_fast(&self, event_data: &Value) -> Option<String> {
        event_data
            .get("params")?
            .get("result")?
            .get("value")?
            .get("account")?
            .get("data")?
            .get(0)?
            .as_str()
            .map(|data| {
                if let Ok(decoded) = BASE64.decode(data) {
                    if decoded.len() >= 40 {
                        let token_bytes = &decoded[8..40];
                        return Some(bs58::encode(token_bytes).into_string());
                    }
                }
                None
            })?
    }

    async fn pre_validate_token(&self, token: &str) -> Result<bool> {
        // Quick check for basic validity
        let pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;
        
        if let Ok(data) = client.get_account_data(&pubkey).await {
            Ok(data.len() >= MIN_ACCOUNT_DATA_LEN)
        } else {
            Ok(false)
        }
    }

    async fn get_token_supply_quick(&self, token: &str) -> Result<u64> {
        let token_pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;
        
        match client.get_token_supply(&token_pubkey).await {
            Ok(supply) => Ok(supply.ui_amount.unwrap_or(0.0) as u64),
            Err(e) => Err(anyhow!("Supply check failed: {}", e))
        }
    }

    async fn get_pool_liquidity_quick(&self, token: &str) -> Result<f64> {
        let token_pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;
        
        match client.get_account_data(&token_pubkey).await {
            Ok(data) if data.len() >= 16 => {
                let liquidity_bytes = &data[8..16];
                let liquidity_value = u64::from_le_bytes(liquidity_bytes.try_into()?);
                Ok((liquidity_value as f64) / 1_000_000.0)
            }
            Ok(_) => Ok(0.0),
            Err(e) => Err(anyhow!("Liquidity check failed: {}", e))
        }
    }

    async fn check_tokens_burnt_quick(&self, token: &str) -> Result<bool> {
        let token_pubkey = Pubkey::from_str(token)?;
        let client = self.select_rpc_client().await;
        
        match client.get_token_account(&token_pubkey).await {
            Ok(Some(account)) => Ok(account.token_amount.amount == "0"),
            _ => Ok(false)
        }
    }

    async fn get_token_price_parallel(&self, token: &str) -> Result<f64> {
        let (primary, fallback) = tokio::join!(
            self.get_token_price(token),
            self.get_token_price_fallback(token)
        );

        primary.or(fallback)
    }

    async fn get_token_price_fallback(&self, token: &str) -> Result<f64> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getTokenPrice",
            "params": [token]
        });

        let response = self.http_client
            .post(&self.config.fallback_ws.replace("wss://", "https://"))
            .json(&request)
            .send()
            .await?
            .json::<Value>()
            .await?;

        response["result"]["price"]
            .as_f64()
            .ok_or_else(|| anyhow!("Invalid price data"))
    }

    async fn verify_transaction(&self, signature: &str) -> Result<bool> {
        for _ in 0..10 {
            match self.rpc_client.confirm_transaction_with_commitment(
                &signature.parse()?,
                self.rpc_client.commitment()
            ).await {
                Ok(result) => return Ok(result.value),
                Err(_) => sleep(Duration::from_millis(100)).await
            }
        }
        Ok(false)
    }

    async fn calculate_optimal_priority_fee(&self, price: f64) -> u64 {
        let base_fee = PRIORITY_FEE;
        if price < 0.001 {
            base_fee * 2
        } else if price < 0.005 {
            base_fee * 3
        } else {
            base_fee
        }
    }
    
    async fn log_error_metrics(&self, token: &str, error_type: &str, error: impl std::fmt::Display) {
        warn!("❌ {} error for {}: {}", error_type, token, error);
        // Add to metrics if needed
    }

    async fn validate_pool_comprehensive(&self, token: &str) -> Result<(bool, ValidationMetrics)> {
        let start_time = Instant::now();
        let mut metrics = ValidationMetrics {
            token: token.to_string(),
            attempts: 0,
            total_time_ms: 0,
            supply_check: None,
            liquidity_check: None,
            mint_authority_check: None,
            tokens_burnt_check: None,
            error_message: None,
            timestamp: Utc::now(),
            validation_history: Vec::new(),
        };

        let token_pubkey = Pubkey::from_str(token).map_err(|e| {
            let error = format!("Invalid token pubkey: {}", e);
            metrics.error_message = Some(error.clone());
            anyhow!(error)
        })?;

        let mut backoff = Duration::from_millis(INITIAL_RETRY_DELAY);
        let validation_start = Instant::now();

        while metrics.attempts < MAX_RETRIES && validation_start.elapsed() < VALIDATION_TIMEOUT {
            metrics.attempts += 1;
            debug!("Validation attempt {} for token {}", metrics.attempts, token);

            let client = self.select_rpc_client().await;
            
            // Store results before processing
            let supply_result = self.get_token_supply_with_retries(&token_pubkey, client).await;
            let liquidity_result = self.get_pool_liquidity_with_retries(&token_pubkey, client).await;
            let burnt_result = self.check_tokens_burnt_with_retries(token, client).await;
            let mint_result = self.check_mint_authority_with_retries(&token_pubkey, client).await;

            let attempt = ValidationAttempt {
                attempt_number: metrics.attempts,
                timestamp: Utc::now(),
                success: supply_result.is_ok() && liquidity_result.is_ok() && 
                        burnt_result.is_ok() && mint_result.is_ok(),
                response_time_ms: validation_start.elapsed().as_millis() as u64,
                metrics: HashMap::new(),
            };
            metrics.validation_history.push(attempt);

            match (&supply_result, &liquidity_result, &burnt_result, &mint_result) {
                (Ok(supply), Ok(liquidity), Ok(burnt), Ok(mint)) => {
                    metrics.supply_check = Some(*supply);
                    metrics.liquidity_check = Some(*liquidity);
                    metrics.tokens_burnt_check = Some(*burnt);
                    metrics.mint_authority_check = Some(*mint);

                    if self.evaluate_validation_results(&metrics) {
                        metrics.total_time_ms = start_time.elapsed().as_millis() as u64;
                        self.validation_cache.insert(token.to_string(), metrics.clone());
                        self.update_pool_status(token, &metrics).await;
                        return Ok((true, metrics));
                    }
                }
                _ => {
                    if self.should_continue_validation(
                        &supply_result,
                        &liquidity_result,
                        &burnt_result,
                        &mint_result,
                    ).await {
                        sleep(backoff).await;
                        backoff = Duration::from_millis(
                            (backoff.as_millis() as f64 * 1.5)
                                .min(MAX_RETRY_DELAY as f64) as u64
                        );
                        continue;
                    }
                }
            }
        }

        metrics.total_time_ms = start_time.elapsed().as_millis() as u64;
        metrics.error_message = Some(format!(
            "Validation failed after {} attempts",
            metrics.attempts
        ));

        Ok((false, metrics))
    }

    async fn should_continue_validation(
        &self,
        supply: &Result<u64>,
        liquidity: &Result<f64>,
        burnt: &Result<bool>,
        mint: &Result<bool>
    ) -> bool {
        let errors: Vec<String> = vec![
            supply.as_ref().err(),
            liquidity.as_ref().err(),
            burnt.as_ref().err(),
            mint.as_ref().err(),
        ].into_iter()
        .filter_map(|e| e.map(|err| err.to_string()))
        .collect();

        errors.iter().any(|e| 
            e.contains("AccountNotFound") || 
            e.contains("Connection refused") || 
            e.contains("rate limited")
        )
    }

    // Fix the monitor_positions_enhanced method
    pub async fn monitor_positions_enhanced(&self) -> Result<()> {
        let positions: Vec<_> = self.active_trades.iter().map(|entry| {
            (entry.key().clone(), entry.value().clone())
        }).collect();

        for (token, trade_data) in positions {
            if trade_data.last_update.elapsed() < Duration::from_millis(500) {
                continue;
            }

            if let Ok(current_price) = self.get_token_price(&token).await {
                if let Some(mut trade) = self.active_trades.get_mut(&token) {
                    match trade.update_status(current_price) {
                        TradeStatus::PendingClose { reason, timestamp } => {
                            info!(
                                "🔄 Closing position for {} - Reason: {}", 
                                token, 
                                reason
                            );
                            
                            if let Err(e) = self.execute_rapid_trade_optimized(&token, false, 0, "", None).await {
                                error!("Failed to close position: {}", e);
                                trade.status = TradeStatus::Failed {
                                    error: e.to_string(),
                                    timestamp,
                                };
                            }
                        }
                        TradeStatus::Active => {
                            debug!(
                                "Position Update - Token: {}, P/L: {:.2}%",
                                token,
                                trade.calculate_pl()
                            );
                        }
                        _ => {}
                    }
                }
            }
        }

        Ok(())
    }

    // Add type annotations for tokio::join! macro
    async fn prepare_transaction(
        &self,
        quote: &Value,
        blockhash: Hash,
        priority_fee: u64,
        _is_buy: bool,
    ) -> Result<Transaction> {
        let swap_data = self.prepare_swap_data_enhanced(quote).await?;
        let tx_data = BASE64.decode(&swap_data)?;

        let priority_ix = ComputeBudgetInstruction::set_compute_unit_price(priority_fee);
        let swap_ix = Instruction {
            program_id: self.jupiter_program_id,
            accounts: vec![],
            data: tx_data,
        };

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

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

        Ok(transaction)
    }
    async fn get_token_supply_with_retries(&self, token_pubkey: &Pubkey, client: &RpcClient) -> Result<u64> {
        let mut attempts = 0;
        let max_attempts = 3;
        
        while attempts < max_attempts {
            match client.get_token_supply(token_pubkey).await {
                Ok(supply) => {
                    return Ok(supply.ui_amount.unwrap_or(0.0) as u64);
                }
                Err(e) => {
                    attempts += 1;
                    if attempts < max_attempts {
                        sleep(Duration::from_millis(100 * attempts as u64)).await;
                    } else {
                        return Err(anyhow!("Supply check failed: {}", e));
                    }
                }
            }
        }
        
        Err(anyhow!("Supply check failed after {} attempts", max_attempts))
    }

    async fn get_pool_liquidity_with_retries(&self, token_pubkey: &Pubkey, client: &RpcClient) -> Result<f64> {
        let mut attempts = 0;
        let max_attempts = 3;
        
        while attempts < max_attempts {
            match client.get_account_data(token_pubkey).await {
                Ok(data) => {
                    if data.len() >= MIN_ACCOUNT_DATA_LEN {
                        let liquidity_bytes = &data[8..16];
                        let liquidity_value = u64::from_le_bytes(
                            liquidity_bytes.try_into().unwrap_or([0; 8])
                        );
                        return Ok((liquidity_value as f64) / 1_000_000.0);
                    }
                    attempts += 1;
                    sleep(Duration::from_millis(100 * attempts as u64)).await;
                }
                Err(e) => {
                    if e.to_string().contains("AccountNotFound") {
                        attempts += 1;
                        sleep(Duration::from_millis(200 * attempts as u64)).await;
                    } else {
                        return Err(anyhow!("Liquidity check failed: {}", e));
                    }
                }
            }
        }
        
        Err(anyhow!("Could not determine pool liquidity after {} attempts", max_attempts))
    }
    pub async fn get_token_price(&self, token: &str) -> Result<f64> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": 1,
            "method": "getTokenPrice",
            "params": [
                token,
                {
                    "source": "raydium",
                    "priority": "high"
                }
            ]
        });

        let response = self
            .http_client
            .post(&self.config.rpc_url)
            .header(
                "Authorization",
                format!("Bearer {}", self.config.helius_api_key),
            )
            .json(&request)
            .send()
            .await?
            .json::<Value>()
            .await?;

        response["result"]["price"]
            .as_f64()
            .ok_or_else(|| anyhow!("Invalid price data"))
    }

    pub fn should_execute_trade(&self, token: &str, price: f64) -> bool {
        price > 0.0
            && price < 0.01
            && !self.active_trades.contains_key(token)
            && self.active_trades.len() < MAX_TRADES
    }

    async fn select_rpc_client(&self) -> &RpcClient {
        let current_tps = *self.current_tps.read().await;
        if current_tps > RPC_SWITCH_THRESHOLD {
            &self.fallback_rpc_client
        } else {
            &self.rpc_client
        }
    }
    async fn check_tokens_burnt_with_retries(&self, token: &str, client: &RpcClient) -> Result<bool> {
        let token_pubkey = Pubkey::from_str(token)?;
        let mut attempts = 0;
        let max_attempts = 3;

        while attempts < max_attempts {
            match client.get_account(&token_pubkey).await {
                Ok(account) => {
                    return Ok(account.data.is_empty() || account.data[0] == 0);
                }
                Err(e) => {
                    attempts += 1;
                    if attempts < max_attempts {
                        sleep(Duration::from_millis(100 * attempts as u64)).await;
                    } else {
                        return Err(anyhow!("Burn check failed: {}", e));
                    }
                }
            }
        }
        
        Ok(false)
    }

    async fn check_mint_authority_with_retries(&self, token_pubkey: &Pubkey, client: &RpcClient) -> Result<bool> {
        let mut attempts = 0;
        let max_attempts = 3;

        while attempts < max_attempts {
            match client.get_account(token_pubkey).await {
                Ok(account) => {
                    return Ok(account.data.len() > 4);
                }
                Err(e) => {
                    attempts += 1;
                    if attempts < max_attempts {
                        sleep(Duration::from_millis(100 * attempts as u64)).await;
                    } else {
                        return Err(anyhow!("Mint authority check failed: {}", e));
                    }
                }
            }
        }

        Ok(false)
    }

    fn evaluate_validation_results(&self, metrics: &ValidationMetrics) -> bool {
        let supply_valid = metrics.supply_check
            .map(|s| (SUPPLY_MIN..=SUPPLY_MAX).contains(&s))
            .unwrap_or(false);

        let liquidity_valid = metrics.liquidity_check
            .map(|l| (MIN_LIQUIDITY..=MAX_LIQUIDITY).contains(&l))
            .unwrap_or(false);

        let mint_valid = !metrics.mint_authority_check.unwrap_or(true);
        let tokens_burnt = metrics.tokens_burnt_check.unwrap_or(false);

        supply_valid && liquidity_valid && mint_valid && tokens_burnt
    }

    async fn update_pool_status(&self, token: &str, metrics: &ValidationMetrics) {
        let status = PoolStatus {
            token: token.to_string(),
            creation_time: Instant::now(),
            last_validation: Instant::now(),
            validation_attempts: metrics.attempts as u8,
            liquidity: metrics.liquidity_check.unwrap_or(0.0),
            is_tradeable: true,
            has_failed: false,
            error_reason: None,
            validation_history: metrics.validation_history.clone(),
            market_metrics: MarketMetrics {
                volume_24h: 0.0,
                price_change_24h: 0.0,
                total_liquidity: metrics.liquidity_check.unwrap_or(0.0),
                num_holders: 0,
                last_update: Utc::now(),
            },
        };

        self.pool_status.insert(token.to_string(), status);
    }

    async fn get_jupiter_quote_enhanced(
        &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 = self.http_client
            .get(&url)
            .timeout(Duration::from_secs(2))
            .send()
            .await?
            .json::<Value>()
            .await?;

        if let Some(error) = response.get("error") {
            return Err(anyhow!("Jupiter API error: {}", error));
        }

        Ok(response)
    }

    async fn prepare_swap_data_enhanced(&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,
            "useSharedAccounts": true,
            "useTokenLedger": false
        });

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

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

    pub fn extract_pool_data(event_data: &Value) -> Option<&Value> {
        event_data
            .get("method")?
            .as_str()
            .filter(|&m| m == "programNotification")?;

        event_data
            .get("params")?
            .get("result")?
            .get("value")?
            .get("account")?
            .get("data")?
            .get(0)
    }

    pub fn extract_token_from_pool(pool_data: &[u8]) -> Result<String> {
        let data_start = 8;

        if pool_data.len() < data_start + 32 {
            return Err(anyhow!("Pool data too short"));
        }

        let token_bytes = &pool_data[data_start..data_start + 32];
        let token_address = bs58::encode(token_bytes).into_string();

        Ok(token_address)
    }

    async fn execute_urgent_trade_enhanced(
        &self,
        token: &str,
        price: f64,
        prepared_data: Option<PreparedTradeData>,
        start_time: Instant,
    ) -> Result<()> {
        info!("⚡ EXECUTING TRADE\n💎 Token: {}\n💰 Price: ${:.8}\n⏱️ Prep Time: {}ms",
            token, price, start_time.elapsed().as_millis());

        // Dynamic priority fee calculation based on market conditions
        let base_priority_fee = self.calculate_optimal_priority_fee(price).await;
        let priority_fees = [
            base_priority_fee,
            base_priority_fee * 2,
            base_priority_fee * 3,
            base_priority_fee * 5  // Ultra-high priority for last attempt
        ];

        // Track attempts across RPCs
        let mut primary_attempts = 0;
        let mut fallback_attempts = 0;
        let max_attempts = priority_fees.len() * 2; // Total attempts across both RPCs

        while primary_attempts + fallback_attempts < max_attempts {
            let use_fallback = primary_attempts >= priority_fees.len() / 2;
            let current_fee = priority_fees[primary_attempts % priority_fees.len()];
            
            let attempt_result = self.execute_rapid_trade_optimized(
                token,
                true,
                current_fee,
                if use_fallback { "fallback" } else { "primary" },
                prepared_data.as_ref(),
            ).await;

            match attempt_result {
                Ok(signature) => {
                    // Verify transaction success
                    match self.verify_transaction(&signature).await {
                        Ok(_) => {
                            let execution_time = start_time.elapsed();
                            info!(
                                "✅ TRADE SUCCESS!\n\
                                🎯 Token: {}\n\
                                💰 Entry: ${:.8}\n\
                                ⚡ Priority Fee: {} lamports\n\
                                ⏱️ Total Time: {:.2}ms\n\
                                📝 TX: {}\n\
                                🌐 RPC: {}",
                                token,
                                price,
                                current_fee,
                                execution_time.as_secs_f64() * 1000.0,
                                signature,
                                if use_fallback { "Fallback" } else { "Primary" }
                            );

                            // Update trade metrics
                            self.update_trade_metrics(true, execution_time).await;
                            
                            // Add to active trades monitoring
                            let trade = Trade::new(price, TRADE_AMOUNT);
                            self.active_trades.insert(token.to_string(), trade);

                            return Ok(());
                        }
                        Err(e) => {
                            warn!("Transaction verification failed: {}", e);
                        }
                    }
                }
                Err(e) => {
                    warn!(
                        "Trade attempt failed on {} RPC (fee: {}): {}", 
                        if use_fallback { "fallback" } else { "primary" },
                        current_fee,
                        e
                    );
                }
            }

            if use_fallback {
                fallback_attempts += 1;
            } else {
                primary_attempts += 1;
            }

            // Quick retry on failure
            sleep(Duration::from_millis(50)).await;
        }

        Err(anyhow!("Failed to execute trade after {} attempts", primary_attempts + fallback_attempts))
    }
    async fn get_token_supply(&self, token_pubkey: &Pubkey) -> Result<u64> {
        let client = self.select_rpc_client().await;
        
        for attempt in 0..3 {
            match client.get_token_supply(token_pubkey).await {
                Ok(supply) => return Ok(supply.ui_amount.unwrap_or(0.0) as u64),
                Err(_) if attempt < 2 => {
                    sleep(Duration::from_millis(100 * (attempt + 1) as u64)).await;
                    continue;
                }
                Err(e) => return Err(anyhow!("Supply check failed: {}", e))
            }
        }
        
        Err(anyhow!("Failed to get token supply after retries"))
    }
    async fn get_pool_liquidity(&self, token_pubkey: &Pubkey) -> Result<f64> {
        let client = self.select_rpc_client().await;
        
        for attempt in 0..3 {
            match client.get_account_data(token_pubkey).await {
                Ok(data) if data.len() >= MIN_ACCOUNT_DATA_LEN => {
                    let liquidity_bytes = &data[8..16];
                    let liquidity_value = u64::from_le_bytes(
                        liquidity_bytes.try_into().unwrap_or([0; 8])
                    );
                    return Ok((liquidity_value as f64) / 1_000_000.0);
                }
                Ok(_) => return Ok(0.0), // Handle other Ok cases
                Err(_) if attempt < 2 => {
                    sleep(Duration::from_millis(100 * (attempt + 1) as u64)).await;
                    continue;
                }
                Err(e) => return Err(anyhow!("Liquidity check failed: {}", e))
            }
        }
        
        Err(anyhow!("Failed to get pool liquidity after retries"))
    }

    // Validate pool status
    async fn validate_pool_status(&self, token: &str) -> Result<bool> {
        let token_pubkey = Pubkey::from_str(token)?;
        
        let (supply, liquidity) = tokio::join!(
            self.get_token_supply(&token_pubkey),
            self.get_pool_liquidity(&token_pubkey)
        );

        match (supply, liquidity) {
            (Ok(supply), Ok(liquidity)) => {
                Ok(supply >= SUPPLY_MIN && 
                   supply <= SUPPLY_MAX && 
                   liquidity >= MIN_LIQUIDITY &&
                   liquidity <= MAX_LIQUIDITY)
            }
            _ => Ok(false)
        }
    }

    // Check if transaction should be retried
    fn should_retry_transaction(&self, error: &ClientError) -> bool {
        matches!(error,
            ClientError::RpcClientError(_) |
            ClientError::TransactionConfirmationError(_) |
            ClientError::CustomError(_)
        )
    }

    // Update performance metrics
    async fn update_performance_metrics(&self, success: bool, duration: Duration) {
        let mut metrics = self.performance_metrics.write().await;
        metrics.total_trades += 1;
        if success {
            metrics.successful_trades += 1;
        }
        
        let total_time = metrics.average_execution_time.as_nanos() as u64 * 
                        (metrics.total_trades - 1);
        metrics.average_execution_time = Duration::from_nanos(
            (total_time + duration.as_nanos() as u64) / metrics.total_trades
        );
    }

    // Display market event with formatting
    async fn display_market_event(&self, event_type: &str, message: &str) {
        let timestamp = Utc::now().format("%H:%M:%S%.3f");
        let (color, symbol) = match event_type {
            "DETECTED" => ("\x1b[36m", "🔍"),
            "SUCCESS" => ("\x1b[32m", "✅"), 
            "ERROR" => ("\x1b[31m", "❌"),
            _ => ("\x1b[37m", "ℹ️"),
        };
        
        println!(
            "{}{} [{}] {} {}\x1b[0m {}",
            color, symbol, timestamp, event_type, symbol, message
        );
    }
}

    
     what do i need to change to fix these issues?