feat: refactor event parsing architecture and add Raydium Launchpad support
Major changes: - Refactor event parsing system: migrate scattered logs_* modules to unified event_parser architecture - Add unified UnifiedEvent trait and EventParser trait for standardized event parsing interface - Introduce GenericEventParser and EventParserFactory for plugin-style protocol extension - Add match_event! macro to simplify event type matching and handling - Add Raydium Launchpad (Bonk.fun) protocol support: - Complete buy/sell trading functionality - Pool state management and querying - Event parsing and subscription - Update trading system to support new protocol architecture - Refactor constants organization, rename raydium to raydium_launchpad - Update documentation and example code Technical improvements: - Unified event interface design for better code maintainability - Factory pattern implementation for dynamic protocol loading - Generic event parser to reduce code duplication - Improved error handling and type safety Breaking Changes: - Remove old logs_* modules, use new event_parser system - Protocol constants path change: raydium -> raydium_launchpad - Event subscription API updated to unified interface
This commit is contained in:
@@ -1,18 +1,18 @@
|
||||
# Sol Trade SDK
|
||||
|
||||
A comprehensive Rust SDK for seamless interaction with Solana DEX trading programs. This SDK provides a robust set of tools and interfaces to integrate PumpFun and PumpSwap functionality into your applications.
|
||||
A comprehensive Rust SDK for seamless interaction with Solana DEX trading programs. This SDK provides a robust set of tools and interfaces to integrate PumpFun, PumpSwap, and Raydium Launchpad (Bonk.fun) functionality into your applications.
|
||||
|
||||
## Features
|
||||
## Project Features
|
||||
|
||||
1. **PumpFun Trading**: Support for `buy`, `sell` operations
|
||||
1. **PumpFun Trading**: Support for `buy` and `sell` operations
|
||||
2. **PumpSwap Trading**: Support for PumpSwap pool trading operations
|
||||
3. **Raydium Trading**: Support for Raydium DEX trading operations
|
||||
4. **Logs Subscription**: Subscribe to PumpFun, PumpSwap, and Raydium program transaction logs
|
||||
5. **Yellowstone gRPC**: Subscribe to program logs using Yellowstone gRPC
|
||||
6. **ShredStream Support**: Subscribe to program logs using ShredStream
|
||||
7. **Multiple MEV Protection**: Support for Jito, Nextblock, 0slot, Nozomi services
|
||||
8. **Concurrent Transactions**: Submit transactions using multiple MEV services simultaneously; the fastest succeeds while others fail
|
||||
9. **Real-time Pricing**: Get real-time token prices and liquidity information
|
||||
3. **Raydium Trading**: Support for Raydium Launchpad (Bonk.fun) trading operations
|
||||
4. **Event Subscription**: Subscribe to PumpFun, PumpSwap, and Raydium Launchpad (Bonk.fun) program trading events
|
||||
5. **Yellowstone gRPC**: Subscribe to program events using Yellowstone gRPC
|
||||
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
|
||||
|
||||
## Installation
|
||||
|
||||
@@ -32,53 +32,425 @@ sol-trade-sdk = { path = "./sol-trade-sdk", version = "0.1.0" }
|
||||
|
||||
## Usage Examples
|
||||
|
||||
### 1. Logs Subscription - Monitor Token Trading
|
||||
### 1. Event Subscription - Monitor Token Trading
|
||||
|
||||
#### 1.1 Subscribe to Events Using Yellowstone gRPC
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{common::pumpfun::logs_events::PumpfunEvent, grpc::YellowstoneGrpc};
|
||||
use solana_sdk::signature::Keypair;
|
||||
|
||||
// Create gRPC client with Yellowstone
|
||||
let grpc_url = "https://solana-yellowstone-grpc.publicnode.com:443";
|
||||
let x_token = None; // Optional auth token
|
||||
let client = YellowstoneGrpc::new(grpc_url.to_string(), x_token)?;
|
||||
|
||||
// Define callback function
|
||||
let callback = |event: PumpfunEvent| match event {
|
||||
PumpfunEvent::NewDevTrade(trade_info) => {
|
||||
println!("Received new dev trade event: {:?}", trade_info);
|
||||
}
|
||||
PumpfunEvent::NewToken(token_info) => {
|
||||
println!("Received new token event: {:?}", token_info);
|
||||
}
|
||||
PumpfunEvent::NewUserTrade(trade_info) => {
|
||||
println!("Received new trade event: {:?}", trade_info);
|
||||
}
|
||||
PumpfunEvent::NewBotTrade(trade_info) => {
|
||||
println!("Received new bot trade event: {:?}", trade_info);
|
||||
}
|
||||
PumpfunEvent::Error(err) => {
|
||||
println!("Received error: {}", err);
|
||||
}
|
||||
use sol_trade_sdk::{
|
||||
event_parser::{
|
||||
protocols::{
|
||||
pumpfun::{PumpFunCreateTokenEvent, PumpFunTradeEvent},
|
||||
pumpswap::{
|
||||
PumpSwapBuyEvent, PumpSwapCreatePoolEvent, PumpSwapDepositEvent,
|
||||
PumpSwapSellEvent, PumpSwapWithdrawEvent,
|
||||
},
|
||||
raydium_launchpad::{RaydiumLaunchpadPoolCreateEvent, RaydiumLaunchpadTradeEvent},
|
||||
},
|
||||
Protocol, UnifiedEvent,
|
||||
},
|
||||
grpc::YellowstoneGrpc,
|
||||
match_event,
|
||||
};
|
||||
|
||||
client.subscribe_pumpfun(callback, None).await?;
|
||||
async fn test_grpc() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Subscribe to events using GRPC client
|
||||
println!("Subscribing to GRPC events...");
|
||||
|
||||
let grpc = YellowstoneGrpc::new(
|
||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
||||
None,
|
||||
)?;
|
||||
|
||||
// Define callback function to handle events
|
||||
let callback = |event: Box<dyn UnifiedEvent>| {
|
||||
match_event!(event, {
|
||||
RaydiumLaunchpadPoolCreateEvent => |e: RaydiumLaunchpadPoolCreateEvent| {
|
||||
println!("RaydiumLaunchpadPoolCreateEvent: {:?}", e.base_mint_param.symbol);
|
||||
},
|
||||
RaydiumLaunchpadTradeEvent => |e: RaydiumLaunchpadTradeEvent| {
|
||||
println!("RaydiumLaunchpadTradeEvent: {:?}", e);
|
||||
},
|
||||
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
|
||||
println!("PumpFunTradeEvent: {:?}", e);
|
||||
},
|
||||
PumpFunCreateTokenEvent => |e: PumpFunCreateTokenEvent| {
|
||||
println!("PumpFunCreateTokenEvent: {:?}", e);
|
||||
},
|
||||
PumpSwapBuyEvent => |e: PumpSwapBuyEvent| {
|
||||
println!("Buy event: {:?}", e);
|
||||
},
|
||||
PumpSwapSellEvent => |e: PumpSwapSellEvent| {
|
||||
println!("Sell event: {:?}", e);
|
||||
},
|
||||
PumpSwapCreatePoolEvent => |e: PumpSwapCreatePoolEvent| {
|
||||
println!("CreatePool event: {:?}", e);
|
||||
},
|
||||
PumpSwapDepositEvent => |e: PumpSwapDepositEvent| {
|
||||
println!("Deposit event: {:?}", e);
|
||||
},
|
||||
PumpSwapWithdrawEvent => |e: PumpSwapWithdrawEvent| {
|
||||
println!("Withdraw event: {:?}", e);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// 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::RaydiumLaunchpad,
|
||||
];
|
||||
grpc.subscribe_events(protocols, None, None, None, callback)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
#### 1.2 Subscribe to Events Using ShredStream
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::grpc::ShredStreamGrpc;
|
||||
|
||||
async fn test_shreds() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Subscribe to events using ShredStream client
|
||||
println!("Subscribing to ShredStream events...");
|
||||
|
||||
let shred_stream = ShredStreamGrpc::new("http://127.0.0.1:10800".to_string()).await?;
|
||||
|
||||
// Define callback function to handle events (same as above)
|
||||
let callback = |event: Box<dyn UnifiedEvent>| {
|
||||
match_event!(event, {
|
||||
RaydiumLaunchpadPoolCreateEvent => |e: RaydiumLaunchpadPoolCreateEvent| {
|
||||
println!("RaydiumLaunchpadPoolCreateEvent: {:?}", e.base_mint_param.symbol);
|
||||
},
|
||||
RaydiumLaunchpadTradeEvent => |e: RaydiumLaunchpadTradeEvent| {
|
||||
println!("RaydiumLaunchpadTradeEvent: {:?}", e);
|
||||
},
|
||||
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
|
||||
println!("PumpFunTradeEvent: {:?}", e);
|
||||
},
|
||||
PumpFunCreateTokenEvent => |e: PumpFunCreateTokenEvent| {
|
||||
println!("PumpFunCreateTokenEvent: {:?}", e);
|
||||
},
|
||||
PumpSwapBuyEvent => |e: PumpSwapBuyEvent| {
|
||||
println!("Buy event: {:?}", e);
|
||||
},
|
||||
PumpSwapSellEvent => |e: PumpSwapSellEvent| {
|
||||
println!("Sell event: {:?}", e);
|
||||
},
|
||||
PumpSwapCreatePoolEvent => |e: PumpSwapCreatePoolEvent| {
|
||||
println!("CreatePool event: {:?}", e);
|
||||
},
|
||||
PumpSwapDepositEvent => |e: PumpSwapDepositEvent| {
|
||||
println!("Deposit event: {:?}", e);
|
||||
},
|
||||
PumpSwapWithdrawEvent => |e: PumpSwapWithdrawEvent| {
|
||||
println!("Withdraw event: {:?}", e);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
// Subscribe to events
|
||||
println!("Starting to listen for events, press Ctrl+C to stop...");
|
||||
let protocols = vec![
|
||||
Protocol::PumpFun,
|
||||
Protocol::PumpSwap,
|
||||
Protocol::RaydiumLaunchpad,
|
||||
];
|
||||
shred_stream
|
||||
.shredstream_subscribe(protocols, None, callback)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Initialize SolanaTrade Instance
|
||||
|
||||
```rust
|
||||
use std::{str::FromStr, sync::Arc};
|
||||
|
||||
use sol_trade_sdk::{
|
||||
common::{AnyResult, PriorityFee, TradeConfig},
|
||||
swqos::{SwqosConfig, SwqosRegion, SwqosType},
|
||||
common::{AnyResult, PriorityFee, TradeConfig},
|
||||
swqos::{SwqosConfig, SwqosRegion},
|
||||
SolanaTrade
|
||||
};
|
||||
use solana_client::rpc_client::RpcClient;
|
||||
use solana_sdk::{commitment_config::CommitmentConfig, pubkey::Pubkey, signature::Keypair};
|
||||
|
||||
// Configure priority fees
|
||||
// Create trader account
|
||||
let payer = Keypair::new();
|
||||
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
||||
|
||||
// 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()),
|
||||
];
|
||||
|
||||
// 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,
|
||||
};
|
||||
|
||||
// Create SolanaTrade instance
|
||||
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
```
|
||||
|
||||
### 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,
|
||||
trading::{
|
||||
core::params::{PumpFunParams, PumpFunSellParams},
|
||||
BuyParams, SellParams,
|
||||
},
|
||||
};
|
||||
|
||||
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
|
||||
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();
|
||||
|
||||
println!("Buying tokens from PumpFun...");
|
||||
|
||||
// Get bonding curve information
|
||||
let (bonding_curve, bonding_curve_pda) =
|
||||
get_bonding_curve_account_v2(&solana_trade_client.rpc, &mint_pubkey).await?;
|
||||
|
||||
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,
|
||||
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());
|
||||
|
||||
solana_trade_client
|
||||
.buy_use_buy_params(buy_with_tip_params, None)
|
||||
.await?;
|
||||
|
||||
// Sell operation
|
||||
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()),
|
||||
};
|
||||
|
||||
solana_trade_client
|
||||
.sell_by_amount_use_sell_params(sell_params)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### 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
|
||||
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();
|
||||
|
||||
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());
|
||||
|
||||
solana_trade_client
|
||||
.buy_use_buy_params(buy_with_tip_params, None)
|
||||
.await?;
|
||||
|
||||
// Sell operation
|
||||
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()),
|
||||
};
|
||||
|
||||
solana_trade_client
|
||||
.sell_by_amount_use_sell_params(sell_params)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### 5. Raydium Launchpad Trading Operations
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::trading::core::params::RaydiumLaunchpadParams;
|
||||
|
||||
async fn test_raydium_launchpad() -> 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?;
|
||||
|
||||
// Raydium Launchpad parameter configuration
|
||||
let raydium_launchpad_params = RaydiumLaunchpadParams {
|
||||
virtual_base: None,
|
||||
virtual_quote: None,
|
||||
real_base_before: None,
|
||||
real_quote_before: None,
|
||||
auto_handle_wsol: true,
|
||||
};
|
||||
|
||||
println!("Buying tokens from Raydium Launchpad...");
|
||||
|
||||
// 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(raydium_launchpad_params.clone()),
|
||||
};
|
||||
|
||||
let buy_with_tip_params = buy_params
|
||||
.clone()
|
||||
.with_tip(solana_trade_client.swqos_clients.clone());
|
||||
|
||||
solana_trade_client
|
||||
.buy_use_buy_params(buy_with_tip_params, None)
|
||||
.await?;
|
||||
|
||||
// Sell operation
|
||||
println!("Selling tokens from Raydium Launchpad...");
|
||||
|
||||
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(raydium_launchpad_params.clone()),
|
||||
};
|
||||
|
||||
solana_trade_client
|
||||
.sell_by_amount_use_sell_params(sell_params)
|
||||
.await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
### 6. Custom Priority Fee Configuration
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::common::PriorityFee;
|
||||
|
||||
// Custom priority fee configuration
|
||||
let priority_fee = PriorityFee {
|
||||
unit_limit: 190000,
|
||||
unit_price: 1000000,
|
||||
@@ -89,327 +461,79 @@ let priority_fee = PriorityFee {
|
||||
sell_tip_fee: 0.0001,
|
||||
};
|
||||
|
||||
// Configure multiple swqos in single region, can send transactions concurrently
|
||||
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
||||
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()),
|
||||
];
|
||||
|
||||
// Define sdk configuration
|
||||
// Use custom priority fee in TradeConfig
|
||||
let trade_config = TradeConfig {
|
||||
rpc_url: rpc_url.clone(),
|
||||
commitment: CommitmentConfig::confirmed(),
|
||||
priority_fee,
|
||||
priority_fee, // Use custom priority fee
|
||||
swqos_configs,
|
||||
lookup_table_key: None,
|
||||
};
|
||||
|
||||
// Create SolanaTrade instance
|
||||
let payer = Keypair::from_base58_string("your_private_key");
|
||||
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
```
|
||||
|
||||
### 3. Buy Tokens
|
||||
|
||||
### 3.1 Buy Tokens --- Sniping
|
||||
```rust
|
||||
use solana_sdk::{pubkey::Pubkey, hash::Hash};
|
||||
use std::sync::Arc;
|
||||
use sol_trade_sdk::accounts::BondingCurveAccount;
|
||||
|
||||
let mint_pubkey = Pubkey::from_str("token_address")?;
|
||||
let creator = Pubkey::from_str("creator_address")?;
|
||||
let recent_blockhash = Hash::default(); // Get latest blockhash
|
||||
let buy_sol_cost = 50000; // 0.00005 SOL
|
||||
let slippage_basis_points = Some(100); // 1%
|
||||
|
||||
// Sniping buy (quick purchase when new token launches)
|
||||
let dev_buy_token = 100_000; // Test value
|
||||
let dev_cost_sol = 10_000; // Test value
|
||||
let bonding_curve = BondingCurveAccount::new(&mint_pubkey, dev_buy_token, dev_cost_sol, creator);
|
||||
|
||||
solana_trade_client.sniper_buy(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
buy_sol_cost,
|
||||
slippage_basis_points,
|
||||
recent_blockhash,
|
||||
Some(Arc::new(bonding_curve)),
|
||||
).await?;
|
||||
|
||||
// Buy with MEV protection using tips
|
||||
solana_trade_client.sniper_buy_with_tip(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
buy_sol_cost,
|
||||
slippage_basis_points,
|
||||
recent_blockhash,
|
||||
Some(Arc::new(bonding_curve)),
|
||||
None, // Custom tip
|
||||
).await?;
|
||||
```
|
||||
|
||||
### 3.2 Buy Tokens --- Copy Trading
|
||||
```rust
|
||||
use solana_sdk::{pubkey::Pubkey, hash::Hash};
|
||||
use std::sync::Arc;
|
||||
use sol_trade_sdk::accounts::BondingCurveAccount;
|
||||
use sol_trade_sdk::{constants::{pumpfun::global_constants::TOKEN_TOTAL_SUPPLY, trade_type::COPY_BUY}, pumpfun::common::get_bonding_curve_pda};
|
||||
|
||||
let mint_pubkey = Pubkey::from_str("token_address")?;
|
||||
let creator = Pubkey::from_str("creator_address")?;
|
||||
let recent_blockhash = Hash::default(); // Get latest blockhash
|
||||
let buy_sol_cost = 50000; // 0.00005 SOL
|
||||
let slippage_basis_points = Some(100); // 1%
|
||||
|
||||
// Copy trading buy
|
||||
let dev_buy_token = 100_000; // Test value
|
||||
let dev_cost_sol = 10_000; // Test value
|
||||
// trade_info comes from pumpfun parsed data, refer to section 1. Logs Subscription above
|
||||
let bonding_curve = Some(Arc::new(BondingCurveAccount {
|
||||
discriminator: 0,
|
||||
account: get_bonding_curve_pda(&trade_info.mint).unwrap(),
|
||||
virtual_token_reserves: trade_info.virtual_token_reserves,
|
||||
virtual_sol_reserves: trade_info.virtual_sol_reserves,
|
||||
real_token_reserves: trade_info.real_token_reserves,
|
||||
real_sol_reserves: trade_info.real_sol_reserves,
|
||||
token_total_supply: TOKEN_TOTAL_SUPPLY,
|
||||
complete: false,
|
||||
creator: Pubkey::from_str(&creator).unwrap(),
|
||||
}));
|
||||
|
||||
solana_trade_client.buy(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
buy_sol_cost,
|
||||
slippage_basis_points,
|
||||
recent_blockhash,
|
||||
Some(Arc::new(bonding_curve)),
|
||||
"pumpfun".to_string(),
|
||||
).await?;
|
||||
|
||||
// Buy with MEV protection using tips
|
||||
solana_trade_client.buy_with_tip(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
buy_sol_cost,
|
||||
slippage_basis_points,
|
||||
recent_blockhash,
|
||||
Some(Arc::new(bonding_curve)),
|
||||
"pumpfun".to_string(),
|
||||
None, // Custom tip
|
||||
).await?;
|
||||
```
|
||||
|
||||
### 4. Sell Tokens
|
||||
|
||||
```rust
|
||||
// Sell by amount
|
||||
solana_trade_client.sell_by_amount_with_tip(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
1000000, // token amount
|
||||
recent_blockhash,
|
||||
"pumpfun".to_string(), // trading platform
|
||||
).await?;
|
||||
|
||||
// Sell by percentage
|
||||
solana_trade_client.sell_by_percent_with_tip(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
50, // percentage (50%)
|
||||
2000000, // total token amount
|
||||
recent_blockhash,
|
||||
"pumpfun".to_string(), // trading platform
|
||||
).await?;
|
||||
```
|
||||
|
||||
### 5. Get Price and Balance Information
|
||||
|
||||
```rust
|
||||
// Get current token price
|
||||
let price = solana_trade_client.get_current_price(&mint_pubkey).await?;
|
||||
println!("Current price: {}", price);
|
||||
|
||||
// Get SOL balance
|
||||
let sol_balance = solana_trade_client.get_payer_sol_balance().await?;
|
||||
println!("SOL balance: {} lamports", sol_balance);
|
||||
|
||||
// Get token balance
|
||||
let token_balance = solana_trade_client.get_payer_token_balance(&mint_pubkey).await?;
|
||||
println!("Token balance: {}", token_balance);
|
||||
|
||||
// Get liquidity information
|
||||
let sol_reserves = solana_trade_client.get_real_sol_reserves(&mint_pubkey).await?;
|
||||
println!("SOL reserves: {} lamports", sol_reserves);
|
||||
```
|
||||
|
||||
### 6. PumpSwap Subscription - Monitor AMM Events
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{common::pumpswap::logs_events::PumpSwapEvent, grpc::YellowstoneGrpc};
|
||||
|
||||
// Create gRPC client with Yellowstone
|
||||
let grpc_url = "https://solana-yellowstone-grpc.publicnode.com:443";
|
||||
let x_token = None;
|
||||
let client = YellowstoneGrpc::new(grpc_url.to_string(), x_token)?;
|
||||
|
||||
// Define callback function for PumpSwap events
|
||||
let callback = |event: PumpSwapEvent| match event {
|
||||
PumpSwapEvent::Buy(buy_event) => {
|
||||
println!("buy_event: {:?}", buy_event);
|
||||
}
|
||||
PumpSwapEvent::Sell(sell_event) => {
|
||||
println!("sell_event: {:?}", sell_event);
|
||||
}
|
||||
PumpSwapEvent::CreatePool(create_event) => {
|
||||
println!("create_event: {:?}", create_event);
|
||||
}
|
||||
PumpSwapEvent::Deposit(deposit_event) => {
|
||||
println!("deposit_event: {:?}", deposit_event);
|
||||
}
|
||||
PumpSwapEvent::Withdraw(withdraw_event) => {
|
||||
println!("withdraw_event: {:?}", withdraw_event);
|
||||
}
|
||||
PumpSwapEvent::Disable(disable_event) => {
|
||||
println!("disable_event: {:?}", disable_event);
|
||||
}
|
||||
PumpSwapEvent::UpdateAdmin(update_admin_event) => {
|
||||
println!("update_admin_event: {:?}", update_admin_event);
|
||||
}
|
||||
PumpSwapEvent::UpdateFeeConfig(update_fee_event) => {
|
||||
println!("update_fee_event: {:?}", update_fee_event);
|
||||
}
|
||||
PumpSwapEvent::Error(err) => {
|
||||
println!("error: {}", err);
|
||||
}
|
||||
};
|
||||
|
||||
// Subscribe to PumpSwap events
|
||||
println!("Monitoring PumpSwap events, press Ctrl+C to stop...");
|
||||
client.subscribe_pumpswap(callback).await?;
|
||||
```
|
||||
|
||||
### 7. PumpSwap Trading Operations
|
||||
|
||||
```rust
|
||||
use std::sync::Arc;
|
||||
use solana_sdk::{pubkey::Pubkey, hash::Hash, signature::Keypair};
|
||||
use solana_client::rpc_client::RpcClient;
|
||||
use sol_trade_sdk::{common::{Cluster, PriorityFee}, SolanaTrade};
|
||||
|
||||
// Configure multiple swqos in single region, can send transactions concurrently
|
||||
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
||||
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()),
|
||||
];
|
||||
|
||||
// Define sdk configuration
|
||||
let trade_config = TradeConfig {
|
||||
rpc_url: rpc_url.clone(),
|
||||
commitment: CommitmentConfig::confirmed(),
|
||||
priority_fee,
|
||||
swqos_configs,
|
||||
lookup_table_key: None,
|
||||
};
|
||||
|
||||
// Create SolanaTrade instance
|
||||
let payer = Keypair::from_base58_string("your_private_key");
|
||||
let solana_trade_client = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
|
||||
let creator = Pubkey::from_str("11111111111111111111111111111111")?; // dev account
|
||||
let buy_sol_cost = 500_000; // 0.0005 SOL
|
||||
let slippage_basis_points = Some(100);
|
||||
let rpc = RpcClient::new(cluster.rpc_url);
|
||||
let recent_blockhash = rpc.get_latest_blockhash().unwrap();
|
||||
let trade_platform = "pumpswap".to_string();
|
||||
let mint_pubkey = Pubkey::from_str("YOUR_TOKEN_MINT")?; // token mint
|
||||
|
||||
println!("Buying tokens from PumpSwap...");
|
||||
solana_trade_client
|
||||
.buy(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
buy_sol_cost,
|
||||
slippage_basis_points,
|
||||
recent_blockhash,
|
||||
None,
|
||||
trade_platform.clone(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
// Sell 30% * amount_token quantity
|
||||
solana_trade_client
|
||||
.sell_by_percent(
|
||||
mint_pubkey,
|
||||
creator,
|
||||
30, // percentage (30%)
|
||||
100, // total token amount
|
||||
recent_blockhash,
|
||||
trade_platform.clone(),
|
||||
)
|
||||
.await?;
|
||||
```
|
||||
|
||||
### 8. PumpSwap Pool Information
|
||||
|
||||
```rust
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
let pool_address = Pubkey::from_str("pool_address")?;
|
||||
|
||||
// Get current price from PumpSwap pool
|
||||
let price = solana_trade_client.get_current_price_with_pumpswap(&pool_address).await?;
|
||||
println!("PumpSwap pool price: {}", price);
|
||||
|
||||
// Get SOL reserves in PumpSwap pool
|
||||
let sol_reserves = solana_trade_client.get_real_sol_reserves_with_pumpswap(&pool_address).await?;
|
||||
println!("PumpSwap SOL reserves: {} lamports", sol_reserves);
|
||||
|
||||
// Get token balance in PumpSwap pool
|
||||
let token_balance = solana_trade_client.get_payer_token_balance_with_pumpswap(&pool_address).await?;
|
||||
println!("PumpSwap token balance: {}", token_balance);
|
||||
```
|
||||
|
||||
## Supported Trading Platforms
|
||||
|
||||
- **PumpFun**: Primary meme coin trading platform
|
||||
- **PumpSwap**: PumpFun's swap protocol
|
||||
- **Raydium**: Integrated Raydium DEX functionality
|
||||
- **Raydium Launchpad**: Raydium's token launch platform (Bonk.fun)
|
||||
|
||||
## MEV Protection Services
|
||||
|
||||
- **Jito**: High-performance block space
|
||||
- **Nextblock**: Fast transaction execution
|
||||
- **0slot**: Zero-latency transactions
|
||||
- **Nozomi**: MEV protection service
|
||||
- **NextBlock**: Fast transaction execution
|
||||
- **ZeroSlot**: Zero-latency transactions
|
||||
- **Temporal**: Time-sensitive transactions
|
||||
- **Bloxroute**: Blockchain network acceleration
|
||||
|
||||
## New Architecture Features
|
||||
|
||||
### Unified Parameter Structure
|
||||
|
||||
- **BuyParams**: Unified buy parameter structure
|
||||
- **SellParams**: Unified sell parameter structure
|
||||
- **Protocol-specific Parameters**: Each protocol has its own parameter structure (PumpFunParams, PumpSwapParams, RaydiumLaunchpadParams)
|
||||
|
||||
### Event Parsing System
|
||||
|
||||
- **Unified Event Interface**: All protocol events implement the UnifiedEvent trait
|
||||
- **Protocol-specific Events**: Each protocol has its own event types
|
||||
- **Event Factory**: Automatically identifies and parses events from different protocols
|
||||
|
||||
### Trading Engine
|
||||
|
||||
- **Unified Trading Interface**: All trading operations use the same methods
|
||||
- **Protocol Abstraction**: Supports trading operations across multiple protocols
|
||||
- **Concurrent Execution**: Supports sending transactions to multiple MEV services simultaneously
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
src/
|
||||
├── accounts/ # Account-related definitions
|
||||
├── common/ # Common utilities and tools
|
||||
├── constants/ # Constant definitions
|
||||
├── error/ # Error handling
|
||||
├── grpc/ # gRPC clients
|
||||
├── instruction/ # Instruction building
|
||||
├── pumpfun/ # PumpFun trading functionality
|
||||
├── pumpswap/ # PumpSwap trading functionality
|
||||
├── swqos/ # MEV service clients
|
||||
├── trading/ # Unified trading engine
|
||||
├── lib.rs # Main library file
|
||||
└── main.rs # Example program
|
||||
├── 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
|
||||
│ │ └── raydium_launchpad/ # Raydium Launchpad event parsing
|
||||
│ └── factory.rs # Parser factory
|
||||
├── grpc/ # gRPC clients
|
||||
├── instruction/ # Instruction building
|
||||
├── protos/ # Protocol buffer definitions
|
||||
├── pumpfun/ # PumpFun trading functionality
|
||||
├── pumpswap/ # PumpSwap trading functionality
|
||||
├── raydium_launchpad/ # Raydium Launchpad trading functionality
|
||||
├── swqos/ # MEV service clients
|
||||
├── trading/ # Unified trading engine
|
||||
│ ├── common/ # Common trading tools
|
||||
│ ├── core/ # Core trading engine
|
||||
│ └── protocols/ # Protocol-specific trading implementations
|
||||
├── lib.rs # Main library file
|
||||
└── main.rs # Example program
|
||||
```
|
||||
|
||||
## License
|
||||
@@ -418,7 +542,7 @@ MIT License
|
||||
|
||||
## Contact
|
||||
|
||||
- Repository: https://github.com/0xfnzero/sol-trade-sdk
|
||||
- Project Repository: https://github.com/0xfnzero/sol-trade-sdk
|
||||
- Telegram Group: https://t.me/fnzero_group
|
||||
|
||||
## Important Notes
|
||||
|
||||
Reference in New Issue
Block a user