refactor: Major SDK architecture refactoring and API consolidation

- Consolidate separate buy/sell modules into unified trading interface
- Remove protocol-specific buy/sell files (bonk, pumpfun, pumpswap)
- Add new trading constants and utility functions
- Simplify API with unified buy/sell methods supporting multiple protocols
- Enhance documentation with comprehensive examples and usage guides
- Add balance checking and token account management utilities
- Improve code organization and maintainability
This commit is contained in:
ysq
2025-07-10 18:14:21 +08:00
parent 57c2848a57
commit b891b2bc27
41 changed files with 1297 additions and 2744 deletions
+178 -238
View File
@@ -12,7 +12,7 @@ A comprehensive Rust SDK for seamless interaction with Solana DEX trading progra
6. **ShredStream Support**: Subscribe to program events using ShredStream
7. **Multiple MEV Protection**: Support for Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, and other services
8. **Concurrent Trading**: Send transactions using multiple MEV services simultaneously; the fastest succeeds while others fail
9. **Unified Trading Interface**: Use unified parameter structures for trading operations
9. **Unified Trading Interface**: Use unified trading protocol enums for trading operations
## Installation
@@ -38,18 +38,20 @@ sol-trade-sdk = { path = "./sol-trade-sdk", version = "0.1.0" }
```rust
use sol_trade_sdk::{
event_parser::{
protocols::{
pumpfun::{PumpFunCreateTokenEvent, PumpFunTradeEvent},
pumpswap::{
PumpSwapBuyEvent, PumpSwapCreatePoolEvent, PumpSwapDepositEvent,
PumpSwapSellEvent, PumpSwapWithdrawEvent,
streaming::{
event_parser::{
protocols::{
bonk::{BonkPoolCreateEvent, BonkTradeEvent},
pumpfun::{PumpFunCreateTokenEvent, PumpFunTradeEvent},
pumpswap::{
PumpSwapBuyEvent, PumpSwapCreatePoolEvent, PumpSwapDepositEvent,
PumpSwapSellEvent, PumpSwapWithdrawEvent,
},
},
bonk::{BonkPoolCreateEvent, BonkTradeEvent},
Protocol, UnifiedEvent,
},
Protocol, UnifiedEvent,
YellowstoneGrpc,
},
grpc::YellowstoneGrpc,
match_event,
};
@@ -97,11 +99,7 @@ async fn test_grpc() -> Result<(), Box<dyn std::error::Error>> {
// Subscribe to events from multiple protocols
println!("Starting to listen for events, press Ctrl+C to stop...");
let protocols = vec![
Protocol::PumpFun,
Protocol::PumpSwap,
Protocol::Bonk,
];
let protocols = vec![Protocol::PumpFun, Protocol::PumpSwap, Protocol::Bonk];
grpc.subscribe_events(protocols, None, None, None, callback)
.await?;
@@ -112,7 +110,7 @@ async fn test_grpc() -> Result<(), Box<dyn std::error::Error>> {
#### 1.2 Subscribe to Events Using ShredStream
```rust
use sol_trade_sdk::grpc::ShredStreamGrpc;
use sol_trade_sdk::streaming::ShredStreamGrpc;
async fn test_shreds() -> Result<(), Box<dyn std::error::Error>> {
// Subscribe to events using ShredStream client
@@ -155,11 +153,7 @@ async fn test_shreds() -> Result<(), Box<dyn std::error::Error>> {
// Subscribe to events
println!("Starting to listen for events, press Ctrl+C to stop...");
let protocols = vec![
Protocol::PumpFun,
Protocol::PumpSwap,
Protocol::Bonk,
];
let protocols = vec![Protocol::PumpFun, Protocol::PumpSwap, Protocol::Bonk];
shred_stream
.shredstream_subscribe(protocols, None, callback)
.await?;
@@ -177,127 +171,120 @@ use sol_trade_sdk::{
swqos::{SwqosConfig, SwqosRegion},
SolanaTrade
};
use solana_client::rpc_client::RpcClient;
use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signature::Keypair};
// Create trader account
let payer = Keypair::new();
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
/// Example of creating a SolanaTrade client
async fn test_create_solana_trade_client() -> AnyResult<SolanaTrade> {
println!("Creating SolanaTrade client...");
// Configure multiple MEV services to support concurrent trading
let swqos_configs = vec![
SwqosConfig::Jito(SwqosRegion::Frankfurt),
SwqosConfig::NextBlock("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::ZeroSlot("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Default(rpc_url.clone()),
];
let payer = Keypair::new();
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
// Define trading configuration
let trade_config = TradeConfig {
rpc_url: rpc_url.clone(),
commitment: CommitmentConfig::confirmed(),
priority_fee: PriorityFee::default(),
swqos_configs,
lookup_table_key: None,
};
// Configure various SWQOS services
let swqos_configs = vec![
SwqosConfig::Jito(SwqosRegion::Frankfurt),
SwqosConfig::NextBlock("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::ZeroSlot("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt),
SwqosConfig::Default(rpc_url.clone()),
];
// Create SolanaTrade instance
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
// Define trading configuration
let trade_config = TradeConfig {
rpc_url: rpc_url.clone(),
commitment: CommitmentConfig::confirmed(),
priority_fee: PriorityFee::default(),
swqos_configs,
lookup_table_key: None,
};
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
println!("SolanaTrade client created successfully!");
Ok(solana_trade_client)
}
```
### 3. PumpFun Trading Operations
```rust
use sol_trade_sdk::{
accounts::BondingCurveAccount,
constants::{pumpfun::global_constants::TOKEN_TOTAL_SUPPLY, trade_type},
pumpfun::common::get_bonding_curve_account_v2,
common::bonding_curve::BondingCurveAccount,
constants::pumpfun::global_constants::TOKEN_TOTAL_SUPPLY,
trading::{
core::params::{PumpFunParams, PumpFunSellParams},
BuyParams, SellParams,
core::params::PumpFunParams,
factory::TradingProtocol,
pumpfun::common::get_bonding_curve_account_v2,
},
};
async fn test_pumpfun() -> AnyResult<()> {
// Basic parameter setup
let creator = Pubkey::from_str("xxxxxx")?; // Developer account
let mint_pubkey = Pubkey::from_str("xxxxxx")?; // Token address
println!("Testing PumpFun trading...");
let solana_trade_client = test_create_solana_trade_client().await?;
let creator = Pubkey::from_str("xxxxxx")?; // dev account
let buy_sol_cost = 100_000; // 0.0001 SOL
let slippage_basis_points = Some(100);
let rpc = RpcClient::new(rpc_url);
let recent_blockhash = rpc.get_latest_blockhash().unwrap();
let recent_blockhash = solana_trade_client.rpc.get_latest_blockhash().await?;
let mint_pubkey = Pubkey::from_str("xxxxxx")?; // token mint
println!("Buying tokens from PumpFun...");
// Get bonding curve information
// get bonding curve
let (bonding_curve, bonding_curve_pda) =
get_bonding_curve_account_v2(&solana_trade_client.rpc, &mint_pubkey).await?;
let virtual_token_reserves = bonding_curve.virtual_token_reserves;
let virtual_sol_reserves = bonding_curve.virtual_sol_reserves;
let real_token_reserves = bonding_curve.real_token_reserves;
let real_sol_reserves = bonding_curve.real_sol_reserves;
let bonding_curve = BondingCurveAccount {
discriminator: bonding_curve.discriminator,
account: bonding_curve_pda,
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,
virtual_token_reserves: virtual_token_reserves,
virtual_sol_reserves: virtual_sol_reserves,
real_token_reserves: real_token_reserves,
real_sol_reserves: real_sol_reserves,
token_total_supply: TOKEN_TOTAL_SUPPLY,
complete: false,
creator: creator,
};
// Buy operation
let buy_protocol_params = PumpFunParams {
trade_type: trade_type::COPY_BUY.to_string(),
bonding_curve: Some(Arc::new(bonding_curve)),
};
let buy_params = BuyParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint_pubkey,
creator: creator,
amount_sol: buy_sol_cost,
slippage_basis_points: slippage_basis_points,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
data_size_limit: 0,
protocol_params: Box::new(buy_protocol_params.clone()),
};
// Buy with MEV protection
let buy_with_tip_params = buy_params
.clone()
.with_tip(solana_trade_client.swqos_clients.clone());
// For sniping developers
// let bonding_curve =
// BondingCurveAccount::new(&mint_pubkey, dev_buy_token, dev_cost_sol, creator);
// buy
solana_trade_client
.buy_use_buy_params(buy_with_tip_params, None)
.buy(
mint_pubkey,
Some(creator),
buy_sol_cost,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::PumpFun,
Some(Box::new(PumpFunParams {
bonding_curve: Some(Arc::new(bonding_curve.clone())),
})),
)
.await?;
// Sell operation
// sell
println!("Selling tokens from PumpFun...");
let sell_protocol_params = PumpFunSellParams {};
let amount_token = 1000000; // Enter the actual token amount
let sell_params = SellParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint_pubkey,
creator: creator,
amount_token: Some(amount_token),
slippage_basis_points: None,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
protocol_params: Box::new(sell_protocol_params.clone()),
};
let amount_token = 0; // Enter the actual amount_token
solana_trade_client
.sell_by_amount_use_sell_params(sell_params)
.sell(
mint_pubkey,
Some(creator),
amount_token,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::PumpFun,
None,
)
.await?;
Ok(())
}
```
@@ -305,73 +292,48 @@ async fn test_pumpfun() -> AnyResult<()> {
### 4. PumpSwap Trading Operations
```rust
use sol_trade_sdk::trading::core::params::PumpSwapParams;
async fn test_pumpswap() -> AnyResult<()> {
// Basic parameter setup
let creator = Pubkey::from_str("11111111111111111111111111111111")?; // Developer account
let mint_pubkey = Pubkey::from_str("2zMMhcVQEXDtdE6vsFS7S7D5oUodfJHE8vd1gnBouauv")?; // Token address
println!("Testing PumpSwap trading...");
let solana_trade_client = test_create_solana_trade_client().await?;
let creator = Pubkey::from_str("11111111111111111111111111111111")?; // dev account
let buy_sol_cost = 100_000; // 0.0001 SOL
let slippage_basis_points = Some(100);
let rpc = RpcClient::new(rpc_url);
let recent_blockhash = rpc.get_latest_blockhash().unwrap();
let recent_blockhash = solana_trade_client.rpc.get_latest_blockhash().await?;
let mint_pubkey = Pubkey::from_str("2zMMhcVQEXDtdE6vsFS7S7D5oUodfJHE8vd1gnBouauv")?; // token mint
println!("Buying tokens from PumpSwap...");
// PumpSwap parameter configuration
let protocol_params = PumpSwapParams {
pool: None,
pool_base_token_account: None,
pool_quote_token_account: None,
user_base_token_account: None,
user_quote_token_account: None,
auto_handle_wsol: true,
};
// Buy operation
let buy_params = BuyParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint_pubkey,
creator: creator,
amount_sol: buy_sol_cost,
slippage_basis_points: slippage_basis_points,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
data_size_limit: 0,
protocol_params: Box::new(protocol_params.clone()),
};
let buy_with_tip_params = buy_params
.clone()
.with_tip(solana_trade_client.swqos_clients.clone());
// buy
solana_trade_client
.buy_use_buy_params(buy_with_tip_params, None)
.buy(
mint_pubkey,
Some(creator),
buy_sol_cost,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::PumpSwap,
None,
)
.await?;
// Sell operation
// sell
println!("Selling tokens from PumpSwap...");
let amount_token = 1000000; // Enter the actual token amount
let sell_params = SellParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint_pubkey,
creator: creator,
amount_token: Some(amount_token),
slippage_basis_points: None,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
protocol_params: Box::new(protocol_params.clone()),
};
let amount_token = 0; // Enter the actual amount_token
solana_trade_client
.sell_by_amount_use_sell_params(sell_params)
.sell(
mint_pubkey,
Some(creator),
amount_token,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::PumpSwap,
None,
)
.await?;
Ok(())
}
```
@@ -379,68 +341,47 @@ async fn test_pumpswap() -> AnyResult<()> {
### 5. Bonk Trading Operations
```rust
use sol_trade_sdk::trading::core::params::BonkParams;
async fn test_bonk() -> Result<(), Box<dyn std::error::Error>> {
// Basic parameter setup
let amount = 100_000; // 0.0001 SOL
let mint = Pubkey::from_str("xxxxxxx")?;
let recent_blockhash = solana_trade_client.rpc.get_latest_blockhash().await?;
println!("Testing Bonk trading...");
// Bonk parameter configuration
let bonk_params = BonkParams {
virtual_base: None,
virtual_quote: None,
real_base_before: None,
real_quote_before: None,
auto_handle_wsol: true,
};
let solana_trade_client = test_create_solana_trade_client().await?;
let buy_sol_cost = 100_000; // 0.0001 SOL
let slippage_basis_points = Some(100); // 1%
let recent_blockhash = solana_trade_client.rpc.get_latest_blockhash().await?;
let mint_pubkey = Pubkey::from_str("xxxxxxx")?;
println!("Buying tokens from letsbonk.fun...");
// Buy operation
let buy_params = BuyParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint,
creator: Pubkey::default(),
amount_sol: amount,
slippage_basis_points: None,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
data_size_limit: 0,
protocol_params: Box::new(bonk_params.clone()),
};
let buy_with_tip_params = buy_params
.clone()
.with_tip(solana_trade_client.swqos_clients.clone());
// buy
solana_trade_client
.buy_use_buy_params(buy_with_tip_params, None)
.buy(
mint_pubkey,
None,
buy_sol_cost,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::Bonk,
None,
)
.await?;
// Sell operation
// sell
println!("Selling tokens from letsbonk.fun...");
let sell_params = SellParams {
rpc: Some(solana_trade_client.rpc.clone()),
payer: solana_trade_client.payer.clone(),
mint: mint,
creator: Pubkey::default(),
amount_token: None,
slippage_basis_points: None,
priority_fee: solana_trade_client.trade_config.clone().priority_fee,
lookup_table_key: solana_trade_client.trade_config.clone().lookup_table_key,
recent_blockhash,
protocol_params: Box::new(bonk_params.clone()),
};
let amount_token = 0; // Enter the actual amount_token
solana_trade_client
.sell_by_amount_use_sell_params(sell_params)
.sell(
mint_pubkey,
None,
amount_token,
slippage_basis_points,
recent_blockhash,
None,
false,
TradingProtocol::Bonk,
None,
)
.await?;
Ok(())
}
```
@@ -487,11 +428,11 @@ let trade_config = TradeConfig {
## New Architecture Features
### Unified Parameter Structure
### Unified Trading Interface
- **BuyParams**: Unified buy parameter structure
- **SellParams**: Unified sell parameter structure
- **Protocol-specific Parameters**: Each protocol has its own parameter structure (PumpFunParams, PumpSwapParams, BonkParams)
- **TradingProtocol Enum**: Use unified protocol enums (PumpFun, PumpSwap, Bonk)
- **Unified buy/sell Methods**: All protocols use the same trading method signatures
- **Protocol-specific Parameters**: Each protocol has its own parameter structure (PumpFunParams, etc.)
### Event Parsing System
@@ -509,29 +450,28 @@ let trade_config = TradeConfig {
```
src/
├── accounts/ # Account-related definitions
├── common/ # Common functionality and tools
├── constants/ # Constant definitions
├── error/ # Error handling
├── event_parser/ # Event parsing system
│ ├── common/ # Common event parsing tools
│ ├── core/ # Core parsing traits and interfaces
│ ├── protocols/ # Protocol-specific parsers
│ │ ├── pumpfun/ # PumpFun event parsing
│ │ ├── pumpswap/ # PumpSwap event parsing
│ │ └── bonk/ # Bonk event parsing
│ └── factory.rs # Parser factory
├── grpc/ # gRPC clients
├── instruction/ # Instruction building
├── protos/ # Protocol buffer definitions
├── pumpfun/ # PumpFun trading functionality
├── pumpswap/ # PumpSwap trading functionality
├── bonk/ # Bonk trading functionality
├── streaming/ # Event stream processing
│ ├── event_parser/ # Event parsing system
│ │ ├── common/ # Common event parsing tools
│ │ ├── core/ # Core parsing traits and interfaces
│ │ ├── protocols/# Protocol-specific parsers
│ │ │ ├── bonk/ # Bonk event parsing
│ │ │ ├── pumpfun/ # PumpFun event parsing
│ │ │ └── pumpswap/ # PumpSwap event parsing
│ │ └── factory.rs # Parser factory
│ ├── shred_stream.rs # ShredStream client
│ └── yellowstone_grpc.rs # Yellowstone gRPC client
├── swqos/ # MEV service clients
├── trading/ # Unified trading engine
│ ├── common/ # Common trading tools
│ ├── core/ # Core trading engine
── protocols/ # Protocol-specific trading implementations
── bonk/ # Bonk trading implementation
│ ├── pumpfun/ # PumpFun trading implementation
│ ├── pumpswap/ # PumpSwap trading implementation
│ └── factory.rs # Trading factory
├── lib.rs # Main library file
└── main.rs # Example program
```