perf: P0/P1/P2 low-latency and maintainability improvements

P0:
- blockhash/nonce: get_transaction_blockhash returns Result; buy/sell entry validation
- Bonk sell: remove RPC get_token_balance from build path; require caller to pass input_amount
- Hot path: drop redundant dex_type/protocol_params clone; tip via sol_f64_to_lamports (no String)
- compute_budget cache uses Arc; extend_compute_budget_instructions avoids SmallVec clone

P1:
- middleware protocol_name takes &str; executor destructures result once to avoid signatures/submit_timings clone
- Error messages include dex context; params use Copy for Pubkey; pumpswap utils clone only Pool for pools[0]

P2:
- transaction_pool capacity constants; TIP_ACCOUNT_CACHE marked allow(dead_code)
- Fix error copy in raydium_amm_v4 / meteora_damm_v2 to correct protocol names

Made-with: Cursor
This commit is contained in:
Wood
2026-03-08 01:05:27 +08:00
parent e32e7ee6ab
commit 9f79e865ab
17 changed files with 397 additions and 294 deletions
+32 -22
View File
@@ -3,6 +3,7 @@ use once_cell::sync::Lazy;
use smallvec::SmallVec;
use solana_sdk::instruction::Instruction;
use solana_compute_budget_interface::ComputeBudgetInstruction;
use std::sync::Arc;
/// Cache key containing all parameters for compute budget instructions
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -11,43 +12,52 @@ struct ComputeBudgetCacheKey {
unit_limit: u32,
}
/// Global cache storing compute budget instructions
/// Uses DashMap for high-performance lock-free concurrent access
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 2]>>> =
/// Global cache storing compute budget instructions (Arc to avoid clone on hit).
/// Uses DashMap for high-performance lock-free concurrent access.
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, Arc<SmallVec<[Instruction; 2]>>>> =
Lazy::new(|| DashMap::new());
/// Extend `instructions` with compute budget instructions; on cache hit extends from cached Arc (no SmallVec clone).
#[inline(always)]
pub fn compute_budget_instructions(
pub fn extend_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
unit_price: u64,
unit_limit: u32,
) -> SmallVec<[Instruction; 2]> {
// Create cache key
let cache_key = ComputeBudgetCacheKey {
unit_price: unit_price,
unit_limit: unit_limit,
};
) {
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
// Try to get from cache first
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
return cached_insts.clone();
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
instructions.extend(cached.iter().cloned());
return;
}
// Cache miss, generate new instructions
let mut insts = SmallVec::<[Instruction; 2]>::new();
// Only add compute unit price instruction if > 0
if unit_price > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
}
// Only add compute unit limit instruction if > 0
if unit_limit > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
}
let arc = Arc::new(insts);
instructions.extend(arc.iter().cloned());
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
}
// Store result in cache
let insts_clone = insts.clone();
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
/// Returns compute budget instructions (allocates on cache hit; prefer `extend_compute_budget_instructions` on hot path).
#[inline(always)]
pub fn compute_budget_instructions(unit_price: u64, unit_limit: u32) -> SmallVec<[Instruction; 2]> {
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
return (**cached).clone();
}
let mut insts = SmallVec::<[Instruction; 2]>::new();
if unit_price > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
}
if unit_limit > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
}
let arc = Arc::new(insts.clone());
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
insts
}
+14 -11
View File
@@ -12,9 +12,7 @@ use crate::common::nonce_cache::DurableNonceInfo;
pub fn add_nonce_instruction(
instructions: &mut Vec<Instruction>,
payer: &Keypair,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
durable_nonce: Option<DurableNonceInfo>,
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<(), anyhow::Error> {
if let Some(durable_nonce) = durable_nonce {
let nonce_advance_ix = advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
@@ -24,17 +22,22 @@ pub fn add_nonce_instruction(
Ok(())
}
/// Get blockhash for transaction
/// If nonce account is used, return blockhash from nonce, otherwise return the provided recent_blockhash
/// Get blockhash for transaction.
/// If nonce account is used, returns blockhash from nonce; otherwise returns the provided recent_blockhash.
/// Returns error when neither durable_nonce nor recent_blockhash is set (caller must provide one for low latency).
pub fn get_transaction_blockhash(
recent_blockhash: Option<Hash>,
durable_nonce: Option<DurableNonceInfo>,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
) -> Hash {
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<Hash, anyhow::Error> {
if let Some(durable_nonce) = durable_nonce {
durable_nonce.current_nonce.unwrap()
durable_nonce
.current_nonce
.ok_or_else(|| anyhow::anyhow!("durable_nonce.current_nonce is None"))
} else if let Some(hash) = recent_blockhash {
Ok(hash)
} else {
recent_blockhash.unwrap()
Err(anyhow::anyhow!(
"Must provide either recent_blockhash or durable_nonce for transaction"
))
}
}
+31 -40
View File
@@ -1,70 +1,66 @@
use solana_hash::Hash;
use solana_sdk::{
instruction::Instruction, message::AddressLookupTableAccount, native_token::sol_str_to_lamports, pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::VersionedTransaction
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
signature::Keypair, signer::Signer, transaction::VersionedTransaction,
};
use solana_system_interface::instruction::transfer;
use std::sync::Arc;
use super::{
compute_budget_manager::compute_budget_instructions,
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
};
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
use crate::{
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
trading::{MiddlewareManager, core::transaction_pool::{acquire_builder, release_builder}},
};
/// Convert SOL amount (f64) to lamports without string allocation (hot path).
#[inline(always)]
fn sol_f64_to_lamports(sol: f64) -> u64 {
if sol <= 0.0 {
return 0;
}
let lamports = sol * 1_000_000_000.0;
(lamports.min(u64::MAX as f64)).round() as u64
}
/// Build standard RPC transaction.
/// Takes `business_instructions` by reference to avoid per-task Vec clone in execute_parallel.
/// Takes Arc/context by reference to avoid clone in worker hot path (Arc::clone is cheap but ref is zero-cost).
pub async fn build_transaction(
payer: Arc<Keypair>,
_rpc: Option<Arc<SolanaRpcClient>>,
payer: &Arc<Keypair>,
_rpc: Option<&Arc<SolanaRpcClient>>,
unit_limit: u32,
unit_price: u64,
business_instructions: &[Instruction],
address_lookup_table_account: Option<AddressLookupTableAccount>,
address_lookup_table_account: Option<&AddressLookupTableAccount>,
recent_blockhash: Option<Hash>,
middleware_manager: Option<Arc<MiddlewareManager>>,
middleware_manager: Option<&Arc<MiddlewareManager>>,
protocol_name: &str,
is_buy: bool,
with_tip: bool,
tip_account: &Pubkey,
tip_amount: f64,
durable_nonce: Option<DurableNonceInfo>,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = Vec::with_capacity(business_instructions.len() + 5);
// Add nonce instruction
if let Err(e) =
add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce.clone())
{
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce) {
return Err(e);
}
// Add tip transfer instruction
if with_tip && tip_amount > 0.0 {
instructions.push(transfer(
&payer.pubkey(),
tip_account,
sol_str_to_lamports(tip_amount.to_string().as_str()).unwrap_or(0),
));
let tip_lamports = sol_f64_to_lamports(tip_amount);
instructions.push(transfer(&payer.pubkey(), tip_account, tip_lamports));
}
// Add compute budget instructions
instructions.extend(compute_budget_instructions(
super::compute_budget_manager::extend_compute_budget_instructions(
&mut instructions,
unit_price,
unit_limit,
));
);
// Add business instructions (clone only here; avoids per-task Vec clone in execute_parallel)
instructions.extend_from_slice(business_instructions);
// Get blockhash for transaction
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce.clone());
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce)?;
// Build transaction
build_versioned_transaction(
payer,
instructions,
@@ -77,23 +73,18 @@ pub async fn build_transaction(
.await
}
/// Low-level function for building versioned transactions
async fn build_versioned_transaction(
payer: Arc<Keypair>,
payer: &Arc<Keypair>,
instructions: Vec<Instruction>,
address_lookup_table_account: Option<AddressLookupTableAccount>,
address_lookup_table_account: Option<&AddressLookupTableAccount>,
blockhash: Hash,
middleware_manager: Option<Arc<MiddlewareManager>>,
middleware_manager: Option<&Arc<MiddlewareManager>>,
protocol_name: &str,
is_buy: bool,
) -> Result<VersionedTransaction, anyhow::Error> {
let full_instructions = match middleware_manager {
Some(middleware_manager) => middleware_manager
.apply_middlewares_process_full_instructions(
instructions,
protocol_name.to_string(),
is_buy,
)?,
.apply_middlewares_process_full_instructions(instructions, protocol_name, is_buy)?,
None => instructions,
};
@@ -108,7 +99,7 @@ async fn build_versioned_transaction(
);
let msg_bytes = versioned_msg.serialize();
let signature = payer.try_sign_message(&msg_bytes).expect("sign failed");
let signature = payer.as_ref().try_sign_message(&msg_bytes).expect("sign failed");
let tx = VersionedTransaction { signatures: vec![signature], message: versioned_msg };
// 归还构建器到池