MCPcopy Index your code
hub / github.com/0xfnzero/sol-trade-sdk

github.com/0xfnzero/sol-trade-sdk @v4.0.22

Chat with this repo
repository ↗ · DeepWiki ↗ · release v4.0.22 ↗ · + Follow
1,312 symbols 3,314 edges 138 files 334 documented · 25%
What it actually does AI analysis from the code graph — generated when you open this
loading…
README
<h1>🚀 Sol Trade SDK</h1>
<h3><em>A comprehensive Rust SDK for seamless Solana DEX trading</em></h3>







<strong>A high-performance Rust SDK for low-latency Solana DEX trading bots. Built for speed and efficiency, it enables seamless, high-throughput interaction with PumpFun, Pump AMM (PumpSwap), Bonk, Meteora DAMM v2, Raydium AMM v4, and Raydium CPMM for latency-critical trading strategies.</strong>







<a href="https://crates.io/crates/sol-trade-sdk">
    <img src="https://img.shields.io/crates/v/sol-trade-sdk.svg" alt="Crates.io">
</a>
<a href="https://docs.rs/sol-trade-sdk">
    <img src="https://docs.rs/sol-trade-sdk/badge.svg" alt="Documentation">
</a>
<a href="https://github.com/0xfnzero/sol-trade-sdk/blob/main/LICENSE">
    <img src="https://img.shields.io/badge/license-MIT-blue.svg" alt="License">
</a>
<a href="https://github.com/0xfnzero/sol-trade-sdk">
    <img src="https://img.shields.io/github/stars/0xfnzero/sol-trade-sdk?style=social" alt="GitHub stars">
</a>
<a href="https://github.com/0xfnzero/sol-trade-sdk/network">
    <img src="https://img.shields.io/github/forks/0xfnzero/sol-trade-sdk?style=social" alt="GitHub forks">
</a>







<img src="https://img.shields.io/badge/Rust-000000?style=for-the-badge&logo=rust&logoColor=white" alt="Rust">
<img src="https://img.shields.io/badge/Solana-9945FF?style=for-the-badge&logo=solana&logoColor=white" alt="Solana">
<img src="https://img.shields.io/badge/DEX-4B8BBE?style=for-the-badge&logo=bitcoin&logoColor=white" alt="DEX Trading">







<a href="https://github.com/0xfnzero/sol-trade-sdk/blob/main/README_CN.md">中文</a> |
<a href="https://github.com/0xfnzero/sol-trade-sdk/blob/main/README.md">English</a> |
<a href="https://fnzero.dev/">Website</a> |
<a href="https://t.me/fnzero_group">Telegram</a> |
<a href="https://discord.gg/vuazbGkqQE">Discord</a>

Support This Project

This SDK is completely free and open source. However, maintaining and continuously updating it requires significant AI computing resources and token consumption. If this SDK helps with your trading development, consider making a monthly SOL donation — any amount is appreciated and helps keep this project alive!

Donation Wallet: 6oW7AXz1yRb57pYSxysuXnMs2aR1ha5rzGzReZ1MjPV8

📋 Table of Contents


📦 SDK Versions

This SDK is available in multiple languages:

Language Repository Description
Rust sol-trade-sdk Ultra-low latency with zero-copy optimization
Node.js sol-trade-sdk-nodejs TypeScript/JavaScript for Node.js
Python sol-trade-sdk-python Async/await native support
Go sol-trade-sdk-golang Concurrent-safe with goroutine support

What This SDK Is For

sol-trade-sdk is the Rust implementation of the FnZero Solana trading SDK family. It focuses on low-latency transaction construction and submission for Solana DEX trading bots, copy-trading systems, sniper bots, arbitrage strategies, and private trading infrastructure.

Area Coverage
DEX protocols PumpFun, PumpSwap, Bonk, Meteora DAMM v2, Raydium AMM v4, Raydium CPMM
Submit lanes Default Solana RPC plus Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Node1, Astralane, SpeedLanding, and other SWQoS providers
Trading workflows Buy/sell, exact input/output, copy trading, sniper trading, address lookup tables, durable nonce, middleware, shared infrastructure
Hot-path design Caller supplies recent blockhash or durable nonce; trade execution avoids RPC reads for blockhash, account, or balance data

🔖 Current Release

Rust crate: sol-trade-sdk = "4.0.21"

This release refreshes PumpFun native-SOL quote handling so SOL/WSOL sentinels prefer the smaller V1 hot path, keeps the default RPC submit lane active alongside SWQoS lanes, restores the fast-submit result window to 5 seconds, and aligns Raydium CPMM fixed-output swaps with the on-chain swap_base_out instruction. Trade execution requires a caller-supplied recent_blockhash or durable nonce; hot-path execution does not query RPC for blockhash, account, or balance data.

