sol-trade-sdk

repository·main·Indexed 43 days ago

https://github.com/0xfnzero/sol-trade-sdk

A high-performance Rust SDK version 5.0.4 for low-latency Solana DEX trading. Optimized for bots and arbitrage strategies, it supports multiple protocols including PumpFun, Raydium, and Meteora. Features include Address Lookup Table (ALT) integration, Bonk copy and sniper trading modules, a trading CLI, and support for durable nonces and instruction middleware.

Tokens
49.1K
Snippets
123
Records
214
Agent score
51%

What's inside sol-trade-sdk

  1. Overview of Sol Trade SDK

    main

    Sol Trade SDK is a high-performance Rust SDK designed for low-latency Solana DEX trading. It is optimized for speed and efficiency, making it suitable for trading bots, copy-trading systems, sniper bots, arbitrage strategies, and private trading infrastructure.

    Supported DEX Protocols:

    • PumpFun
    • PumpSwap
    • LaunchLab
    • Bonk
    • StonkFun
    • Meteora DAMM v2
    • Raydium AMM v4
    • Raydium CPMM

    Supported Submission Channels (SWQoS):

    • Default Solana RPC
    • Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Node1, Astralane, Glaive, SpeedLanding, and more.
  2. Overview of Sol Trade SDK capabilities

    main

    The sol-trade-sdk is a high-performance Rust SDK designed for low-latency Solana DEX trading. It is optimized for trading bots, copy-trading systems, sniper bots, and arbitrage strategies.

    Supported DEX Protocols

    • PumpFun: Unified flows for buy, sell, and buy_exact_quote_in (supports V1 and V2).
    • PumpSwap: Support for PumpSwap pool operations.
    • LaunchLab: Generic LaunchLab routing (compatible with Bonk).
    • StonkFun: Routing over LaunchLab and graduated-pool swaps via CPMM.
    • Raydium: Support for both AMM V4 and CPMM (Concentrated Pool Market Maker).
    • Meteora: Support for DAMM V2 (Dynamic AMM).

    Key Design Principles

    • Hot-Path Optimization: To minimize latency, the SDK avoids RPC reads for blockhashes, accounts, or balance data during trade execution. The caller is expected to supply the recent blockhash or a durable nonce.
    • Concurrent Submission: Supports submitting trades through multiple SWQoS (Service Quality of Service) providers simultaneously. The first accepted result can return early while other routes continue.
    • Middleware System: Allows users to inject custom instruction middleware to modify, add, or remove instructions before execution.
    • MEV Protection: Integrated support for various MEV protection services including Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, and more.
  3. What is Durable Nonce and why use it?

    main

    Durable Nonce is a Solana feature that allows transactions to remain valid for extended periods, bypassing the standard 150-block limitation of recent block hashes.

    In the sol-trade-sdk, using Durable Nonce provides:

    • Transaction Replay Protection: Prevents identical transactions from being executed multiple times.
    • Extended Time Window: Transactions stay valid longer.
    • Network Performance Optimization: Reduces dependency on the latest block hash.
    • Transaction Determinism: Provides a consistent processing experience.
    • Offline Transaction Support: Enables processing of pre-signed transactions offline.
  4. What is a Durable Nonce and why use it?

    main

    A Durable Nonce is a Solana feature that allows you to create transactions that remain valid for longer periods, bypassing the standard 150-block limit imposed by recent blockhashes.

    Using Durable Nonces provides several advantages:

    • Transaction Replay Protection: Prevents the same transaction from being executed multiple times.
    • Extended Validity Window: Transactions stay valid for a longer duration.
    • Network Performance Optimization: Reduces dependency on the absolute latest blockhashes.
    • Transaction Determinism: Provides a more consistent transaction processing experience.
    • Offline Transaction Support: Enables the processing of pre-signed transactions offline.
  5. How Pump Cashback works in the SDK

    main

    The SDK supports Pump Cashback Rewards. When trading coins with cashback enabled, users receive fee rebates instead of the fees going to the creator.

    Behavior by Trading Type

    Bonding Curve (Pump)

    • Buy: No instruction changes required; cashback accumulates automatically if the coin has cashback enabled.
    • Sell: If bonding_curve.is_cashback_coin == true, the SDK appends the UserVolumeAccumulator PDA as a remaining account to accumulate claimable cashback.

    Pump Swap

    • Buy: If PumpSwapParams.is_cashback_coin == true, the SDK appends the UserVolumeAccumulator's WSOL ATA as a remaining account.
    • Sell: If is_cashback_coin == true, the SDK appends the WSOL ATA (0th) and the UserVolumeAccumulator PDA (1st) as remaining accounts.

    Parameter Resolution

    • PumpFunParams resolves is_cashback_coin by fetching the bonding curve via from_mint_by_rpc.
    • PumpSwapParams resolves is_cashback_coin by fetching the pool via from_pool_address_by_rpc or from_mint_by_rpc.
  6. Calculate PumpSwap Effective Quote Reserves

    main

    For PumpSwap quoting, you must use the effective reserves: effective_quote_reserves = pool_quote_token_account.amount + virtual_quote_reserves.

    • RPC Construction: PumpSwapParams::from_pool_address_by_rpc automatically handles this.
    • Event Hot-path: When using PumpSwapParams::from_trade(...) or from_trade_with_fee_basis_points(...), pass the raw pool_quote_token_reserves and virtual_quote_reserves from the event directly. Do not sum them manually before calling the function; the SDK handles the summation internally. The SDK uses signed i128 values and will return an error on invalid results instead of integer wrapping.
  7. Use seed optimization for PumpSwap trading

    main

    When performing PumpSwap buy/sell operations, you must ensure that the same use_seed_optimize policy is applied consistently across two distinct steps:

    1. Account Derivation: Deriving the necessary accounts.
    2. Transaction Building: Constructing the actual transaction.

    If these policies do not match, the derived accounts will not align with the transaction requirements. Additionally, when implementing production code based on this pattern, ensure you refresh the blockhash before executing a sell transaction, as the example reuses a blockhash across a delay which is not suitable for production.

  8. Understand trading parameter modes and account policies

    main

    When configuring trading parameters, choose between the following modes and policies based on your execution requirements:

    Input Protection Modes

    • WithMaxInput: Protects against maximum quote cost. Best suited for prioritizing execution (getting the trade through).
    • ExactInput: Protects against minimum output amount. In highly active markets, this mode is more prone to failure.

    Account Policies

    • HotPathMinimal: Requires that all necessary token accounts already exist. This is used for ultra-low latency paths.
    • AccountPolicy::Auto: The standard choice for most integrations; it handles account requirements automatically.
  9. Understand PumpSwap trade semantics and slippage modes

    main

    When building trades for PumpSwap, choose between two primary input modes depending on your priority:

    1. BuyAmount::WithMaxInput: Applies slippage to the maximum quote cost. Use this when fill priority is the most important factor. It uses post-trade reserves and fee bps (LP/protocol/creator) directly from the event to minimize latency.
    2. BuyAmount::ExactInput: Use this when the quote spend must be exact. This mode protects the minimum output but is more likely to fail in highly active pools.

    Latency Optimization Details:

    • The example avoids fetching the Pool account in the hot path to prevent added latency and mixed-slot quotes; it uses the raw and virtual quote reserves provided in the event snapshot.
    • The first matching event asynchronously records the pre-buy balance. Subsequent events perform trades without an RPC balance check in the submission hot path.

    Production Recommendations:

    • Do not solve slippage errors by setting min_out to zero.
    • Implement durable signature deduplication, a position state machine, SWQoS configuration, and bounded requoting.
  10. How Bonk Copy Trading works

    main

    The Bonk Copy Trading module follows a three-step lifecycle:

    1. Event Consumption: It consumes Bonk events via the solana-streamer-sdk.
    2. State Mapping: It maps the received event state to the SDK protocol parameters.
    3. Execution: It performs a follow-up buy/sell flow based on the mapped parameters.

    Important Implementation Note for Delayed Sells: If implementing delayed sells, you must use the current state and a fresh blockhash. Do not reuse the blockhash or state from the initial trigger snapshot.

  11. Note on Raydium AMM V4 IDLs

    main
    Raydium AMM V4 is not an Anchor program and therefore does not have a protocol-maintained Anchor IDL. The files raydium_amm_v4.json and raydium_pool_v4.json in this repository serve as compatibility references only. For current instruction and ray_log layouts, refer to raydium-io/raydium-amm.
  12. Configure Risk Gate Cache Strategies

    main

    When implementing a risk gate, you must explicitly choose how to handle missing or expired data in your cache. Common strategies include:

    StrategyBehaviorUse Case
    Fail closedReject buy if no fresh result is availableSecurity-first; new mints or unknown mints
    Fail openContinue buy if no result is availableAvailability-first; when other risk controls exist
    WhitelistOnly explicitly allowed mints can be boughtControlled strategies or fixed sets of targets
    BlacklistOnly explicitly denied mints are interceptedBroad coverage with independent monitoring

    Warning: Do not silently treat expired Allow results as valid. Your background refresh task should explicitly handle expiration by changing the verdict to Deny, deleting the entry (to trigger a 'missing' strategy), or switching the gate to an unavailable state.