Compare commits

...

33 Commits

Author SHA1 Message Date
Wood e16cd6620f chore: release v3.6.0
Made-with: Cursor
2026-03-09 00:40:59 +08:00
Wood 9f79e865ab perf: P0/P1/P2 low-latency and maintainability improvements
P0:
- blockhash/nonce: get_transaction_blockhash returns Result; buy/sell entry validation
- Bonk sell: remove RPC get_token_balance from build path; require caller to pass input_amount
- Hot path: drop redundant dex_type/protocol_params clone; tip via sol_f64_to_lamports (no String)
- compute_budget cache uses Arc; extend_compute_budget_instructions avoids SmallVec clone

P1:
- middleware protocol_name takes &str; executor destructures result once to avoid signatures/submit_timings clone
- Error messages include dex context; params use Copy for Pubkey; pumpswap utils clone only Pool for pools[0]

P2:
- transaction_pool capacity constants; TIP_ACCOUNT_CACHE marked allow(dead_code)
- Fix error copy in raydium_amm_v4 / meteora_damm_v2 to correct protocol names

Made-with: Cursor
2026-03-08 01:05:27 +08:00
Wood e32e7ee6ab docs: creator_vault/coin_creator from events; CODE_REVIEW three-repo check
Made-with: Cursor
2026-03-07 11:45:33 +08:00
Wood 30c91a74af docs: wrap Astralane QUIC line in README for readability
Made-with: Cursor
2026-03-07 10:54:35 +08:00
Wood 6c41e1cfe6 docs: README Astralane HTTP+QUIC example, sync README_CN
Made-with: Cursor
2026-03-07 10:52:42 +08:00
Wood a003fd4d2f feat: Astralane QUIC, code review fixes, README & example updates
- Add Astralane QUIC client (astralane_quic.rs) and SwqosTransport::Quic
- README: Astralane QUIC usage, remove third-party doc links, add QUIC to examples
- Code review: API key not in logs, PumpSwap no clone, PDA Result, SELL_DISCRIMINATOR, ensure_wsol_ata refactor, tracing in astralane, only supports fix
- instruction/utils: pumpfun/pumpswap PDA & discriminator unit tests
- trading_client example: SwqosTransport, Astralane QUIC in config
- cli_trading: fix all unused variable warnings (_prefix)
- Add docs/CODE_REVIEW_REPORT.md

Made-with: Cursor
2026-03-07 10:47:31 +08:00
Wood fd5af3ab61 feat: track_volume only when cashback; PumpSwap sell cashback use quote_mint ATA; sync IDL
- Pump/PumpSwap buy: track_volume OptionBool = Some(true) only when is_cashback_coin, else Some(false)
- PumpSwap sell cashback: use get_user_volume_accumulator_quote_ata(quote_mint) instead of WSOL-only ATA
- Sync idl/pump_amm.json, idl/pump_fees.json from pump-public-docs

Made-with: Cursor
2026-03-06 16:41:29 +08:00
Wood 7e2860d8de feat: PumpSwap/PumpFun improvements, align with pump-public-docs, sync IDL
- Re-apply PumpSwap pool lookup, lib/utils/seed changes (no Fastlane)
- pump-public-docs: Mayhem fee recipient at index 11 use WSOL ATA; random mayhem fee recipients (PumpSwap + PumpFun); Pool decode 244 bytes
- Sync idl (pump.json, pump_amm.json, pump_fees.json) from pump-fun/pump-public-docs

Made-with: Cursor
2026-03-06 15:18:04 +08:00
Wood 07487c06cb Revert "feat: Fastlane SWQoS, PumpSwap pool lookup and init robustness"
This reverts commit 1142829394.
2026-03-06 11:03:49 +08:00
Wood 1142829394 feat: Fastlane SWQoS, PumpSwap pool lookup and init robustness
- swqos: add Fastlane client and endpoint/tip constants
- pumpswap: pool 244-byte DataSize, canonical PDA lookup, find_by_mint diagnostics
- lib: find_pool_by_mint generic entry; rent/SWQoS init timeouts and default rent fallback
- lib: create WSOL ATA only when SOL balance is sufficient
- utils: get_token_balance_with_options and get_payer_token_balance_with_program (seed ATA aligned)

Made-with: Cursor
2026-03-05 23:45:42 +08:00
Wood d2ce193e2c Merge pull request #85 from hookenful/perf/serializer-coldstart-main
Perf/serializer coldstart main
2026-03-01 14:15:35 +08:00
Hookie 46564f1bb5 test(swqos): add serializer cold-start perf tests
Add manual ignored performance tests for SWQOS serializer cold start:\n- compare legacy eager zero-fill preallocation vs bounded prewarm\n- measure lazy growth amortization (first vs reused serialize)\n\nAlso fix PumpFun test fixture to include newly required SwapParams\nfields so lib tests compile when running targeted perf tests.\n\nValidation:\n- cargo test --release perf_serializer_ -- --ignored --nocapture
2026-02-28 22:58:27 +02:00
Hookie 63afac7aea perf(swqos): reduce serializer cold-start overhead
Replace full eager preallocation in the SWQOS serializer with a bounded\nprewarm and lazy growth strategy.\n\n- Prewarm only a small hot set of buffers instead of allocating all\n  10,000 upfront\n- Keep the same max pool capacity and buffer size to preserve the\n  original buffer-pool design in steady state\n- Stop zero-filling each buffer during initialization; reserve capacity\n  and grow data on demand\n- Return temporary buffers in Base64Encoder::serialize_and_encode to\n  avoid pool depletion\n- Add tests for bounded prewarm and lazy allocation/return behavior\n\nWhy:\nThe previous Lazy initialization allocated and touched ~2.44 GiB\n(10,000 x 256 KiB) on first use, which can block the first buy submit\npath and produce a large cold-start latency spike.\n\nValidation:\n- cargo fmt --all\n- cargo check --lib\n- cargo check (SolBot workspace with path dependency)
2026-02-28 22:58:05 +02:00
Wood d9b9ddc53f chore: release v3.5.7
Made-with: Cursor
2026-02-28 20:58:12 +08:00
Wood d610745c7e feat(executor): timing logs from grpc_recv_us, hot-path optimizations
- Log build_instructions / before_submit once; per-channel submit, confirmed, total (all from grpc_recv_us)
- confirmed = per-channel submit-to-confirm duration; total = batch start-to-confirm when need_confirm
- No logging between execute_parallel and poll_any_transaction_confirmation to reduce latency
- Clone submit_timings only when log_enabled; all logging after result is ready
- Use provider name (Jito, Helius, etc.) in log lines instead of generic SWQOS
- Timing format: .4 ms; simulate (dry-run) label for simulate mode
- execute_parallel returns 4-tuple with submit_timings for per-channel timing

Made-with: Cursor
2026-02-28 20:56:33 +08:00
Wood 460395e5b2 chore: release v3.5.6
Made-with: Cursor
2026-02-28 01:01:44 +08:00
Wood 5335a4f5ff Merge pull request #82 from VariantConst/patch-5
Change Helius endpoints from HTTPS to HTTP
2026-02-28 00:47:55 +08:00
VariantConst 23a45e611c Change Helius endpoints from HTTPS to HTTP
Change Helius endpoints from HTTPS to HTTP
2026-02-27 23:49:38 +08:00
Wood 48b9b17ab1 chore: release v3.5.5
Made-with: Cursor
2026-02-27 15:07:18 +08:00
Wood 0cd276d6cb feat: Helius Sender SWQOS support and global check_min_tip option
- Add Helius Sender client (helius.rs) with dual routing and swqos_only mode
- Helius min tip: 0.0002 SOL default, 0.000005 SOL when swqos_only=true
- Add TradeConfig.check_min_tip (default false) to skip min-tip validation for lower latency
- Thread check_min_tip through SwapParams and execute_parallel; only call min_tip_sol when enabled
- Add SWQOS_ENDPOINTS_HELIUS and HELIUS_TIP_ACCOUNTS in constants
- Extend SwqosConfig/SwqosType for Helius; add Helius to get_endpoint and get_swqos_client
- Update trading_client, shared_infrastructure and middleware_system examples

Made-with: Cursor
2026-02-27 15:00:13 +08:00
Wood 82438479d3 chore: fix all examples to compile and expand workspace
- Add pumpfun_copy_trading and pumpfun_sniper_trading to workspace members
- Add grpc_recv_us field to all TradeBuyParams/TradeSellParams in examples
- Switch address_lookup and nonce_cache to sol-parser-sdk, use event is_cashback_coin
- Remove invalid rustls call from pumpfun examples for successful build
- All 18 examples pass cargo check --workspace

Made-with: Cursor
2026-02-27 13:44:22 +08:00
Wood 3d062279d9 chore: release v3.5.4
- Bump version to 3.5.4; update README and README_CN
- Astralane: irisb binary API (no Base64), POST /irisb with query api-key&method; constants use /irisb endpoints; ping POST getHealth
- BlockRazor: Send Transaction v2 (plain Base64 body, Content-Type text/plain, auth in URI only); ping POST /v2/health; use default_http_client_builder
- SWQOS: all clients use default_http_client_builder (nextblock, temporal, zeroslot, astralane, lightspeed, jito, flashblock); remove unused Duration imports

Made-with: Cursor
2026-02-27 02:30:52 +08:00
Wood 15e07e9130 docs: remove version release notes from README_CN, fix crates.io version to 3.5.3
Made-with: Cursor
2026-02-27 00:42:43 +08:00
Wood 6eaafde4fd docs: remove version release notes from README
Made-with: Cursor
2026-02-27 00:42:17 +08:00
Wood 0f37950adf chore: release v3.5.3 (full release with IDL + instructions)
- Bump version to 3.5.3; README What's new in 3.5.3 includes SWQoS + PumpFun/PumpSwap updates
- Replaces incomplete v3.5.2 release

Made-with: Cursor
2026-02-27 00:29:20 +08:00
Wood dd4f42324e feat: IDL updates, PumpFun/PumpSwap instruction and utils, fast_fn, release notes
- idl: pump.json and pump_amm.json updates
- instruction: pumpfun.rs, pumpswap.rs and utils (pumpfun, pumpswap)
- common: fast_fn.rs
- docs: release_notes_v3.5.0.md

Made-with: Cursor
2026-02-27 00:27:36 +08:00
Wood d0897b53d3 chore: release v3.5.2
- Bump version to 3.5.2 in Cargo.toml
- Update README and README_CN with 3.5.2 and What's new in 3.5.2

Made-with: Cursor
2026-02-27 00:24:10 +08:00
Wood e67a21df58 chore: bump README dependency examples to 3.5.1
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-26 01:03:34 +08:00
Wood 147c6068d1 Release v3.5.1: bump version, update README
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-26 00:58:48 +08:00
Wood 6ce8ee582e Merge pull request #79 from HelvetiCrypt/fix/confirm-all-signatures
Fix: poll all channel signatures during confirmation
2026-02-26 00:52:02 +08:00
vibes bcc6860bc3 Exclude examples requiring sol-parser-sdk from workspace
These examples depend on a local path to sol-parser-sdk which is not
available in the public repo, causing build failures for consumers.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 09:19:03 +00:00
vibes 1b7e3781c7 Fix confirmation polling to check all channel signatures
In v3.5.0, confirmation was split out of execute_parallel into
poll_transaction_confirmation, but it only polled sig[0]. When
multi-channel submit is used, each channel produces a different
signature and only one lands on-chain. If the landed sig is not
sig[0], the poll times out after 15s and reports failure despite
a successful on-chain transaction.

