/// A high-performance Solana trading bot implementation in Rust with Python bindings.
/// This module provides fast and efficient trading capabilities on Solana using Rust's
/// performance while maintaining Python's ease of use.
///
/// Key features:
/// - Efficient ATA (Associated Token Account) management
/// - Blockhash caching for faster transactions
/// - Priority fee support for Helius RPC
/// - Async/await support through pyo3-asyncio
///
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,
};
use spl_associated_token_account::{instruction as associated_instruction, get_associated_token_address};
use spl_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;
lazy_static! {
static ref RAYDIUM_PUBKEY: 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();
}
#[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(),
}
}
}
#[pyclass]
#[derive(Clone, Debug)]
struct PyPubkey {
pubkey: Pubkey,
}
#[pymethods]
impl PyPubkey {
#[new]
fn new(value: String) -> PyResult {
Pubkey::from_str(&value)
.map(|pubkey| PyPubkey { pubkey })
.map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("Invalid Pubkey: {}", e)))
}
fn __str__(&self) -> String {
self.pubkey.to_string()
}
}
#[pyclass]
#[derive(Clone, Debug)]
struct PyPubkeyVec {
vec: Vec,
}
#[pymethods]
impl PyPubkeyVec {
#[new]
fn new(value: Vec) -> PyResult {
value
.into_iter()
.map(|s| Pubkey::from_str(&s))
.collect::<Result<Vec<_>, _>>()
.map(|vec| PyPubkeyVec { vec })
.map_err(|e| PyErr::new::<exceptions::PyValueError, _>(format!("Invalid Pubkey in vec: {}", e)))
}
fn __str__(&self) -> String {
format!("{:?}", self.vec)
}
}
#[pyclass]
#[derive(Clone)]
pub struct TradeParams {
#[pyo3(get, set)]
pub accounts: PyPubkeyVec,
#[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,
#[pyo3(get, set)]
pub token_a_decimals: u8,
#[pyo3(get, set)]
pub token_b_decimals: u8,
}
#[pymethods]
impl TradeParams {
#[new]
#[pyo3(signature = (
accounts,
amount_in=None,
is_buy=false,
victim_data=None,
reuse_blockhash=false,
token_a_mint="".to_string(),
token_b_mint="So11111111111111111111111111111111111111112".to_string(),
token_a_decimals=9,
token_b_decimals=9
))]
fn new(
accounts: Vec,
amount_in: Option,
is_buy: bool,
victim_data: Option,
reuse_blockhash: bool,
token_a_mint: String,
token_b_mint: String,
token_a_decimals: u8,
token_b_decimals: u8,
) -> PyResult {
Ok(Self {
accounts: PyPubkeyVec::new(accounts)?,
amount_in,
is_buy,
victim_data,
reuse_blockhash,
token_a_mint,
token_b_mint,
token_a_decimals,
token_b_decimals,
})
}
}
#[pyclass]
#[derive(Clone)]
pub struct TradingCore {
client: Arc,
keypair: Arc,
trade_state: Arc<RwLock>,
}
#[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())),
})
}
#[getter]
fn pubkey(&self) -> PyResult<String> {
Ok(self.keypair.pubkey().to_string())
}
/// Creates an Associated Token Account (ATA) for a given mint.
/// This function will:
/// 1. Check if the ATA already exists
/// 2. Create it if it doesn't exist
/// 3. Cache the result for future operations
///
/// Args:
/// mint_str (str): The mint address as a base-58 encoded string
///
/// Returns:
/// str: The created/existing ATA address
#[pyo3(text_signature = "(self, mint_str)")]
fn create_ata_py<'py>(&self, mint_str: String, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = self.clone();
future_into_py(py, async move {
let mint = Pubkey::from_str(&mint_str).map_err(|e| {
PyErr::new::<exceptions::PyValueError, _>(format!("Invalid mint: {}", e))
})?;
let owner = self_clone.keypair.pubkey();
let ata = get_associated_token_address(&owner, &mint);
let mut state = self_clone.trade_state.write().await;
// Check if ATA exists or needs to be recreated
if let Some(last_check) = state.last_ata_check.get(&mint_str) {
if last_check.elapsed() > Duration::from_secs(60) {
match self_clone.client.get_account(&ata).await {
Ok(_) => {
state.last_ata_check.insert(mint_str.clone(), Instant::now());
},
Err(_) => {
let instruction = associated_instruction::create_associated_token_account(
&owner,
&owner,
&mint,
&*TOKEN_PROGRAM_ID
);
let recent_blockhash = self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e)))?;
let message = Message::new(&[instruction], Some(&owner));
let mut tx = Transaction::new_unsigned(message);
tx.message.recent_blockhash = recent_blockhash;
tx.sign(&[self_clone.keypair.as_ref()], recent_blockhash);
self_clone.client.send_transaction(&tx).await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to create ATA: {}", e)))?;
state.last_ata_check.insert(mint_str.clone(), Instant::now());
}
}
}
} else {
// First time checking this ATA
match self_clone.client.get_account(&ata).await {
Ok(_) => {
state.last_ata_check.insert(mint_str.clone(), Instant::now());
},
Err(_) => {
let instruction = associated_instruction::create_associated_token_account(
&owner,
&owner,
&mint,
&*TOKEN_PROGRAM_ID
);
let recent_blockhash = self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new_err(format!("Failed to get blockhash: {}", e)))?;
let message = Message::new(&[instruction], Some(&owner));
let mut tx = Transaction::new_unsigned(message);
tx.message.recent_blockhash = recent_blockhash;
tx.sign(&[self_clone.keypair.as_ref()], recent_blockhash);
self_clone.client.send_transaction(&tx).await
.map_err(|e| PyErr::new_err(format!("Failed to create ATA: {}", e)))?;
state.last_ata_check.insert(mint_str.clone(), Instant::now());
}
}
}
state.token_atas.insert(mint_str, ata);
Ok(ata.to_string())
})
}
/// Executes a trade on Solana.
/// This function handles:
/// 1. Token transfers between ATAs
/// 2. Computing and setting priority fees
/// 3. Managing blockhash caching
/// 4. Transaction signing and submission
///
/// Args:
/// params (TradeParams): Trading parameters including:
/// - token_a_mint: Source token mint
/// - token_b_mint: Destination token mint
/// - amount_in: Amount to trade
/// - is_buy: True for buy, False for sell
/// - reuse_blockhash: Whether to reuse cached blockhash
///
/// Returns:
/// str: The transaction signature if successful
#[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 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))
})?;
let owner = self_clone.keypair.pubkey();
let token_a_ata = {
let state = self_clone.trade_state.read().await;
if let Some(ata) = state.token_atas.get(¶ms_clone.token_a_mint) {
*ata
} else {
let new_ata = get_associated_token_address(&owner, &token_a);
drop(state);
let mut state = self_clone.trade_state.write().await;
state.token_atas.insert(params_clone.token_a_mint.clone(), new_ata);
new_ata
}
};
let token_b_ata = {
let state = self_clone.trade_state.read().await;
if let Some(ata) = state.token_atas.get(¶ms_clone.token_b_mint) {
*ata
} else {
let new_ata = get_associated_token_address(&owner, &token_b);
drop(state);
let mut state = self_clone.trade_state.write().await;
state.token_atas.insert(params_clone.token_b_mint.clone(), new_ata);
new_ata
}
};
// Prepare transaction instructions
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;
// Add transfer instruction based on trade direction
if params_clone.is_buy {
ixs.push(
instruction::transfer(
&*TOKEN_PROGRAM_ID,
&token_b_ata,
&token_a_ata,
&owner,
&[&owner],
amount_in,
).map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Transfer error: {:?}", e)))?
);
}
// Add nonce for unique transactions
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 with caching logic
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
.map_err(|e| PyErr::new_err(format!("Failed to get blockhash: {}", e)))?;
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
.map_err(|e| PyErr::new_err(format!("Failed to get blockhash: {}", e)))?
};
// 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 with configuration
let config = RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
};
// Trade execution completed
let signature = match self_clone.client.send_transaction_with_config(&tx, config).await {
Ok(signature) => {
// Update trade state
let mut state = self_clone.trade_state.write().await;
state.active_trades += 1;
// Cache ATAs for future use
state.token_atas.insert(params_clone.token_a_mint.clone(), token_a_ata);
state.token_atas.insert(params_clone.token_b_mint.clone(), token_b_ata);
Ok(signature.to_string())
},
Err(e) => Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Trade execution failed: {}", e)
))
}?;
// Return success response
Ok(signature)
})
}
}
#[pymodule]
fn solana_rust_bot(py: Python<'>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
// Register core trading types
m.add_class::<PyPubkey>()?;
m.add_class::<PyPubkeyVec>()?;
m.add_class::<TradeParams>()?;
m.add_class::<TradingCore>()?;
// Add module level constants
m.add("LAMPORTS_PER_SOL", LAMPORTS_PER_SOL)?;
m.add("HELIUS_PRIORITY_FEE", HELIUS_PRIORITY_FEE)?;
m.add("COMPUTE_UNITS", COMPUTE_UNITS)?;
Ok(())
}
} else {
ixs.push(
instruction::transfer(
&*TOKEN_PROGRAM_ID,
&token_a_ata,
&token_b_ata,
&owner,
&[&owner],
amount_in,
).map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Transfer error: {:?}", e)))?
);
}
// Add nonce for unique transactions
use rand::Rng;
let mut rng = rand::thread_rng();
let nonce = rng.gen::<u8>().to_le_bytes();
ixs.push(
ComputeBudgetInstruction::set_compute_unit_price(
HELIUS_PRIORITY_FEE + (nonce[0] as u64 % 100)
)
);
// Get blockhash with caching logic
let blockhash = if params_clone.reuse_blockhash {
let should_fetch_new = {
let state = self_clone.trade_state.read().await;
match (&state.last_blockhash, state.last_blockhash_time) {
(Some(_), Some(time)) => time.elapsed() >= BLOCKHASH_CACHE_DURATION,
_ => true
}
};
if should_fetch_new {
let new_blockhash = self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e)))?;
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 {
let state = self_clone.trade_state.read().await;
solana_sdk::hash::Hash::from_str(state.last_blockhash.as_ref().unwrap()).unwrap()
}
} else {
self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e)))?
};
// 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 with configuration
let config = RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
};
// Trade execution completed
let signature = match self_clone.client.send_transaction_with_config(&tx, config).await {
Ok(signature) => {
// Update trade state
let mut state = self_clone.trade_state.write().await;
state.active_trades += 1;
// Cache ATAs for future use
state.token_atas.insert(params_clone.token_a_mint.clone(), token_a_ata);
state.token_atas.insert(params_clone.token_b_mint.clone(), token_b_ata);
Ok(signature.to_string())
},
Err(e) => Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Trade execution failed: {}", e)
))
}?;
// Return success response
Ok(signature)
})
}
}
}
// Add nonce for unique transactions
use rand::Rng;
let mut rng = rand::thread_rng();
let nonce = rng.gen::<u8>().to_le_bytes();
ixs.push(
ComputeBudgetInstruction::set_compute_unit_price(
HELIUS_PRIORITY_FEE + (nonce[0] as u64 % 100)
)
);
// Get blockhash with caching logic
let blockhash = if params_clone.reuse_blockhash {
let should_fetch_new = {
let state = self_clone.trade_state.read().await;
match (&state.last_blockhash, state.last_blockhash_time) {
(Some(_), Some(time)) => time.elapsed() >= BLOCKHASH_CACHE_DURATION,
_ => true
}
};
if should_fetch_new {
let new_blockhash = self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e)))?;
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 {
let state = self_clone.trade_state.read().await;
solana_sdk::hash::Hash::from_str(state.last_blockhash.as_ref().unwrap()).unwrap()
}
} else {
self_clone.client.get_latest_blockhash().await
.map_err(|e| PyErr::new::<exceptions::PyRuntimeError, _>(format!("Failed to get blockhash: {}", e)))?
};
// 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 with configuration
let config = RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
};
// Trade execution completed
let signature = match self_clone.client.send_transaction_with_config(&tx, config).await {
Ok(signature) => {
// Update trade state
let mut state = self_clone.trade_state.write().await;
state.active_trades += 1;
// Cache ATAs for future use
state.token_atas.insert(params_clone.token_a_mint.clone(), token_a_ata);
state.token_atas.insert(params_clone.token_b_mint.clone(), token_b_ata);
Ok(signature.to_string())
},
Err(e) => Err(PyErr::new::<exceptions::PyRuntimeError, _>(
format!("Trade execution failed: {}", e)
))
}?;
// Return success response
Ok(signature)
})
}
}
#[pymodule]
fn solana_rust_bot(py: Python<'>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
// Register core trading types
m.add_class::<PyPubkey>()?;
m.add_class::<PyPubkeyVec>()?;
m.add_class::<TradeParams>()?;
m.add_class::<TradingCore>()?;
// Add module level constants
m.add("LAMPORTS_PER_SOL", LAMPORTS_PER_SOL)?;
m.add("HELIUS_PRIORITY_FEE", HELIUS_PRIORITY_FEE)?;
m.add("COMPUTE_UNITS", COMPUTE_UNITS)?;
Ok(())
} fix spacing issue and rewrite it exactly word for word