perf: optimize trade executor performance and reduce memory usage
- Implement singleton pattern for TradeFactory - Replace TradeTimer with direct Instant measurements - Optimize PumpFun instruction building and parallel execution - Reduce unnecessary clones and improve memory allocation - Simplify address lookup table management
This commit is contained in:
@@ -1,10 +1,9 @@
|
||||
use anyhow::Result;
|
||||
use std::sync::Arc;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use super::{
|
||||
parallel::parallel_execute_with_tips,
|
||||
params::{BuyParams, SellParams},
|
||||
timer::TradeTimer,
|
||||
traits::{InstructionBuilder, TradeExecutor},
|
||||
};
|
||||
use crate::{swqos::SwqosClient, trading::middleware::MiddlewareManager};
|
||||
@@ -38,26 +37,12 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
if data_size_limit == 0 {
|
||||
data_size_limit = MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT;
|
||||
}
|
||||
let timer = TradeTimer::new("Building buy transaction instructions");
|
||||
|
||||
// Validate parameters - convert to BuyParams for validation
|
||||
let buy_params = BuyParams {
|
||||
rpc: params.rpc,
|
||||
payer: params.payer.clone(),
|
||||
mint: params.mint,
|
||||
sol_amount: params.sol_amount,
|
||||
slippage_basis_points: params.slippage_basis_points,
|
||||
priority_fee: params.priority_fee.clone(),
|
||||
lookup_table_key: params.lookup_table_key,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
data_size_limit: data_size_limit,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: params.protocol_params.clone(),
|
||||
};
|
||||
let start = Instant::now();
|
||||
|
||||
// Build instructions
|
||||
let instructions = self.instruction_builder.build_buy_instructions(&buy_params).await?;
|
||||
let final_instructions = match middleware_manager.clone() {
|
||||
// Build instructions directly from params to avoid unnecessary cloning
|
||||
let instructions = self.instruction_builder.build_buy_instructions(¶ms).await?;
|
||||
let final_instructions = match &middleware_manager {
|
||||
Some(middleware_manager) => middleware_manager
|
||||
.apply_middlewares_process_protocol_instructions(
|
||||
instructions,
|
||||
@@ -67,19 +52,19 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
None => instructions,
|
||||
};
|
||||
|
||||
timer.finish();
|
||||
println!("Building buy transaction instructions time cost: {:?}", start.elapsed());
|
||||
|
||||
// Execute transactions in parallel
|
||||
parallel_execute_with_tips(
|
||||
swqos_clients,
|
||||
params.payer,
|
||||
final_instructions,
|
||||
params.priority_fee,
|
||||
Arc::new(params.priority_fee),
|
||||
params.lookup_table_key,
|
||||
params.recent_blockhash,
|
||||
data_size_limit,
|
||||
middleware_manager,
|
||||
self.protocol_name.to_string(),
|
||||
self.protocol_name,
|
||||
true,
|
||||
params.wait_transaction_confirmed,
|
||||
true,
|
||||
@@ -95,26 +80,11 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
swqos_clients: Vec<Arc<SwqosClient>>,
|
||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
) -> Result<()> {
|
||||
let timer = TradeTimer::new("Building sell transaction instructions");
|
||||
let start = Instant::now();
|
||||
|
||||
// Convert to SellParams for instruction building
|
||||
let sell_params = SellParams {
|
||||
rpc: params.rpc,
|
||||
payer: params.payer.clone(),
|
||||
mint: params.mint,
|
||||
token_amount: params.token_amount,
|
||||
slippage_basis_points: params.slippage_basis_points,
|
||||
priority_fee: params.priority_fee.clone(),
|
||||
lookup_table_key: params.lookup_table_key,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: params.protocol_params.clone(),
|
||||
with_tip: params.with_tip,
|
||||
};
|
||||
|
||||
// Build instructions
|
||||
let instructions = self.instruction_builder.build_sell_instructions(&sell_params).await?;
|
||||
let final_instructions = match middleware_manager.clone() {
|
||||
// Build instructions directly from params to avoid unnecessary cloning
|
||||
let instructions = self.instruction_builder.build_sell_instructions(¶ms).await?;
|
||||
let final_instructions = match &middleware_manager {
|
||||
Some(middleware_manager) => middleware_manager
|
||||
.apply_middlewares_process_protocol_instructions(
|
||||
instructions,
|
||||
@@ -124,19 +94,19 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
None => instructions,
|
||||
};
|
||||
|
||||
timer.finish();
|
||||
println!("Building sell transaction instructions time cost: {:?}", start.elapsed());
|
||||
|
||||
// Execute transactions in parallel
|
||||
parallel_execute_with_tips(
|
||||
swqos_clients,
|
||||
params.payer,
|
||||
final_instructions,
|
||||
params.priority_fee,
|
||||
Arc::new(params.priority_fee),
|
||||
params.lookup_table_key,
|
||||
params.recent_blockhash,
|
||||
0,
|
||||
middleware_manager,
|
||||
self.protocol_name.to_string(),
|
||||
self.protocol_name,
|
||||
false,
|
||||
params.wait_transaction_confirmed,
|
||||
params.with_tip,
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
pub mod params;
|
||||
pub mod traits;
|
||||
pub mod executor;
|
||||
pub mod parallel;
|
||||
pub mod timer;
|
||||
pub mod parallel;
|
||||
@@ -1,14 +1,14 @@
|
||||
use anyhow::{anyhow, Result};
|
||||
use solana_hash::Hash;
|
||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signature::Keypair};
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
use std::{str::FromStr, sync::Arc, time::Instant};
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::task::JoinHandle;
|
||||
|
||||
use crate::{
|
||||
common::PriorityFee,
|
||||
swqos::{SwqosClient, SwqosType, TradeType},
|
||||
trading::{common::build_transaction, core::timer::TradeTimer, MiddlewareManager},
|
||||
trading::{common::build_transaction, MiddlewareManager},
|
||||
};
|
||||
|
||||
/// Generic function for parallel transaction execution
|
||||
@@ -16,26 +16,34 @@ pub async fn parallel_execute_with_tips(
|
||||
swqos_clients: Vec<Arc<SwqosClient>>,
|
||||
payer: Arc<Keypair>,
|
||||
instructions: Vec<Instruction>,
|
||||
priority_fee: PriorityFee,
|
||||
priority_fee: Arc<PriorityFee>,
|
||||
lookup_table_key: Option<Pubkey>,
|
||||
recent_blockhash: Hash,
|
||||
data_size_limit: u32,
|
||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
protocol_name: String,
|
||||
protocol_name: &'static str,
|
||||
is_buy: bool,
|
||||
wait_transaction_confirmed: bool,
|
||||
with_tip: bool,
|
||||
) -> Result<()> {
|
||||
let cores = core_affinity::get_core_ids().unwrap();
|
||||
let mut handles: Vec<JoinHandle<Result<()>>> = vec![];
|
||||
|
||||
if is_buy && swqos_clients.len() > priority_fee.buy_tip_fees.len() {
|
||||
let mut handles: Vec<JoinHandle<Result<()>>> = Vec::with_capacity(swqos_clients.len());
|
||||
if is_buy
|
||||
&& (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"));
|
||||
}
|
||||
if !is_buy && swqos_clients.len() > priority_fee.sell_tip_fees.len() {
|
||||
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"));
|
||||
}
|
||||
|
||||
let instructions = Arc::new(instructions);
|
||||
|
||||
for i in 0..swqos_clients.len() {
|
||||
let swqos_client = swqos_clients[i].clone();
|
||||
if !with_tip && !matches!(swqos_client.get_swqos_type(), SwqosType::Default) {
|
||||
@@ -47,43 +55,36 @@ pub async fn parallel_execute_with_tips(
|
||||
let core_id = cores[i % cores.len()];
|
||||
|
||||
let middleware_manager = middleware_manager.clone();
|
||||
let protocol_name = protocol_name.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
core_affinity::set_for_current(core_id);
|
||||
|
||||
let mut timer = TradeTimer::new(format!(
|
||||
"Building transaction instructions: {:?}",
|
||||
swqos_client.get_swqos_type()
|
||||
));
|
||||
let swqos_type = swqos_client.get_swqos_type();
|
||||
let mut start = Instant::now();
|
||||
|
||||
let tip_account = swqos_client.get_tip_account()?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
|
||||
if priority_fee.buy_tip_fees.len() == 0 {
|
||||
return Err(anyhow!("buy_tip_fees is empty"));
|
||||
}
|
||||
let tip_account_str = swqos_client.get_tip_account()?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account_str).unwrap_or_default());
|
||||
let tip_amount = priority_fee.buy_tip_fees[i];
|
||||
|
||||
let transaction = build_transaction(
|
||||
payer,
|
||||
&priority_fee,
|
||||
instructions,
|
||||
(*instructions).clone(),
|
||||
lookup_table_key,
|
||||
recent_blockhash,
|
||||
data_size_limit,
|
||||
middleware_manager,
|
||||
protocol_name,
|
||||
is_buy,
|
||||
swqos_client.get_swqos_type() != SwqosType::Default,
|
||||
swqos_type != SwqosType::Default,
|
||||
&tip_account,
|
||||
tip_amount,
|
||||
)
|
||||
.await?;
|
||||
|
||||
timer.stage(format!(
|
||||
"Submitting transaction instructions: {:?}",
|
||||
swqos_client.get_swqos_type()
|
||||
));
|
||||
println!("Building transaction instructions: {:?} {:?}", swqos_type, start.elapsed());
|
||||
|
||||
start = Instant::now();
|
||||
|
||||
swqos_client
|
||||
.send_transaction(
|
||||
@@ -92,7 +93,8 @@ pub async fn parallel_execute_with_tips(
|
||||
)
|
||||
.await?;
|
||||
|
||||
timer.finish();
|
||||
println!("Submitting transaction instructions: {:?} {:?}", swqos_type, start.elapsed());
|
||||
|
||||
Ok::<(), anyhow::Error>(())
|
||||
});
|
||||
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
use std::time::Instant;
|
||||
|
||||
/// Trade time measurement tool
|
||||
#[derive(Clone)]
|
||||
pub struct TradeTimer {
|
||||
start_time: Instant,
|
||||
stage: String,
|
||||
}
|
||||
|
||||
impl TradeTimer {
|
||||
/// Create a new timer
|
||||
pub fn new(stage: impl Into<String>) -> Self {
|
||||
Self { start_time: Instant::now(), stage: stage.into() }
|
||||
}
|
||||
|
||||
/// Record current stage time and start a new stage
|
||||
pub fn stage(&mut self, new_stage: impl Into<String>) {
|
||||
let elapsed = self.start_time.elapsed();
|
||||
println!(" {} time cost: {:?}", self.stage, elapsed);
|
||||
|
||||
self.start_time = Instant::now();
|
||||
self.stage = new_stage.into();
|
||||
}
|
||||
|
||||
/// Complete timing and output final time cost
|
||||
pub fn finish(mut self) {
|
||||
let elapsed = self.start_time.elapsed();
|
||||
println!(" {} time cost: {:?}", self.stage, elapsed);
|
||||
self.stage.clear(); // Clear stage to avoid duplicate printing in Drop
|
||||
}
|
||||
|
||||
/// Get the elapsed time of current stage (without resetting the timer)
|
||||
pub fn elapsed(&self) -> std::time::Duration {
|
||||
self.start_time.elapsed()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for TradeTimer {
|
||||
fn drop(&mut self) {
|
||||
if !self.stage.is_empty() {
|
||||
let elapsed = self.start_time.elapsed();
|
||||
println!(" {} time cost: {:?}", self.stage, elapsed);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user