A high-performance TypeScript 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.
中文 | English | Website | Telegram | Discord
Current version: 10.0.0. Read the migration notes before upgrading; see the changelog for historical changes.
Pump.fun defaults to V3 with per-request V1/V2/V3 overrides. See version configuration, multi-hop examples and simulation limits.
Official single-instruction multi-hop buys and sells for Pump.fun curves and PumpSwap pools: pump_multi_hop. See usage and simulation.
Cached trade preparation supports Auto / Official / Sequential: official preference requires an independent final minimum and current buyback recipient; cross-DEX paths keep sequential execution. See execution selection above.
- SDK Versions and Related SDKs
- Installation
- What This SDK Is For
- Features
- Usage Examples
- Documentation
- PumpSwap cached routes
Repositories are versioned independently; follow each SDK’s installation guide for compatible dependencies.
| Language | Repository | Purpose | Version |
|---|---|---|---|
| Rust | sol-parser-sdk | DEX transaction and account event parsing | v0.10.0 |
| Node.js | sol-parser-sdk-nodejs | DEX transaction and account event parsing | v0.10.0 |
| Python | sol-parser-sdk-python | DEX transaction and account event parsing | v0.10.0 |
| Go | sol-parser-sdk-golang | DEX transaction and account event parsing | v0.10.0 |
| Rust | sol-trade-sdk | Transaction building, signing and multi-channel submission | v10.0.0 |
| Node.js | sol-trade-sdk-nodejs | Transaction building, signing and multi-channel submission | v10.0.0 |
| Python | sol-trade-sdk-python | Transaction building, signing and multi-channel submission | v10.0.0 |
| Go | sol-trade-sdk-golang | Transaction building, signing and multi-channel submission | v10.0.0 |
| Rust | sol-shred-sdk | Raw shred decoding and ShredStream instruction events | v6.0.2 |
| Rust | solana-streamer | gRPC / ShredStream subscriptions and event streaming | v5.0.1 |
| Rust | sol-trade-router-sdk | On-chain multi-hop router and client SDK | v0.4.0 |
npm install sol-trade-sdk@10.0.0To run repository examples or contribute, clone the source:
git clone https://github.com/0xfnzero/sol-trade-sdk-nodejs
cd sol-trade-sdk-nodejs
npm install
npm run buildSee the example index for configuration and offline versus live workflows.
sol-trade-sdk-nodejs brings the FnZero Solana trading SDK to TypeScript and Node.js. It is built for JavaScript/TypeScript trading bots, copy-trading services, sniper bots, backend automation, and DEX integrations that need low-latency transaction construction with Rust SDK behavior parity.
| Area | Coverage |
|---|---|
| DEX protocols | PumpFun, PumpSwap, Bonk, Meteora DAMM v2, Raydium AMM v4, Raydium CPMM |
| Submit lanes | Default Solana RPC plus Jito, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Astralane, Stellium, Lightspeed, Soyas, Speedlanding, Helius, and Solami; NextBlock remains Rust-blacklisted by default |
| Trading workflows | buySimple / sellSimple, legacy buy/sell params, copy trading, sniper trading, address lookup tables, durable nonce, middleware, shared infrastructure |
| Runtime | Node.js 18+, TypeScript, npm/yarn/pnpm projects |
- PumpFun Trading: Unified
buy,sell, andbuy_exact_quote_inflow with automatic legacy or V2 instruction selection for SOL and USDC quote pools - PumpSwap Trading: Support for PumpSwap pool trading operations
- Bonk Trading: Support for Bonk trading operations
- Raydium CPMM Trading: Support for Raydium CPMM (Constant Product Market Maker) trading operations
- Raydium AMM V4 Trading: Support for Raydium AMM V4 (Automated Market Maker) trading operations
- Meteora DAMM V2 Trading: Support for Meteora DAMM V2 (Dynamic AMM) trading operations
- Multiple MEV Protection: Support for the Rust v5.0.2 SWQoS set, including Jito, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Astralane, Stellium, Lightspeed, Soyas, Speedlanding, Helius, Solami, LunarLander, Glaive, and Default RPC
- 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
- Unified Trading Interface: Use unified trading protocol types for trading operations, including Rust-parity
buySimple/sellSimpleintent params - Middleware System: Support for custom instruction middleware to modify, add, or remove instructions before transaction execution
- Shared Infrastructure: Share expensive RPC and SWQoS clients across multiple wallets for reduced resource usage
- Hot-Path RPC Boundary: Trade execution uses caller-supplied blockhash or durable nonce and never queries RPC for blockhash, account, or balance data
For the high-level intent API, see Simple Trading. It shows createSimpleBuyParams, BuyAmount.WithMaxInput, AccountPolicy.Auto, and the conversion to legacy TradeBuyParams.
You can refer to Example: Create TradingClient Instance.
Method 1: Simple (single wallet)
import { TradingClient, TradeConfig, SwqosConfig, SwqosRegion } from 'sol-trade-sdk';
// Wallet
const payer = Keypair.fromSecretKey(/* your keypair */);
// RPC URL
const rpcUrl = "https://mainnet.helius-rpc.com/?api-key=xxxxxx";
// Multiple SWQoS services can be configured
const swqosConfigs: SwqosConfig[] = [
{ type: 'Default', rpcUrl },
{ type: 'Jito', uuid: "your_uuid", region: SwqosRegion.Frankfurt },
{ type: 'Bloxroute', apiToken: "your_api_token", region: SwqosRegion.Frankfurt },
{ type: 'Astralane', apiKey: "your_api_key", region: SwqosRegion.Frankfurt },
];
// Create TradeConfig instance
const tradeConfig = new TradeConfig(rpcUrl, swqosConfigs);
// Create TradingClient
const client = new TradingClient(payer, tradeConfig);Temporal uses HTTP/3 QUIC first and Binary Batch HTTP as its default fallback. BlockRazor uses gRPC SendBinaryTransaction first and JSON HTTP as fallback. Astralane uses persistent QUIC first and Binary HTTP as fallback. Explicit transport settings force one protocol; a custom URL without a transport remains an explicit HTTP route.
Method 2: Shared infrastructure (multiple wallets)
For multi-wallet scenarios, create the infrastructure once and share it across wallets. See Example: Shared Infrastructure.
import { TradingInfrastructure, InfrastructureConfig } from 'sol-trade-sdk';
// Create infrastructure once (expensive)
const infraConfig = new InfrastructureConfig(rpcUrl, swqosConfigs);
const infrastructure = new TradingInfrastructure(infraConfig);
// Create multiple clients sharing the same infrastructure (fast)
const client1 = TradingClient.fromInfrastructure(payer1, infrastructure);
const client2 = TradingClient.fromInfrastructure(payer2, infrastructure);import { GasFeeStrategy } from 'sol-trade-sdk';
// Create GasFeeStrategy instance
const gasFeeStrategy = new GasFeeStrategy();
// Set global strategy
gasFeeStrategy.setGlobalFeeStrategy(150000, 150000, 500000, 500000, 0.001, 0.001);import {
AccountPolicy,
BuyAmount,
DexType,
TradeTokenType,
createSimpleBuyParams,
simpleBuyParamsToTradeBuyParams,
withSimpleBuyAccountPolicy,
withSimpleBuySlippage,
} from 'sol-trade-sdk';
const simple = withSimpleBuyAccountPolicy(
withSimpleBuySlippage(
createSimpleBuyParams(
DexType.PumpSwap,
TradeTokenType.WSOL,
mintPubkey,
BuyAmount.WithMaxInput(buySolAmount),
{ type: 'PumpSwap', params: pumpSwapParams },
recentBlockhash,
gasFeeStrategy
),
500
),
AccountPolicy.Auto
);
const buyParams = simpleBuyParamsToTradeBuyParams(simple);const result = await client.buy(buyParams);
console.log(`Transaction signature: ${result.signature}`);For comprehensive information about all trading parameters including TradeBuyParams and TradeSellParams, see the Trading Parameters documentation.
When using shred to subscribe to events, due to the nature of shreds, you cannot get complete information about transaction events. Please ensure that the parameters your trading logic depends on are available in shreds when using them.
See the example index for workflows, commands and configuration requirements.
When configuring SWQoS services, note the different parameter requirements for each service:
- Jito: The first parameter is UUID (if no UUID, pass an empty string
"") - Other MEV services: The first parameter is the API Token
Each SWQoS service supports an optional custom URL parameter:
// Using custom URL
const jitoConfig: SwqosConfig = {
type: 'Jito',
uuid: "your_uuid",
region: SwqosRegion.Frankfurt,
customUrl: "https://custom-jito-endpoint.com"
};
// Using default regional endpoint
const bloxrouteConfig: SwqosConfig = {
type: 'Bloxroute',
apiToken: "your_api_token",
region: SwqosRegion.NewYork
};URL Priority Logic:
- If a custom URL is provided, it will be used instead of the regional endpoint
- If no custom URL is provided, the system will use the default endpoint for the specified region
- This allows for maximum flexibility while maintaining backward compatibility
When using multiple MEV services, you need to use Durable Nonce. You need to use the fetchNonceInfo function to get the latest nonce value, and use it as the durableNonce when trading.
The SDK provides a powerful middleware system that allows you to modify, add, or remove instructions before transaction execution. Middleware executes in the order they are added:
import { MiddlewareManager, ValidationMiddleware, TimerMiddleware } from 'sol-trade-sdk';
const manager = new MiddlewareManager()
.addMiddleware(new FirstMiddleware()) // Executes first
.addMiddleware(new SecondMiddleware()) // Executes second
.addMiddleware(new ThirdMiddleware()); // Executes lastAddress Lookup Tables (ALT) allow you to optimize transaction size and reduce fees by storing frequently used addresses in a compact table format.
import { fetchAddressLookupTableAccount, AddressLookupTableCache } from 'sol-trade-sdk';
// Fetch ALT from chain
const alt = await fetchAddressLookupTableAccount(rpc, altAddress);
console.log(`ALT contains ${alt.addresses.length} addresses`);
// Use cache for performance
const cache = new AddressLookupTableCache(rpc);
await cache.prefetch([altAddress1, altAddress2, altAddress3]);
const cached = cache.get(altAddress1);Use Durable Nonce to implement transaction replay protection and optimize transaction processing.
import { fetchNonceInfo, NonceCache } from 'sol-trade-sdk';
// Fetch nonce info
const nonceInfo = await fetchNonceInfo(rpc, nonceAccount);PumpFun and PumpSwap support cashback for eligible tokens: part of the trading fee can be returned to the user. The SDK must know whether the token has cashback enabled so that buy/sell instructions include the correct accounts.
- When params come from RPC: If you use
PumpFunParams.fromMintByRpcorPumpSwapParams.fromPoolAddressByRpc, the SDK readsisCashbackCoinfrom chain—no extra step. - When params come from decoded events: If you build params from already-decoded trade events (for example from a parser service), you must pass the cashback flag into the SDK:
- PumpFun: Set
isCashbackCoinwhen building params from decoded events. - PumpSwap: Set
isCashbackCoinfield when constructing params manually.
- PumpFun: Set
You can apply for a key through the official website: Community Website
- Jito: High-performance block space
- ZeroSlot: Zero-latency transactions
- Temporal: Time-sensitive transactions
- Bloxroute: Blockchain network acceleration
- FlashBlock: High-speed transaction execution with API key authentication
- BlockRazor: High-speed transaction execution with API key authentication
- Astralane: Blockchain network acceleration
src/
├── common/ # Common functionality and tools
├── constants/ # Constant definitions
├── instruction/ # Instruction building
│ └── utils/ # Instruction utilities
├── swqos/ # MEV service clients
├── trading/ # Unified trading engine
│ ├── common/ # Common trading tools
│ ├── core/ # Core trading engine
│ ├── middleware/ # Middleware system
│ └── factory.ts # Trading factory
├── utils/ # Utility functions
│ ├── calc/ # Amount calculation utilities
│ └── price/ # Price calculation utilities
└── index.ts # Main library file
- Test thoroughly before using on mainnet
- Properly configure private keys and API tokens
- Pay attention to slippage settings to avoid transaction failures
- Monitor balances and transaction fees
- Comply with relevant laws and regulations
Full cross-language API parity is still in progress. See the API migration guide for public behavior and support boundaries, and the examples directory for usage.
Live parser-to-trade integration uses Yellowstone gRPC. See gRPC cache integration and language examples. Quoting and construction read cached state without hot-path RPC.
See cached_damm_v2 for single-hop DAMM v2 cached preparation and explicit simulation. Callers supply a minimum output; expected net receipts remain unknown. Native SOL and existing WSOL settle through different accounts. Reading PumpFun configuration alone does not provide complete fee quotes or a cached factory.
Each SWQOS route can optionally set a minimum tip in SOL, accepting decimals such as 0.0001 (internally rounded to whole lamports). Buy/sell fee lanes below this threshold are skipped before building the route tip instruction, signing or submitting its transaction. Equality is accepted. Omitting the option preserves existing behavior; zero accepts non-negative tips. This limit applies independently of the existing check_min_tip / checkMinTip option, whose behavior is preserved. Other eligible routes, including default RPC, still participate.
const provider: SwqosConfig = {
type: SwqosType.Jito,
apiKey: 'your_uuid',
region: SwqosRegion.Frankfurt,
minTipSol: 0.0001, // SOL; omit to preserve existing behavior
};See reported 3007 failure and synchronized fixes for creator validation, explicit fee recipients and readonly volume accounts.
buildBuyInstructions / buildSellInstructions in instruction/pumpswap accept
inputMint, outputMint, and optional endpoint token programs. Supply both mints:
these select the actual quote-to-base buy or base-to-quote sell instruction,
including custom Token-2022 quotes. A SOL request against a custom quote pool
requires a conversion route. Creator vault authority/quote ATA and token programs
are validated locally; high-level trades retain supplied creator and fee context.
Direct builders require coinCreator and complete execution accounts. Enrich
incomplete parser log events from a verified pool snapshot before building.
Cache preparation reads and validates the complete creator identity from the
captured pool state.
preparePumpSwapTrade(request, orderedHints) freezes an explicit path;
searchPumpSwapTrade(request, {pool, tokenMint, assetMint, conversionPools})
chooses the largest final protected output from supplied cached conversion pools.
Buy and Sell are prepared independently. Each following leg spends only the
preceding protected credit; intermediate surplus may remain in token accounts.
Search defaults to two conversion hops and 128 visited nodes, with limits of
32 supplied hints, three conversion hops and 4096 nodes. Budget exhaustion rejects
the search rather than returning an incomplete result. Ties prefer fewer hops,
then raw pool public-key bytes. Invalid candidate routes are reported separately.
There is no network pool discovery, split routing or packet-cost ranking.
Call trade.buildSigned({context, recentBlockhash, signers, version, ...}) to build
a complete signed transaction offline. Version 0 supports caller-provided ALTs,
durable nonce, compute budget, explicit tip and middleware, with a 1232-byte packet
limit. Version 1 uses the existing native V1 serializer (4096-byte limit; no ALTs).
A prepared quote rejects epoch changes and excess slot age. Native SOL uses an
explicit temporary WSOL account; supply a unique seed and cached rent. The SDK
does not fetch blockhash/rent/ALTs, simulate, confirm or broadcast during this path.
Cashback quotes lacking verified fee context and active transfer-fee quotes fail
closed. Cache slot age is a bound, not proof of fork consistency or execution.
Repeatable native TypeScript fixture replay and signature verification:
npx tsx examples/pumpswap_cached_prepare.ts
npx vitest run tests/pumpswap_preparation.test.ts
npm run typecheck:examplesThe example replays captured TTWO/USDC/WSOL account bytes without RPC and signs independent buy/sell conversion transactions. These are offline quote, wire and signature tests, not claims of fresh mainnet prices, BPF bank execution or measured production latency. Existing generic candidate-route APIs retain their first executable route behavior; use the dedicated PumpSwap search for output ranking.
Actual local SBF execution, using pinned deployed programs and captured accounts:
npx tsx examples/pumpswap_offline_bank.ts
npx vitest run tests/pumpswap_offline_bank.test.tsThis separate example executes independent direct buys/sells with static keys and ALTs plus full SOL → USDC → TTWO → target routes and their reverse. It checks success, excessive-minimum rollback, invalid signatures/ALTs, simulation/send state equality and deterministic fresh-bank repetition without RPC. See fixture provenance and configuration; program and account captures come from different historical slots, and wallet funding is synthetic. Optional configuration measures local prepare/sign overhead separately; it does not measure production latency.
npx tsx examples/hotpath_benchmark.ts
# Optional: pass the path to your edited JSON configuration
npx tsx examples/hotpath_benchmark.ts examples/hotpath_benchmark.jsonThe checked-in JSON config controls warmup, sample count and batch size. Fixture loading and setup occur before timing; timed loops perform no RPC or network I/O. The fixed workloads measure three-hop PumpSwap preparation, route search and prepared V1 transaction building/signing separately. Output reports p50/p95/p99 of batch-normalized microseconds per transaction, a checksum and runtime metadata. These local CPU distributions include scheduling and GC effects; they measure neither provider/network latency nor production landing speed. Compare warmed runs with the same runtime, config and host load.
MIT License
- Official Website: https://fnzero.dev/
- Project Repository: https://github.com/0xfnzero/sol-trade-sdk-nodejs
- Telegram Group: https://t.me/fnzero_group
- Discord: https://discord.gg/vuazbGkqQE
Shared stock bridges: 33 official stock/ETF mints and 58 pools. See eleven-SDK catalog and routing alignment for configuration, USDC routing and cache-only boundaries.