write the fully working code do not remove my funcitons or alter code if it doesnt need to be please ....   THIS IS LIB.RS use {
    anyhow::{anyhow, Result},
    base64::{engine::general_purpose::STANDARD as BASE64, Engine},
    chrono::Utc,
    dashmap::DashMap,
    log::{error, info},
    reqwest::Client,
    serde::{Deserialize, Serialize},
    serde_json::{json, Value},
    solana_client::nonblocking::rpc_client::RpcClient,
    solana_sdk::{
        commitment_config::CommitmentConfig,
        compute_budget::ComputeBudgetInstruction,
        instruction::Instruction,
        message::Message,
        pubkey::Pubkey,
        signature::{Keypair, Signer},
        transaction::Transaction,
    },
    std::{str::FromStr, time::Instant},
    tokio::time::{sleep, Duration},
};

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

// Timing and trading parameters
const INITIAL_VALIDATION_DELAY: u64 = 800;
const TRADE_AMOUNT: u64 = 10_000_000; // 0.01 SOL
const TAKE_PROFIT: f64 = 20.0; // 20%
const STOP_LOSS: f64 = -5.0; // 5%
const MIN_LIQUIDITY: f64 = 1000.0; // $1,000
const MAX_LIQUIDITY: f64 = 20000.0; // $20,000
const PRIORITY_FEE: u64 = 1_000_000; // 0.001 SOL
const COMPUTE_UNITS: u32 = 200_000;

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

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

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

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

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

impl Bot {
    pub fn new(keypair: Keypair) -> Self {
        info!("🚀 Initializing trading bot");

        let http_client = Client::builder()
            .timeout(Duration::from_secs(5))
            .pool_idle_timeout(Duration::from_secs(30))
            .pool_max_idle_per_host(32)
            .build()
            .expect("Failed to build HTTP client");

        Self {
            keypair,
            http_client,
            active_trades: DashMap::new(),
            rpc_client: RpcClient::new_with_commitment(
                HELIUS_RPC.to_string(),
                CommitmentConfig::confirmed(),
            ),
        }
    }

    pub async fn execute_trade(&self, token: &str, is_buy: bool) -> Result<String> {
        let start = Instant::now();
        let operation = if is_buy { "BUY" } else { "SELL" };

        info!("🎯 Executing {} for {}", operation, token);

        // Pre-trade validation for buys
        if is_buy {
            sleep(Duration::from_millis(INITIAL_VALIDATION_DELAY)).await;
            if !self.validate_pool_requirements(token).await? {
                return Err(anyhow!("Pool validation failed"));
            }
        }

        // Get quote and build transaction
        let quote = self.get_jupiter_quote(token, is_buy).await?;
        let blockhash = self.rpc_client.get_latest_blockhash().await?;

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

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

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

        match self.rpc_client.send_and_confirm_transaction(&tx).await {
            Ok(signature) => {
                info!(
                    "✅ {} executed in {:.2}ms ({})",
                    operation,
                    start.elapsed().as_millis(),
                    signature
                );

                if is_buy {
                    let price = self.get_token_price(token).await?;
                    let trade = Trade::new(price, TRADE_AMOUNT);
                    self.active_trades.insert(token.to_string(), trade);
                } else {
                    self.active_trades.remove(token);
                }

                Ok(signature.to_string())
            }
            Err(e) => {
                error!("❌ {} failed: {}", operation, e);
                Err(anyhow!(e))
            }
        }
    }

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

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

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

