please fix the spacing here and rewrite the full script The errors and warnings you're encountering are related to Rust's borrowing rules and missing imports. Let's address each issue one by one:
1. **Unused Imports**:
   - The warning about unused imports (`instruction::Instruction`, `pubkey::Pubkey`, and `signature::Signature`) can be resolved by removing these unused imports from the `use` statements at the beginning of your script. Since these types are not used in the current version of the script, you can safely remove them.

2. **Mutable Borrowing Errors**:
   - The errors related to borrowing `last_prices`, `self.active_trades`, and `self.token_blacklist` as mutable can be fixed by making these variables mutable. You need to add the `mut` keyword when declaring these variables.

   For `last_prices`, you can change:
   ```rust
   let last_prices: HashMap<String, f64> = HashMap::new();
   ```
   to:
   ```rust
   let mut last_prices: HashMap<String, f64> = HashMap::new();
   ```

   Similarly, for `self.active_trades` and `self.token_blacklist`, you need to change the function signatures to include the `mut` keyword for `self`. For example:
   ```rust
   async fn execute_sell(&mut self, token_mint: &str, price: f64) -> Result<()> {
   ```

3. **Missing Method `split`**:
   - The error about the missing method `split` is due to a missing import. You need to add the following import statement at the beginning of your script:
   ```rust
   use futures_util::stream::StreamExt;
   ```

   This import provides the `split` method for the `WebSocketStream` type.

4. **Other Potential Issues**:
   - Ensure that you have the correct version of the required crates and dependencies installed. You can update them using `cargo update`.
   - Double-check that all function signatures and method calls are consistent and match the types and arguments they are expecting.