✨ Features

  1. PumpFun Trading: Unified SDK-side buy, sell, and buy_exact_quote_in flow, preferring V1 for native SOL and selecting V2 for USDC/non-native quote mints or explicit WSOL settlement
  2. PumpSwap Trading: Support for PumpSwap pool trading operations
  3. Bonk Trading: Support for Bonk trading operations
  4. Raydium CPMM Trading: Support for Raydium CPMM (Concentrated Pool Market Maker) trading operations
  5. Raydium AMM V4 Trading: Support for Raydium AMM V4 (Automated Market Maker) trading operations
  6. Meteora DAMM V2 Trading: Support for Meteora DAMM V2 (Dynamic AMM) trading operations
  7. Multiple MEV Protection: Support for Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Node1, Astralane and other services
  8. Concurrent Trading: Submit through every configured SWQoS provider plus the default RPC lane; the first accepted result can return early while slower routes continue submitting
  9. Unified Trading Interface: Use unified trading protocol enums for trading operations
  10. Middleware System: Support for custom instruction middleware to modify, add, or remove instructions before transaction execution
  11. Shared Infrastructure: Share expensive RPC and SWQoS clients across multiple wallets for reduced resource usage
  12. Hot-Path RPC Boundary: Trade execution uses caller-supplied blockhash or durable nonce and never queries RPC for blockhash, account, or balance data

📦 Installation

Direct Clone

Clone this project to your project directory:

cd your_project_root_directory
git clone https://github.com/0xfnzero/sol-trade-sdk

Add the dependency to your Cargo.toml:

# Add to your Cargo.toml
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.21" }

Use crates.io

# Add to your Cargo.toml
sol-trade-sdk = "4.0.21"

🛠️ Usage Examples

📋 Example Usage

1. Create TradingClient Instance

You can refer to Example: Create TradingClient Instance.

Method 1: Simple (single wallet)

// Wallet
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
// RPC URL
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
let commitment = CommitmentConfig::processed();
// Multiple SWQoS services can be configured
let swqos_configs: Vec<SwqosConfig> = vec![
    SwqosConfig::Default(rpc_url.clone()),
    SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
    SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt, None),
    SwqosConfig::FlashBlock("your api_token".to_string(), SwqosRegion::Frankfurt, None),
    SwqosConfig::BlockRazor("your api_token".to_string(), SwqosRegion::Frankfurt, None),
    // Astralane: 4th param = AstralaneTransport — Binary (default), Plain (/iris), or Quic
    SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // Binary HTTP /irisb
    SwqosConfig::SpeedLanding("your api_token".to_string(), SwqosRegion::Frankfurt, None),
];
// Create TradeConfig instance
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
    // .create_wsol_ata_on_startup(true)  // default: true  - check & create WSOL ATA on init
    // .use_seed_optimize(true)            // default: true  - seed optimization for ATA ops
    // .log_enabled(true)                  // default: true  - SDK timing / SWQOS logs
    // .check_min_tip(false)               // default: false - filter SWQOS below min tip
    // .swqos_cores_from_end(false)        // default: false - bind SWQOS to last N CPU cores
    // .mev_protection(false)              // default: false - MEV (Astralane QUIC :9000 or HTTP mev-protect / BlockRazor)
    .build();

// Create TradingClient
let client = TradingClient::new(Arc::new(payer), trade_config).await;

Method 2: Shared infrastructure (multiple wallets)

For multi-wallet scenarios, create the infrastructure once and share it across wallets. See Example: Shared Infrastructure.

// Create infrastructure once (expensive)
let infra_config = InfrastructureConfig::new(rpc_url, swqos_configs, commitment);
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);

// Create multiple clients sharing the same infrastructure (fast)
let client1 = TradingClient::from_infrastructure(Arc::new(payer1), infrastructure.clone(), true);
let client2 = TradingClient::from_infrastructure(Arc::new(payer2), infrastructure.clone(), true);

2. Configure Gas Fee Strategy

For detailed information about Gas Fee Strategy, see the Gas Fee Strategy Reference.

// Create GasFeeStrategy instance
let gas_fee_strategy = GasFeeStrategy::new();
// Set global strategy
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);

3. Build Trading Parameters

For detailed information about all trading parameters, see the Trading Parameters Reference.

use sol_trade_sdk::{
    AccountPolicy, BuyAmount, DexType, SimpleBuyParams, TradeTokenType,
    trading::core::params::DexParamEnum,
};

let buy_params = SimpleBuyParams::new(
    DexType::PumpFun,
    // Token used to pay. For PumpFun V2 SOL/WSOL quote pools, keep this as SOL
    // when you want to spend native SOL; the SDK will still use V2 accounts.
    TradeTokenType::SOL,
    // Mint of the meme/token you want to buy.
    mint_pubkey,
    // Regular PumpFun/PumpSwap buy. The SDK estimates token output and applies
    // slippage to the maximum quote cost.
    BuyAmount::WithMaxInput { quote_amount: buy_sol_amount },
    // Protocol state from parser/RPC cache, for example PumpFunParams::from_trade(...).
    DexParamEnum::PumpFun(pumpfun_params),
    // Pass a cached recent blockhash; the SDK does not fetch it on the hot path.
    recent_blockhash,
    gas_fee_strategy.clone(),
)
// 300 = 3%.
.slippage_basis_points(300)
// For bots/sniping: assume ATAs are already prepared and keep the tx small.
.account_policy(AccountPolicy::HotPathMinimal);