        Ok(response)
    }

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

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

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

        let decoded_data = BASE64.decode(swap_data)?;

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

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

        let account = self.rpc_client.get_account(&token_pubkey).await?;
        if account.data.len() < 8 {
            return Ok(false);
        }

        // Check liquidity
        let liquidity = if account.data.len() >= 16 {
            let liquidity_bytes = &account.data[8..16];
            u64::from_le_bytes(liquidity_bytes.try_into()?) as f64 / 1e6
        } else {
            0.0
        };

        // Check supply
        let supply = self.rpc_client.get_token_supply(&token_pubkey).await?;
        let supply_amount = supply.ui_amount.unwrap_or(0.0) as u64;

        // Validate requirements
        let valid = (MIN_LIQUIDITY..=MAX_LIQUIDITY).contains(&liquidity)
            && (1_000_000..=1_000_000_000_000).contains(&supply_amount);

        if valid {
            info!(
                "✅ Pool validated - Supply: {}, Liquidity: ${:.2}",
                supply_amount, liquidity
            );
        }

        Ok(valid)
    }

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

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

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

    pub async fn monitor_positions(&self) -> Result<()> {
        for item in self.active_trades.iter() {
            let (token, trade) = item.pair();

            if let Ok(new_price) = self.get_token_price(token).await {
                let mut trade = trade.clone();
                trade.current_price = new_price;

                if trade.should_close() {
                    info!(
                        "🎯 Closing position for {} (P/L: {:.2}%)",
                        token,
                        trade.calculate_pl()
                    );
                    if let Err(e) = self.execute_trade(token, false).await {
                        error!("Failed to close position: {}", e);
                    }
                }
            }
        }
        Ok(())
    }

    pub fn extract_token_from_pool(&self, pool_data: &[u8]) -> Result<String> {
        if pool_data.len() < 40 {
            return Err(anyhow!("Invalid pool data length"));
        }

        let token_bytes = &pool_data[8..40];
        Ok(bs58::encode(token_bytes).into_string())
    }
}
 AND THE NEXT IS MISSING TOKIO MAIN AND IS THE MAIN.RS use {
    anyhow::{anyhow, Context, Result},
    base64::Engine,
    colored::*,
    futures_util::{SinkExt, StreamExt},
    log::{error, info, warn},
    serde_json::json,
    solana_sdk::{
        commitment_config::CommitmentConfig,
        signature::{keypair::Keypair, Signer},
    },
    std::{
        fs,
        path::PathBuf,
        sync::Arc,
        time::{Duration, SystemTime},
    },
    tokio::{
        net::TcpStream,
        sync::Mutex,
    },
    tokio_tungstenite::{
        connect_async,
        tungstenite::Message,
        MaybeTlsStream,
        WebSocketStream,
    },
};
use {
    anyhow::{Context, Result},
    solana_sdk::signature::keypair::Keypair,
    std::sync::Arc,
    tokio::sync::Mutex,
};

mod lib; // Import your existing lib module
const CHECK_INTERVAL: u64 = 2000;
const RECONNECT_DELAY: u64 = 1000;
const MAX_RETRIES: u8 = 5;
const RPC_URL: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com/ws";

struct BotMetrics {
    start_time: SystemTime,
    pools_scanned: u32,
    trades_executed: u32,
    successful_trades: u32,
    missed_opportunities: u32,
}

impl Default for BotMetrics {
    fn default() -> Self {
        Self {
            start_time: SystemTime::now(),
            pools_scanned: 0,
            trades_executed: 0,
            successful_trades: 0,
            missed_opportunities: 0,
        }
    }
}

fn load_keypair() -> Result<Keypair> {
    let keypair_path = get_keypair_path()?;

    if !keypair_path.exists() {
        return Err(anyhow!("Solana keypair not found at: {}", keypair_path.display()));
    }

    let keypair_json = fs::read_to_string(&keypair_path)
        .with_context(|| format!("Failed to read keypair from: {}", keypair_path.display()))?;

    let keypair_bytes: Vec<u8> = serde_json::from_str(&keypair_json)
        .with_context(|| "Invalid keypair JSON format")?;

    if keypair_bytes.len() != 64 {
        return Err(anyhow!(
            "Invalid keypair length: expected 64 bytes, got {}",
            keypair_bytes.len()
        ));
    }

    let mut array = [0u8; 64];
    array.copy_from_slice(&keypair_bytes);

    Keypair::from_bytes(&array).with_context(|| "Failed to create keypair from bytes")
}

fn get_keypair_path() -> Result<PathBuf> {
    dirs::home_dir()
        .map(|mut path| {
            path.push(".config");
            path.push("solana");
            path.push("id.json");
            path
        })
        .ok_or_else(|| anyhow!("Could not find home directory"))
}