Here's the updated version of your script with the above fixes applied:
```rust
use solana_sdk::{
    pubkey::Pubkey,
    signature::Signature,
};
use std::collections::HashMap;
use tokio::sync::Mutex;
use serde_json::{json, Value};
use reqwest::Client;
use log::{info, warn};
use anyhow::{anyhow, Result};
use tokio_tungstenite::{connect_async, tungstenite::protocol::Message as WsMessage};
use url::Url;
use futures_util::stream::StreamExt;

// Configuration Constants
const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com";
const WALLET_PUBLIC_KEY: &str = "YOUR_WALLET_PUBLIC_KEY";
const HELIUS_API_KEY: &str = "YOUR_HELIUS_API_KEY";
const SOL_MINT: &str = "So1111111111111111111111111111111111111112";

// Trading Parameters
const MIN_SUPPLY: u64 = 900_000_000;
const REQUIRED_MUTABLE: bool = false;
const REQUIRED_BURNT: bool = true;
const REQUIRED_FROZEN: bool = false;
const TRADE_AMOUNT: u64 = 5_000_000;
const PRIORITY_FEE: u64 = 15000;
const MAX_CONCURRENT_TRADES: usize = 5;
const PROFIT_TARGET: f64 = 20.0;
const STOP_LOSS: f64 = -5.0;
const MAX_TOKEN_AGE_SECONDS: u64 = 3600;

#[derive(Debug, Clone)]
struct ActiveTrade {
    token_mint: String,
    entry_price: f64,
    amount: u64,
    start_time: std::time::Instant,
    last_price: Arc<Mutex<f64>>,
}

#[derive(Debug)]
struct TradeManager {
    active_trades: HashMap<String, ActiveTrade>,
    token_blacklist: HashMap<String, ()>,
}

impl TradeManager {
    fn new() -> Self {
        Self {
            active_trades: HashMap::new(),
            token_blacklist: HashMap::new(),
        }
    }

    async fn get_quote(&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 = Client::new()
            .get(&url)
            .send()
            .await?
            .json::<Value>()
            .await?;
        
        info!("💫 Quote received: {}", serde_json::to_string_pretty(&response)?);
        Ok(response)
    }
    
    async fn get_swap_data(&self, quote: Value) -> Result<String> {
        let swap_request = json!({
            "quoteResponse": quote,
            "userPublicKey": WALLET_PUBLIC_KEY,
            "wrapUnwrapSOL": true,
            "computeUnitPriceMicroLamports": PRIORITY_FEE,
            "priorityFeeLamports": PRIORITY_FEE,
            "asLegacyTransaction": false,
            "maxAccounts": 64,
            "verifyWallet": true
        });
    
        let response = Client::new()
            .post(format!("{}/swap", JUPITER_API))
            .json(&swap_request)
            .send()
            .await?
            .json::<Value>()
            .await?;
    
        info!("🚀 Swap response: {}", serde_json::to_string_pretty(&response)?);
    
        // Check for market not found error
        if let Some(error) = response.get("error") {
            if error.as_str().unwrap_or("").contains("Market") {
                info!("🔄 Market setup in progress, waiting...");
                return Ok("retry".to_string());
            }
        }
    
        match response.get("swapTransaction") {
            Some(tx) => Ok(tx.as_str().unwrap_or_default().to_string()),
            None => Ok("retry".to_string())  // Return retry signal instead of error
        }
    }

    async fn send_priority_tx(&self, swap_data: String) -> Result<String> {
        // Skip if we got a retry signal
        if swap_data == "retry" {
            return Ok("waiting_for_market".to_string());
        }
    
        let helius_request = json!({
            "jsonrpc": "2.0",
            "id": "helius-priority",
            "method": "sendTransaction",
            "params": [
                swap_data,
                {
                    "encoding": "base64",
                    "maxRetries": 0,
                    "skipPreflight": true,
                    "preflightCommitment": "processed",
                    "priorityFee": PRIORITY_FEE
                }
            ]
        });
    
        let response = Client::new()
            .post(HELIUS_RPC)
            .header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
            .json(&helius_request)
            .send()
            .await?
            .json::<Value>()
            .await?;
    
        info!("💎 Transaction response: {}", serde_json::to_string_pretty(&response)?);
    
        match response.get("result") {
            Some(result) => Ok(result.as_str().unwrap_or_default().to_string()),
            None => Ok("transaction_pending".to_string())  // Keep the bot running
        }
    }
    
    async fn fetch_price(&self, token_mint: &str) -> Result<f64> {
        let request = json!({
            "jsonrpc": "2.0",
            "id": "price-check",
            "method": "getAsset",
            "params": {
                "id": token_mint,
                "displayOptions": {
                    "showFungible": true
                }
            }
        });

        let response = Client::new()
            .post(HELIUS_RPC)
            .json(&request)
            .send()
            .await?
            .json::<Value>()
            .await?;

        let price = response["result"]["token_info"]["price_info"]["price_per_token"]
            .as_f64()
            .ok_or_else(|| anyhow!("Failed to get price"))?;

        Ok(price)
    }

    async fn monitor_trades(&self) {
        let mut interval = tokio::time::interval(std::time::Duration::from_millis(100));
        let mut last_trade_count = 0;
        let mut last_prices: HashMap<String, f64> = HashMap::new();
        
        loop {
            interval.tick().await;
            let current_trades = self.active_trades.len();
            
            if current_trades != last_trade_count {
                info!("💫 Active Trades: {}", current_trades);
                last_trade_count = current_trades;
            }
            
            for (token_mint, trade) in self.active_trades.iter_mut() {
                if let Ok(current_price) = self.fetch_price(token_mint).await {
                    let profit_percent = (current_price - trade.entry_price) / trade.entry_price * 100.0;
                    
                    // Check for significant price movement
                    if let Some(last_price) = last_prices.get(token_mint) {
                        if (current_price - *last_price).abs() > (current_price * 0.005) {
                            info!("🔄 Token: {} | Price: {} | Profit: {:.2}%", token_mint, current_price, profit_percent);
                            last_prices.insert(token_mint.to_string(), current_price);
                        }
                    } else {
                        last_prices.insert(token_mint.to_string(), current_price);
                        info!("🆕 New Token Tracked: {} | Initial Price: {}", token_mint, current_price);
                    }
                    
                    if profit_percent >= PROFIT_TARGET {
                        info!("🎯 Take profit hit for {}", token_mint);
                        if let Err(e) = self.execute_sell(token_mint, current_price).await {
                            warn!("❌ Take profit sell failed: {}", e);
                        }
                    } else if profit_percent <= STOP_LOSS {
                        warn!("⚠️ Stop loss hit for {}", token_mint);
                        if let Err(e) = self.execute_sell(token_mint, current_price).await {
                            warn!("❌ Stop loss sell failed: {}", e);
                        }
                    }
                    
                    *trade.last_price.lock().await = current_price;
                }
            }
        }
    }

    async fn execute_buy(&mut self, token_mint: &str) -> Result<()> {
        // Check if token is tradeable first
        let quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
        
        // If we get an error about token not being tradeable, we'll wait and retry
        if quote.get("error").is_some() {
            info!("🔄 Token {} not tradeable yet, waiting for liquidity...", token_mint);
            
            // Retry loop for 30 seconds
            for _ in 0..30 {
                tokio::time::sleep(std::time::Duration::from_secs(1)).await;
                let retry_quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
                if retry_quote.get("error").is_none() {
                    info!("✅ Token {} now tradeable!", token_mint);
                    // Get swap transaction data
                    let swap_data = self.get_swap_data(retry_quote).await?;
                    
                    // Execute the swap with priority
                    let signature = self.send_priority_tx(swap_data).await?;
                    
                    // Get initial price
                    let entry_price = self.fetch_price(token_mint).await?;
                    
                    // Add to active trades
                    self.active_trades.insert(
                        token_mint.to_string(),
                        ActiveTrade {
                            token_mint: token_mint.to_string(),
                            entry_price,
                            amount: TRADE_AMOUNT,
                            start_time: std::time::Instant::now(),
                            last_price: Arc::new(Mutex::new(entry_price)),
                        }
                    );
                    
                    info!("💎 Bought {} at price {} - TX: {}", token_mint, entry_price, signature);
                    return Ok(());
                }
            }
            info!("⏱️ Timeout waiting for {} to become tradeable", token_mint);
            return Ok(());
        }
    
        // If token is already tradeable, execute immediately
        let swap_data = self.get_swap_data(quote).await?;
        let signature = self.send_priority_tx(swap_data).await?;
        let entry_price = self.fetch_price(token_mint).await?;
        
        self.active_trades.insert(
            token_mint.to_string(),
            ActiveTrade {
                token_mint: token_mint.to_string(),
                entry_price,
                amount: TRADE_AMOUNT,
                start_time: std::time::Instant::now(),
                last_price: Arc::new(Mutex::new(entry_price)),
            }
        );
        
        info!("💎 Bought {} at price {} - TX: {}", token_mint, entry_price, signature);
        Ok(())
    }

    async fn execute_sell(&mut self, token_mint: &str, price: f64) -> Result<()> {
        let trade = self.active_trades.get_mut(token_mint)
            .ok_or_else(|| anyhow!("Trade not found"))?;

        let quote = self.get_quote(token_mint, SOL_MINT, trade.amount).await?;
        let swap_data = self.get_swap_data(quote).await?;
        let signature = self.send_priority_tx(swap_data).await?;

        info!("💰 Sold {} at price {} - TX: {}", token_mint, price, signature);
        self.active_trades.remove(token_mint);
        
        Ok(())
    }

    async fn validate_and_execute_trade(&self, token_mint: &str, amount: u64) -> Result<String> {
        // Check liquidity first
        info!("🔍 Checking liquidity...");
        let quote = self.get_quote(SOL_MINT, token_mint, amount).await?;
        if quote.get("error").is_some() {
            info!("⚡ Skipping - No liquidity");
            return Ok("no_liquidity".to_string());
        }
    
        // Get token data
        let token_request = json!({
            "jsonrpc": "2.0",
            "id": "token-check",
            "method": "getAsset",
            "params": {
                "id": token_mint
            }
        });
    
        let response = Client::new()
            .post(HELIUS_RPC)
            .header("Authorization", format!("Bearer {}", HELIUS_API_KEY))
            .json(&token_request)
            .send()
            .await?
            .json::<Value>()
            .await?;
    
        // Validate token criteria
        let token_info = &response["result"]["token_info"];
        let supply = token_info["supply"]
            .as_str()
            .ok_or_else(|| anyhow!("Supply not found"))?
            .parse::<u64>()?;
        let is_frozen = token_info["is_frozen"].as_bool().unwrap_or(true);
        let is_burnt = token_info["is_burnt"].as_bool().unwrap_or(false);
        let is_mutable = token_info["is_mutable"].as_bool().unwrap_or(true);
    
        if supply < MIN_SUPPLY || !is_frozen || !is_burnt || !is_mutable {
            info!("⚡ Token doesn't meet criteria");
            return Ok("invalid_token".to_string());
        }
    
        info!("✅ Token validated! Executing trade...");
        
        // Execute the trade
        info!("🚀 Building swap...");
        let swap_data = self.get_swap_data(quote).await?;
        
        info!("💨 Sending priority transaction...");
        let signature = self.send_priority_tx(swap_data).await?;
        
        Ok(signature)
    }

    async fn handle_new_token(&mut self, token_mint: &str) -> Result<()> {
        info!("🎯 Analyzing token for tradeability: {}", token_mint);
    
    // Check if token is tradeable
    let quote = self.get_quote(SOL_MINT, token_mint, TRADE_AMOUNT).await?;
    if quote.get("error").is_some() {
        info!("⛔ Token {} is not tradeable, skipping...", token_mint);
        return Ok(());
    }
    
    // Check token age
    let token_request = json!({
        "jsonrpc": "2.0",
        "id": "token-check",
        "method": "getAsset",
        "params": {
            "id": token_mint
        }
    });

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

    let creation_time = response["result"]["creationTime"].as_u64().unwrap_or(0);
    let current_time = std::time::Instant::now().elapsed().as_secs();
    if current_time - creation_time > MAX_TOKEN_AGE_SECONDS {
        info!("⏳ Token {} is too old, skipping...", token_mint);
        return Ok(());
    }
    
    info!("✅ Token {} is tradeable and within age limit, proceeding with trade setup...", token_mint);
    
    // Execute Jupiter buy
    self.execute_buy(token_mint).await?;
    
    // Add token to blacklist to avoid processing again
    self.token_blacklist.insert(token_mint.to_string(), ());
    
    Ok(())
}

#[tokio::main]
async fn main() -> Result<()> {
    env_logger::init();
    info!("🚀 Trading bot initialized!");

    let trade_manager = Arc::new(TradeManager::new());

    loop {
        match run_bot(trade_manager.clone()).await {
            Ok(_) => info!("🔄 Bot cycle completed, continuing the hunt..."),
            Err(e) => {
                warn!("⚠️ Bot encountered error: {}. Restarting in 5 seconds...", e);
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            }
        }
    }


async fn run_bot(trade_manager: Arc<TradeManager>) -> Result<()> {
    let ws_url = Url::parse(WS_URL)?;
    
    loop {
        info!("📡 Connecting to WebSocket...");
        match connect_async(ws_url.clone()).await {
            Ok((ws_stream, _)) => {
                let (mut write, mut read) = ws_stream.split();

                let monitor_manager = trade_manager.clone();
                tokio::spawn(async move {
                    monitor_manager.monitor_trades().await;
                });

                let subscribe_msg = json!({
                    "jsonrpc": "2.0",
                    "id": "1",
                    "method": "programSubscribe",
                    "params": [
                        "TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA",
                        {
                            "encoding": "jsonParsed",
                            "filters": [
                                {
                                    "dataSize": 82
                                }
                            ]
                        }
                    ]
                });

                if let Err(e) = write.send(WsMessage::Text(subscribe_msg.to_string())).await {
                    warn!("⚠️ WebSocket subscription error: {}. Reconnecting...", e);
                    continue;
                }
                info!("📡 WebSocket subscription active!");

                while let Some(msg_result) = read.next().await {
                    match msg_result {
                        Ok(WsMessage::Text(text)) => {
                            let value: Value = match serde_json::from_str(&text) {
                                Ok(v) => v,
                                Err(e) => {
                                    info!("⚡ Skipping non-token message: {}", e);
                                    continue;
                                }
                            };

                            if let Some(params) = value.get("params") {
                                if let Some(result) = params.get("result") {
                                    if let Some(value) = result.get("value") {
                                        if let Some(account) = value.get("account") {
                                            if let Some(data) = account.get("data") {
                                                if let Some(parsed) = data.get("parsed") {
                                                    if let Some(info) = parsed.get("info") {
                                                        let token_mint = info["mint"].as_str().unwrap_or("unknown");
                                                        
                                                        info!("🎯 Analyzing Token:");
                                                        info!("📍 Mint: {}", token_mint);
                                                        
                                                        // Validate and execute trade
                                                        if let Ok(signature) = trade_manager.validate_and_execute_trade(token_mint, TRADE_AMOUNT).await {
                                                            info!("💰 Trade executed - TX: {}", signature);
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        Err(e) => {
                            info!("📡 WebSocket message error: {}. Reconnecting...", e);
                            break;
                        }
                        _ => {
                            info!("⚡ Non-text message received, continuing...");
                        }
                    }
                }
            }
            Err(e) => {
                warn!("⚠️ WebSocket connection error: {}. Retrying in 5 seconds...", e);
                tokio::time::sleep(std::time::Duration::from_secs(5)).await;
            }
        }
    }
} 
// Configuration Constants
const JUPITER_API: &str = "https://quote-api.jup.ag/v6";
const HELIUS_RPC: &str = "https://marga-e56m84-fast-mainnet.helius-rpc.com";
const WS_URL: &str = "wss://marga-e56m84-fast-mainnet.helius-rpc.com";
const WALLET_PUBLIC_KEY: &str = "EHrpEhiBU13CygunXsmeGnzR6ircuYFQcFYPZT5BWUMA";
const HELIUS_API_KEY: &str = "1ea5843b-9daa-4926-a97a-be021922da2f";
const SOL_MINT: &str = "So11111111111111111111111111111111111111112"; hard code the const's please