use log::{info, warn}; // Removed unused import for error use…
- User
use log::{info, warn}; // Removed unused import for
erroruse 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; // For creating and fetching associated token account details use spl_token; 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<Vec>, }
#[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<u64> { 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<Pubkey> { 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 = spl_associated_token_account::instruction::create_associated_token_account_idempotent( &self.keypair.pubkey(), // Funding account (fee payer) owner, // Wallet address for new ATA mint, // Token mint address &spl_token::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<solana_sdk::instruction::AccountMeta> = 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