use log::{info, warn}; use pyo3::{exceptions::PyValueError, prelude::*}; use…
- User
use log::{info, warn}; use pyo3::{exceptions::PyValueError, prelude::*}; use pyo3_asyncio::tokio::future_into_py; use solana_client::nonblocking::rpc_client::RpcClient; use solana_sdk::{ commitment_config::{CommitmentConfig, CommitmentLevel}, compute_budget::ComputeBudgetInstruction, instruction::Instruction, message::Message, pubkey::Pubkey, signature::{Keypair, Signer}, transaction::Transaction, }; use spl_associated_token_account::{ get_associated_token_address, instruction::create_associated_token_account_idempotent, }; use spl_token::ID as SPL_TOKEN_PROGRAM_ID; use std::{env, str::FromStr, sync::Arc}; use base58::FromBase58;
// Constants const COMPUTE_UNITS: u32 = 50_000; const PRIORITY_FEE: u64 = 750_000;
#[pyclass] #[derive(Clone)] pub struct TradeParams { #[pyo3(get, set)] pub accounts: Vec, #[pyo3(get, set)] pub amount_in: Option, #[pyo3(get, set)] pub is_buy: bool, #[pyo3(get, set)] pub reuse_blockhash: bool, #[pyo3(get, set)] pub token_a_mint: String, #[pyo3(get, set)] pub token_b_mint: String, #[pyo3(get, set)] pub sell_all: bool, #[pyo3(get, set)] pub victim_data: Option>, }
#[pyclass] pub struct TradingCore { client: Arc, keypair: Arc, }
impl TradingCore { /// Load keypair from environment variables fn load_keypair_from_env() -> PyResult { let private_key = env::var("SOLANA_PRIVATE_KEY") .map_err(|| PyValueError::new_err("SOLANA_PRIVATE_KEY not found in environment"))?; let public_key = env::var("SOLANA_PUBLIC_KEY") .map_err(|| PyValueError::new_err("SOLANA_PUBLIC_KEY not found in environment"))?;
// Validate public key let _pubkey = Pubkey::from_str(&public_key) .map_err(|e| PyValueError::new_err(format!("Invalid public key: {}", e)))?; // Decode private key (assumes Base58 encoding) let secret_key_bytes = private_key.from_base58() .map_err(|e| PyValueError::new_err(format!("Invalid private key encoding: {:?}", e)))?; Keypair::from_bytes(&secret_key_bytes) .map_err(|e| PyValueError::new_err(format!("Invalid keypair: {}", e))) } /// Check the SOL balance of the keypair async fn check_sol_balance(&self) -> PyResult { let balance = self.client.get_balance(&self.keypair.pubkey()).await .map_err(|e| PyValueError::new_err(format!("Failed to get SOL balance: {}", e)))?; Ok(balance) } /// Ensure Associated Token Account (ATA) exists async fn ensure_ata_exists( &self, owner: &Pubkey, mint: &Pubkey ) -> PyResult { let ata = get_associated_token_address(owner, mint); match self.client.get_account(&ata).await { Ok(_) => { info!("ATA already exists: {}", ata); Ok(ata) } Err(_) => { warn!("ATA does not exist. Creating ATA for mint: {}", mint); // Create instruction using spl_associated_token_account let ix = create_associated_token_account_idempotent( &self.keypair.pubkey(), // Funding account (fee payer) owner, // Wallet address for new ATA mint, // Token mint address &SPL_TOKEN_PROGRAM_ID, // Token program ID ); let blockhash = self.client.get_latest_blockhash().await .map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?; // Create and sign transaction let mut tx = Transaction::new_with_payer(&[ix], Some(&self.keypair.pubkey())); tx.sign(&[self.keypair.as_ref()], blockhash); // Send transaction with preflight disabled let config = solana_client::rpc_config::RpcSendTransactionConfig { skip_preflight: true, preflight_commitment: Some(CommitmentLevel::Confirmed), encoding: None, max_retries: Some(3), min_context_slot: None, }; match self.client.send_transaction_with_config(&tx, config).await { Ok(_) => { info!("ATA created successfully: {}", ata); Ok(ata) }, Err(e) => { warn!("ATA creation failed with error: {:?}", e); Err(PyValueError::new_err(format!("Failed to create ATA. Full error: {:?}", e))) } } } } } /// Create custom swap instruction fn create_swap_instruction( &self, program_id: &Pubkey, accounts: &[Pubkey], amount: u64, is_buy: bool, source_ata: Pubkey, destination_ata: Pubkey, victim_data: Option<&[u8]>, ) -> Instruction { let mut modified_accounts = accounts.to_vec(); // Ensure minimum account length if modified_accounts.len() < 3 { modified_accounts.resize(3, self.keypair.pubkey()); } // Modify accounts to use ATAs if is_buy { modified_accounts[1] = source_ata; // Source WSOL ATA modified_accounts[2] = destination_ata; // Destination Token ATA } else { modified_accounts[1] = source_ata; // Source Token ATA modified_accounts[2] = destination_ata; // Destination WSOL ATA } // Prepare instruction data let mut data = vec![if is_buy { 9u8 } else { 11u8 }]; if is_buy { if let Some(vdata) = victim_data { data.extend_from_slice(vdata); } else { data.extend_from_slice(&amount.to_le_bytes()); } } else { data.extend_from_slice(&amount.to_le_bytes()); } // Create account metas dynamically and pad to at least 18 accounts if needed if modified_accounts.len() < 18 { modified_accounts.resize(18, self.keypair.pubkey()); } let account_metas: Vec = modified_accounts .iter() .enumerate() .map(|(i, &pubkey)| { match i { 0 => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false), // Program ID 1 => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false), // AMM Authority (NOT a signer) 2 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // AMM Open Orders 3 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // AMM Target 4 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Pool Token Mint 5 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Pool Token Account 6 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Program ID 7 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Market 8 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Bids 9 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Asks 10 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Event Queue 11 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Base Vault 12 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // Serum Quote Vault 13 => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false), // Base Vault Signer 14 => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false), // Quote Vault Signer 15 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // User Source Token Account (not a signer) 16 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // User Destination Token Account (not a signer) 17 => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, true), // User Owner (signer) _ => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false), // Any additional accounts } }) .collect(); Instruction { program_id: *program_id, accounts: account_metas, data, } } - Assistant
- User
2025-02-08 21:06:28.906 | ERROR | Trade execution error: 'builtins.TradingCore' object has no attribute 'ensure_ata_exists' 2025-02-08 21:06:28.906 | TRADE | 🎯 Trade Found: Size: 42.4958 SOL Position: 0.4 SOL (400000000 lamports) Token A: GUqcZKdzcAB4UPi6zGGKsxp5Lg1rTzdKcHk7tBKNsxbq Token B: So11111111111111111111111111111111111111112 Est. Profit: 0.975404 SOL TX ID: 6pPnFEZiZ5xpYVBuqazof5TYoNGq9esghd8Eni8u1NY588Yvm4ftT7itLNaUikBDmjQ8FGK9qt6uyuWfbbfP59L
- Assistant
- User
full script for it please
- Assistant
- User
Compiling solana_rust_bot v0.1.0 (C:\solana_rust_bot) error: cannot find attribute
pyo3in this scope --> src\lib.rs:213:7 | 213 | #[pyo3(name = "ensure_ata_exists")] | ^^^^ | = note:pyo3is in scope, but it is a crate, not an attributeerror: could not compile
solana_rust_bot(lib) due to 1 previous error 2025-02-09T05:09:12.680958Z INFO build_wheels: maturin::build_context: close time.busy=2.07s 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> wtf happened here accident? or what it means like that - Assistant