Add poll_any_transaction_confirmation() that passes all signatures
to get_signature_statuses in a single RPC call per poll, returning
the first one that confirms. The executor now uses this instead of
polling a single signature.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
2026-02-25 09:16:50 +00:00
Wood 807b015fc3 Release v3.5.0: performance, constants, bilingual docs
- Bump version to 3.5.0
- Performance: hot-path timing only when log_enabled/simulate; execute_parallel takes &[Arc<SwqosClient>]; shared HTTP client constants for SWQoS
- Code quality: validate_protocol_params extracted for buy/sell; BYTES_PER_ACCOUNT, MAX_INSTRUCTIONS_WARN, HTTP timeout constants; prefetch/syscall bypass comments
- Documentation: bilingual (EN + 中文) doc comments in execution, executor, perf, swqos; README/README_CN version and What's new in 3.5.0
- Add release_notes_v3.5.0.md

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-02-25 01:25:42 +08:00
81 changed files with 3352 additions and 1573 deletions
+35
View File
@@ -0,0 +1,35 @@
# 推送 tag(如 v3.4.1)时自动创建 GitHub Release
name: Release
on:
push:
tags:
- 'v*'
permissions:
contents: write
jobs:
release:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0
- name: Get version from tag
id: tag
run: echo "VERSION=${GITHUB_REF#refs/tags/v}" >> $GITHUB_OUTPUT
- name: Create Release
uses: softprops/action-gh-release@v2
with:
name: v${{ steps.tag.outputs.VERSION }}
body: |
## sol-trade-sdk ${{ steps.tag.outputs.VERSION }}
Rust SDK to interact with the dex trade Solana program (Pump.fun, Raydium, etc.).
- **Cargo**: `sol-trade-sdk = { git = "https://github.com/${{ github.repository }}", tag = "v${{ steps.tag.outputs.VERSION }}" }`
draft: false
generate_release_notes: true
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
-21
View File
@@ -1,21 +0,0 @@
# 更新日志
## [3.3.6] - 2025-01-30
### 新增
- **Stellium SWQOS 支持**:全新 Stellium 客户端实现
- 使用标准 Solana `sendTransaction` RPC 格式
- 自动连接保活,60 秒 ping 间隔
- 5 个小费账户用于负载分配
- 支持 8 个区域端点(纽约、法兰克福、阿姆斯特丹、东京、伦敦等)
- 最低小费要求:0.001 SOL
### 变更
- **更新最低小费要求**以提高交易成功率:
- NextBlock: 0.00001 → 0.001 SOL
- ZeroSlot: 0.00001 → 0.001 SOL
- Temporal: 0.00001 → 0.001 SOL
- BloxRoute: 0.00001 → 0.001 SOL
- FlashBlock: 0.00001 → 0.001 SOL
- BlockRazor: 0.00001 → 0.001 SOL
- 增强异步执行器,添加小费验证警告
+18 -18
View File
@@ -1,6 +1,6 @@
[package]
name = "sol-trade-sdk"
version = "3.4.1"
version = "3.6.0"
edition = "2021"
authors = [
"William <byteblock6@gmail.com>",
@@ -19,9 +19,9 @@ members = [
"examples/trading_client",
"examples/shared_infrastructure",
"examples/middleware_system",
"examples/pumpswap_trading",
"examples/pumpfun_copy_trading",
"examples/pumpfun_sniper_trading",
"examples/pumpswap_trading",
"examples/bonk_sniper_trading",
"examples/bonk_copy_trading",
"examples/raydium_cpmm_trading",
@@ -45,23 +45,23 @@ perf-trace = [] # 性能追踪特性,生产环境应禁用以获得最佳性
[dependencies]
solana-sdk = "3.0.0"
solana-client = "3.0.8"
solana-client = "3.1.9"
solana-program = "3.0.0"
solana-rpc-client = "3.0.8"
solana-rpc-client-api = "3.0.8"
solana-transaction-status = "3.0.8"
solana-account-decoder = "3.0.8"
solana-rpc-client = "3.1.9"
solana-rpc-client-api = "3.1.9"
solana-transaction-status = "3.1.9"
solana-account-decoder = "3.1.9"
solana-hash = "3.0.0"
solana-entry = "3.0.8"
solana-rpc-client-nonce-utils = "3.0.8"
solana-perf = "3.0.8"
solana-metrics = "3.0.8"
solana-nonce = "3.0.0"
solana-address-lookup-table-interface = "3.0.0"
solana-entry = "3.1.9"
solana-rpc-client-nonce-utils = "3.1.9"
solana-perf = "3.1.9"
solana-metrics = "3.1.9"
solana-nonce = "3.1.0"
solana-address-lookup-table-interface = "3.0.1"
solana-compute-budget-interface = "3.0.0"
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
solana-transaction-status-client-types = "3.0.0"
solana-tls-utils = "3.0.8"
solana-commitment-config = { version = "3.1.1", features = ["serde"] }
solana-transaction-status-client-types = "3.1.9"
solana-tls-utils = "3.1.9"
borsh = { version = "1.5.3", features = ["derive"] }
isahc = "1.7.2"
@@ -81,7 +81,6 @@ rustls = { version = "0.23.23", features = ["ring"] }
rustls-native-certs = "0.8.1"
tokio-rustls = "0.26.1"
core_affinity = "0.8"
log = "0.4.22"
chrono = "0.4.39"
regex = "1"
tracing = "0.1.41"
@@ -108,7 +107,8 @@ parking_lot = "0.12"
arc-swap = "1.7"
sha2 = "0.10"
tonic-prost = "0.14.2"
quinn = {version = "0.11", default-features = false, features = ["rustls"]}
quinn = { version = "0.11", default-features = false, features = ["rustls"] }
rcgen = "0.13"
# Performance optimization dependencies
crossbeam-queue = "0.3"
+60 -6
View File
@@ -48,6 +48,7 @@
- [⚡ Trading Parameters](#-trading-parameters)
- [📊 Usage Examples Summary Table](#-usage-examples-summary-table)
- [⚙️ SWQoS Service Configuration](#-swqos-service-configuration)
- [Astralane QUIC (Low-Latency)](#astralane-quic-low-latency)
- [🔧 Middleware System](#-middleware-system)
- [🔍 Address Lookup Tables](#-address-lookup-tables)
- [🔍 Nonce Cache](#-nonce-cache)
@@ -89,14 +90,14 @@ Add the dependency to your `Cargo.toml`:
```toml
# Add to your Cargo.toml
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.4.1" }
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.0" }
```
### Use crates.io
```toml
# Add to your Cargo.toml
sol-trade-sdk = "3.4.1"
sol-trade-sdk = "3.6.0"
```
## 🛠️ Usage Examples
@@ -119,6 +120,14 @@ let swqos_configs: Vec<SwqosConfig> = vec![
SwqosConfig::Default(rpc_url.clone()),
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
// Astralane: HTTP (4th param None) or QUIC (Some(SwqosTransport::Quic)); same API key
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // HTTP
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt,
None,
Some(SwqosTransport::Quic),
), // QUIC
];
// Create TradeConfig instance
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
@@ -257,6 +266,29 @@ let bloxroute_config = SwqosConfig::Bloxroute(
When using multiple MEV services, you need to use `Durable Nonce`. You need to use the `fetch_nonce_info` function to get the latest `nonce` value, and use it as the `durable_nonce` when trading.
#### Astralane QUIC (Low-Latency)
Astralane supports both HTTP and **QUIC** transport. QUIC reduces connection overhead and can lower submission latency. To use the QUIC channel, pass `Some(SwqosTransport::Quic)` as the fourth parameter of `SwqosConfig::Astralane`. Astralanes QUIC service uses a **single endpoint** (no per-region endpoints); the SDK ignores the `region` (and optional custom URL) when QUIC is selected. You can pass the same region as your other SWQoS configs for consistency.
```rust
use sol_trade_sdk::{SwqosConfig, SwqosRegion, SwqosTransport};
// Astralane over QUIC (low-latency); region is ignored (single QUIC endpoint)
let swqos_configs: Vec<SwqosConfig> = vec![
SwqosConfig::Default(rpc_url.clone()),
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt, // same as other services; ignored for QUIC
None,
Some(SwqosTransport::Quic),
),
];
// Then create TradeConfig / TradingClient as usual with swqos_configs
```
- **HTTP** (default): use `None` or `Some(SwqosTransport::Http)`; region and optional custom URL apply.
- **QUIC**: use `Some(SwqosTransport::Quic)`; the SDK uses a single QUIC endpoint and ignores region. Same API key as HTTP.
---
### 🔧 Middleware System
@@ -289,6 +321,24 @@ PumpFun and PumpSwap support **cashback** for eligible tokens: part of the tradi
- The **pumpfun_copy_trading** and **pumpfun_sniper_trading** examples use sol-parser-sdk for gRPC subscription and pass `e.is_cashback_coin` when building params.
- **Claim**: Use `client.claim_cashback_pumpfun()` and `client.claim_cashback_pumpswap(...)` to claim accumulated cashback.
#### PumpFun: Creator Rewards Sharing (creator_vault)
Some PumpFun coins use **Creator Rewards Sharing**, so the on-chain `creator_vault` can differ from the default derivation. If you reuse cached params from a **buy** when **selling**, you may see program error **2006 (seeds constraint violated)**. To avoid this:
- **From gRPC/events (no RPC needed)**: You can get both `creator` and `creator_vault` from parsed transaction events:
- **sol-parser-sdk**: Before pushing events, the pipeline calls `fill_trade_accounts`, which fills `creator_vault` from the buy/sell instruction accounts (buy index 9, sell index 8). `creator` comes from the TradeEvent log. Use `PumpFunParams::from_trade(..., e.creator, e.creator_vault, ...)` or `from_dev_trade(..., e.creator, e.creator_vault, ...)` with the event `e`.
- **solana-streamer**: Instruction parsers set `creator_vault` from accounts[9] (buy) or accounts[8] (sell); `creator` comes from the merged CPI TradeEvent log. Use the same `from_trade` / `from_dev_trade` with `e.creator` and `e.creator_vault`.
- **Override after RPC**: If you get params via `PumpFunParams::from_mint_by_rpc` but later receive a newer `creator_vault` from gRPC, call `.with_creator_vault(latest_creator_vault)` on the params before selling.
The SDK does not fetch creator_vault from RPC on every sell (to avoid latency); pass the up-to-date vault from gRPC/events when available.
#### PumpSwap: coin_creator_vault from events (no RPC)
For **PumpSwap** (Pump AMM), `coin_creator_vault_ata` and `coin_creator_vault_authority` are required in buy/sell instructions. Both are available from parsed events without RPC:
- **sol-parser-sdk**: Instruction parser sets them from accounts 17 and 18; the account filler also fills them when the event comes from logs. Use `PumpSwapParams::from_trade(..., e.coin_creator_vault_ata, e.coin_creator_vault_authority, ...)` with the buy/sell event `e`.
- **solana-streamer**: Instruction parser sets them from `accounts.get(17)` and `accounts.get(18)`. Use the same `from_trade` with the events `coin_creator_vault_ata` and `coin_creator_vault_authority`.
## 🛡️ MEV Protection Services
You can apply for a key through the official website: [Community Website](https://fnzero.dev/swqos)
@@ -297,10 +347,10 @@ You can apply for a key through the official website: [Community Website](https:
- **ZeroSlot**: Zero-latency transactions
- **Temporal**: Time-sensitive transactions
- **Bloxroute**: Blockchain network acceleration
- **FlashBlock**: High-speed transaction execution with API key authentication - [Official Documentation](https://doc.flashblock.trade/)
- **BlockRazor**: High-speed transaction execution with API key authentication - [Official Documentation](https://blockrazor.gitbook.io/blockrazor/)
- **Node1**: High-speed transaction execution with API key authentication - [Official Documentation](https://node1.me/docs.html)
- **Astralane**: Blockchain network acceleration
- **FlashBlock**: High-speed transaction execution with API key authentication
- **BlockRazor**: High-speed transaction execution with API key authentication
- **Node1**: High-speed transaction execution with API key authentication
- **Astralane**: Blockchain network acceleration (supports HTTP and QUIC; see [Astralane QUIC](#astralane-quic-low-latency) above)
## 📁 Project Structure
@@ -333,6 +383,10 @@ MIT License
- Telegram Group: https://t.me/fnzero_group
- Discord: https://discord.gg/vuazbGkqQE
## ⏱️ Timing metrics (v3.5.0+)
When `log_enabled` and SDK log are on, the executor prints `[SDK] Buy/Sell timing(...)`. **Semantics changed in v3.5.0**: `submit` is now only the send to SWQOS/RPC; `confirm` is separate; `start_to_submit` (when `grpc_recv_us` is set) is **end-to-end from gRPC event to submit**, so it is larger than in-process timings. See [docs/TIMING_METRICS.md](docs/TIMING_METRICS.md) for definitions and how to compare with older versions.
## ⚠️ Important Notes
1. Test thoroughly before using on mainnet
+56 -6
View File
@@ -48,6 +48,7 @@
- [⚡ 交易参数](#-交易参数)
- [📊 使用示例汇总表格](#-使用示例汇总表格)
- [⚙️ SWQoS 服务配置说明](#-swqos-服务配置说明)
- [Astralane QUIC(低延迟)](#astralane-quic低延迟)
- [🔧 中间件系统说明](#-中间件系统说明)
- [🔍 地址查找表](#-地址查找表)
- [🔍 Nonce 缓存](#-nonce-缓存)
@@ -89,14 +90,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
```toml
# 添加到您的 Cargo.toml
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.4.1" }
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.5.7" }
```
### 使用 crates.io
```toml
# 添加到您的 Cargo.toml
sol-trade-sdk = "3.4.1"
sol-trade-sdk = "3.5.7"
```
## 🛠️ 使用示例
@@ -119,6 +120,14 @@ let swqos_configs: Vec<SwqosConfig> = vec![
SwqosConfig::Default(rpc_url.clone()),
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
// Astralane:第4个参数 None 为 HTTPSome(SwqosTransport::Quic) 为 QUIC;同一 API key
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // HTTP
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt,
None,
Some(SwqosTransport::Quic),
), // QUIC
];
// 创建 TradeConfig 实例
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
@@ -256,6 +265,29 @@ let bloxroute_config = SwqosConfig::Bloxroute(
当使用多个MEV服务时,需要使用`Durable Nonce`。你需要使用`fetch_nonce_info`函数获取最新的`nonce`值,并在交易的时候将`durable_nonce`填入交易参数。
#### Astralane QUIC(低延迟)
Astralane 支持 **HTTP****QUIC** 两种传输方式。QUIC 可减少连接开销,降低提交延迟。使用 QUIC 时,将 `SwqosConfig::Astralane` 的第四个参数设为 `Some(SwqosTransport::Quic)`。Astralane 的 QUIC 服务使用**单一端点**(无分区域端点),选 QUIC 时 SDK 会忽略 `region` 与可选自定义 URL;为与其他 SWQoS 配置一致,可传入相同 region。
```rust
use sol_trade_sdk::{SwqosConfig, SwqosRegion, SwqosTransport};
// Astralane 使用 QUIC(低延迟);region 会被忽略(QUIC 单一端点)
let swqos_configs: Vec<SwqosConfig> = vec![
SwqosConfig::Default(rpc_url.clone()),
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt, // 与其他服务一致即可;QUIC 时会被忽略
None,
Some(SwqosTransport::Quic),
),
];
// 然后照常使用 swqos_configs 创建 TradeConfig / TradingClient
```
- **HTTP**(默认):第四个参数为 `None``Some(SwqosTransport::Http)`region 与可选自定义 URL 生效。
- **QUIC**:第四个参数为 `Some(SwqosTransport::Quic)`;SDK 使用单一 QUIC 端点并忽略 region。与 HTTP 使用同一 API key。
---
### 🔧 中间件系统说明
@@ -288,6 +320,24 @@ PumpFun 与 PumpSwap 支持**返现(Cashback**:部分手续费可返还
- **pumpfun_copy_trading**、**pumpfun_sniper_trading** 示例使用 sol-parser-sdk 订阅 gRPC 事件,并在构造参数时传入 `e.is_cashback_coin`
- **领取返现**:使用 `client.claim_cashback_pumpfun()``client.claim_cashback_pumpswap(...)` 领取累计的返现。
#### PumpFunCreator Rewards Sharingcreator_vault
部分 PumpFun 代币启用了 **Creator Rewards Sharing**,链上 `creator_vault` 可能与默认推导结果不同。若在**卖出**时复用**买入**时缓存的 params,可能触发程序错误 **2006seeds constraint violated**。建议:
- **来自 gRPC/事件(无需 RPC**`creator``creator_vault` 均可从解析后的事件中直接拿到:
- **sol-parser-sdk**:推送前会调用 `fill_trade_accounts`,从 buy/sell 指令账户补全 `creator_vault`buy 索引 9sell 索引 8);`creator` 来自 TradeEvent 日志。用 `PumpFunParams::from_trade(..., e.creator, e.creator_vault, ...)``from_dev_trade(..., e.creator, e.creator_vault, ...)` 即可。
- **solana-streamer**:指令解析时从 accounts[9]buy/ accounts[8]sell)写入 `creator_vault``creator` 来自合并后的 CPI TradeEvent 日志。同样用事件的 `e.creator``e.creator_vault` 调用 `from_trade` / `from_dev_trade`
- **RPC 后覆盖**:若通过 `PumpFunParams::from_mint_by_rpc` 得到 params,之后又从 gRPC 拿到更新的 `creator_vault`,在卖出前对 params 调用 `.with_creator_vault(latest_creator_vault)`
SDK 不会在每次卖出时通过 RPC 拉取 creator_vault(以避免延迟);请从 gRPC/事件中传入最新 vault。
#### PumpSwap:从事件拿 coin_creator_vault(无需 RPC
**PumpSwap**Pump AMM)的 buy/sell 指令需要 `coin_creator_vault_ata``coin_creator_vault_authority`,二者均可从解析事件中拿到,无需 RPC:
- **sol-parser-sdk**:指令解析从账户 17、18 写入;若事件来自日志,账户填充器也会从指令补全。用 `PumpSwapParams::from_trade(..., e.coin_creator_vault_ata, e.coin_creator_vault_authority, ...)` 即可。
- **solana-streamer**:指令解析从 `accounts.get(17)``accounts.get(18)` 写入。同样用事件的 `coin_creator_vault_ata``coin_creator_vault_authority` 调用 `from_trade`
## 🛡️ MEV 保护服务
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
@@ -296,10 +346,10 @@ PumpFun 与 PumpSwap 支持**返现(Cashback**:部分手续费可返还
- **ZeroSlot**: 零延迟交易
- **Temporal**: 时间敏感交易
- **Bloxroute**: 区块链网络加速
- **FlashBlock**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://doc.flashblock.trade/)
- **BlockRazor**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://blockrazor.gitbook.io/blockrazor/)
- **Node1**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://node1.me/docs.html)
- **Astralane**: 高速交易执行,支持 API 密钥认证
- **FlashBlock**: 高速交易执行,支持 API 密钥认证
- **BlockRazor**: 高速交易执行,支持 API 密钥认证
- **Node1**: 高速交易执行,支持 API 密钥认证
- **Astralane**: 区块链网络加速(支持 HTTP 与 QUIC,见上方 [Astralane QUIC](#astralane-quic低延迟)
## 📁 项目结构
+170
View File
@@ -0,0 +1,170 @@
# sol-trade-sdk 代码审查报告
审查维度:**逻辑准确性**、**可读性**、**模块化**、**超低延迟**、**代码质量**、**安全性**。
---
## 1. 代码逻辑准确性
### 1.1 Instruction 与 IDL / 官方行为
| 模块 | 结论 | 说明 |
|------|------|------|
| PumpFun buy/sell | ✅ 一致 | 账户顺序、discriminator、track_volume 与 `idl/pump.json` 一致;cashback 时 remainingAccounts 顺序正确 |
| PumpSwap buy/sell | ✅ 一致 | 与 `idl/pump_amm.json` 一致;sell cashback 使用 quote_mint ATA |
| PDA 推导 | ✅ 一致 | bonding_curve_v2、pool_v2、user_volume_accumulator、creator_vault 等 seeds 与官方一致 |
### 1.2 需修正的逻辑/风格
- **`src/instruction/utils/pumpswap.rs` 约 258、291 行**`let program_id: &Pubkey = &&accounts::AMM_PROGRAM` 为双重引用,易误导且多余。建议改为 `&accounts::AMM_PROGRAM`
---
## 2. 代码可读性
### 2.1 命名与注释
- 多数模块有中英文注释,instruction 与 IDL 的对应关系有标注。
- **建议**`src/instruction/pumpfun.rs` 约 259 行 sell 的 discriminator 使用魔法数组 `[51, 230, 133, ...]`,建议改为 `SELL_DISCRIMINATOR` 常量(与 buy 路径一致)。
### 2.2 错误信息与文案
- **建议**`src/lib.rs` 中 “Current version only support” 应为 “only supports”;类似拼写/语法可统一检查。
### 2.3 过长函数
- **建议**`src/lib.rs``ensure_wsol_ata` 可拆为「入口 + 重试循环」与「单次尝试 + 结果判断」,便于单测和阅读。
---
## 3. 模块化
### 3.1 职责与分层
- **instruction**:按协议分(pumpfun / pumpswap / bonk / raydium_* 等),实现 `InstructionBuilder`,边界清晰。
- **instruction/utils**PDA、常量、类型、池子解析与上层「组指令」分工明确。
- **swqos**:按提供商分模块,common 放序列化、确认轮询、HTTP 客户端,无循环依赖。
- **结论**:分层合理,模块化良好。
---
## 4. 超低延迟
### 4.1 必须改:避免多余 clone
| 位置 | 问题 | 建议 |
|------|------|------|
| `src/instruction/pumpswap.rs` 约 232、429 行 | `Instruction { accounts: accounts.clone(), data }` 对已拥有的 `Vec<AccountMeta>` 做完整 clone | 改为直接移动:`Instruction { program_id, accounts, data }`,不再 clone |
### 4.2 建议
- 若多路 SWQOS 并发发**同一笔**交易,可在调用方序列化一次,再传 `&[u8]` 给各 client,减少重复 bincode 序列化。
- 热点路径未见不必要的 `Mutex`/`RwLock` 竞争,当前设计可接受。
---
## 5. 代码质量
### 5.1 必须改:避免 panic 的 unwrap
以下 PDA 或关键 `Option` 使用 `.unwrap()`,在异常输入下会直接 panic,建议改为 `Result` 并向上传播错误:
| 文件 | 行号(约) | 说明 |
|------|------------|------|
| `src/instruction/pumpfun.rs` | 67, 101, 149, 221, 291, 295 | `get_bonding_curve_pda``get_user_volume_accumulator_pda``get_bonding_curve_v2_pda` |
| `src/instruction/pumpswap.rs` | 184, 198, 385, 407 | `get_user_volume_accumulator_pda``get_pool_v2_pda` |
| `src/instruction/utils/pumpfun.rs` | 229 | `DEFAULT_CREATOR_VAULT.unwrap()`LazyLock 未初始化时可能 panic |
| `src/instruction/bonk.rs` | 多处 | `get_pool_pda``get_vault_pda``params.rpc.as_ref().unwrap()` |
| `src/instruction/utils/bonk.rs` | 110116, 148152 | `checked_*` 链后 `.unwrap()`,数学假设不成立会 panic |
| `src/instruction/raydium_cpmm.rs` | 46, 106, 189, 250 | PDA / 状态相关 unwrap |
| `src/instruction/utils/raydium_cpmm.rs` | 83, 85, 141 | `get_vault_pda(...).unwrap()` |
**建议**:统一改为 `.ok_or_else(|| anyhow!("..."))?` 或返回 `Result`,在调用链顶层处理错误,避免进程退出。
### 5.2 建议
- **测试**:为 instruction 构建(或至少 PDA + discriminator/data 布局)增加单元测试,固定输入与预期 bytes/accounts 比对,便于 IDL 升级时回归。
- **错误类型**`claim_cashback_*` 等返回 `Option<Instruction>`;可考虑统一为 `Result<Instruction>` 并带“无法构建”原因,或在文档中明确 None 的语义。
---
## 6. 安全性
### 6.1 必须改:API key 不得写入日志
| 位置 | 问题 | 建议 |
|------|------|------|
| `src/swqos/astralane_quic.rs` 约 61 行 | `info!(..., "api_key as CN: {}", api_key)` | 移除 api_key 或改为占位(如 `***` / 仅长度) |
| `src/swqos/astralane_quic.rs` 约 74 行 | `info!(..., "Connected at {} (api_key: {})", addr, api_key)` | 同上 |
### 6.2 必须改:SkipServerVerification 风险
| 位置 | 问题 | 建议 |
|------|------|------|
| `src/swqos/astralane_quic.rs` 约 179181 行 | `with_custom_certificate_verifier(SkipServerVerification)` 完全跳过服务端证书校验 | 1)若服务端提供证书:用 `RootCertStore` 或固定证书做校验;2)若仅 dev/内网:用 feature 或配置限制,并在文档/日志中明确“仅受控环境使用”;3)默认/生产构建建议不跳过校验 |
### 6.3 建议
- **敏感配置**:确保生产环境从环境变量或安全配置读取 API key,并在文档中说明。
- **依赖**:定期执行 `cargo audit` 与依赖升级。
- **unsafe**`perf/hardware_optimizations.rs``realtime_tuning.rs` 中的 `unsafe` 使用范围可控,需保持注释中的安全约定。
---
## 7. 三库联动与超低延迟检查(sol-trade-sdk / sol-parser-sdk / solana-streamer
### 7.1 逻辑一致性(已确认)
| 检查项 | sol-parser-sdk | solana-streamer | 说明 |
|--------|----------------|-----------------|------|
| Pump buy 账户数 | 16fill 用 get(9) 填 creator_vault | 16accounts[9]=creator_vault | 与 idl/pumpfun.json 一致 |
| Pump sell 账户数 | 14get(8)=creator_vault | 14accounts[8]=creator_vault | 一致 |
| PumpSwap buy 17/18 | 指令解析 + fill_buy_accounts get(17)/get(18) | 指令解析 accounts.get(17)/get(18) | coin_creator_vault_ata/authority 正确 |
| PumpSwap sell 17/18 | fill_sell_accounts 同左 | 同左 | 一致 |
| 填充顺序 | 先 parselog 或 instruction)→ fill_accounts → push | 指令解析直接写 17/18;无单独 fill 步骤 | 两者均保证事件带齐 creator_vault / coin_creator_vault |
| find_instruction_invoke | 选「账户数最多」的 invoke,保证取到 outer buy/sell | N/A(按当前 instruction 解析) | 正确 |
### 7.2 版本化交易账户解析
- **sol-parser-sdk**`get_instruction_account_getter` 正确支持 versioned tx:先 `account_keys`,再 `loaded_writable_addresses`,再 `loaded_readonly_addresses`,与 Solana 约定一致。
- **solana-streamer**:指令的 `accounts` 为索引,通过 `accounts.get(idx as usize).copied()` 从完整 `accounts: &[Pubkey]` 解析;调用方需传入已包含 loaded 的完整账户列表,否则高索引会得到 `default()`
### 7.3 超低延迟相关
| 项目 | 状态 / 建议 |
|------|-------------|
| solana-streamer 热路径 | 已改为**顺序执行** inner 解析与 swap_data 提取,去掉 `thread::scope` + 双 spawn/join,减少 μs 级开销。 |
| sol-parser-sdk | log 与 instruction 并行(rayon::join);fill 仅在有 invoke 时做;`find_instruction_invoke` 为 O(invokes),单程序单 tx 下可接受。 |
| sol-trade-sdk | 见上文第 4 节;PumpSwap instruction 构建避免 `accounts.clone()` 已列为必须改。 |
### 7.4 建议
- **solana-streamer**:若 gRPC 上游已提供完整 `accounts`(含 loaded),可避免对每笔 tx 做 `accounts.to_vec()`,仅在需要 resize 时克隆,进一步降低分配。
- **三库**:保持 IDL 与账户索引注释同步(pumpfun.json / pump_amm.json),避免后续扩展时索引错位。
---
## 8. 汇总:必须改 vs 建议改
### 必须改(优先处理)
| 序号 | 项 | 位置 |
|------|----|------|
| 1 | 移除 astralane_quic 中 API key 的日志输出 | `src/swqos/astralane_quic.rs` 61、74 行 |
| 2 | SkipServerVerification:改为证书校验或仅限 dev 并文档化 | `src/swqos/astralane_quic.rs` 179181 行 |
| 3 | instruction 中 PDA 等 `.unwrap()` 改为 `Result` 并传播错误 | pumpfun.rs、pumpswap.rs、pumpfun/utils、bonk、raydium_cpmm 等 |
| 4 | PumpSwap 构建 instruction 时避免 `accounts.clone()`,改为移动 | `src/instruction/pumpswap.rs` 232、429 行 |
### 建议改(可分批)
| 序号 | 项 | 位置 |
|------|----|------|
| 5 | PDA 的 `program_id``&&AMM_PROGRAM` 改为 `&AMM_PROGRAM` | `src/instruction/utils/pumpswap.rs` 258、291 行 |
| 6 | PumpFun sell discriminator 改为命名常量 | `src/instruction/pumpfun.rs` 约 259 行 |
| 7 | `ensure_wsol_ata` 拆分;修正 “only support” 等文案 | `src/lib.rs` |
| 8 | 为 instruction 构建与 PDA 增加单元测试 | 新建 tests 或模块下 |
| 9 | 生产日志用 tracing 替代 println!/eprintln! | `src/swqos/astralane.rs` 等 |
---
*报告基于当前仓库与 IDL 的静态阅读;若官方 SDK 或链上程序有未公开变更,建议再与官方实现或链上行为做一次对照验证。*
+1 -3
View File
@@ -5,9 +5,7 @@ edition = "2021"
[dependencies]
sol-trade-sdk = { path = "../.." }
solana-streamer-sdk = "0.5.0"
sol-parser-sdk = "0.2.2"
solana-sdk = "3.0.0"
solana-address-lookup-table-interface = "3.0.0"
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
tokio = { version = "1", features = ["full"] }
anyhow = "1.0.94"
+86 -87
View File
@@ -1,5 +1,18 @@
use std::{
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
use sol_parser_sdk::grpc::{
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
TransactionFilter, YellowstoneGrpc,
};
use sol_parser_sdk::DexEvent;
use sol_trade_sdk::common::address_lookup::fetch_address_lookup_table_account;
use sol_trade_sdk::common::{gas_fee_strategy, GasFeeStrategy, TradeConfig};
use sol_trade_sdk::common::{GasFeeStrategy, TradeConfig};
use sol_trade_sdk::{
common::AnyResult,
swqos::SwqosConfig,
@@ -9,95 +22,82 @@ use sol_trade_sdk::{
use solana_commitment_config::CommitmentConfig;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::signature::Keypair;
use solana_streamer_sdk::match_event;
use solana_streamer_sdk::streaming::event_parser::common::filter::EventTypeFilter;
use solana_streamer_sdk::streaming::event_parser::common::EventType;
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::parser::PUMPFUN_PROGRAM_ID;
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::PumpFunTradeEvent;
use solana_streamer_sdk::streaming::event_parser::{Protocol, UnifiedEvent};
use solana_streamer_sdk::streaming::yellowstone_grpc::{AccountFilter, TransactionFilter};
use solana_streamer_sdk::streaming::YellowstoneGrpc;
use std::{
str::FromStr,
sync::{
atomic::{AtomicBool, Ordering},
Arc,
},
};
// Global static flag to ensure transaction is executed only once
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Subscribing to GRPC events...");
println!("Subscribing to GRPC events (sol-parser-sdk, is_cashback_coin from event)...");
let grpc = YellowstoneGrpc::new(
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
None,
)?;
let callback = create_event_callback();
let protocols = vec![Protocol::PumpFun];
// Filter accounts
let account_include = vec![
PUMPFUN_PROGRAM_ID.to_string(), // Listen to pumpfun program ID
];
let account_exclude = vec![];
let account_required = vec![];
// Listen to transaction data
let transaction_filter = TransactionFilter {
account_include: account_include.clone(),
account_exclude,
account_required,
let config = ClientConfig {
enable_metrics: false,
connection_timeout_ms: 10000,
request_timeout_ms: 30000,
enable_tls: true,
order_mode: OrderMode::Unordered,
..Default::default()
};
// Listen to account data belonging to owner programs -> account event monitoring
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
.unwrap_or_else(|_| "https://solana-yellowstone-grpc.publicnode.com:443".to_string());
let grpc = YellowstoneGrpc::new_with_config(
grpc_endpoint,
std::env::var("GRPC_AUTH_TOKEN").ok(),
config,
)?;
// listen to specific event type
let event_type_filter =
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
let protocols = vec![Protocol::PumpFun];
let transaction_filter = TransactionFilter::for_protocols(&protocols);
let account_filter = AccountFilter::for_protocols(&protocols);
let event_filter = EventTypeFilter::include_only(vec![
EventType::PumpFunBuy,
EventType::PumpFunSell,
EventType::PumpFunBuyExactSolIn,
EventType::PumpFunTrade,
]);
grpc.subscribe_events_immediate(
protocols,
None,
vec![transaction_filter],
vec![account_filter],
Some(event_type_filter),
None,
callback,
)
.await?;
let queue = grpc
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
.await?;
loop {
if let Some(event) = queue.pop() {
let run = match &event {
DexEvent::PumpFunBuy(e) | DexEvent::PumpFunSell(e) | DexEvent::PumpFunBuyExactSolIn(e) => {
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
Some(e.clone())
} else {
None
}
}
DexEvent::PumpFunTrade(e) => {
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
Some(e.clone())
} else {
None
}
}
_ => None,
};
if let Some(e) = run {
tokio::spawn(async move {
if let Err(err) = pumpfun_copy_trade_with_grpc(e).await {
eprintln!("Error in copy trade: {:?}", err);
std::process::exit(1);
}
std::process::exit(0);
});
break;
}
} else {
tokio::time::sleep(tokio::time::Duration::from_millis(5)).await;
}
}
tokio::signal::ctrl_c().await?;
Ok(())
}
/// Create an event callback function that handles different types of events
fn create_event_callback() -> impl Fn(Box<dyn UnifiedEvent>) {
|event: Box<dyn UnifiedEvent>| {
match_event!(event, {
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
// Test code, only test one transaction
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
let event_clone = e.clone();
tokio::spawn(async move {
if let Err(err) = pumpfun_copy_trade_with_grpc(event_clone).await {
eprintln!("Error in copy trade: {:?}", err);
std::process::exit(0);
}
});
}
},
});
}
}
/// Create SolanaTrade client
/// Initializes a new SolanaTrade client with configuration
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
println!("🚀 Initializing SolanaTrade client...");
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
@@ -110,9 +110,10 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
Ok(solana_trade)
}
/// PumpFun sniper trade
/// This function demonstrates how to snipe a new token from a PumpFun trade event
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
async fn pumpfun_copy_trade_with_grpc(
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
) -> AnyResult<()> {
println!("Testing PumpFun trading...");
let client = create_solana_trade_client().await?;
@@ -127,15 +128,13 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
let gas_fee_strategy = GasFeeStrategy::new();
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
// Buy tokens
println!("Buying tokens from PumpFun...");
let buy_sol_amount = 100_000;
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
let buy_params = sol_trade_sdk::TradeBuyParams {
dex_type: DexType::PumpFun,
input_token_type: sol_trade_sdk::TradeTokenType::SOL,
mint: mint_pubkey,
input_token_amount: buy_sol_amount,
slippage_basis_points: slippage_basis_points,
input_token_amount: 100_000,
slippage_basis_points,
recent_blockhash: Some(recent_blockhash),
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
trade_info.bonding_curve,
@@ -150,21 +149,21 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
None,
trade_info.fee_recipient,
trade_info.token_program,
false, // is_cashback_coin: set from event/parser when available
trade_info.is_cashback_coin,
)),
address_lookup_table_account: address_lookup_table_account,
address_lookup_table_account,
wait_transaction_confirmed: true,
create_input_token_ata: false,
close_input_token_ata: false,
create_mint_ata: true,
durable_nonce: None,
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
// Exit program
std::process::exit(0);
}
+2
View File
@@ -176,6 +176,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -226,6 +227,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
+2
View File
@@ -144,6 +144,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -187,6 +188,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
+42 -32
View File
@@ -531,7 +531,7 @@ async fn handle_buy(
let client = initialize_real_client().await?;
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
check_mint_ata(&client, mint).await?;
match dex {
@@ -565,7 +565,7 @@ async fn handle_buy_rv4(
slippage: Option<u64>,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
check_mint_ata(&client, mint).await?;
handle_buy_raydium_v4(mint, amm, sol_amount, slippage, create_mint_ata, use_seed, owner_pubkey)
.await?;
@@ -579,7 +579,7 @@ async fn handle_buy_rcpmm(
slippage: Option<u64>,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
check_mint_ata(&client, mint).await?;
handle_buy_raydium_cpmm(
mint,
@@ -599,8 +599,8 @@ async fn handle_buy_pumpfun(
sol_amount: f64,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_use_seed: bool,
_owner_pubkey: Pubkey,
) -> Result<(), Box<dyn std::error::Error>> {
println!("🔥 BUY PUMPFUN COMMAND");
println!(" Token Mint: {}", mint);
@@ -635,6 +635,7 @@ async fn handle_buy_pumpfun(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
Ok((_, signature, _)) => {
@@ -654,7 +655,7 @@ async fn handle_buy_pumpswap(
sol_amount: f64,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
@@ -690,6 +691,7 @@ async fn handle_buy_pumpswap(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
Ok((_, signature, _)) => {
@@ -708,8 +710,8 @@ async fn handle_buy_bonk(
sol_amount: f64,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_use_seed: bool,
_owner_pubkey: Pubkey,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
println!("🔥 BUY BONK COMMAND");
@@ -744,6 +746,7 @@ async fn handle_buy_bonk(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
Ok((_, signature, _)) => {
@@ -763,8 +766,8 @@ async fn handle_buy_raydium_v4(
sol_amount: f64,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_use_seed: bool,
_owner_pubkey: Pubkey,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
println!("🔥 BUY RAYDIUM V4 COMMAND");
@@ -802,6 +805,7 @@ async fn handle_buy_raydium_v4(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
Ok((_, signature, _)) => {
@@ -821,8 +825,8 @@ async fn handle_buy_raydium_cpmm(
sol_amount: f64,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_use_seed: bool,
_owner_pubkey: Pubkey,
) -> Result<(), Box<dyn std::error::Error>> {
let client = initialize_real_client().await?;
println!("🔥 BUY RAYDIUM CPMM COMMAND");
@@ -860,6 +864,7 @@ async fn handle_buy_raydium_cpmm(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
Ok((_, signature, _)) => {
@@ -987,11 +992,11 @@ async fn handle_sell_pumpfun(
mint: &str,
token_amount: Option<f64>,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_create_mint_ata: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
amount_f64: f64,
decimals: u8,
_decimals: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
@@ -1028,6 +1033,7 @@ async fn handle_sell_pumpfun(
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
match client.sell(sell_params).await {
@@ -1047,11 +1053,11 @@ async fn handle_sell_pumpswap(
mint: &str,
token_amount: Option<f64>,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_create_mint_ata: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
amount_f64: f64,
decimals: u8,
_decimals: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
println!("🔥 SELL PUMPSWAP COMMAND");
@@ -1086,6 +1092,7 @@ async fn handle_sell_pumpswap(
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
match client.sell(sell_params).await {
Ok((_, signature, _)) => {
@@ -1104,11 +1111,11 @@ async fn handle_sell_bonk(
mint: &str,
token_amount: Option<f64>,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_create_mint_ata: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
amount_f64: f64,
decimals: u8,
_decimals: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
println!("🔥 SELL PUMPSWAP COMMAND");
@@ -1143,6 +1150,7 @@ async fn handle_sell_bonk(
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
match client.sell(sell_params).await {
Ok((_, signature, _)) => {
@@ -1162,11 +1170,11 @@ async fn handle_sell_raydium_v4(
mint: &str,
token_amount: Option<f64>,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_create_mint_ata: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
amount_f64: f64,
decimals: u8,
_decimals: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
println!("🔥 SELL RAYDIUM V4 COMMAND");
@@ -1203,6 +1211,7 @@ async fn handle_sell_raydium_v4(
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
match client.sell(sell_params).await {
Ok((_, signature, _)) => {
@@ -1222,11 +1231,11 @@ async fn handle_sell_raydium_cpmm(
pool_address: &str,
token_amount: Option<f64>,
slippage: Option<u64>,
create_mint_ata: bool,
use_seed: bool,
owner_pubkey: Pubkey,
_create_mint_ata: bool,
_use_seed: bool,
_owner_pubkey: Pubkey,
amount_f64: f64,
decimals: u8,
_decimals: u8,
) -> Result<(), Box<dyn std::error::Error>> {
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
println!("🔥 SELL RAYDIUM CPMM COMMAND");
@@ -1263,6 +1272,7 @@ async fn handle_sell_raydium_cpmm(
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
match client.sell(sell_params).await {
Ok((_, signature, _)) => {
@@ -44,6 +44,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -77,6 +78,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
fixed_output_token_amount: Some(1),
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
+7 -6
View File
@@ -1,9 +1,9 @@
use anyhow::Result;
use sol_trade_sdk::{
common::{AnyResult, TradeConfig},
swqos::{SwqosConfig, SwqosRegion},
swqos::SwqosConfig,
trading::{
core::params::{PumpSwapParams, DexParamEnum}, factory::DexType, middleware::builtin::LoggingMiddleware,
core::params::{PumpSwapParams, DexParamEnum}, factory::DexType,
InstructionMiddleware, MiddlewareManager,
},
SolanaTrade, TradeTokenType,
@@ -30,8 +30,8 @@ impl InstructionMiddleware for CustomMiddleware {
fn process_protocol_instructions(
&self,
protocol_instructions: Vec<Instruction>,
protocol_name: String,
is_buy: bool,
_protocol_name: String,
_is_buy: bool,
) -> Result<Vec<Instruction>> {
// do anything you want here
// you can modify the instructions here
@@ -41,8 +41,8 @@ impl InstructionMiddleware for CustomMiddleware {
fn process_full_instructions(
&self,
full_instructions: Vec<Instruction>,
protocol_name: String,
is_buy: bool,
_protocol_name: String,
_is_buy: bool,
) -> Result<Vec<Instruction>> {
// do anything you want here
// you can modify the instructions here
@@ -103,6 +103,7 @@ async fn test_middleware() -> AnyResult<()> {
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
println!("tip: This transaction will not succeed because we're using a test account. You can modify the code to initialize the payer with your own private key");
+1 -1
View File
@@ -5,7 +5,7 @@ edition = "2021"
[dependencies]
sol-trade-sdk = { path = "../.." }
solana-streamer-sdk = "0.5.0"
sol-parser-sdk = "0.2.2"
solana-sdk = "3.0.0"
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
spl-associated-token-account = "7.0.0"
+77 -80
View File
@@ -6,6 +6,11 @@ use std::{
},
};
use sol_parser_sdk::grpc::{
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
TransactionFilter, YellowstoneGrpc,
};
use sol_parser_sdk::DexEvent;
use sol_trade_sdk::common::{nonce_cache::fetch_nonce_info, TradeConfig};
use sol_trade_sdk::TradeTokenType;
use sol_trade_sdk::{
@@ -16,88 +21,82 @@ use sol_trade_sdk::{
};
use solana_commitment_config::CommitmentConfig;
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
use solana_streamer_sdk::match_event;
use solana_streamer_sdk::streaming::event_parser::common::filter::EventTypeFilter;
use solana_streamer_sdk::streaming::event_parser::common::EventType;
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::parser::PUMPFUN_PROGRAM_ID;
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::PumpFunTradeEvent;
use solana_streamer_sdk::streaming::event_parser::{Protocol, UnifiedEvent};
use solana_streamer_sdk::streaming::yellowstone_grpc::{AccountFilter, TransactionFilter};
use solana_streamer_sdk::streaming::YellowstoneGrpc;
// Global static flag to ensure transaction is executed only once
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
println!("Subscribing to GRPC events...");
println!("Subscribing to GRPC events (sol-parser-sdk, is_cashback_coin from event)...");
let grpc = YellowstoneGrpc::new(
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
None,
)?;
let callback = create_event_callback();
let protocols = vec![Protocol::PumpFun];
// Filter accounts
let account_include = vec![
PUMPFUN_PROGRAM_ID.to_string(), // Listen to pumpfun program ID
];
let account_exclude = vec![];
let account_required = vec![];
// Listen to transaction data
let transaction_filter = TransactionFilter {
account_include: account_include.clone(),
account_exclude,
account_required,
let config = ClientConfig {
enable_metrics: false,
connection_timeout_ms: 10000,
request_timeout_ms: 30000,
enable_tls: true,
order_mode: OrderMode::Unordered,
..Default::default()
};
// Listen to account data belonging to owner programs -> account event monitoring
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
.unwrap_or_else(|_| "https://solana-yellowstone-grpc.publicnode.com:443".to_string());
let grpc = YellowstoneGrpc::new_with_config(
grpc_endpoint,
std::env::var("GRPC_AUTH_TOKEN").ok(),
config,
)?;
// listen to specific event type
let event_type_filter =
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
let protocols = vec![Protocol::PumpFun];
let transaction_filter = TransactionFilter::for_protocols(&protocols);
let account_filter = AccountFilter::for_protocols(&protocols);
let event_filter = EventTypeFilter::include_only(vec![
EventType::PumpFunBuy,
EventType::PumpFunSell,
EventType::PumpFunBuyExactSolIn,
EventType::PumpFunTrade,
]);
grpc.subscribe_events_immediate(
protocols,
None,
vec![transaction_filter],
vec![account_filter],
Some(event_type_filter),
None,
callback,
)
.await?;
let queue = grpc
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
.await?;
loop {
if let Some(event) = queue.pop() {
let run = match &event {
DexEvent::PumpFunBuy(e) | DexEvent::PumpFunSell(e) | DexEvent::PumpFunBuyExactSolIn(e) => {
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
Some(e.clone())
} else {
None
}
}
DexEvent::PumpFunTrade(e) => {
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
Some(e.clone())
} else {
None
}
}
_ => None,
};
if let Some(e) = run {
tokio::spawn(async move {
if let Err(err) = pumpfun_copy_trade_with_grpc(e).await {
eprintln!("Error in copy trade: {:?}", err);
std::process::exit(1);
}
std::process::exit(0);
});
break;
}
} else {
tokio::time::sleep(tokio::time::Duration::from_millis(5)).await;
}
}
tokio::signal::ctrl_c().await?;
Ok(())
}
/// Create an event callback function that handles different types of events
fn create_event_callback() -> impl Fn(Box<dyn UnifiedEvent>) {
|event: Box<dyn UnifiedEvent>| {
match_event!(event, {
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
// Test code, only test one transaction
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
let event_clone = e.clone();
tokio::spawn(async move {
if let Err(err) = pumpfun_copy_trade_with_grpc(event_clone).await {
eprintln!("Error in copy trade: {:?}", err);
std::process::exit(0);
}
});
}
},
});
}
}
/// Create SolanaTrade client
/// Initializes a new SolanaTrade client with configuration
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
println!("🚀 Initializing SolanaTrade client...");
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
@@ -110,9 +109,10 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
Ok(solana_trade)
}
/// PumpFun sniper trade
/// This function demonstrates how to snipe a new token from a PumpFun trade event
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
async fn pumpfun_copy_trade_with_grpc(
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
) -> AnyResult<()> {
println!("Testing PumpFun trading...");
let client = create_solana_trade_client().await?;
@@ -120,22 +120,19 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
let slippage_basis_points = Some(100);
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
// Setup nonce cache
let nonce_account_str = Pubkey::from_str("use_your_nonce_account_here")?;
let durable_nonce = fetch_nonce_info(&client.infrastructure.rpc, nonce_account_str).await;
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
// Buy tokens
println!("Buying tokens from PumpFun...");
let buy_sol_amount = 100_000;
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
let buy_params = sol_trade_sdk::TradeBuyParams {
dex_type: DexType::PumpFun,
input_token_type: TradeTokenType::SOL,
mint: mint_pubkey,
input_token_amount: buy_sol_amount,
slippage_basis_points: slippage_basis_points,
input_token_amount: 100_000,
slippage_basis_points,
recent_blockhash: Some(recent_blockhash),
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
trade_info.bonding_curve,
@@ -150,21 +147,21 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
None,
trade_info.fee_recipient,
trade_info.token_program,
false, // is_cashback_coin: set from event/parser when available
trade_info.is_cashback_coin,
)),
address_lookup_table_account: None,
wait_transaction_confirmed: true,
create_input_token_ata: false,
close_input_token_ata: false,
create_mint_ata: true,
durable_nonce: durable_nonce,
durable_nonce,
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
// Exit program
std::process::exit(0);
}
+1 -1
View File
@@ -5,7 +5,7 @@ edition = "2021"
[dependencies]
sol-trade-sdk = { path = "../.." }
sol-parser-sdk = { path = "../../../sol-parser-sdk" }
sol-parser-sdk = "0.2.2"
solana-sdk = "3.0.0"
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
tokio = { version = "1", features = ["full"] }
+2 -1
View File
@@ -27,7 +27,6 @@ static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = rustls::crypto::ring::default_provider().install_default();
println!("PumpFun 跟单示例(sol-parser-sdk gRPC...");
let config = ClientConfig {
@@ -155,6 +154,7 @@ async fn pumpfun_copy_trade(
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -202,6 +202,7 @@ async fn pumpfun_copy_trade(
fixed_output_token_amount: None,
gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
+1 -1
View File
@@ -5,7 +5,7 @@ edition = "2021"
[dependencies]
sol-trade-sdk = { path = "../.." }
sol-parser-sdk = { path = "../../../sol-parser-sdk" }
sol-parser-sdk = "0.2.2"
solana-sdk = "3.0.0"
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
tokio = { version = "1", features = ["full"] }
+2 -1
View File
@@ -27,7 +27,6 @@ static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let _ = rustls::crypto::ring::default_provider().install_default();
println!("PumpFun 狙击示例(sol-parser-sdk gRPC...");
let config = ClientConfig {
@@ -147,6 +146,7 @@ async fn pumpfun_sniper_trade(
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -188,6 +188,7 @@ async fn pumpfun_sniper_trade(
fixed_output_token_amount: None,
gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
@@ -44,6 +44,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -72,6 +73,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
create_output_token_ata: true,
close_output_token_ata: true,
close_mint_token_ata: false,
grpc_recv_us: None,
durable_nonce: None,
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
+18 -7
View File
@@ -1,6 +1,7 @@
use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed;
use sol_trade_sdk::common::TradeConfig;
use sol_trade_sdk::TradeTokenType;
use sol_trade_sdk::instruction::utils::pumpswap::fetch_pool;
use sol_trade_sdk::{
common::AnyResult,
swqos::SwqosConfig,
@@ -136,7 +137,9 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
}
async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> AnyResult<()> {
let params = PumpSwapParams::new(
let client = create_solana_trade_client().await?;
let pool_data = fetch_pool(&client.infrastructure.rpc, &trade_info.pool).await?;
let params = PumpSwapParams::from_trade(
trade_info.pool,
trade_info.base_mint,
trade_info.quote_mint,
@@ -149,6 +152,7 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
trade_info.base_token_program,
trade_info.quote_token_program,
trade_info.protocol_fee_recipient,
pool_data.is_cashback_coin,
);
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
@@ -157,12 +161,14 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
} else {
trade_info.base_mint
};
pumpswap_trade_with_grpc(mint, params).await?;
pumpswap_trade_with_grpc(&client, mint, params).await?;
Ok(())
}
async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> AnyResult<()> {
let params = PumpSwapParams::new(
let client = create_solana_trade_client().await?;
let pool_data = fetch_pool(&client.infrastructure.rpc, &trade_info.pool).await?;
let params = PumpSwapParams::from_trade(
trade_info.pool,
trade_info.base_mint,
trade_info.quote_mint,
@@ -175,6 +181,7 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
trade_info.base_token_program,
trade_info.quote_token_program,
trade_info.protocol_fee_recipient,
pool_data.is_cashback_coin,
);
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
@@ -183,14 +190,16 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
} else {
trade_info.base_mint
};
pumpswap_trade_with_grpc(mint, params).await?;
pumpswap_trade_with_grpc(&client, mint, params).await?;
Ok(())
}
async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -> AnyResult<()> {
async fn pumpswap_trade_with_grpc(
client: &SolanaTrade,
mint_pubkey: Pubkey,
params: PumpSwapParams,
) -> AnyResult<()> {
println!("Testing PumpSwap trading...");
let client = create_solana_trade_client().await?;
let slippage_basis_points = Some(500);
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
@@ -221,6 +230,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -255,6 +265,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
@@ -174,6 +174,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -212,6 +213,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
@@ -159,6 +159,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -194,6 +195,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
+2
View File
@@ -47,6 +47,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -87,6 +88,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
fixed_output_token_amount: None,
gas_fee_strategy: gas_fee_strategy,
simulate: false,
grpc_recv_us: None,
};
client.sell(sell_params).await?;
@@ -31,6 +31,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
SwqosConfig::Default(rpc_url.clone()),
SwqosConfig::Jito("your_uuid".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Bloxroute("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
];
// Step 1: Create shared infrastructure (expensive, do once)
+4 -2
View File
@@ -10,7 +10,7 @@
use sol_trade_sdk::{
common::{AnyResult, InfrastructureConfig, TradeConfig},
swqos::{SwqosConfig, SwqosRegion},
TradingClient, TradingInfrastructure,
SwqosTransport, TradingClient, TradingInfrastructure,
};
use solana_commitment_config::CommitmentConfig;
use solana_sdk::signature::Keypair;
@@ -48,7 +48,9 @@ async fn create_trading_client_simple() -> AnyResult<TradingClient> {
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::BlockRazor("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None, Some(SwqosTransport::Quic)), // QUIC; use None for HTTP
// Helius Sender: 4th param swqos_only Some(true) => min tip 0.000005 SOL; None => 0.0002 SOL
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
];
// Optional: Customize WSOL ATA and Seed optimization settings
+1 -1
View File
@@ -4835,7 +4835,7 @@
},
{
"code": 6052,
"name": "CashbackEarnedDoesNotMatchTokenInVault"
"name": "TokensInVaultLessThanCashbackEarned"
}
],
"types": [
+40
View File
@@ -0,0 +1,40 @@
# sol-trade-sdk v3.4.1
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
## What's Changed
### New Features
- **PumpFun & PumpSwap Cashback** (#77): Support for cashback in PumpFun and PumpSwap trading flows. See [Cashback documentation](docs/PUMP_CASHBACK_README.md).
- **Events**: `is_cashback_coin` is now passed from events; PumpFun examples use `sol-parser-sdk` only for event parsing.
### Performance
- **SWQoS**: Reduced submit latency; fixed high latency after ~5 minutes idle.
### Bug Fixes
- **WSOL ATA**: WSOL Associated Token Account creation now runs in background with retry and timeout for more reliable setup.
- Silenced unused and deprecated compiler warnings.
### Documentation
- README (EN/中文): Added Cashback section, outline, examples and tables.
- Updated crates.io / docs references in README.
---
## Cargo
**From Git (this release):**
```toml
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.4.1" }
```
**From crates.io** (when published):
```toml
sol-trade-sdk = "3.4.1"
```
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.0...v3.4.1
+37
View File
@@ -0,0 +1,37 @@
# sol-trade-sdk v3.5.0
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
## What's Changed
### Performance
- **Executor hot path**: Sample `Instant::now()` only when `log_enabled` or `simulate` (total, build, submit, confirm) to reduce cold-path syscalls.
- **SWQOS**: `execute_parallel` now takes `&[Arc<SwqosClient>]` to avoid cloning the client list on each swap.
- **Constants**: Named constants for instruction/account sizes and HTTP client timeouts; no magic numbers in hot paths.
### Code Quality
- **Protocol params**: Single `validate_protocol_params()` used for both buy and sell; removed duplicate match blocks in `lib.rs`.
- **Comments**: Bilingual (English + 中文) doc and inline comments across execution, executor, perf (hardware_optimizations, syscall_bypass), and swqos/common.
- **Prefetch/safety**: Clearer docs for cache prefetch and `unsafe` usage (valid read-only ref, no concurrent write).
### Documentation
- README (EN/CN): Version references updated to 3.5.0 for path and crates.io usage.
---
## Cargo
**From Git (this release):**
```toml
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.5.0" }
```
**From crates.io:**
```toml
sol-trade-sdk = "3.5.0"
```
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.1...v3.5.0
+97
View File
@@ -0,0 +1,97 @@
//! High-performance clock (same design as sol-parser-sdk for consistent grpc_recv_us vs "now").
//!
//! Uses monotonic clock + base UTC timestamp to avoid frequent syscalls; aligned with sol-parser-sdk
//! so event-side grpc_recv_us and SDK-side now_micros() share the same time scale.
use std::time::Instant;
/// High-performance clock: monotonic + base UTC microsecond timestamp.
#[derive(Debug)]
pub struct HighPerformanceClock {
base_instant: Instant,
base_timestamp_us: i64,
last_calibration: Instant,
calibration_interval_secs: u64,
}
impl HighPerformanceClock {
/// Calibrate every 5 minutes by default.
pub fn new() -> Self {
Self::new_with_calibration_interval(300)
}
/// Sample multiple times and use the lowest-latency baseline to reduce init error.
pub fn new_with_calibration_interval(calibration_interval_secs: u64) -> Self {
let mut best_offset = i64::MAX;
let mut best_instant = Instant::now();
let mut best_timestamp = chrono::Utc::now().timestamp_micros();
for _ in 0..3 {
let instant_before = Instant::now();
let timestamp = chrono::Utc::now().timestamp_micros();
let instant_after = Instant::now();
let sample_latency = instant_after.duration_since(instant_before).as_nanos() as i64;
if sample_latency < best_offset {
best_offset = sample_latency;
best_instant = instant_before;
best_timestamp = timestamp;
}
}
Self {
base_instant: best_instant,
base_timestamp_us: best_timestamp,
last_calibration: best_instant,
calibration_interval_secs,
}
}
#[inline(always)]
pub fn now_micros(&self) -> i64 {
let elapsed = self.base_instant.elapsed();
self.base_timestamp_us + elapsed.as_micros() as i64
}
/// Recalibrate when needed to prevent drift.
pub fn now_micros_with_calibration(&mut self) -> i64 {
if self.last_calibration.elapsed().as_secs() >= self.calibration_interval_secs {
self.recalibrate();
}
self.now_micros()
}
fn recalibrate(&mut self) {
let current_monotonic = Instant::now();
let current_utc = chrono::Utc::now().timestamp_micros();
let expected_utc = self.base_timestamp_us
+ current_monotonic.duration_since(self.base_instant).as_micros() as i64;
let drift_us = current_utc - expected_utc;
if drift_us.abs() > 1000 {
self.base_instant = current_monotonic;
self.base_timestamp_us = current_utc;
}
self.last_calibration = current_monotonic;
}
}
impl Default for HighPerformanceClock {
fn default() -> Self {
Self::new()
}
}
static HIGH_PERF_CLOCK: once_cell::sync::OnceCell<HighPerformanceClock> =
once_cell::sync::OnceCell::new();
/// Current time in microseconds (UTC scale); same as sol-parser-sdk clock::now_micros for comparable grpc_recv_us.
#[inline(always)]
pub fn now_micros() -> i64 {
let clock = HIGH_PERF_CLOCK.get_or_init(HighPerformanceClock::new);
clock.now_micros()
}
/// Elapsed microseconds from start_timestamp_us to now.
#[inline(always)]
pub fn elapsed_micros_since(start_timestamp_us: i64) -> i64 {
now_micros() - start_timestamp_us
}
+2
View File
@@ -153,10 +153,12 @@ pub fn _create_associated_token_account_idempotent_fast(
pub enum PdaCacheKey {
PumpFunUserVolume(Pubkey),
PumpFunBondingCurve(Pubkey),
PumpFunBondingCurveV2(Pubkey),
PumpFunCreatorVault(Pubkey),
BonkPool(Pubkey, Pubkey),
BonkVault(Pubkey, Pubkey),
PumpSwapUserVolume(Pubkey),
PumpSwapPoolV2(Pubkey),
}
/// Global lock-free PDA cache for storing computation results
+6 -2
View File
@@ -174,7 +174,9 @@ mod tests {
let total_elapsed = start.elapsed();
let avg_per_call = total_elapsed.as_nanos() / iterations;
println!("Average fast_now_nanos() call: {}ns", avg_per_call);
if crate::common::sdk_log::sdk_log_enabled() {
println!("Average fast_now_nanos() call: {}ns", avg_per_call);
}
// 快速时间戳应该非常快(< 100ns per call
assert!(avg_per_call < 100);
@@ -193,6 +195,8 @@ mod tests {
let total_elapsed = start.elapsed();
let avg_per_call = total_elapsed.as_nanos() / iterations;
println!("Average Instant::now() call: {}ns", avg_per_call);
if crate::common::sdk_log::sdk_log_enabled() {
println!("Average Instant::now() call: {}ns", avg_per_call);
}
}
}
+3
View File
@@ -354,6 +354,9 @@ impl GasFeeStrategy {
/// 打印所有策略。
/// Print all strategies
pub fn print_all_strategies(&self) {
if !crate::common::sdk_log::sdk_log_enabled() {
return;
}
for strategy in self.get_strategies(TradeType::Buy) {
println!("[buy] - {:?}", strategy);
}
+3 -1
View File
@@ -1,5 +1,8 @@
pub mod address_lookup;
pub mod bonding_curve;
pub mod clock;
pub mod fast_fn;
pub mod sdk_log;
pub mod fast_timing;
pub mod gas_fee_strategy;
pub mod global;
@@ -10,7 +13,6 @@ pub mod spl_token;
pub mod spl_token_2022;
pub mod subscription_handle;
pub mod types;
pub mod address_lookup;
pub use gas_fee_strategy::*;
pub use types::*;
+19
View File
@@ -0,0 +1,19 @@
//! sol-trade-sdk global log switch
//!
//! Controlled by `TradeConfig::log_enabled`, set in `TradingClient::new`.
//! All SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.) should check this before output.
use std::sync::atomic::{AtomicBool, Ordering};
static SDK_LOG_ENABLED: AtomicBool = AtomicBool::new(true);
/// Whether SDK logging is enabled (set from TradeConfig.log_enabled in TradingClient::new).
#[inline(always)]
pub fn sdk_log_enabled() -> bool {
SDK_LOG_ENABLED.load(Ordering::Relaxed)
}
/// Set the SDK global log switch (only called from TradingClient::new).
pub fn set_sdk_log_enabled(enabled: bool) {
SDK_LOG_ENABLED.store(enabled, Ordering::Relaxed);
}
+9
View File
@@ -25,6 +25,15 @@ pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error>
Ok(())
}
/// 165 字节 Token 账户的典型租金(lamports),RPC 超时时用作回退
const DEFAULT_TOKEN_ACCOUNT_RENT: u64 = 2_039_280;
/// 当 RPC 超时或不可用时设置默认租金,避免客户端创建卡死
pub fn set_default_rents() {
SPL_TOKEN_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
SPL_TOKEN_2022_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
}
pub fn start_rent_updater(client: Arc<SolanaRpcClient>) {
tokio::spawn(async move {
loop {
+21 -4
View File
@@ -72,6 +72,12 @@ pub struct TradeConfig {
pub create_wsol_ata_on_startup: bool,
/// Whether to use seed optimization for all ATA operations (default: true)
pub use_seed_optimize: bool,
/// Whether to pin parallel submit tasks to CPU cores (can reduce latency; set false in containers). Default true.
pub use_core_affinity: bool,
/// Whether to output all SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default true.
pub log_enabled: bool,
/// Whether to check minimum tip per SWQOS provider (filter out configs below min). Default false to save latency.
pub check_min_tip: bool,
}
impl TradeConfig {
@@ -80,14 +86,19 @@ impl TradeConfig {
swqos_configs: Vec<SwqosConfig>,
commitment: CommitmentConfig,
) -> Self {
println!("🔧 TradeConfig create_wsol_ata_on_startup default value: true");
println!("🔧 TradeConfig use_seed_optimize default value: true");
if crate::common::sdk_log::sdk_log_enabled() {
println!("🔧 TradeConfig create_wsol_ata_on_startup default: true");
println!("🔧 TradeConfig use_seed_optimize default: true");
}
Self {
rpc_url,
swqos_configs,
commitment,
create_wsol_ata_on_startup: true, // 默认:启动时检查并创建
use_seed_optimize: true, // 默认:使用seed优化
create_wsol_ata_on_startup: true, // default: check and create on startup
use_seed_optimize: true, // default: use seed optimization
use_core_affinity: true, // default: pin parallel submit tasks to cores
log_enabled: true, // default: enable all SDK logs
check_min_tip: false, // default: skip min tip check to reduce latency
}
}
@@ -101,6 +112,12 @@ impl TradeConfig {
self.use_seed_optimize = use_seed_optimize;
self
}
/// Set whether to check minimum tip per SWQOS (filter out configs below min). Default false for lower latency.
pub fn with_check_min_tip(mut self, check_min_tip: bool) -> Self {
self.check_min_tip = check_min_tip;
self
}
}
pub type SolanaRpcClient = solana_client::nonblocking::rpc_client::RpcClient;
+55 -16
View File
@@ -13,6 +13,20 @@ pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
pubkey!("3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT"),
];
/// Helius Sender tip accounts (fee recipient addresses).
pub const HELIUS_TIP_ACCOUNTS: &[Pubkey] = &[
pubkey!("4ACfpUFoaSD9bfPdeu6DBt89gB6ENTeHBXCAi87NhDEE"),
pubkey!("D2L6yPZ2FmmmTKPgzaMKdhu6EWZcTpLy1Vhx8uvZe7NZ"),
pubkey!("9bnz4RShgq1hAnLnZbP8kbgBg1kEmcJBYQq3gQbmnSta"),
pubkey!("5VY91ws6B2hMmBFRsXkoAAdsPHBJwRfBht4DXox3xkwn"),
pubkey!("2nyhqdwKcJZR2vcqCyrYsaPVdAnFoJjiksCXJ7hfEYgD"),
pubkey!("2q5pghRs6arqVjRvT5gfgWfWcHWmw1ZuCzphgd5KfWGJ"),
pubkey!("wyvPkWjVZz1M8fHQnMMCDTQDbkManefNNhweYk5WkcF"),
pubkey!("3KCKozbAaF75qEU33jtzozcJ29yJuaLJTy2jFdzUY8bT"),
pubkey!("4vieeGHPYPG2MmyPRcYjdiDmmhN3ww7hsFNap8pVN3Ey"),
pubkey!("4TQLFNWK8AovT1gFvda5jfw2oJeRMKEmw7aH6MGBJ3or"),
];
pub const NEXTBLOCK_TIP_ACCOUNTS: &[Pubkey] = &[
pubkey!("NextbLoCkVtMGcV47JzewQdvBpLqT9TxQFozQkN98pE"),
pubkey!("NexTbLoCkWykbLuB1NkjXgFWkX9oAtcoagQegygXXA2"),
@@ -227,28 +241,36 @@ pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
"http://ny.flashblock.trade",
];
/// BlockRazor Send Transaction v2: plain-text Base64 body, auth in URI, Content-Type: text/plain. Keep-alive: POST /v2/health.
/// 若 HTTP 返回 500,可尝试 HTTPShttps://<region>.solana.blockrazor.io/v2/sendTransactionFrankfurt/NewYork/Tokyo),通过 custom_url 覆盖。
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 8] = [
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
"http://amsterdam.solana.blockrazor.xyz:443/sendTransaction",
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
"http://tokyo.solana.blockrazor.xyz:443/sendTransaction",
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://amsterdam.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://tokyo.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://london.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction",
];
/// Astralane binary API path (no Base64; use with ?api-key=...&method=sendTransaction|getHealth).
pub const ASTRALANE_PATH_IRISB: &str = "irisb";
pub const SWQOS_ENDPOINTS_ASTRALANE: [&str; 8] = [
"http://ny.gateway.astralane.io/iris",
"http://fr.gateway.astralane.io/iris",
"http://ams.gateway.astralane.io/iris",
"http://ny.gateway.astralane.io/iris",
"http://jp.gateway.astralane.io/iris",
"http://ny.gateway.astralane.io/iris",
"http://lax.gateway.astralane.io/iris",
"http://lim.gateway.astralane.io/iris",
"http://ny.gateway.astralane.io/irisb",
"http://fr.gateway.astralane.io/irisb",
"http://ams.gateway.astralane.io/irisb",
"http://ny.gateway.astralane.io/irisb",
"http://jp.gateway.astralane.io/irisb",
"http://ny.gateway.astralane.io/irisb",
"http://lax.gateway.astralane.io/irisb",
"http://lim.gateway.astralane.io/irisb",
];
/// Astralane QUIC 默认端点。
pub const ASTRALANE_QUIC_ENDPOINT: &str = "lim.gateway.astralane.io:7000";
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
"http://ewr1.flashrpc.com",
"http://fra1.flashrpc.com",
@@ -282,6 +304,19 @@ pub const SWQOS_ENDPOINTS_SPEEDLANDING: [&str; 8] = [
"fra.speedlanding.trade:17778",
];
/// Helius Sender: POST /fast, dual routing to validators and Jito. API key optional (custom TPS only).
/// Region order: NewYork(EWR), Frankfurt, Amsterdam, SLC, Tokyo, London, LosAngeles(SG), Default(Global).
pub const SWQOS_ENDPOINTS_HELIUS: [&str; 8] = [
"http://ewr-sender.helius-rpc.com/fast",
"http://fra-sender.helius-rpc.com/fast",
"http://ams-sender.helius-rpc.com/fast",
"http://slc-sender.helius-rpc.com/fast",
"http://tyo-sender.helius-rpc.com/fast",
"http://lon-sender.helius-rpc.com/fast",
"http://sg-sender.helius-rpc.com/fast",
"https://sender.helius-rpc.com/fast",
];
pub const SWQOS_MIN_TIP_DEFAULT: f64 = 0.00001; // 其它SWQOS默认最低小费
pub const SWQOS_MIN_TIP_JITO: f64 = 0.00001;
pub const SWQOS_MIN_TIP_NEXTBLOCK: f64 = 0.001;
@@ -296,3 +331,7 @@ pub const SWQOS_MIN_TIP_STELLIUM: f64 = 0.0001; // Stellium requires minimum 0.0
pub const SWQOS_MIN_TIP_LIGHTSPEED: f64 = 0.0001; // Lightspeed requires minimum 0.001 SOL tip
pub const SWQOS_MIN_TIP_SOYAS: f64 = 0.001; // Soyas requires minimum 0.001 SOL tip
pub const SWQOS_MIN_TIP_SPEEDLANDING: f64 = 0.001; // Speedlanding requires minimum 0.001 SOL tip
/// Helius Sender: 0.0002 SOL when not swqos_only; use SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY when swqos_only=true.
pub const SWQOS_MIN_TIP_HELIUS: f64 = 0.0002;
/// Helius Sender with swqos_only: minimum 0.000005 SOL (much lower tip allowed).
pub const SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY: f64 = 0.000005;
+7 -23
View File
@@ -4,12 +4,9 @@ use crate::{
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
SELL_EXECT_IN_DISCRIMINATOR,
},
trading::{
common::utils::get_token_balance,
core::{
params::{BonkParams, SwapParams},
traits::InstructionBuilder,
},
trading::core::{
params::{BonkParams, SwapParams},
traits::InstructionBuilder,
},
utils::calc::bonk::{
get_buy_token_amount_from_sol_amount, get_sell_sol_amount_from_token_amount,
@@ -177,9 +174,10 @@ impl InstructionBuilder for BonkInstructionBuilder {
// ========================================
// Parameter validation and basic data preparation
// ========================================
if params.rpc.is_none() {
return Err(anyhow!("RPC is not set"));
}
let amount = params
.input_amount
.filter(|&a| a > 0)
.ok_or_else(|| anyhow!("Bonk sell requires input_amount (token amount to sell); fetch balance via RPC before calling build_sell"))?;
let protocol_params = params
.protocol_params
@@ -189,20 +187,6 @@ impl InstructionBuilder for BonkInstructionBuilder {
let usd1_pool = protocol_params.global_config == accounts::USD1_GLOBAL_CONFIG;
let rpc = params.rpc.as_ref().unwrap().clone();
let mut amount = params.input_amount;
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
let balance_u64 =
get_token_balance(rpc.as_ref(), &params.payer.pubkey(), &params.input_mint).await?;
amount = Some(balance_u64);
}
let amount = amount.unwrap_or(0);
if amount == 0 {
return Err(anyhow!("Amount cannot be zero"));
}
let pool_state = if protocol_params.pool_state == Pubkey::default() {
if usd1_pool {
get_pool_pda(&params.input_mint, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
+2 -2
View File
@@ -27,7 +27,7 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
.protocol_params
.as_any()
.downcast_ref::<MeteoraDammV2Params>()
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
@@ -135,7 +135,7 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
.protocol_params
.as_any()
.downcast_ref::<MeteoraDammV2Params>()
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
return Err(anyhow!("Token amount is not set"));
+32 -20
View File
@@ -8,8 +8,9 @@ use crate::{
};
use crate::{
instruction::utils::pumpfun::{
accounts, get_bonding_curve_pda, get_creator, get_user_volume_accumulator_pda,
global_constants::{self}, BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR,
accounts, get_bonding_curve_pda, get_bonding_curve_v2_pda, get_creator,
get_mayhem_fee_recipient_meta_random, get_user_volume_accumulator_pda,
global_constants::{self}, BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
},
utils::calc::{
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
@@ -63,7 +64,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
);
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
get_bonding_curve_pda(&params.output_mint).unwrap()
get_bonding_curve_pda(&params.output_mint)
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.output_mint))?
} else {
bonding_curve.account
};
@@ -96,8 +98,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
params.open_seed_optimize,
);
let user_volume_accumulator =
get_user_volume_accumulator_pda(&params.payer.pubkey()).unwrap();
let user_volume_accumulator = get_user_volume_accumulator_pda(&params.payer.pubkey())
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
// ========================================
// Build instructions
@@ -117,10 +119,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
);
}
let mut buy_data = [0u8; 24];
// IDL: buy/buy_exact_sol_in 第三参数 track_volume: OptionBool,仅代币支持返现时传 Some(true)
let track_volume = if bonding_curve.is_cashback_coin { [1u8, 1u8] } else { [1u8, 0u8] }; // Some(true) / Some(false)
let mut buy_data = [0u8; 26];
if params.use_exact_sol_amount.unwrap_or(true) {
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64)
// Spend exactly the input SOL amount, get at least min_tokens_out
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64, track_volume)
let min_tokens_out = calculate_with_slippage_sell(
buy_token_amount,
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
@@ -128,22 +131,25 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
buy_data[..8].copy_from_slice(&BUY_EXACT_SOL_IN_DISCRIMINATOR);
buy_data[8..16].copy_from_slice(&params.input_amount.unwrap_or(0).to_le_bytes());
buy_data[16..24].copy_from_slice(&min_tokens_out.to_le_bytes());
buy_data[24..26].copy_from_slice(&track_volume);
} else {
// buy(token_amount: u64, max_sol_cost: u64)
// Buy exactly token_amount tokens, pay up to max_sol_cost
// buy(token_amount: u64, max_sol_cost: u64, track_volume)
buy_data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
buy_data[8..16].copy_from_slice(&buy_token_amount.to_le_bytes());
buy_data[16..24].copy_from_slice(&max_sol_cost.to_le_bytes());
buy_data[24..26].copy_from_slice(&track_volume);
}
// Determine fee recipient based on mayhem mode
// Determine fee recipient based on mayhem mode (pump-public-docs: 2nd account = Mayhem fee recipient; use any one randomly)
let fee_recipient_meta = if is_mayhem_mode {
global_constants::MAYHEM_FEE_RECIPIENT_META
get_mayhem_fee_recipient_meta_random()
} else {
global_constants::FEE_RECIPIENT_META
};
let accounts: [AccountMeta; 16] = [
let bonding_curve_v2 = get_bonding_curve_v2_pda(&params.output_mint)
.ok_or_else(|| anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.output_mint))?;
let mut accounts: Vec<AccountMeta> = vec![
global_constants::GLOBAL_ACCOUNT_META,
fee_recipient_meta,
AccountMeta::new_readonly(params.output_mint, false),
@@ -161,11 +167,12 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
accounts::FEE_CONFIG_META,
accounts::FEE_PROGRAM_META,
];
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // remainingAccounts: @pump-fun/pump-sdk 要求末尾传 bondingCurveV2Pda(mint),勿删
instructions.push(Instruction::new_with_bytes(
accounts::PUMPFUN,
&buy_data,
accounts.to_vec(),
accounts,
));
Ok(instructions)
@@ -213,7 +220,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
};
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
get_bonding_curve_pda(&params.input_mint).unwrap()
get_bonding_curve_pda(&params.input_mint)
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.input_mint))?
} else {
bonding_curve.account
};
@@ -252,13 +260,13 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
let mut instructions = Vec::with_capacity(2);
let mut sell_data = [0u8; 24];
sell_data[..8].copy_from_slice(&[51, 230, 133, 164, 1, 127, 131, 173]); // Method ID
sell_data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
sell_data[8..16].copy_from_slice(&token_amount.to_le_bytes());
sell_data[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
// Determine fee recipient based on mayhem mode
// Determine fee recipient based on mayhem mode (pump-public-docs: 2nd account = Mayhem fee recipient; use any one randomly)
let fee_recipient_meta = if is_mayhem_mode {
global_constants::MAYHEM_FEE_RECIPIENT_META
get_mayhem_fee_recipient_meta_random()
} else {
global_constants::FEE_RECIPIENT_META
};
@@ -282,10 +290,14 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
// Cashback: Bonding Curve Sell expects UserVolumeAccumulator PDA at 0th remaining account (writable)
if bonding_curve.is_cashback_coin {
let user_volume_accumulator =
get_user_volume_accumulator_pda(&params.payer.pubkey()).unwrap();
let user_volume_accumulator = get_user_volume_accumulator_pda(&params.payer.pubkey())
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
accounts.push(AccountMeta::new(user_volume_accumulator, false));
}
// remainingAccounts: @pump-fun/pump-sdk sell 要求末尾传 bondingCurveV2Pda(mint)cashback 时在 user_volume_accumulator 之后),勿删
let bonding_curve_v2 = get_bonding_curve_v2_pda(&params.input_mint)
.ok_or_else(|| anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.input_mint))?;
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false));
instructions.push(Instruction::new_with_bytes(
accounts::PUMPFUN,
+70 -63
View File
@@ -1,9 +1,10 @@
use crate::{
constants::trade::trade::DEFAULT_SLIPPAGE,
instruction::utils::pumpswap::{
accounts, fee_recipient_ata, get_user_volume_accumulator_pda,
get_user_volume_accumulator_wsol_ata, BUY_DISCRIMINATOR,
BUY_EXACT_QUOTE_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
accounts, fee_recipient_ata, get_mayhem_fee_recipient_random, get_pool_v2_pda,
get_user_volume_accumulator_pda, get_user_volume_accumulator_quote_ata,
get_user_volume_accumulator_wsol_ata, BUY_DISCRIMINATOR, BUY_EXACT_QUOTE_IN_DISCRIMINATOR,
SELL_DISCRIMINATOR,
},
trading::{
common::wsol_manager,
@@ -119,16 +120,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
params.open_seed_optimize,
);
// Determine fee recipient based on mayhem mode
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
let is_mayhem_mode = protocol_params.is_mayhem_mode;
let fee_recipient =
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
let fee_recipient_meta = if is_mayhem_mode {
accounts::MAYHEM_FEE_RECIPIENT_META
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
get_mayhem_fee_recipient_random()
} else {
accounts::FEE_RECIPIENT_META
(accounts::FEE_RECIPIENT, accounts::FEE_RECIPIENT_META)
};
let fee_recipient_ata = if is_mayhem_mode {
fee_recipient_ata(fee_recipient, crate::constants::WSOL_TOKEN_ACCOUNT)
} else {
fee_recipient_ata(fee_recipient, quote_mint)
};
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
// ========================================
// Build instructions
@@ -177,10 +180,9 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
]);
if quote_is_wsol_or_usdc {
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
accounts.push(AccountMeta::new(
get_user_volume_accumulator_pda(&params.payer.pubkey()).unwrap(),
false,
));
let uva = get_user_volume_accumulator_pda(&params.payer.pubkey())
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
accounts.push(AccountMeta::new(uva, false));
}
accounts.push(accounts::FEE_CONFIG_META);
accounts.push(accounts::FEE_PROGRAM_META);
@@ -190,46 +192,44 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
accounts.push(AccountMeta::new(wsol_ata, false));
}
}
// remainingAccounts: @pump-fun/pump-swap-sdk 要求末尾传 poolV2Pda(baseMint),勿删
let pool_v2 = get_pool_v2_pda(&base_mint)
.ok_or_else(|| anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint))?;
accounts.push(AccountMeta::new_readonly(pool_v2, false));
// Create instruction data
let mut data = [0u8; 24];
if quote_is_wsol_or_usdc {
// Create instruction databuy/buy_exact_quote_in 第三参数 track_volume: OptionBool,仅代币支持返现时传 Some(true);sell 仅两参数)
let track_volume = if protocol_params.is_cashback_coin { [1u8, 1u8] } else { [1u8, 0u8] }; // Some(true) / Some(false)
let data: Vec<u8> = if quote_is_wsol_or_usdc {
let mut buf = [0u8; 26];
if params.use_exact_sol_amount.unwrap_or(true) {
// buy_exact_quote_in(spendable_quote_in: u64, min_base_amount_out: u64)
// Spend exactly the input SOL/quote amount, get at least min_base_amount_out
let min_base_amount_out = crate::utils::calc::common::calculate_with_slippage_sell(
token_amount,
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
);
data[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
// spendable_quote_in (exact SOL amount to spend)
data[8..16].copy_from_slice(&params.input_amount.unwrap_or(0).to_le_bytes());
// min_base_amount_out (minimum tokens to receive)
data[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
buf[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
buf[8..16].copy_from_slice(&params.input_amount.unwrap_or(0).to_le_bytes());
buf[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
buf[24..26].copy_from_slice(&track_volume);
} else {
// buy(base_amount_out: u64, max_quote_amount_in: u64)
// Buy exactly base_amount_out tokens, pay up to max_quote_amount_in
data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
// base_amount_out
data[8..16].copy_from_slice(&token_amount.to_le_bytes());
// max_quote_amount_in
data[16..24].copy_from_slice(&sol_amount.to_le_bytes());
buf[..8].copy_from_slice(&BUY_DISCRIMINATOR);
buf[8..16].copy_from_slice(&token_amount.to_le_bytes());
buf[16..24].copy_from_slice(&sol_amount.to_le_bytes());
buf[24..26].copy_from_slice(&track_volume);
}
buf.to_vec()
} else {
data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
// base_amount_in
data[8..16].copy_from_slice(&sol_amount.to_le_bytes());
// min_quote_amount_out
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
}
let buy_instruction = Instruction {
program_id: accounts::AMM_PROGRAM,
accounts: accounts.clone(),
data: data.to_vec(),
let mut buf = [0u8; 24];
buf[..8].copy_from_slice(&SELL_DISCRIMINATOR);
buf[8..16].copy_from_slice(&sol_amount.to_le_bytes());
buf[16..24].copy_from_slice(&token_amount.to_le_bytes());
buf.to_vec()
};
instructions.push(buy_instruction);
instructions.push(Instruction {
program_id: accounts::AMM_PROGRAM,
accounts,
data,
});
if close_wsol_ata {
// Close wSOL ATA account, reclaim rent
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
@@ -315,16 +315,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
sol_amount = params.fixed_output_amount.unwrap();
}
// Determine fee recipient based on mayhem mode
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
let is_mayhem_mode = protocol_params.is_mayhem_mode;
let fee_recipient =
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
let fee_recipient_meta = if is_mayhem_mode {
accounts::MAYHEM_FEE_RECIPIENT_META
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
get_mayhem_fee_recipient_random()
} else {
accounts::FEE_RECIPIENT_META
(accounts::FEE_RECIPIENT, accounts::FEE_RECIPIENT_META)
};
let fee_recipient_ata = if is_mayhem_mode {
fee_recipient_ata(fee_recipient, crate::constants::WSOL_TOKEN_ACCOUNT)
} else {
fee_recipient_ata(fee_recipient, quote_mint)
};
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
let user_base_token_account =
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
@@ -375,23 +377,30 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
]);
if !quote_is_wsol_or_usdc {
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
accounts.push(AccountMeta::new(
get_user_volume_accumulator_pda(&params.payer.pubkey()).unwrap(),
false,
));
let uva = get_user_volume_accumulator_pda(&params.payer.pubkey())
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
accounts.push(AccountMeta::new(uva, false));
}
accounts.push(accounts::FEE_CONFIG_META);
accounts.push(accounts::FEE_PROGRAM_META);
// Cashback: remaining_accounts[0] = WSOL ATA of UserVolumeAccumulator, remaining_accounts[1] = UserVolumeAccumulator PDA
// Cashback sell: 官方 remainingAccounts = [accumulator 的 quote_mint ATA, accumulator PDA, poolV2](用 quote_mint 非固定 WSOL
if protocol_params.is_cashback_coin {
if let (Some(wsol_ata), Some(accumulator)) = (
get_user_volume_accumulator_wsol_ata(&params.payer.pubkey()),
if let (Some(quote_ata), Some(accumulator)) = (
get_user_volume_accumulator_quote_ata(
&params.payer.pubkey(),
&quote_mint,
&quote_token_program,
),
get_user_volume_accumulator_pda(&params.payer.pubkey()),
) {
accounts.push(AccountMeta::new(wsol_ata, false));
accounts.push(AccountMeta::new(quote_ata, false));
accounts.push(AccountMeta::new(accumulator, false));
}
}
// remainingAccounts: @pump-fun/pump-swap-sdk sell 要求末尾传 poolV2Pda(baseMint),勿删
let pool_v2 = get_pool_v2_pda(&base_mint)
.ok_or_else(|| anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint))?;
accounts.push(AccountMeta::new_readonly(pool_v2, false));
// Create instruction data
let mut data = [0u8; 24];
@@ -409,13 +418,11 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
}
let sell_instruction = Instruction {
instructions.push(Instruction {
program_id: accounts::AMM_PROGRAM,
accounts: accounts.clone(),
accounts,
data: data.to_vec(),
};
instructions.push(sell_instruction);
});
if close_wsol_ata {
instructions.extend(crate::trading::common::close_wsol(&params.payer.pubkey()));
+2 -2
View File
@@ -29,7 +29,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
.protocol_params
.as_any()
.downcast_ref::<RaydiumAmmV4Params>()
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
let is_wsol = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|| protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
@@ -144,7 +144,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
.protocol_params
.as_any()
.downcast_ref::<RaydiumAmmV4Params>()
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
return Err(anyhow!("Token amount is not set"));
+75 -7
View File
@@ -1,12 +1,15 @@
use crate::common::{bonding_curve::BondingCurveAccount, SolanaRpcClient};
use anyhow::anyhow;
use solana_sdk::pubkey::Pubkey;
use rand::seq::IndexedRandom;
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
use std::sync::Arc;
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
pub mod seeds {
/// Seed for bonding curve PDAs
pub const BONDING_CURVE_SEED: &[u8] = b"bonding-curve";
/// Seed for bonding curve v2 PDA (required by program upgrade, readonly at end of account list)
pub const BONDING_CURVE_V2_SEED: &[u8] = b"bonding-curve-v2";
/// Seed for creator vault PDAs
pub const CREATOR_VAULT_SEED: &[u8] = b"creator-vault";
@@ -57,8 +60,18 @@ pub mod global_constants {
is_writable: true,
};
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
/// Mayhem fee recipients (pump-public-docs: use any one randomly)
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
];
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
pub const MAYHEM_FEE_RECIPIENT_META: solana_sdk::instruction::AccountMeta =
solana_sdk::instruction::AccountMeta {
pubkey: MAYHEM_FEE_RECIPIENT,
@@ -159,6 +172,19 @@ pub const BUY_DISCRIMINATOR: [u8; 8] = [102, 6, 61, 18, 1, 218, 235, 234];
pub const BUY_EXACT_SOL_IN_DISCRIMINATOR: [u8; 8] = [56, 252, 116, 8, 158, 223, 205, 95];
pub const SELL_DISCRIMINATOR: [u8; 8] = [51, 230, 133, 164, 1, 127, 131, 173];
/// Returns a random Mayhem fee recipient AccountMeta (pump-public-docs: Bonding Curve 2nd account = Mayhem fee recipient; use any one randomly).
#[inline]
pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
.choose(&mut rand::rng())
.unwrap_or(&global_constants::MAYHEM_FEE_RECIPIENTS[0]);
AccountMeta {
pubkey: recipient,
is_signer: false,
is_writable: true,
}
}
pub struct Symbol;
impl Symbol {
@@ -178,6 +204,20 @@ pub fn get_bonding_curve_pda(mint: &Pubkey) -> Option<Pubkey> {
)
}
/// Bonding curve v2 PDA (seeds: ["bonding-curve-v2", mint]). Required at end of buy/sell/buy_exact_sol_in accounts.
#[inline]
pub fn get_bonding_curve_v2_pda(mint: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::get_cached_pda(
crate::common::fast_fn::PdaCacheKey::PumpFunBondingCurveV2(*mint),
|| {
let seeds: &[&[u8]; 2] = &[seeds::BONDING_CURVE_V2_SEED, mint.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
},
)
}
#[inline]
pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
if creator_vault_pda.eq(&Pubkey::default()) {
@@ -186,10 +226,9 @@ pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
// Fast check against cached default creator vault
static DEFAULT_CREATOR_VAULT: std::sync::LazyLock<Option<Pubkey>> =
std::sync::LazyLock::new(|| get_creator_vault_pda(&Pubkey::default()));
if creator_vault_pda.eq(&DEFAULT_CREATOR_VAULT.unwrap()) {
Pubkey::default()
} else {
*creator_vault_pda
match DEFAULT_CREATOR_VAULT.as_ref() {
Some(default) if creator_vault_pda.eq(default) => Pubkey::default(),
_ => *creator_vault_pda,
}
}
}
@@ -259,3 +298,32 @@ pub fn get_buy_price(
s_u64.min(real_token_reserves)
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::pubkey::Pubkey;
#[test]
fn pumpfun_discriminators_are_8_bytes() {
assert_eq!(BUY_DISCRIMINATOR.len(), 8);
assert_eq!(BUY_EXACT_SOL_IN_DISCRIMINATOR.len(), 8);
assert_eq!(SELL_DISCRIMINATOR.len(), 8);
}
#[test]
fn pumpfun_bonding_curve_and_v2_pda_differ_for_same_mint() {
let mint = Pubkey::new_unique();
let pda = get_bonding_curve_pda(&mint).unwrap();
let pda_v2 = get_bonding_curve_v2_pda(&mint).unwrap();
assert_ne!(pda, pda_v2, "bonding_curve and bonding_curve_v2 PDAs must differ");
}
#[test]
fn pumpfun_creator_vault_pda_deterministic() {
let creator = Pubkey::new_unique();
let a = get_creator_vault_pda(&creator).unwrap();
let b = get_creator_vault_pda(&creator).unwrap();
assert_eq!(a, b);
}
}
+179 -23
View File
@@ -2,12 +2,17 @@ use crate::{
common::{
spl_associated_token_account::get_associated_token_address_with_program_id, SolanaRpcClient,
},
constants::TOKEN_PROGRAM,
constants::{TOKEN_PROGRAM, WSOL_TOKEN_ACCOUNT},
instruction::utils::pumpswap_types::{pool_decode, Pool},
};
use anyhow::anyhow;
use rand::seq::IndexedRandom;
use solana_account_decoder::UiAccountEncoding;
use solana_sdk::pubkey::Pubkey;
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
/// PumpSwap 池账户总长度(见 pump-public-docs Breaking Change):8 字节 discriminator + 244 字节 Pool。
/// 官方文档:pool structure needs to be 244 bytes (was 243),含 is_mayhem_mode。DataSize 必须与此一致,否则 getProgramAccounts 会返回 0。
const POOL_ACCOUNT_DATA_LEN: u64 = 8 + 244;
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
pub mod seeds {
@@ -26,6 +31,13 @@ pub mod seeds {
pub const USER_VOLUME_ACCUMULATOR_SEED: &[u8] = b"user_volume_accumulator";
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
pub const FEE_CONFIG_SEED: &[u8] = b"fee_config";
/// Seed for pool v2 PDA (required by program upgrade, readonly at end of account list)
pub const POOL_V2_SEED: &[u8] = b"pool-v2";
/// Legacy pool PDA seed (used with index, creator, base_mint, quote_mint)
pub const POOL_SEED: &[u8] = b"pool";
/// Pump program: pool-authority PDA seed (creator for canonical pool)
pub const POOL_AUTHORITY_SEED: &[u8] = b"pool-authority";
}
/// Constants related to program accounts and authorities
@@ -50,6 +62,8 @@ pub mod accounts {
pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
pub const AMM_PROGRAM: Pubkey = pubkey!("pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA");
/// Pump Bonding Curve programcanonical pool 的 creator 来自此程序的 pool-authority PDA
pub const PUMP_PROGRAM_ID: Pubkey = pubkey!("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P");
pub const LP_FEE_BASIS_POINTS: u64 = 25;
pub const PROTOCOL_FEE_BASIS_POINTS: u64 = 5;
@@ -65,9 +79,19 @@ pub mod accounts {
pub const DEFAULT_COIN_CREATOR_VAULT_AUTHORITY: Pubkey =
pubkey!("8N3GDaZ2iwN65oxVatKTLPNooAVUJTbfiVJ1ahyqwjSk");
/// Mayhem fee recipient (for mayhem mode coins)
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
/// Mayhem fee recipients (pump-public-docs: use any one randomly for throughput)
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
];
/// Default Mayhem fee recipient (first of MAYHEM_FEE_RECIPIENTS)
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
// META
@@ -139,6 +163,59 @@ pub const BUY_DISCRIMINATOR: [u8; 8] = [102, 6, 61, 18, 1, 218, 235, 234];
pub const BUY_EXACT_QUOTE_IN_DISCRIMINATOR: [u8; 8] = [198, 46, 21, 82, 180, 217, 232, 112];
pub const SELL_DISCRIMINATOR: [u8; 8] = [51, 230, 133, 164, 1, 127, 131, 173];
/// Returns a random Mayhem fee recipient and its AccountMeta (pump-public-docs: use any one randomly).
#[inline]
pub fn get_mayhem_fee_recipient_random() -> (Pubkey, AccountMeta) {
let recipient = *accounts::MAYHEM_FEE_RECIPIENTS
.choose(&mut rand::rng())
.unwrap_or(&accounts::MAYHEM_FEE_RECIPIENTS[0]);
let meta = AccountMeta {
pubkey: recipient,
is_signer: false,
is_writable: false,
};
(recipient, meta)
}
/// Pool v2 PDA (seeds: ["pool-v2", base_mint]). Required at end of buy/sell/buy_exact_quote_in accounts.
#[inline]
pub fn get_pool_v2_pda(base_mint: &Pubkey) -> Option<Pubkey> {
let (pda, _) = Pubkey::find_program_address(
&[seeds::POOL_V2_SEED, base_mint.as_ref()],
&accounts::AMM_PROGRAM,
);
Some(pda)
}
/// Pump 程序上的 pool-authority PDAcanonical pool 的 creator),与 @pump-fun/pump-swap-sdk 一致。
#[inline]
pub fn get_pump_pool_authority_pda(mint: &Pubkey) -> Pubkey {
Pubkey::find_program_address(
&[seeds::POOL_AUTHORITY_SEED, mint.as_ref()],
&accounts::PUMP_PROGRAM_ID,
)
.0
}
/// Canonical Pump 池 PDAindex=0creator=pumpPoolAuthorityPda(mint)base_mint=mintquote_mint=WSOL。
/// 与 @pump-fun/pump-swap-sdk 的 canonicalPumpPoolPda(mint) 一致,用于从 bonding curve 迁移后的标准池查找。
#[inline]
pub fn get_canonical_pool_pda(mint: &Pubkey) -> Pubkey {
const CANONICAL_POOL_INDEX: u16 = 0;
let authority = get_pump_pool_authority_pda(mint);
let (pda, _) = Pubkey::find_program_address(
&[
seeds::POOL_SEED,
&CANONICAL_POOL_INDEX.to_le_bytes(),
authority.as_ref(),
mint.as_ref(),
WSOL_TOKEN_ACCOUNT.as_ref(),
],
&accounts::AMM_PROGRAM,
);
pda
}
// Find a pool for a specific mint
pub async fn find_pool(rpc: &SolanaRpcClient, mint: &Pubkey) -> Result<Pubkey, anyhow::Error> {
let (pool_address, _) = find_by_mint(rpc, mint).await?;
@@ -178,14 +255,14 @@ pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::PdaCacheKey::PumpSwapUserVolume(*user),
|| {
let seeds: &[&[u8]; 2] = &[&seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
},
)
}
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (used for cashback remaining accounts).
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (buy cashback: remaining_accounts[0] 官方用 NATIVE_MINT).
pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
let accumulator = get_user_volume_accumulator_pda(user)?;
Some(crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
@@ -195,9 +272,23 @@ pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
))
}
/// Quote-mint ATA of UserVolumeAccumulatorsell cashback 时官方用 quoteMint,非固定 WSOL.
pub fn get_user_volume_accumulator_quote_ata(
user: &Pubkey,
quote_mint: &Pubkey,
quote_token_program: &Pubkey,
) -> Option<Pubkey> {
let accumulator = get_user_volume_accumulator_pda(user)?;
Some(crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
&accumulator,
quote_mint,
quote_token_program,
))
}
pub fn get_global_volume_accumulator_pda() -> Option<Pubkey> {
let seeds: &[&[u8]; 1] = &[&seeds::GLOBAL_VOLUME_ACCUMULATOR_SEED];
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
}
@@ -218,11 +309,12 @@ pub async fn find_by_base_mint(
rpc: &SolanaRpcClient,
base_mint: &Pubkey,
) -> Result<(Pubkey, Pool), anyhow::Error> {
// Use getProgramAccounts to find pools for the given mint
// Use getProgramAccounts to find pools for the given mint.
// base_mint 在账户布局中的偏移:8(discriminator) + 1(bump) + 2(index) + 32(creator) = 43
let filters = vec![
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
solana_rpc_client_api::filter::RpcFilterType::DataSize(POOL_ACCOUNT_DATA_LEN),
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, &base_mint.to_bytes()),
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, base_mint.as_ref()),
),
];
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
@@ -261,19 +353,20 @@ pub async fn find_by_base_mint(
}
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
let (address, pool) = pools[0].clone();
Ok((address, pool))
let first = &pools[0];
Ok((first.0, first.1.clone()))
}
pub async fn find_by_quote_mint(
rpc: &SolanaRpcClient,
quote_mint: &Pubkey,
) -> Result<(Pubkey, Pool), anyhow::Error> {
// Use getProgramAccounts to find pools for the given mint
// Use getProgramAccounts to find pools for the given mint.
// quote_mint 在账户布局中的偏移:8 + 1 + 2 + 32 + 32 = 75
let filters = vec![
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
solana_rpc_client_api::filter::RpcFilterType::DataSize(POOL_ACCOUNT_DATA_LEN),
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, &quote_mint.to_bytes()),
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, quote_mint.as_ref()),
),
];
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
@@ -312,21 +405,56 @@ pub async fn find_by_quote_mint(
}
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
let (address, pool) = pools[0].clone();
Ok((address, pool))
let first = &pools[0];
Ok((first.0, first.1.clone()))
}
/// 按 mint 查找 PumpSwap 池(本函数仅用于 PumpSwap,其他 DEX 勿用)。
///
/// 查找顺序(与 @pump-fun/pump-swap-sdk 一致):
/// 1. Pool v2 PDA ["pool-v2", base_mint] — 一次 getAccount
/// 2. Canonical pool PDA ["pool", 0, pumpPoolAuthority(mint), mint, WSOL] — 迁移后的标准池
/// 3. getProgramAccounts 按 base_mint / quote_mint 过滤
pub async fn find_by_mint(
rpc: &SolanaRpcClient,
mint: &Pubkey,
) -> Result<(Pubkey, Pool), anyhow::Error> {
if let Ok((address, pool)) = find_by_base_mint(rpc, mint).await {
return Ok((address, pool));
let mut diag = Vec::<String>::new();
// 1. PumpSwap v2 PDAseeds: ["pool-v2", base_mint]
if let Some(pool_address) = get_pool_v2_pda(mint) {
diag.push(format!("PDA(v2)={}", pool_address));
match fetch_pool(rpc, &pool_address).await {
Ok(pool) if pool.base_mint == *mint => return Ok((pool_address, pool)),
Ok(_) => diag.push("PDA(v2) 账户存在但 base_mint 不匹配".into()),
Err(e) => diag.push(format!("PDA(v2) get_account/decode 失败: {}", e)),
}
}
if let Ok((address, pool)) = find_by_quote_mint(rpc, mint).await {
return Ok((address, pool));
// 2. Canonical pool PDA(与 pump-swap-sdk canonicalPumpPoolPda(mint) 一致)
let canonical_address = get_canonical_pool_pda(mint);
diag.push(format!("canonical={}", canonical_address));
match fetch_pool(rpc, &canonical_address).await {
Ok(pool) if pool.base_mint == *mint => return Ok((canonical_address, pool)),
Ok(_) => diag.push("canonical 账户存在但 base_mint 不匹配".into()),
Err(e) => diag.push(format!("canonical get_account/decode 失败: {}", e)),
}
Err(anyhow!("No pool found for mint {}", mint))
// 3. 回退:getProgramAccounts 按 base_mint / quote_mint
match find_by_base_mint(rpc, mint).await {
Ok((address, pool)) => return Ok((address, pool)),
Err(e) => diag.push(format!("getProgramAccounts(base_mint): {}", e)),
}
match find_by_quote_mint(rpc, mint).await {
Ok((address, pool)) => return Ok((address, pool)),
Err(e) => diag.push(format!("getProgramAccounts(quote_mint): {}", e)),
}
Err(anyhow!(
"No pool found for mint {}. 诊断: {}。若使用自建 RPC 请确认已开启 getProgramAccounts 或换用公共 RPC 重试;若代币未在 PumpSwap 建池请先在 pump.fun/DEX 上确认",
mint,
diag.join("; ")
))
}
pub async fn get_token_balances(
@@ -349,3 +477,31 @@ pub fn get_fee_config_pda() -> Option<Pubkey> {
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
}
#[cfg(test)]
mod tests {
use super::*;
use solana_sdk::pubkey::Pubkey;
#[test]
fn pumpswap_user_volume_accumulator_pda_deterministic() {
let user = Pubkey::new_unique();
let a = get_user_volume_accumulator_pda(&user).unwrap();
let b = get_user_volume_accumulator_pda(&user).unwrap();
assert_eq!(a, b);
}
#[test]
fn pumpswap_global_volume_accumulator_matches_constant() {
let pda = get_global_volume_accumulator_pda().unwrap();
assert_eq!(pda, accounts::GLOBAL_VOLUME_ACCUMULATOR);
}
#[test]
fn pumpswap_pool_v2_pda_deterministic() {
let base_mint = Pubkey::new_unique();
let a = get_pool_v2_pda(&base_mint).unwrap();
let b = get_pool_v2_pda(&base_mint).unwrap();
assert_eq!(a, b);
}
}
+4 -1
View File
@@ -17,9 +17,12 @@ pub struct Pool {
pub is_mayhem_mode: bool,
/// Whether this pool's coin has cashback enabled
pub is_cashback_coin: bool,
/// Reserved for future fields (pump-public-docs: pool structure = 244 bytes total)
pub _reserved: [u8; 7],
}
pub const POOL_SIZE: usize = 1 + 2 + 32 * 6 + 8 + 32 + 1 + 1;
/// Borsh 解码用的 Pool 长度。链上池为 244 字节(pump-public-docs Breaking Change),与 POOL_SIZE 一致。
pub const POOL_SIZE: usize = 244;
pub fn pool_decode(data: &[u8]) -> Option<Pool> {
if data.len() < POOL_SIZE {
+271 -165
View File
@@ -6,6 +6,7 @@ pub mod swqos;
pub mod trading;
pub mod utils;
use crate::common::nonce_cache::DurableNonceInfo;
use crate::common::sdk_log;
use crate::common::GasFeeStrategy;
use crate::common::{TradeConfig, InfrastructureConfig};
#[cfg(feature = "perf-trace")]
@@ -18,6 +19,8 @@ use crate::swqos::common::TradeError;
use crate::swqos::SwqosClient;
use crate::swqos::SwqosConfig;
use crate::swqos::TradeType;
// Re-export for SWQOS HTTP/QUIC choice in SwqosConfig (e.g. Astralane)
pub use crate::swqos::SwqosTransport;
use crate::trading::core::params::BonkParams;
use crate::trading::core::params::MeteoraDammV2Params;
use crate::trading::core::params::PumpFunParams;
@@ -37,6 +40,40 @@ use solana_sdk::message::AddressLookupTableAccount;
use solana_sdk::signer::Signer;
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signature::Signature};
use std::sync::Arc;
#[allow(unused_imports)]
use tracing::{debug, error, info, warn};
/// Single place to validate that protocol params match the given DEX type (avoids duplicate match in buy/sell).
#[inline(always)]
fn validate_protocol_params(dex_type: DexType, params: &DexParamEnum) -> bool {
match dex_type {
DexType::PumpFun => params.as_any().downcast_ref::<PumpFunParams>().is_some(),
DexType::PumpSwap => params.as_any().downcast_ref::<PumpSwapParams>().is_some(),
DexType::Bonk => params.as_any().downcast_ref::<BonkParams>().is_some(),
DexType::RaydiumCpmm => params.as_any().downcast_ref::<RaydiumCpmmParams>().is_some(),
DexType::RaydiumAmmV4 => params.as_any().downcast_ref::<RaydiumAmmV4Params>().is_some(),
DexType::MeteoraDammV2 => params.as_any().downcast_ref::<MeteoraDammV2Params>().is_some(),
}
}
/// 按 mint 查找池地址(通用入口,根据 DEX 类型分发,仅 PumpSwap 等已实现的类型会走优化路径)。
///
/// * `dex_type`PumpSwap 时先走 PDA 再回退 getProgramAccounts,其他类型返回未实现错误。
pub async fn find_pool_by_mint(
rpc: &SolanaRpcClient,
mint: &Pubkey,
dex_type: DexType,
) -> Result<Pubkey, anyhow::Error> {
match dex_type {
DexType::PumpSwap => {
crate::instruction::utils::pumpswap::find_pool(rpc, mint).await
}
_ => Err(anyhow::anyhow!(
"find_pool_by_mint not implemented for {:?}",
dex_type
)),
}
}
/// Type of the token to buy
#[derive(Clone, PartialEq)]
@@ -81,28 +118,65 @@ impl TradingInfrastructure {
config.commitment.clone(),
));
// Initialize rent cache and start background updater
common::seed::update_rents(&rpc).await.unwrap();
// Initialize rent cache (with timeout so slow RPC doesn't block forever)
const RENT_UPDATE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
match tokio::time::timeout(RENT_UPDATE_TIMEOUT, common::seed::update_rents(&rpc)).await {
Ok(Ok(())) => {}
Ok(Err(e)) => {
if sdk_log::sdk_log_enabled() {
warn!(target: "sol_trade_sdk", "rent update failed: {}, using defaults", e);
}
common::seed::set_default_rents();
}
Err(_) => {
if sdk_log::sdk_log_enabled() {
warn!(target: "sol_trade_sdk", "rent update timed out ({}s), using defaults; check RPC", RENT_UPDATE_TIMEOUT.as_secs());
}
common::seed::set_default_rents();
}
}
common::seed::start_rent_updater(rpc.clone());
// Create SWQOS clients with blacklist checking
// Create SWQOS clients with blacklist checking(单节点超时 5s,避免某一家卡死整段初始化)
const SWQOS_CLIENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
let mut swqos_clients: Vec<Arc<SwqosClient>> = vec![];
for swqos in &config.swqos_configs {
// Check blacklist, skip disabled providers
if swqos.is_blacklisted() {
eprintln!("\u{26a0}\u{fe0f} SWQOS {:?} is blacklisted, skipping", swqos.swqos_type());
if sdk_log::sdk_log_enabled() {
warn!(target: "sol_trade_sdk", "⚠️ SWQOS {:?} is blacklisted, skipping", swqos.swqos_type());
}
continue;
}
match SwqosConfig::get_swqos_client(
config.rpc_url.clone(),
config.commitment.clone(),
swqos.clone(),
).await {
Ok(swqos_client) => swqos_clients.push(swqos_client),
Err(err) => eprintln!(
"failed to create {:?} swqos client: {err}. Excluding from swqos list",
swqos.swqos_type()
match tokio::time::timeout(
SWQOS_CLIENT_TIMEOUT,
SwqosConfig::get_swqos_client(
config.rpc_url.clone(),
config.commitment.clone(),
swqos.clone(),
),
)
.await
{
Ok(Ok(swqos_client)) => swqos_clients.push(swqos_client),
Ok(Err(err)) => {
if sdk_log::sdk_log_enabled() {
warn!(
target: "sol_trade_sdk",
"failed to create {:?} swqos client: {err}. Excluding from swqos list",
swqos.swqos_type()
);
}
}
Err(_) => {
if sdk_log::sdk_log_enabled() {
warn!(
target: "sol_trade_sdk",
"swqos {:?} init timed out ({}s), skipping",
swqos.swqos_type(),
SWQOS_CLIENT_TIMEOUT.as_secs()
);
}
}
}
}
@@ -130,6 +204,12 @@ pub struct TradingClient {
/// Whether to use seed optimization for all ATA operations (default: true)
/// Applies to all token account creations across buy and sell operations
pub use_seed_optimize: bool,
/// Whether to pin parallel submit tasks to CPU cores (from TradeConfig.use_core_affinity). Default true.
pub use_core_affinity: bool,
/// Whether to output all SDK logs (from TradeConfig.log_enabled).
pub log_enabled: bool,
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). Default false for lower latency.
pub check_min_tip: bool,
}
static INSTANCE: Mutex<Option<Arc<TradingClient>>> = Mutex::new(None);
@@ -144,6 +224,9 @@ impl Clone for TradingClient {
infrastructure: self.infrastructure.clone(),
middleware_manager: self.middleware_manager.clone(),
use_seed_optimize: self.use_seed_optimize,
use_core_affinity: self.use_core_affinity,
log_enabled: self.log_enabled,
check_min_tip: self.check_min_tip,
}
}
}
@@ -193,6 +276,8 @@ pub struct TradeBuyParams {
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
/// This option only applies to PumpFun and PumpSwap DEXes; it is ignored for other DEXes.
pub use_exact_sol_amount: Option<bool>,
/// 可选:事件收到时间(微秒,与 sol-parser-sdk 的 metadata.grpc_recv_us / clock::now_micros 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点,打印起点→提交耗时。
pub grpc_recv_us: Option<i64>,
}
/// Parameters for executing sell orders across different DEX protocols
@@ -237,6 +322,8 @@ pub struct TradeSellParams {
pub gas_fee_strategy: GasFeeStrategy,
/// Whether to simulate the transaction instead of executing it
pub simulate: bool,
/// 可选:事件收到时间(微秒,与 sol-parser-sdk clock 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点。
pub grpc_recv_us: Option<i64>,
}
impl TradingClient {
@@ -266,6 +353,9 @@ impl TradingClient {
infrastructure,
middleware_manager: None,
use_seed_optimize,
use_core_affinity: true,
log_enabled: true,
check_min_tip: false,
}
}
@@ -293,7 +383,9 @@ impl TradingClient {
tokio::spawn(async move {
Self::ensure_wsol_ata(&payer_clone, &rpc_clone).await;
});
println!("ℹ️ WSOL ATA 创建已在后台启动,不阻塞机器人启动");
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "️ WSOL ATA creation started in background, does not block bot startup");
}
}
Self {
@@ -301,11 +393,50 @@ impl TradingClient {
infrastructure,
middleware_manager: None,
use_seed_optimize,
use_core_affinity: true,
log_enabled: true,
check_min_tip: false,
}
}
/// Helper to ensure WSOL ATA exists for a wallet
/// 单次尝试创建 WSOL ATA:获取 blockhash、组交易、发送并确认。成功或账户已存在返回 Ok(()),否则返回 Err(错误信息)。
async fn try_create_wsol_ata_once(
rpc: &SolanaRpcClient,
payer: &Arc<Keypair>,
wsol_ata: &solana_sdk::pubkey::Pubkey,
create_ata_ixs: &[solana_sdk::instruction::Instruction],
timeout_secs: u64,
) -> Result<(), String> {
use solana_sdk::transaction::Transaction;
let recent_blockhash = rpc.get_latest_blockhash().await
.map_err(|e| format!("Failed to get blockhash: {}", e))?;
let tx = Transaction::new_signed_with_payer(
create_ata_ixs,
Some(&payer.pubkey()),
&[payer.as_ref()],
recent_blockhash,
);
let send_result = tokio::time::timeout(
tokio::time::Duration::from_secs(timeout_secs),
rpc.send_and_confirm_transaction(&tx),
).await;
match send_result {
Ok(Ok(_signature)) => Ok(()),
Ok(Err(e)) => {
if rpc.get_account(wsol_ata).await.is_ok() {
return Ok(());
}
Err(format!("{}", e))
}
Err(_) => Err(format!("Transaction confirmation timeout ({}s)", timeout_secs)),
}
}
/// 确保钱包存在 WSOL ATA;不存在则发交易创建(会花费租金 + 手续费,初始化阶段唯一会扣钱的逻辑)
async fn ensure_wsol_ata(payer: &Arc<Keypair>, rpc: &Arc<SolanaRpcClient>) {
const MAX_RETRIES: usize = 3;
const TIMEOUT_SECS: u64 = 10;
let wsol_ata =
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
&payer.pubkey(),
@@ -313,104 +444,62 @@ impl TradingClient {
&crate::constants::TOKEN_PROGRAM,
);
match rpc.get_account(&wsol_ata).await {
Ok(_) => {
println!("✅ WSOL ATA已存在: {}", wsol_ata);
return;
if rpc.get_account(&wsol_ata).await.is_ok() {
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists: {}", wsol_ata);
}
Err(_) => {
println!("🔨 创建WSOL ATA: {}", wsol_ata);
let create_ata_ixs =
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
return;
}
if !create_ata_ixs.is_empty() {
use solana_sdk::transaction::Transaction;
let create_ata_ixs =
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
if create_ata_ixs.is_empty() {
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "️ WSOL ATA already exists (no need to create)");
}
return;
}
// 重试逻辑:最多尝试3次,每次超时10秒
const MAX_RETRIES: usize = 3;
const TIMEOUT_SECS: u64 = 10;
let mut last_error = None;
for attempt in 1..=MAX_RETRIES {
if attempt > 1 {
println!("🔄 重试创建WSOL ATA (第{}/{})...", attempt, MAX_RETRIES);
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
}
let recent_blockhash = match rpc.get_latest_blockhash().await {
Ok(hash) => hash,
Err(e) => {
eprintln!("⚠️ 获取最新blockhash失败: {}", e);
last_error = Some(format!("获取blockhash失败: {}", e));
continue;
}
};
let tx = Transaction::new_signed_with_payer(
&create_ata_ixs,
Some(&payer.pubkey()),
&[payer.as_ref()],
recent_blockhash,
);
// 使用超时包装 send_and_confirm_transaction
let send_result = tokio::time::timeout(
tokio::time::Duration::from_secs(TIMEOUT_SECS),
rpc.send_and_confirm_transaction(&tx)
).await;
match send_result {
Ok(Ok(signature)) => {
println!("✅ WSOL ATA创建成功: {}", signature);
return;
}
Ok(Err(e)) => {
last_error = Some(format!("{}", e));
// 检查账户是否实际已存在
if let Ok(_) = rpc.get_account(&wsol_ata).await {
println!(
"✅ WSOL ATA已存在(交易失败但账户存在): {}",
wsol_ata
);
return;
}
if attempt < MAX_RETRIES {
eprintln!("⚠️ 第{}次尝试失败: {}", attempt, e);
}
}
Err(_) => {
last_error = Some(format!("交易确认超时({}秒)", TIMEOUT_SECS));
eprintln!("⚠️ 第{}次尝试超时", attempt);
}
}
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "🔨 Creating WSOL ATA: {}", wsol_ata);
}
let mut last_error = None;
for attempt in 1..=MAX_RETRIES {
if attempt > 1 {
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "🔄 Retrying WSOL ATA creation (attempt {}/{})...", attempt, MAX_RETRIES);
}
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
}
match Self::try_create_wsol_ata_once(rpc.as_ref(), payer, &wsol_ata, &create_ata_ixs, TIMEOUT_SECS).await {
Ok(()) => {
if sdk_log::sdk_log_enabled() {
info!(target: "sol_trade_sdk", "✅ WSOL ATA created or already exists");
}
// 所有重试都失败了
if let Some(err) = last_error {
eprintln!("❌ WSOL ATA创建失败(已重试{}次): {}", MAX_RETRIES, wsol_ata);
eprintln!(" 错误详情: {}", err);
eprintln!(" 💡 可能原因:");
eprintln!(" 1. 钱包SOL余额不足(需要约0.002 SOL用于租金豁免)");
eprintln!(" 2. RPC节点响应超时或网络拥堵");
eprintln!(" 3. 交易费用不足");
eprintln!(" 🔧 解决方案:");
eprintln!(" 1. 给钱包充值至少0.1 SOL");
eprintln!(" 2. 等待几秒后重试");
eprintln!(" 3. 检查RPC节点连接");
eprintln!(" ⚠️ 程序将在5秒后退出,请解决上述问题后重启");
std::thread::sleep(std::time::Duration::from_secs(5));
panic!(
"❌ WSOL ATA创建失败且账户不存在: {}. 错误: {}",
wsol_ata, err
);
return;
}
Err(e) => {
last_error = Some(e.clone());
if attempt < MAX_RETRIES && sdk_log::sdk_log_enabled() {
warn!(target: "sol_trade_sdk", "⚠️ Attempt {} failed: {}", attempt, e);
}
} else {
println!("ℹ️ WSOL ATA已存在(无需创建)");
}
}
}
if let Some(err) = last_error {
if sdk_log::sdk_log_enabled() {
error!(target: "sol_trade_sdk", "❌ WSOL ATA creation failed after {} retries: {}", MAX_RETRIES, wsol_ata);
error!(target: "sol_trade_sdk", " Error: {}", err);
error!(target: "sol_trade_sdk", " 💡 Possible causes: insufficient SOL, RPC timeout, or fee");
error!(target: "sol_trade_sdk", " 🔧 Solutions: fund wallet (e.g. 0.1 SOL), retry, check RPC");
}
std::thread::sleep(std::time::Duration::from_secs(5));
panic!(
"❌ WSOL ATA creation failed and account does not exist: {}. Error: {}",
wsol_ata, err
);
}
}
/// Creates a new SolTradingSDK instance with the specified configuration
@@ -426,6 +515,10 @@ impl TradingClient {
/// Returns a configured `SolTradingSDK` instance ready for trading operations
#[inline]
pub async fn new(payer: Arc<Keypair>, trade_config: TradeConfig) -> Self {
// 设置 SDK 全局日志开关,后续所有 SDK 内日志(SWQOS/WSOL/耗时等)均受此控制
sdk_log::set_sdk_log_enabled(trade_config.log_enabled);
// 预热高性能时钟,避免首笔交易时触发 3 次 Utc::now() 校准
let _ = crate::common::clock::now_micros();
// Create infrastructure from trade config
let infra_config = InfrastructureConfig::from_trade_config(&trade_config);
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);
@@ -433,9 +526,32 @@ impl TradingClient {
// Initialize wallet-specific caches
crate::common::fast_fn::fast_init(&payer.pubkey());
// Handle WSOL ATA creation if configured
// ═══════════════════════════════════════════════════════════════════════════════
// 初始化阶段会花费租金/手续费的唯一路径:创建 WSOL ATAensure_wsol_ata
// - 触发条件:create_wsol_ata_on_startup == true 且钱包 SOL >= MIN_SOL_FOR_WSOL_ATA_LAMPORTS
// - 花费:ATA 租金(约 0.00203928 SOL)+ 交易手续费;钱包不足时已跳过
// - 其它初始化(TradingInfrastructure::new、update_rents、get_swqos_client)仅 RPC/HTTP,不发送交易
// ═══════════════════════════════════════════════════════════════════════════════
if trade_config.create_wsol_ata_on_startup {
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
const MIN_SOL_FOR_WSOL_ATA_LAMPORTS: u64 = 500_000; // 约 0.0005 SOL,用于 ATA 租金 + 手续费
const BALANCE_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
let balance = tokio::time::timeout(
BALANCE_CHECK_TIMEOUT,
infrastructure.rpc.get_balance(&payer.pubkey()),
)
.await
.unwrap_or(Ok(0))
.unwrap_or(0);
if balance >= MIN_SOL_FOR_WSOL_ATA_LAMPORTS {
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
} else if sdk_log::sdk_log_enabled() {
info!(
target: "sol_trade_sdk",
"⏭️ 跳过创建 WSOL ATA:钱包 SOL 不足(当前 {} lamports,需要至少 {}",
balance,
MIN_SOL_FOR_WSOL_ATA_LAMPORTS
);
}
}
let instance = Self {
@@ -443,6 +559,9 @@ impl TradingClient {
infrastructure,
middleware_manager: None,
use_seed_optimize: trade_config.use_seed_optimize,
use_core_affinity: trade_config.use_core_affinity,
log_enabled: trade_config.log_enabled,
check_min_tip: trade_config.check_min_tip,
};
let mut current = INSTANCE.lock();
@@ -524,16 +643,29 @@ impl TradingClient {
&self,
params: TradeBuyParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
if params.recent_blockhash.is_none() && params.durable_nonce.is_none() {
return Err(anyhow::anyhow!(
"Must provide either recent_blockhash or durable_nonce for buy (required for transaction validity)"
));
}
#[cfg(feature = "perf-trace")]
if params.slippage_basis_points.is_none() {
log::debug!(
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
debug!(
target: "sol_trade_sdk",
"slippage_basis_points is none, use default slippage basis points: {}",
DEFAULT_SLIPPAGE
);
}
if params.input_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
return Err(anyhow::anyhow!(
" Current version only support USD1 trading on Bonk protocols"
" Current version only supports USD1 trading on Bonk protocols"
));
}
let protocol_params = params.extension_params;
if !validate_protocol_params(params.dex_type, &protocol_params) {
return Err(anyhow::anyhow!(
"Invalid protocol params for Trade (dex={:?})",
params.dex_type
));
}
let input_token_mint = if params.input_token_type == TradeTokenType::SOL {
@@ -545,8 +677,7 @@ impl TradingClient {
} else {
USD1_TOKEN_ACCOUNT
};
let executor = TradeFactory::create_executor(params.dex_type.clone());
let protocol_params = params.extension_params;
let executor = TradeFactory::create_executor(params.dex_type);
let buy_params = SwapParams {
rpc: Some(self.infrastructure.rpc.clone()),
payer: self.payer.clone(),
@@ -560,7 +691,7 @@ impl TradingClient {
address_lookup_table_account: params.address_lookup_table_account,
recent_blockhash: params.recent_blockhash,
wait_transaction_confirmed: params.wait_transaction_confirmed,
protocol_params: protocol_params.clone(),
protocol_params,
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
swqos_clients: self.infrastructure.swqos_clients.clone(),
middleware_manager: self.middleware_manager.clone(),
@@ -573,31 +704,13 @@ impl TradingClient {
fixed_output_amount: params.fixed_output_token_amount,
gas_fee_strategy: params.gas_fee_strategy,
simulate: params.simulate,
log_enabled: self.log_enabled,
use_core_affinity: self.use_core_affinity,
check_min_tip: self.check_min_tip,
grpc_recv_us: params.grpc_recv_us,
use_exact_sol_amount: params.use_exact_sol_amount,
};
// Validate protocol params
let is_valid_params = match params.dex_type {
DexType::PumpFun => protocol_params.as_any().downcast_ref::<PumpFunParams>().is_some(),
DexType::PumpSwap => {
protocol_params.as_any().downcast_ref::<PumpSwapParams>().is_some()
}
DexType::Bonk => protocol_params.as_any().downcast_ref::<BonkParams>().is_some(),
DexType::RaydiumCpmm => {
protocol_params.as_any().downcast_ref::<RaydiumCpmmParams>().is_some()
}
DexType::RaydiumAmmV4 => {
protocol_params.as_any().downcast_ref::<RaydiumAmmV4Params>().is_some()
}
DexType::MeteoraDammV2 => {
protocol_params.as_any().downcast_ref::<MeteoraDammV2Params>().is_some()
}
};
if !is_valid_params {
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
}
let swap_result = executor.swap(buy_params).await;
let result =
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
@@ -635,19 +748,31 @@ impl TradingClient {
params: TradeSellParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
#[cfg(feature = "perf-trace")]
if params.slippage_basis_points.is_none() {
log::debug!(
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
debug!(
target: "sol_trade_sdk",
"slippage_basis_points is none, use default slippage basis points: {}",
DEFAULT_SLIPPAGE
);
}
if params.output_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
if params.recent_blockhash.is_none() && params.durable_nonce.is_none() {
return Err(anyhow::anyhow!(
" Current version only support USD1 trading on Bonk protocols"
"Must provide either recent_blockhash or durable_nonce for sell (required for transaction validity)"
));
}
if params.output_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
return Err(anyhow::anyhow!(
" Current version only supports USD1 trading on Bonk protocols"
));
}
let executor = TradeFactory::create_executor(params.dex_type.clone());
let protocol_params = params.extension_params;
if !validate_protocol_params(params.dex_type, &protocol_params) {
return Err(anyhow::anyhow!(
"Invalid protocol params for Trade (dex={:?})",
params.dex_type
));
}
let executor = TradeFactory::create_executor(params.dex_type);
let output_token_mint = if params.output_token_type == TradeTokenType::SOL {
SOL_TOKEN_ACCOUNT
} else if params.output_token_type == TradeTokenType::WSOL {
@@ -670,7 +795,7 @@ impl TradingClient {
address_lookup_table_account: params.address_lookup_table_account,
recent_blockhash: params.recent_blockhash,
wait_transaction_confirmed: params.wait_transaction_confirmed,
protocol_params: protocol_params.clone(),
protocol_params,
with_tip: params.with_tip,
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
swqos_clients: self.infrastructure.swqos_clients.clone(),
@@ -683,32 +808,13 @@ impl TradingClient {
fixed_output_amount: params.fixed_output_token_amount,
gas_fee_strategy: params.gas_fee_strategy,
simulate: params.simulate,
log_enabled: self.log_enabled,
use_core_affinity: self.use_core_affinity,
check_min_tip: self.check_min_tip,
grpc_recv_us: params.grpc_recv_us,
use_exact_sol_amount: None,
};
// Validate protocol params
let is_valid_params = match params.dex_type {
DexType::PumpFun => protocol_params.as_any().downcast_ref::<PumpFunParams>().is_some(),
DexType::PumpSwap => {
protocol_params.as_any().downcast_ref::<PumpSwapParams>().is_some()
}
DexType::Bonk => protocol_params.as_any().downcast_ref::<BonkParams>().is_some(),
DexType::RaydiumCpmm => {
protocol_params.as_any().downcast_ref::<RaydiumCpmmParams>().is_some()
}
DexType::RaydiumAmmV4 => {
protocol_params.as_any().downcast_ref::<RaydiumAmmV4Params>().is_some()
}
DexType::MeteoraDammV2 => {
protocol_params.as_any().downcast_ref::<MeteoraDammV2Params>().is_some()
}
};
if !is_valid_params {
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
}
// Execute sell based on tip preference
let swap_result = executor.swap(sell_params).await;
let result =
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
+2 -2
View File
@@ -140,7 +140,7 @@ impl CompilerOptimizer {
/// 🚀 生成超高性能编译配置
pub fn generate_ultra_performance_config(&self) -> Result<CompilerConfig> {
log::info!("🚀 Generating ultra-performance compiler configuration...");
tracing::info!(target: "sol_trade_sdk","🚀 Generating ultra-performance compiler configuration...");
let mut rustflags = Vec::new();
@@ -206,7 +206,7 @@ impl CompilerOptimizer {
cargo_config: self.generate_cargo_config(),
};
log::info!("✅ Ultra-performance compiler configuration generated");
tracing::info!(target: "sol_trade_sdk","✅ Ultra-performance compiler configuration generated");
Ok(config)
}
+39 -78
View File
@@ -1,11 +1,5 @@
//! 🚀 硬件级性能优化 - CPU缓存行对齐 & SIMD加速
//!
//! 实现CPU硬件特性的深度利用,包括:
//! - 缓存行对齐和缓存预取
//! - SIMD指令集优化
//! - 分支预测优化
//! - 内存屏障控制
//! - CPU指令流水线优化
//! Hardware-oriented optimizations: cache-line alignment, prefetch, SIMD, branch hints, memory barriers.
//! 硬件级优化:缓存行对齐与预取、SIMD、分支提示、内存屏障。
use std::sync::atomic::{AtomicU64, Ordering};
use std::mem::size_of;
@@ -13,26 +7,23 @@ use std::ptr;
use crossbeam_utils::CachePadded;
use anyhow::Result;
// CPU缓存行大小常量 (通常为64字节)
/// Typical CPU cache line size in bytes. 典型 CPU 缓存行大小(字节)。
pub const CACHE_LINE_SIZE: usize = 64;
/// 🚀 硬件优化的数据结构基础特征
/// Trait for cache-line-aligned data and prefetch. 缓存行对齐与预取 trait。
pub trait CacheLineAligned {
/// 确保数据结构按缓存行对齐
fn ensure_cache_aligned(&self) -> bool;
/// 预取数据到CPU缓存
fn prefetch_data(&self);
}
/// 🚀 SIMD优化的内存操作
/// SIMD-accelerated memory operations. SIMD 加速的内存操作
pub struct SIMDMemoryOps;
impl SIMDMemoryOps {
/// 🚀 SIMD加速的内存拷贝 - 针对小数据包优化
/// SIMD-optimized copy by size class. 按长度分派的 SIMD 拷贝。
#[inline(always)]
pub unsafe fn memcpy_simd_optimized(dst: *mut u8, src: *const u8, len: usize) {
match len {
// 针对不同数据大小使用不同优化策略
0 => return,
1..=8 => Self::memcpy_small(dst, src, len),
9..=16 => Self::memcpy_sse(dst, src, len),
@@ -42,7 +33,7 @@ impl SIMDMemoryOps {
}
}
/// 小数据拷贝优化 (1-8字节)
/// Copy 18 bytes (scalar / small word). 小数据拷贝(18 字节)。
#[inline(always)]
unsafe fn memcpy_small(dst: *mut u8, src: *const u8, len: usize) {
match len {
@@ -63,7 +54,7 @@ impl SIMDMemoryOps {
}
}
/// SSE优化拷贝 (9-16字节)
/// Copy 916 bytes using SSE (128-bit). SSE 拷贝(916 字节)。
#[inline(always)]
unsafe fn memcpy_sse(dst: *mut u8, src: *const u8, len: usize) {
#[cfg(target_arch = "x86_64")]
@@ -82,7 +73,7 @@ impl SIMDMemoryOps {
}
}
/// AVX优化拷贝 (17-32字节)
/// Copy 1732 bytes using AVX (256-bit). AVX 拷贝(1732 字节)。
#[inline(always)]
unsafe fn memcpy_avx(dst: *mut u8, src: *const u8, len: usize) {
#[cfg(target_arch = "x86_64")]
@@ -101,19 +92,16 @@ impl SIMDMemoryOps {
}
}
/// AVX2优化拷贝 (33-64字节)
/// Copy 3364 bytes using AVX2 (256-bit, two chunks). AVX2 拷贝(3364 字节,两段)。
#[inline(always)]
unsafe fn memcpy_avx2(dst: *mut u8, src: *const u8, len: usize) {
#[cfg(target_arch = "x86_64")]
{
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
// 拷贝前32字节
let chunk1 = _mm256_loadu_si256(src as *const __m256i);
_mm256_storeu_si256(dst as *mut __m256i, chunk1);
if len > 32 {
// 拷贝剩余字节
let remaining = len - 32;
if remaining <= 32 {
let chunk2 = _mm256_loadu_si256(src.add(32) as *const __m256i);
@@ -128,7 +116,7 @@ impl SIMDMemoryOps {
}
}
/// AVX512或回退拷贝 (>64字节)
/// Copy >64 bytes: AVX-512 64-byte chunks when available, else AVX2 32-byte chunks. >64 字节:有 AVX512 用 64 字节块,否则 AVX2 32 字节块。
#[inline(always)]
unsafe fn memcpy_avx512_or_fallback(dst: *mut u8, src: *const u8, len: usize) {
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
@@ -138,14 +126,12 @@ impl SIMDMemoryOps {
let chunks = len / 64;
let mut offset = 0;
// 使用AVX512处理64字节块
for _ in 0..chunks {
let chunk = _mm512_loadu_si512(src.add(offset) as *const __m512i);
_mm512_storeu_si512(dst.add(offset) as *mut __m512i, chunk);
offset += 64;
}
// 处理剩余字节
let remaining = len % 64;
if remaining > 0 {
Self::memcpy_avx2(dst.add(offset), src.add(offset), remaining);
@@ -154,7 +140,6 @@ impl SIMDMemoryOps {
#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
{
// 回退到AVX2分块处理
let chunks = len / 32;
let mut offset = 0;
@@ -170,7 +155,7 @@ impl SIMDMemoryOps {
}
}
/// 🚀 SIMD加速的内存比较
/// SIMD-optimized byte equality; dispatches by length (small / SSE / AVX2 / large). SIMD 加速的内存比较,按长度分派。
#[inline(always)]
pub unsafe fn memcmp_simd_optimized(a: *const u8, b: *const u8, len: usize) -> bool {
match len {
@@ -182,7 +167,7 @@ impl SIMDMemoryOps {
}
}
/// 小数据比较
/// Compare 18 bytes (scalar). 小数据比较(18 字节)。
#[inline(always)]
unsafe fn memcmp_small(a: *const u8, b: *const u8, len: usize) -> bool {
match len {
@@ -198,7 +183,7 @@ impl SIMDMemoryOps {
}
}
/// SSE比较
/// Compare 916 bytes using SSE. SSE 比较(916 字节)。
#[inline(always)]
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
#[cfg(target_arch = "x86_64")]
@@ -210,7 +195,6 @@ impl SIMDMemoryOps {
let cmp_result = _mm_cmpeq_epi8(chunk_a, chunk_b);
let mask = _mm_movemask_epi8(cmp_result) as u32;
// 检查前len字节是否相等
let valid_mask = if len >= 16 { 0xFFFF } else { (1u32 << len) - 1 };
(mask & valid_mask) == valid_mask
}
@@ -221,7 +205,7 @@ impl SIMDMemoryOps {
}
}
/// AVX2比较
/// Compare 1732 bytes using AVX2. AVX2 比较(1732 字节)。
#[inline(always)]
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
#[cfg(target_arch = "x86_64")]
@@ -243,7 +227,7 @@ impl SIMDMemoryOps {
}
}
/// 大数据比较
/// Compare >32 bytes in 32-byte AVX2 chunks. 大数据比较(32 字节 AVX2 分块)。
#[inline(always)]
unsafe fn memcmp_large(a: *const u8, b: *const u8, len: usize) -> bool {
let chunks = len / 32;
@@ -263,7 +247,7 @@ impl SIMDMemoryOps {
true
}
/// 🚀 SIMD加速的内存清零
/// SIMD-optimized zero memory. SIMD 加速的内存清零
#[inline(always)]
pub unsafe fn memzero_simd_optimized(ptr: *mut u8, len: usize) {
#[cfg(target_arch = "x86_64")]
@@ -279,7 +263,6 @@ impl SIMDMemoryOps {
offset += 32;
}
// 处理剩余字节
let remaining = len % 32;
for i in 0..remaining {
*ptr.add(offset + i) = 0;
@@ -293,14 +276,15 @@ impl SIMDMemoryOps {
}
}
/// 🚀 缓存行对齐的原子计数器
#[repr(align(64))] // 强制64字节对齐
/// Cache-line-aligned atomic counter. 缓存行对齐的原子计数器
#[repr(align(64))]
pub struct CacheAlignedCounter {
value: AtomicU64,
_padding: [u8; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
}
impl CacheAlignedCounter {
/// Create counter with initial value. 创建并设置初值。
pub fn new(initial: u64) -> Self {
Self {
value: AtomicU64::new(initial),
@@ -339,23 +323,18 @@ impl CacheLineAligned for CacheAlignedCounter {
}
}
/// 🚀 缓存友好的环形缓冲区
/// Cache-friendly lock-free ring buffer. 缓存友好的无锁环形缓冲区
#[repr(align(64))]
pub struct CacheOptimizedRingBuffer<T> {
/// 数据缓冲区
buffer: Vec<T>,
/// 生产者头指针 (独占缓存行)
producer_head: CachePadded<AtomicU64>,
/// 消费者尾指针 (独占缓存行)
consumer_tail: CachePadded<AtomicU64>,
/// 容量 (2的幂次方)
capacity: usize,
/// 掩码 (capacity - 1)
mask: usize,
}
impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
/// 创建缓存优化的环形缓冲区
/// Create ring buffer; capacity must be a power of 2. 创建环形缓冲区,容量须为 2 的幂。
pub fn new(capacity: usize) -> Result<Self> {
if !capacity.is_power_of_two() {
return Err(anyhow::anyhow!("Capacity must be a power of 2"));
@@ -373,53 +352,41 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
})
}
/// 🚀 无锁写入元素
/// Lock-free push; returns false if full. 无锁写入,满则返回 false。
#[inline(always)]
pub fn try_push(&self, item: T) -> bool {
let current_head = self.producer_head.load(Ordering::Relaxed);
let current_tail = self.consumer_tail.load(Ordering::Acquire);
// 检查是否还有空间
if (current_head + 1) & self.mask as u64 == current_tail & self.mask as u64 {
return false; // 缓冲区满
return false;
}
// 写入数据
unsafe {
let index = current_head & self.mask as u64;
let ptr = self.buffer.as_ptr().add(index as usize) as *mut T;
ptr.write(item);
}
// 发布新的头指针
self.producer_head.store(current_head + 1, Ordering::Release);
true
}
/// 🚀 无锁读取元素
/// Lock-free pop; returns None if empty. 无锁读取,空则返回 None。
#[inline(always)]
pub fn try_pop(&self) -> Option<T> {
let current_tail = self.consumer_tail.load(Ordering::Relaxed);
let current_head = self.producer_head.load(Ordering::Acquire);
// 检查是否有数据
if current_tail == current_head {
return None; // 缓冲区空
return None;
}
// 读取数据
let item = unsafe {
let index = current_tail & self.mask as u64;
let ptr = self.buffer.as_ptr().add(index as usize);
ptr.read()
};
// 发布新的尾指针
self.consumer_tail.store(current_tail + 1, Ordering::Release);
Some(item)
}
/// 获取当前元素数量
/// Current number of elements. 当前元素个数。
#[inline(always)]
pub fn len(&self) -> usize {
let head = self.producer_head.load(Ordering::Relaxed);
@@ -427,7 +394,7 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
((head + self.capacity as u64 - tail) & self.mask as u64) as usize
}
/// 检查是否为空
/// True if no elements. 是否为空
#[inline(always)]
pub fn is_empty(&self) -> bool {
self.producer_head.load(Ordering::Relaxed) ==
@@ -445,24 +412,18 @@ impl<T> CacheLineAligned for CacheOptimizedRingBuffer<T> {
unsafe {
use std::arch::x86_64::_mm_prefetch;
use std::arch::x86_64::_MM_HINT_T0;
// 预取头指针
_mm_prefetch(self.producer_head.as_ptr() as *const i8, _MM_HINT_T0);
// 预取尾指针
_mm_prefetch(self.consumer_tail.as_ptr() as *const i8, _MM_HINT_T0);
// 预取缓冲区开始位置
_mm_prefetch(self.buffer.as_ptr() as *const i8, _MM_HINT_T0);
}
}
}
/// 🚀 CPU分支预测优化工具
/// Branch hint helpers (likely/unlikely) and prefetch. 分支提示与预取。
pub struct BranchOptimizer;
impl BranchOptimizer {
/// likely宏 - 告诉编译器条件大概率为真
/// Hint: condition is usually true. 提示编译器条件大概率为真
#[inline(always)]
pub fn likely(condition: bool) -> bool {
#[cold]
@@ -474,7 +435,7 @@ impl BranchOptimizer {
condition
}
/// unlikely宏 - 告诉编译器条件大概率为假
/// Hint: condition is usually false. 提示编译器条件大概率为假
#[inline(always)]
pub fn unlikely(condition: bool) -> bool {
#[cold]
@@ -486,7 +447,7 @@ impl BranchOptimizer {
condition
}
/// 预取指令 - 提前加载数据到缓存
/// Prefetch: load cache line at ptr into L1. Caller must ensure ptr is valid, read-only, no concurrent write. 预取:将 ptr 所在缓存行加载到 L1;调用方需保证有效、只读、无并发写。
#[inline(always)]
pub unsafe fn prefetch_read_data<T>(ptr: *const T) {
#[cfg(target_arch = "x86_64")]
@@ -497,7 +458,7 @@ impl BranchOptimizer {
}
}
/// 预取指令 - 提前加载数据到缓存(写优化)
/// Prefetch for write (T1 hint). 写预取(T1 提示)。
#[inline(always)]
pub unsafe fn prefetch_write_data<T>(ptr: *const T) {
#[cfg(target_arch = "x86_64")]
@@ -509,35 +470,35 @@ impl BranchOptimizer {
}
}
/// 🚀 内存屏障控制
/// Memory barrier helpers. 内存屏障辅助。
pub struct MemoryBarriers;
impl MemoryBarriers {
/// 编译器屏障 - 防止编译器重排序
/// Compiler barrier only (no CPU reorder). 仅编译器屏障,防止重排序
#[inline(always)]
pub fn compiler_barrier() {
std::sync::atomic::compiler_fence(Ordering::SeqCst);
}
/// 轻量级内存屏障 - 仅CPU重排序保护
/// Light barrier (Acquire). 轻量级屏障(Acquire)。
#[inline(always)]
pub fn memory_barrier_light() {
std::sync::atomic::fence(Ordering::Acquire);
}
/// 重量级内存屏障 - 全序一致性
/// Full sequential consistency barrier. 全序一致性屏障。
#[inline(always)]
pub fn memory_barrier_heavy() {
std::sync::atomic::fence(Ordering::SeqCst);
}
/// 存储屏障 - 确保写入可见性
/// Store/release barrier. 存储屏障,保证写入可见性
#[inline(always)]
pub fn store_barrier() {
std::sync::atomic::fence(Ordering::Release);
}
/// 加载屏障 - 确保读取正确性
/// Load/acquire barrier. 加载屏障,保证读取顺序。
#[inline(always)]
pub fn load_barrier() {
std::sync::atomic::fence(Ordering::Acquire);
+2 -8
View File
@@ -1,11 +1,5 @@
//! 🚀 性能优化模块
//!
//! 提供多层次性能优化:
//! - SIMD 向量化:AVX2 内存操作、批量计算
//! - 硬件级优化:分支预测、缓存预取
//! - 零拷贝 I/O:内存映射、DMA传输
//! - 系统调用绕过:批处理、快速时间
//! - 编译器优化:内联、向量化
//! Performance: SIMD, cache prefetch, branch hints, zero-copy I/O, syscall bypass, compiler hints.
//! 性能优化:SIMD、缓存预取、分支提示、零拷贝 I/O、系统调用绕过、编译器提示。
pub mod simd;
pub mod hardware_optimizations;
+27 -59
View File
@@ -1,13 +1,5 @@
//! 🚀 系统调用绕过机制 - 最小化系统调用开销
//!
//! 实现系统调用级别的极致优化,包括:
//! - 系统调用批处理
//! - vDSO快速系统调用
//! - io_uring异步I/O优化
//! - 内存映射系统调用
//! - 用户空间系统调用实现
//! - 系统调用拦截与优化
//! - 直接硬件访问
//! Syscall bypass: batching, vDSO fast time, io_uring, mmap, userspace impl.
//! 系统调用绕过:批处理、vDSO 快速时间、io_uring、mmap、用户态实现。
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
@@ -18,38 +10,25 @@ use std::fs::OpenOptions;
use anyhow::Result;
use crossbeam_utils::CachePadded;
/// 🚀 系统调用绕过管理器
/// Syscall bypass manager (batch, fast time, I/O). 系统调用绕过管理器
pub struct SystemCallBypassManager {
/// 绕过配置
config: SyscallBypassConfig,
/// 批处理器
batch_processor: Arc<SyscallBatchProcessor>,
/// 快速时间获取器
fast_time_provider: Arc<FastTimeProvider>,
/// I/O优化器
_io_optimizer: Arc<IOOptimizer>,
/// 统计信息
stats: Arc<SyscallBypassStats>,
}
/// 系统调用绕过配置
/// Syscall bypass configuration. 系统调用绕过配置
#[derive(Debug, Clone)]
pub struct SyscallBypassConfig {
/// 启用系统调用批处理
pub enable_batch_processing: bool,
/// 批处理大小
pub batch_size: usize,
/// 启用快速时间获取
pub enable_fast_time: bool,
/// 启用vDSO优化
pub enable_vdso: bool,
/// 启用io_uring
pub enable_io_uring: bool,
/// 启用内存映射优化
pub enable_mmap_optimization: bool,
/// 启用用户空间实现
pub enable_userspace_impl: bool,
/// 系统调用缓存大小
pub syscall_cache_size: usize,
}
@@ -68,30 +47,19 @@ impl Default for SyscallBypassConfig {
}
}
/// 系统调用批处理器
pub struct SyscallBatchProcessor {
/// 待处理的系统调用队列
pending_calls: crossbeam_queue::ArrayQueue<SyscallRequest>,
/// 批处理线程池
_executor: tokio::runtime::Handle,
/// 批处理统计
batch_stats: CachePadded<AtomicU64>,
}
/// 系统调用请求
#[derive(Debug, Clone)]
pub enum SyscallRequest {
/// 文件写入
Write { fd: i32, data: Vec<u8> },
/// 文件读取
Read { fd: i32, size: usize },
/// 网络发送
Send { socket: i32, data: Vec<u8> },
/// 网络接收
Recv { socket: i32, size: usize },
/// 时间获取
GetTime,
/// 内存分配
MemAlloc { size: usize },
/// 内存释放
MemFree { ptr: usize },
@@ -132,7 +100,7 @@ impl FastTimeProvider {
vdso_enabled: enable_vdso,
};
log::info!("🚀 Fast time provider initialized with vDSO: {}", enable_vdso);
tracing::info!(target: "sol_trade_sdk","🚀 Fast time provider initialized with vDSO: {}", enable_vdso);
Ok(provider)
}
@@ -233,7 +201,7 @@ impl IOOptimizer {
pub fn new(_config: &SyscallBypassConfig) -> Result<Self> {
let io_uring_available = Self::check_io_uring_support();
log::info!("🚀 I/O Optimizer initialized - io_uring: {}", io_uring_available);
tracing::info!(target: "sol_trade_sdk","🚀 I/O Optimizer initialized - io_uring: {}", io_uring_available);
Ok(Self {
io_uring_available,
@@ -249,7 +217,7 @@ impl IOOptimizer {
// 检查内核版本和io_uring支持
if let Ok(uname) = std::process::Command::new("uname").arg("-r").output() {
let kernel_version = String::from_utf8_lossy(&uname.stdout);
log::info!("Kernel version: {}", kernel_version.trim());
tracing::info!(target: "sol_trade_sdk","Kernel version: {}", kernel_version.trim());
// 简单检查:内核版本 >= 5.1 支持io_uring
if let Some(version_str) = kernel_version.split('.').next() {
@@ -277,7 +245,7 @@ impl IOOptimizer {
/// 使用io_uring进行批量写入
async fn io_uring_batch_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
// 这里是伪代码 - 实际实现需要io_uring库
log::trace!("Using io_uring for {} write operations", requests.len());
tracing::trace!(target: "sol_trade_sdk","Using io_uring for {} write operations", requests.len());
let mut results = Vec::with_capacity(requests.len());
@@ -362,7 +330,7 @@ impl IOOptimizer {
self.mmap_regions.push(region);
log::info!("✅ Memory mapped I/O created: {} bytes at {:p}", size, addr);
tracing::info!(target: "sol_trade_sdk","✅ Memory mapped I/O created: {} bytes at {:p}", size, addr);
Ok(addr as usize)
}
}
@@ -390,7 +358,7 @@ impl SyscallBatchProcessor {
let pending_calls = crossbeam_queue::ArrayQueue::new(batch_size * 10);
let executor = tokio::runtime::Handle::current();
log::info!("🚀 Syscall batch processor created with batch size: {}", batch_size);
tracing::info!(target: "sol_trade_sdk","🚀 Syscall batch processor created with batch size: {}", batch_size);
Ok(Self {
pending_calls,
@@ -464,7 +432,7 @@ impl SyscallBatchProcessor {
self.batch_stats.fetch_add(1, Ordering::Relaxed);
log::trace!("Executed batch of {} syscalls", batch_size);
tracing::trace!(target: "sol_trade_sdk","Executed batch of {} syscalls", batch_size);
Ok(batch_size)
}
@@ -473,7 +441,7 @@ impl SyscallBatchProcessor {
// 使用writev系统调用进行批量写入
for (fd, data) in requests {
// 实际实现会使用writev或io_uring
log::trace!("Batched write to fd {}: {} bytes", fd, data.len());
tracing::trace!(target: "sol_trade_sdk","Batched write to fd {}: {} bytes", fd, data.len());
}
Ok(())
}
@@ -482,7 +450,7 @@ impl SyscallBatchProcessor {
async fn batch_read_operations(&self, requests: Vec<(i32, usize)>) -> Result<()> {
// 使用readv系统调用进行批量读取
for (fd, size) in requests {
log::trace!("Batched read from fd {}: {} bytes", fd, size);
tracing::trace!(target: "sol_trade_sdk","Batched read from fd {}: {} bytes", fd, size);
}
Ok(())
}
@@ -491,7 +459,7 @@ impl SyscallBatchProcessor {
async fn batch_network_operations(&self, requests: Vec<(i32, Vec<u8>)>) -> Result<()> {
// 使用sendmsg/recvmsg进行批量网络操作
for (socket, data) in requests {
log::trace!("Batched network send to socket {}: {} bytes", socket, data.len());
tracing::trace!(target: "sol_trade_sdk","Batched network send to socket {}: {} bytes", socket, data.len());
}
Ok(())
}
@@ -515,11 +483,11 @@ impl SystemCallBypassManager {
let io_optimizer = Arc::new(IOOptimizer::new(&config)?);
let stats = Arc::new(SyscallBypassStats::default());
log::info!("🚀 System Call Bypass Manager initialized");
log::info!(" 📦 Batch Processing: {}", config.enable_batch_processing);
log::info!(" ⏰ Fast Time: {}", config.enable_fast_time);
log::info!(" 🚀 vDSO: {}", config.enable_vdso);
log::info!(" 📁 io_uring: {}", config.enable_io_uring);
tracing::info!(target: "sol_trade_sdk","🚀 System Call Bypass Manager initialized");
tracing::info!(target: "sol_trade_sdk"," 📦 Batch Processing: {}", config.enable_batch_processing);
tracing::info!(target: "sol_trade_sdk"," ⏰ Fast Time: {}", config.enable_fast_time);
tracing::info!(target: "sol_trade_sdk"," 🚀 vDSO: {}", config.enable_vdso);
tracing::info!(target: "sol_trade_sdk"," 📁 io_uring: {}", config.enable_io_uring);
Ok(Self {
config,
@@ -626,7 +594,7 @@ impl SystemCallBypassManager {
}
});
log::info!("✅ Batch processing worker started");
tracing::info!(target: "sol_trade_sdk","✅ Batch processing worker started");
Ok(())
}
@@ -669,16 +637,16 @@ pub struct SyscallBypassStatsSnapshot {
impl SyscallBypassStatsSnapshot {
/// 打印统计信息
pub fn print_stats(&self) {
log::info!("📊 System Call Bypass Stats:");
log::info!(" 🚫 Syscalls Bypassed: {}", self.syscalls_bypassed);
log::info!(" 📦 Syscalls Batched: {}", self.syscalls_batched);
log::info!(" ⏰ Time Calls Cached: {}", self.time_calls_cached);
log::info!(" 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
log::info!(" 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
tracing::info!(target: "sol_trade_sdk","📊 System Call Bypass Stats:");
tracing::info!(target: "sol_trade_sdk"," 🚫 Syscalls Bypassed: {}", self.syscalls_bypassed);
tracing::info!(target: "sol_trade_sdk"," 📦 Syscalls Batched: {}", self.syscalls_batched);
tracing::info!(target: "sol_trade_sdk"," ⏰ Time Calls Cached: {}", self.time_calls_cached);
tracing::info!(target: "sol_trade_sdk"," 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
tracing::info!(target: "sol_trade_sdk"," 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
let total_optimizations = self.syscalls_bypassed + self.time_calls_cached +
self.io_operations_optimized + self.memory_operations_avoided;
log::info!(" 🏆 Total Optimizations: {}", total_optimizations);
tracing::info!(target: "sol_trade_sdk"," 🏆 Total Optimizations: {}", total_optimizations);
}
}
+12 -12
View File
@@ -73,7 +73,7 @@ impl SharedMemoryPool {
free_blocks.push(AtomicU64::new(bits));
}
log::info!("🚀 Created shared memory pool {} with {} blocks of {} bytes each",
tracing::info!(target: "sol_trade_sdk","🚀 Created shared memory pool {} with {} blocks of {} bytes each",
pool_id, total_blocks, aligned_block_size);
Ok(Self {
@@ -155,7 +155,7 @@ impl SharedMemoryPool {
#[inline(always)]
pub fn deallocate_block(&self, block: ZeroCopyBlock) {
if block.pool_id != self.pool_id {
log::error!("Attempting to deallocate block from wrong pool");
tracing::error!(target: "sol_trade_sdk", "Attempting to deallocate block from wrong pool");
return;
}
@@ -267,7 +267,7 @@ impl MemoryMappedBuffer {
.map_anon()
.context("Failed to create memory mapped buffer")?;
log::info!("🚀 Created memory mapped buffer {} with size {} bytes", buffer_id, size);
tracing::info!(target: "sol_trade_sdk","🚀 Created memory mapped buffer {} with size {} bytes", buffer_id, size);
Ok(Self {
mmap,
@@ -425,7 +425,7 @@ impl DirectMemoryAccessManager {
dma_channels.push(Arc::new(DMAChannel::new(i)?));
}
log::info!("🚀 Created DMA manager with {} channels", num_channels);
tracing::info!(target: "sol_trade_sdk","🚀 Created DMA manager with {} channels", num_channels);
Ok(Self {
dma_channels,
@@ -549,12 +549,12 @@ impl ZeroCopyStats {
let bytes = self.bytes_transferred.load(Ordering::Relaxed);
let mmap_usage = self.mmap_buffer_usage.load(Ordering::Relaxed);
log::info!("🚀 Zero-Copy Stats:");
log::info!(" 📦 Blocks: Allocated={}, Freed={}, Active={}",
tracing::info!(target: "sol_trade_sdk","🚀 Zero-Copy Stats:");
tracing::info!(target: "sol_trade_sdk"," 📦 Blocks: Allocated={}, Freed={}, Active={}",
allocated, freed, allocated.saturating_sub(freed));
log::info!(" 📊 Bytes Transferred: {} ({:.2} MB)",
tracing::info!(target: "sol_trade_sdk"," 📊 Bytes Transferred: {} ({:.2} MB)",
bytes, bytes as f64 / 1024.0 / 1024.0);
log::info!(" 💾 Memory Mapped Usage: {} ({:.2} MB)",
tracing::info!(target: "sol_trade_sdk"," 💾 Memory Mapped Usage: {} ({:.2} MB)",
mmap_usage, mmap_usage as f64 / 1024.0 / 1024.0);
}
}
@@ -581,10 +581,10 @@ impl ZeroCopyMemoryManager {
let dma_manager = Arc::new(DirectMemoryAccessManager::new(16)?); // 16 DMA channels
let stats = Arc::new(ZeroCopyStats::new());
log::info!("🚀 Zero-Copy Memory Manager initialized");
log::info!(" 📦 Memory Pools: {}", shared_pools.len());
log::info!(" 💾 Mapped Buffers: {}", mmap_buffers.len());
log::info!(" 🔄 DMA Channels: 16");
tracing::info!(target: "sol_trade_sdk","🚀 Zero-Copy Memory Manager initialized");
tracing::info!(target: "sol_trade_sdk"," 📦 Memory Pools: {}", shared_pools.len());
tracing::info!(target: "sol_trade_sdk"," 💾 Mapped Buffers: {}", mmap_buffers.len());
tracing::info!(target: "sol_trade_sdk"," 🔄 DMA Channels: 16");
Ok(Self {
shared_pools,
+124 -136
View File
@@ -1,13 +1,13 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use tracing::{error, info, warn};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
use bincode::serialize as bincode_serialize;
use solana_client::rpc_client::SerializableTransaction;
use solana_sdk::transaction::VersionedTransaction;
use crate::swqos::{SwqosType, TradeType};
use crate::swqos::SwqosClientTrait;
@@ -17,24 +17,40 @@ use crate::{common::SolanaRpcClient, constants::swqos::ASTRALANE_TIP_ACCOUNTS};
use tokio::task::JoinHandle;
use std::sync::atomic::{AtomicBool, Ordering};
/// Empty body for getHealth POST; avoid per-request allocation.
static PING_BODY: &[u8] = &[];
use crate::swqos::astralane_quic::AstralaneQuicClient;
#[derive(Clone)]
pub enum AstralaneBackend {
Http {
endpoint: String,
auth_token: String,
http_client: Client,
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
stop_ping: Arc<AtomicBool>,
},
Quic(Arc<AstralaneQuicClient>),
}
#[derive(Clone)]
pub struct AstralaneClient {
pub endpoint: String,
pub auth_token: String,
pub rpc_client: Arc<SolanaRpcClient>,
pub http_client: Client,
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
pub stop_ping: Arc<AtomicBool>,
backend: AstralaneBackend,
}
#[async_trait::async_trait]
impl SwqosClientTrait for AstralaneClient {
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
self.send_transaction(trade_type, transaction, wait_confirmation).await
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
}
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
self.send_transactions(trade_type, transactions, wait_confirmation).await
for transaction in transactions {
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
}
Ok(())
}
fn get_tip_account(&self) -> Result<String> {
@@ -48,157 +64,128 @@ impl SwqosClientTrait for AstralaneClient {
}
impl AstralaneClient {
/// 使用 HTTPirisb)提交。
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(300))
.pool_max_idle_per_host(4)
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let client = Self {
rpc_client: Arc::new(rpc_client),
endpoint,
auth_token,
http_client,
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
stop_ping: Arc::new(AtomicBool::new(false)),
let http_client = default_http_client_builder().build().unwrap();
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
let stop_ping = Arc::new(AtomicBool::new(false));
let client = Self {
rpc_client: Arc::new(rpc_client),
backend: AstralaneBackend::Http {
endpoint,
auth_token,
http_client,
ping_handle,
stop_ping,
},
};
// Start ping task
let client_clone = client.clone();
tokio::spawn(async move {
client_clone.start_ping_task().await;
});
client
}
/// Start periodic ping task to keep connections active
/// 使用 QUIC 提交。
pub async fn new_quic(rpc_url: String, quic_endpoint: &str, api_key: String) -> Result<Self> {
let rpc_client = SolanaRpcClient::new(rpc_url);
let quic_client = AstralaneQuicClient::connect(quic_endpoint, &api_key).await?;
Ok(Self {
rpc_client: Arc::new(rpc_client),
backend: AstralaneBackend::Quic(Arc::new(quic_client)),
})
}
async fn start_ping_task(&self) {
let endpoint = self.endpoint.clone();
let auth_token = self.auth_token.clone();
let http_client = self.http_client.clone();
let stop_ping = self.stop_ping.clone();
let handle = tokio::spawn(async move {
// Immediate first ping to warm connection and reduce first-submit cold start latency
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("Astralane ping request failed: {}", e);
}
let mut interval = tokio::time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
if stop_ping.load(Ordering::Relaxed) {
break;
}
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("Astralane ping request failed: {}", e);
match &self.backend {
AstralaneBackend::Http { endpoint, auth_token, http_client, ping_handle, stop_ping } => {
let endpoint = endpoint.clone();
let auth_token = auth_token.clone();
let http_client = http_client.clone();
let ping_handle = ping_handle.clone();
let stop_ping = stop_ping.clone();
let handle = tokio::spawn(async move {
let mut interval = tokio::time::interval(Duration::from_secs(30));
loop {
interval.tick().await;
if stop_ping.load(Ordering::Relaxed) {
break;
}
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
warn!(target: "sol_trade_sdk", "Astralane ping request failed: {}", e);
}
}
});
let mut guard = ping_handle.lock().await;
if let Some(old) = guard.as_ref() {
old.abort();
}
});
// Update ping_handle - use Mutex to safely update
{
let mut ping_guard = self.ping_handle.lock().await;
if let Some(old_handle) = ping_guard.as_ref() {
old_handle.abort();
*guard = Some(handle);
}
*ping_guard = Some(handle);
AstralaneBackend::Quic(_) => {}
}
}
/// Send ping request to /gethealth endpoint
/// Send ping request: POST endpoint?api-key=...&method=getHealth
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
// Build ping URL by replacing /iris with /gethealth
let ping_url = if endpoint.ends_with("/iris") {
endpoint.replace("/iris", "/gethealth")
} else if endpoint.ends_with("/iris/") {
endpoint.replace("/iris/", "/gethealth")
} else if endpoint.ends_with('/') {
format!("{}gethealth", endpoint)
} else {
format!("{}/gethealth", endpoint)
};
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
let response = http_client.get(&ping_url)
.header("api_key", auth_token)
let response = http_client
.post(endpoint)
.query(&[("api-key", auth_token), ("method", "getHealth")])
.timeout(Duration::from_millis(1500))
.body(PING_BODY)
.send()
.await?;
let status = response.status();
let _ = response.bytes().await;
if !status.is_success() {
eprintln!("Astralane ping request returned non-success status: {}", status);
warn!(target: "sol_trade_sdk", "Astralane ping request returned non-success status: {}", status);
}
Ok(())
}
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
async fn send_transaction_impl(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
let start_time = Instant::now();
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
let signature = transaction.get_signature();
let body_bytes = bincode_serialize(transaction).map_err(|e| anyhow::anyhow!("Astralane binary serialize failed: {}", e))?;
let request_body = serde_json::to_string(&json!({
"jsonrpc": "2.0",
"id": 1,
"method": "sendTransaction",
"params": [
content,
{ "encoding": "base64", "skipPreflight": true },
{ "mevProtect": false }
]
}))?;
// Send request with api_key header
let response_text = self.http_client.post(&self.endpoint)
.body(request_body)
.header("Content-Type", "application/json")
.header("api_key", &self.auth_token)
.send()
.await?
.text()
.await?;
// Parse JSON response
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" [astralane] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [astralane] {} submission failed: {:?}", trade_type, _error);
match &self.backend {
AstralaneBackend::Http { endpoint, auth_token, http_client, .. } => {
let response = http_client
.post(endpoint)
.query(&[("api-key", auth_token.as_str()), ("method", "sendTransaction")])
.header("Content-Type", "application/octet-stream")
.body(body_bytes)
.send()
.await?;
let status = response.status();
let _ = response.bytes().await;
if status.is_success() {
info!(target: "sol_trade_sdk", "[astralane] {} submitted: {:?}", trade_type, start_time.elapsed());
} else {
error!(target: "sol_trade_sdk", "[astralane] {} submission failed: status {}", trade_type, status);
return Err(anyhow::anyhow!("Astralane sendTransaction failed: {}", status));
}
}
AstralaneBackend::Quic(quic) => {
quic.send_transaction(&body_bytes).await?;
info!(target: "sol_trade_sdk", "[astralane-quic] {} submitted: {:?}", trade_type, start_time.elapsed());
}
} else {
eprintln!(" [astralane] {} submission failed: {:?}", trade_type, response_text);
}
let start_time: Instant = Instant::now();
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
let start_time = Instant::now();
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [astralane] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
info!(target: "sol_trade_sdk", "signature: {:?}", signature);
error!(target: "sol_trade_sdk", "[astralane] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
return Err(e);
},
}
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [astralane] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
Ok(())
}
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
for transaction in transactions {
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
info!(target: "sol_trade_sdk", "signature: {:?}", signature);
info!(target: "sol_trade_sdk", "[astralane] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
Ok(())
}
@@ -206,18 +193,19 @@ impl AstralaneClient {
impl Drop for AstralaneClient {
fn drop(&mut self) {
// Ensure ping task stops when client is destroyed
self.stop_ping.store(true, Ordering::Relaxed);
// Try to stop ping task immediately
// Use tokio::spawn to avoid blocking Drop
let ping_handle = self.ping_handle.clone();
tokio::spawn(async move {
let mut ping_guard = ping_handle.lock().await;
if let Some(handle) = ping_guard.as_ref() {
handle.abort();
match &self.backend {
AstralaneBackend::Http { stop_ping, ping_handle, .. } => {
stop_ping.store(true, Ordering::Relaxed);
let ping_handle = ping_handle.clone();
tokio::spawn(async move {
let mut guard = ping_handle.lock().await;
if let Some(handle) = guard.as_ref() {
handle.abort();
}
*guard = None;
});
}
*ping_guard = None;
});
AstralaneBackend::Quic(_) => {}
}
}
}
+252
View File
@@ -0,0 +1,252 @@
//! 内联自 [Astralane/astralane-quic-client](https://github.com/Astralane/astralane-quic-client)
//! 用于向 Astralane QUIC TPU 提交交易,不依赖外部 crate,便于审计与安全可控。
use anyhow::{Context, Result};
use quinn::crypto::rustls::QuicClientConfig;
use quinn::{ClientConfig, Connection, Endpoint, IdleTimeout, TransportConfig};
use rcgen::{CertificateParams, KeyPair};
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
use std::net::SocketAddr;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::Mutex;
use tracing::{info, warn};
/// ALPN protocol identifier for Astralane TPU.
const ALPN_ASTRALANE_TPU: &[u8] = b"astralane-tpu";
/// Maximum Solana transaction size.
pub const MAX_TRANSACTION_SIZE: usize = 1232;
/// QUIC application error codes returned by the server.
pub mod error_code {
pub const OK: u32 = 0;
pub const UNKNOWN_API_KEY: u32 = 1;
pub const CONNECTION_LIMIT: u32 = 2;
pub fn describe(code: u32) -> &'static str {
match code {
OK => "OK",
UNKNOWN_API_KEY => "Unknown API key",
CONNECTION_LIMIT => "Connection limit exceeded",
_ => "Unknown error",
}
}
}
/// QUIC client for sending transactions to Astralane's TPU endpoint.
pub struct AstralaneQuicClient {
endpoint: Endpoint,
connection: Mutex<Connection>,
server_addr: SocketAddr,
#[allow(dead_code)]
api_key: String,
}
impl AstralaneQuicClient {
/// Connect to an Astralane QUIC server.
/// Generates a self-signed TLS certificate with the API key as the Common Name (CN).
pub async fn connect(server_addr: &str, api_key: &str) -> Result<Self> {
let _ = rustls::crypto::ring::default_provider().install_default();
let addr = SocketAddr::from_str(server_addr).or_else(|_| {
use std::net::ToSocketAddrs;
server_addr
.to_socket_addrs()
.ok()
.and_then(|mut addrs| addrs.next())
.ok_or_else(|| anyhow::anyhow!("Cannot resolve address: {}", server_addr))
}).context("Invalid server address")?;
info!("[astralane-quic] Building TLS config (CN = api_key)");
let client_config = Self::build_client_config(api_key)?;
let mut endpoint =
Endpoint::client("0.0.0.0:0".parse()?).context("Failed to create QUIC endpoint")?;
endpoint.set_default_client_config(client_config);
info!("[astralane-quic] Connecting to {} ...", addr);
let connection = endpoint
.connect(addr, "astralane")?
.await
.context("Failed to connect to Astralane QUIC server")?;
info!("[astralane-quic] Connected at {}", addr);
Ok(Self {
endpoint,
connection: Mutex::new(connection),
server_addr: addr,
api_key: api_key.to_string(),
})
}
/// Send a single bincode-serialized `VersionedTransaction`.
/// Fire-and-forget; automatically reconnects if the connection is dead.
pub async fn send_transaction(&self, transaction_bytes: &[u8]) -> Result<()> {
if transaction_bytes.len() > MAX_TRANSACTION_SIZE {
anyhow::bail!(
"Transaction too large: {} bytes (max {})",
transaction_bytes.len(),
MAX_TRANSACTION_SIZE
);
}
let conn = {
let mut guard = self.connection.lock().await;
if let Some(reason) = guard.close_reason() {
if let quinn::ConnectionError::ApplicationClosed(ref info) = reason {
let code = info.error_code.into_inner();
if code != error_code::OK as u64 {
anyhow::bail!(
"Server closed connection: {} (code {})",
error_code::describe(code as u32),
code
);
}
}
warn!("[astralane-quic] Connection dead, reconnecting to {} ...", self.server_addr);
*guard = self
.endpoint
.connect(self.server_addr, "astralane")?
.await
.context("Failed to reconnect to Astralane QUIC server")?;
info!("[astralane-quic] Reconnected to {}", self.server_addr);
}
guard.clone()
};
let mut send_stream = conn
.open_uni()
.await
.context("Failed to open unidirectional stream")?;
send_stream
.write_all(transaction_bytes)
.await
.context("Failed to write transaction data")?;
send_stream.finish().context("Failed to finish stream")?;
info!("[astralane-quic] Transaction sent ({} bytes)", transaction_bytes.len());
Ok(())
}
/// Reconnect to the server if the connection was closed.
pub async fn reconnect(&self) -> Result<()> {
let mut guard = self.connection.lock().await;
if guard.close_reason().is_some() {
info!("[astralane-quic] Reconnecting at {}", self.server_addr);
*guard = self
.endpoint
.connect(self.server_addr, "astralane")?
.await
.context("Failed to reconnect to Astralane QUIC server")?;
info!("[astralane-quic] Reconnected to {}", self.server_addr);
}
Ok(())
}
/// Check if the connection is still alive.
pub async fn is_connected(&self) -> bool {
self.connection.lock().await.close_reason().is_none()
}
/// Close the connection gracefully.
pub async fn close(&self) {
self.connection
.lock()
.await
.close(error_code::OK.into(), b"client closing");
}
fn build_client_config(api_key: &str) -> Result<ClientConfig> {
let key_pair = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
let mut cert_params = CertificateParams::new(vec![])?;
cert_params.distinguished_name.push(
rcgen::DnType::CommonName,
rcgen::DnValue::Utf8String(api_key.to_string()),
);
let cert = cert_params.self_signed(&key_pair)?;
let cert_der = CertificateDer::from(cert.der().to_vec());
let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));
let mut crypto = rustls::ClientConfig::builder()
.dangerous()
.with_custom_certificate_verifier(Arc::new(SkipServerVerification))
.with_client_auth_cert(vec![cert_der], key_der)
.context("Failed to set client certificate")?;
crypto.alpn_protocols = vec![ALPN_ASTRALANE_TPU.to_vec()];
let mut transport = TransportConfig::default();
transport.max_idle_timeout(Some(
IdleTimeout::try_from(Duration::from_secs(30)).unwrap(),
));
transport.keep_alive_interval(Some(Duration::from_secs(25)));
let mut client_config =
ClientConfig::new(Arc::new(QuicClientConfig::try_from(crypto).unwrap()));
client_config.transport_config(Arc::new(transport));
Ok(client_config)
}
}
impl Drop for AstralaneQuicClient {
fn drop(&mut self) {
self.connection
.get_mut()
.close(error_code::OK.into(), b"client closing");
}
}
/// Skip server certificate verification (Astralane server may use self-signed cert).
#[derive(Debug)]
struct SkipServerVerification;
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
fn verify_server_cert(
&self,
_end_entity: &CertificateDer<'_>,
_intermediates: &[CertificateDer<'_>],
_server_name: &rustls::pki_types::ServerName<'_>,
_ocsp_response: &[u8],
_now: rustls::pki_types::UnixTime,
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
Ok(rustls::client::danger::ServerCertVerified::assertion())
}
fn verify_tls12_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn verify_tls13_signature(
&self,
_message: &[u8],
_cert: &CertificateDer<'_>,
_dss: &rustls::DigitallySignedStruct,
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
}
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
vec![
rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
rustls::SignatureScheme::RSA_PSS_SHA256,
rustls::SignatureScheme::RSA_PSS_SHA384,
rustls::SignatureScheme::RSA_PSS_SHA512,
rustls::SignatureScheme::RSA_PKCS1_SHA256,
rustls::SignatureScheme::RSA_PKCS1_SHA384,
rustls::SignatureScheme::RSA_PKCS1_SHA512,
rustls::SignatureScheme::ED25519,
]
}
}
+44 -62
View File
@@ -1,7 +1,6 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::{Client, header::{HeaderMap, HeaderValue, CONTENT_TYPE}};
use serde_json::json;
use reqwest::Client;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
@@ -50,17 +49,9 @@ impl SwqosClientTrait for BlockRazorClient {
impl BlockRazorClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(300)) // 5min so ping-kept connection is not evicted early
.pool_max_idle_per_host(4) // Few connections so submit reuses same connection as ping, avoiding cold connection after ~5min server idle close
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
// 官方文档:請求中唯一允許的 header 是 Content-Type: text/plain;避免默认 User-Agent 等导致 500
let http_client = default_http_client_builder()
.user_agent("")
.build()
.unwrap();
@@ -92,7 +83,9 @@ impl BlockRazorClient {
let handle = tokio::spawn(async move {
// Immediate first ping to warm connection and reduce first-submit cold start latency
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("BlockRazor ping request failed: {}", e);
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("BlockRazor ping request failed: {}", e);
}
}
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive to avoid server ~5min idle close
loop {
@@ -101,7 +94,9 @@ impl BlockRazorClient {
break;
}
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("BlockRazor ping request failed: {}", e);
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("BlockRazor ping request failed: {}", e);
}
}
}
});
@@ -116,31 +111,15 @@ impl BlockRazorClient {
}
}
/// Send ping request to /health endpoint
/// Send ping request: POST /v2/health?auth=... (Keep Alive). Only required param: auth.
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
// Build health URL by replacing sendTransaction with health
let ping_url = if endpoint.ends_with("sendTransaction") {
endpoint.replace("sendTransaction", "health")
} else if endpoint.ends_with("/sendTransaction") {
endpoint.replace("/sendTransaction", "/health")
} else {
// Fallback to original logic if endpoint doesn't end with sendTransaction
if endpoint.ends_with('/') {
format!("{}health", endpoint)
} else {
format!("{}/health", endpoint)
}
};
// Prepare headers
let mut headers = HeaderMap::new();
headers.insert("apikey", HeaderValue::from_str(auth_token)?);
headers.insert(CONTENT_TYPE, HeaderValue::from_static("application/json"));
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
let response = http_client.get(&ping_url)
.headers(headers)
let ping_url = endpoint.replace("/v2/sendTransaction", "/v2/health");
let response = http_client
.post(&ping_url)
.query(&[("auth", auth_token)])
.header("Content-Type", "text/plain")
.timeout(Duration::from_millis(1500))
.body(&[] as &[u8])
.send()
.await?;
let status = response.status();
@@ -151,47 +130,50 @@ impl BlockRazorClient {
Ok(())
}
/// Send transaction via v2 API: plain Base64 body, Content-Type: text/plain. Only required URI param: auth.
/// 文档要求:auth 以 URI 参数传入;body 为纯 Base64 编码交易;唯一允许的 header 为 Content-Type: text/plain。
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
let start_time = Instant::now();
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
// BlockRazor fast-mode request format
let request_body = serde_json::to_string(&json!({
"transaction": content,
"mode": "fast"
}))?;
// BlockRazor uses apikey header
let response_text = self.http_client.post(&self.endpoint)
.body(request_body)
.header("Content-Type", "application/json")
.header("apikey", &self.auth_token)
let response = self.http_client
.post(&self.endpoint)
.query(&[("auth", self.auth_token.as_str())])
.header("Content-Type", "text/plain")
.body(content)
.send()
.await?
.text()
.await?;
// Parse JSON response
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() || response_json.get("signature").is_some() {
let status = response.status();
if status.is_success() {
let _ = response.bytes().await;
if crate::common::sdk_log::sdk_log_enabled() {
println!(" [blockrazor] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [blockrazor] {} submission failed: {:?}", trade_type, _error);
}
} else {
eprintln!(" [blockrazor] {} submission failed: {:?}", trade_type, response_text);
let body = response.text().await.unwrap_or_default();
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [blockrazor] {} submission failed: status {} body: {}", trade_type, status, body);
}
return Err(anyhow::anyhow!(
"BlockRazor sendTransaction failed: status {} body: {}",
status,
body
));
}
let start_time: Instant = Instant::now();
let start_time = Instant::now();
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [blockrazor] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [blockrazor] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
}
return Err(e);
},
}
if wait_confirmation {
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [blockrazor] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
+22 -23
View File
@@ -1,3 +1,4 @@
use crate::swqos::common::default_http_client_builder;
use crate::swqos::common::poll_transaction_confirmation;
use crate::swqos::common::serialize_transaction_and_encode;
use crate::swqos::serialization;
@@ -47,17 +48,9 @@ impl SwqosClientTrait for BloxrouteClient {
impl BloxrouteClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
let http_client = default_http_client_builder()
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256) // Increased from 64 to 256
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.pool_max_idle_per_host(256)
.build()
.unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
@@ -85,12 +78,14 @@ impl BloxrouteClient {
// Parse with from_str to avoid extra wait from .json().await
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" [bloxroute] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [bloxroute] {} submission failed: {:?}", trade_type, _error);
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
println!(" [bloxroute] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [bloxroute] {} submission failed: {:?}", trade_type, _error);
}
}
} else {
} else if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [bloxroute] {} submission failed: {:?}", trade_type, response_text);
}
@@ -98,12 +93,14 @@ impl BloxrouteClient {
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [bloxroute] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [bloxroute] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
}
return Err(e);
},
}
if wait_confirmation {
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [bloxroute] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
@@ -135,11 +132,13 @@ impl BloxrouteClient {
.text()
.await?;
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" bloxroute {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" bloxroute {} submission failed: {:?}", trade_type, _error);
if crate::common::sdk_log::sdk_log_enabled() {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" bloxroute {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" bloxroute {} submission failed: {:?}", trade_type, _error);
}
}
}
+69 -16
View File
@@ -17,6 +17,36 @@ use std::str::FromStr;
use std::time::{Duration, Instant};
use tokio::time::sleep;
/// Default pool idle timeout for SWQOS HTTP client (seconds). 连接池空闲超时(秒)。
const HTTP_POOL_IDLE_TIMEOUT_SECS: u64 = 300;
/// Max idle connections per host. 每主机最大空闲连接数。
const HTTP_POOL_MAX_IDLE_PER_HOST: usize = 4;
/// TCP keepalive interval (seconds). TCP 保活间隔(秒)。
const HTTP_TCP_KEEPALIVE_SECS: u64 = 60;
/// HTTP/2 keepalive interval (seconds). HTTP/2 保活间隔(秒)。
const HTTP2_KEEPALIVE_INTERVAL_SECS: u64 = 10;
/// HTTP/2 keepalive timeout (seconds). HTTP/2 保活超时(秒)。
const HTTP2_KEEPALIVE_TIMEOUT_SECS: u64 = 5;
/// Request timeout (milliseconds). 请求超时(毫秒)。
const HTTP_TIMEOUT_MS: u64 = 3000;
/// Connect timeout (milliseconds). 连接超时(毫秒)。
const HTTP_CONNECT_TIMEOUT_MS: u64 = 2000;
/// Shared HTTP client builder for SWQOS clients; call `.build().unwrap()` or override pool first. SWQOS 共用 HTTP 客户端构建器。
pub fn default_http_client_builder() -> reqwest::ClientBuilder {
Client::builder()
.pool_idle_timeout(Duration::from_secs(HTTP_POOL_IDLE_TIMEOUT_SECS))
.pool_max_idle_per_host(HTTP_POOL_MAX_IDLE_PER_HOST)
.tcp_keepalive(Some(Duration::from_secs(HTTP_TCP_KEEPALIVE_SECS)))
.tcp_nodelay(true)
.http2_keep_alive_interval(Duration::from_secs(HTTP2_KEEPALIVE_INTERVAL_SECS))
.http2_keep_alive_timeout(Duration::from_secs(HTTP2_KEEPALIVE_TIMEOUT_SECS))
.http2_adaptive_window(true)
.timeout(Duration::from_millis(HTTP_TIMEOUT_MS))
.connect_timeout(Duration::from_millis(HTTP_CONNECT_TIMEOUT_MS))
}
/// Trade/on-chain error with code and optional instruction index. 交易/链上错误,含错误码与可选指令下标。
#[derive(Debug, Clone)]
pub struct TradeError {
pub code: u32,
@@ -59,41 +89,64 @@ pub async fn poll_transaction_confirmation(
txt_sig: Signature,
wait_confirmation: bool,
) -> Result<Signature> {
// If no confirmation needed, return signature immediately
poll_any_transaction_confirmation(rpc, &[txt_sig], wait_confirmation).await
}
/// Poll multiple signatures in parallel (one RPC call per poll) and return the first one that confirms.
/// When transactions are submitted to multiple SWQOS channels, each channel produces a different
/// signature. Only one will land on-chain, so we must check all of them.
pub async fn poll_any_transaction_confirmation(
rpc: &SolanaRpcClient,
signatures: &[Signature],
wait_confirmation: bool,
) -> Result<Signature> {
if signatures.is_empty() {
return Err(anyhow::anyhow!("No signatures to confirm"));
}
// If no confirmation needed, return first signature immediately
if !wait_confirmation {
return Ok(txt_sig);
return Ok(signatures[0]);
}
let timeout: Duration = Duration::from_secs(15); // 15s to avoid timeout under network congestion
let timeout: Duration = Duration::from_secs(15);
let interval: Duration = Duration::from_millis(1000);
let start: Instant = Instant::now();
let mut poll_count = 0u32;
// Track which signature landed (confirmed or failed on-chain)
let mut landed_sig: Option<Signature> = None;
loop {
if start.elapsed() >= timeout {
return Err(anyhow::anyhow!("Transaction {}'s confirmation timed out", txt_sig));
return Err(anyhow::anyhow!("Transaction confirmation timed out after {}s ({} signatures polled)", timeout.as_secs(), signatures.len()));
}
poll_count += 1;
let status = rpc.get_signature_statuses(&[txt_sig]).await?;
let first = status.value.get(0).and_then(|o| o.as_ref());
match first {
Some(s) => {
let status = rpc.get_signature_statuses(signatures).await?;
// Check all signatures for any that confirmed successfully
for (i, maybe_status) in status.value.iter().enumerate() {
if let Some(s) = maybe_status {
if s.err.is_none()
&& (s.confirmation_status == Some(TransactionConfirmationStatus::Confirmed)
|| s.confirmation_status == Some(TransactionConfirmationStatus::Finalized))
{
return Ok(txt_sig);
return Ok(signatures[i]);
}
// Track the first signature that landed on-chain (even if errored)
if landed_sig.is_none() {
landed_sig = Some(signatures[i]);
}
}
None => {
sleep(interval).await;
continue;
}
}
let should_get_transaction = first.map(|s| s.err.is_some()).unwrap_or(false) || poll_count >= 10;
// If no signature has any status yet, keep waiting
if landed_sig.is_none() {
sleep(interval).await;
continue;
}
let landed = landed_sig.unwrap();
let should_get_transaction = poll_count >= 10;
if !should_get_transaction {
sleep(interval).await;
@@ -102,7 +155,7 @@ pub async fn poll_transaction_confirmation(
let tx_details = match rpc
.get_transaction_with_config(
&txt_sig,
&landed,
RpcTransactionConfig {
encoding: Some(UiTransactionEncoding::JsonParsed),
max_supported_transaction_version: Some(0),
@@ -125,7 +178,7 @@ pub async fn poll_transaction_confirmation(
} else {
let meta = meta.unwrap();
if meta.err.is_none() {
return Ok(txt_sig);
return Ok(landed);
} else {
// Extract error message from log_messages
let mut error_msg = String::new();
+2 -15
View File
@@ -1,10 +1,9 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
@@ -46,19 +45,7 @@ impl SwqosClientTrait for FlashBlockClient {
impl FlashBlockClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256) // Increased from 64 to 256
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
}
+220
View File
@@ -0,0 +1,220 @@
//! Helius Sender SWQOS client.
//!
//! Ultra-low latency transaction submission with dual routing to validators and Jito.
//! All transactions must include tips, priority fees, and skip preflight.
//! - Without swqos_only: minimum tip 0.0002 SOL.
//! - With swqos_only=true: minimum tip 0.000005 SOL (much lower, benefit of Helius).
//! API: POST {endpoint}/fast with JSON-RPC sendTransaction.
//! Optional query: api-key (custom TPS only), swqos_only (SWQOS-only routing, lower min tip).
use crate::swqos::common::{
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
};
use anyhow::Result;
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use solana_sdk::transaction::VersionedTransaction;
use solana_transaction_status::UiTransactionEncoding;
use std::sync::Arc;
use std::time::Instant;
use crate::common::SolanaRpcClient;
use crate::constants::swqos::{HELIUS_TIP_ACCOUNTS, SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY};
use crate::swqos::{SwqosClientTrait, SwqosType, TradeType};
#[derive(Clone)]
pub struct HeliusClient {
/// Cached full URL with query params (auth/swqos_only) to avoid per-request allocation.
pub submit_url: String,
pub rpc_client: Arc<SolanaRpcClient>,
pub http_client: Client,
/// When true, min_tip_sol() returns 0.000005; else 0.0002.
swqos_only: bool,
}
impl HeliusClient {
pub fn new(
rpc_url: String,
endpoint: String,
api_key: Option<String>,
swqos_only: bool,
) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = default_http_client_builder().build().unwrap();
let submit_url = Self::build_submit_url(&endpoint, api_key.as_deref(), swqos_only);
Self {
submit_url,
rpc_client: Arc::new(rpc_client),
http_client,
swqos_only,
}
}
/// Build URL once at construction; no per-request allocation.
#[inline]
fn build_submit_url(endpoint: &str, api_key: Option<&str>, swqos_only: bool) -> String {
let mut url = endpoint.to_string();
let mut has_query = endpoint.contains('?');
if let Some(key) = api_key {
if !key.is_empty() {
url.push_str(if has_query { "&" } else { "?" });
url.push_str("api-key=");
url.push_str(key);
has_query = true;
}
}
if swqos_only {
url.push_str(if has_query { "&" } else { "?" });
url.push_str("swqos_only=true");
}
url
}
pub async fn send_transaction(
&self,
trade_type: TradeType,
transaction: &VersionedTransaction,
wait_confirmation: bool,
) -> Result<()> {
let start_time = Instant::now();
let (content, signature) =
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
let request_body = serde_json::to_string(&json!({
"jsonrpc": "2.0",
"id": "1",
"method": "sendTransaction",
"params": [
content,
{
"encoding": "base64",
"skipPreflight": true,
"maxRetries": 0
}
]
}))?;
let response = self
.http_client
.post(&self.submit_url)
.body(request_body)
.header("Content-Type", "application/json")
.send()
.await?;
let status = response.status();
let response_text = response.text().await?;
if !status.is_success() {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(
" [helius] {} submission failed status={} body={}",
trade_type, status, response_text
);
}
return Err(anyhow::anyhow!(
"Helius Sender failed: status={} body={}",
status,
response_text
));
}
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("error").is_some() {
let err_msg = response_json["error"]
.get("message")
.and_then(|v| v.as_str())
.unwrap_or("unknown");
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [helius] {} submission error: {}", trade_type, err_msg);
}
return Err(anyhow::anyhow!("Helius Sender error: {}", err_msg));
}
if response_json.get("result").is_some() && crate::common::sdk_log::sdk_log_enabled() {
println!(
" [helius] {} submitted: {:?}",
trade_type,
start_time.elapsed()
);
}
} else if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(
" [helius] {} submission failed: {:?}",
trade_type, response_text
);
}
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(
" [helius] {} confirmation failed: {:?}",
trade_type,
start_time.elapsed()
);
}
return Err(e);
}
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(
" signature: {:?}",
signature
);
println!(
" [helius] {} confirmed: {:?}",
trade_type,
start_time.elapsed()
);
}
Ok(())
}
}
#[async_trait::async_trait]
impl SwqosClientTrait for HeliusClient {
async fn send_transaction(
&self,
trade_type: TradeType,
transaction: &VersionedTransaction,
wait_confirmation: bool,
) -> Result<()> {
HeliusClient::send_transaction(self, trade_type, transaction, wait_confirmation).await
}
async fn send_transactions(
&self,
trade_type: TradeType,
transactions: &Vec<VersionedTransaction>,
wait_confirmation: bool,
) -> Result<()> {
for transaction in transactions {
self.send_transaction(trade_type, transaction, wait_confirmation)
.await?;
}
Ok(())
}
fn get_tip_account(&self) -> Result<String> {
let tip_account = *HELIUS_TIP_ACCOUNTS
.choose(&mut rand::rng())
.or_else(|| HELIUS_TIP_ACCOUNTS.first())
.unwrap();
Ok(tip_account.to_string())
}
fn get_swqos_type(&self) -> SwqosType {
SwqosType::Helius
}
#[inline(always)]
fn min_tip_sol(&self) -> f64 {
if self.swqos_only {
SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY
} else {
SWQOS_MIN_TIP_HELIUS
}
}
}
+2 -15
View File
@@ -1,11 +1,10 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode, FormatBase64VersionedTransaction};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode, FormatBase64VersionedTransaction};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
@@ -49,19 +48,7 @@ impl SwqosClientTrait for JitoClient {
impl JitoClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256) // Increased from 64 to 256
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
}
+2 -15
View File
@@ -1,10 +1,9 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
@@ -47,19 +46,7 @@ impl LightspeedClient {
// Lightspeed endpoint should already include /lightspeed path
// Format: https://<tier>.rpc.solanavibestation.com/lightspeed?api_key=<key>
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256)
.tcp_keepalive(Some(Duration::from_secs(60)))
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000))
.connect_timeout(Duration::from_millis(2000))
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
}
+90 -12
View File
@@ -1,3 +1,4 @@
pub mod astralane_quic;
pub mod common;
pub mod serialization;
pub mod solana_rpc;
@@ -14,6 +15,7 @@ pub mod stellium;
pub mod lightspeed;
pub mod soyas;
pub mod speedlanding;
pub mod helius;
use std::sync::Arc;
@@ -37,7 +39,23 @@ use crate::{
SWQOS_ENDPOINTS_ASTRALANE,
SWQOS_ENDPOINTS_STELLIUM,
SWQOS_ENDPOINTS_SOYAS,
SWQOS_ENDPOINTS_SPEEDLANDING
SWQOS_ENDPOINTS_SPEEDLANDING,
SWQOS_ENDPOINTS_HELIUS,
SWQOS_MIN_TIP_DEFAULT,
SWQOS_MIN_TIP_JITO,
SWQOS_MIN_TIP_NEXTBLOCK,
SWQOS_MIN_TIP_ZERO_SLOT,
SWQOS_MIN_TIP_TEMPORAL,
SWQOS_MIN_TIP_BLOXROUTE,
SWQOS_MIN_TIP_NODE1,
SWQOS_MIN_TIP_FLASHBLOCK,
SWQOS_MIN_TIP_BLOCKRAZOR,
SWQOS_MIN_TIP_ASTRALANE,
SWQOS_MIN_TIP_STELLIUM,
SWQOS_MIN_TIP_LIGHTSPEED,
SWQOS_MIN_TIP_SOYAS,
SWQOS_MIN_TIP_SPEEDLANDING,
SWQOS_MIN_TIP_HELIUS,
},
swqos::{
bloxroute::BloxrouteClient,
@@ -54,10 +72,13 @@ use crate::{
lightspeed::LightspeedClient,
soyas::SoyasClient,
speedlanding::SpeedlandingClient,
helius::HeliusClient,
}
};
lazy_static::lazy_static! {
/// Reserved for future per-SWQOS tip account caching (currently unused).
#[allow(dead_code)]
static ref TIP_ACCOUNT_CACHE: RwLock<Vec<String>> = RwLock::new(Vec::new());
}
@@ -68,6 +89,14 @@ pub const SWQOS_BLACKLIST: &[SwqosType] = &[
SwqosType::NextBlock, // NextBlock is disabled by default
];
/// SWQOS 提交通道:HTTP 或 QUIC(低延迟)。部分提供商(如 Astralane)支持 QUIC。
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub enum SwqosTransport {
#[default]
Http,
Quic,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TradeType {
Create,
@@ -103,6 +132,7 @@ pub enum SwqosType {
Lightspeed,
Soyas,
Speedlanding,
Helius,
Default,
}
@@ -121,6 +151,8 @@ impl SwqosType {
Self::Stellium,
Self::Lightspeed,
Self::Soyas,
Self::Speedlanding,
Self::Helius,
Self::Default,
]
}
@@ -134,6 +166,27 @@ pub trait SwqosClientTrait {
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()>;
fn get_tip_account(&self) -> Result<String>;
fn get_swqos_type(&self) -> SwqosType;
/// Minimum tip in SOL required by this provider. Helius returns lower value when swqos_only is true.
#[inline]
fn min_tip_sol(&self) -> f64 {
match self.get_swqos_type() {
SwqosType::Jito => SWQOS_MIN_TIP_JITO,
SwqosType::NextBlock => SWQOS_MIN_TIP_NEXTBLOCK,
SwqosType::ZeroSlot => SWQOS_MIN_TIP_ZERO_SLOT,
SwqosType::Temporal => SWQOS_MIN_TIP_TEMPORAL,
SwqosType::Bloxroute => SWQOS_MIN_TIP_BLOXROUTE,
SwqosType::Node1 => SWQOS_MIN_TIP_NODE1,
SwqosType::FlashBlock => SWQOS_MIN_TIP_FLASHBLOCK,
SwqosType::BlockRazor => SWQOS_MIN_TIP_BLOCKRAZOR,
SwqosType::Astralane => SWQOS_MIN_TIP_ASTRALANE,
SwqosType::Stellium => SWQOS_MIN_TIP_STELLIUM,
SwqosType::Lightspeed => SWQOS_MIN_TIP_LIGHTSPEED,
SwqosType::Soyas => SWQOS_MIN_TIP_SOYAS,
SwqosType::Speedlanding => SWQOS_MIN_TIP_SPEEDLANDING,
SwqosType::Helius => SWQOS_MIN_TIP_HELIUS,
SwqosType::Default => SWQOS_MIN_TIP_DEFAULT,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -167,8 +220,8 @@ pub enum SwqosConfig {
FlashBlock(String, SwqosRegion, Option<String>),
/// BlockRazor(api_token, region, custom_url)
BlockRazor(String, SwqosRegion, Option<String>),
/// Astralane(api_token, region, custom_url)
Astralane(String, SwqosRegion, Option<String>),
/// Astralane(api_token, region, custom_url, transport). transport=None 表示 Http。
Astralane(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
/// Stellium(api_token, region, custom_url)
Stellium(String, SwqosRegion, Option<String>),
/// Lightspeed(api_key, region, custom_url) - Solana Vibe Station
@@ -180,6 +233,9 @@ pub enum SwqosConfig {
/// To apply for an API key, please contact -> https://t.me/speedlanding_bot?start=0xzero
/// Minimum tip: 0.001 SOL
Speedlanding(String, SwqosRegion, Option<String>),
/// Helius Sender: dual routing to validators and Jito. API key optional (custom TPS only).
/// (api_key, region, custom_url, swqos_only). swqos_only: None => false (min tip 0.0002 SOL); Some(true) => SWQOS-only (min tip 0.000005 SOL, much lower).
Helius(String, SwqosRegion, Option<String>, Option<bool>),
}
impl SwqosConfig {
@@ -194,11 +250,12 @@ impl SwqosConfig {
SwqosConfig::Node1(_, _, _) => SwqosType::Node1,
SwqosConfig::FlashBlock(_, _, _) => SwqosType::FlashBlock,
SwqosConfig::BlockRazor(_, _, _) => SwqosType::BlockRazor,
SwqosConfig::Astralane(_, _, _) => SwqosType::Astralane,
SwqosConfig::Astralane(_, _, _, _) => SwqosType::Astralane,
SwqosConfig::Stellium(_, _, _) => SwqosType::Stellium,
SwqosConfig::Lightspeed(_, _, _) => SwqosType::Lightspeed,
SwqosConfig::Soyas(_, _, _) => SwqosType::Soyas,
SwqosConfig::Speedlanding(_, _, _) => SwqosType::Speedlanding,
SwqosConfig::Helius(_, _, _, _) => SwqosType::Helius,
}
}
@@ -226,6 +283,7 @@ impl SwqosConfig {
SwqosType::Lightspeed => "".to_string(), // Lightspeed requires custom URL with api_key
SwqosType::Soyas => SWQOS_ENDPOINTS_SOYAS[region as usize].to_string(),
SwqosType::Speedlanding => SWQOS_ENDPOINTS_SPEEDLANDING[region as usize].to_string(),
SwqosType::Helius => SWQOS_ENDPOINTS_HELIUS[region as usize].to_string(),
SwqosType::Default => "".to_string(),
}
}
@@ -304,14 +362,22 @@ impl SwqosConfig {
);
Ok(Arc::new(blockrazor_client))
},
SwqosConfig::Astralane(auth_token, region, url) => {
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
let astralane_client = AstralaneClient::new(
rpc_url.clone(),
endpoint.to_string(),
auth_token
);
Ok(Arc::new(astralane_client))
SwqosConfig::Astralane(auth_token, region, url, transport) => {
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
if use_quic {
let quic_endpoint = crate::constants::swqos::ASTRALANE_QUIC_ENDPOINT;
let astralane_client =
AstralaneClient::new_quic(rpc_url.clone(), quic_endpoint, auth_token).await?;
Ok(Arc::new(astralane_client))
} else {
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
let astralane_client = AstralaneClient::new(
rpc_url.clone(),
endpoint.to_string(),
auth_token,
);
Ok(Arc::new(astralane_client))
}
},
SwqosConfig::Stellium(auth_token, region, url) => {
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
@@ -349,6 +415,18 @@ impl SwqosConfig {
).await?;
Ok(Arc::new(speedlanding_client))
},
SwqosConfig::Helius(api_key, region, url, swqos_only) => {
let swqos_only = swqos_only.unwrap_or(false);
let endpoint = SwqosConfig::get_endpoint(SwqosType::Helius, region, url.clone());
let api_key_opt = if api_key.is_empty() { None } else { Some(api_key.clone()) };
let helius_client = HeliusClient::new(
rpc_url.clone(),
endpoint,
api_key_opt,
swqos_only,
);
Ok(Arc::new(helius_client))
},
SwqosConfig::Default(endpoint) => {
let rpc = SolanaRpcClient::new_with_commitment(
endpoint,
+2 -15
View File
@@ -1,10 +1,9 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
@@ -51,19 +50,7 @@ impl NextBlockClient {
format!("{}/api/v2/submit", endpoint.trim_end_matches('/'))
};
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256) // Increased from 64 to 256
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
}
+21 -25
View File
@@ -1,4 +1,4 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
@@ -50,19 +50,7 @@ impl SwqosClientTrait for Node1Client {
impl Node1Client {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(300))
.pool_max_idle_per_host(4)
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
let client = Self {
rpc_client: Arc::new(rpc_client),
@@ -92,7 +80,9 @@ impl Node1Client {
let handle = tokio::spawn(async move {
// Immediate first ping to warm connection and reduce first-submit cold start latency
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("Node1 ping request failed: {}", e);
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("Node1 ping request failed: {}", e);
}
}
let mut interval = tokio::time::interval(Duration::from_secs(30));
loop {
@@ -101,7 +91,9 @@ impl Node1Client {
break;
}
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
eprintln!("Node1 ping request failed: {}", e);
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("Node1 ping request failed: {}", e);
}
}
}
});
@@ -132,7 +124,7 @@ impl Node1Client {
.await?;
let status = response.status();
let _ = response.bytes().await;
if !status.is_success() {
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
eprintln!("Node1 ping request returned non-success status: {}", status);
}
Ok(())
@@ -164,12 +156,14 @@ impl Node1Client {
// Parse JSON response
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" [node1] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [node1] {} submission failed: {:?}", trade_type, _error);
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
println!(" [node1] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [node1] {} submission failed: {:?}", trade_type, _error);
}
}
} else {
} else if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [node1] {} submission failed: {:?}", trade_type, response_text);
}
@@ -177,12 +171,14 @@ impl Node1Client {
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [node1] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [node1] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
}
return Err(e);
},
}
if wait_confirmation {
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [node1] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
+182 -40
View File
@@ -1,18 +1,24 @@
//! Transaction serialization module.
use crate::perf::{
compiler_optimization::CompileTimeOptimizedEventProcessor, simd::SIMDSerializer,
};
use anyhow::Result;
use base64::Engine;
use base64::engine::general_purpose::STANDARD;
use base64::Engine;
use crossbeam_queue::ArrayQueue;
use once_cell::sync::Lazy;
use solana_client::rpc_client::SerializableTransaction;
use solana_sdk::signature::Signature;
use solana_transaction_status::UiTransactionEncoding;
use std::sync::Arc;
use crossbeam_queue::ArrayQueue;
use crate::perf::{
simd::SIMDSerializer,
compiler_optimization::CompileTimeOptimizedEventProcessor,
};
/// Max number of reusable buffers kept in the queue.
const SERIALIZER_POOL_SIZE: usize = 10_000;
/// Per-buffer reserved capacity (bytes).
const SERIALIZER_BUFFER_SIZE: usize = 256 * 1024;
/// Cold-start prewarm count. Keep small to avoid first-submit spikes.
const SERIALIZER_PREWARM_BUFFERS: usize = 64;
/// Zero-allocation serializer using a buffer pool to avoid runtime allocation.
pub struct ZeroAllocSerializer {
@@ -22,28 +28,30 @@ pub struct ZeroAllocSerializer {
impl ZeroAllocSerializer {
pub fn new(pool_size: usize, buffer_size: usize) -> Self {
let pool = ArrayQueue::new(pool_size);
// Pre-allocate buffers
for _ in 0..pool_size {
let mut buffer = Vec::with_capacity(buffer_size);
buffer.resize(buffer_size, 0);
let _ = pool.push(buffer);
}
Self {
buffer_pool: Arc::new(pool),
buffer_size,
}
Self::new_with_prewarm(pool_size, buffer_size, SERIALIZER_PREWARM_BUFFERS)
}
pub fn serialize_zero_alloc<T: serde::Serialize>(&self, data: &T, _label: &str) -> Result<Vec<u8>> {
fn new_with_prewarm(pool_size: usize, buffer_size: usize, prewarm_buffers: usize) -> Self {
let pool = ArrayQueue::new(pool_size);
let prewarm_count = prewarm_buffers.min(pool_size);
// Prewarm only a small hot set to avoid large cold-start blocking.
// Remaining buffers are allocated lazily and returned to this pool.
for _ in 0..prewarm_count {
let _ = pool.push(Vec::with_capacity(buffer_size));
}
Self { buffer_pool: Arc::new(pool), buffer_size }
}
pub fn serialize_zero_alloc<T: serde::Serialize>(
&self,
data: &T,
_label: &str,
) -> Result<Vec<u8>> {
// Try to get a buffer from the pool
let mut buffer = self.buffer_pool.pop().unwrap_or_else(|| {
let mut buf = Vec::with_capacity(self.buffer_size);
buf.resize(self.buffer_size, 0);
buf
});
let mut buffer =
self.buffer_pool.pop().unwrap_or_else(|| Vec::with_capacity(self.buffer_size));
// Serialize into buffer
let serialized = bincode::serialize(data)?;
@@ -67,12 +75,8 @@ impl ZeroAllocSerializer {
}
/// Global serializer instance.
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> = Lazy::new(|| {
Arc::new(ZeroAllocSerializer::new(
10_000, // Pool size
256 * 1024, // Buffer size: 256KB
))
});
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> =
Lazy::new(|| Arc::new(ZeroAllocSerializer::new(SERIALIZER_POOL_SIZE, SERIALIZER_BUFFER_SIZE)));
/// Compile-time optimized event processor (zero runtime cost).
static COMPILE_TIME_PROCESSOR: CompileTimeOptimizedEventProcessor =
@@ -101,11 +105,47 @@ impl Base64Encoder {
event_type: &str,
) -> Result<String> {
let serialized = SERIALIZER.serialize_zero_alloc(value, event_type)?;
Ok(STANDARD.encode(&serialized))
let encoded = STANDARD.encode(&serialized);
SERIALIZER.return_buffer(serialized);
Ok(encoded)
}
}
/// Guard that returns the serialization buffer to the pool on drop.
pub struct PooledTxBufGuard(pub Vec<u8>);
impl std::ops::Deref for PooledTxBufGuard {
type Target = [u8];
fn deref(&self) -> &[u8] {
&self.0
}
}
impl Drop for PooledTxBufGuard {
fn drop(&mut self) {
if !self.0.is_empty() {
SERIALIZER.return_buffer(std::mem::take(&mut self.0));
}
}
}
/// Serialize transaction to bincode bytes using buffer pool. The returned guard returns the buffer
/// to the pool when dropped; use `&*guard` or `guard.as_ref()` for `&[u8]`.
pub fn serialize_transaction_bincode_sync(
transaction: &impl SerializableTransaction,
) -> Result<(PooledTxBufGuard, Signature)> {
let signature = transaction.get_signature();
let serialized_tx = SERIALIZER.serialize_zero_alloc(transaction, "transaction")?;
Ok((PooledTxBufGuard(serialized_tx), *signature))
}
/// Return a buffer to the pool (for manual use when not using `PooledTxBufGuard`).
pub fn return_serialization_buffer(buffer: Vec<u8>) {
SERIALIZER.return_buffer(buffer);
}
/// Sync serialize + encode using buffer pool; use in hot path to reduce allocs.
/// Base64 path uses SIMD-accelerated encoding.
pub fn serialize_transaction_sync(
transaction: &impl SerializableTransaction,
encoding: UiTransactionEncoding,
@@ -114,7 +154,7 @@ pub fn serialize_transaction_sync(
let serialized_tx = SERIALIZER.serialize_zero_alloc(transaction, "transaction")?;
let serialized = match encoding {
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
UiTransactionEncoding::Base64 => STANDARD.encode(&serialized_tx),
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
};
SERIALIZER.return_buffer(serialized_tx);
@@ -133,10 +173,7 @@ pub async fn serialize_transaction(
let serialized = match encoding {
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
UiTransactionEncoding::Base64 => {
// Use SIMD-optimized Base64 encoding
STANDARD.encode(&serialized_tx)
}
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
};
@@ -156,7 +193,7 @@ pub fn serialize_transactions_batch_sync(
let serialized_tx = SERIALIZER.serialize_zero_alloc(tx, "transaction")?;
let encoded = match encoding {
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
UiTransactionEncoding::Base64 => STANDARD.encode(&serialized_tx),
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
};
SERIALIZER.return_buffer(serialized_tx);
@@ -177,7 +214,7 @@ pub async fn serialize_transactions_batch(
let encoded = match encoding {
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
UiTransactionEncoding::Base64 => STANDARD.encode(&serialized_tx),
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
};
@@ -196,6 +233,7 @@ pub fn get_serializer_stats() -> (usize, usize) {
#[cfg(test)]
mod tests {
use super::*;
use std::time::Instant;
#[test]
fn test_base64_encode() {
@@ -212,6 +250,110 @@ mod tests {
fn test_serializer_stats() {
let (available, capacity) = get_serializer_stats();
assert!(available <= capacity);
assert_eq!(capacity, 10_000);
assert_eq!(capacity, SERIALIZER_POOL_SIZE);
}
#[test]
fn test_serializer_prewarm_is_bounded() {
let serializer = ZeroAllocSerializer::new_with_prewarm(128, 1024, 8);
let (available, capacity) = serializer.get_pool_stats();
assert_eq!(capacity, 128);
assert_eq!(available, 8);
}
#[test]
fn test_serializer_lazy_alloc_and_return() {
let serializer = ZeroAllocSerializer::new_with_prewarm(8, 1024, 0);
let (available_before, capacity) = serializer.get_pool_stats();
assert_eq!(capacity, 8);
assert_eq!(available_before, 0);
let buf = serializer.serialize_zero_alloc(&"hello", "test").unwrap();
assert!(buf.capacity() >= 1024);
serializer.return_buffer(buf);
let (available_after, _) = serializer.get_pool_stats();
assert_eq!(available_after, 1);
}
fn legacy_eager_zero_fill_serializer(
pool_size: usize,
buffer_size: usize,
) -> ZeroAllocSerializer {
let pool = ArrayQueue::new(pool_size);
for _ in 0..pool_size {
let mut buffer = Vec::with_capacity(buffer_size);
buffer.resize(buffer_size, 0);
let _ = pool.push(buffer);
}
ZeroAllocSerializer { buffer_pool: Arc::new(pool), buffer_size }
}
/// Manual perf test: compares old eager cold-start behavior to current bounded prewarm.
/// Run with:
/// cargo test --release perf_serializer_cold_start_vs_legacy_eager -- --ignored --nocapture
#[test]
#[ignore = "manual perf benchmark"]
fn perf_serializer_cold_start_vs_legacy_eager() {
const POOL_SIZE: usize = 4096;
const BUFFER_SIZE: usize = 32 * 1024;
const PREWARM: usize = 64;
let payload = vec![7u8; 4096];
let legacy_init_start = Instant::now();
let legacy = legacy_eager_zero_fill_serializer(POOL_SIZE, BUFFER_SIZE);
let legacy_init = legacy_init_start.elapsed();
let current_init_start = Instant::now();
let current = ZeroAllocSerializer::new_with_prewarm(POOL_SIZE, BUFFER_SIZE, PREWARM);
let current_init = current_init_start.elapsed();
let legacy_first_start = Instant::now();
let legacy_buf = legacy.serialize_zero_alloc(&payload, "perf").unwrap();
let legacy_first = legacy_first_start.elapsed();
legacy.return_buffer(legacy_buf);
let current_first_start = Instant::now();
let current_buf = current.serialize_zero_alloc(&payload, "perf").unwrap();
let current_first = current_first_start.elapsed();
current.return_buffer(current_buf);
println!(
"[perf] serializer cold-start compare\n pool_size={POOL_SIZE} buffer_size={BUFFER_SIZE} prewarm={PREWARM}\n legacy_init={legacy_init:?} current_init={current_init:?}\n legacy_first_serialize={legacy_first:?} current_first_serialize={current_first:?}"
);
assert!(
current_init <= legacy_init,
"expected bounded prewarm init ({current_init:?}) to be <= legacy eager init ({legacy_init:?})"
);
}
/// Manual perf test: demonstrates lazy allocation amortization.
/// Run with:
/// cargo test --release perf_serializer_lazy_growth_amortization -- --ignored --nocapture
#[test]
#[ignore = "manual perf benchmark"]
fn perf_serializer_lazy_growth_amortization() {
const POOL_SIZE: usize = 128;
const BUFFER_SIZE: usize = 256 * 1024;
let serializer = ZeroAllocSerializer::new_with_prewarm(POOL_SIZE, BUFFER_SIZE, 0);
let payload = vec![1u8; 8 * 1024];
let first_start = Instant::now();
let first_buf = serializer.serialize_zero_alloc(&payload, "perf").unwrap();
let first = first_start.elapsed();
serializer.return_buffer(first_buf);
let second_start = Instant::now();
let second_buf = serializer.serialize_zero_alloc(&payload, "perf").unwrap();
let second = second_start.elapsed();
serializer.return_buffer(second_buf);
let (available, capacity) = serializer.get_pool_stats();
println!(
"[perf] serializer lazy growth\n pool_size={POOL_SIZE} buffer_size={BUFFER_SIZE}\n first_serialize={first:?} second_serialize={second:?}\n available={available} capacity={capacity}"
);
assert!(available >= 1);
assert_eq!(capacity, POOL_SIZE);
}
}
+16 -11
View File
@@ -6,7 +6,6 @@ use quinn::{
TransportConfig,
};
use rand::seq::IndexedRandom as _;
use solana_rpc_client::rpc_client::SerializableTransaction;
use solana_sdk::{signature::Keypair, transaction::VersionedTransaction};
use solana_tls_utils::{new_dummy_x509_certificate, SkipServerVerification};
use std::time::Instant;
@@ -19,6 +18,7 @@ use tokio::sync::Mutex;
use crate::common::SolanaRpcClient;
use crate::swqos::common::poll_transaction_confirmation;
use crate::swqos::serialization::serialize_transaction_bincode_sync;
use crate::swqos::SwqosClientTrait;
use crate::{
constants::swqos::SPEEDLANDING_TIP_ACCOUNTS,
@@ -105,27 +105,32 @@ impl SwqosClientTrait for SpeedlandingClient {
wait_confirmation: bool,
) -> Result<()> {
let start_time = Instant::now();
let signature = transaction.get_signature();
let serialized_tx = bincode::serialize(transaction)?;
let (buf_guard, signature) = serialize_transaction_bincode_sync(transaction)?;
let connection = self.connection.load_full();
if Self::try_send_bytes(&connection, &serialized_tx).await.is_err() {
eprintln!(" [speedlanding] {} submission failed, reconnecting", trade_type);
if Self::try_send_bytes(&connection, &*buf_guard).await.is_err() {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [speedlanding] {} submission failed, reconnecting", trade_type);
}
self.reconnect().await?;
let connection = self.connection.load_full();
if let Err(e) = Self::try_send_bytes(&connection, &serialized_tx).await {
eprintln!(" [speedlanding] {} submission failed: {:?}", trade_type, e);
if let Err(e) = Self::try_send_bytes(&connection, &*buf_guard).await {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [speedlanding] {} submission failed: {:?}", trade_type, e);
}
return Err(e.into());
}
}
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [speedlanding] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [speedlanding] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
}
return Err(e);
}
}
if wait_confirmation {
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [speedlanding] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
+19 -25
View File
@@ -1,4 +1,4 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
@@ -48,19 +48,7 @@ impl SwqosClientTrait for StelliumClient {
impl StelliumClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(300))
.pool_max_idle_per_host(4)
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
let keep_alive_running = Arc::new(AtomicBool::new(true));
@@ -94,7 +82,7 @@ impl StelliumClient {
if let Ok(resp) = http_client.get(&url).timeout(Duration::from_millis(1500)).send().await {
let status = resp.status();
let _ = resp.bytes().await;
if !status.is_success() {
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [Stellium] Ping failed with status: {}", status);
}
}
@@ -109,12 +97,14 @@ impl StelliumClient {
Ok(response) => {
let status = response.status();
let _ = response.bytes().await;
if !status.is_success() {
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [Stellium] Ping failed with status: {}", status);
}
}
Err(e) => {
eprintln!(" [Stellium] Ping request error: {:?}", e);
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [Stellium] Ping request error: {:?}", e);
}
}
}
}
@@ -152,12 +142,14 @@ impl StelliumClient {
// Parse response
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
println!(" [Stellium] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [Stellium] {} submission failed: {:?}", trade_type, _error);
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
println!(" [Stellium] {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [Stellium] {} submission failed: {:?}", trade_type, _error);
}
}
} else {
} else if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(" [Stellium] {} submission failed: {:?}", trade_type, response_text);
}
@@ -165,12 +157,14 @@ impl StelliumClient {
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [Stellium] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [Stellium] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
}
return Err(e);
},
}
if wait_confirmation {
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [Stellium] {} confirmed: {:?}", trade_type, start_time.elapsed());
}
+2 -14
View File
@@ -1,5 +1,5 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
@@ -76,19 +76,7 @@ impl SwqosClientTrait for TemporalClient {
impl TemporalClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(300))
.pool_max_idle_per_host(4)
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
let client = Self {
rpc_client: Arc::new(rpc_client),
+2 -15
View File
@@ -1,10 +1,9 @@
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
use rand::seq::IndexedRandom;
use reqwest::Client;
use serde_json::json;
use std::{sync::Arc, time::Instant};
use std::time::Duration;
use solana_transaction_status::UiTransactionEncoding;
use anyhow::Result;
@@ -46,19 +45,7 @@ impl SwqosClientTrait for ZeroSlotClient {
impl ZeroSlotClient {
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = Client::builder()
// Optimized connection pool settings for high performance
.pool_idle_timeout(Duration::from_secs(120))
.pool_max_idle_per_host(256) // Increased from 64 to 256
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
.http2_keep_alive_interval(Duration::from_secs(10))
.http2_keep_alive_timeout(Duration::from_secs(5))
.http2_adaptive_window(true) // Enable adaptive flow control
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
.build()
.unwrap();
let http_client = default_http_client_builder().build().unwrap();
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
}
+32 -22
View File
@@ -3,6 +3,7 @@ use once_cell::sync::Lazy;
use smallvec::SmallVec;
use solana_sdk::instruction::Instruction;
use solana_compute_budget_interface::ComputeBudgetInstruction;
use std::sync::Arc;
/// Cache key containing all parameters for compute budget instructions
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
@@ -11,43 +12,52 @@ struct ComputeBudgetCacheKey {
unit_limit: u32,
}
/// Global cache storing compute budget instructions
/// Uses DashMap for high-performance lock-free concurrent access
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 2]>>> =
/// Global cache storing compute budget instructions (Arc to avoid clone on hit).
/// Uses DashMap for high-performance lock-free concurrent access.
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, Arc<SmallVec<[Instruction; 2]>>>> =
Lazy::new(|| DashMap::new());
/// Extend `instructions` with compute budget instructions; on cache hit extends from cached Arc (no SmallVec clone).
#[inline(always)]
pub fn compute_budget_instructions(
pub fn extend_compute_budget_instructions(
instructions: &mut Vec<Instruction>,
unit_price: u64,
unit_limit: u32,
) -> SmallVec<[Instruction; 2]> {
// Create cache key
let cache_key = ComputeBudgetCacheKey {
unit_price: unit_price,
unit_limit: unit_limit,
};
) {
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
// Try to get from cache first
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
return cached_insts.clone();
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
instructions.extend(cached.iter().cloned());
return;
}
// Cache miss, generate new instructions
let mut insts = SmallVec::<[Instruction; 2]>::new();
// Only add compute unit price instruction if > 0
if unit_price > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
}
// Only add compute unit limit instruction if > 0
if unit_limit > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
}
let arc = Arc::new(insts);
instructions.extend(arc.iter().cloned());
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
}
// Store result in cache
let insts_clone = insts.clone();
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
/// Returns compute budget instructions (allocates on cache hit; prefer `extend_compute_budget_instructions` on hot path).
#[inline(always)]
pub fn compute_budget_instructions(unit_price: u64, unit_limit: u32) -> SmallVec<[Instruction; 2]> {
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
return (**cached).clone();
}
let mut insts = SmallVec::<[Instruction; 2]>::new();
if unit_price > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
}
if unit_limit > 0 {
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
}
let arc = Arc::new(insts.clone());
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
insts
}
+14 -11
View File
@@ -12,9 +12,7 @@ use crate::common::nonce_cache::DurableNonceInfo;
pub fn add_nonce_instruction(
instructions: &mut Vec<Instruction>,
payer: &Keypair,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
durable_nonce: Option<DurableNonceInfo>,
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<(), anyhow::Error> {
if let Some(durable_nonce) = durable_nonce {
let nonce_advance_ix = advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
@@ -24,17 +22,22 @@ pub fn add_nonce_instruction(
Ok(())
}
/// Get blockhash for transaction
/// If nonce account is used, return blockhash from nonce, otherwise return the provided recent_blockhash
/// Get blockhash for transaction.
/// If nonce account is used, returns blockhash from nonce; otherwise returns the provided recent_blockhash.
/// Returns error when neither durable_nonce nor recent_blockhash is set (caller must provide one for low latency).
pub fn get_transaction_blockhash(
recent_blockhash: Option<Hash>,
durable_nonce: Option<DurableNonceInfo>,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
) -> Hash {
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<Hash, anyhow::Error> {
if let Some(durable_nonce) = durable_nonce {
durable_nonce.current_nonce.unwrap()
durable_nonce
.current_nonce
.ok_or_else(|| anyhow::anyhow!("durable_nonce.current_nonce is None"))
} else if let Some(hash) = recent_blockhash {
Ok(hash)
} else {
recent_blockhash.unwrap()
Err(anyhow::anyhow!(
"Must provide either recent_blockhash or durable_nonce for transaction"
))
}
}
+34 -42
View File
@@ -1,69 +1,66 @@
use solana_hash::Hash;
use solana_sdk::{
instruction::Instruction, message::AddressLookupTableAccount, native_token::sol_str_to_lamports, pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::VersionedTransaction
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
signature::Keypair, signer::Signer, transaction::VersionedTransaction,
};
use solana_system_interface::instruction::transfer;
use std::sync::Arc;
use super::{
compute_budget_manager::compute_budget_instructions,
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
};
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
use crate::{
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
trading::{MiddlewareManager, core::transaction_pool::{acquire_builder, release_builder}},
};
/// Build standard RPC transaction
/// Convert SOL amount (f64) to lamports without string allocation (hot path).
#[inline(always)]
fn sol_f64_to_lamports(sol: f64) -> u64 {
if sol <= 0.0 {
return 0;
}
let lamports = sol * 1_000_000_000.0;
(lamports.min(u64::MAX as f64)).round() as u64
}
/// Build standard RPC transaction.
/// Takes Arc/context by reference to avoid clone in worker hot path (Arc::clone is cheap but ref is zero-cost).
pub async fn build_transaction(
payer: Arc<Keypair>,
_rpc: Option<Arc<SolanaRpcClient>>,
payer: &Arc<Keypair>,
_rpc: Option<&Arc<SolanaRpcClient>>,
unit_limit: u32,
unit_price: u64,
business_instructions: Vec<Instruction>,
address_lookup_table_account: Option<AddressLookupTableAccount>,
business_instructions: &[Instruction],
address_lookup_table_account: Option<&AddressLookupTableAccount>,
recent_blockhash: Option<Hash>,
middleware_manager: Option<Arc<MiddlewareManager>>,
middleware_manager: Option<&Arc<MiddlewareManager>>,
protocol_name: &str,
is_buy: bool,
with_tip: bool,
tip_account: &Pubkey,
tip_amount: f64,
durable_nonce: Option<DurableNonceInfo>,
// nonce_account: Option<Pubkey>,
// current_nonce: Option<Hash>,
durable_nonce: Option<&DurableNonceInfo>,
) -> Result<VersionedTransaction, anyhow::Error> {
let mut instructions = Vec::with_capacity(business_instructions.len() + 5);
// Add nonce instruction
if let Err(e) =
add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce.clone())
{
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce) {
return Err(e);
}
// Add tip transfer instruction
if with_tip && tip_amount > 0.0 {
instructions.push(transfer(
&payer.pubkey(),
tip_account,
sol_str_to_lamports(tip_amount.to_string().as_str()).unwrap_or(0),
));
let tip_lamports = sol_f64_to_lamports(tip_amount);
instructions.push(transfer(&payer.pubkey(), tip_account, tip_lamports));
}
// Add compute budget instructions
instructions.extend(compute_budget_instructions(
super::compute_budget_manager::extend_compute_budget_instructions(
&mut instructions,
unit_price,
unit_limit,
));
);
// Add business instructions
instructions.extend(business_instructions);
instructions.extend_from_slice(business_instructions);
// Get blockhash for transaction
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce.clone());
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce)?;
// Build transaction
build_versioned_transaction(
payer,
instructions,
@@ -76,23 +73,18 @@ pub async fn build_transaction(
.await
}
/// Low-level function for building versioned transactions
async fn build_versioned_transaction(
payer: Arc<Keypair>,
payer: &Arc<Keypair>,
instructions: Vec<Instruction>,
address_lookup_table_account: Option<AddressLookupTableAccount>,
address_lookup_table_account: Option<&AddressLookupTableAccount>,
blockhash: Hash,
middleware_manager: Option<Arc<MiddlewareManager>>,
middleware_manager: Option<&Arc<MiddlewareManager>>,
protocol_name: &str,
is_buy: bool,
) -> Result<VersionedTransaction, anyhow::Error> {
let full_instructions = match middleware_manager {
Some(middleware_manager) => middleware_manager
.apply_middlewares_process_full_instructions(
instructions,
protocol_name.to_string(),
is_buy,
)?,
.apply_middlewares_process_full_instructions(instructions, protocol_name, is_buy)?,
None => instructions,
};
@@ -107,7 +99,7 @@ async fn build_versioned_transaction(
);
let msg_bytes = versioned_msg.serialize();
let signature = payer.try_sign_message(&msg_bytes).expect("sign failed");
let signature = payer.as_ref().try_sign_message(&msg_bytes).expect("sign failed");
let tx = VersionedTransaction { signatures: vec![signature], message: versioned_msg };
// 归还构建器到池
+26 -2
View File
@@ -2,7 +2,11 @@ use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer, transaction
use solana_system_interface::instruction::transfer;
use crate::common::{
fast_fn::get_associated_token_address_with_program_id_fast, spl_token::close_account,
fast_fn::{
get_associated_token_address_with_program_id_fast,
get_associated_token_address_with_program_id_fast_use_seed,
},
spl_token::close_account,
SolanaRpcClient,
};
use anyhow::anyhow;
@@ -36,10 +40,30 @@ pub async fn get_token_balance(
payer: &Pubkey,
mint: &Pubkey,
) -> Result<u64, anyhow::Error> {
let ata = crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
get_token_balance_with_options(
rpc,
payer,
mint,
&crate::constants::TOKEN_PROGRAM,
false,
)
.await
}
/// 使用与交易指令一致的 ATA 推导(可选 seed)查询余额;卖出/余额查询应与买入使用同一 ATA 地址。
#[inline]
pub async fn get_token_balance_with_options(
rpc: &SolanaRpcClient,
payer: &Pubkey,
mint: &Pubkey,
token_program: &Pubkey,
use_seed: bool,
) -> Result<u64, anyhow::Error> {
let ata = get_associated_token_address_with_program_id_fast_use_seed(
payer,
mint,
token_program,
use_seed,
);
let balance = rpc.get_token_account_balance(&ata).await?;
let balance_u64 =
+259 -166
View File
@@ -1,46 +1,169 @@
//! 并行执行器
//! Parallel executor for multi-SWQOS submit.
//!
//! - **Pool**: Pre-spawned workers; hot path only enqueues jobs (no per-call tokio::spawn).
//! - **Arc**: Shared data is behind `Arc` so "clone" is just a refcount increment (no data copy).
//! - **Refs**: `build_transaction` takes `&Arc<..>`, `Option<&DurableNonceInfo>`, `Option<&AddressLookupTableAccount>` so the worker passes refs only (zero clone on worker path).
use anyhow::{anyhow, Result};
use crossbeam_queue::ArrayQueue;
use once_cell::sync::OnceCell;
use solana_hash::Hash;
use solana_sdk::message::AddressLookupTableAccount;
use solana_sdk::{
instruction::Instruction, pubkey::Pubkey, signature::Keypair, signature::Signature,
};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::{str::FromStr, sync::Arc, time::Instant};
use fnv::FnvHasher;
type FnvHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FnvHasher>>;
use crate::{
common::nonce_cache::DurableNonceInfo,
common::{GasFeeStrategy, SolanaRpcClient},
swqos::{SwqosClient, SwqosType, TradeType},
trading::{common::build_transaction, MiddlewareManager},
constants::swqos::{
SWQOS_MIN_TIP_DEFAULT,
SWQOS_MIN_TIP_JITO,
SWQOS_MIN_TIP_NEXTBLOCK,
SWQOS_MIN_TIP_ZERO_SLOT,
SWQOS_MIN_TIP_TEMPORAL,
SWQOS_MIN_TIP_BLOXROUTE,
SWQOS_MIN_TIP_NODE1,
SWQOS_MIN_TIP_FLASHBLOCK,
SWQOS_MIN_TIP_BLOCKRAZOR,
SWQOS_MIN_TIP_ASTRALANE,
SWQOS_MIN_TIP_STELLIUM,
SWQOS_MIN_TIP_LIGHTSPEED,
SWQOS_MIN_TIP_SOYAS,
SWQOS_MIN_TIP_SPEEDLANDING
},
};
const SWQOS_POOL_WORKERS: usize = 32;
const SWQOS_QUEUE_CAP: usize = 128;
/// Shared across all jobs in one batch; built once, cloned as single Arc per job (minimal hot-path clone).
struct SwqosSharedContext {
payer: Arc<Keypair>,
instructions: Arc<Vec<Instruction>>,
rpc: Option<Arc<SolanaRpcClient>>,
address_lookup_table_account: Option<AddressLookupTableAccount>,
recent_blockhash: Option<Hash>,
durable_nonce: Option<DurableNonceInfo>,
middleware_manager: Option<Arc<MiddlewareManager>>,
protocol_name: &'static str,
is_buy: bool,
wait_transaction_confirmed: bool,
with_tip: bool,
collector: Arc<ResultCollector>,
}
/// One SWQOS submit task; only per-task data + one Arc to shared (reduces hot-path clones).
struct SwqosJob {
shared: Arc<SwqosSharedContext>,
tip: f64,
unit_limit: u32,
unit_price: u64,
tip_account: Arc<Pubkey>,
swqos_client: Arc<SwqosClient>,
swqos_type: SwqosType,
core_id: Option<core_affinity::CoreId>,
use_affinity: bool,
}
async fn run_one_swqos_job(job: SwqosJob) {
let s = &job.shared;
if job.use_affinity {
if let Some(cid) = job.core_id {
core_affinity::set_for_current(cid);
}
}
let tip_amount = if s.with_tip { job.tip } else { 0.0 };
let transaction = match build_transaction(
&s.payer,
s.rpc.as_ref(),
job.unit_limit,
job.unit_price,
s.instructions.as_ref(),
s.address_lookup_table_account.as_ref(),
s.recent_blockhash,
s.middleware_manager.as_ref(),
s.protocol_name,
s.is_buy,
job.swqos_type != SwqosType::Default,
&job.tip_account,
tip_amount,
s.durable_nonce.as_ref(),
)
.await
{
Ok(tx) => tx,
Err(e) => {
s.collector.submit(TaskResult {
success: false,
signature: Signature::default(),
error: Some(e),
swqos_type: job.swqos_type,
landed_on_chain: false,
submit_done_us: crate::common::clock::now_micros(),
});
return;
}
};
let (success, err, landed_on_chain) = match job
.swqos_client
.send_transaction(
if s.is_buy {
TradeType::Buy
} else {
TradeType::Sell
},
&transaction,
s.wait_transaction_confirmed,
)
.await
{
Ok(()) => (true, None, true),
Err(e) => {
let landed = is_landed_error(&e);
(false, Some(e), landed)
}
};
let sig = transaction.signatures.first().copied().unwrap_or_default();
s.collector.submit(TaskResult {
success,
signature: sig,
error: err,
swqos_type: job.swqos_type,
landed_on_chain,
submit_done_us: crate::common::clock::now_micros(),
});
}
async fn swqos_worker_loop(queue: Arc<ArrayQueue<SwqosJob>>) {
loop {
if let Some(job) = queue.pop() {
run_one_swqos_job(job).await;
} else {
tokio::task::yield_now().await;
}
}
}
static SWQOS_QUEUE: OnceCell<Arc<ArrayQueue<SwqosJob>>> = OnceCell::new();
static SWQOS_WORKERS_STARTED: AtomicBool = AtomicBool::new(false);
fn ensure_swqos_pool(queue: Arc<ArrayQueue<SwqosJob>>) {
if SWQOS_WORKERS_STARTED.swap(true, Ordering::AcqRel) {
return;
}
for _ in 0..SWQOS_POOL_WORKERS {
tokio::spawn(swqos_worker_loop(queue.clone()));
}
}
#[repr(align(64))]
struct TaskResult {
success: bool,
signature: Signature,
error: Option<anyhow::Error>,
#[allow(dead_code)]
swqos_type: SwqosType, // 🔧 增加:记录SWQOS类型
landed_on_chain: bool, // 🔧 Whether tx landed on-chain (even if failed)
swqos_type: SwqosType,
landed_on_chain: bool,
/// Microsecond timestamp when this task finished (SWQOS returned); for per-SWQOS event→submit timing.
submit_done_us: i64,
}
/// Check if an error indicates the transaction landed on-chain (vs network/timeout error)
@@ -87,14 +210,14 @@ impl ResultCollector {
}
fn submit(&self, result: TaskResult) {
// 🚀 优化:ArrayQueue 内部已保证同步,无需额外 fence
// ArrayQueue is already synchronized; no extra fence needed
let is_success = result.success;
let is_landed_failed = result.landed_on_chain && !result.success;
let _ = self.results.push(result);
if is_success {
self.success_flag.store(true, Ordering::Release); // Release 确保 push 可见
self.success_flag.store(true, Ordering::Release);
} else if is_landed_failed {
// 🔧 Tx landed but failed (e.g., ExceededSlippage) - nonce is consumed, no point waiting
self.landed_failed_flag.store(true, Ordering::Release);
@@ -103,52 +226,56 @@ impl ResultCollector {
self.completed_count.fetch_add(1, Ordering::Release);
}
async fn wait_for_success(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>)> {
async fn wait_for_success(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
let start = Instant::now();
let timeout = std::time::Duration::from_secs(30);
let timeout = std::time::Duration::from_secs(5);
let poll_interval = std::time::Duration::from_millis(1000);
loop {
// 🚀 Acquire 确保看到 push 的内容
if self.success_flag.load(Ordering::Acquire) {
// 🔧 修复:收集所有签名
let mut signatures = Vec::new();
let mut has_success = false;
let mut submit_timings = Vec::new();
while let Some(result) = self.results.pop() {
signatures.push(result.signature);
submit_timings.push((result.swqos_type, result.submit_done_us));
if result.success {
has_success = true;
}
}
if has_success && !signatures.is_empty() {
return Some((true, signatures, None));
return Some((true, signatures, None, submit_timings));
}
}
// 🔧 Early exit: if a tx landed but failed (e.g., ExceededSlippage),
// Early exit: if a tx landed but failed (e.g., ExceededSlippage),
// nonce is consumed and other channels can't succeed - return immediately
if self.landed_failed_flag.load(Ordering::Acquire) {
let mut signatures = Vec::new();
let mut landed_error = None;
let mut submit_timings = Vec::new();
while let Some(result) = self.results.pop() {
signatures.push(result.signature);
submit_timings.push((result.swqos_type, result.submit_done_us));
// Prefer the error from the tx that actually landed
if result.landed_on_chain && result.error.is_some() {
landed_error = result.error;
}
}
if !signatures.is_empty() {
return Some((false, signatures, landed_error));
return Some((false, signatures, landed_error, submit_timings));
}
}
let completed = self.completed_count.load(Ordering::Acquire);
if completed >= self.total_tasks {
// 🔧 修复:收集所有签名
if completed >= self.total_tasks {
let mut signatures = Vec::new();
let mut last_error = None;
let mut any_success = false;
let mut submit_timings = Vec::new();
while let Some(result) = self.results.pop() {
signatures.push(result.signature);
submit_timings.push((result.swqos_type, result.submit_done_us));
if result.success {
any_success = true;
}
@@ -157,7 +284,7 @@ impl ResultCollector {
}
}
if !signatures.is_empty() {
return Some((any_success, signatures, last_error));
return Some((any_success, signatures, last_error, submit_timings));
}
return None;
}
@@ -165,18 +292,19 @@ impl ResultCollector {
if start.elapsed() > timeout {
return None;
}
tokio::task::yield_now().await;
tokio::time::sleep(poll_interval).await;
}
}
fn get_first(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>)> {
// 🔧 修复:收集已提交的所有签名
fn get_first(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
let mut signatures = Vec::new();
let mut has_success = false;
let mut last_error = None;
let mut submit_timings = Vec::new();
while let Some(result) = self.results.pop() {
signatures.push(result.signature);
submit_timings.push((result.swqos_type, result.submit_done_us));
if result.success {
has_success = true;
}
@@ -184,18 +312,33 @@ impl ResultCollector {
last_error = result.error;
}
}
if !signatures.is_empty() {
Some((has_success, signatures, last_error))
Some((has_success, signatures, last_error, submit_timings))
} else {
None
}
}
/// 等待全部任务完成(不等待链上确认),然后收集并返回所有签名。用于「多路提交」时返回多笔签名。
/// 轮询间隔 2ms,避免 50ms 间隔在最后一笔返回时多等几十 ms 拉高 submit 耗时。
async fn wait_for_all_submitted(&self, timeout_secs: u64) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
let start = Instant::now();
let timeout = std::time::Duration::from_secs(timeout_secs);
let poll_interval = std::time::Duration::from_millis(2);
while self.completed_count.load(Ordering::Acquire) < self.total_tasks {
if start.elapsed() > timeout {
break;
}
tokio::time::sleep(poll_interval).await;
}
self.get_first()
}
}
/// 🔧 修复:返回Vec<Signature>支持多SWQOS并发交易
/// Execute trade on multiple SWQOS clients in parallel; returns success flag, all signatures, and last error.
pub async fn execute_parallel(
swqos_clients: Vec<Arc<SwqosClient>>,
swqos_clients: &[Arc<SwqosClient>],
payer: Arc<Keypair>,
rpc: Option<Arc<SolanaRpcClient>>,
instructions: Vec<Instruction>,
@@ -208,7 +351,9 @@ pub async fn execute_parallel(
wait_transaction_confirmed: bool,
with_tip: bool,
gas_fee_strategy: GasFeeStrategy,
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)> {
use_core_affinity: bool,
check_min_tip: bool,
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
let _exec_start = Instant::now();
if swqos_clients.is_empty() {
@@ -224,10 +369,10 @@ pub async fn execute_parallel(
return Err(anyhow!("No Rpc Default Swqos configured."));
}
let cores = core_affinity::get_core_ids().unwrap();
let cores = core_affinity::get_core_ids().unwrap_or_default();
let instructions = Arc::new(instructions);
// 预先计算所有有效的组合
// Precompute all valid (client, gas config) combinations
let task_configs: Vec<_> = swqos_clients
.iter()
.enumerate()
@@ -235,36 +380,26 @@ pub async fn execute_parallel(
with_tip || matches!(swqos_client.get_swqos_type(), SwqosType::Default)
})
.flat_map(|(i, swqos_client)| {
let swqos_type = swqos_client.get_swqos_type();
let gas_fee_strategy_configs = gas_fee_strategy.get_strategies(if is_buy {
TradeType::Buy
} else {
TradeType::Sell
});
let check_tip = with_tip && !matches!(swqos_type, SwqosType::Default) && check_min_tip;
let min_tip = if check_tip {
swqos_client.min_tip_sol()
} else {
0.0
};
gas_fee_strategy_configs
.into_iter()
.filter(|config| config.0.eq(&swqos_client.get_swqos_type()))
.filter(|config| {
// 当需要 tip 且不是 Default 时,按 provider 最低小费进行筛选
if with_tip && !matches!(config.0, SwqosType::Default) {
let min_tip = match config.0 {
SwqosType::Jito => SWQOS_MIN_TIP_JITO,
SwqosType::NextBlock => SWQOS_MIN_TIP_NEXTBLOCK,
SwqosType::ZeroSlot => SWQOS_MIN_TIP_ZERO_SLOT,
SwqosType::Temporal => SWQOS_MIN_TIP_TEMPORAL,
SwqosType::Bloxroute => SWQOS_MIN_TIP_BLOXROUTE,
SwqosType::Node1 => SWQOS_MIN_TIP_NODE1,
SwqosType::FlashBlock => SWQOS_MIN_TIP_FLASHBLOCK,
SwqosType::BlockRazor => SWQOS_MIN_TIP_BLOCKRAZOR,
SwqosType::Astralane => SWQOS_MIN_TIP_ASTRALANE,
SwqosType::Stellium => SWQOS_MIN_TIP_STELLIUM,
SwqosType::Lightspeed => SWQOS_MIN_TIP_LIGHTSPEED,
SwqosType::Soyas => SWQOS_MIN_TIP_SOYAS,
SwqosType::Speedlanding => SWQOS_MIN_TIP_SPEEDLANDING,
SwqosType::Default => SWQOS_MIN_TIP_DEFAULT,
};
if config.2.tip < min_tip {
.filter(move |config| config.0 == swqos_type)
.filter(move |config| {
if check_tip {
if config.2.tip < min_tip && crate::common::sdk_log::sdk_log_enabled() {
println!(
"⚠️ Config filtered: {:?} tip {} is below minimum required tip {}",
"⚠️ Config filtered: {:?} tip {} is below minimum required {}",
config.0, config.2.tip, min_tip
);
}
@@ -285,120 +420,78 @@ pub async fn execute_parallel(
return Err(anyhow!("Multiple swqos transactions require durable_nonce to be set.",));
}
// Task preparation completed
// Task preparation completed: one shared context (clone once per batch), then minimal per-task data.
let collector = Arc::new(ResultCollector::new(task_configs.len()));
let _spawn_start = Instant::now();
let shared = Arc::new(SwqosSharedContext {
payer,
instructions,
rpc,
address_lookup_table_account,
recent_blockhash,
durable_nonce,
middleware_manager,
protocol_name,
is_buy,
wait_transaction_confirmed,
with_tip,
collector: collector.clone(),
});
for (i, swqos_client, gas_fee_strategy_config) in task_configs {
let core_id = cores[i % cores.len()];
let payer = payer.clone();
let instructions = instructions.clone();
let middleware_manager = middleware_manager.clone();
let swqos_type = swqos_client.get_swqos_type();
let tip_account_str = swqos_client.get_tip_account()?;
let tip_account = Arc::new(Pubkey::from_str(&tip_account_str).unwrap_or_default());
let collector = collector.clone();
let queue = SWQOS_QUEUE.get_or_init(|| Arc::new(ArrayQueue::new(SWQOS_QUEUE_CAP)));
ensure_swqos_pool(queue.clone());
let tip = gas_fee_strategy_config.2.tip;
let unit_limit = gas_fee_strategy_config.2.cu_limit;
let unit_price = gas_fee_strategy_config.2.cu_price;
let rpc = rpc.clone();
let durable_nonce = durable_nonce.clone();
let address_lookup_table_account = address_lookup_table_account.clone();
tokio::spawn(async move {
let _task_start = Instant::now();
core_affinity::set_for_current(core_id);
let tip_amount = if with_tip { tip } else { 0.0 };
let _build_start = Instant::now();
let transaction = match build_transaction(
payer,
rpc,
{
// Cache tip_account per client (one get_tip_account/from_str per unique client per batch). Dropped before await so future stays Send.
let mut tip_cache: FnvHashMap<*const (), Arc<Pubkey>> =
FnvHashMap::with_capacity_and_hasher(task_configs.len(), BuildHasherDefault::default());
for (i, swqos_client, gas_fee_strategy_config) in task_configs {
let core_id = cores.get(i % cores.len().max(1)).copied();
let swqos_type = swqos_client.get_swqos_type();
let key = Arc::as_ptr(&swqos_client) as *const ();
let tip_account = match tip_cache.get(&key) {
Some(tip) => tip.clone(),
None => {
let s = swqos_client.get_tip_account()?;
let tip = Arc::new(Pubkey::from_str(&s).unwrap_or_default());
tip_cache.insert(key, tip.clone());
tip
}
};
let (tip, unit_limit, unit_price) = (
gas_fee_strategy_config.2.tip,
gas_fee_strategy_config.2.cu_limit,
gas_fee_strategy_config.2.cu_price,
);
let job = SwqosJob {
shared: shared.clone(),
tip,
unit_limit,
unit_price,
instructions.as_ref().clone(),
address_lookup_table_account,
recent_blockhash,
middleware_manager,
protocol_name,
is_buy,
swqos_type != SwqosType::Default,
&tip_account,
tip_amount,
durable_nonce,
)
.await
{
Ok(tx) => tx,
Err(e) => {
// Build transaction failed
collector.submit(TaskResult {
success: false,
signature: Signature::default(),
error: Some(e),
swqos_type, // 🔧 记录SWQOS类型
landed_on_chain: false, // Build failed, tx never sent
});
return;
}
tip_account,
swqos_client,
swqos_type,
core_id,
use_affinity: use_core_affinity,
};
// Transaction built
let _send_start = Instant::now();
let mut err: Option<anyhow::Error> = None;
#[allow(unused_assignments)]
let mut landed_on_chain = false;
let success = match swqos_client
.send_transaction(
if is_buy { TradeType::Buy } else { TradeType::Sell },
&transaction,
wait_transaction_confirmed,
)
.await
{
Ok(()) => {
landed_on_chain = true; // Success means tx confirmed on-chain
true
}
Err(e) => {
// Check if this error indicates the tx landed but failed (e.g., ExceededSlippage)
landed_on_chain = is_landed_error(&e);
err = Some(e);
// Send transaction failed
false
}
};
// Transaction sent
if let Some(signature) = transaction.signatures.first() {
collector.submit(TaskResult {
success,
signature: *signature,
error: err,
swqos_type, // 🔧 记录SWQOS类型
landed_on_chain, // 🔧 Whether tx landed (even if it failed)
});
}
});
let _ = queue.push(job);
}
}
// All tasks spawned
// All jobs enqueued (no spawn on hot path)
if !wait_transaction_confirmed {
tokio::time::sleep(std::time::Duration::from_millis(10)).await;
if let Some(result) = collector.get_first() {
return Ok(result);
}
return Err(anyhow!("No transaction signature available"));
const SUBMIT_TIMEOUT_SECS: u64 = 30;
let ret = collector
.wait_for_all_submitted(SUBMIT_TIMEOUT_SECS)
.await
.unwrap_or((false, vec![], Some(anyhow!("No SWQOS result within {}s", SUBMIT_TIMEOUT_SECS)), vec![]));
let (success, signatures, last_error, submit_timings) = ret;
return Ok((success, signatures, last_error, submit_timings));
}
if let Some(result) = collector.wait_for_success().await {
Ok(result)
let (success, signatures, last_error, submit_timings) = result;
Ok((success, signatures, last_error, submit_timings))
} else {
Err(anyhow!("All transactions failed"))
}
+19 -22
View File
@@ -1,4 +1,5 @@
//! 执行模块
//! Execution: instruction preprocessing, cache prefetch, branch hints.
//! 执行模块:指令预处理、缓存预取、分支提示。
use anyhow::Result;
use solana_sdk::{
@@ -12,7 +13,15 @@ use crate::perf::{
simd::SIMDMemory,
};
/// 预取工具
/// Solana account key size in bytes (Pubkey). 每个账户(Pubkey)的字节数。
pub const BYTES_PER_ACCOUNT: usize = 32;
/// Threshold above which we warn about large instruction count. 超过此次数会打 warning。
pub const MAX_INSTRUCTIONS_WARN: usize = 64;
/// Prefetch helper: triggers CPU prefetch for soon-to-be-accessed data to reduce cache-miss latency.
/// Call once on hot-path refs; no-op on non-x86_64. Safety: caller ensures valid read-only ref, no concurrent write.
/// 缓存预取:对即将访问的数据做 CPU 预取以降低 cache-miss;热路径上调用一次即可;非 x86_64 为 no-op。安全:调用方保证有效只读、无并发写。
pub struct Prefetch;
impl Prefetch {
@@ -21,20 +30,15 @@ impl Prefetch {
if instructions.is_empty() {
return;
}
// 预取第一条指令
// Prefetch first/middle/last instruction into L1 for subsequent build_transaction access. 预取首/中/尾指令到 L1。
unsafe {
BranchOptimizer::prefetch_read_data(&instructions[0]);
}
// 预取中间指令
if instructions.len() > 2 {
unsafe {
BranchOptimizer::prefetch_read_data(&instructions[instructions.len() / 2]);
}
}
// 预取最后一条指令
if instructions.len() > 1 {
unsafe {
BranchOptimizer::prefetch_read_data(&instructions[instructions.len() - 1]);
@@ -57,46 +61,40 @@ impl Prefetch {
}
}
/// 内存操作
/// Memory operations (SIMD-accelerated where available). 内存操作(可用时走 SIMD 加速)。
pub struct MemoryOps;
impl MemoryOps {
#[inline(always)]
pub unsafe fn copy(dst: *mut u8, src: *const u8, len: usize) {
// 优先使用 AVX2 SIMD 加速
SIMDMemory::copy_avx2(dst, src, len);
}
#[inline(always)]
pub unsafe fn compare(a: *const u8, b: *const u8, len: usize) -> bool {
// 优先使用 AVX2 SIMD 比较
SIMDMemory::compare_avx2(a, b, len)
}
#[inline(always)]
pub unsafe fn zero(ptr: *mut u8, len: usize) {
// 优先使用 AVX2 SIMD 清零
SIMDMemory::zero_avx2(ptr, len);
}
}
/// 指令处理
/// Instruction preprocessing and validation. 指令处理与校验。
pub struct InstructionProcessor;
impl InstructionProcessor {
#[inline(always)]
pub fn preprocess(instructions: &[Instruction]) -> Result<()> {
// 分支预测: 大概率指令不为空
if BranchOptimizer::unlikely(instructions.is_empty()) {
return Err(anyhow::anyhow!("Instructions empty"));
}
// 预取所有指令到缓存
Prefetch::instructions(instructions);
// 分支预测: 大概率指令数量合理
if BranchOptimizer::unlikely(instructions.len() > 64) {
log::warn!("Large instruction count: {}", instructions.len());
if BranchOptimizer::unlikely(instructions.len() > MAX_INSTRUCTIONS_WARN) {
tracing::warn!(target: "sol_trade_sdk", "Large instruction count: {}", instructions.len());
}
Ok(())
@@ -107,7 +105,7 @@ impl InstructionProcessor {
let mut total_size = 0;
for (i, instr) in instructions.iter().enumerate() {
// 预取下一条指令
// Prefetch next instruction; safe: same slice, read-only. 预取下一条指令;安全:同 slice、只读。
unsafe {
if let Some(next_instr) = instructions.get(i + 1) {
BranchOptimizer::prefetch_read_data(next_instr);
@@ -115,20 +113,19 @@ impl InstructionProcessor {
}
total_size += instr.data.len();
total_size += instr.accounts.len() * 32; // 每个账户 32 字节
total_size += instr.accounts.len() * BYTES_PER_ACCOUNT;
}
total_size
}
}
/// 执行路径
/// Trade direction / execution path helpers. 交易方向与执行路径辅助。
pub struct ExecutionPath;
impl ExecutionPath {
#[inline(always)]
pub fn is_buy(input_mint: &Pubkey) -> bool {
// 分支预测: 大概率是买入
let is_buy = input_mint == &crate::constants::SOL_TOKEN_ACCOUNT
|| input_mint == &crate::constants::WSOL_TOKEN_ACCOUNT
|| input_mint == &crate::constants::USD1_TOKEN_ACCOUNT
+170 -80
View File
@@ -4,11 +4,14 @@ use solana_sdk::{
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
signature::Keypair, signature::Signature,
};
use std::{sync::Arc, time::Instant};
use std::{sync::Arc, time::{Duration, Instant}};
#[allow(unused_imports)]
use tracing::{info, trace, warn};
use crate::{
common::{nonce_cache::DurableNonceInfo, GasFeeStrategy, SolanaRpcClient},
perf::syscall_bypass::SystemCallBypassManager,
swqos::common::poll_any_transaction_confirmation,
trading::core::{
async_executor::execute_parallel,
execution::{InstructionProcessor, Prefetch},
@@ -20,7 +23,9 @@ use once_cell::sync::Lazy;
use crate::swqos::TradeType;
use super::{params::SwapParams, traits::InstructionBuilder};
/// 🚀 全局系统调用绕过管理器
/// Global syscall bypass manager (reserved for future time/IO optimizations).
/// 全局系统调用绕过管理器(预留,后续可接入时间/IO 等优化)。
#[allow(dead_code)]
static SYSCALL_BYPASS: Lazy<SystemCallBypassManager> = Lazy::new(|| {
use crate::perf::syscall_bypass::SyscallBypassConfig;
SystemCallBypassManager::new(SyscallBypassConfig::default())
@@ -45,43 +50,47 @@ impl GenericTradeExecutor {
#[async_trait::async_trait]
impl TradeExecutor for GenericTradeExecutor {
async fn swap(&self, params: SwapParams) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)> {
let total_start = Instant::now();
// Sample total start only when logging or simulate. 仅在有日志或 simulate 时取起点。
let total_start = (params.log_enabled || params.simulate).then(Instant::now);
let timing_start_us: Option<i64> = if params.log_enabled {
Some(params.grpc_recv_us.unwrap_or_else(crate::common::clock::now_micros))
} else {
None
};
// 判断买卖方向
let is_buy = params.trade_type == TradeType::Buy || params.trade_type == TradeType::CreateAndBuy;
// CPU 预取
Prefetch::keypair(&params.payer);
// 构建指令
let build_start = Instant::now();
// Time build only when log_enabled to avoid cold-path syscalls. 仅 log_enabled 时计时,减少冷路径 syscall。
let build_start = params.log_enabled.then(Instant::now);
let instructions = if is_buy {
self.instruction_builder.build_buy_instructions(&params).await?
} else {
self.instruction_builder.build_sell_instructions(&params).await?
};
let build_elapsed = build_start.elapsed();
let _build_elapsed = build_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
// 指令预处理
InstructionProcessor::preprocess(&instructions)?;
// 中间件处理
let final_instructions = match &params.middleware_manager {
Some(middleware_manager) => middleware_manager
.apply_middlewares_process_protocol_instructions(
instructions,
self.protocol_name.to_string(),
self.protocol_name,
is_buy,
)?,
None => instructions,
};
// 提交前耗时
let before_submit_elapsed = total_start.elapsed();
let build_end_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
.then(crate::common::clock::now_micros);
let _before_submit_elapsed = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
let before_submit_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
.then(crate::common::clock::now_micros);
// 如果是模拟模式,直接通过 RPC 模拟交易
if params.simulate {
let send_start = Instant::now();
let send_start = crate::common::sdk_log::sdk_log_enabled().then(Instant::now);
let result = simulate_transaction(
params.rpc,
params.payer,
@@ -96,44 +105,29 @@ impl TradeExecutor for GenericTradeExecutor {
params.gas_fee_strategy,
)
.await;
let send_elapsed = send_start.elapsed();
let total_elapsed = total_start.elapsed();
let send_elapsed = send_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
let total_elapsed = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
// Get performance metrics using fast timestamp
let timestamp_ns = SYSCALL_BYPASS.fast_timestamp_nanos();
// Print all timing metrics at once to avoid blocking critical path
println!("[Timestamp] {}ns", timestamp_ns);
println!(
"[Build Instructions] Time: {:.3}ms ({:.0}μs)",
build_elapsed.as_micros() as f64 / 1000.0,
build_elapsed.as_micros()
);
println!(
"[Before Submit] {:.3}ms ({:.0}μs)",
before_submit_elapsed.as_micros() as f64 / 1000.0,
before_submit_elapsed.as_micros()
);
println!(
"[Simulate Transaction] Time: {:.3}ms ({:.0}μs)",
send_elapsed.as_micros() as f64 / 1000.0,
send_elapsed.as_micros()
);
println!(
"[Total Time] {:.3}ms ({:.0}μs)",
total_elapsed.as_micros() as f64 / 1000.0,
total_elapsed.as_micros()
);
if crate::common::sdk_log::sdk_log_enabled() {
let dir = if is_buy { "Buy" } else { "Sell" };
if let (Some(start_us), Some(end_us)) = (timing_start_us, build_end_us) {
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
if let (Some(start_us), Some(end_us)) = (timing_start_us, before_submit_us) {
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
println!(" [SDK] {} simulate (dry-run): {:.4} ms", dir, send_elapsed.as_secs_f64() * 1000.0);
println!(" [SDK] {} total: {:.4} ms", dir, total_elapsed.as_secs_f64() * 1000.0);
}
return result;
}
// 并行发送交易
let send_start = Instant::now();
let need_confirm = params.wait_transaction_confirmed;
let result = execute_parallel(
params.swqos_clients.clone(),
&params.swqos_clients,
params.payer,
params.rpc,
params.rpc.clone(),
final_instructions,
params.address_lookup_table_account,
params.recent_blockhash,
@@ -141,30 +135,80 @@ impl TradeExecutor for GenericTradeExecutor {
params.middleware_manager,
self.protocol_name,
is_buy,
params.wait_transaction_confirmed,
false, // submit only here; confirmation and log timing handled below
if is_buy { true } else { params.with_tip },
params.gas_fee_strategy,
params.use_core_affinity,
params.check_min_tip,
)
.await;
let send_elapsed = send_start.elapsed();
let total_elapsed = total_start.elapsed();
// Get performance metrics using fast timestamp
#[cfg(feature = "perf-trace")]
{
let timestamp_ns = SYSCALL_BYPASS.fast_timestamp_nanos();
log::trace!(
"[Execute] timestamp_ns={} build_us={} before_submit_us={} send_us={} total_us={}",
timestamp_ns,
build_elapsed.as_micros(),
before_submit_elapsed.as_micros(),
send_elapsed.as_micros(),
total_elapsed.as_micros()
);
}
#[cfg(not(feature = "perf-trace"))]
let _ = (build_elapsed, before_submit_elapsed, send_elapsed, total_elapsed);
let log_enabled = params.log_enabled && crate::common::sdk_log::sdk_log_enabled();
let (ok, signatures, err, submit_timings) = match result {
Ok((success, sigs, last_error, timings)) => (
success,
sigs,
last_error.map(|e| anyhow::anyhow!("{}", e)),
timings,
),
Err(e) => (false, vec![], Some(anyhow::anyhow!("{}", e)), vec![]),
};
let submit_timings_ref: &[(crate::swqos::SwqosType, i64)] = submit_timings.as_slice();
let result = if need_confirm {
let confirm_result = if let Some(rpc) = params.rpc.as_ref() {
if signatures.is_empty() {
(ok, signatures, err)
} else {
let poll_res = poll_any_transaction_confirmation(rpc, &signatures, true).await;
let confirm_done_us = log_enabled.then(crate::common::clock::now_micros);
if log_enabled {
let dir = if is_buy { "Buy" } else { "Sell" };
if let Some(start_us) = timing_start_us {
if let Some(end_us) = build_end_us {
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
if let Some(end_us) = before_submit_us {
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
if let Some(confirm_us) = confirm_done_us {
let total_ms = (confirm_us - start_us) as f64 / 1000.0;
for (swqos_type, submit_done_us) in submit_timings_ref {
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
let confirmed_ms = (confirm_us - *submit_done_us).max(0) as f64 / 1000.0;
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms", dir, swqos_type, submit_ms, confirmed_ms, total_ms);
}
}
}
}
match poll_res {
Ok(_) => (true, signatures, None),
Err(e) => (false, signatures, Some(e)),
}
}
} else {
(ok, signatures, err)
};
Ok(confirm_result)
} else {
if log_enabled {
let dir = if is_buy { "Buy" } else { "Sell" };
if let Some(start_us) = timing_start_us {
if let Some(end_us) = build_end_us {
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
if let Some(end_us) = before_submit_us {
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
}
for (swqos_type, submit_done_us) in submit_timings_ref {
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms", dir, swqos_type, submit_ms, submit_ms);
}
}
}
Ok((ok, signatures, err))
};
result
}
@@ -174,7 +218,8 @@ impl TradeExecutor for GenericTradeExecutor {
}
}
/// 🔧 修复:Simulate模式返回Vec<Signature>(单个RPC模拟)
/// Simulate mode: single RPC simulation, returns Vec<Signature> for API consistency.
/// 模拟模式:单次 RPC 模拟,返回 Vec<Signature> 以与 API 一致。
async fn simulate_transaction(
rpc: Option<Arc<SolanaRpcClient>>,
payer: Arc<Keypair>,
@@ -209,22 +254,21 @@ async fn simulate_transaction(
let unit_limit = default_config.2.cu_limit;
let unit_price = default_config.2.cu_price;
// Build transaction for simulation
let transaction = build_transaction(
payer.clone(),
Some(rpc.clone()),
&payer,
Some(&rpc),
unit_limit,
unit_price,
instructions,
address_lookup_table_account,
&instructions,
address_lookup_table_account.as_ref(),
recent_blockhash,
middleware_manager,
middleware_manager.as_ref(),
protocol_name,
is_buy,
false, // simulate doesn't need tip instruction
false,
&Pubkey::default(),
tip,
durable_nonce,
durable_nonce.as_ref(),
)
.await?;
@@ -256,12 +300,12 @@ async fn simulate_transaction(
if let Some(err) = simulate_result.value.err {
#[cfg(feature = "perf-trace")]
{
log::warn!("[Simulation Failed] error={:?} signature={:?}", err, signature);
warn!(target: "sol_trade_sdk", "[Simulation Failed] error={:?} signature={:?}", err, signature);
if let Some(logs) = &simulate_result.value.logs {
log::trace!("Transaction logs: {:?}", logs);
trace!(target: "sol_trade_sdk", "Transaction logs: {:?}", logs);
}
if let Some(units_consumed) = simulate_result.value.units_consumed {
log::trace!("Compute Units Consumed: {}", units_consumed);
trace!(target: "sol_trade_sdk", "Compute Units Consumed: {}", units_consumed);
}
}
return Ok((false, vec![signature], Some(anyhow::anyhow!("{:?}", err))));
@@ -270,14 +314,60 @@ async fn simulate_transaction(
// Simulation succeeded
#[cfg(feature = "perf-trace")]
{
log::info!("[Simulation Succeeded] signature={:?}", signature);
info!(target: "sol_trade_sdk", "[Simulation Succeeded] signature={:?}", signature);
if let Some(units_consumed) = simulate_result.value.units_consumed {
log::trace!("Compute Units Consumed: {}", units_consumed);
trace!(target: "sol_trade_sdk", "Compute Units Consumed: {}", units_consumed);
}
if let Some(logs) = &simulate_result.value.logs {
log::trace!("Transaction logs: {:?}", logs);
trace!(target: "sol_trade_sdk", "Transaction logs: {:?}", logs);
}
}
Ok((true, vec![signature], None))
}
#[cfg(test)]
mod tests {
use crate::swqos::SwqosType;
/// 运行 `cargo test -p sol-trade-sdk log_timing_preview -- --nocapture` 查看日志打印效果
#[test]
fn log_timing_preview() {
let dir = "Buy";
let build_ms = 12.34;
let before_submit_ms = 15.67;
println!("\n--- 1. 构建指令耗时 / 提交前耗时(各打印一次,统一 ms,保留 4 位小数)---\n");
println!(" [SDK] {} build_instructions: {:.4} ms", dir, build_ms);
println!(" [SDK] {} before_submit: {:.4} ms", dir, before_submit_ms);
println!("\n--- 2. 每个 SWQOS 独立耗时:submit=起点→该通道返回, confirmed=该通道提交→链上确认, total=起点→链上确认 ---\n");
for (swqos_type, submit_ms, confirmed_ms, total_ms) in [
(SwqosType::Jito, 45.12, 83.38, 128.50),
(SwqosType::Helius, 52.30, 76.20, 128.50),
(SwqosType::ZeroSlot, 48.90, 79.60, 128.50),
] {
println!(
" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms",
dir, swqos_type, submit_ms, confirmed_ms, total_ms
);
}
println!("\n--- 3. 不等待链上确认时:每行 total = 该通道 submit 耗时(独立)---\n");
for (swqos_type, submit_ms, total_ms) in [
(SwqosType::Jito, 44.20, 44.20),
(SwqosType::Helius, 51.80, 51.80),
] {
println!(
" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms",
dir, swqos_type, submit_ms, total_ms
);
}
println!("\n--- 4. Simulate 模式(build/before_submit 仍从 grpc_recv_us 起算)---\n");
println!(" [SDK] {} build_instructions: {:.4} ms", dir, build_ms);
println!(" [SDK] {} before_submit: {:.4} ms", dir, before_submit_ms);
println!(" [SDK] {} simulate (dry-run): {:.4} ms", dir, 8.50);
println!(" [SDK] {} total: {:.4} ms", dir, 36.51);
println!();
}
}
+70 -5
View File
@@ -67,6 +67,14 @@ pub struct SwapParams {
pub fixed_output_amount: Option<u64>,
pub gas_fee_strategy: GasFeeStrategy,
pub simulate: bool,
/// Whether to output SDK logs (from TradeConfig.log_enabled).
pub log_enabled: bool,
/// Whether to pin parallel submit tasks to cores (from TradeConfig.use_core_affinity).
pub use_core_affinity: bool,
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). When false, skip filter for lower latency.
pub check_min_tip: bool,
/// Optional event receive time in microseconds (same scale as sol-parser-sdk clock::now_micros). Used as timing start when log_enabled.
pub grpc_recv_us: Option<i64>,
/// Use exact SOL amount instructions (buy_exact_sol_in for PumpFun, buy_exact_quote_in for PumpSwap).
/// When Some(true) or None (default), the exact SOL/quote amount is spent and slippage is applied to output tokens.
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
@@ -81,11 +89,18 @@ impl std::fmt::Debug for SwapParams {
}
/// PumpFun protocol specific parameters
/// Configuration parameters specific to PumpFun trading protocol
/// Configuration parameters specific to PumpFun trading protocol.
///
/// **Creator Rewards Sharing**: Some coins use a dynamic `creator_vault` (fee-sharing config).
/// Always use the latest on-chain creator/vault when building params for **sell**; do not reuse
/// cached params from buy. Either fetch fresh data via RPC, or pass `creator_vault` from gRPC
/// using [`from_trade`](PumpFunParams::from_trade) / [`from_dev_trade`](PumpFunParams::from_dev_trade),
/// or override with [`with_creator_vault`](PumpFunParams::with_creator_vault).
#[derive(Clone)]
pub struct PumpFunParams {
pub bonding_curve: Arc<BondingCurveAccount>,
pub associated_bonding_curve: Pubkey,
/// Creator vault PDA. For Creator Rewards Sharing coins this can change; pass latest from gRPC when selling.
pub creator_vault: Pubkey,
pub token_program: Pubkey,
/// Whether to close token account when selling, only effective during sell operations
@@ -214,6 +229,14 @@ impl PumpFunParams {
token_program: mint_account.owner,
})
}
/// Override `creator_vault` with a value from gRPC/event (e.g. for Creator Rewards Sharing).
/// Use when selling so the instruction uses the latest on-chain vault and avoids "seeds constraint violated" (2006).
#[inline]
pub fn with_creator_vault(mut self, creator_vault: Pubkey) -> Self {
self.creator_vault = creator_vault;
self
}
}
/// PumpSwap Protocol Specific Parameters
@@ -270,6 +293,7 @@ impl PumpSwapParams {
base_token_program: Pubkey,
quote_token_program: Pubkey,
fee_recipient: Pubkey,
is_cashback_coin: bool,
) -> Self {
let is_mayhem_mode = fee_recipient == MAYHEM_FEE_RECIPIENT_SWAP;
Self {
@@ -285,10 +309,51 @@ impl PumpSwapParams {
base_token_program,
quote_token_program,
is_mayhem_mode,
is_cashback_coin: false,
is_cashback_coin,
}
}
/// Fast-path constructor for building PumpSwap parameters directly from decoded
/// trade/event data and the accompanying instruction accounts, avoiding RPC
/// lookups and associated latency. Token program IDs should be sourced from
/// the instruction accounts themselves to respect Token Program vs Token-2022
/// differences.
///
/// When building from event/parser (e.g. sol-parser-sdk), pass `is_cashback_coin`
/// from the event so that buy/sell instructions include the correct remaining
/// accounts for cashback.
pub fn from_trade(
pool: Pubkey,
base_mint: Pubkey,
quote_mint: Pubkey,
pool_base_token_account: Pubkey,
pool_quote_token_account: Pubkey,
pool_base_token_reserves: u64,
pool_quote_token_reserves: u64,
coin_creator_vault_ata: Pubkey,
coin_creator_vault_authority: Pubkey,
base_token_program: Pubkey,
quote_token_program: Pubkey,
fee_recipient: Pubkey,
is_cashback_coin: bool,
) -> Self {
Self::new(
pool,
base_mint,
quote_mint,
pool_base_token_account,
pool_quote_token_account,
pool_base_token_reserves,
pool_quote_token_reserves,
coin_creator_vault_ata,
coin_creator_vault_authority,
base_token_program,
quote_token_program,
fee_recipient,
is_cashback_coin,
)
}
pub async fn from_mint_by_rpc(
rpc: &SolanaRpcClient,
mint: &Pubkey,
@@ -333,7 +398,7 @@ impl PumpSwapParams {
);
Ok(Self {
pool: pool_address.clone(),
pool: *pool_address,
base_mint: pool_data.base_mint,
quote_mint: pool_data.quote_mint,
pool_base_token_account: pool_data.pool_base_token_account,
@@ -606,7 +671,7 @@ impl RaydiumCpmmParams {
)
.await?;
Ok(Self {
pool_state: pool_address.clone(),
pool_state: *pool_address,
amm_config: pool.amm_config,
base_mint: pool.token0_mint,
quote_mint: pool.token1_mint,
@@ -713,7 +778,7 @@ impl MeteoraDammV2Params {
let pool_data =
crate::instruction::utils::meteora_damm_v2::fetch_pool(rpc, pool_address).await?;
Ok(Self {
pool: pool_address.clone(),
pool: *pool_address,
token_a_vault: pool_data.token_a_vault,
token_b_vault: pool_data.token_b_vault,
token_a_mint: pool_data.token_a_mint,
+19 -14
View File
@@ -6,6 +6,15 @@
//! - 零拷贝 I/O
//! - 内存预热
/// 预分配指令容量(单笔交易常见指令数)
const TX_BUILDER_INSTRUCTION_CAP: usize = 32;
/// 预分配地址查找表数量
const TX_BUILDER_LOOKUP_TABLE_CAP: usize = 8;
/// 对象池最大容量
const TX_BUILDER_POOL_CAP: usize = 1000;
/// 启动时预填充对象池数量
const TX_BUILDER_POOL_PREFILL: usize = 100;
use crossbeam_queue::ArrayQueue;
use once_cell::sync::Lazy;
use solana_sdk::{
@@ -23,8 +32,8 @@ pub struct PreallocatedTxBuilder {
impl PreallocatedTxBuilder {
fn new() -> Self {
Self {
instructions: Vec::with_capacity(32), // 预分配32条指令空间
lookup_tables: Vec::with_capacity(8), // 预分配8个查找表空间
instructions: Vec::with_capacity(TX_BUILDER_INSTRUCTION_CAP),
lookup_tables: Vec::with_capacity(TX_BUILDER_LOOKUP_TABLE_CAP),
}
}
@@ -65,23 +74,20 @@ impl PreallocatedTxBuilder {
&mut self,
payer: &Pubkey,
instructions: &[Instruction],
address_lookup_table_account: Option<AddressLookupTableAccount>,
address_lookup_table_account: Option<&AddressLookupTableAccount>,
recent_blockhash: Hash,
) -> VersionedMessage {
// 重用已分配的 vector
self.reset();
self.instructions.extend_from_slice(instructions);
// ✅ 如果有查找表,使用 V0 消息
if let Some(address_lookup_table_account) = address_lookup_table_account {
let message = v0::Message::try_compile(
if let Some(alt) = address_lookup_table_account {
let message = v0::Message::try_compile(
payer,
&self.instructions,
&[address_lookup_table_account],
std::slice::from_ref(alt),
recent_blockhash,
).expect("v0 message compile failed");
)
.expect("v0 message compile failed");
VersionedMessage::V0(message)
} else {
// ✅ 没有查找表,使用 Legacy 消息(兼容所有 RPC
@@ -97,10 +103,9 @@ impl PreallocatedTxBuilder {
/// 🚀 全局交易构建器对象池
static TX_BUILDER_POOL: Lazy<Arc<ArrayQueue<PreallocatedTxBuilder>>> = Lazy::new(|| {
let pool = ArrayQueue::new(1000); // 1000个预分配构建器
let pool = ArrayQueue::new(TX_BUILDER_POOL_CAP);
// 预填充池
for _ in 0..100 {
for _ in 0..TX_BUILDER_POOL_PREFILL {
let _ = pool.push(PreallocatedTxBuilder::new());
}
+2 -2
View File
@@ -14,7 +14,7 @@ impl InstructionMiddleware for LoggingMiddleware {
fn process_protocol_instructions(
&self,
protocol_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>> {
println!("-------------------[{}]-------------------", self.name());
@@ -32,7 +32,7 @@ impl InstructionMiddleware for LoggingMiddleware {
fn process_full_instructions(
&self,
full_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>> {
println!("-------------------[{}]-------------------", self.name());
+6 -6
View File
@@ -20,7 +20,7 @@ pub trait InstructionMiddleware: Send + Sync {
fn process_protocol_instructions(
&self,
protocol_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>>;
@@ -36,7 +36,7 @@ pub trait InstructionMiddleware: Send + Sync {
fn process_full_instructions(
&self,
full_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>>;
@@ -72,13 +72,13 @@ impl MiddlewareManager {
pub fn apply_middlewares_process_full_instructions(
&self,
mut full_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>> {
for middleware in &self.middlewares {
full_instructions = middleware.process_full_instructions(
full_instructions,
protocol_name.clone(),
protocol_name,
is_buy,
)?;
if full_instructions.is_empty() {
@@ -92,13 +92,13 @@ impl MiddlewareManager {
pub fn apply_middlewares_process_protocol_instructions(
&self,
mut protocol_instructions: Vec<Instruction>,
protocol_name: String,
protocol_name: &str,
is_buy: bool,
) -> Result<Vec<Instruction>> {
for middleware in &self.middlewares {
protocol_instructions = middleware.process_protocol_instructions(
protocol_instructions,
protocol_name.clone(),
protocol_name,
is_buy,
)?;
if protocol_instructions.is_empty() {
+17
View File
@@ -31,6 +31,23 @@ impl TradingClient {
trading::common::utils::get_token_balance(&self.infrastructure.rpc, &self.payer.pubkey(), mint).await
}
/// 使用与交易一致的 ATA 推导(含 seed 优化)查询 payer 某 mint 的余额;卖出前查余额应使用此接口并传入池的 base_token_program,否则若使用 seed ATA 会查错账户。
#[inline]
pub async fn get_payer_token_balance_with_program(
&self,
mint: &Pubkey,
token_program: &Pubkey,
) -> Result<u64, anyhow::Error> {
trading::common::utils::get_token_balance_with_options(
&self.infrastructure.rpc,
&self.payer.pubkey(),
mint,
token_program,
self.use_seed_optimize,
)
.await
}
#[inline]
pub fn get_payer_pubkey(&self) -> Pubkey {
self.payer.pubkey()