async fn connect_to_market() -> Result<WebSocketStream<MaybeTlsStream<TcpStream>>> {
    let ws_endpoints = vec![
        WS_URL,
        "wss://solana-mainnet.rpc.extrnode.com/ws",
        "wss://mainnet.helius-rpc.com/?api-key=1ea5843b-9daa-4926-a97a-be021922da2f",
    ];

    for endpoint in ws_endpoints {
        info!("🔌 Attempting connection to {}", endpoint);

        match connect_async(endpoint).await {
            Ok((ws_stream, _)) => {
                info!("✅ Successfully connected to WebSocket endpoint");

                // Test connection with a ping
                let (mut write, _) = ws_stream.split();
                if let Err(_) = write.send(Message::Ping(vec![1])).await {
                    warn!("Failed ping test, trying next endpoint...");
                    continue;
                }

                return Ok(ws_stream);
            }
            Err(e) => {
                warn!("Failed to connect to {}: {}", endpoint, e);
                continue;
            }
        }
    }

    Err(anyhow!("Failed to connect to any WebSocket endpoint"))
}

async fn process_market_feed(
    ws_stream: WebSocketStream<MaybeTlsStream<TcpStream>>,
    bot: Arc<Bot>,
    metrics: Arc<Mutex<BotMetrics>>,
) -> Result<()> {
    let (mut write, mut read) = ws_stream.split();

    // Enhanced subscription message
    let subscribe_msg = json!({
        "jsonrpc": "2.0",
        "id": 1,
        "method": "programSubscribe",
        "params": [
            "675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8",
            {
                "encoding": "base64",
                "commitment": "confirmed"
            }
        ]
    });

    write.send(Message::Text(subscribe_msg.to_string())).await?;
    info!("👀 Market subscription active");

    let mut interval = tokio::time::interval(Duration::from_millis(CHECK_INTERVAL));

    while let Some(msg) = read.next().await {
        match msg {
            Ok(Message::Text(text)) => {
                if let Err(e) = process_market_message(&text, &bot, &metrics).await {
                    error!("Message processing error: {}", e);
                }
            }
            Ok(Message::Ping(_)) => {
                write.send(Message::Pong(vec![])).await?;
            }
            Err(e) => {
                error!("WebSocket error: {}", e);
                break;
            }
            _ => {}
        }

        tokio::select! {
            _ = interval.tick() => {
                display_market_status(&metrics).await;
            }
        }
    }

    Ok(())
}

async fn process_market_message(
    message: &str,
    bot: &Bot,
    metrics: &Arc<Mutex<BotMetrics>>,
) -> Result<()> {
    let value: serde_json::Value = serde_json::from_str(message)?;

    if let Some(pool_data) = extract_pool_data(&value) {
        let start = std::time::Instant::now();
        
        {
            let mut metrics = metrics.lock().await;
            metrics.pools_scanned += 1;
        }

        let decoded = base64::engine::general_purpose::STANDARD.decode(pool_data)?;
        if decoded.len() != 2208 {
            return Ok(());
        }

        if let Ok(token) = bot.extract_token_from_pool(&decoded) {
            display_token_detection(&token, start.elapsed());

            if let Ok(signature) = bot.execute_trade(&token, true).await {
                let mut metrics = metrics.lock().await;
                metrics.trades_executed += 1;
                metrics.successful_trades += 1;
                display_trade_execution("BUY", &token, &signature);
            }
        }
    }

    Ok(())
}

fn extract_pool_data(event_data: &serde_json::Value) -> Option<&str> {
    event_data
        .get("params")?
        .get("result")?
        .get("value")?
        .get("data")?
        .get(0)?
        .as_str()
}

fn display_welcome_banner() {
    println!("\n{}", "═".repeat(70).blue());
    println!("{:^70}", " SOLANA MARKET SNIPER v2.0 ".green().bold());
    println!("{:^70}", " Enhanced Helius Integration ".yellow());
    println!("{}\n", "═".repeat(70).blue());
}

fn display_status_message(context: &str, message: &str, success: bool) {
    let symbol = if success { "✅" } else { "⏳" };
    println!(
        "{} {} | {}",
        symbol,
        context.blue(),
        if success {
            message.green()
        } else {
            message.yellow()
        }
    );
}

fn display_error_message(context: &str, error: &str) {
    println!("❌ {} | {}", context.red(), error.red());
}

