feat: refactor trading architecture with unified framework

- Add unified TradeExecutor interface and protocol abstraction
- Refactor PumpFun/PumpSwap into adapter pattern
- Introduce TradeFactory for multi-protocol support
- Add parallel execution and unified parameter system
- Include Raydium protocol support and log parsing
- Simplify codebase structure and improve maintainability
This commit is contained in:
sgxiang
2025-06-17 23:32:20 +08:00
parent 768dc92156
commit 428ece5d6a
23 changed files with 1908 additions and 1505 deletions
@@ -0,0 +1,21 @@
use solana_sdk::{
message::AddressLookupTableAccount,
pubkey::Pubkey,
};
use crate::common::address_lookup_cache::get_address_lookup_table_account;
/// 获取地址查找表账户列表
/// 如果提供了lookup_table_key,则获取对应的账户,否则返回空列表
pub async fn get_address_lookup_table_accounts(
lookup_table_key: Option<Pubkey>,
) -> Vec<AddressLookupTableAccount> {
let mut address_lookup_table_accounts = vec![];
if let Some(lookup_table_key) = lookup_table_key {
let account = get_address_lookup_table_account(&lookup_table_key).await;
address_lookup_table_accounts.push(account);
}
address_lookup_table_accounts
}
@@ -0,0 +1,73 @@
use solana_sdk::{compute_budget::ComputeBudgetInstruction, instruction::Instruction};
use crate::common::PriorityFee;
/// 为RPC交易添加计算预算指令
pub fn add_rpc_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
priority_fee: &PriorityFee,
data_size_limit: u32,
) {
instructions
.push(ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(data_size_limit));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(
priority_fee.rpc_unit_price,
));
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(
priority_fee.rpc_unit_limit,
));
}
/// 为带小费的交易添加计算预算指令
pub fn add_tip_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
priority_fee: &PriorityFee,
data_size_limit: u32,
) {
instructions
.push(ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(data_size_limit));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(
priority_fee.unit_price,
));
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(
priority_fee.unit_limit,
));
}
/// 通用的计算预算指令添加函数
pub fn add_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
unit_price: u64,
unit_limit: u32,
data_size_limit: u32,
) {
instructions
.push(ComputeBudgetInstruction::set_loaded_accounts_data_size_limit(data_size_limit));
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
}
pub fn add_sell_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
priority_fee: &PriorityFee,
) {
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(
priority_fee.rpc_unit_price,
));
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(
priority_fee.rpc_unit_limit,
));
}
/// 为带小费的交易添加计算预算指令
pub fn add_sell_tip_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
priority_fee: &PriorityFee,
) {
instructions.push(ComputeBudgetInstruction::set_compute_unit_price(
priority_fee.unit_price,
));
instructions.push(ComputeBudgetInstruction::set_compute_unit_limit(
priority_fee.unit_limit,
));
}
+10
View File
@@ -0,0 +1,10 @@
pub mod nonce_manager;
pub mod transaction_builder;
pub mod compute_budget_manager;
pub mod address_lookup_manager;
// Re-export commonly used functions
pub use nonce_manager::*;
pub use transaction_builder::*;
pub use compute_budget_manager::*;
pub use address_lookup_manager::*;
+72
View File
@@ -0,0 +1,72 @@
use anyhow::anyhow;
use solana_sdk::{
instruction::Instruction,
signature::Keypair,
signer::Signer,
system_instruction,
};
use solana_hash::Hash;
use crate::common::nonce_cache::NonceCache;
/// 添加nonce消费指令到指令集合中
///
/// 只有提供了nonce_pubkey时才使用nonce功能
/// 如果nonce被锁定、已使用或未准备好,将返回错误
/// 成功时会锁定并标记nonce为已使用
pub fn add_nonce_instruction(
instructions: &mut Vec<Instruction>,
payer: &Keypair
) -> Result<(), anyhow::Error> {
let nonce_cache = NonceCache::get_instance();
let nonce_info = nonce_cache.get_nonce_info();
// 只检查nonce_account是否存在
if let Some(nonce_pubkey) = nonce_info.nonce_account {
// 暂不加锁
// if nonce_info.lock {
// return Err(anyhow!("Nonce is locked"));
// }
if nonce_info.used {
return Err(anyhow!("Nonce is used"));
}
if nonce_info.current_nonce == Hash::default() {
return Err(anyhow!("Nonce is not ready"));
}
// if nonce_info.next_buy_time == 0 || chrono::Utc::now().timestamp() < nonce_info.next_buy_time {
// return Err(anyhow!("Nonce is not ready"));
// }
// 加锁 - 暂不加锁
// nonce_cache.lock();
// 创建Solana系统nonce推进指令 - 使用系统程序ID
let nonce_advance_ix = system_instruction::advance_nonce_account(
&nonce_pubkey,
&payer.pubkey(),
);
instructions.push(nonce_advance_ix);
}
Ok(())
}
/// 获取用于交易的blockhash
/// 如果使用了nonce账户,返回nonce中的blockhash,否则返回传入的recent_blockhash
pub fn get_transaction_blockhash(recent_blockhash: Hash) -> Hash {
let nonce_cache = NonceCache::get_instance();
let nonce_info = nonce_cache.get_nonce_info();
if nonce_info.nonce_account.is_some() {
nonce_info.current_nonce
} else {
recent_blockhash
}
}
/// 检查是否使用nonce账户
pub fn is_using_nonce() -> bool {
let nonce_cache = NonceCache::get_instance();
let nonce_info = nonce_cache.get_nonce_info();
nonce_info.nonce_account.is_some()
}
+241
View File
@@ -0,0 +1,241 @@
use anyhow::anyhow;
use solana_hash::Hash;
use solana_sdk::{
instruction::Instruction,
message::{v0, VersionedMessage},
native_token::sol_to_lamports,
pubkey::Pubkey,
signature::Keypair,
signer::Signer,
system_instruction,
transaction::VersionedTransaction,
};
use std::sync::Arc;
use super::{
address_lookup_manager::get_address_lookup_table_accounts,
compute_budget_manager::{
add_rpc_compute_budget_instructions, add_tip_compute_budget_instructions,
},
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
};
use crate::{
common::PriorityFee,
trading::common::{
add_sell_compute_budget_instructions, add_sell_tip_compute_budget_instructions,
},
};
/// 构建标准的RPC交易
pub async fn build_rpc_transaction(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
data_size_limit: u32,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = vec![];
// 添加nonce指令
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref()) {
return Err(e);
}
// 添加计算预算指令
add_rpc_compute_budget_instructions(&mut instructions, priority_fee, data_size_limit);
// 添加业务指令
instructions.extend(business_instructions);
// 获取交易使用的blockhash
let blockhash = get_transaction_blockhash(recent_blockhash);
// 获取地址查找表账户
let address_lookup_table_accounts = get_address_lookup_table_accounts(lookup_table_key).await;
// 构建交易
build_versioned_transaction(
payer,
instructions,
address_lookup_table_accounts,
blockhash,
)
.await
}
/// 构建带小费的交易
pub async fn build_tip_transaction(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
tip_account: &Pubkey,
tip_amount: f64,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
data_size_limit: u32,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = vec![];
// 添加nonce指令
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref()) {
return Err(e);
}
// 添加计算预算指令
add_tip_compute_budget_instructions(&mut instructions, priority_fee, data_size_limit);
// 添加业务指令
instructions.extend(business_instructions);
// 添加小费转账指令
instructions.push(system_instruction::transfer(
&payer.pubkey(),
tip_account,
sol_to_lamports(tip_amount),
));
// 获取交易使用的blockhash
let blockhash = get_transaction_blockhash(recent_blockhash);
// 获取地址查找表账户
let address_lookup_table_accounts = get_address_lookup_table_accounts(lookup_table_key).await;
// 构建交易
build_versioned_transaction(
payer,
instructions,
address_lookup_table_accounts,
blockhash,
)
.await
}
/// 构建版本化交易的底层函数
async fn build_versioned_transaction(
payer: Arc<Keypair>,
instructions: Vec<Instruction>,
address_lookup_table_accounts: Vec<solana_sdk::message::AddressLookupTableAccount>,
blockhash: Hash,
) -> Result<VersionedTransaction, anyhow::Error> {
let v0_message: v0::Message = v0::Message::try_compile(
&payer.pubkey(),
&instructions,
&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)
}
/// 构建带小费的交易(使用PriorityFee中的tip_fee
pub async fn build_tip_transaction_with_priority_fee(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
tip_account: &Pubkey,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
data_size_limit: u32,
) -> Result<VersionedTransaction, anyhow::Error> {
build_tip_transaction(
payer,
priority_fee,
business_instructions,
tip_account,
priority_fee.buy_tip_fee,
lookup_table_key,
recent_blockhash,
data_size_limit,
)
.await
}
/// 构建标准的RPC交易
pub async fn build_sell_transaction(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = vec![];
// 添加计算预算指令
add_sell_compute_budget_instructions(&mut instructions, priority_fee);
// 添加业务指令
instructions.extend(business_instructions);
// 获取地址查找表账户
let address_lookup_table_accounts = get_address_lookup_table_accounts(lookup_table_key).await;
// 构建交易
build_versioned_transaction(
payer,
instructions,
address_lookup_table_accounts,
recent_blockhash,
)
.await
}
pub async fn build_sell_tip_transaction(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
tip_account: &Pubkey,
tip_amount: f64,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = vec![];
// 添加计算预算指令
add_sell_tip_compute_budget_instructions(&mut instructions, priority_fee);
// 添加业务指令
instructions.extend(business_instructions);
// 添加小费转账指令
instructions.push(system_instruction::transfer(
&payer.pubkey(),
tip_account,
sol_to_lamports(tip_amount),
));
// 获取地址查找表账户
let address_lookup_table_accounts = get_address_lookup_table_accounts(lookup_table_key).await;
// 构建交易
build_versioned_transaction(
payer,
instructions,
address_lookup_table_accounts,
recent_blockhash,
)
.await
}
pub async fn build_sell_tip_transaction_with_priority_fee(
payer: Arc<Keypair>,
priority_fee: &PriorityFee,
business_instructions: Vec<Instruction>,
tip_account: &Pubkey,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
) -> Result<VersionedTransaction, anyhow::Error> {
build_sell_tip_transaction(
payer,
priority_fee,
business_instructions,
tip_account,
priority_fee.sell_tip_fee,
lookup_table_key,
recent_blockhash,
)
.await
}
+1
View File
@@ -0,0 +1 @@
pub const DEFAULT_SLIPPAGE_BASIS_POINTS: u64 = 100;
+201
View File
@@ -0,0 +1,201 @@
use anyhow::{anyhow, Result};
use solana_sdk::signer::Signer;
use std::sync::Arc;
use super::{
parallel::parallel_execute_with_tips,
params::{BuyParams, BuyWithTipParams, SellParams, SellWithTipParams},
timer::TradeTimer,
traits::{InstructionBuilder, TradeExecutor},
};
use crate::{
swqos::TradeType,
trading::common::{build_rpc_transaction, build_sell_transaction},
};
/// 通用交易执行器实现
pub struct GenericTradeExecutor {
instruction_builder: Arc<dyn InstructionBuilder>,
protocol_name: &'static str,
}
impl GenericTradeExecutor {
pub fn new(
instruction_builder: Arc<dyn InstructionBuilder>,
protocol_name: &'static str,
) -> Self {
Self {
instruction_builder,
protocol_name,
}
}
/// 获取代币余额
async fn get_token_balance(
&self,
rpc: Arc<crate::common::SolanaRpcClient>,
payer: &solana_sdk::signature::Keypair,
mint: &solana_sdk::pubkey::Pubkey,
) -> Result<u64> {
let ata = spl_associated_token_account::get_associated_token_address(&payer.pubkey(), mint);
let balance = rpc.get_token_account_balance(&ata).await?;
balance
.amount
.parse::<u64>()
.map_err(|_| anyhow!("Failed to parse token balance"))
}
}
#[async_trait::async_trait]
impl TradeExecutor for GenericTradeExecutor {
async fn buy(&self, params: BuyParams) -> Result<()> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
let mut timer = TradeTimer::new("构建买入交易指令");
// 构建指令
let instructions = self
.instruction_builder
.build_buy_instructions(&params)
.await?;
timer.stage("买入交易指令");
// 构建交易
let transaction = build_rpc_transaction(
params.payer.clone(),
&params.priority_fee,
instructions,
params.lookup_table_key,
params.recent_blockhash,
params.data_size_limit,
)
.await?;
timer.stage("买入交易签名");
// 发送交易
rpc.send_and_confirm_transaction(&transaction).await?;
timer.finish();
Ok(())
}
async fn buy_with_tip(&self, params: BuyWithTipParams) -> Result<()> {
let mut timer = TradeTimer::new("构建买入交易指令");
// 验证参数 - 转换为BuyParams进行验证
let buy_params = BuyParams {
rpc: params.rpc,
payer: params.payer.clone(),
mint: params.mint,
creator: params.creator,
amount_sol: params.amount_sol,
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: params.data_size_limit,
protocol_params: params.protocol_params.clone(),
};
// 构建指令
let instructions = self
.instruction_builder
.build_buy_instructions(&buy_params)
.await?;
timer.stage("买入交易指令");
// 并行执行交易
parallel_execute_with_tips(
params.fee_clients,
params.payer,
instructions,
params.priority_fee,
params.lookup_table_key,
params.recent_blockhash,
params.data_size_limit,
TradeType::Buy,
)
.await?;
timer.finish();
Ok(())
}
async fn sell(&self, params: SellParams) -> Result<()> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
let mut timer = TradeTimer::new("构建卖出交易指令");
// 构建指令
let instructions = self
.instruction_builder
.build_sell_instructions(&params)
.await?;
timer.stage("卖出交易指令");
// 构建交易
let transaction = build_sell_transaction(
params.payer.clone(),
&params.priority_fee,
instructions,
params.lookup_table_key,
params.recent_blockhash,
)
.await?;
timer.stage("卖出交易签名");
// 发送交易
rpc.send_and_confirm_transaction(&transaction).await?;
timer.finish();
Ok(())
}
async fn sell_with_tip(&self, params: SellWithTipParams) -> Result<()> {
let mut timer = TradeTimer::new("构建卖出交易指令");
// 转换为SellParams进行指令构建
let sell_params = SellParams {
rpc: params.rpc,
payer: params.payer.clone(),
mint: params.mint,
creator: params.creator,
amount_token: params.amount_token,
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,
protocol_params: params.protocol_params.clone(),
};
// 构建指令
let instructions = self
.instruction_builder
.build_sell_instructions(&sell_params)
.await?;
timer.stage("卖出交易指令");
// 并行执行交易
parallel_execute_with_tips(
params.fee_clients,
params.payer,
instructions,
params.priority_fee,
params.lookup_table_key,
params.recent_blockhash,
0,
TradeType::Sell,
)
.await?;
timer.finish();
Ok(())
}
fn protocol_name(&self) -> &'static str {
self.protocol_name
}
}
+6
View File
@@ -0,0 +1,6 @@
pub mod constants;
pub mod params;
pub mod traits;
pub mod executor;
pub mod parallel;
pub mod timer;
+118
View File
@@ -0,0 +1,118 @@
use anyhow::{anyhow, Result};
use solana_hash::Hash;
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signature::Keypair};
use std::{str::FromStr, sync::Arc};
use tokio::task::JoinHandle;
use crate::{
common::PriorityFee,
swqos::{ClientType, FeeClient, TradeType},
trading::common::{
build_rpc_transaction, build_sell_tip_transaction_with_priority_fee,
build_sell_transaction, build_tip_transaction_with_priority_fee,
},
};
/// 并行执行交易的通用函数
pub async fn parallel_execute_with_tips(
fee_clients: Vec<Arc<FeeClient>>,
payer: Arc<Keypair>,
instructions: Vec<Instruction>,
priority_fee: PriorityFee,
lookup_table_key: Option<Pubkey>,
recent_blockhash: Hash,
data_size_limit: u32,
trade_type: TradeType,
) -> Result<()> {
let cores = core_affinity::get_core_ids().unwrap();
let mut handles: Vec<JoinHandle<Result<()>>> = vec![];
for i in 0..fee_clients.len() {
let fee_client = fee_clients[i].clone();
let payer = payer.clone();
let instructions = instructions.clone();
let mut priority_fee = priority_fee.clone();
let core_id = cores[i % cores.len()];
let handle = tokio::spawn(async move {
core_affinity::set_for_current(core_id);
let transaction = if matches!(trade_type, TradeType::Sell)
&& fee_client.get_client_type() == ClientType::Rpc
{
build_sell_transaction(
payer,
&priority_fee,
instructions,
lookup_table_key,
recent_blockhash,
)
.await?
} else if matches!(trade_type, TradeType::Sell)
&& fee_client.get_client_type() != ClientType::Rpc
{
let tip_account = fee_client.get_tip_account()?;
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
build_sell_tip_transaction_with_priority_fee(
payer,
&priority_fee,
instructions,
&tip_account,
lookup_table_key,
recent_blockhash,
)
.await?
} else if fee_client.get_client_type() == ClientType::Rpc {
build_rpc_transaction(
payer,
&priority_fee,
instructions,
lookup_table_key,
recent_blockhash,
data_size_limit,
)
.await?
} else {
let tip_account = fee_client.get_tip_account()?;
let tip_account = Arc::new(Pubkey::from_str(&tip_account).map_err(|e| anyhow!(e))?);
priority_fee.buy_tip_fee = priority_fee.buy_tip_fees[i];
build_tip_transaction_with_priority_fee(
payer,
&priority_fee,
instructions,
&tip_account,
lookup_table_key,
recent_blockhash,
data_size_limit,
)
.await?
};
fee_client
.send_transaction(trade_type, &transaction)
.await?;
Ok::<(), anyhow::Error>(())
});
handles.push(handle);
}
// 等待所有任务完成
let mut errors = Vec::new();
for handle in handles {
match handle.await {
Ok(Ok(_)) => (),
Ok(Err(e)) => errors.push(format!("Task error: {}", e)),
Err(e) => errors.push(format!("Join error: {}", e)),
}
}
if !errors.is_empty() {
for error in &errors {
println!("{}", error);
}
return Err(anyhow!("Some tasks failed: {:?}", errors));
}
Ok(())
}
+161
View File
@@ -0,0 +1,161 @@
use solana_hash::Hash;
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
use std::sync::Arc;
use super::traits::ProtocolParams;
use crate::common::{PriorityFee, SolanaRpcClient};
use crate::swqos::FeeClient;
/// 通用买入参数
#[derive(Clone)]
pub struct BuyParams {
pub rpc: Option<Arc<SolanaRpcClient>>,
pub payer: Arc<Keypair>,
pub mint: Pubkey,
pub creator: Pubkey,
pub amount_sol: u64,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub data_size_limit: u32,
pub protocol_params: Box<dyn ProtocolParams>,
}
/// 带MEV服务的买入参数
#[derive(Clone)]
pub struct BuyWithTipParams {
pub rpc: Option<Arc<SolanaRpcClient>>,
pub fee_clients: Vec<Arc<FeeClient>>,
pub payer: Arc<Keypair>,
pub mint: Pubkey,
pub creator: Pubkey,
pub amount_sol: u64,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub data_size_limit: u32,
pub protocol_params: Box<dyn ProtocolParams>,
}
/// 通用卖出参数
#[derive(Clone)]
pub struct SellParams {
pub rpc: Option<Arc<SolanaRpcClient>>,
pub payer: Arc<Keypair>,
pub mint: Pubkey,
pub creator: Pubkey,
pub amount_token: Option<u64>,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub protocol_params: Box<dyn ProtocolParams>,
}
/// 带MEV服务的卖出参数
#[derive(Clone)]
pub struct SellWithTipParams {
pub rpc: Option<Arc<SolanaRpcClient>>,
pub fee_clients: Vec<Arc<FeeClient>>,
pub payer: Arc<Keypair>,
pub mint: Pubkey,
pub creator: Pubkey,
pub amount_token: Option<u64>,
pub slippage_basis_points: Option<u64>,
pub priority_fee: PriorityFee,
pub lookup_table_key: Option<Pubkey>,
pub recent_blockhash: Hash,
pub protocol_params: Box<dyn ProtocolParams>,
}
/// PumpFun协议特定参数
#[derive(Clone)]
pub struct PumpFunParams {
pub dev_buy_token: u64,
pub dev_sol_cost: u64,
pub trade_type: String,
}
impl ProtocolParams for PumpFunParams {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn clone_box(&self) -> Box<dyn ProtocolParams> {
Box::new(self.clone())
}
}
#[derive(Clone)]
pub struct PumpFunSellParams {}
impl ProtocolParams for PumpFunSellParams {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn clone_box(&self) -> Box<dyn ProtocolParams> {
Box::new(self.clone())
}
}
/// PumpSwap协议特定参数
#[derive(Clone)]
pub struct PumpSwapParams {
pub pool: Option<Pubkey>,
pub pool_base_token_account: Option<Pubkey>,
pub pool_quote_token_account: Option<Pubkey>,
pub user_base_token_account: Option<Pubkey>,
pub user_quote_token_account: Option<Pubkey>,
}
impl ProtocolParams for PumpSwapParams {
fn as_any(&self) -> &dyn std::any::Any {
self
}
fn clone_box(&self) -> Box<dyn ProtocolParams> {
Box::new(self.clone())
}
}
impl BuyParams {
/// 转换为BuyWithTipParams
pub fn with_tip(self, fee_clients: Vec<Arc<FeeClient>>) -> BuyWithTipParams {
BuyWithTipParams {
rpc: self.rpc,
fee_clients,
payer: self.payer,
mint: self.mint,
creator: self.creator,
amount_sol: self.amount_sol,
slippage_basis_points: self.slippage_basis_points,
priority_fee: self.priority_fee,
lookup_table_key: self.lookup_table_key,
recent_blockhash: self.recent_blockhash,
data_size_limit: self.data_size_limit,
protocol_params: self.protocol_params,
}
}
}
impl SellParams {
/// 转换为SellWithTipParams
pub fn with_tip(self, fee_clients: Vec<Arc<FeeClient>>) -> SellWithTipParams {
SellWithTipParams {
rpc: self.rpc,
fee_clients,
payer: self.payer,
mint: self.mint,
creator: self.creator,
amount_token: self.amount_token,
slippage_basis_points: self.slippage_basis_points,
priority_fee: self.priority_fee,
lookup_table_key: self.lookup_table_key,
recent_blockhash: self.recent_blockhash,
protocol_params: self.protocol_params,
}
}
}
+46
View File
@@ -0,0 +1,46 @@
use std::time::Instant;
/// 交易时间测量器
pub struct TradeTimer {
start_time: Instant,
stage: String,
}
impl TradeTimer {
/// 创建新的计时器
pub fn new(stage: impl Into<String>) -> Self {
Self {
start_time: Instant::now(),
stage: stage.into(),
}
}
/// 记录当前阶段耗时并开始新阶段
pub fn stage(&mut self, new_stage: impl Into<String>) {
let elapsed = self.start_time.elapsed();
println!(" {} 耗时: {:?}", self.stage, elapsed);
self.start_time = Instant::now();
self.stage = new_stage.into();
}
/// 完成计时并输出最终耗时
pub fn finish(self) {
let elapsed = self.start_time.elapsed();
println!(" {} 耗时: {:?}", self.stage, elapsed);
}
/// 获取当前阶段的耗时(不重置计时器)
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!(" {} 耗时: {:?}", self.stage, elapsed);
}
}
}
+49
View File
@@ -0,0 +1,49 @@
use anyhow::Result;
use solana_sdk::instruction::Instruction;
use std::sync::Arc;
use super::params::{BuyParams, BuyWithTipParams, SellParams, SellWithTipParams};
/// 交易执行器trait - 定义了所有交易协议都需要实现的核心方法
#[async_trait::async_trait]
pub trait TradeExecutor: Send + Sync {
/// 执行买入交易
async fn buy(&self, params: BuyParams) -> Result<()>;
/// 使用MEV服务执行买入交易
async fn buy_with_tip(&self, params: BuyWithTipParams) -> Result<()>;
/// 执行卖出交易
async fn sell(&self, params: SellParams) -> Result<()>;
/// 使用MEV服务执行卖出交易
async fn sell_with_tip(&self, params: SellWithTipParams) -> Result<()>;
/// 获取协议名称
fn protocol_name(&self) -> &'static str;
}
/// 指令构建器trait - 负责构建协议特定的交易指令
#[async_trait::async_trait]
pub trait InstructionBuilder: Send + Sync {
/// 构建买入指令
async fn build_buy_instructions(&self, params: &BuyParams) -> Result<Vec<Instruction>>;
/// 构建卖出指令
async fn build_sell_instructions(&self, params: &SellParams) -> Result<Vec<Instruction>>;
}
/// 协议特定参数trait - 允许每个协议定义自己的参数
pub trait ProtocolParams: Send + Sync {
/// 将参数转换为Any以便向下转型
fn as_any(&self) -> &dyn std::any::Any;
/// 克隆参数
fn clone_box(&self) -> Box<dyn ProtocolParams>;
}
impl Clone for Box<dyn ProtocolParams> {
fn clone(&self) -> Self {
self.clone_box()
}
}
+93
View File
@@ -0,0 +1,93 @@
use anyhow::{anyhow, Result};
use std::sync::Arc;
use super::{
core::{executor::GenericTradeExecutor, traits::TradeExecutor},
protocols::{pumpfun::PumpFunInstructionBuilder, pumpswap::PumpSwapInstructionBuilder},
};
/// 支持的交易协议
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Protocol {
PumpFun,
PumpSwap,
}
impl std::fmt::Display for Protocol {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Protocol::PumpFun => write!(f, "PumpFun"),
Protocol::PumpSwap => write!(f, "PumpSwap"),
}
}
}
impl std::str::FromStr for Protocol {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"pumpfun" => Ok(Protocol::PumpFun),
"pumpswap" => Ok(Protocol::PumpSwap),
_ => Err(anyhow!("Unsupported protocol: {}", s)),
}
}
}
/// 交易工厂 - 用于创建不同协议的交易执行器
pub struct TradeFactory;
impl TradeFactory {
/// 创建指定协议的交易执行器
pub fn create_executor(protocol: Protocol) -> Arc<dyn TradeExecutor> {
match protocol {
Protocol::PumpFun => {
let instruction_builder = Arc::new(PumpFunInstructionBuilder);
Arc::new(GenericTradeExecutor::new(instruction_builder, "PumpFun"))
}
Protocol::PumpSwap => {
let instruction_builder = Arc::new(PumpSwapInstructionBuilder);
Arc::new(GenericTradeExecutor::new(instruction_builder, "PumpSwap"))
}
}
}
/// 获取所有支持的协议
pub fn supported_protocols() -> Vec<Protocol> {
vec![Protocol::PumpFun, Protocol::PumpSwap]
}
/// 检查协议是否支持
pub fn is_supported(protocol: &Protocol) -> bool {
Self::supported_protocols().contains(protocol)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_protocol_from_str() {
assert_eq!("pumpfun".parse::<Protocol>().unwrap(), Protocol::PumpFun);
assert_eq!("pumpswap".parse::<Protocol>().unwrap(), Protocol::PumpSwap);
assert_eq!("PUMPFUN".parse::<Protocol>().unwrap(), Protocol::PumpFun);
assert!("unknown".parse::<Protocol>().is_err());
}
#[test]
fn test_create_executor() {
let pumpfun_executor = TradeFactory::create_executor(Protocol::PumpFun);
assert_eq!(pumpfun_executor.protocol_name(), "PumpFun");
let pumpswap_executor = TradeFactory::create_executor(Protocol::PumpSwap);
assert_eq!(pumpswap_executor.protocol_name(), "PumpSwap");
}
#[test]
fn test_supported_protocols() {
let protocols = TradeFactory::supported_protocols();
assert!(protocols.contains(&Protocol::PumpFun));
assert!(protocols.contains(&Protocol::PumpSwap));
}
}
+8
View File
@@ -0,0 +1,8 @@
pub mod common;
pub mod core;
pub mod factory;
pub mod protocols;
pub use core::params::{BuyParams, BuyWithTipParams, SellParams, SellWithTipParams};
pub use core::traits::{InstructionBuilder, TradeExecutor};
pub use factory::TradeFactory;
+2
View File
@@ -0,0 +1,2 @@
pub mod pumpfun;
pub mod pumpswap;
+168
View File
@@ -0,0 +1,168 @@
use anyhow::{anyhow, Result};
use solana_sdk::{
instruction::Instruction, native_token::sol_to_lamports, pubkey::Pubkey, signer::Signer,
};
use spl_associated_token_account::{
get_associated_token_address, instruction::create_associated_token_account,
};
use spl_token::instruction::close_account;
use std::sync::Arc;
use crate::{
accounts::BondingCurveAccount,
constants::{self, pumpfun::global_constants::FEE_RECIPIENT, trade_type::SNIPER_BUY},
instruction,
pumpfun::common::{
calculate_with_slippage_buy, get_bonding_curve_account_v2, get_bonding_curve_pda,
get_buy_token_amount_from_sol_amount, get_creator_vault_pda, init_bonding_curve_account,
},
trading::core::{
constants::DEFAULT_SLIPPAGE_BASIS_POINTS,
params::{BuyParams, PumpFunParams, SellParams},
traits::InstructionBuilder,
},
PumpFun,
};
/// PumpFun协议的指令构建器
pub struct PumpFunInstructionBuilder;
#[async_trait::async_trait]
impl InstructionBuilder for PumpFunInstructionBuilder {
async fn build_buy_instructions(&self, params: &BuyParams) -> Result<Vec<Instruction>> {
// 获取PumpFun特定参数
let protocol_params = params
.protocol_params
.as_any()
.downcast_ref::<PumpFunParams>()
.ok_or_else(|| anyhow!("Invalid protocol params for PumpFun"))?;
if params.amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
// 获取或初始化bonding curve账户
let bonding_curve = if protocol_params.trade_type == SNIPER_BUY {
init_bonding_curve_account(
&params.mint,
protocol_params.dev_buy_token,
protocol_params.dev_sol_cost,
params.creator,
)
.await?
} else {
let (bonding_curve, _) =
get_bonding_curve_account_v2(&PumpFun::get_instance().get_rpc(), &params.mint)
.await?;
Arc::new(BondingCurveAccount {
discriminator: bonding_curve.discriminator,
account: get_bonding_curve_pda(&params.mint).unwrap(),
virtual_token_reserves: bonding_curve.virtual_token_reserves,
virtual_sol_reserves: bonding_curve.virtual_sol_reserves,
real_token_reserves: bonding_curve.real_token_reserves,
real_sol_reserves: bonding_curve.real_sol_reserves,
token_total_supply: bonding_curve.token_total_supply,
complete: bonding_curve.complete,
creator: params.creator,
})
};
let max_sol_cost = calculate_with_slippage_buy(
params.amount_sol,
params
.slippage_basis_points
.unwrap_or(DEFAULT_SLIPPAGE_BASIS_POINTS),
);
let creator_vault_pda = bonding_curve.get_creator_vault_pda();
let mut buy_token_amount =
get_buy_token_amount_from_sol_amount(&bonding_curve, params.amount_sol);
if buy_token_amount <= 100 * 1_000_000_u64 {
buy_token_amount = if max_sol_cost > sol_to_lamports(0.01) {
25547619 * 1_000_000_u64
} else {
255476 * 1_000_000_u64
};
}
let mut instructions = vec![];
// 创建关联代币账户
instructions.push(create_associated_token_account(
&params.payer.pubkey(),
&params.payer.pubkey(),
&params.mint,
&constants::pumpfun::accounts::TOKEN_PROGRAM,
));
// 创建买入指令
instructions.push(instruction::buy(
params.payer.as_ref(),
&params.mint,
&bonding_curve.account,
&creator_vault_pda,
&FEE_RECIPIENT,
instruction::Buy {
_amount: buy_token_amount,
_max_sol_cost: max_sol_cost,
},
));
println!("max_sol_cost: {:?}", max_sol_cost);
Ok(instructions)
}
async fn build_sell_instructions(&self, params: &SellParams) -> Result<Vec<Instruction>> {
let amount_token = if let Some(amount) = params.amount_token {
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
amount
} else {
return Err(anyhow!("Amount token is required"));
};
let creator_vault_pda = get_creator_vault_pda(&params.creator).unwrap();
let ata = get_associated_token_address(&params.payer.pubkey(), &params.mint);
// 获取代币余额
let balance_u64 = if let Some(rpc) = &params.rpc {
let balance = rpc.get_token_account_balance(&ata).await?;
balance
.amount
.parse::<u64>()
.map_err(|_| anyhow!("Failed to parse token balance"))?
} else {
return Err(anyhow!("RPC client is required to get token balance"));
};
let mut amount_token = amount_token;
if amount_token > balance_u64 {
amount_token = balance_u64;
}
let mut instructions = vec![instruction::sell(
params.payer.as_ref(),
&params.mint,
&creator_vault_pda,
&FEE_RECIPIENT,
instruction::Sell {
_amount: amount_token,
_min_sol_output: 1,
},
)];
// 如果卖出全部代币,关闭账户
if amount_token >= balance_u64 {
instructions.push(close_account(
&spl_token::ID,
&ata,
&params.payer.pubkey(),
&params.payer.pubkey(),
&[&params.payer.pubkey()],
)?);
}
Ok(instructions)
}
}
+371
View File
@@ -0,0 +1,371 @@
use anyhow::{anyhow, Result};
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signer::Signer};
use spl_associated_token_account::instruction::create_associated_token_account_idempotent;
use std::sync::Arc;
use crate::{
constants::pumpswap::{
accounts, trade::DEFAULT_SLIPPAGE, BUY_DISCRIMINATOR, SELL_DISCRIMINATOR,
},
pumpswap::common::{
calculate_with_slippage_buy, calculate_with_slippage_sell, coin_creator_vault_ata,
coin_creator_vault_authority, find_pool, get_buy_token_amount, get_sell_sol_amount,
get_token_balance,
},
trading::core::{
constants::DEFAULT_SLIPPAGE_BASIS_POINTS,
params::{BuyParams, PumpSwapParams, SellParams},
traits::InstructionBuilder,
},
};
/// PumpSwap协议的指令构建器
pub struct PumpSwapInstructionBuilder;
#[async_trait::async_trait]
impl InstructionBuilder for PumpSwapInstructionBuilder {
async fn build_buy_instructions(&self, params: &BuyParams) -> Result<Vec<Instruction>> {
// 获取PumpSwap特定参数
let protocol_params = params
.protocol_params
.as_any()
.downcast_ref::<PumpSwapParams>()
.ok_or_else(|| anyhow!("Invalid protocol params for PumpSwap"))?;
if params.amount_sol == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
// 根据是否提供了账户信息来构建指令
match (
&protocol_params.pool,
&protocol_params.pool_base_token_account,
&protocol_params.pool_quote_token_account,
&protocol_params.user_base_token_account,
&protocol_params.user_quote_token_account,
) {
(
Some(pool),
Some(pool_base_token_account),
Some(pool_quote_token_account),
Some(user_base_token_account),
Some(user_quote_token_account),
) => {
self.build_buy_instructions_with_accounts(
params,
*pool,
*pool_base_token_account,
*pool_quote_token_account,
*user_base_token_account,
*user_quote_token_account,
)
.await
}
_ => self.build_buy_instructions_auto_discover(params).await,
}
}
async fn build_sell_instructions(&self, params: &SellParams) -> Result<Vec<Instruction>> {
// 获取PumpSwap特定参数
let protocol_params = params
.protocol_params
.as_any()
.downcast_ref::<PumpSwapParams>()
.ok_or_else(|| anyhow!("Invalid protocol params for PumpSwap"))?;
// 根据是否提供了账户信息来构建指令
match (
&protocol_params.pool,
&protocol_params.pool_base_token_account,
&protocol_params.pool_quote_token_account,
&protocol_params.user_base_token_account,
&protocol_params.user_quote_token_account,
) {
(
Some(pool),
Some(pool_base_token_account),
Some(pool_quote_token_account),
Some(user_base_token_account),
Some(user_quote_token_account),
) => {
self.build_sell_instructions_with_accounts(
params,
*pool,
*pool_base_token_account,
*pool_quote_token_account,
*user_base_token_account,
*user_quote_token_account,
)
.await
}
_ => self.build_sell_instructions_auto_discover(params).await,
}
}
}
impl PumpSwapInstructionBuilder {
/// 自动发现池和账户信息并构建买入指令
async fn build_buy_instructions_auto_discover(
&self,
params: &BuyParams,
) -> Result<Vec<Instruction>> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
// 查找池
let pool = find_pool(rpc.as_ref(), &params.mint).await?;
// 创建用户代币账户
let user_base_token_account = spl_associated_token_account::get_associated_token_address(
&params.payer.pubkey(),
&params.mint,
);
let user_quote_token_account = spl_associated_token_account::get_associated_token_address(
&params.payer.pubkey(),
&accounts::WSOL_TOKEN_ACCOUNT,
);
// 获取池的代币账户
let pool_base_token_account =
spl_associated_token_account::get_associated_token_address_with_program_id(
&pool,
&params.mint,
&accounts::TOKEN_PROGRAM,
);
let pool_quote_token_account =
spl_associated_token_account::get_associated_token_address_with_program_id(
&pool,
&accounts::WSOL_TOKEN_ACCOUNT,
&accounts::TOKEN_PROGRAM,
);
self.build_buy_instructions_with_accounts(
params,
pool,
pool_base_token_account,
pool_quote_token_account,
user_base_token_account,
user_quote_token_account,
)
.await
}
/// 自动发现池和账户信息并构建卖出指令
async fn build_sell_instructions_auto_discover(
&self,
params: &SellParams,
) -> Result<Vec<Instruction>> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
// 查找池
let pool = find_pool(rpc.as_ref(), &params.mint).await?;
// 创建用户代币账户
let user_base_token_account = spl_associated_token_account::get_associated_token_address(
&params.payer.pubkey(),
&params.mint,
);
let user_quote_token_account = spl_associated_token_account::get_associated_token_address(
&params.payer.pubkey(),
&accounts::WSOL_TOKEN_ACCOUNT,
);
// 获取池的代币账户
let pool_base_token_account =
spl_associated_token_account::get_associated_token_address_with_program_id(
&pool,
&params.mint,
&accounts::TOKEN_PROGRAM,
);
let pool_quote_token_account =
spl_associated_token_account::get_associated_token_address_with_program_id(
&pool,
&accounts::WSOL_TOKEN_ACCOUNT,
&accounts::TOKEN_PROGRAM,
);
self.build_sell_instructions_with_accounts(
params,
pool,
pool_base_token_account,
pool_quote_token_account,
user_base_token_account,
user_quote_token_account,
)
.await
}
/// 使用提供的账户信息构建买入指令
async fn build_buy_instructions_with_accounts(
&self,
params: &BuyParams,
pool: Pubkey,
pool_base_token_account: Pubkey,
pool_quote_token_account: Pubkey,
user_base_token_account: Pubkey,
user_quote_token_account: Pubkey,
) -> Result<Vec<Instruction>> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
// 计算预期的代币数量
let token_amount = get_buy_token_amount(rpc.as_ref(), &pool, params.amount_sol).await?;
// 计算滑点后的最大SOL数量
let max_sol_amount = calculate_with_slippage_buy(
params.amount_sol,
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
);
let mut instructions = vec![];
// 创建用户的基础代币账户
instructions.push(create_associated_token_account_idempotent(
&params.payer.pubkey(),
&params.payer.pubkey(),
&params.mint,
&accounts::TOKEN_PROGRAM,
));
let coin_creator_vault_ata = coin_creator_vault_ata(params.creator);
let coin_creator_vault_authority = coin_creator_vault_authority(params.creator);
// 创建买入指令
let accounts = vec![
solana_sdk::instruction::AccountMeta::new_readonly(pool, false), // pool_id (readonly)
solana_sdk::instruction::AccountMeta::new(params.payer.pubkey(), true), // user (signer)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::GLOBAL_ACCOUNT, false), // global (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(params.mint, false), // mint (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::WSOL_TOKEN_ACCOUNT, false), // WSOL_TOKEN_ACCOUNT (readonly)
solana_sdk::instruction::AccountMeta::new(user_base_token_account, false), // user_base_token_account
solana_sdk::instruction::AccountMeta::new(user_quote_token_account, false), // user_quote_token_account
solana_sdk::instruction::AccountMeta::new(pool_base_token_account, false), // pool_base_token_account
solana_sdk::instruction::AccountMeta::new(pool_quote_token_account, false), // pool_quote_token_account
solana_sdk::instruction::AccountMeta::new_readonly(accounts::FEE_RECIPIENT, false), // fee_recipient (readonly)
solana_sdk::instruction::AccountMeta::new(accounts::FEE_RECIPIENT_ATA, false), // fee_recipient_ata
solana_sdk::instruction::AccountMeta::new_readonly(accounts::TOKEN_PROGRAM, false), // TOKEN_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::TOKEN_PROGRAM, false), // TOKEN_PROGRAM_ID (readonly, duplicated as in JS)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::SYSTEM_PROGRAM, false), // System Program (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(
accounts::ASSOCIATED_TOKEN_PROGRAM,
false,
), // ASSOCIATED_TOKEN_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::EVENT_AUTHORITY, false), // event_authority (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::AMM_PROGRAM, false), // PUMP_AMM_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new(coin_creator_vault_ata, false), // coin_creator_vault_ata
solana_sdk::instruction::AccountMeta::new_readonly(coin_creator_vault_authority, false), // coin_creator_vault_authority (readonly)
];
// 创建指令数据
let mut data = vec![];
data.extend_from_slice(&BUY_DISCRIMINATOR);
data.extend_from_slice(&token_amount.to_le_bytes());
data.extend_from_slice(&max_sol_amount.to_le_bytes());
instructions.push(Instruction {
program_id: accounts::AMM_PROGRAM,
accounts,
data,
});
Ok(instructions)
}
/// 使用提供的账户信息构建卖出指令
async fn build_sell_instructions_with_accounts(
&self,
params: &SellParams,
pool: Pubkey,
pool_base_token_account: Pubkey,
pool_quote_token_account: Pubkey,
user_base_token_account: Pubkey,
user_quote_token_account: Pubkey,
) -> Result<Vec<Instruction>> {
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let rpc = params.rpc.as_ref().unwrap().clone();
// 获取代币余额
let mut amount = params.amount_token;
if params.amount_token.is_none() {
let (balance_u64, _) =
get_token_balance(rpc.as_ref(), params.payer.as_ref(), &params.mint).await?;
amount = Some(balance_u64);
}
let amount = amount.unwrap_or(0);
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
// 计算预期的SOL数量
let sol_amount = get_sell_sol_amount(rpc.as_ref(), &pool, amount).await?;
// 计算滑点后的最小SOL数量
let min_sol_amount = calculate_with_slippage_sell(
sol_amount,
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
);
let coin_creator_vault_ata = coin_creator_vault_ata(params.creator);
let coin_creator_vault_authority = coin_creator_vault_authority(params.creator);
let mut instructions = vec![];
// 创建用户的代币账户
instructions.push(create_associated_token_account_idempotent(
&params.payer.pubkey(),
&params.payer.pubkey(),
&params.mint,
&accounts::TOKEN_PROGRAM,
));
// 创建卖出指令
let accounts = vec![
solana_sdk::instruction::AccountMeta::new_readonly(pool, false), // pool_id (readonly)
solana_sdk::instruction::AccountMeta::new(params.payer.pubkey(), true), // user (signer)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::GLOBAL_ACCOUNT, false), // global (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(params.mint, false), // mint (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::WSOL_TOKEN_ACCOUNT, false), // WSOL_TOKEN_ACCOUNT (readonly)
solana_sdk::instruction::AccountMeta::new(user_base_token_account, false), // user_base_token_account
solana_sdk::instruction::AccountMeta::new(user_quote_token_account, false), // user_quote_token_account
solana_sdk::instruction::AccountMeta::new(pool_base_token_account, false), // pool_base_token_account
solana_sdk::instruction::AccountMeta::new(pool_quote_token_account, false), // pool_quote_token_account
solana_sdk::instruction::AccountMeta::new_readonly(accounts::FEE_RECIPIENT, false), // fee_recipient (readonly)
solana_sdk::instruction::AccountMeta::new(accounts::FEE_RECIPIENT_ATA, false), // fee_recipient_ata
solana_sdk::instruction::AccountMeta::new_readonly(accounts::TOKEN_PROGRAM, false), // TOKEN_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::TOKEN_PROGRAM, false), // TOKEN_PROGRAM_ID (readonly, duplicated as in JS)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::SYSTEM_PROGRAM, false), // System Program (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(
accounts::ASSOCIATED_TOKEN_PROGRAM,
false,
), // ASSOCIATED_TOKEN_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::EVENT_AUTHORITY, false), // event_authority (readonly)
solana_sdk::instruction::AccountMeta::new_readonly(accounts::AMM_PROGRAM, false), // PUMP_AMM_PROGRAM_ID (readonly)
solana_sdk::instruction::AccountMeta::new(coin_creator_vault_ata, false), // coin_creator_vault_ata
solana_sdk::instruction::AccountMeta::new_readonly(coin_creator_vault_authority, false), // coin_creator_vault_authority (readonly)
];
// 创建指令数据
let mut data = vec![];
data.extend_from_slice(&SELL_DISCRIMINATOR);
data.extend_from_slice(&amount.to_le_bytes());
data.extend_from_slice(&min_sol_amount.to_le_bytes());
instructions.push(Instruction {
program_id: accounts::AMM_PROGRAM,
accounts,
data,
});
Ok(instructions)
}
}