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,
};
use spl_token;
use std::{
env,
str::FromStr,
sync::Arc,
};
use base58::FromBase58;
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"))?;
code
Assistant
User
is that all we need to make the transactions or no?
Assistant
User
can u make sure it has everything needed to make a buy and sell ??? for raydium amm right ???
Assistant
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
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)))
}
/// 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 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();
// 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());
}
// Dynamic account metas based on Raydium protocol
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(pubkey, true), // AMM Authority (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, true), // User Source Token Account
16 => solana_sdk::instruction::AccountMeta::new(pubkey, true), // User Destination Token Account
17 => solana_sdk::instruction::AccountMeta::new(pubkey, true), // User Owner
_ => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false) // Any additional accounts
}
})
.collect();
Instruction {
program_id: *program_id,
accounts: account_metas,
data,
}
}
info!("Loaded keypair with public key: {}", keypair.pubkey());
Ok(Self {
client: Arc::new(RpcClient::new_with_commitment(
rpc_url.to_string(),
CommitmentConfig::processed(),
)),
keypair: Arc::new(keypair),
})
}
fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> {
let params = params.clone();
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
// Convert account strings to pubkeys
let mut accounts: Vec<Pubkey> = Vec::with_capacity(params.accounts.len());
for (idx, acc) in params.accounts.iter().enumerate() {
let pubkey = Pubkey::from_str(acc)
.map_err(|e| PyValueError::new_err(format!("Invalid account address at index {}: {}", idx, e)))?;
accounts.push(pubkey);
}
// Prepare token mints
let token_a_mint = Pubkey::from_str(¶ms.token_a_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token A mint: {}", e)))?;
let token_b_mint = Pubkey::from_str(¶ms.token_b_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token B mint: {}", e)))?;
// Ensure ATAs exist
let source_ata = if params.is_buy {
// For buy, source is WSOL ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
} else {
// For sell, source is token A ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
};
let destination_ata = if params.is_buy {
// For buy, destination is token A ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
} else {
// For sell, destination is WSOL ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
};
let mut instructions = vec![];
// Add compute budget instructions
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(PRIORITY_FEE));
// Determine trade amount
let amount = if let Some(amount) = params.amount_in {
amount
} else if params.sell_all {
// Get token balance for sell_all
let balance = self_clone.client.get_token_account_balance(&source_ata)
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get token balance: {}", e)))?
.amount
.parse::<u64>()
.map_err(|e| PyValueError::new_err(format!("Invalid token balance: {}", e)))?;
balance
} else {
return Err(PyValueError::new_err("No amount specified for swap"));
};
// Create swap instruction with ATAs
let swap_ix = self_clone.create_swap_instruction(
&accounts[0], // Program ID
&accounts, // Original accounts
amount,
params.is_buy,
source_ata,
destination_ata,
params.victim_data.as_deref(),
);
instructions.push(swap_ix);
// Get recent blockhash
let blockhash = self_clone.client.get_latest_blockhash()
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?;
// Create transaction message
let message = Message::new_with_blockhash(
&instructions,
Some(&self_clone.keypair.pubkey()),
&blockhash
);
// Create and sign transaction
let mut tx = Transaction::new_unsigned(message);
tx.try_sign(&[self_clone.keypair.as_ref()], blockhash)
.map_err(|e| PyValueError::new_err(format!("Transaction signing failed: {:?}", e)))?;
// Send transaction
let signature = self_clone.client.send_transaction_with_config(
&tx,
solana_client::rpc_config::RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
},
)
.await
.map_err(|e| PyValueError::new_err(format!("Transaction failed: {}", e)))?;
Ok(signature.to_string())
})
}
#[pyo3(name = "get_sol_balance")]
fn get_sol_balance_py<'py>(&self, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
let balance = self_clone.client.get_balance(&self_clone.keypair.pubkey())
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get SOL balance: {}", e)))?;
Ok(balance as f64 / 1e9) // Convert lamports to SOL
})
}
#[pyo3(name = "get_wsol_balance")]
fn get_wsol_balance_py<'py>(&self, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
let wsol_account = env::var("WSOL_TOKEN_ACCOUNT")
.map_err(|_| PyValueError::new_err("WSOL_TOKEN_ACCOUNT not found"))?;
let pubkey = Pubkey::from_str(&wsol_account)
.map_err(|e| PyValueError::new_err(format!("Invalid WSOL account: {}", e)))?;
let balance = self_clone.client.get_token_account_balance(&pubkey)
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get WSOL balance: {}", e)))?;
let amount = balance.amount.parse::<u64>()
.map_err(|e| PyValueError::new_err(format!("Invalid balance format: {}", e)))?;
Ok(amount as f64 / 1e9) // Convert lamports to SOL
})
}
}
#[pymodule]
fn solana_rust_bot(py: Python<'>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
m.add_class::()?;
m.add_class::()?;
Ok(())
} write the full lib.rs
Certainly! Below is an example of a lib.rs file that integrates the provided Rust code. This implementation utilizes PyO3 to create a Python module for trading on the Solana blockchain. You can use the provided structure as a starting point for your Rust-based Solana bot.
Make sure you have the appropriate dependencies added in your Cargo.toml file:
toml
[dependencies]
log = "0.4"
pyo3 = { version = "0.17", features = ["extension-module"] }
pyo3-asyncio = "0.16"
solana-client = "1.10" # Adjust version as necessary
solana-sdk = "1.10" # Adjust version as necessary
spl-associated-token-account = "0.3" # Adjust version as necessary
spl-token = "0.3" # Adjust version as necessary
base58 = "0.4"
tokio = { version = "1", features = ["full"] }
[lib]
crate-type = ["cdylib"]
Here's how the lib.rs can be set up:
rust
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,
};
use spl_token;
use std::{
env,
str::FromStr,
sync::Arc,
};
use base58::FromBase58;
const COMPUTE_UNITS: u32 = 50_000;
const PRIORITY_FEE: u64 = 750_000;
#[pyclass]
#[derive(Clone)]
pub struct TradeParams {
#[pyo3(get, set)]
pub accounts: Vec<String>,
#[pyo3(get, set)]
pub amount_in: Option<u64>,
#[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<u8>>,
}
#[pyclass]
pub struct TradingCore {
client: Arc<RpcClient>,
keypair: Arc<Keypair>,
}
impl TradingCore {
fn load_keypair_from_env() -> PyResult<Keypair> {
// Load private and public keys from environment variables
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"))?;
let _pubkey = Pubkey::from_str(&public_key)
.map_err(|e| PyValueError::new_err(format!("Invalid public key: {}", e)))?;
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)))
}
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);
let ix = spl_associated_token_account::instruction::create_associated_token_account_idempotent(
&self.keypair.pubkey(),
owner,
mint,
&spl_token::ID
);
let blockhash = self.client.get_latest_blockhash().await
.map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?;
let mut tx = Transaction::new_with_payer(&[ix], Some(&self.keypair.pubkey()));
tx.sign(&[self.keypair.as_ref()], blockhash);
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)))
}
}
}
}
}
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();
if is_buy {
modified_accounts[1] = source_ata;
modified_accounts[2] = destination_ata;
} else {
modified_accounts[1] = source_ata;
modified_accounts[2] = destination_ata;
}
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());
}
// Construct account metas for the instruction
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(pubkey, true), // AMM Authority
2 => solana_sdk::instruction::AccountMeta::new(pubkey, false), // AMM Open Orders
// ... other account metas as per your protocol
_ => solana_sdk::instruction::AccountMeta::new_readonly(pubkey, false) // Any additional accounts
}
})
.collect();
Instruction {
program_id: *program_id,
accounts: account_metas,
data,
}
}
}
#[pymethods]
impl TradeParams {
#[new]
#[pyo3(signature = (
accounts,
amount_in=None,
is_buy=false,
reuse_blockhash=false,
token_a_mint="".to_string(),
token_b_mint="".to_string(),
sell_all=false,
victim_data=None,
))]
fn new(
accounts: Vec<String>,
amount_in: Option<u64>,
is_buy: bool,
reuse_blockhash: bool,
token_a_mint: String,
token_b_mint: String,
sell_all: bool,
victim_data: Option<Vec<u8>>,
) -> Self {
Self {
accounts,
amount_in,
is_buy,
reuse_blockhash,
token_a_mint,
token_b_mint,
sell_all,
victim_data,
}
}
}
#[pymethods]
impl TradingCore {
#[new]
fn new(rpc_url: &str) -> PyResult<Self> {
let keypair = Self::load_keypair_from_env()?;
info!("Loaded keypair with public key: {}", keypair.pubkey());
Ok(Self {
client: Arc::new(RpcClient::new_with_commitment(
rpc_url.to_string(),
CommitmentConfig::processed(),
)),
keypair: Arc::new(keypair),
})
}
fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
let mut accounts: Vec<Pubkey> = Vec::new();
for (idx, acc) in params.accounts.iter().enumerate() {
let pubkey = Pubkey::from_str(acc)
.map_err(|e| PyValueError::new_err(format!("Invalid account address at index {}: {}", idx, e)))?;
accounts.push(pubkey);
}
let token_a_mint = Pubkey::from_str(¶ms.token_a_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token A mint: {}", e)))?;
let token_b_mint = Pubkey::from_str(¶ms.token_b_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token B mint: {}", e)))?;
let source_ata = if params.is_buy {
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
} else {
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
};
let destination_ata = if params.is_buy {
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
} else {
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
};
let mut instructions = vec![];
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(PRIORITY_FEE));
let amount = if let Some(amount) = params.amount_in {
amount
} else if params.sell_all {
let balance = self_clone.client.get_token_account_balance(&source_ata)
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get token balance: {}", e)))?
.amount
.parse::<u64>()
.map_err(|e| PyValueError::new_err(format!("Invalid token balance: {}", e)))?;
balance
} else {
return Err(PyValueError::new_err("No amount specified for swap"));
};
let swap_ix = self_clone.create_swap_instruction(
&accounts[0], // Program ID
&accounts, // Original accounts
amount,
params.is_buy,
source_ata,
destination_ata,
params.victim_data.as_deref(),
);
instructions.push(swap_ix);
let blockhash = self_clone.client.get_latest_blockhash()
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?;
let message = Message::new_with_blockhash(
&instructions,
Some(&self_clone.keypair.pubkey()),
&blockhash
);
let mut tx = Transaction::new_unsigned(message);
tx.try_sign(&[self_clone.keypair.as_ref()], blockhash)
.map_err(|e| PyValueError::new_err(format!("Transaction signing failed: {:?}", e)))?;
let signature = self_clone.client.send_transaction_with_config(
&tx,
solana_client::rpc_config::RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
},
)
.await
.map_err(|e| PyValueError::new_err(format!("Transaction failed: {}", e)))?;
Ok(signature.to_string())
})
}
#[pyo3(name = "get_sol_balance")]
fn get_sol_balance_py<'py>(&self, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
let balance = self_clone.client.get_balance(&self_clone.keypair.pubkey())
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get SOL balance: {}", e)))?;
Ok(balance as f64 / 1e9) // Convert lamports to SOL
})
}
#[pyo3(name = "get_wsol_balance")]
fn get_wsol_balance_py<'py>(&self, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
let wsol_account = env::var("WSOL_TOKEN_ACCOUNT")
.map_err(|_| PyValueError::new_err("WSOL_TOKEN_ACCOUNT not found"))?;
let pubkey = Pubkey::from_str(&wsol_account)
.map_err(|e| PyValueError::new_err(format!("Invalid WSOL account: {}", e)))?;
let balance = self_clone.client.get_token_account_balance(&pubkey)
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get WSOL balance: {}", e)))?;
let amount = balance.amount.parse::<u64>()
.map_err(|e| PyValueError::new_err(format!("Invalid balance format: {}", e)))?;
Ok(amount as f64 / 1e9) // Convert lamports to SOL
})
}
}
#[pymodule]
fn solana_rust_bot(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
m.add_class::<TradingCore>()?;
m.add_class::<TradeParams>()?;
Ok(())
}
Instructions for Usage
Setup: Ensure you have Rust, Cargo, and Python along with PyO3 set up in your environment.
Environment Variables: Before using the bot, set your SOLANA_PRIVATE_KEY, SOLANA_PUBLIC_KEY, and WSOL_TOKEN_ACCOUNT as environment variables.
Build: Use cargo build --release to build the library.
Integrate Python: You can now use this library in a Python environment by importing solana_rust_bot.
Testing
Make sure to test the bot in a testing environment or with a test wallet to avoid any loss of funds during development. Always validate Pubkeys and amounts before executing trades to avoid transaction errors.
Note
For deploying or utilizing the bot, ensure adherence to Solana programming best practices and review any changes or risk factors in the transaction processes, as the blockchain's libraries and protocols are regularly updated.
The provided code serves as a foundation for a Solana trading bot that allows you to execute token swaps, check wallet balances, and manage associated token accounts (ATAs). However, there are several important aspects and additional considerations to ensure that the bot can function correctly and efficiently in a production environment. Below are the key components and considerations:
Key Components
Environment Variables:
SOLANA_PRIVATE_KEY: The private key used for signing transactions.
SOLANA_PUBLIC_KEY: The public key for your Solana wallet.
WSOL_TOKEN_ACCOUNT: The public key for your wrapped SOL (WSOL) token account.
Transaction Structure:
The trading bot implements transaction creation, signing, and sending logic. Ensure that the mint addresses (for token A and token B) and accounts used in the transactions are valid and accessible.
Account Validation:
The bot needs to handle proper validation for account addresses and ensure that enough balance exists for performing trades.
Error Handling:
Robust error handling is necessary to deal with transaction failures or unexpected states, like network issues or incorrect account states.
Additional Considerations
Marketplace Protocols:
Ensure that your swap operations align with the protocol being used (in this case, Raydium is implied). Understand the accounts required for the swap, as they will vary based on the program.
Gas Fees:
Address how to handle transaction fees. You may want to ensure that there are sufficient funds in your wallet to cover transaction costs.
Testing:
It is strongly advised to test your bot on the Solana Devnet or Testnet before running it on Mainnet. This will help you catch bugs without risking actual funds.
Concurrency and Rate Limiting:
Depending on the trading strategy (especially if you are looking at high-frequency trading or multiple simultaneous trades), consider managing concurrency to avoid hitting Solana's rate limits.
Logging and Monitoring:
Implement a logging mechanism for monitoring trade executions, errors, and statuses. This can help you adjust parameters or methods based on trading performance.
Market Conditions:
Tailor your trading logic to account for market conditions, slippage, and execution timing.
Security:
Ensure that private keys are handled securely. Avoid hardcoding keys and prefer using environment variables or secure vault solutions.
Integrating with a Frontend:
If this bot will be used with a user interface, ensure to set up APIs or other means of communication between the UI and the Rust backend.
Additional Features You May Want
Withdrawal and Deposit Handling: If you're also managing funds in addition to trading, implement features to handle deposits and withdrawals.
User Configurations: Allow users to configure trading parameters, such as slippage tolerance and gas limits, directly from a configuration file or through the UI.
Periodic Balances Check: Implement a way to periodically check and report balances for active monitoring.
Summary
The provided code can serve as a starting point for executing transactions on the Solana blockchain, particularly for token swaps. To create a fully functional trading bot, you will need to integrate additional features and robust error handling, along with thorough testing to ensure its reliability in a live trading environment. Additionally, you might also consider the regulatory aspects of running a trading bot based on your jurisdiction.
To create a robust trading bot for executing buy and sell transactions using the Raydium AMM (Automated Market Maker) on Solana, it's essential to clarify several components and structures. I will modify the previous example to ensure it can handle both buying and selling of tokens through the Raydium AMM and include checks for balances, connection setup, and transaction management.
Complete lib.rs for Raydium Trading Bot
The following code provides a more comprehensive implementation, including transaction execution for both buy and sell actions, ensuring a more seamless interaction with the Raydium AMM.
In addition to the code, ensure you have the necessary environment variables set up and your dependencies configured in your Cargo.toml.
rust
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};
use spl_token;
use std::{
env,
str::FromStr,
sync::Arc,
};
use base58::FromBase58;
const COMPUTE_UNITS: u32 = 50_000;
const PRIORITY_FEE: u64 = 750_000;
#[pyclass]
#[derive(Clone)]
pub struct TradeParams {
#[pyo3(get, set)]
pub accounts: Vec<String>,
#[pyo3(get, set)]
pub amount_in: Option<u64>, // Amount to trade
#[pyo3(get, set)]
pub is_buy: bool, // true for buy, false for sell
#[pyo3(get, set)]
pub reuse_blockhash: bool,
#[pyo3(get, set)]
pub token_a_mint: String, // Mint address for token A
#[pyo3(get, set)]
pub token_b_mint: String, // Mint address for token B
#[pyo3(get, set)]
pub sell_all: bool, // If true, sell all available tokens
}
#[pyclass]
pub struct TradingCore {
client: Arc<RpcClient>,
keypair: Arc<Keypair>,
}
impl TradingCore {
fn load_keypair_from_env() -> PyResult<Keypair> {
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"))?;
let _pubkey = Pubkey::from_str(&public_key)
.map_err(|e| PyValueError::new_err(format!("Invalid public key: {}", e)))?;
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)))
}
/// 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);
let ix = spl_associated_token_account::instruction::create_associated_token_account_idempotent(
&self.keypair.pubkey(),
owner,
mint,
&spl_token::ID,
);
let blockhash = self.client.get_latest_blockhash().await
.map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?;
let mut tx = Transaction::new_with_payer(&[ix], Some(&self.keypair.pubkey()));
tx.sign(&[self.keypair.as_ref()], blockhash);
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)))
}
}
}
}
}
fn create_swap_instruction(
&self,
program_id: &Pubkey,
accounts: &[Pubkey],
amount: u64,
is_buy: bool,
source_ata: Pubkey,
destination_ata: Pubkey,
) -> Instruction {
let mut account_metas = accounts.iter().enumerate().map(|(i, pubkey)| {
if i == 0 {
solana_sdk::instruction::AccountMeta::new_readonly(*pubkey, false) // Program ID
} else {
solana_sdk::instruction::AccountMeta::new(*pubkey, i == 1) // AMM Authority (signer for the swap)
}
}).collect::<Vec<_>>();
let mut data = vec![if is_buy { /* Buying */ 9u8 } else { /* Selling */ 11u8 }];
data.extend_from_slice(&amount.to_le_bytes());
account_metas.push(solana_sdk::instruction::AccountMeta::new(source_ata, true));
account_metas.push(solana_sdk::instruction::AccountMeta::new(destination_ata, true));
Instruction {
program_id: *program_id,
accounts: account_metas,
data,
}
}
}
#[pymethods]
impl TradeParams {
#[new]
#[pyo3(signature = (
accounts,
amount_in=None,
is_buy=false,
token_a_mint="".to_string(),
token_b_mint="".to_string(),
sell_all=false,
))]
fn new(
accounts: Vec<String>,
amount_in: Option<u64>,
is_buy: bool,
token_a_mint: String,
token_b_mint: String,
sell_all: bool,
) -> Self {
Self {
accounts,
amount_in,
is_buy,
token_a_mint,
token_b_mint,
sell_all,
}
}
}
#[pymethods]
impl TradingCore {
#[new]
fn new(rpc_url: &str) -> PyResult<Self> {
let keypair = Self::load_keypair_from_env()?;
info!("Loaded keypair with public key: {}", keypair.pubkey());
Ok(Self {
client: Arc::new(RpcClient::new_with_commitment(
rpc_url.to_string(),
CommitmentConfig::processed(),
)),
keypair: Arc::new(keypair),
})
}
fn execute_trade_py<'py>(&self, params: &TradeParams, py: Python<'py>) -> PyResult<&'py PyAny> {
let self_clone = Self {
client: self.client.clone(),
keypair: self.keypair.clone(),
};
future_into_py(py, async move {
// Convert account strings to pubkeys
let mut accounts: Vec<Pubkey> = Vec::with_capacity(params.accounts.len());
for (idx, acc) in params.accounts.iter().enumerate() {
let pubkey = Pubkey::from_str(acc)
.map_err(|e| PyValueError::new_err(format!("Invalid account address at index {}: {}", idx, e)))?;
accounts.push(pubkey);
}
// Prepare token mints
let token_a_mint = Pubkey::from_str(¶ms.token_a_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token A mint: {}", e)))?;
let token_b_mint = Pubkey::from_str(¶ms.token_b_mint)
.map_err(|e| PyValueError::new_err(format!("Invalid token B mint: {}", e)))?;
// Ensure ATAs exist
let source_ata = if params.is_buy {
// For buy, source is WSOL ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
} else {
// For sell, source is token A ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
};
let destination_ata = if params.is_buy {
// For buy, destination is token A ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_a_mint).await?
} else {
// For sell, destination is WSOL ATA
self_clone.ensure_ata_exists(&self_clone.keypair.pubkey(), &token_b_mint).await?
};
let amount = if let Some(amount) = params.amount_in {
amount
} else if params.sell_all {
// Get token balance for sell_all
let balance = self_clone.client.get_token_account_balance(&source_ata)
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get token balance: {}", e)))?
.amount
.parse::<u64>()
.map_err(|e| PyValueError::new_err(format!("Invalid token balance: {}", e)))?;
balance
} else {
return Err(PyValueError::new_err("No amount specified for swap"));
};
// Create swap instruction with ATAs
let swap_ix = self_clone.create_swap_instruction(
&accounts[0], // Program ID
&accounts, // Accounts from params
amount,
params.is_buy,
source_ata,
destination_ata,
);
let blockhash = self_clone.client.get_latest_blockhash()
.await
.map_err(|e| PyValueError::new_err(format!("Failed to get blockhash: {}", e)))?;
let mut instructions = vec![];
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(COMPUTE_UNITS));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(PRIORITY_FEE));
instructions.push(swap_ix);
// Create a transaction message
let message = Message::new_with_blockhash(
&instructions,
Some(&self_clone.keypair.pubkey()),
&blockhash,
);
let mut tx = Transaction::new_unsigned(message);
tx.try_sign(&[self_clone.keypair.as_ref()], blockhash)
.map_err(|e| PyValueError::new_err(format!("Transaction signing failed: {:?}", e)))?;
// Send transaction
let signature = self_clone.client.send_transaction_with_config(
&tx,
solana_client::rpc_config::RpcSendTransactionConfig {
skip_preflight: true,
preflight_commitment: Some(CommitmentLevel::Processed),
encoding: None,
max_retries: None,
min_context_slot: None,
},
)
.await
.map_err(|e| PyValueError::new_err(format!("Transaction failed: {}", e)))?;
Ok(signature.to_string())
})
}
}
#[pymodule]
fn solana_rust_bot(_py: Python<'_>, m: &PyModule) -> PyResult<()> {
pyo3_log::init();
m.add_class::<TradingCore>()?;
m.add_class::<TradeParams>()?;
Ok(())
}
Things to Note in the Implementation:
Swap Instruction:
The logic for creating the swap instruction is implemented in the create_swap_instruction method. It adjusts depending on whether you are buying or selling. The accounts used should align with the Raydium AMM program's requirements.
Ensuring ATAs:
The bot ensures that the associated token accounts (ATAs) for the tokens involved are created if they do not already exist.
Transaction Management:
The bot prepares a transaction that includes computing budget instructions to limit compute units and set the priority fee.
Handling Buy/Sell Logic:
The execution logic in execute_trade_py differentiates between buy and sell operations using the is_buy parameter.
Account Addresses:
The account addresses for the Raydium AMM program and any other associated accounts must be included in the accounts vector passed to TradeParams.
Additional Considerations:
Testing on Devnet: Before deploying to the mainnet, ensure extensive testing on Solana’s devnet.
Network Fees: Make sure to keep track of transaction fees and ensure your wallet has enough SOL to cover them.
Handling Slippage: You can extend the logic to handle trade slippage, which might be a crucial factor in actual trading scenarios.
Log and Monitor: Implement monitoring and logging of operations for troubleshooting.
Conclusion
This implementation provides a comprehensive starting point for executing buy and sell operations on Raydium AMM. Adjustments may need to be made based on the exact requirements of the AMM and the specifics of the transactions being executed, especially regarding the accounts and data used in the swaps.