// MODIFY THIS PART in create_trade_instruction:
if let Some(victim) = victim_data {
// Atomic entry trade - FIXED account ordering
let mut data = vec![9u8]; // Raydium atomic swap
data.extend_from_slice(&amount_in.to_le_bytes());
data.extend_from_slice(&victim);
// FIXED account order for Raydium atomic swap
let swap_accounts = vec![
AccountMeta::new(accounts[0], true), // Wallet (signer)
AccountMeta::new(accounts[0], false), // User wallet
AccountMeta::new(*wsol_token_account, false), // Your WSOL account
AccountMeta::new(accounts[2], false), // User token account
AccountMeta::new(*RAYDIUM_PROGRAM_ID, false), // Raydium program
AccountMeta::new(accounts[5], false), // Market
AccountMeta::new(accounts[6], false), // AMM Authority
AccountMeta::new(accounts[7], false), // AMM Open Orders
AccountMeta::new(accounts[8], false), // Pool Target
AccountMeta::new(accounts[9], false), // Serum Market
AccountMeta::new(accounts[10], false), // Serum Bids
AccountMeta::new(accounts[11], false), // Serum Asks
AccountMeta::new(accounts[12], false), // Event Queue
AccountMeta::new(accounts[13], false), // Base Vault
AccountMeta::new(accounts[14], false), // Quote Vault
AccountMeta::new(accounts[15], false), // Vault Signer
AccountMeta::new(*TOKEN_PROGRAM_ID, false), // Token Program
AccountMeta::new(*SYSTEM_PROGRAM_ID, false) // System Program
];
instructions.push(Instruction {
program_id: *RAYDIUM_PROGRAM_ID,
accounts: swap_accounts,
data,
});
} else {
// MODIFIED exit trade to use proper accounts
instructions.push(
token_instruction::transfer(
&TOKEN_PROGRAM_ID,
&accounts[2], // Source ATA
wsol_token_account, // Your WSOL account
&accounts[0], // Owner
&[&accounts[0]], // Added signer
amount_in,
).map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Transfer error: {:?}", e)
))?
);
}
// ADD THIS NEW FUNCTION to verify accounts before trading:
async fn verify_account_balance(&self, account: &Pubkey) -> Result<u64, PyErr> {
match self.client.get_token_account_balance(account).await {
Ok(balance) => {
info!("Account {} balance: {}", account, balance.ui_amount.unwrap_or(0.0));
Ok(balance.amount.parse().unwrap_or(0))
},
Err(e) => {
info!("Failed to get balance for {}: {}", account, e);
Err(PyErr::new::<exceptions::PyRuntimeError, _>(format!("Balance check failed: {}", e)))
}
}
}
// MODIFY execute_trade_py to add balance checks:
#[pyo3(text_signature = "(self, params)")]
fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> {
let params_clone = params.clone();
let self_clone = self.clone();
future_into_py(py, async move {
// ... existing code ...
// Add balance verification before trade
if let Some(_) = victim_data {
// For entry trades, verify WSOL balance
let wsol_balance = self_clone.verify_account_balance(&wsol_token_account).await?;
if wsol_balance < amount_in {
return Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Insufficient WSOL balance: {} < {}", wsol_balance, amount_in)
));
}
} else {
// For exit trades, verify source token balance
let token_balance = self_clone.verify_account_balance(&token_ata).await?;
if token_balance < amount_in {
return Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Insufficient token balance: {} < {}", token_balance, amount_in)
));
}
}
// ... rest of existing code ...
// MODIFY transaction sending to add confirmation check
match self_clone.client.send_transaction_with_config(&tx, config).await {
Ok(signature) => {
info!("Transaction sent: {}", signature);
// Wait for confirmation
match self_clone.client.confirm_transaction_with_spinner(&signature, None).await {
Ok(_) => {
info!("Transaction confirmed!");
let mut state = self_clone.trade_state.write().await;
state.active_trades += 1;
Ok(Some(signature.to_string()))
},
Err(e) => {
info!("Transaction failed to confirm: {}", e);
Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Confirmation failed: {}", e)
))
}
}
},
Err(e) => Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Transaction failed: {}", e)
))
}?
})
} use lazy_static::lazy_static;
use log::info;
use pyo3::{prelude::*, exceptions};
use pyo3_asyncio::tokio::future_into_py;
use rand::Rng;
use solana_client::{
nonblocking::rpc_client::RpcClient,
rpc_config::RpcSendTransactionConfig,
};
use solana_sdk::{
commitment_config::{CommitmentConfig, CommitmentLevel},
compute_budget::ComputeBudgetInstruction,
message::Message,
pubkey::Pubkey,
signature::{Keypair, Signer},
transaction::Transaction,
instruction::Instruction,
system_instruction,
account_meta::AccountMeta,
};
use spl_associated_token_account::{instruction as associated_instruction, get_associated_token_address};
use spl_token::instruction as token_instruction;
use std::{
str::FromStr,
sync::Arc,
time::{Duration, Instant},
collections::HashMap,
};
use tokio::sync::RwLock;
const LAMPORTS_PER_SOL: u64 = 1_000_000_000;
const HELIUS_PRIORITY_FEE: u64 = 750_000;
const BLOCKHASH_CACHE_DURATION: Duration = Duration::from_secs(2);
const COMPUTE_UNITS: u32 = 50_000;
#[derive(Debug)]
struct TradeState {
active_trades: u32,
last_blockhash: Option,
last_blockhash_time: Option,
token_atas: HashMap<String, Pubkey>,
last_ata_check: HashMap<String, Instant>,
}
impl Default for TradeState {
fn default() -> Self {
Self {
active_trades: 0,
last_blockhash: None,
last_blockhash_time: None,
token_atas: HashMap::new(),
last_ata_check: HashMap::new(),
}
}
}
lazy_static! {
static ref RAYDIUM_PROGRAM_ID: Pubkey = Pubkey::from_str("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8").unwrap();
static ref TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str("TokenkegQfeZyiNwAJbNbGKPFXCWuBvf9Ss623VQ5DA").unwrap();
static ref SYSTEM_PROGRAM_ID: Pubkey = Pubkey::from_str("11111111111111111111111111111111").unwrap();
static ref ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey = Pubkey::from_str("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL").unwrap();
}
#[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 victim_data: Option,
#[pyo3(get, set)]
pub reuse_blockhash: bool,
#[pyo3(get, set)]
pub token_a_mint: String,
#[pyo3(get, set)]
pub token_b_mint: String,
}
#[pyclass]
#[derive(Clone)]
pub struct TradingCore {
client: Arc,
keypair: Arc,
trade_state: Arc<RwLock>,
}
impl TradingCore {
async fn ensure_ata_exists(
&self,
mint: &Pubkey,
owner: &Pubkey,
) -> Result<Pubkey, PyErr> {
let ata = get_associated_token_address(owner, mint);
// Check if ATA exists
if self.client.get_account(&ata).await.is_err() {
// Create ATA if it doesn't exist
let create_ata_ix = associated_instruction::create_associated_token_account(
owner,
owner,
mint,
&TOKEN_PROGRAM_ID
);
let recent_blockhash = self.client.get_latest_blockhash().await.map_err(|e| {
PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e))
})?;
let message = Message::new(&[create_ata_ix], Some(owner));
let mut tx = Transaction::new_unsigned(message);
tx.message.recent_blockhash = recent_blockhash;
tx.sign(&[self.keypair.as_ref()], recent_blockhash);
self.client.send_transaction(&tx).await.map_err(|e| {
PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to create ATA: {}", e))
})?;
// Wait for ATA creation
tokio::time::sleep(Duration::from_millis(200)).await;
}
Ok(ata)
}
fn create_trade_instruction(
&self,
accounts: &[Pubkey],
amount_in: u64,
is_buy: bool,
victim_data: Option<Vec<u8>>,
wsol_token_account: &Pubkey,
) -> Result<Vec<Instruction>, PyErr> {
let mut instructions = Vec::new();
if let Some(victim) = victim_data {
// Atomic entry trade
let mut data = vec![9u8]; // Raydium atomic swap
data.extend_from_slice(&amount_in.to_le_bytes());
data.extend_from_slice(&victim);
let swap_accounts = vec![
AccountMeta::new(accounts[0], true), // Wallet (signer)
AccountMeta::new(*wsol_token_account, false), // WSOL token account
AccountMeta::new(accounts[2], false), // User token account
AccountMeta::new(accounts[4], false), // Raydium program
AccountMeta::new(accounts[5], false), // Market
AccountMeta::new(accounts[6], false), // AMM Authority
AccountMeta::new(accounts[7], false), // AMM Open Orders
AccountMeta::new(accounts[8], false), // Pool Target
AccountMeta::new(accounts[9], false), // Serum Market
AccountMeta::new(accounts[10], false), // Serum Bids
AccountMeta::new(accounts[11], false), // Serum Asks
AccountMeta::new(accounts[12], false), // Event Queue
AccountMeta::new(accounts[13], false), // Base Vault
AccountMeta::new(accounts[14], false), // Quote Vault
AccountMeta::new(accounts[15], false), // Vault Signer
AccountMeta::new(*TOKEN_PROGRAM_ID, false), // Token Program
AccountMeta::new(*SYSTEM_PROGRAM_ID, false) // System Program
];
instructions.push(Instruction {
program_id: *RAYDIUM_PROGRAM_ID,
accounts: swap_accounts,
data,
});
} else {
// Regular exit trade - transfer back to WSOL account
instructions.push(
token_instruction::transfer(
&TOKEN_PROGRAM_ID,
&accounts[2], // Source token account (ATA)
wsol_token_account, // Destination (WSOL account)
&accounts[0], // Owner
&[],
amount_in,
).map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Transfer instruction error: {:?}", e)
))?
);
}
Ok(instructions)
}
}
#[pymethods]
impl TradingCore {
#[new]
fn new(rpc_url: &str, keypair_bytes: Vec) -> PyResult {
if keypair_bytes.len() != 64 {
return Err(exceptions::PyValueError::new_err(
format!("Invalid keypair length: {} bytes (expected 64)", keypair_bytes.len())
));
}
let keypair = Keypair::from_bytes(&keypair_bytes).map_err(|_| {
exceptions::PyValueError::new_err("Invalid keypair bytes")
})?;
info!("Initialized TradingCore with pubkey: {}", keypair.pubkey());
Ok(Self {
client: Arc::new(RpcClient::new_with_commitment(
rpc_url.to_string(),
CommitmentConfig::processed(),
)),
keypair: Arc::new(keypair),
trade_state: Arc::new(RwLock::new(TradeState::default())),
})
}
#[pyo3(text_signature = "(self, params)")]
fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> {
let params_clone = params.clone();
let self_clone = self.clone();
future_into_py(py, async move {
let owner = self_clone.keypair.pubkey();
// Convert accounts to Pubkeys
let account_pubkeys: Result<Vec<Pubkey>, _> = params_clone.accounts
.iter()
.map(|s| Pubkey::from_str(s))
.collect();
let account_pubkeys = account_pubkeys.map_err(|e| {
PyErr::new::<exceptions::PyValueError, _>(format!("Invalid account address: {}", e))
})?;
// Get token mints
let token_a = Pubkey::from_str(¶ms_clone.token_a_mint).map_err(|e| {
PyErr::new::<exceptions::PyValueError, _>(format!("Invalid token A mint: {}", e))
})?;
let token_b = Pubkey::from_str(¶ms_clone.token_b_mint).map_err(|e| {
PyErr::new::<exceptions::PyValueError, _>(format!("Invalid token B mint: {}", e))
})?;
// Get or create ATAs and WSOL account
let token_ata = self_clone.ensure_ata_exists(&token_a, &owner).await?;
let wsol_token_account = get_associated_token_address(&owner, &token_b);
let mut ixs = vec![
ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS),
ComputeBudgetInstruction::set_compute_unit_price(HELIUS_PRIORITY_FEE),
];
let amount_in = (params_clone.amount_in.unwrap_or(0.0) * LAMPORTS_PER_SOL as f64) as u64;
let victim_data = params_clone.victim_data
.map(|s| base64::decode(&s).unwrap_or_default());
// Add trade instructions
let mut trade_ixs = self_clone.create_trade_instruction(
&account_pubkeys,
amount_in,
params_clone.is_buy,
victim_data.clone(),
&wsol_token_account,
)?;
ixs.append(&mut trade_ixs);
// Add nonce
let nonce = rand::random::<u8>().to_le_bytes();
ixs.push(
ComputeBudgetInstruction::set_compute_unit_price(
HELIUS_PRIORITY_FEE + (nonce[0] as u64 % 100)
)
);
// Get blockhash
let blockhash = if params_clone.reuse_blockhash {
let state = self_clone.trade_state.read().await;
match (&state.last_blockhash, state.last_blockhash_time) {
(Some(hash_str), Some(time)) if time.elapsed() < BLOCKHASH_CACHE_DURATION => {
solana_sdk::hash::Hash::from_str(hash_str).unwrap()
}
_ => {
drop(state);
let new_blockhash = self_clone.client.get_latest_blockhash().await?;
let mut state = self_clone.trade_state.write().await;
state.last_blockhash = Some(new_blockhash.to_string());
state.last_blockhash_time = Some(Instant::now());
new_blockhash
}
}
} else {
self_clone.client.get_latest_blockhash().await?
};
// Build and sign transaction
let message = Message::new(&ixs, Some(&owner));
let mut tx = Transaction::new_unsigned(message);
tx.message.recent_blockhash = blockhash;
tx.sign(&[self_clone.keypair.as_ref()], blockhash);
// Send transaction
let config = RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: Some(3),
min_context_slot: None,
};
match self_clone.client.send_transaction_with_config(&tx, config).await {
Ok(signature) => {
let mut state = self_clone.trade_state.write().await;
state.active_trades += 1;
Ok(Some(signature.to_string()))
},
Err(e) => Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Transaction failed: {}", e)
))
}?
})
}
}
#[pymodule]
fn solana_rust_bot(py: Python<'>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
m.add_class::()?;
m.add_class::()?;
m.add("LAMPORTS_PER_SOL", LAMPORTS_PER_SOL)?;
m.add("HELIUS_PRIORITY_FEE", HELIUS_PRIORITY_FEE)?;
m.add("COMPUTE_UNITS", COMPUTE_UNITS)?;
Ok(())
} add the top shit into the bottom shit and write the full word for word script