refactor: optimize trading execution architecture and add wSOL management

- Simplify TradeExecutor interface by integrating middleware and swqos clients into params
- Refactor parallel execution module with dedicated buy/sell execute functions
- Add SOL wrapping/unwrapping functionality for wSOL management
- Remove redundant parameter passing in sell operations
- Delete example main.rs file
- Optimize transaction building with integrated parameter structures

BREAKING CHANGE: TradeExecutor interface simplified, middleware and swqos_clients now passed through params
This commit is contained in:
ysq
2025-09-09 17:02:24 +08:00
parent b9fa2f2f0f
commit 48a6c6283a
34 changed files with 586 additions and 853 deletions
+11 -11
View File
@@ -14,13 +14,13 @@ pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]>
);
let mut insts = SmallVec::<[Instruction; 3]>::new();
insts.extend(create_associated_token_account_idempotent_fast(
&payer,
&payer,
&crate::constants::WSOL_TOKEN_ACCOUNT,
&crate::constants::TOKEN_PROGRAM,
));
insts.extend([
create_associated_token_account_idempotent_fast(
&payer,
&payer,
&crate::constants::WSOL_TOKEN_ACCOUNT,
&crate::constants::TOKEN_PROGRAM,
),
transfer(&payer, &wsol_token_account, amount_in),
spl_token::instruction::sync_native(&crate::constants::TOKEN_PROGRAM, &wsol_token_account)
.unwrap(),
@@ -29,33 +29,33 @@ pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]>
insts
}
pub fn close_wsol(payer: &Pubkey) -> Instruction {
pub fn close_wsol(payer: &Pubkey) -> Vec<Instruction> {
let wsol_token_account =
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
&payer,
&crate::constants::WSOL_TOKEN_ACCOUNT,
&crate::constants::TOKEN_PROGRAM,
);
crate::common::fast_fn::get_cached_instruction(
crate::common::fast_fn::get_cached_instructions(
crate::common::fast_fn::InstructionCacheKey::CloseWsolAccount {
payer: *payer,
wsol_token_account,
},
|| {
close_account(
vec![close_account(
&crate::constants::TOKEN_PROGRAM,
&wsol_token_account,
&payer,
&payer,
&[],
)
.unwrap()
.unwrap()]
},
)
}
#[inline]
pub fn create_wsol_ata(payer: &Pubkey) -> Instruction {
pub fn create_wsol_ata(payer: &Pubkey) -> Vec<Instruction> {
create_associated_token_account_idempotent_fast(
&payer,
&payer,
+8 -53
View File
@@ -1,14 +1,12 @@
use anyhow::Result;
use std::{sync::Arc, time::Instant};
use crate::trading::core::parallel::{buy_parallel_execute, sell_parallel_execute};
use super::{
parallel::parallel_execute_with_tips,
params::{BuyParams, SellParams},
traits::{InstructionBuilder, TradeExecutor},
};
use crate::{swqos::SwqosClient, trading::middleware::MiddlewareManager};
const MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT: u32 = 256 * 1024;
/// Generic trade executor implementation
pub struct GenericTradeExecutor {
@@ -27,22 +25,12 @@ impl GenericTradeExecutor {
#[async_trait::async_trait]
impl TradeExecutor for GenericTradeExecutor {
async fn buy_with_tip(
&self,
params: BuyParams,
swqos_clients: Vec<Arc<SwqosClient>>,
middleware_manager: Option<Arc<MiddlewareManager>>,
) -> Result<()> {
let mut data_size_limit = params.data_size_limit;
if data_size_limit == 0 {
data_size_limit = MAX_LOADED_ACCOUNTS_DATA_SIZE_LIMIT;
}
async fn buy_with_tip(&self, params: BuyParams) -> Result<()> {
let start = Instant::now();
// Build instructions directly from params to avoid unnecessary cloning
let instructions = self.instruction_builder.build_buy_instructions(&params).await?;
let final_instructions = match &middleware_manager {
let final_instructions = match &params.middleware_manager {
Some(middleware_manager) => middleware_manager
.apply_middlewares_process_protocol_instructions(
instructions,
@@ -55,36 +43,17 @@ impl TradeExecutor for GenericTradeExecutor {
println!("Building buy transaction instructions time cost: {:?}", start.elapsed());
// Execute transactions in parallel
parallel_execute_with_tips(
swqos_clients,
params.payer,
final_instructions,
Arc::new(params.priority_fee),
params.lookup_table_key,
params.recent_blockhash,
data_size_limit,
middleware_manager,
self.protocol_name,
true,
params.wait_transaction_confirmed,
true,
)
.await?;
buy_parallel_execute(params, final_instructions, self.protocol_name).await?;
Ok(())
}
async fn sell_with_tip(
&self,
params: SellParams,
swqos_clients: Vec<Arc<SwqosClient>>,
middleware_manager: Option<Arc<MiddlewareManager>>,
) -> Result<()> {
async fn sell_with_tip(&self, params: SellParams) -> Result<()> {
let start = Instant::now();
// Build instructions directly from params to avoid unnecessary cloning
let instructions = self.instruction_builder.build_sell_instructions(&params).await?;
let final_instructions = match &middleware_manager {
let final_instructions = match &params.middleware_manager {
Some(middleware_manager) => middleware_manager
.apply_middlewares_process_protocol_instructions(
instructions,
@@ -97,21 +66,7 @@ impl TradeExecutor for GenericTradeExecutor {
println!("Building sell transaction instructions time cost: {:?}", start.elapsed());
// Execute transactions in parallel
parallel_execute_with_tips(
swqos_clients,
params.payer,
final_instructions,
Arc::new(params.priority_fee),
params.lookup_table_key,
params.recent_blockhash,
0,
middleware_manager,
self.protocol_name,
false,
params.wait_transaction_confirmed,
params.with_tip,
)
.await?;
sell_parallel_execute(params, final_instructions, self.protocol_name).await?;
Ok(())
}
+46 -2
View File
@@ -8,11 +8,55 @@ use tokio::task::JoinHandle;
use crate::{
common::PriorityFee,
swqos::{SwqosClient, SwqosType, TradeType},
trading::{common::build_transaction, MiddlewareManager},
trading::{common::build_transaction, BuyParams, MiddlewareManager, SellParams},
};
pub async fn buy_parallel_execute(
params: BuyParams,
instructions: Vec<Instruction>,
protocol_name: &'static str,
) -> Result<()> {
parallel_execute(
params.swqos_clients,
params.payer,
instructions,
params.priority_fee,
params.lookup_table_key,
params.recent_blockhash,
params.data_size_limit,
params.middleware_manager,
protocol_name,
true,
params.wait_transaction_confirmed,
true,
)
.await
}
pub async fn sell_parallel_execute(
params: SellParams,
instructions: Vec<Instruction>,
protocol_name: &'static str,
) -> Result<()> {
parallel_execute(
params.swqos_clients,
params.payer,
instructions,
params.priority_fee,
params.lookup_table_key,
params.recent_blockhash,
0,
params.middleware_manager,
protocol_name,
false,
params.wait_transaction_confirmed,
params.with_tip,
)
.await
}
/// Generic function for parallel transaction execution
pub async fn parallel_execute_with_tips(
async fn parallel_execute(
swqos_clients: Vec<Arc<SwqosClient>>,
payer: Arc<Keypair>,
instructions: Vec<Instruction>,
+10 -2
View File
@@ -3,7 +3,9 @@ use crate::common::bonding_curve::BondingCurveAccount;
use crate::common::{PriorityFee, SolanaRpcClient};
use crate::solana_streamer_sdk::streaming::event_parser::common::EventType;
use crate::solana_streamer_sdk::streaming::event_parser::protocols::bonk::BonkTradeEvent;
use crate::swqos::SwqosClient;
use crate::trading::common::get_multi_token_balances;
use crate::trading::MiddlewareManager;
use solana_hash::Hash;
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::PumpFunTradeEvent;
@@ -21,12 +23,15 @@ pub struct BuyParams {
pub mint: Pubkey,
pub sol_amount: u64,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub priority_fee: Arc<PriorityFee>,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub data_size_limit: u32,
pub wait_transaction_confirmed: bool,
pub protocol_params: Box<dyn ProtocolParams>,
pub open_seed_optimize: bool,
pub swqos_clients: Vec<Arc<SwqosClient>>,
pub middleware_manager: Option<Arc<MiddlewareManager>>,
}
/// Sell parameters
@@ -37,12 +42,15 @@ pub struct SellParams {
pub mint: Pubkey,
pub token_amount: Option<u64>,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub priority_fee: Arc<PriorityFee>,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub wait_transaction_confirmed: bool,
pub with_tip: bool,
pub protocol_params: Box<dyn ProtocolParams>,
pub open_seed_optimize: bool,
pub swqos_clients: Vec<Arc<SwqosClient>>,
pub middleware_manager: Option<Arc<MiddlewareManager>>,
}
/// PumpFun protocol specific parameters
+3 -17
View File
@@ -1,28 +1,14 @@
use std::sync::Arc;
use crate::{swqos::SwqosClient, trading::MiddlewareManager};
use super::params::{BuyParams, SellParams};
use anyhow::Result;
use solana_sdk::instruction::Instruction;
use super::params::{BuyParams, SellParams};
/// 交易执行器trait - 定义了所有交易协议都需要实现的核心方法
#[async_trait::async_trait]
pub trait TradeExecutor: Send + Sync {
/// 使用MEV服务执行买入交易
async fn buy_with_tip(
&self,
params: BuyParams,
swqos_clients: Vec<Arc<SwqosClient>>,
middleware_manager: Option<Arc<MiddlewareManager>>,
) -> Result<()>;
async fn buy_with_tip(&self, params: BuyParams) -> Result<()>;
/// 使用MEV服务执行卖出交易
async fn sell_with_tip(
&self,
params: SellParams,
swqos_clients: Vec<Arc<SwqosClient>>,
middleware_manager: Option<Arc<MiddlewareManager>>,
) -> Result<()>;
async fn sell_with_tip(&self, params: SellParams) -> Result<()>;
/// 获取协议名称
fn protocol_name(&self) -> &'static str;
}