fn display_error_shutdown(reason: &str) {
    println!("\n{}", "╔═══════════ ERROR SHUTDOWN ═══════════╗".red());
    println!("║ {:<37} ║", reason.red());
    println!("{}", "╚═════════════════════════════════════╝".red());
}

fn display_token_detection(token: &String, elapsed: Duration) {
    println!(
        "\n{}",
        "╔════════════ NEW TOKEN DETECTED ════════════╗".blue()
    );
    println!("║ 🪙 Token    : {:<30} ║", token);
    println!("║ ⚡ Response : {:<30} ║", format!("{:.2}ms", elapsed.as_millis()));
    println!("{}", "╚═════════════════════════════════════════╝".blue());
}

fn display_trade_execution(action: &str, token: &str, signature: &str) {
    let (color, icon) = match action {
        "BUY" => (Color::Green, "🟢"),
        "SELL" => (Color::Red, "🔴"),
        _ => (Color::White, "⚪"),
    };

    println!(
        "\n{}",
        "╔════════════ TRADE EXECUTED ════════════╗".color(color)
    );
    println!("║ {} Action   : {:<30} ║", icon, action);
    println!("║ 🪙 Token    : {:<30} ║", token);
    println!("║ 📝 TX       : {:<30} ║", &signature[..12]);
    println!(
        "{}",
        "╚═════════════════════════════════════════╝".color(color)
    );
}

async fn display_market_status(metrics: &Arc<Mutex<BotMetrics>>) {
    let metrics = metrics.lock().await;
    let runtime = metrics.start_time.elapsed().unwrap_or_default();

    println!("\n{}", "╔════════════ MARKET METRICS ════════════╗".blue());
    println!(
        "║ ⏱️  Runtime    : {:02}:{:02}:{:02}               ║",
        runtime.as_secs() / 3600,
        (runtime.as_secs() % 3600) / 60,
        runtime.as_secs() % 60
    );
    println!("║ 🔍 Scanned    : {:<24} ║", metrics.pools_scanned);
    println!(
        "║ 📊 Success    : {:.1}%                  ║",
        if metrics.trades_executed > 0 {
            (metrics.successful_trades as f64 / metrics.trades_executed as f64) * 100.0
        } else {
            0.0
        }
    );
    println!("║ 💫 Missed     : {:<24} ║", metrics.missed_opportunities);
    println!("{}", "╚═════════════════════════════════════════╝".blue());
}

async fn close_active_positions(bot: &Bot) {
    println!(
        "\n{}",
        "╔═══════════ CLOSING POSITIONS ═══════════╗".yellow()
    );

    let mut success_count = 0;
    let mut total_count = 0;

    for trade in bot.active_trades.iter() {
        let token = trade.key();
        total_count += 1;

        match bot.execute_trade(token, false).await {
            Ok(sig) => {
                success_count += 1;
                println!("║ ✅ Closed {} ({:<12})       ║", token, &sig[..12]);
            }
            Err(e) => {
                println!("║ ❌ Failed {} ({})             ║", token, e);
            }
        }
    }

    println!(
        "║ 📊 Closed {}/{} positions              ║",
        success_count, total_count
    );
    println!("{}", "╚══════════════════════════════════════╝".yellow());
}
#[tokio::main]
async fn main() -> Result<()> {
    // Display welcome banner
    lib::display_welcome_banner();

    // Load the keypair
    let keypair = lib::load_keypair().context("Failed to load keypair")?;
    let bot = Arc::new(lib::Bot::new(keypair));
    let metrics = Arc::new(Mutex::new(lib::BotMetrics::default()));

    // Attempt to connect to market (WebSocket)
    let ws_stream = lib::connect_to_market().await.context("Failed to connect to market")?;

    // Process the market feed
    lib::process_market_feed(ws_stream, bot.clone(), metrics.clone())
        .await
        .context("Market feed processing failed")?;

    // Monitor open positions in the bot
    loop {
        if let Err(e) = bot.monitor_positions().await {
            eprintln!("Error monitoring positions: {}", e);
        }
        tokio::time::sleep(std::time::Duration::from_secs(5)).await; // Check every 5 seconds
    }
} WRITE THE FULLY FUNCTIONAL REVISIONS PLEASE OF THE WORKING CODE FOR THE SCRIPTS TO COMPILE RUN AND OPERATE AS INTENDED