feat: Add caching system and performance optimizations

- Add fast_fn module with global caches for PDA, ATA, and instruction operations
- Implement memory-efficient caches using CLRU and parking_lot for thread-safe access
- Optimize compute budget instruction generation with caching
- Replace std::sync::Mutex with parking_lot::Mutex for better performance
- Add dedicated caching for PumpFun PDAs and associated token addresses
- Improve transaction building with batch signature optimization
- Add new dependencies: clru, smallvec, parking_lot for cache infrastructure
- Remove unused utility functions in pumpfun module
- Enhance error messages for tip fee configuration validation
This commit is contained in:
ysq
2025-09-08 17:12:29 +08:00
parent 31b5e2855b
commit 93c133a9ea
12 changed files with 356 additions and 169 deletions
+49 -18
View File
@@ -1,28 +1,59 @@
use crate::common::PriorityFee;
use dashmap::DashMap;
use once_cell::sync::Lazy;
use smallvec::SmallVec;
use solana_sdk::{compute_budget::ComputeBudgetInstruction, instruction::Instruction};
use crate::common::PriorityFee;
/// 缓存键,包含计算预算指令的所有参数
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
struct ComputeBudgetCacheKey {
data_size_limit: u32,
unit_price: u64,
unit_limit: u32,
is_buy: bool,
}
/// 为交易添加计算预算指令
pub fn add_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
/// 全局缓存,存储计算预算指令
/// 使用 DashMap 提供高性能的无锁并发访问
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 3]>>> =
Lazy::new(|| DashMap::new());
#[inline(always)]
pub fn compute_budget_instructions(
priority_fee: &PriorityFee,
data_size_limit: u32,
is_rpc: bool,
is_buy: bool,
) {
if is_buy {
instructions
.push(ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(data_size_limit));
}
if is_rpc {
instructions
.push(ComputeBudgetInstruction::set_compute_unit_price(priority_fee.rpc_unit_price));
instructions
.push(ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.rpc_unit_limit));
) -> SmallVec<[Instruction; 3]> {
let (unit_price, unit_limit) = if is_rpc {
(priority_fee.rpc_unit_price, priority_fee.rpc_unit_limit)
} else {
instructions
.push(ComputeBudgetInstruction::set_compute_unit_price(priority_fee.tip_unit_price));
instructions
.push(ComputeBudgetInstruction::set_compute_unit_limit(priority_fee.tip_unit_limit));
(priority_fee.tip_unit_price, priority_fee.tip_unit_limit)
};
// 创建缓存键
let cache_key = ComputeBudgetCacheKey { data_size_limit, unit_price, unit_limit, is_buy };
// 先尝试从缓存中获取
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
return cached_insts.clone();
}
// 缓存未命中,生成新的指令
let mut insts = SmallVec::<[Instruction; 3]>::new();
if is_buy {
insts.push(ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(data_size_limit));
}
insts.extend([
ComputeBudgetInstruction::set_compute_unit_price(unit_price),
ComputeBudgetInstruction::set_compute_unit_limit(unit_limit),
]);
// 将结果存入缓存
let insts_clone = insts.clone();
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
insts
}
+11 -7
View File
@@ -13,7 +13,7 @@ use std::sync::Arc;
use super::{
address_lookup_manager::get_address_lookup_table_accounts,
compute_budget_manager::add_compute_budget_instructions,
compute_budget_manager::compute_budget_instructions,
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
};
use crate::{common::PriorityFee, trading::MiddlewareManager};
@@ -43,7 +43,12 @@ pub async fn build_transaction(
}
// 添加计算预算指令
add_compute_budget_instructions(&mut instructions, priority_fee, data_size_limit, true, is_buy);
instructions.extend(compute_budget_instructions(
priority_fee,
data_size_limit,
!with_tip,
is_buy,
));
// 添加业务指令
instructions.extend(business_instructions);
@@ -102,9 +107,8 @@ async fn build_versioned_transaction(
&address_lookup_table_accounts,
blockhash,
)?;
let versioned_message: VersionedMessage = VersionedMessage::V0(v0_message.clone());
let transaction = VersionedTransaction::try_new(versioned_message, &[payer.as_ref()])?;
Ok(transaction)
let versioned_msg = VersionedMessage::V0(v0_message);
let msg_bytes = versioned_msg.serialize();
let signature = payer.try_sign_message(&msg_bytes).expect("sign failed");
Ok(VersionedTransaction { signatures: vec![signature], message: versioned_msg })
}
+12 -4
View File
@@ -32,14 +32,14 @@ pub async fn parallel_execute_with_tips(
&& (swqos_clients.len() > priority_fee.buy_tip_fees.len()
|| priority_fee.buy_tip_fees.is_empty())
{
return Err(anyhow!("Number of tip clients exceeds the configured buy tip fees"));
return Err(anyhow!("Number of tip clients exceeds the configured buy tip fees. Please configure buy_tip_fees to match swqos_clients"));
}
if !is_buy
&& !with_tip
&& (swqos_clients.len() > priority_fee.sell_tip_fees.len()
|| priority_fee.sell_tip_fees.is_empty())
{
return Err(anyhow!("Number of tip clients exceeds the configured sell tip fees"));
return Err(anyhow!("Number of tip clients exceeds the configured sell tip fees. Please configure sell_tip_fees to match swqos_clients"));
}
let instructions = Arc::new(instructions);
@@ -82,7 +82,11 @@ pub async fn parallel_execute_with_tips(
)
.await?;
println!("Building transaction instructions: {:?} {:?}", swqos_type, start.elapsed());
println!(
"[{:?}] - Building transaction instructions: {:?}",
swqos_type,
start.elapsed()
);
start = Instant::now();
@@ -93,7 +97,11 @@ pub async fn parallel_execute_with_tips(
)
.await?;
println!("Submitting transaction instructions: {:?} {:?}", swqos_type, start.elapsed());
println!(
"[{:?}] - Submitting transaction instructions: {:?}",
swqos_type,
start.elapsed()
);
Ok::<(), anyhow::Error>(())
});
+4
View File
@@ -50,6 +50,7 @@ pub struct SellParams {
#[derive(Clone)]
pub struct PumpFunParams {
pub bonding_curve: Arc<BondingCurveAccount>,
pub associated_bonding_curve: Pubkey,
pub creator_vault: Pubkey,
/// Whether to close token account when selling, only effective during sell operations
pub close_token_account_when_sell: Option<bool>,
@@ -59,6 +60,7 @@ impl PumpFunParams {
pub fn immediate_sell(creator_vault: Pubkey, close_token_account_when_sell: bool) -> Self {
Self {
bonding_curve: Arc::new(BondingCurveAccount { ..Default::default() }),
associated_bonding_curve: Pubkey::default(),
creator_vault: creator_vault,
close_token_account_when_sell: Some(close_token_account_when_sell),
}
@@ -76,6 +78,7 @@ impl PumpFunParams {
);
Self {
bonding_curve: Arc::new(bonding_curve),
associated_bonding_curve: event.associated_bonding_curve,
creator_vault: event.creator_vault,
close_token_account_when_sell: close_token_account_when_sell,
}
@@ -88,6 +91,7 @@ impl PumpFunParams {
let bonding_curve = BondingCurveAccount::from_trade(event);
Self {
bonding_curve: Arc::new(bonding_curve),
associated_bonding_curve: event.associated_bonding_curve,
creator_vault: event.creator_vault,
close_token_account_when_sell: close_token_account_when_sell,
}