4. Execute Trading

client.buy_simple(buy_params).await?;

⚡ Trading Parameters

Use SimpleBuyParams / SimpleSellParams for new integrations. They describe trading intent and hide low-level ATA flags. Most users only choose:

  • pay_with / receive_as: quote token direction. Use SOL when the wallet spends or receives native SOL. For PumpFun V2 SOL-paired pools whose quote mint is WSOL, still use SOL if you want native SOL settlement.
  • amount: trade sizing intent. Pick one enum variant instead of combining input_token_amount, fixed_output_token_amount, and use_exact_sol_amount.
  • account_policy: account creation behavior. Bots usually use HotPathMinimal; normal apps can keep the default Auto.
Parameter Meaning Recommendation
BuyAmount::ExactInput(amount) Spend exactly this quote amount; slippage protects minimum output. Normal swaps
BuyAmount::WithMaxInput { quote_amount } Regular PumpFun/PumpSwap buy with slippage applied to max quote cost. Sniping/arbitrage
BuyAmount::ExactOutput { output_amount, max_input_amount } Buy an exact token amount with a max quote budget. Exact-output workflows
SellAmount::ExactInput(amount) Sell exactly this token amount. Normal sells
SellAmount::ExactOutput { output_amount, max_input_amount } Receive an exact quote amount while limiting token input, where the DEX supports it. Exact-output sells
AccountPolicy::Auto SDK creates practical ATAs when needed. General usage
AccountPolicy::HotPathMinimal Avoid ATA create/close instructions in the trade tx. Bots, sniping, latency-sensitive flows
AccountPolicy::CreateMissing Include ATA creation instructions where possible. Convenience over transaction size
AccountPolicy::AssumePrepared Caller prepared every required ATA. Deterministic advanced flows

Optional builder methods:

Method Meaning
.slippage_basis_points(300) Set slippage. 300 means 3%.
.address_lookup_table_account(alt) Attach an ALT to reduce transaction size. Useful for large PumpFun V2 transactions.
.wait_tx_confirmed(true) Return only after confirmation. Usually disabled for fastest submit paths.
.wait_for_all_submits(true) Wait for all SW

Extension points exported contracts — how you extend this code

InstructionBuilder (Interface)
(no doc) [6 implementers]
src/trading/core/traits.rs
SwqosClientTrait (Interface)
(no doc) [17 implementers]
src/swqos/mod.rs
CacheLineAligned (Interface)
Trait for cache-line-aligned data and prefetch. 缓存行对齐与预取 trait。 [2 implementers]
src/perf/hardware_optimizations.rs
InstructionMiddleware (Interface)
Instruction middleware trait Used to modify, add or remove protocol_instructions before transaction execution [2 implementers]
src/trading/middleware/traits.rs
FormatBase64VersionedTransaction (Interface)
(no doc) [1 implementers]
src/swqos/common.rs
UserSpaceNetworking (Interface)
🚀 用户态网络栈接口 [1 implementers]
src/perf/kernel_bypass.rs
TradeExecutor (Interface)
(no doc) [1 implementers]
src/trading/core/traits.rs
Server (Interface)
(no doc)
src/swqos/pb/serverpb.rs

Core symbols most depended-on inside this repo

pubkey
called by 151
src/trading/core/execution.rs
len
called by 132
src/perf/hardware_optimizations.rs
load
called by 122
src/perf/hardware_optimizations.rs
clone
called by 118
src/client/mod.rs
sdk_log_enabled
called by 90
src/common/sdk_log.rs
clone
called by 87
src/swqos/pb/serverpb.rs
elapsed
called by 82
src/common/fast_timing.rs
is_empty
called by 57
src/perf/hardware_optimizations.rs

Shape

Method 575
Function 517
Class 182
Enum 29
Interface 9

Languages

Rust100%

Modules by API surface

src/instruction/utils/pumpswap.rs59 symbols
src/client/mod.rs58 symbols
src/instruction/pumpfun.rs46 symbols
src/instruction/utils/pumpfun.rs44 symbols
src/perf/syscall_bypass.rs43 symbols
src/perf/hardware_optimizations.rs42 symbols
examples/cli_trading/src/main.rs38 symbols
src/perf/compiler_optimization.rs36 symbols
src/perf/zero_copy_io.rs35 symbols
src/perf/protocol_optimization.rs30 symbols
src/common/gas_fee_strategy.rs30 symbols
src/trading/core/async_executor.rs29 symbols

For agents

$ claude mcp add sol-trade-sdk \
  -- python -m otcore.mcp_server <graph>

⬇ download graph artifact

Ask about this repo answers extend the page