feat: add seed optimization and refactor wSOL account control

- Add `open_seed_optimize` parameter for enhanced performance
- Move wSOL account flags from protocol params to buy/sell params
- Add seed_trading example demonstrating optimization features
- Update all examples and upgrade dependencies
- Improve wSOL account management flexibility

BREAKING CHANGE: Modified buy/sell method signatures and protocol param structs
This commit is contained in:
ysq
2025-09-10 00:05:13 +08:00
parent 1f44de8f9a
commit 5225cff73c
22 changed files with 199 additions and 54 deletions
+2 -1
View File
@@ -30,13 +30,14 @@ members = [
"examples/nonce_cache",
"examples/pumpswap_direct_trading",
"examples/wsol_wrapper",
"examples/seed_trading",
]
[lib]
crate-type = ["cdylib", "rlib"]
[dependencies]
solana-streamer-sdk = "0.4.2"
solana-streamer-sdk = "0.4.3"
solana-sdk = "2.3.0"
solana-client = "2.3.6"
solana-program = "2.3.0"
-2
View File
@@ -54,12 +54,10 @@ In PumpSwap, Bonk, and Raydium trading, the `create_wsol_ata` and `close_wsol_at
- **create_wsol_ata**:
- When `create_wsol_ata: true`, the SDK automatically creates and wraps SOL to wSOL before trading
- When buying: automatically wraps SOL to wSOL for trading
- Default value is `true`
- **close_wsol_ata**:
- When `close_wsol_ata: true`, the SDK automatically closes the wSOL account and unwraps to SOL after trading
- When selling: automatically unwraps the received wSOL to SOL and reclaims rent
- Default value is `true`
- **Benefits of Separate Parameters**:
- Allows independent control of wSOL account creation and closure
-2
View File
@@ -54,12 +54,10 @@ sol-trade-sdk = "0.6.1"
- **create_wsol_ata**
-`create_wsol_ata: true` 时,SDK 会在交易前自动创建并将 SOL 包装为 wSOL
- 买入时:自动将 SOL 包装为 wSOL 进行交易
- 默认值为 `true`
- **close_wsol_ata**
-`close_wsol_ata: true` 时,SDK 会在交易后自动关闭 wSOL 账户并解包装为 SOL
- 卖出时:自动将获得的 wSOL 解包装为 SOL 并回收租金
- 默认值为 `true`
- **分离参数的优势**
- 允许独立控制 wSOL 账户的创建和关闭
+2
View File
@@ -170,6 +170,8 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
Some(lookup_table_key), // you still need to update the AddressLookupTableCache
true,
false,
false,
false,
)
.await?;
+4
View File
@@ -151,6 +151,8 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
Box::new(BonkParams::from_trade(trade_info.clone())),
None,
true,
true,
true,
false,
)
.await?;
@@ -178,6 +180,8 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
Box::new(BonkParams::from_trade(trade_info.clone())),
None,
true,
true,
true,
false,
)
.await?;
+4
View File
@@ -120,6 +120,8 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
Box::new(BonkParams::from_dev_trade(trade_info.clone())),
None,
true,
true,
true,
false,
)
.await?;
@@ -152,6 +154,8 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
)),
None,
true,
true,
true,
false,
)
.await?;
+2
View File
@@ -102,6 +102,8 @@ async fn test_middleware() -> AnyResult<()> {
Box::new(PumpSwapParams::from_pool_address_by_rpc(&client.rpc, &pool_address).await?),
None,
true,
true,
true,
false,
)
.await?;
+2
View File
@@ -153,6 +153,8 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
None,
true,
false,
false,
false,
)
.await?;
@@ -146,6 +146,8 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
None,
true,
false,
false,
false,
)
.await?;
@@ -173,6 +175,8 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
None,
true,
false,
false,
false,
)
.await?;
@@ -113,6 +113,8 @@ async fn pumpfun_sniper_trade_with_shreds(trade_info: PumpFunTradeEvent) -> AnyR
Box::new(PumpFunParams::from_dev_trade(&trade_info, None)),
None,
true,
true,
true,
false,
)
.await?;
@@ -140,6 +142,8 @@ async fn pumpfun_sniper_trade_with_shreds(trade_info: PumpFunTradeEvent) -> AnyR
Box::new(PumpFunParams::immediate_sell(trade_info.creator_vault, true)),
None,
true,
true,
true,
false,
)
.await?;
@@ -33,6 +33,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Box::new(PumpSwapParams::from_pool_address_by_rpc(&client.rpc, &pool).await?),
None,
true,
true,
true,
false,
)
.await?;
@@ -58,6 +60,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
Box::new(PumpSwapParams::from_pool_address_by_rpc(&client.rpc, &pool).await?),
None,
true,
true,
true,
false,
)
.await?;
+4
View File
@@ -187,6 +187,8 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
Box::new(params.clone()),
None,
true,
true,
true,
false,
)
.await?;
@@ -216,6 +218,8 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
Box::new(params.clone()),
None,
true,
true,
true,
false,
)
.await?;
@@ -158,6 +158,8 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
Box::new(params),
None,
true,
true,
true,
false,
)
.await?;
@@ -186,6 +188,8 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
Box::new(params),
None,
true,
true,
true,
false,
)
.await?;
@@ -162,6 +162,8 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
Box::new(buy_params),
None,
true,
true,
true,
false,
)
.await?;
@@ -192,6 +194,8 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
Box::new(sell_params),
None,
true,
true,
true,
false,
)
.await?;
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "seed_trading"
version = "0.1.0"
edition = "2021"
[dependencies]
sol-trade-sdk = { path = "../.." }
solana-sdk = "2.3.0"
spl-associated-token-account = "7.0.0"
tokio = { version = "1", features = ["full"] }
spl-token= "8.0.0"
spl-token-2022 = { version = "8.0.0", features = ["no-entrypoint"] }
+109
View File
@@ -0,0 +1,109 @@
use sol_trade_sdk::{
common::{
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult,
PriorityFee, TradeConfig,
},
swqos::SwqosConfig,
trading::{core::params::PumpSwapParams, factory::DexType},
SolanaTrade,
};
use solana_sdk::{commitment_config::CommitmentConfig, signature::Keypair};
use solana_sdk::{pubkey::Pubkey, signer::Signer};
use std::{str::FromStr, sync::Arc};
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Testing PumpSwap trading...");
let client = create_solana_trade_client().await?;
let slippage_basis_points = Some(100);
let recent_blockhash = client.rpc.get_latest_blockhash().await?;
let pool = Pubkey::from_str("9qKxzRejsV6Bp2zkefXWCbGvg61c3hHei7ShXJ4FythA").unwrap();
let mint_pubkey = Pubkey::from_str("2zMMhcVQEXDtdE6vsFS7S7D5oUodfJHE8vd1gnBouauv").unwrap();
// Buy tokens
println!("Buying tokens from PumpSwap...");
let buy_sol_amount = 100_000;
client
.buy(
DexType::PumpSwap,
mint_pubkey,
buy_sol_amount,
slippage_basis_points,
recent_blockhash,
None,
Box::new(PumpSwapParams::from_pool_address_by_rpc(&client.rpc, &pool).await?),
None,
true,
true,
true,
true, // ❗️❗️❗️❗️ open seed optimize
)
.await?;
tokio::time::sleep(std::time::Duration::from_secs(4)).await;
// Sell tokens
println!("Selling tokens from PumpSwap...");
let rpc = client.rpc.clone();
let payer = client.payer.pubkey();
let program_id = spl_token::ID;
// ❗️❗️❗️❗️ Must use the 'use seed' method to get the ATA account, otherwise the transaction will fail
let account = get_associated_token_address_with_program_id_fast_use_seed(
&payer,
&mint_pubkey,
&program_id,
true,
);
let balance = rpc.get_token_account_balance(&account).await?;
let amount_token = balance.amount.parse::<u64>().unwrap();
client
.sell(
DexType::PumpSwap,
mint_pubkey,
amount_token,
slippage_basis_points,
recent_blockhash,
None,
false,
Box::new(PumpSwapParams::from_pool_address_by_rpc(&client.rpc, &pool).await?),
None,
true,
true,
true,
true, // ❗️❗️❗️❗️ open seed optimize
)
.await?;
tokio::signal::ctrl_c().await?;
Ok(())
}
/// Create SolanaTrade client
/// Initializes a new SolanaTrade client with configuration
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
println!("Creating SolanaTrade client...");
let payer = Keypair::from_base58_string("use_your_own_keypair");
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
let swqos_configs = vec![SwqosConfig::Default(rpc_url.clone())];
let mut priority_fee = PriorityFee::default();
priority_fee.buy_tip_fees = vec![0.001];
// Configure according to your needs
priority_fee.rpc_unit_limit = 150000;
let trade_config = TradeConfig {
rpc_url,
commitment: CommitmentConfig::confirmed(),
priority_fee: priority_fee,
swqos_configs,
};
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
println!("SolanaTrade client created successfully!");
Ok(solana_trade_client)
}
+4 -4
View File
@@ -91,7 +91,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(6);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions
.extend(crate::trading::common::handle_wsol(&params.payer.pubkey(), amount_in));
}
@@ -135,7 +135,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
instructions.push(Instruction::new_with_bytes(accounts::BONK, &data, accounts.to_vec()));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
@@ -220,7 +220,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(3);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions.extend(crate::trading::common::create_wsol_ata(&params.payer.pubkey()));
}
@@ -253,7 +253,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
instructions.push(Instruction::new_with_bytes(accounts::BONK, &data, accounts.to_vec()));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
+4 -4
View File
@@ -46,8 +46,8 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
let pool_quote_token_reserves = protocol_params.pool_quote_token_reserves;
let params_coin_creator_vault_ata = protocol_params.coin_creator_vault_ata;
let params_coin_creator_vault_authority = protocol_params.coin_creator_vault_authority;
let create_wsol_ata = protocol_params.create_wsol_ata;
let close_wsol_ata = protocol_params.close_wsol_ata;
let create_wsol_ata = params.create_wsol_ata;
let close_wsol_ata = params.close_wsol_ata;
let base_token_program = protocol_params.base_token_program;
let quote_token_program = protocol_params.quote_token_program;
let pool_base_token_account = protocol_params.pool_base_token_account;
@@ -214,8 +214,8 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
let pool_quote_token_account = protocol_params.pool_quote_token_account;
let params_coin_creator_vault_ata = protocol_params.coin_creator_vault_ata;
let params_coin_creator_vault_authority = protocol_params.coin_creator_vault_authority;
let create_wsol_ata = protocol_params.create_wsol_ata;
let close_wsol_ata = protocol_params.close_wsol_ata;
let create_wsol_ata = params.create_wsol_ata;
let close_wsol_ata = params.close_wsol_ata;
let base_token_program = protocol_params.base_token_program;
let quote_token_program = protocol_params.quote_token_program;
+4 -4
View File
@@ -65,7 +65,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(6);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions
.extend(crate::trading::common::handle_wsol(&params.payer.pubkey(), amount_in));
}
@@ -112,7 +112,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
accounts.to_vec(),
));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
// Close wSOL ATA account, reclaim rent
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
@@ -167,7 +167,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(3);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions.extend(crate::trading::common::create_wsol_ata(&params.payer.pubkey()));
}
@@ -203,7 +203,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
accounts.to_vec(),
));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
+4 -4
View File
@@ -100,7 +100,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(6);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions
.extend(crate::trading::common::handle_wsol(&params.payer.pubkey(), amount_in));
}
@@ -143,7 +143,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
accounts.to_vec(),
));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
// Close wSOL ATA account, reclaim rent
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
@@ -228,7 +228,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
// ========================================
let mut instructions = Vec::with_capacity(3);
if protocol_params.create_wsol_ata {
if params.create_wsol_ata {
instructions.extend(crate::trading::common::create_wsol_ata(&params.payer.pubkey()));
}
@@ -260,7 +260,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
accounts.to_vec(),
));
if protocol_params.close_wsol_ata {
if params.close_wsol_ata {
// Close wSOL ATA account, reclaim rent
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
}
+18 -3
View File
@@ -133,6 +133,9 @@ impl SolanaTrade {
/// * `extension_params` - Optional protocol-specific parameters (uses defaults if None)
/// * `lookup_table_key` - Optional address lookup table key for transaction optimization
/// * `wait_transaction_confirmed` - Whether to wait for the transaction to be confirmed
/// * `create_wsol_ata` - Whether to create wSOL ATA account
/// * `close_wsol_ata` - Whether to close wSOL ATA account
/// * `open_seed_optimize` - Whether to open seed optimize
///
/// # Returns
///
@@ -156,6 +159,8 @@ impl SolanaTrade {
extension_params: Box<dyn ProtocolParams>,
lookup_table_key: Option<Pubkey>,
wait_transaction_confirmed: bool,
create_wsol_ata: bool,
close_wsol_ata: bool,
open_seed_optimize: bool,
) -> Result<Signature, anyhow::Error> {
if slippage_basis_points.is_none() {
@@ -180,6 +185,8 @@ impl SolanaTrade {
wait_transaction_confirmed: wait_transaction_confirmed,
protocol_params: protocol_params.clone(),
open_seed_optimize,
create_wsol_ata,
close_wsol_ata,
swqos_clients: self.swqos_clients.clone(),
middleware_manager: self.middleware_manager.clone(),
};
@@ -223,6 +230,9 @@ impl SolanaTrade {
/// * `extension_params` - Optional protocol-specific parameters (uses defaults if None)
/// * `lookup_table_key` - Optional address lookup table key for transaction optimization
/// * `wait_transaction_confirmed` - Whether to wait for the transaction to be confirmed
/// * `create_wsol_ata` - Whether to create wSOL ATA account
/// * `close_wsol_ata` - Whether to close wSOL ATA account
/// * `open_seed_optimize` - Whether to open seed optimize
///
/// # Returns
///
@@ -248,6 +258,8 @@ impl SolanaTrade {
extension_params: Box<dyn ProtocolParams>,
lookup_table_key: Option<Pubkey>,
wait_transaction_confirmed: bool,
create_wsol_ata: bool,
close_wsol_ata: bool,
open_seed_optimize: bool,
) -> Result<Signature, anyhow::Error> {
if slippage_basis_points.is_none() {
@@ -278,6 +290,8 @@ impl SolanaTrade {
self.swqos_clients.clone()
},
middleware_manager: self.middleware_manager.clone(),
create_wsol_ata,
close_wsol_ata,
};
if custom_priority_fee.is_some() {
sell_params.priority_fee = Arc::new(custom_priority_fee.unwrap());
@@ -302,9 +316,6 @@ impl SolanaTrade {
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
}
let _swqos_clients =
if !with_tip { self.rpc_client.clone() } else { self.swqos_clients.clone() };
// Execute sell based on tip preference
executor.sell_with_tip(sell_params).await
}
@@ -354,6 +365,8 @@ impl SolanaTrade {
extension_params: Box<dyn ProtocolParams>,
lookup_table_key: Option<Pubkey>,
wait_transaction_confirmed: bool,
create_wsol_ata: bool,
close_wsol_ata: bool,
open_seed_optimize: bool,
) -> Result<Signature, anyhow::Error> {
if percent == 0 || percent > 100 {
@@ -371,6 +384,8 @@ impl SolanaTrade {
extension_params,
lookup_table_key,
wait_transaction_confirmed,
create_wsol_ata,
close_wsol_ata,
open_seed_optimize,
)
.await
+4 -30
View File
@@ -32,6 +32,8 @@ pub struct BuyParams {
pub open_seed_optimize: bool,
pub swqos_clients: Vec<Arc<SwqosClient>>,
pub middleware_manager: Option<Arc<MiddlewareManager>>,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
/// Sell parameters
@@ -51,6 +53,8 @@ pub struct SellParams {
pub open_seed_optimize: bool,
pub swqos_clients: Vec<Arc<SwqosClient>>,
pub middleware_manager: Option<Arc<MiddlewareManager>>,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
/// PumpFun protocol specific parameters
@@ -150,8 +154,6 @@ pub struct PumpSwapParams {
pub base_token_program: Pubkey,
/// Quote token program ID
pub quote_token_program: Pubkey,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
impl PumpSwapParams {
@@ -168,8 +170,6 @@ impl PumpSwapParams {
coin_creator_vault_authority: event.coin_creator_vault_authority,
base_token_program: event.base_token_program,
quote_token_program: event.quote_token_program,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
@@ -186,8 +186,6 @@ impl PumpSwapParams {
coin_creator_vault_authority: event.coin_creator_vault_authority,
base_token_program: event.base_token_program,
quote_token_program: event.quote_token_program,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
@@ -239,8 +237,6 @@ impl PumpSwapParams {
} else {
crate::constants::TOKEN_PROGRAM_2022
},
create_wsol_ata: true,
close_wsol_ata: true,
})
}
}
@@ -272,8 +268,6 @@ pub struct BonkParams {
pub platform_config: Pubkey,
pub platform_associated_account: Pubkey,
pub creator_associated_account: Pubkey,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
impl BonkParams {
@@ -284,8 +278,6 @@ impl BonkParams {
creator_associated_account: Pubkey,
) -> Self {
Self {
create_wsol_ata: true,
close_wsol_ata: true,
mint_token_program,
platform_config,
platform_associated_account,
@@ -306,8 +298,6 @@ impl BonkParams {
platform_config: trade_info.platform_config,
platform_associated_account: trade_info.platform_associated_account,
creator_associated_account: trade_info.creator_associated_account,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
@@ -363,8 +353,6 @@ impl BonkParams {
platform_config: trade_info.platform_config,
platform_associated_account: trade_info.platform_associated_account,
creator_associated_account: trade_info.creator_associated_account,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
@@ -400,8 +388,6 @@ impl BonkParams {
platform_config: pool_data.platform_config,
platform_associated_account,
creator_associated_account,
create_wsol_ata: true,
close_wsol_ata: true,
})
}
}
@@ -442,8 +428,6 @@ pub struct RaydiumCpmmParams {
pub quote_token_program: Pubkey,
/// Observation state account
pub observation_state: Pubkey,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
impl RaydiumCpmmParams {
@@ -464,8 +448,6 @@ impl RaydiumCpmmParams {
base_token_program: trade_info.input_token_program,
quote_token_program: trade_info.output_token_program,
observation_state: trade_info.observation_state,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
@@ -495,8 +477,6 @@ impl RaydiumCpmmParams {
base_token_program: pool.token0_program,
quote_token_program: pool.token1_program,
observation_state: pool.observation_key,
create_wsol_ata: true,
close_wsol_ata: true,
})
}
}
@@ -529,8 +509,6 @@ pub struct RaydiumAmmV4Params {
pub coin_reserve: u64,
/// Current pc reserve amount in the pool
pub pc_reserve: u64,
pub create_wsol_ata: bool,
pub close_wsol_ata: bool,
}
impl RaydiumAmmV4Params {
@@ -548,8 +526,6 @@ impl RaydiumAmmV4Params {
token_pc: amm_info.token_pc,
coin_reserve,
pc_reserve,
create_wsol_ata: true,
close_wsol_ata: true,
}
}
pub async fn from_amm_address_by_rpc(
@@ -567,8 +543,6 @@ impl RaydiumAmmV4Params {
token_pc: amm_info.token_pc,
coin_reserve,
pc_reserve,
create_wsol_ata: true,
close_wsol_ata: true,
})
}
}