2025-09-08 17:12:29 +08:00
|
|
|
use dashmap::DashMap;
|
|
|
|
|
use once_cell::sync::Lazy;
|
|
|
|
|
use smallvec::SmallVec;
|
2025-06-17 23:32:20 +08:00
|
|
|
use solana_sdk::{compute_budget::ComputeBudgetInstruction, instruction::Instruction};
|
|
|
|
|
|
2025-09-09 00:50:24 +08:00
|
|
|
/// Cache key containing all parameters for compute budget instructions
|
2025-09-08 17:12:29 +08:00
|
|
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
|
|
|
|
struct ComputeBudgetCacheKey {
|
|
|
|
|
data_size_limit: u32,
|
|
|
|
|
unit_price: u64,
|
|
|
|
|
unit_limit: u32,
|
|
|
|
|
is_buy: bool,
|
|
|
|
|
}
|
2025-06-17 23:32:20 +08:00
|
|
|
|
2025-09-09 00:50:24 +08:00
|
|
|
/// Global cache storing compute budget instructions
|
|
|
|
|
/// Uses DashMap for high-performance lock-free concurrent access
|
2025-09-08 17:12:29 +08:00
|
|
|
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 3]>>> =
|
|
|
|
|
Lazy::new(|| DashMap::new());
|
|
|
|
|
|
|
|
|
|
#[inline(always)]
|
|
|
|
|
pub fn compute_budget_instructions(
|
2025-09-17 00:10:33 +08:00
|
|
|
unit_price: u64,
|
|
|
|
|
unit_limit: u32,
|
2025-06-17 23:32:20 +08:00
|
|
|
data_size_limit: u32,
|
2025-09-07 17:22:58 +08:00
|
|
|
is_buy: bool,
|
2025-09-08 17:12:29 +08:00
|
|
|
) -> SmallVec<[Instruction; 3]> {
|
2025-09-09 00:50:24 +08:00
|
|
|
// Create cache key
|
2025-09-17 00:10:33 +08:00
|
|
|
let cache_key = ComputeBudgetCacheKey {
|
|
|
|
|
data_size_limit,
|
|
|
|
|
unit_price: unit_price,
|
|
|
|
|
unit_limit: unit_limit,
|
|
|
|
|
is_buy,
|
|
|
|
|
};
|
2025-09-08 17:12:29 +08:00
|
|
|
|
2025-09-09 00:50:24 +08:00
|
|
|
// Try to get from cache first
|
2025-09-08 17:12:29 +08:00
|
|
|
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
|
|
|
|
return cached_insts.clone();
|
2025-09-07 17:22:58 +08:00
|
|
|
}
|
2025-09-08 17:12:29 +08:00
|
|
|
|
2025-09-09 00:50:24 +08:00
|
|
|
// Cache miss, generate new instructions
|
2025-09-08 17:12:29 +08:00
|
|
|
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),
|
|
|
|
|
]);
|
|
|
|
|
|
2025-09-09 00:50:24 +08:00
|
|
|
// Store result in cache
|
2025-09-08 17:12:29 +08:00
|
|
|
let insts_clone = insts.clone();
|
|
|
|
|
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
|
|
|
|
|
|
|
|
|
|
insts
|
2025-06-17 23:32:20 +08:00
|
|
|
}
|