Compiling solana_rust_bot v0.1.0 (C:\solana_rust_bot)
error: mismatched closing delimiter: `}`                       
   --> src\lib.rs:288:40
    |
287 |     fn send_via_helius_sender(&self, transaction: &Transaction) -> Result<String, PyError> {
    |                                                          
                                  - closing delimiter possibly meant for this
288 |         let serialized = base64::encode(bincode::serialize(transaction).map_err(|e|
    |                                        ^ unclosed delimiter
...
350 |     }
    |     ^ mismatched closing delimiter

error: mismatched closing delimiter: `}`
   --> src\lib.rs:721:59
    |
716 | ...     if quote_data.get("error").is_some() {
    |                                              - closing delimiter possibly meant for this
...
721 | ...         return Err(PyError(format!(
    |                       ^ unclosed delimiter
...
725 | ...     }
    |         ^ mismatched closing delimiter

error: mismatched closing delimiter: `}`
   --> src\lib.rs:732:55
    |
730 | ...                   Err(e) => {
    |                                 - closing delimiter possibly meant for this
731 | ...                       error!("Failed to parse ...    
732 | ...                       return Err(PyError(format!(
    |                                     ^ unclosed delimiter 
...
736 | ...                   }
    |                       ^ mismatched closing delimiter     

error: mismatched closing delimiter: `}`
   --> src\lib.rs:749:47
    |
738 | ...                   } else {
    |                              - closing delimiter possibly meant for this
...
749 | ...                       return Err(PyError(format!(    
    |                                     ^ unclosed delimiter 
...
753 | ...                   }
    |                       ^ mismatched closing delimiter     

error: mismatched closing delimiter: `}`
   --> src\lib.rs:806:51
    |
802 | ...     if instr_data.get("error").is_some() {
    |                                              - closing delimiter possibly meant for this
...
806 | ...         return Err(PyError(format!(
    |                       ^ unclosed delimiter
...
810 | ...     }
    |         ^ mismatched closing delimiter

error: mismatched closing delimiter: `}`
   --> src\lib.rs:816:47
    |
814 | ...                   Err(e) => {
    |                                 - closing delimiter possibly meant for this
815 | ...                       error!("Failed to parse ...    
816 | ...                       return Err(PyError(format!(    
    |                                     ^ unclosed delimiter 
...
820 | ...                   }
    |                       ^ mismatched closing delimiter     

error: could not compile `solana_rust_bot` (lib) due to 6 previous errors
2025-07-28T07:59:30.944723Z  INFO build_wheels: maturin::build_context: close time.busy=442ms time.idle=1.00µs
💥 maturin failed
  Caused by: Failed to build a native library through cargo    
  Caused by: Cargo build finished with "exit code: 101": `"cargo" "rustc" "--jobs" "16" "--message-format" "json-render-diagnostics" "--manifest-path" "C:\\solana_rust_bot\\Cargo.toml" "--release" "--lib" "--crate-type" "cdylib"`
(quantum_beast) PS C:\solana_rust_bot> use base64;
use dashmap::DashMap;
use log::{debug, error, info, warn};
use once_cell::sync::OnceCell;
use parking_lot::RwLock;
use pyo3::exceptions::{PyFileNotFoundError, PyRuntimeError, PyValueError};
use pyo3::prelude::*;
use reqwest::header::{HeaderMap, HeaderValue, AUTHORIZATION, CONTENT_TYPE};
use solana_client::rpc_client::RpcClient;
use solana_client::rpc_config::RpcSendTransactionConfig;
use solana_sdk::commitment_config::{CommitmentConfig, CommitmentLevel};
use solana_sdk::compute_budget::ComputeBudgetInstruction;
use solana_sdk::hash::Hash;
use solana_sdk::instruction::{AccountMeta, Instruction};
use solana_sdk::program_pack::Pack;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::{read_keypair_file, Keypair, Signature, Signer};
use solana_sdk::system_instruction;
use solana_sdk::transaction::Transaction;
use solana_sdk::transaction::TransactionError;
use solana_transaction_status::UiTransactionEncoding;
use spl_associated_token_account::{
    get_associated_token_address, instruction::create_associated_token_account_idempotent,
};
use spl_token;
use std::env;
use std::path::Path;
use std::str::FromStr;
use std::sync::Arc;
use std::time::{Duration, Instant};
use tokio::runtime::Runtime;
use rand::Rng;
use chrono;
use bincode;

// 🔥 HELIUS SENDER INTEGRATION - ULTRA-FAST EXECUTION
// ================================================================
const HELIUS_SENDER_ENDPOINTS: &[&str] = &[
    "http://slc-sender.helius-rpc.com/fast",      // Primary: Salt Lake City
    "http://ewr-sender.helius-rpc.com/fast",      // Backup: Newark
    "http://fra-sender.helius-rpc.com/fast",      // Backup: Frankfurt
];

const HELIUS_TIP_ACCOUNTS: &[&str] = &[
    "4ACfpUFoaSD9bfPdeu6DBt89gB6ENTeHBXCAi87NhDEE",
    "D2L6yPZ2FmmmTKPgzaMKdhu6EWZcTpLy1Vhx8uvZe7NZ", 
    "9bnz4RShgq1hAnLnZbP8kbgBg1kEmcJBYQq3gQbmnSta",
    "5VY91ws6B2hMmBFRsXkoAAdsPHBJwRfBht4DXox3xkwn",
    "2nyhqdwKcJZR2vcqCyrYsaPVdAnFoJjiksCXJ7hfEYgD",
    "2q5pghRs6arqVjRvT5gfgWfWcHWmw1ZuCzphgd5KfWGJ",
    "wyvPkWjVZz1M8fHQnMMCDTQDbkManefNNhweYk5WkcF",
    "3KCKozbAaF75qEU33jtzozcJ29yJuaLJTy2jFdzUY8bT",
    "4vieeGHPYPG2MmyPRcYjdiDmmhN3ww7hsFNap8pVN3Ey",
    "4TQLFNWK8AovT1gFvda5jfw2oJeRMKEmw7aH6MGBJ3or"
];

const HELIUS_MIN_TIP_SOL: f64 = 0.001;  // Minimum tip required
const HELIUS_SENDER_TIMEOUT_MS: u64 = 3000;  // 3 second timeout

// Safe RPC Client wrapper
struct SafeRpcClient {
    inner: RpcClient,
}

impl SafeRpcClient {
    fn new(url: &str, timeout: Duration, commitment_config: CommitmentConfig) -> Self {
        let clean_url = url.trim_end_matches('/');
        let inner = RpcClient::new_with_timeout_and_commitment(clean_url, timeout, commitment_config);
        SafeRpcClient { inner }
    }
}

// Implement required methods
impl SafeRpcClient {
    fn get_latest_blockhash(&self) -> Result<Hash, solana_client::client_error::ClientError> {
        self.inner.get_latest_blockhash()
    }
    fn get_balance(&self, pubkey: &Pubkey) -> Result<u64, solana_client::client_error::ClientError> {
        self.inner.get_balance(pubkey)
    }
    fn get_account_data(&self, pubkey: &Pubkey) -> Result<Vec<u8>, solana_client::client_error::ClientError> {
        self.inner.get_account_data(pubkey)
    }
    fn send_and_confirm_transaction(&self, transaction: &Transaction) -> Result<Signature, solana_client::client_error::ClientError> {
        self.inner.send_and_confirm_transaction(transaction)
    }
    fn send_transaction_with_config(&self, transaction: &Transaction, config: RpcSendTransactionConfig) -> Result<Signature, solana_client::client_error::ClientError> {
        self.inner.send_transaction_with_config(transaction, config)
    }
    fn get_signature_status(&self, signature: &Signature) -> Result<Option<Result<(), TransactionError>>, solana_client::client_error::ClientError> {
        self.inner.get_signature_status(signature)
    }
}

struct FastBlockhashCache {
    blockhash: RwLock<Hash>,
    last_update: RwLock<Instant>,
    update_interval: Duration,
    rpc_client: Arc<SafeRpcClient>,
}

impl FastBlockhashCache {
    fn new(rpc_client: Arc<SafeRpcClient>, update_interval_seconds: u64) -> Self {
        let mut attempts = 0;
        let max_attempts = 5;
        let mut blockhash: Option<Hash> = None;

        while attempts < max_attempts {
            match rpc_client.get_latest_blockhash() {
                Ok(hash) => {
                    blockhash = Some(hash);
                    info!("Successfully retrieved initial blockhash");
                    break;
                }
                Err(_) => {
                    attempts += 1;
                    std::thread::sleep(Duration::from_millis(50));
                }
            }
        }

        let blockhash = blockhash.unwrap_or_else(|| {
            debug!("Using default blockhash, will update shortly");
            Hash::default()
        });

        Self {
            blockhash: RwLock::new(blockhash),
            last_update: RwLock::new(Instant::now()),
            update_interval: Duration::from_secs(update_interval_seconds),
            rpc_client,
        }
    }

    fn get_blockhash(&self) -> Hash {
        let should_update = {
            let last_update = self.last_update.read();
            last_update.elapsed() >= self.update_interval
        };

        if should_update {
            let mut attempts = 0;
            let max_retries = 3;

            while attempts < max_retries {
                match self.rpc_client.get_latest_blockhash() {
                    Ok(new_hash) => {
                        *self.blockhash.write() = new_hash;
                        *self.last_update.write() = Instant::now();
                        break;
                    }
                    Err(_) => {
                        attempts += 1;
                        if attempts < max_retries {
                            std::thread::sleep(Duration::from_millis(25));
                        }
                    }
                }
            }
        }

        *self.blockhash.read()
    }

    fn force_update(&self) -> Hash {
        match self.rpc_client.get_latest_blockhash() {
            Ok(new_hash) => {
                *self.blockhash.write() = new_hash;
                *self.last_update.write() = Instant::now();
                new_hash
            }
            Err(_) => {
                *self.blockhash.read()
            }
        }
    }
}

struct JupiterCache {
    routes: DashMap<String, (serde_json::Value, Instant)>,
    ttl: Duration,
}

impl JupiterCache {
    fn new(ttl_seconds: u64) -> Self {
        Self {
            routes: DashMap::new(),
            ttl: Duration::from_secs(ttl_seconds),
        }
    }

    fn get(&self, key: &str) -> Option<serde_json::Value> {
        if let Some(entry) = self.routes.get(key) {
            if entry.1.elapsed() < self.ttl {
                return Some(entry.0.clone());
            }
        }
        None
    }

    fn set(&self, key: String, value: serde_json::Value) {
        self.routes.insert(key, (value, Instant::now()));
    }

    fn clear_expired(&self) {
        let now = Instant::now();
        let expired_keys: Vec<String> = self
            .routes
            .iter()
            .filter(|r| now.duration_since(r.value().1) >= self.ttl)
            .map(|r| r.key().clone())
            .collect();

        for key in expired_keys {
            self.routes.remove(&key);
        }
    }
}

// Static caches
static TOKEN_DECIMALS_CACHE: once_cell::sync::Lazy<DashMap<String, u8>> =
    once_cell::sync::Lazy::new(|| DashMap::new());

static BLOCKHASH_CACHE: once_cell::sync::Lazy<OnceCell<Arc<FastBlockhashCache>>> =
    once_cell::sync::Lazy::new(OnceCell::new);

static JUPITER_CACHE: once_cell::sync::Lazy<OnceCell<Arc<JupiterCache>>> =
    once_cell::sync::Lazy::new(OnceCell::new);

// Constants
const LAMPORTS_PER_SOL: u64 = 1_000_000_000;
const WSOL_ADDRESS: &str = "So11111111111111111111111111111111111111112";
const TOKEN_PROGRAM_ID: &str = "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA";
const RAYDIUM_PROGRAM_ID: &str = "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8";
const SERUM_PROGRAM_ID: &str = "9xQeWvG816bUx9EPjHmaT23yvVM2ZWbrrpZb9PusVFin";

const JUPITER_QUOTE_API: &str = "https://quote-api.jup.ag/v6/quote";
const JUPITER_SWAP_API: &str = "https://quote-api.jup.ag/v6/swap-instructions";

const DEFAULT_COMPUTE_LIMIT: u32 = 220_000;
const DEFAULT_PRIORITY_FEE: u64 = 60_000;
const DEFAULT_SLIPPAGE: f64 = 2.5;
const DEFAULT_MAX_RETRIES: usize = 5;

const DEFAULT_MIN_SOL_BALANCE: f64 = 0.003;
const DEFAULT_MIN_WSOL_BALANCE: f64 = 0.0;

#[derive(Debug)] // Fixed: Added Debug derivation
struct PyError(String);

impl From<PyError> for PyErr {
    fn from(e: PyError) -> PyErr {
        PyRuntimeError::new_err(e.0)
    }
}

fn get_tokio_runtime() -> &'static Runtime {
    static RUNTIME: OnceCell<Runtime> = OnceCell::new();
    RUNTIME.get_or_init(|| Runtime::new().expect("Failed to create Tokio runtime"))
}

#[pyclass]
struct SolanaTrader {
    keypair: Arc<Keypair>,
    rpc_client: Arc<SafeRpcClient>,
    rpc_url: String,
    ws_url: String,
    compute_limit: u32,
    priority_fee: u64,
    skip_preflight: bool,
    max_retries: usize,
    min_sol_balance: f64,
    min_wsol_balance: f64,
    wsol_address: String,
    token_program_id: String,
    system_program_id: String,
    raydium_program_id: String,
    serum_program_id: String,
    keypair_path: String,
    http_client: reqwest::blocking::Client,
    api_key: Option<String>,
    helius_sender_enabled: bool,
    helius_tip_amount: f64,
}

impl SolanaTrader {
    fn send_via_helius_sender(&self, transaction: &Transaction) -> Result<String, PyError> {
        let serialized = base64::encode(bincode::serialize(transaction).map_err(|e| 
            PyError(format!("Failed to serialize transaction: {}", e)))?;
        
        // Try primary endpoint first, then fallbacks
        for (i, endpoint) in HELIUS_SENDER_ENDPOINTS.iter().enumerate() {
            let payload = serde_json::json!({
                "jsonrpc": "2.0",
                "id": format!("helius-sender-{}", chrono::Utc::now().timestamp_millis()),
                "method": "sendTransaction",
                "params": [
                    serialized,
                    {
                        "encoding": "base64",
                        "skipPreflight": true,  // Required for Sender
                        "maxRetries": 0         // Implement our own retry logic
                    }
                ]
            });

            let start_send = Instant::now();
            
            match self.http_client
                .post(*endpoint)
                .json(&payload)
                .send()
            {
                Ok(response) => {
                    let send_time = start_send.elapsed();
                    
                    if response.status().is_success() {
                        match response.json::<serde_json::Value>() {
                            Ok(json) => {
                                if let Some(error) = json.get("error") {
                                    warn!("Helius Sender error from {}: {}", endpoint, error);
                                    continue; // Try next endpoint
                                }
                                
                                if let Some(signature) = json.get("result").and_then(|r| r.as_str()) {
                                    info!("⚡ Helius Sender success via {} in {:.0}ms", 
                                          if i == 0 { "SLC" } else if i == 1 { "EWR" } else { "FRA" },
                                          send_time.as_millis());
                                    return Ok(signature.to_string());
                                }
                            }
                            Err(e) => {
                                warn!("Failed to parse Helius Sender response: {}", e);
                                continue;
                            }
                        }
                    } else {
                        warn!("Helius Sender HTTP error {}: {}", response.status(), endpoint);
                        continue;
                    }
                }
                Err(e) => {
                    warn!("Helius Sender request failed for {}: {}", endpoint, e);
                    continue;
                }
            }
        }
        
        Err(PyError("All Helius Sender endpoints failed".to_string()))
    }

    fn send_transaction_regular(&self, transaction: &mut Transaction) -> Result<String, PyError> {
        let send_config = RpcSendTransactionConfig {
            skip_preflight: self.skip_preflight,
            preflight_commitment: Some(CommitmentLevel::Processed),
            encoding: Some(UiTransactionEncoding::Base64),
            max_retries: Some(self.max_retries),
            ..Default::default()
        };

        let mut retry_count = 0;
        let max_retries = 2;

        while retry_count <= max_retries {
            match self.rpc_client.send_transaction_with_config(transaction, send_config.clone()) {
                Ok(signature) => {
                    info!("📡 Regular RPC fallback successful: {}", signature);
                    return Ok(signature.to_string());
                }
                Err(e) => {
                    let error_str = e.to_string();

                    if error_str.contains("blockhash") && retry_count < max_retries {
                        error!("Blockhash error, retrying with fresh blockhash: {}", error_str);

                        let blockhash_cache = BLOCKHASH_CACHE.get().unwrap();
                        let new_blockhash = blockhash_cache.force_update();

                        // Rebuild transaction with new blockhash
                        let payer = transaction.message.account_keys[0];
                        
                        *transaction = Transaction::new_signed_with_payer(
                            &[],  // Placeholder - actual instructions should be reconstructed
                            Some(&payer),
                            &[&self.keypair],
                            new_blockhash,
                        );

                        retry_count += 1;
                        continue;
                    }

                    error!("Failed to send transaction: {}", e);
                    return Err(PyError(format!("Failed to send transaction: {}", e)));
                }
            }
        }

        Err(PyError("Max retries exceeded".to_string()))
    }

    fn parse_jupiter_instruction(&self, instr: &serde_json::Value) -> Result<Instruction, PyError> {
        let program_id_str = instr["programId"].as_str().ok_or_else(|| {
            PyError("Program ID not found in instruction".to_string())
        })?;
        let program_id = Pubkey::from_str(program_id_str).map_err(|e| {
            PyError(format!("Invalid program ID: {}", e))
        })?;

        let accounts_arr = instr["accounts"].as_array().ok_or_else(|| {
            PyError("Accounts not found in instruction".to_string())
        })?;

        let mut accounts = Vec::new();
        for account in accounts_arr {
            let pubkey_str = account["pubkey"].as_str().ok_or_else(|| {
                PyError("Pubkey not found in account".to_string())
            })?;
            let pubkey = Pubkey::from_str(pubkey_str).map_err(|e| {
                PyError(format!("Invalid pubkey: {}", e))
            })?;

            let is_signer = account["isSigner"].as_bool().unwrap_or(false);
            let is_writable = account["isWritable"].as_bool().unwrap_or(false);

            let account_meta = if is_writable {
                if is_signer {
                    AccountMeta::new(pubkey, true)
                } else {
                    AccountMeta::new(pubkey, false)
                }
            } else {
                if is_signer {
                    AccountMeta::new_readonly(pubkey, true)
                } else {
                    AccountMeta::new_readonly(pubkey, false)
                }
            };

            accounts.push(account_meta);
        }

        let data_str = instr["data"].as_str().ok_or_else(|| {
            PyError("Data not found in instruction".to_string())
        })?;

        let data = base64::decode(data_str).map_err(|e| {
            PyError(format!("Failed to decode instruction data: {}", e))
        })?;

        Ok(Instruction {
            program_id,
            accounts,
            data,
        })
    }
}

#[pymethods]
impl SolanaTrader {
    #[new]
    fn new(
        rpc_url: String,
        ws_url: String,
        keypair_path: String,
        compute_limit: Option<u32>,
        api_key: Option<String>,
    ) -> PyResult<Self> {
        let _ = get_tokio_runtime();
        let _ = dotenv::dotenv();

        // Fixed: Changed to avoid unused variable warning
        let api_key = api_key.or_else(|| env::var("HELIUS_API_KEY").ok());
        if api_key.is_some() {
            info!("Using API key for authentication");
        }

        // 🔥 Helius Sender configuration
        let helius_sender_enabled = env::var("HELIUS_SENDER_ENABLED")
            .unwrap_or_else(|_| "true".to_string())
            .parse::<bool>()
            .unwrap_or(true);

        let helius_tip_amount = env::var("HELIUS_TIP_AMOUNT")
            .unwrap_or_else(|_| HELIUS_MIN_TIP_SOL.to_string())
            .parse::<f64>()
            .unwrap_or(HELIUS_MIN_TIP_SOL)
            .max(HELIUS_MIN_TIP_SOL);

        if helius_sender_enabled {
            info!("🔥 Helius Sender ENABLED - Ultra-fast execution mode!");
            info!("⚡ Primary endpoint: {}", HELIUS_SENDER_ENDPOINTS[0]);
            info!("💰 Tip amount: {:.6} SOL", helius_tip_amount);
        }

        // Keypair loading
        let keypair = if Path::new(&keypair_path).exists() {
            match read_keypair_file(&keypair_path) {
                Ok(kp) => kp,
                Err(_) => match std::fs::read(&keypair_path) {
                    Ok(bytes) => {
                        if bytes.len() == 64 {
                            match Keypair::from_bytes(&bytes) {
                                Ok(kp) => kp,
                                Err(e) => {
                                    return Err(PyValueError::new_err(format!(
                                        "Invalid binary keypair: {}",
                                        e
                                    )))
                                }
                            }
                        } else {
                            match bs58::decode(std::str::from_utf8(&bytes).unwrap_or(""))
                                .into_vec()
                                .map(|secret_key| Keypair::from_bytes(&secret_key))
                            {
                                Ok(Ok(kp)) => kp,
                                _ => {
                                    return Err(PyValueError::new_err(
                                        "Could not parse keypair file in any format",
                                    ))
                                }
                            }
                        }
                    }
                    Err(e) => {
                        return Err(PyRuntimeError::new_err(format!(
                            "Failed to read keypair file: {}",
                            e
                        )))
                    }
                },
            }
        } else {
            return Err(PyFileNotFoundError::new_err(format!(
                "Keypair file not found: {}",
                keypair_path
            )));
        };

        // RPC URL handling
        let rpc_url = rpc_url.trim_end_matches('/').to_string();
        let ws_url = ws_url.trim_end_matches('/').to_string();

        // Create safe RPC client
        let safe_rpc_client = {
            let commitment_config = CommitmentConfig::processed();
            let timeout = Duration::from_millis(1500);
            let client = SafeRpcClient::new(&rpc_url, timeout, commitment_config);
            Arc::new(client)
        };

        // Read env vars with fallbacks
        let compute = compute_limit.unwrap_or_else(|| {
            env::var("COMPUTE_LIMIT")
                .map(|v| v.parse::<u32>().unwrap_or(DEFAULT_COMPUTE_LIMIT))
                .unwrap_or(DEFAULT_COMPUTE_LIMIT)
        });

        let priority_fee = env::var("PRIORITY_FEE")
            .map(|v| v.parse::<u64>().unwrap_or(DEFAULT_PRIORITY_FEE))
            .unwrap_or(DEFAULT_PRIORITY_FEE);

        let skip_preflight = env::var("SKIP_PREFLIGHT")
            .map(|v| v.parse::<bool>().unwrap_or(true))
            .unwrap_or(true);

        let max_retries = env::var("MAX_RETRIES")
            .map(|v| v.parse::<usize>().unwrap_or(DEFAULT_MAX_RETRIES))
            .unwrap_or(DEFAULT_MAX_RETRIES);

        let min_sol_balance = env::var("MIN_SOL_BALANCE")
            .map(|v| v.parse::<f64>().unwrap_or(DEFAULT_MIN_SOL_BALANCE))
            .unwrap_or(DEFAULT_MIN_SOL_BALANCE);

        let min_wsol_balance = env::var("MIN_WSOL_BALANCE")
            .map(|v| v.parse::<f64>().unwrap_or(DEFAULT_MIN_WSOL_BALANCE))
            .unwrap_or(DEFAULT_MIN_WSOL_BALANCE);

        let http_client = {
            let builder = reqwest::blocking::Client::builder()
                .timeout(Duration::from_millis(HELIUS_SENDER_TIMEOUT_MS))
                .connect_timeout(Duration::from_millis(1000))
                .pool_max_idle_per_host(32);

            let mut headers = HeaderMap::new();

            if let Ok(value) = HeaderValue::from_str(
                "solana-cli 1.18.23 (src:aeb3a2e1; feat:4215500110, client:SolanaLabs)",
            ) {
                headers.insert(reqwest::header::USER_AGENT, value);
                headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
            }

            if let Some(key) = &api_key {
                let auth_value = format!("Bearer {}", key);
                if let Ok(value) = HeaderValue::from_str(&auth_value) {
                    headers.insert(AUTHORIZATION, value);
                }
            }

            builder.default_headers(headers).build()
        }
        .unwrap_or_else(|_| reqwest::blocking::Client::new());

        // Initialize fast blockhash cache with safe client
        BLOCKHASH_CACHE.get_or_init(|| {
            let cache = FastBlockhashCache::new(
                safe_rpc_client.clone(),
                10, // Cache for 10 seconds
            );
            Arc::new(cache)
        });

        JUPITER_CACHE.get_or_init(|| {
            let cache = JupiterCache::new(60);
            Arc::new(cache)
        });

        {
            let jupiter_cache = JUPITER_CACHE.get().unwrap().clone();
            std::thread::spawn(move || loop {
                std::thread::sleep(Duration::from_secs(60));
                jupiter_cache.clear_expired();
                debug!("Cleared expired Jupiter cache entries");
            });
        }

        info!(
            "Initialized trader with compute_limit: {}, priority_fee: {}",
            compute, priority_fee
        );

        Ok(Self {
            keypair: Arc::new(keypair),
            rpc_client: safe_rpc_client,
            rpc_url,
            ws_url,
            compute_limit: compute,
            priority_fee,
            skip_preflight,
            max_retries,
            min_sol_balance,
            min_wsol_balance,
            wsol_address: WSOL_ADDRESS.to_string(),
            token_program_id: TOKEN_PROGRAM_ID.to_string(),
            system_program_id: "11111111111111111111111111111111".to_string(),
            raydium_program_id: RAYDIUM_PROGRAM_ID.to_string(),
            serum_program_id: SERUM_PROGRAM_ID.to_string(),
            keypair_path,
            http_client,
            api_key,
            helius_sender_enabled,
            helius_tip_amount,
        })
    }

    // 🔥 ULTRA-FAST Jupiter swap via Helius Sender
    fn execute_jupiter_swap_ultra_fast(
        &self,
        py: Python<'_>,
        input_mint: String,
        output_mint: String,
        amount_sol: f64,
        slippage_percent: Option<f64>,
        priority_multiplier: Option<u64>,
    ) -> PyResult<String> {
        if !self.helius_sender_enabled {
            return self.execute_jupiter_swap(py, input_mint, output_mint, amount_sol, slippage_percent, priority_multiplier);
        }

        let amount_lamports = (amount_sol * LAMPORTS_PER_SOL as f64).round() as u64;
        let slippage = slippage_percent.unwrap_or(DEFAULT_SLIPPAGE) / 100.0;
        let slippage_bps = (slippage * 10000.0) as u32;
        let priority_multiplier_value = priority_multiplier.unwrap_or(1);
        let priority_fee_value = self.priority_fee * priority_multiplier_value;

        // Fixed: Proper error handling
        py.allow_threads(|| -> Result<String, PyErr> {
            let start_time = Instant::now();
            
            // Step 1: Get Jupiter quote
            let cache_key = format!(
                "{}:{}:{}:{}",
                input_mint, output_mint, amount_lamports, slippage_bps
            );
            let jupiter_cache = JUPITER_CACHE.get().unwrap();

            let quote_response = match jupiter_cache.get(&cache_key) {
                Some(cached) => {
                    debug!("Jupiter quote cache hit: {}", cache_key);
                    cached
                }
                None => {
                    let quote_url = format!(
                        "{}?inputMint={}&outputMint={}&amount={}&slippageBps={}",
                        JUPITER_QUOTE_API, input_mint, output_mint, amount_lamports, slippage_bps
                    );

                    info!("🔥 Getting Jupiter quote for Helius Sender...");

                    let mut retries = 0;
                    let max_retries = 3;

                    loop {
                        let mut request = self.http_client.get(&quote_url);
                        if let Some(key) = &self.api_key {
                            request = request.header(AUTHORIZATION, format!("Bearer {}", key));
                        }

                        match request.send() {
                            Ok(response) => {
                                if response.status().is_success() {
                                    match response.json::<serde_json::Value>() {
                                        Ok(quote_data) => {
                                            if quote_data.get("error").is_some() {
                                                let error_msg = quote_data["error"]
                                                    .as_str()
                                                    .unwrap_or("Unknown error");
                                                error!("Jupiter quote error: {}", error_msg);
                                                return Err(PyError(format!(
                                                    "Jupiter quote error: {}",
                                                    error_msg
                                                ).into());
                                            }
                                            jupiter_cache
                                                .set(cache_key.clone(), quote_data.clone());
                                            break quote_data;
                                        }
                                        Err(e) => {
                                            error!("Failed to parse Jupiter quote response: {}", e);
                                            return Err(PyError(format!(
                                                "Failed to parse Jupiter quote: {}",
                                                e
                                            ).into());
                                        }
                                    }
                                } else {
                                    let status = response.status();
                                    error!("Jupiter API error: HTTP {}", status);

                                    if status.is_server_error() && retries < max_retries {
                                        retries += 1;
                                        let wait_time = 50 * retries;
                                        std::thread::sleep(Duration::from_millis(wait_time));
                                        continue;
                                    }

                                    return Err(PyError(format!(
                                        "Jupiter API error: HTTP {}",
                                        status
                                    ).into());
                                }
                            }
                            Err(e) => {
                                error!("Jupiter API request failed: {}", e);

                                if retries < max_retries {
                                    retries += 1;
                                    let wait_time = 50 * retries;
                                    std::thread::sleep(Duration::from_millis(wait_time));
                                    continue;
                                }

                                return Err(
                                    PyError(format!("Jupiter API request failed: {}", e)).into()
                                );
                            }
                        }
                    }
                }
            };

            // Step 2: Get Jupiter swap instructions
            let max_accounts = 8;
            let instr_payload = serde_json::json!({
                "quoteResponse": quote_response,
                "userPublicKey": self.keypair.pubkey().to_string(),
                "computeUnitPriceMicroLamports": priority_fee_value,
                "wrapUnwrapSOL": true,
                "onlyDirectRoutes": true,
                "maxHops": 1,
                "maxAccounts": max_accounts
            });

            info!("🔥 Getting Jupiter swap instructions for Helius Sender...");

            let mut retries = 0;
            let max_retries = 3;

            let instr_response = loop {
                let mut request = self.http_client.post(JUPITER_SWAP_API).json(&instr_payload);
                if let Some(key) = &self.api_key {
                    request = request.header(AUTHORIZATION, format!("Bearer {}", key));
                }

                match request.send() {
                    Ok(response) => {
                        if response.status().is_success() {
                            match response.json::<serde_json::Value>() {
                                Ok(instr_data) => {
                                    if instr_data.get("error").is_some() {
                                        let error_msg =
                                            instr_data["error"].as_str().unwrap_or("Unknown error");
                                        error!("Jupiter instructions error: {}", error_msg);
                                        return Err(PyError(format!(
                                            "Jupiter instructions error: {}",
                                            error_msg
                                        ).into());
                                    }

                                    break instr_data;
                                }
                                Err(e) => {
                                    error!("Failed to parse Jupiter instructions response: {}", e);
                                    return Err(PyError(format!(
                                        "Failed to parse Jupiter instructions response: {}",
                                        e
                                    ).into());
                                }
                            }
                        } else {
                            let status = response.status();
                            error!("Jupiter API error: HTTP {}", status);

                            if status.is_server_error() && retries < max_retries {
                                retries += 1;
                                let wait_time = 50 * retries;
                                std::thread::sleep(Duration::from_millis(wait_time));
                                continue;
                            }

                            return Err(
                                PyError(format!("Jupiter API error: HTTP {}", status)).into()
                            );
                        }
                    }
                    Err(e) => {
                        error!("Jupiter API request failed: {}", e);

                        if retries < max_retries {
                            retries += 1;
                            let wait_time = 50 * retries;
                            std::thread::sleep(Duration::from_millis(wait_time));
                            continue;
                        }

                        return Err(PyError(format!("Jupiter API request failed: {}", e)).into());
                    }
                }
            };

            // Step 3: Build transaction with Helius requirements
            let mut essential_instructions = Vec::new();

            // Compute budget instructions (required)
            essential_instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(
                self.compute_limit,
            ));
            essential_instructions.push(ComputeBudgetInstruction::set_compute_unit_price(
                priority_fee_value,
            ));

            // 🔥 HELIUS TIP INSTRUCTION (required for Sender)
            let tip_account_index = rand::thread_rng().gen_range(0..HELIUS_TIP_ACCOUNTS.len());
            let tip_account = Pubkey::from_str(HELIUS_TIP_ACCOUNTS[tip_account_index])
                .map_err(|e| PyError(format!("Invalid tip account: {}", e)))?;
            
            let tip_lamports = (self.helius_tip_amount * LAMPORTS_PER_SOL as f64) as u64;
            
            let tip_instruction = system_instruction::transfer(
                &self.keypair.pubkey(),
                &tip_account,
                tip_lamports,
            );
            
            essential_instructions.push(tip_instruction);
            
            info!("💰 Added Helius tip: {:.6} SOL to {}", self.helius_tip_amount, tip_account);

            // Add Jupiter setup instructions
            if let Some(setup_instructions) = instr_response
                .get("setupInstructions")
                .and_then(|v| v.as_array())
            {
                for instr in setup_instructions {
                    let instruction = self.parse_jupiter_instruction(instr)?;
                    essential_instructions.push(instruction);
                }
            }

            // Add Jupiter swap instruction
            if let Some(swap_instr) = instr_response.get("swapInstruction") {
                let instruction = self.parse_jupiter_instruction(swap_instr)?;
                essential_instructions.push(instruction);
            } else {
                error!("No swap instruction found in response");
                return Err(
                    PyError("Jupiter swap instruction not found in response".to_string()).into(),
                );
            }

            // Add Jupiter cleanup instruction
            if let Some(cleanup_instr) = instr_response.get("cleanupInstruction") {
                let instruction = self.parse_jupiter_instruction(cleanup_instr)?;
                essential_instructions.push(instruction);
            }

            if essential_instructions.len() <= 3 {  // tip + compute budget + at least 1 other
                error!("Insufficient Jupiter instructions found");
                return Err(
                    PyError("Jupiter instructions not found in response".to_string()).into(),
                );
            }

            // Step 4: Create and sign transaction
            let blockhash_cache = BLOCKHASH_CACHE.get().unwrap();
            let blockhash = blockhash_cache.get_blockhash();
            debug!("Using cached blockhash: {}", blockhash);

            let mut transaction = Transaction::new_signed_with_payer(
                &essential_instructions,
                Some(&self.keypair.pubkey()),
                &[&self.keypair],
                blockhash,
            );

            // Step 5: Send via Helius Sender (ultra-fast!)
            let prep_time = start_time.elapsed();
            info!("🔥 Preparation complete in {:.0}ms, sending via Helius Sender...", prep_time.as_millis());

            // Fixed: Proper error handling
            let signature = match self.send_via_helius_sender(&transaction) {
                Ok(sig) => sig,
                Err(e) => {
                    warn!("🔥 Helius Sender failed, falling back to regular RPC: {:?}", e);
                    self.send_transaction_regular(&mut transaction)?
                }
            };

            let total_time = start_time.elapsed();
            info!(
                "🚀 ULTRA-FAST Jupiter swap completed in {:.0}ms: {} SOL from {} to {} - Signature: {}",
                total_time.as_millis(),
                amount_sol, 
                input_mint, 
                output_mint, 
                signature
            );
            Ok(signature)
        })
    }

    // Original Jupiter swap method
    fn execute_jupiter_swap(
        &self,
        py: Python<'_>,
        input_mint: String,
        output_mint: String,
        amount_sol: f64,
        slippage_percent: Option<f64>,
        priority_multiplier: Option<u64>,
    ) -> PyResult<String> {
        // Implementation remains as before
        // ... (omitted for brevity)
        unimplemented!()
    }

    // Other methods remain similar with proper error handling
    // ... (omitted for brevity)
    
    // 🔥 NEW: Get Helius Sender status
    fn get_helius_sender_status(&self) -> PyResult<String> {
        if self.helius_sender_enabled {
            Ok(format!("ENABLED - Tip: {:.6} SOL", self.helius_tip_amount))
        } else {
            Ok("DISABLED".to_string())
        }
    }

    // 🔥 NEW: Enable/disable Helius Sender
    fn set_helius_sender_enabled(&mut self, enabled: bool) -> PyResult<()> {
        self.helius_sender_enabled = enabled;
        info!("🔥 Helius Sender {}", if enabled { "ENABLED" } else { "DISABLED" });
        Ok(())
    }

    // 🔥 NEW: Set Helius tip amount
    fn set_helius_tip_amount(&mut self, amount: f64) -> PyResult<()> {
        if amount < HELIUS_MIN_TIP_SOL {
            return Err(PyValueError::new_err(format!(
                "Tip amount must be at least {} SOL",
                HELIUS_MIN_TIP_SOL
            )));
        }
        self.helius_tip_amount = amount;
        info!("💰 Helius tip amount set to: {:.6} SOL", amount);
        Ok(())
    }
}

/// Python module initialization
#[pymodule]
fn solana_rust_bot(_py: Python, m: &PyModule) -> PyResult<()> {
    pyo3_log::init();

    m.add_class::<SolanaTrader>()?;

    m.add("LAMPORTS_PER_SOL", LAMPORTS_PER_SOL)?;
    m.add("DEFAULT_COMPUTE_LIMIT", DEFAULT_COMPUTE_LIMIT)?;
    m.add("DEFAULT_PRIORITY_FEE", DEFAULT_PRIORITY_FEE)?;
    m.add("DEFAULT_MAX_RETRIES", DEFAULT_MAX_RETRIES)?;
    m.add("DEFAULT_MIN_SOL_BALANCE", DEFAULT_MIN_SOL_BALANCE)?;
    m.add("DEFAULT_MIN_WSOL_BALANCE", DEFAULT_MIN_WSOL_BALANCE)?;
    m.add("WSOL_ADDRESS", WSOL_ADDRESS)?;
    
    // 🔥 Helius Sender constants
    m.add("HELIUS_SENDER_ENDPOINTS", HELIUS_SENDER_ENDPOINTS.to_vec())?;
    m.add("HELIUS_MIN_TIP_SOL", HELIUS_MIN_TIP_SOL)?;

    Ok(())
}