Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e8ec9103ab | ||
|
|
0fe54f0e94 | ||
|
|
7ac07247a3 | ||
|
|
06ed710869 | ||
|
|
d711346c55 | ||
|
|
06ef2fed84 | ||
|
|
a391539000 | ||
|
|
c75ca4b034 | ||
|
|
b13b4fda0a | ||
|
|
4dec087ea6 | ||
|
|
9c9ecf3e5b | ||
|
|
4b451af5ff | ||
|
|
8f2f99f3d9 | ||
|
|
971ef41fad | ||
|
|
35bfa93516 | ||
|
|
c8f9f9f6aa | ||
|
|
99846a21c2 | ||
|
|
062c5415c3 | ||
|
|
eaa3214e4d | ||
|
|
ae890ad976 | ||
|
|
e10ee0de3b | ||
|
|
5e1fb1a66b | ||
|
|
a5ea26afaf | ||
|
|
ee4a8f685b | ||
|
|
322acf8baf | ||
|
|
378b8fc324 | ||
|
|
19f11aa620 | ||
|
|
61cea7546c | ||
|
|
d52503b8de | ||
|
|
9e53b7694c | ||
|
|
07e45d136f | ||
|
|
20d053bab3 | ||
|
|
5d921f23ff | ||
|
|
a187126554 | ||
|
|
6ea8c27824 | ||
|
|
8c4e3ee0c5 | ||
|
|
624b1843a2 | ||
|
|
7d2ecd57e9 | ||
|
|
667d6d2c5b | ||
|
|
e957bc4bee | ||
|
|
274636abc5 | ||
|
|
2abcf3839e | ||
|
|
0ec826fcbd | ||
|
|
6607d276db | ||
|
|
d7b0985844 | ||
|
|
2e39649ebc | ||
|
|
0201d3443a | ||
|
|
9872b1b4a7 | ||
|
|
e16cd6620f | ||
|
|
9f79e865ab | ||
|
|
e32e7ee6ab | ||
|
|
30c91a74af | ||
|
|
6c41e1cfe6 | ||
|
|
a003fd4d2f | ||
|
|
fd5af3ab61 | ||
|
|
7e2860d8de | ||
|
|
07487c06cb | ||
|
|
1142829394 | ||
|
|
d2ce193e2c | ||
|
|
46564f1bb5 | ||
|
|
63afac7aea | ||
|
|
d9b9ddc53f | ||
|
|
d610745c7e | ||
|
|
460395e5b2 | ||
|
|
5335a4f5ff | ||
|
|
23a45e611c | ||
|
|
48b9b17ab1 | ||
|
|
0cd276d6cb | ||
|
|
82438479d3 | ||
|
|
3d062279d9 | ||
|
|
15e07e9130 | ||
|
|
6eaafde4fd | ||
|
|
0f37950adf | ||
|
|
dd4f42324e | ||
|
|
d0897b53d3 | ||
|
|
e67a21df58 | ||
|
|
147c6068d1 | ||
|
|
6ce8ee582e | ||
|
|
bcc6860bc3 | ||
|
|
1b7e3781c7 | ||
|
|
807b015fc3 | ||
|
|
8f6cc6fb08 | ||
|
|
5e4977f6a6 | ||
|
|
c27e479659 | ||
|
|
9a8e3ffb2d | ||
|
|
43d1369d4e | ||
|
|
a048f3b6ad | ||
|
|
feaac5ddd2 | ||
|
|
710a8d482f |
@@ -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 }}
|
||||||
+9
-27
@@ -1,30 +1,12 @@
|
|||||||
# Generated by Cargo
|
# Proto 生成工具和生成的代码(用户不需要)
|
||||||
# will have compiled files and executables
|
/proto/gen/
|
||||||
debug/
|
|
||||||
target/
|
|
||||||
|
|
||||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
# 预生成的 proto Rust 代码(提交到仓库,但用户不应修改)
|
||||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
# /src/swqos/pb/serverpb.rs <- 这个文件已经提交,用户不应修改
|
||||||
|
|
||||||
|
# Build artifacts
|
||||||
|
/target/
|
||||||
Cargo.lock
|
Cargo.lock
|
||||||
|
|
||||||
# These are backup files generated by rustfmt
|
# Proto sources
|
||||||
**/*.rs.bk
|
/proto/
|
||||||
|
|
||||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
|
||||||
*.pdb
|
|
||||||
|
|
||||||
# RustRover
|
|
||||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
|
||||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
|
||||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
|
||||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
|
||||||
#.idea/
|
|
||||||
|
|
||||||
.cargo/
|
|
||||||
|
|
||||||
tmp_*.rs
|
|
||||||
tmp_*.log
|
|
||||||
|
|
||||||
|
|
||||||
.claude/
|
|
||||||
.serena/
|
|
||||||
|
|||||||
@@ -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
|
|
||||||
- 增强异步执行器,添加小费验证警告
|
|
||||||
+30
-22
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "sol-trade-sdk"
|
name = "sol-trade-sdk"
|
||||||
version = "3.4.0"
|
version = "4.0.4"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = [
|
authors = [
|
||||||
"William <byteblock6@gmail.com>",
|
"William <byteblock6@gmail.com>",
|
||||||
@@ -19,9 +19,9 @@ members = [
|
|||||||
"examples/trading_client",
|
"examples/trading_client",
|
||||||
"examples/shared_infrastructure",
|
"examples/shared_infrastructure",
|
||||||
"examples/middleware_system",
|
"examples/middleware_system",
|
||||||
|
"examples/pumpswap_trading",
|
||||||
"examples/pumpfun_copy_trading",
|
"examples/pumpfun_copy_trading",
|
||||||
"examples/pumpfun_sniper_trading",
|
"examples/pumpfun_sniper_trading",
|
||||||
"examples/pumpswap_trading",
|
|
||||||
"examples/bonk_sniper_trading",
|
"examples/bonk_sniper_trading",
|
||||||
"examples/bonk_copy_trading",
|
"examples/bonk_copy_trading",
|
||||||
"examples/raydium_cpmm_trading",
|
"examples/raydium_cpmm_trading",
|
||||||
@@ -45,23 +45,26 @@ perf-trace = [] # 性能追踪特性,生产环境应禁用以获得最佳性
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
solana-sdk = "3.0.0"
|
solana-sdk = "3.0.0"
|
||||||
solana-client = "3.0.8"
|
solana-client = "3.1.12"
|
||||||
solana-program = "3.0.0"
|
solana-program = "3.0.0"
|
||||||
solana-rpc-client = "3.0.8"
|
solana-rpc-client = "3.1.12"
|
||||||
solana-rpc-client-api = "3.0.8"
|
solana-rpc-client-api = "3.1.12"
|
||||||
solana-transaction-status = "3.0.8"
|
solana-transaction-status = "3.1.12"
|
||||||
solana-account-decoder = "3.0.8"
|
solana-account-decoder = "3.1.12"
|
||||||
solana-hash = "3.0.0"
|
solana-hash = "3.0.0"
|
||||||
solana-entry = "3.0.8"
|
solana-entry = "3.0.0"
|
||||||
solana-rpc-client-nonce-utils = "3.0.8"
|
solana-rpc-client-nonce-utils = "3.1.12"
|
||||||
solana-perf = "3.0.8"
|
solana-perf = "3.1.12"
|
||||||
solana-metrics = "3.0.8"
|
solana-metrics = "3.1.12"
|
||||||
solana-nonce = "3.0.0"
|
solana-tls-utils = "3.1.12"
|
||||||
|
solana-nonce = "3.2.0"
|
||||||
|
|
||||||
solana-address-lookup-table-interface = "3.0.0"
|
solana-address-lookup-table-interface = "3.0.0"
|
||||||
|
solana-message = "3.1.0"
|
||||||
solana-compute-budget-interface = "3.0.0"
|
solana-compute-budget-interface = "3.0.0"
|
||||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
solana-commitment-config = { version = "3.1.1", features = ["serde"] }
|
||||||
solana-transaction-status-client-types = "3.0.0"
|
solana-transaction-status-client-types = "3.1.12"
|
||||||
solana-tls-utils = "3.0.8"
|
solana-system-interface = { version = "3.0.0", features = ["bincode"] }
|
||||||
|
|
||||||
borsh = { version = "1.5.3", features = ["derive"] }
|
borsh = { version = "1.5.3", features = ["derive"] }
|
||||||
isahc = "1.7.2"
|
isahc = "1.7.2"
|
||||||
@@ -76,21 +79,19 @@ bincode = "1.3.3"
|
|||||||
anyhow = "1.0.90"
|
anyhow = "1.0.90"
|
||||||
reqwest = { version = "0.12.12", features = ["json", "multipart"] }
|
reqwest = { version = "0.12.12", features = ["json", "multipart"] }
|
||||||
tokio = { version = "1.42.0" , features = ["full", "rt-multi-thread"]}
|
tokio = { version = "1.42.0" , features = ["full", "rt-multi-thread"]}
|
||||||
tonic = { version = "0.14.2", features = ["transport"] }
|
tonic = { version = "0.12", features = ["transport"] }
|
||||||
rustls = { version = "0.23.23", features = ["ring"] }
|
rustls = { version = "0.23.23", features = ["ring"] }
|
||||||
rustls-native-certs = "0.8.1"
|
rustls-native-certs = "0.8.1"
|
||||||
tokio-rustls = "0.26.1"
|
tokio-rustls = "0.26.1"
|
||||||
core_affinity = "0.8"
|
core_affinity = "0.8"
|
||||||
log = "0.4.22"
|
|
||||||
chrono = "0.4.39"
|
chrono = "0.4.39"
|
||||||
regex = "1"
|
regex = "1"
|
||||||
tracing = "0.1.41"
|
tracing = "0.1.41"
|
||||||
thiserror = "2.0.11"
|
thiserror = "2.0.11"
|
||||||
async-trait = "0.1.86"
|
async-trait = "0.1.86"
|
||||||
lazy_static = "1.5.0"
|
|
||||||
once_cell = "1.20.3"
|
once_cell = "1.20.3"
|
||||||
prost = "0.14.1"
|
prost = "0.13"
|
||||||
prost-types = "0.14.1"
|
prost-types = "0.13"
|
||||||
num_enum = "0.7.3"
|
num_enum = "0.7.3"
|
||||||
num-derive = "0.4.2"
|
num-derive = "0.4.2"
|
||||||
num-traits = "0.2.19"
|
num-traits = "0.2.19"
|
||||||
@@ -99,7 +100,7 @@ bytemuck = { version = "1.4.0" }
|
|||||||
arrayref = "0.3.6"
|
arrayref = "0.3.6"
|
||||||
borsh-derive = "1.5.5"
|
borsh-derive = "1.5.5"
|
||||||
indicatif = "0.18.0"
|
indicatif = "0.18.0"
|
||||||
solana-system-interface = { version = "2.0.0", features = ["bincode"] }
|
|
||||||
fnv = "1.0.7"
|
fnv = "1.0.7"
|
||||||
dashmap = "6.1.0"
|
dashmap = "6.1.0"
|
||||||
clru = "0.6"
|
clru = "0.6"
|
||||||
@@ -108,7 +109,10 @@ parking_lot = "0.12"
|
|||||||
arc-swap = "1.7"
|
arc-swap = "1.7"
|
||||||
sha2 = "0.10"
|
sha2 = "0.10"
|
||||||
tonic-prost = "0.14.2"
|
tonic-prost = "0.14.2"
|
||||||
quinn = {version = "0.11", default-features = false, features = ["rustls"]}
|
# 须含 runtime-tokio,否则 quinn::Endpoint::client 报 no async runtime found,QUIC(Speedlanding/Soyas)无法初始化
|
||||||
|
quinn = { version = "0.11", default-features = false, features = ["rustls", "runtime-tokio"] }
|
||||||
|
rcgen = "0.13"
|
||||||
|
uuid = "1.11"
|
||||||
|
|
||||||
# Performance optimization dependencies
|
# Performance optimization dependencies
|
||||||
crossbeam-queue = "0.3"
|
crossbeam-queue = "0.3"
|
||||||
@@ -134,6 +138,10 @@ incremental = true # 增量编译 - 大幅加速重新编译
|
|||||||
opt-level = 1 # 开发时适度优化
|
opt-level = 1 # 开发时适度优化
|
||||||
overflow-checks = true # 开发时启用溢出检查
|
overflow-checks = true # 开发时启用溢出检查
|
||||||
|
|
||||||
|
# 🚀 构建依赖
|
||||||
|
# 注意:proto 代码已预生成在 src/swqos/pb/serverpb.rs
|
||||||
|
# 开发者如需重新生成代码,请运行 gen_proto 目录下的工具
|
||||||
|
|
||||||
# 🚀 性能关键依赖的特殊优化
|
# 🚀 性能关键依赖的特殊优化
|
||||||
[profile.release.package.solana-sdk]
|
[profile.release.package.solana-sdk]
|
||||||
opt-level = 3
|
opt-level = 3
|
||||||
|
|||||||
@@ -47,10 +47,12 @@
|
|||||||
- [📋 Example Usage](#-example-usage)
|
- [📋 Example Usage](#-example-usage)
|
||||||
- [⚡ Trading Parameters](#-trading-parameters)
|
- [⚡ Trading Parameters](#-trading-parameters)
|
||||||
- [📊 Usage Examples Summary Table](#-usage-examples-summary-table)
|
- [📊 Usage Examples Summary Table](#-usage-examples-summary-table)
|
||||||
- [⚙️ SWQOS Service Configuration](#️-swqos-service-configuration)
|
- [⚙️ SWQoS Service Configuration](#️-swqos-service-configuration)
|
||||||
|
- [Astralane (Binary / Plain / QUIC)](#astralane-binary--plain--quic)
|
||||||
- [🔧 Middleware System](#-middleware-system)
|
- [🔧 Middleware System](#-middleware-system)
|
||||||
- [🔍 Address Lookup Tables](#-address-lookup-tables)
|
- [🔍 Address Lookup Tables](#-address-lookup-tables)
|
||||||
- [🔍 Nonce Cache](#-nonce-cache)
|
- [🔍 Nonce Cache](#-nonce-cache)
|
||||||
|
- [💰 Cashback Support (PumpFun / PumpSwap)](#-cashback-support-pumpfun--pumpswap)
|
||||||
- [🛡️ MEV Protection Services](#️-mev-protection-services)
|
- [🛡️ MEV Protection Services](#️-mev-protection-services)
|
||||||
- [📁 Project Structure](#-project-structure)
|
- [📁 Project Structure](#-project-structure)
|
||||||
- [📄 License](#-license)
|
- [📄 License](#-license)
|
||||||
@@ -59,6 +61,17 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 📦 SDK Versions
|
||||||
|
|
||||||
|
This SDK is available in multiple languages:
|
||||||
|
|
||||||
|
| Language | Repository | Description |
|
||||||
|
|----------|------------|-------------|
|
||||||
|
| **Rust** | [sol-trade-sdk](https://github.com/0xfnzero/sol-trade-sdk) | Ultra-low latency with zero-copy optimization |
|
||||||
|
| **Node.js** | [sol-trade-sdk-nodejs](https://github.com/0xfnzero/sol-trade-sdk-nodejs) | TypeScript/JavaScript for Node.js |
|
||||||
|
| **Python** | [sol-trade-sdk-python](https://github.com/0xfnzero/sol-trade-sdk-python) | Async/await native support |
|
||||||
|
| **Go** | [sol-trade-sdk-golang](https://github.com/0xfnzero/sol-trade-sdk-golang) | Concurrent-safe with goroutine support |
|
||||||
|
|
||||||
## ✨ Features
|
## ✨ Features
|
||||||
|
|
||||||
1. **PumpFun Trading**: Support for `buy` and `sell` operations
|
1. **PumpFun Trading**: Support for `buy` and `sell` operations
|
||||||
@@ -71,7 +84,7 @@
|
|||||||
8. **Concurrent Trading**: Send transactions using multiple MEV services simultaneously; the fastest succeeds while others fail
|
8. **Concurrent Trading**: Send transactions using multiple MEV services simultaneously; the fastest succeeds while others fail
|
||||||
9. **Unified Trading Interface**: Use unified trading protocol enums for trading operations
|
9. **Unified Trading Interface**: Use unified trading protocol enums for trading operations
|
||||||
10. **Middleware System**: Support for custom instruction middleware to modify, add, or remove instructions before transaction execution
|
10. **Middleware System**: Support for custom instruction middleware to modify, add, or remove instructions before transaction execution
|
||||||
11. **Shared Infrastructure**: Share expensive RPC and SWQOS clients across multiple wallets for reduced resource usage
|
11. **Shared Infrastructure**: Share expensive RPC and SWQoS clients across multiple wallets for reduced resource usage
|
||||||
|
|
||||||
## 📦 Installation
|
## 📦 Installation
|
||||||
|
|
||||||
@@ -88,14 +101,14 @@ Add the dependency to your `Cargo.toml`:
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
# Add to your Cargo.toml
|
# Add to your Cargo.toml
|
||||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.4.0" }
|
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.3" }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Use crates.io
|
### Use crates.io
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
# Add to your Cargo.toml
|
# Add to your Cargo.toml
|
||||||
sol-trade-sdk = "3.4.0"
|
sol-trade-sdk = "4.0.3"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ Usage Examples
|
## 🛠️ Usage Examples
|
||||||
@@ -113,14 +126,29 @@ let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
|||||||
// RPC URL
|
// RPC URL
|
||||||
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
||||||
let commitment = CommitmentConfig::processed();
|
let commitment = CommitmentConfig::processed();
|
||||||
// Multiple SWQOS services can be configured
|
// Multiple SWQoS services can be configured
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||||
SwqosConfig::Default(rpc_url.clone()),
|
SwqosConfig::Default(rpc_url.clone()),
|
||||||
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
|
// Astralane: 4th param = AstralaneTransport — Binary (default), Plain (/iris), or Quic
|
||||||
|
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // Binary HTTP /irisb
|
||||||
|
SwqosConfig::Astralane(
|
||||||
|
"your_astralane_api_key".to_string(),
|
||||||
|
SwqosRegion::Frankfurt,
|
||||||
|
None,
|
||||||
|
Some(AstralaneTransport::Quic),
|
||||||
|
), // QUIC
|
||||||
];
|
];
|
||||||
// Create TradeConfig instance
|
// Create TradeConfig instance
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true - check & create WSOL ATA on init
|
||||||
|
// .use_seed_optimize(true) // default: true - seed optimization for ATA ops
|
||||||
|
// .log_enabled(true) // default: true - SDK timing / SWQOS logs
|
||||||
|
// .check_min_tip(false) // default: false - filter SWQOS below min tip
|
||||||
|
// .swqos_cores_from_end(false) // default: false - bind SWQOS to last N CPU cores
|
||||||
|
// .mev_protection(false) // default: false - MEV (Astralane QUIC :9000 or HTTP mev-protect / BlockRazor)
|
||||||
|
.build();
|
||||||
|
|
||||||
// Create TradingClient
|
// Create TradingClient
|
||||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||||
@@ -218,16 +246,16 @@ Please ensure that the parameters your trading logic depends on are available in
|
|||||||
| Seed trading example | `cargo run --package seed_trading` | [examples/seed_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/seed_trading/src/main.rs) |
|
| Seed trading example | `cargo run --package seed_trading` | [examples/seed_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/seed_trading/src/main.rs) |
|
||||||
| Gas fee strategy example | `cargo run --package gas_fee_strategy` | [examples/gas_fee_strategy](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/gas_fee_strategy/src/main.rs) |
|
| Gas fee strategy example | `cargo run --package gas_fee_strategy` | [examples/gas_fee_strategy](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/gas_fee_strategy/src/main.rs) |
|
||||||
|
|
||||||
### ⚙️ SWQOS Service Configuration
|
### ⚙️ SWQoS Service Configuration
|
||||||
|
|
||||||
When configuring SWQOS services, note the different parameter requirements for each service:
|
When configuring SWQoS services, note the different parameter requirements for each service:
|
||||||
|
|
||||||
- **Jito**: The first parameter is UUID (if no UUID, pass an empty string `""`)
|
- **Jito**: The first parameter is UUID (if no UUID, pass an empty string `""`)
|
||||||
- **Other MEV services**: The first parameter is the API Token
|
- **Other MEV services**: The first parameter is the API Token
|
||||||
|
|
||||||
#### Custom URL Support
|
#### Custom URL Support
|
||||||
|
|
||||||
Each SWQOS service now supports an optional custom URL parameter:
|
Each SWQoS service now supports an optional custom URL parameter:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
// Using custom URL (third parameter)
|
// Using custom URL (third parameter)
|
||||||
@@ -252,6 +280,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.
|
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 (Binary / Plain HTTP / QUIC)
|
||||||
|
|
||||||
|
Astralane supports **Binary** HTTP (`/irisb`), **Plain** HTTP (`/iris`), and **QUIC** (`host:7000`, or `:9000` when global `mev_protection` is true). Pass `Some(AstralaneTransport::Plain)`, `Some(AstralaneTransport::Quic)`, or use `None` / omit for **Binary** (default). Global `mev_protection` adds `mev-protect=true` on HTTP or selects QUIC port 9000.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use sol_trade_sdk::{SwqosConfig, SwqosRegion, AstralaneTransport};
|
||||||
|
|
||||||
|
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||||
|
SwqosConfig::Default(rpc_url.clone()),
|
||||||
|
SwqosConfig::Astralane(
|
||||||
|
"your_astralane_api_key".to_string(),
|
||||||
|
SwqosRegion::Frankfurt,
|
||||||
|
None,
|
||||||
|
Some(AstralaneTransport::Quic),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
// Then create TradeConfig / TradingClient as usual with swqos_configs
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Binary** (default): `None` or `Some(AstralaneTransport::Binary)` — `/irisb`, bincode body.
|
||||||
|
- **Plain**: `Some(AstralaneTransport::Plain)` — `/iris`.
|
||||||
|
- **QUIC**: `Some(AstralaneTransport::Quic)` — regional `host:7000` / `:9000` (MEV); same API key.
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 🔧 Middleware System
|
### 🔧 Middleware System
|
||||||
@@ -273,6 +324,35 @@ Address Lookup Tables (ALT) allow you to optimize transaction size and reduce fe
|
|||||||
|
|
||||||
Use Durable Nonce to implement transaction replay protection and optimize transaction processing. For detailed information, see the [Durable Nonce Guide](docs/NONCE_CACHE.md).
|
Use Durable Nonce to implement transaction replay protection and optimize transaction processing. For detailed information, see the [Durable Nonce Guide](docs/NONCE_CACHE.md).
|
||||||
|
|
||||||
|
## 💰 Cashback Support (PumpFun / PumpSwap)
|
||||||
|
|
||||||
|
PumpFun and PumpSwap support **cashback** for eligible tokens: part of the trading fee can be returned to the user. The SDK **must know** whether the token has cashback enabled so that buy/sell instructions include the correct accounts (e.g. `UserVolumeAccumulator` as remaining account for cashback coins).
|
||||||
|
|
||||||
|
- **When params come from RPC**: If you use `PumpFunParams::from_mint_by_rpc` or `PumpSwapParams::from_pool_address_by_rpc` / `from_mint_by_rpc`, the SDK reads `is_cashback_coin` from chain—no extra step.
|
||||||
|
- **When params come from event/parser**: If you build params from trade events (e.g. [sol-parser-sdk](https://github.com/0xfnzero/sol-parser-sdk)), you **must** pass the cashback flag into the SDK:
|
||||||
|
- **PumpFun**: `PumpFunParams::from_trade(..., is_cashback_coin)` and `PumpFunParams::from_dev_trade(..., is_cashback_coin)` take an `is_cashback_coin` parameter. Set it from the parsed event (e.g. CreateEvent’s `is_cashback_enabled` or BondingCurve’s `is_cashback_coin`).
|
||||||
|
- **PumpSwap**: `PumpSwapParams` has a field `is_cashback_coin`. When constructing params manually (e.g. from pool/trade events), set it from the parsed pool or event data.
|
||||||
|
- 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 event’s `coin_creator_vault_ata` and `coin_creator_vault_authority`.
|
||||||
|
|
||||||
## 🛡️ MEV Protection Services
|
## 🛡️ MEV Protection Services
|
||||||
|
|
||||||
You can apply for a key through the official website: [Community Website](https://fnzero.dev/swqos)
|
You can apply for a key through the official website: [Community Website](https://fnzero.dev/swqos)
|
||||||
@@ -281,10 +361,10 @@ You can apply for a key through the official website: [Community Website](https:
|
|||||||
- **ZeroSlot**: Zero-latency transactions
|
- **ZeroSlot**: Zero-latency transactions
|
||||||
- **Temporal**: Time-sensitive transactions
|
- **Temporal**: Time-sensitive transactions
|
||||||
- **Bloxroute**: Blockchain network acceleration
|
- **Bloxroute**: Blockchain network acceleration
|
||||||
- **FlashBlock**: High-speed transaction execution with API key authentication - [Official Documentation](https://doc.flashblock.trade/)
|
- **FlashBlock**: High-speed transaction execution with API key authentication
|
||||||
- **BlockRazor**: High-speed transaction execution with API key authentication - [Official Documentation](https://blockrazor.gitbook.io/blockrazor/)
|
- **BlockRazor**: High-speed transaction execution with API key authentication
|
||||||
- **Node1**: High-speed transaction execution with API key authentication - [Official Documentation](https://node1.me/docs.html)
|
- **Node1**: High-speed transaction execution with API key authentication
|
||||||
- **Astralane**: Blockchain network acceleration
|
- **Astralane**: Blockchain network acceleration (Binary/Plain HTTP and QUIC; see [Astralane](#astralane-binary--plain--quic) above)
|
||||||
|
|
||||||
## 📁 Project Structure
|
## 📁 Project Structure
|
||||||
|
|
||||||
@@ -317,6 +397,10 @@ MIT License
|
|||||||
- Telegram Group: https://t.me/fnzero_group
|
- Telegram Group: https://t.me/fnzero_group
|
||||||
- Discord: https://discord.gg/vuazbGkqQE
|
- 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
|
## ⚠️ Important Notes
|
||||||
|
|
||||||
1. Test thoroughly before using on mainnet
|
1. Test thoroughly before using on mainnet
|
||||||
|
|||||||
+111
-27
@@ -47,10 +47,12 @@
|
|||||||
- [📋 使用示例](#-使用示例)
|
- [📋 使用示例](#-使用示例)
|
||||||
- [⚡ 交易参数](#-交易参数)
|
- [⚡ 交易参数](#-交易参数)
|
||||||
- [📊 使用示例汇总表格](#-使用示例汇总表格)
|
- [📊 使用示例汇总表格](#-使用示例汇总表格)
|
||||||
- [⚙️ SWQOS 服务配置说明](#️-swqos-服务配置说明)
|
- [⚙️ SWQoS 服务配置说明](#️-swqos-服务配置说明)
|
||||||
|
- [Astralane(Binary / Plain / QUIC)](#astralanebinary--plain--quic)
|
||||||
- [🔧 中间件系统说明](#-中间件系统说明)
|
- [🔧 中间件系统说明](#-中间件系统说明)
|
||||||
- [🔍 地址查找表](#-地址查找表)
|
- [🔍 地址查找表](#-地址查找表)
|
||||||
- [🔍 Nonce 缓存](#-nonce-缓存)
|
- [🔍 Nonce 缓存](#-nonce-缓存)
|
||||||
|
- [💰 Cashback 支持(PumpFun / PumpSwap)](#-cashback-支持pumpfun--pumpswap)
|
||||||
- [🛡️ MEV 保护服务](#️-mev-保护服务)
|
- [🛡️ MEV 保护服务](#️-mev-保护服务)
|
||||||
- [📁 项目结构](#-项目结构)
|
- [📁 项目结构](#-项目结构)
|
||||||
- [📄 许可证](#-许可证)
|
- [📄 许可证](#-许可证)
|
||||||
@@ -59,6 +61,17 @@
|
|||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
|
## 📦 SDK 版本
|
||||||
|
|
||||||
|
本 SDK 提供多种语言版本:
|
||||||
|
|
||||||
|
| 语言 | 仓库 | 描述 |
|
||||||
|
|------|------|------|
|
||||||
|
| **Rust** | [sol-trade-sdk](https://github.com/0xfnzero/sol-trade-sdk) | 超低延迟,零拷贝优化 |
|
||||||
|
| **Node.js** | [sol-trade-sdk-nodejs](https://github.com/0xfnzero/sol-trade-sdk-nodejs) | TypeScript/JavaScript,Node.js 支持 |
|
||||||
|
| **Python** | [sol-trade-sdk-python](https://github.com/0xfnzero/sol-trade-sdk-python) | 原生 async/await 支持 |
|
||||||
|
| **Go** | [sol-trade-sdk-golang](https://github.com/0xfnzero/sol-trade-sdk-golang) | 并发安全,goroutine 支持 |
|
||||||
|
|
||||||
## ✨ 项目特性
|
## ✨ 项目特性
|
||||||
|
|
||||||
1. **PumpFun 交易**: 支持`购买`、`卖出`功能
|
1. **PumpFun 交易**: 支持`购买`、`卖出`功能
|
||||||
@@ -71,6 +84,7 @@
|
|||||||
8. **并发交易**: 同时使用多个 MEV 服务发送交易,最快的成功,其他失败
|
8. **并发交易**: 同时使用多个 MEV 服务发送交易,最快的成功,其他失败
|
||||||
9. **统一交易接口**: 使用统一的交易协议枚举进行交易操作
|
9. **统一交易接口**: 使用统一的交易协议枚举进行交易操作
|
||||||
10. **中间件系统**: 支持自定义指令中间件,可在交易执行前对指令进行修改、添加或移除
|
10. **中间件系统**: 支持自定义指令中间件,可在交易执行前对指令进行修改、添加或移除
|
||||||
|
11. **共享基础设施**: 多钱包可共享同一套 RPC 与 SWQoS 客户端,降低资源占用
|
||||||
|
|
||||||
## 📦 安装
|
## 📦 安装
|
||||||
|
|
||||||
@@ -87,14 +101,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
# 添加到您的 Cargo.toml
|
# 添加到您的 Cargo.toml
|
||||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.4.0" }
|
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.3" }
|
||||||
```
|
```
|
||||||
|
|
||||||
### 使用 crates.io
|
### 使用 crates.io
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
# 添加到您的 Cargo.toml
|
# 添加到您的 Cargo.toml
|
||||||
sol-trade-sdk = "3.4.0"
|
sol-trade-sdk = "4.0.3"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ 使用示例
|
## 🛠️ 使用示例
|
||||||
@@ -103,40 +117,57 @@ sol-trade-sdk = "3.4.0"
|
|||||||
|
|
||||||
#### 1. 创建 TradingClient 实例
|
#### 1. 创建 TradingClient 实例
|
||||||
|
|
||||||
可以参考 [示例:创建 TradingClient 实例](examples/trading_client/src/main.rs)。
|
可参考 [示例:创建 TradingClient 实例](examples/trading_client/src/main.rs)。
|
||||||
|
|
||||||
|
**方式一:简单创建(单钱包)**
|
||||||
```rust
|
```rust
|
||||||
// 钱包
|
// 钱包
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
// RPC 地址
|
// RPC 地址
|
||||||
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
let rpc_url = "https://mainnet.helius-rpc.com/?api-key=xxxxxx".to_string();
|
||||||
let commitment = CommitmentConfig::processed();
|
let commitment = CommitmentConfig::processed();
|
||||||
// 可以配置多个SWQOS服务
|
// 可配置多个 SWQoS 服务
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||||
SwqosConfig::Default(rpc_url.clone()),
|
SwqosConfig::Default(rpc_url.clone()),
|
||||||
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::ZeroSlot("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
// Astralane:第4个参数为 AstralaneTransport — Binary(默认)、Plain(/iris)或 Quic
|
||||||
SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // Binary /irisb
|
||||||
SwqosConfig::FlashBlock("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Astralane(
|
||||||
SwqosConfig::Node1("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
"your_astralane_api_key".to_string(),
|
||||||
SwqosConfig::BlockRazor("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosRegion::Frankfurt,
|
||||||
SwqosConfig::Astralane("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
None,
|
||||||
|
Some(AstralaneTransport::Quic),
|
||||||
|
), // QUIC
|
||||||
];
|
];
|
||||||
// 创建 TradeConfig 实例
|
// 创建 TradeConfig 实例
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // 默认: true - 初始化时检查并创建 WSOL ATA
|
||||||
|
// .use_seed_optimize(true) // 默认: true - ATA 操作启用 seed 优化
|
||||||
|
// .log_enabled(true) // 默认: true - SDK 计时 / SWQOS 日志
|
||||||
|
// .check_min_tip(false) // 默认: false - 过滤低于最低小费的 SWQOS
|
||||||
|
// .swqos_cores_from_end(false) // 默认: false - 将 SWQOS 绑定到末尾 N 个 CPU 核心
|
||||||
|
// .mev_protection(false) // 默认: false - MEV(Astralane QUIC :9000 或 HTTP mev-protect / BlockRazor)
|
||||||
|
.build();
|
||||||
|
|
||||||
// 可选:自定义 WSOL ATA 和 Seed 优化设置
|
// 创建 TradingClient
|
||||||
// let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
|
||||||
// .with_wsol_ata_config(
|
|
||||||
// true, // create_wsol_ata_on_startup: 启动时检查并创建 WSOL ATA(默认: true)
|
|
||||||
// true // use_seed_optimize: 全局启用所有 ATA 操作的 seed 优化(默认: true)
|
|
||||||
// );
|
|
||||||
|
|
||||||
// 创建 TradingClient 客户端
|
|
||||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||||
```
|
```
|
||||||
|
|
||||||
|
**方式二:共享基础设施(多钱包)**
|
||||||
|
|
||||||
|
多钱包场景下可先创建一份基础设施,再复用到多个钱包。参见 [示例:共享基础设施](examples/shared_infrastructure/src/main.rs)。
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// 创建一次基础设施(开销较大)
|
||||||
|
let infra_config = InfrastructureConfig::new(rpc_url, swqos_configs, commitment);
|
||||||
|
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);
|
||||||
|
|
||||||
|
// 基于同一基础设施创建多个客户端(开销小)
|
||||||
|
let client1 = TradingClient::from_infrastructure(Arc::new(payer1), infrastructure.clone(), true);
|
||||||
|
let client2 = TradingClient::from_infrastructure(Arc::new(payer2), infrastructure.clone(), true);
|
||||||
|
```
|
||||||
|
|
||||||
#### 2. 配置 Gas Fee 策略
|
#### 2. 配置 Gas Fee 策略
|
||||||
|
|
||||||
有关 Gas Fee 策略的详细信息,请参阅 [Gas Fee 策略参考手册](docs/GAS_FEE_STRATEGY_CN.md)。
|
有关 Gas Fee 策略的详细信息,请参阅 [Gas Fee 策略参考手册](docs/GAS_FEE_STRATEGY_CN.md)。
|
||||||
@@ -198,6 +229,7 @@ client.buy(buy_params).await?;
|
|||||||
| 描述 | 运行命令 | 源码路径 |
|
| 描述 | 运行命令 | 源码路径 |
|
||||||
|------|---------|----------|
|
|------|---------|----------|
|
||||||
| 创建和配置 TradingClient 实例 | `cargo run --package trading_client` | [examples/trading_client](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/trading_client/src/main.rs) |
|
| 创建和配置 TradingClient 实例 | `cargo run --package trading_client` | [examples/trading_client](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/trading_client/src/main.rs) |
|
||||||
|
| 多钱包共享基础设施 | `cargo run --package shared_infrastructure` | [examples/shared_infrastructure](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/shared_infrastructure/src/main.rs) |
|
||||||
| PumpFun 代币狙击交易 | `cargo run --package pumpfun_sniper_trading` | [examples/pumpfun_sniper_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_sniper_trading/src/main.rs) |
|
| PumpFun 代币狙击交易 | `cargo run --package pumpfun_sniper_trading` | [examples/pumpfun_sniper_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_sniper_trading/src/main.rs) |
|
||||||
| PumpFun 代币跟单交易 | `cargo run --package pumpfun_copy_trading` | [examples/pumpfun_copy_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_copy_trading/src/main.rs) |
|
| PumpFun 代币跟单交易 | `cargo run --package pumpfun_copy_trading` | [examples/pumpfun_copy_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_copy_trading/src/main.rs) |
|
||||||
| PumpSwap 交易操作 | `cargo run --package pumpswap_trading` | [examples/pumpswap_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpswap_trading/src/main.rs) |
|
| PumpSwap 交易操作 | `cargo run --package pumpswap_trading` | [examples/pumpswap_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpswap_trading/src/main.rs) |
|
||||||
@@ -213,16 +245,16 @@ client.buy(buy_params).await?;
|
|||||||
| Seed 优化交易示例 | `cargo run --package seed_trading` | [examples/seed_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/seed_trading/src/main.rs) |
|
| Seed 优化交易示例 | `cargo run --package seed_trading` | [examples/seed_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/seed_trading/src/main.rs) |
|
||||||
| Gas费用策略示例 | `cargo run --package gas_fee_strategy` | [examples/gas_fee_strategy](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/gas_fee_strategy/src/main.rs) |
|
| Gas费用策略示例 | `cargo run --package gas_fee_strategy` | [examples/gas_fee_strategy](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/gas_fee_strategy/src/main.rs) |
|
||||||
|
|
||||||
### ⚙️ SWQOS 服务配置说明
|
### ⚙️ SWQoS 服务配置说明
|
||||||
|
|
||||||
在配置 SWQOS 服务时,需要注意不同服务的参数要求:
|
在配置 SWQoS 服务时,需要注意不同服务的参数要求:
|
||||||
|
|
||||||
- **Jito**: 第一个参数为 UUID(如无 UUID 请传入空字符串 `""`)
|
- **Jito**: 第一个参数为 UUID(如无 UUID 请传入空字符串 `""`)
|
||||||
- 其他的MEV服务,第一个参数为 API Token
|
- 其他的MEV服务,第一个参数为 API Token
|
||||||
|
|
||||||
#### 自定义 URL 支持
|
#### 自定义 URL 支持
|
||||||
|
|
||||||
每个 SWQOS 服务现在都支持可选的自定义 URL 参数:
|
每个 SWQoS 服务现在都支持可选的自定义 URL 参数:
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
// 使用自定义 URL(第三个参数)
|
// 使用自定义 URL(第三个参数)
|
||||||
@@ -247,6 +279,29 @@ let bloxroute_config = SwqosConfig::Bloxroute(
|
|||||||
|
|
||||||
当使用多个MEV服务时,需要使用`Durable Nonce`。你需要使用`fetch_nonce_info`函数获取最新的`nonce`值,并在交易的时候将`durable_nonce`填入交易参数。
|
当使用多个MEV服务时,需要使用`Durable Nonce`。你需要使用`fetch_nonce_info`函数获取最新的`nonce`值,并在交易的时候将`durable_nonce`填入交易参数。
|
||||||
|
|
||||||
|
#### Astralane(Binary / Plain / QUIC)
|
||||||
|
|
||||||
|
Astralane 支持 **Binary** HTTP(`/irisb`)、**Plain** HTTP(`/iris`)与 **QUIC**(`host:7000`,全局 `mev_protection` 为 true 时用 `:9000`)。第四个参数:`Some(AstralaneTransport::Plain)`、`Some(AstralaneTransport::Quic)`,或 `None` 表示 **Binary**(默认)。全局 `mev_protection` 会在 HTTP 上附加 `mev-protect=true`,或为 QUIC 选择 9000 端口。
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use sol_trade_sdk::{SwqosConfig, SwqosRegion, AstralaneTransport};
|
||||||
|
|
||||||
|
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||||
|
SwqosConfig::Default(rpc_url.clone()),
|
||||||
|
SwqosConfig::Astralane(
|
||||||
|
"your_astralane_api_key".to_string(),
|
||||||
|
SwqosRegion::Frankfurt,
|
||||||
|
None,
|
||||||
|
Some(AstralaneTransport::Quic),
|
||||||
|
),
|
||||||
|
];
|
||||||
|
// 然后照常使用 swqos_configs 创建 TradeConfig / TradingClient
|
||||||
|
```
|
||||||
|
|
||||||
|
- **Binary**(默认):`None` 或 `Some(AstralaneTransport::Binary)` — `/irisb`,bincode 正文。
|
||||||
|
- **Plain**:`Some(AstralaneTransport::Plain)` — `/iris`。
|
||||||
|
- **QUIC**:`Some(AstralaneTransport::Quic)` — 按区域的 `host:7000` / `:9000`(MEV);同一 API key。
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
### 🔧 中间件系统说明
|
### 🔧 中间件系统说明
|
||||||
@@ -268,6 +323,35 @@ let middleware_manager = MiddlewareManager::new()
|
|||||||
|
|
||||||
使用 Durable Nonce 来实现交易重放保护和优化交易处理。详细信息请参阅 [Nonce 使用指南](docs/NONCE_CACHE_CN.md)。
|
使用 Durable Nonce 来实现交易重放保护和优化交易处理。详细信息请参阅 [Nonce 使用指南](docs/NONCE_CACHE_CN.md)。
|
||||||
|
|
||||||
|
## 💰 Cashback 支持(PumpFun / PumpSwap)
|
||||||
|
|
||||||
|
PumpFun 与 PumpSwap 支持**返现(Cashback)**:部分手续费可返还给用户。SDK **必须知道**该代币是否开启返现,才能为 buy/sell 指令传入正确的账户(例如返现代币需要把 `UserVolumeAccumulator` 作为 remaining account)。
|
||||||
|
|
||||||
|
- **参数来自 RPC 时**:使用 `PumpFunParams::from_mint_by_rpc` 或 `PumpSwapParams::from_pool_address_by_rpc` / `from_mint_by_rpc` 时,SDK 会从链上读取 `is_cashback_coin`,无需额外传入。
|
||||||
|
- **参数来自事件/解析器时**:若根据交易事件(如 [sol-parser-sdk](https://github.com/0xfnzero/sol-parser-sdk))构建参数,**必须**把返现标志传给 SDK:
|
||||||
|
- **PumpFun**:`PumpFunParams::from_trade(..., is_cashback_coin)` 与 `PumpFunParams::from_dev_trade(..., is_cashback_coin)` 最后一个参数为 `is_cashback_coin`。从解析出的事件传入(如 sol-parser-sdk 的 `PumpFunTradeEvent.is_cashback_coin`)。
|
||||||
|
- **PumpSwap**:`PumpSwapParams` 有字段 `is_cashback_coin`。手动构造参数(如从池/交易事件)时,从解析到的池或事件数据中设置该字段。
|
||||||
|
- **pumpfun_copy_trading**、**pumpfun_sniper_trading** 示例使用 sol-parser-sdk 订阅 gRPC 事件,并在构造参数时传入 `e.is_cashback_coin`。
|
||||||
|
- **领取返现**:使用 `client.claim_cashback_pumpfun()` 和 `client.claim_cashback_pumpswap(...)` 领取累计的返现。
|
||||||
|
|
||||||
|
#### PumpFun:Creator Rewards Sharing(creator_vault)
|
||||||
|
|
||||||
|
部分 PumpFun 代币启用了 **Creator Rewards Sharing**,链上 `creator_vault` 可能与默认推导结果不同。若在**卖出**时复用**买入**时缓存的 params,可能触发程序错误 **2006(seeds constraint violated)**。建议:
|
||||||
|
|
||||||
|
- **来自 gRPC/事件(无需 RPC)**:`creator` 与 `creator_vault` 均可从解析后的事件中直接拿到:
|
||||||
|
- **sol-parser-sdk**:推送前会调用 `fill_trade_accounts`,从 buy/sell 指令账户补全 `creator_vault`(buy 索引 9,sell 索引 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 保护服务
|
## 🛡️ MEV 保护服务
|
||||||
|
|
||||||
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
|
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
|
||||||
@@ -276,10 +360,10 @@ let middleware_manager = MiddlewareManager::new()
|
|||||||
- **ZeroSlot**: 零延迟交易
|
- **ZeroSlot**: 零延迟交易
|
||||||
- **Temporal**: 时间敏感交易
|
- **Temporal**: 时间敏感交易
|
||||||
- **Bloxroute**: 区块链网络加速
|
- **Bloxroute**: 区块链网络加速
|
||||||
- **FlashBlock**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://doc.flashblock.trade/)
|
- **FlashBlock**: 高速交易执行,支持 API 密钥认证
|
||||||
- **BlockRazor**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://blockrazor.gitbook.io/blockrazor/)
|
- **BlockRazor**: 高速交易执行,支持 API 密钥认证
|
||||||
- **Node1**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://node1.me/docs.html)
|
- **Node1**: 高速交易执行,支持 API 密钥认证
|
||||||
- **Astralane**: 高速交易执行,支持 API 密钥认证
|
- **Astralane**: 区块链网络加速(Binary/Plain HTTP 与 QUIC,见 [Astralane](#astralanebinary--plain--quic))
|
||||||
|
|
||||||
## 📁 项目结构
|
## 📁 项目结构
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,19 @@
|
|||||||
|
## sol-trade-sdk v4.0.2
|
||||||
|
|
||||||
|
This release focuses on QUIC reliability and low-latency submission stability for Astralane.
|
||||||
|
|
||||||
|
### Highlights
|
||||||
|
|
||||||
|
- Fixed Astralane QUIC address-family mismatch that could produce `invalid remote address` when DNS returned IPv6 first and local endpoint was IPv4-only.
|
||||||
|
- Added remote-family-aware local QUIC bind selection:
|
||||||
|
- IPv4 remote -> bind `0.0.0.0:0`
|
||||||
|
- IPv6 remote -> bind `[::]:0`
|
||||||
|
- Added Astralane direct-IP candidate support (official region IPs), with IPv4-first selection for better QUIC stability.
|
||||||
|
- Added automatic endpoint failover and reconnect rotation across candidate addresses, reducing single-endpoint/DNS variance impact.
|
||||||
|
- Kept existing SDK interfaces compatible while improving submit-path resiliency.
|
||||||
|
|
||||||
|
### Also included from recent updates
|
||||||
|
|
||||||
|
- BlockRazor gRPC endpoint fixes and gRPC default transport behavior improvements (v4.0.1).
|
||||||
|
- SWQOS transport path hardening and Binary-Tx response handling improvements (v4.0.0).
|
||||||
|
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
{
|
||||||
|
"url": "https://context7.com/0xfnzero/sol-trade-sdk",
|
||||||
|
"public_key": "pk_ShleAZazFTUV8ORpmH4jy"
|
||||||
|
}
|
||||||
@@ -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` | 110–116, 148–152 | `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` 约 179–181 行 | `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 账户数 | 16(fill 用 get(9) 填 creator_vault) | 16,accounts[9]=creator_vault | 与 idl/pumpfun.json 一致 |
|
||||||
|
| Pump sell 账户数 | 14(get(8)=creator_vault) | 14,accounts[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 同左 | 同左 | 一致 |
|
||||||
|
| 填充顺序 | 先 parse(log 或 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` 179–181 行 |
|
||||||
|
| 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 或链上程序有未公开变更,建议再与官方实现或链上行为做一次对照验证。*
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
# Pump Cashback 集成说明
|
||||||
|
|
||||||
|
本 SDK 已支持 [Pump Cashback Rewards](https://github.com/pump-fun/pump-public-docs/blob/main/docs/PUMP_CASHBACK_README.md):在启用 cashback 的币种上交易时,用户可获得手续费返还而非支付给创作者。
|
||||||
|
|
||||||
|
## 行为概览
|
||||||
|
|
||||||
|
- **Bonding Curve (Pump)**
|
||||||
|
- **Buy**:无需改指令,若币种启用 cashback 会自动累计。
|
||||||
|
- **Sell**:当 `bonding_curve.is_cashback_coin == true` 时,SDK 会在指令中追加 `UserVolumeAccumulator` PDA(remaining account),用于累计可领取的 cashback。
|
||||||
|
- **Pump Swap**
|
||||||
|
- **Buy**:当 `PumpSwapParams.is_cashback_coin == true` 时,会追加 UserVolumeAccumulator 的 **WSOL ATA** 作为 remaining account。
|
||||||
|
- **Sell**:当 `is_cashback_coin == true` 时,会追加 **WSOL ATA**(0th)和 **UserVolumeAccumulator PDA**(1st)作为 remaining accounts。
|
||||||
|
|
||||||
|
`PumpFunParams` 通过 `from_mint_by_rpc` 拉取 bonding curve 时会解析链上 `is_cashback_coin`;`PumpSwapParams` 通过 `from_pool_address_by_rpc` / `from_mint_by_rpc` 拉取 pool 时会解析 `is_cashback_coin`。
|
||||||
|
|
||||||
|
## 领取 Cashback
|
||||||
|
|
||||||
|
### 推荐:使用 TradingClient 一键领取
|
||||||
|
|
||||||
|
若已有 `TradingClient`(例如用于买卖的同一个客户端),可直接调用以下方法,内部会完成构建交易、签名与发送:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
// 领取 Pump 曲线产生的 Cashback(到账为 native SOL)
|
||||||
|
let sig = client.claim_cashback_pumpfun().await?;
|
||||||
|
|
||||||
|
// 领取 PumpSwap 产生的 Cashback(到账为 WSOL,自动确保用户 WSOL ATA 存在)
|
||||||
|
let sig = client.claim_cashback_pumpswap().await?;
|
||||||
|
```
|
||||||
|
|
||||||
|
- **`claim_cashback_pumpfun()`**:领取 Bonding Curve (Pump) 的返还,到账为钱包 SOL。
|
||||||
|
- **`claim_cashback_pumpswap()`**:领取 PumpSwap (AMM) 的返还,到账为用户的 WSOL ATA;若用户尚无 WSOL ATA 会先自动创建再领取。
|
||||||
|
|
||||||
|
### 仅构建指令(自行组交易时使用)
|
||||||
|
|
||||||
|
#### Bonding Curve (Pump)
|
||||||
|
|
||||||
|
将 native lamports 从 UserVolumeAccumulator 转到用户钱包:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use sol_trade_sdk::instruction::pumpfun;
|
||||||
|
|
||||||
|
let ix = pumpfun::claim_cashback_pumpfun_instruction(&payer.pubkey());
|
||||||
|
// 将 ix 放入交易并发送
|
||||||
|
```
|
||||||
|
|
||||||
|
#### Pump Swap (AMM)
|
||||||
|
|
||||||
|
将 WSOL 从 UserVolumeAccumulator 的 WSOL ATA 转到用户的 WSOL ATA。**调用前需确保用户 WSOL ATA 已存在**(或使用上面的 `claim_cashback_pumpswap()` 会自动处理):
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use sol_trade_sdk::instruction::pumpswap;
|
||||||
|
use sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
|
use sol_trade_sdk::constants::TOKEN_PROGRAM;
|
||||||
|
|
||||||
|
let ix = pumpswap::claim_cashback_pumpswap_instruction(
|
||||||
|
&payer.pubkey(),
|
||||||
|
WSOL_TOKEN_ACCOUNT,
|
||||||
|
TOKEN_PROGRAM,
|
||||||
|
);
|
||||||
|
```
|
||||||
|
|
||||||
|
## 读取未领取金额
|
||||||
|
|
||||||
|
- **Pump (Bonding Curve)**:读 Pump 程序的 `UserVolumeAccumulator` PDA 的 lamports,减去维持账户所需的 rent-exempt 金额,即为未领取 cashback(lamports)。
|
||||||
|
- **Pump Swap**:读 Pump AMM 程序的 UserVolumeAccumulator 的 **WSOL ATA** 的 token balance,即为未领取 cashback(WSOL 数量)。
|
||||||
|
|
||||||
|
PDA 推导(本 SDK 已实现):
|
||||||
|
|
||||||
|
- Pump:`instruction::utils::pumpfun::get_user_volume_accumulator_pda(user)`
|
||||||
|
- Pump AMM:`instruction::utils::pumpswap::get_user_volume_accumulator_pda(user)`,WSOL ATA:`instruction::utils::pumpswap::get_user_volume_accumulator_wsol_ata(user)`
|
||||||
|
|
||||||
|
## IDL 来源
|
||||||
|
|
||||||
|
根目录 `idl/` 下的 `pump.json`、`pump_amm.json`、`pump_fees.json` 从 [pump-fun/pump-public-docs](https://github.com/pump-fun/pump-public-docs) 的 `idl` 目录同步,便于与官方 IDL 对照和后续升级。
|
||||||
@@ -30,7 +30,7 @@ The `TradeBuyParams` struct contains all parameters required for executing buy o
|
|||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
|-----------|------|----------|-------------|
|
|-----------|------|----------|-------------|
|
||||||
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | Address lookup table for transaction optimization |
|
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | Address lookup table for transaction optimization |
|
||||||
| `wait_transaction_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
| `wait_tx_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||||
| `create_input_token_ata` | `bool` | ✅ | Whether to create input token Associated Token Account |
|
| `create_input_token_ata` | `bool` | ✅ | Whether to create input token Associated Token Account |
|
||||||
| `close_input_token_ata` | `bool` | ✅ | Whether to close input token ATA after transaction |
|
| `close_input_token_ata` | `bool` | ✅ | Whether to close input token ATA after transaction |
|
||||||
| `create_mint_ata` | `bool` | ✅ | Whether to create token mint ATA |
|
| `create_mint_ata` | `bool` | ✅ | Whether to create token mint ATA |
|
||||||
@@ -62,7 +62,7 @@ The `TradeSellParams` struct contains all parameters required for executing sell
|
|||||||
| Parameter | Type | Required | Description |
|
| Parameter | Type | Required | Description |
|
||||||
|-----------|------|----------|-------------|
|
|-----------|------|----------|-------------|
|
||||||
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | Address lookup table for transaction optimization |
|
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | Address lookup table for transaction optimization |
|
||||||
| `wait_transaction_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
| `wait_tx_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||||
| `create_output_token_ata` | `bool` | ✅ | Whether to create output token Associated Token Account |
|
| `create_output_token_ata` | `bool` | ✅ | Whether to create output token Associated Token Account |
|
||||||
| `close_output_token_ata` | `bool` | ✅ | Whether to close output token ATA after transaction |
|
| `close_output_token_ata` | `bool` | ✅ | Whether to close output token ATA after transaction |
|
||||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce information containing nonce account and current nonce value |
|
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce information containing nonce account and current nonce value |
|
||||||
@@ -88,7 +88,7 @@ These parameters are essential for defining the basic trading operation:
|
|||||||
These parameters control how the transaction is processed:
|
These parameters control how the transaction is processed:
|
||||||
|
|
||||||
- **slippage_basis_points**: Controls acceptable price slippage
|
- **slippage_basis_points**: Controls acceptable price slippage
|
||||||
- **wait_transaction_confirmed**: Controls whether to wait for confirmation
|
- **wait_tx_confirmed**: Controls whether to wait for confirmation
|
||||||
|
|
||||||
### 🔧 Account Management Parameters
|
### 🔧 Account Management Parameters
|
||||||
|
|
||||||
|
|||||||
@@ -30,7 +30,7 @@
|
|||||||
| 参数 | 类型 | 必需 | 描述 |
|
| 参数 | 类型 | 必需 | 描述 |
|
||||||
|------|------|------|------|
|
|------|------|------|------|
|
||||||
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | 用于交易优化的地址查找表 |
|
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | 用于交易优化的地址查找表 |
|
||||||
| `wait_transaction_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
| `wait_tx_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||||
| `create_input_token_ata` | `bool` | ✅ | 是否创建输入代币关联代币账户 |
|
| `create_input_token_ata` | `bool` | ✅ | 是否创建输入代币关联代币账户 |
|
||||||
| `close_input_token_ata` | `bool` | ✅ | 交易后是否关闭输入代币 ATA |
|
| `close_input_token_ata` | `bool` | ✅ | 交易后是否关闭输入代币 ATA |
|
||||||
| `create_mint_ata` | `bool` | ✅ | 是否创建代币 mint ATA |
|
| `create_mint_ata` | `bool` | ✅ | 是否创建代币 mint ATA |
|
||||||
@@ -62,7 +62,7 @@
|
|||||||
| 参数 | 类型 | 必需 | 描述 |
|
| 参数 | 类型 | 必需 | 描述 |
|
||||||
|------|------|------|------|
|
|------|------|------|------|
|
||||||
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | 用于交易优化的地址查找表 |
|
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | 用于交易优化的地址查找表 |
|
||||||
| `wait_transaction_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
| `wait_tx_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||||
| `create_output_token_ata` | `bool` | ✅ | 是否创建输出代币关联代币账户 |
|
| `create_output_token_ata` | `bool` | ✅ | 是否创建输出代币关联代币账户 |
|
||||||
| `close_output_token_ata` | `bool` | ✅ | 交易后是否关闭输出代币 ATA |
|
| `close_output_token_ata` | `bool` | ✅ | 交易后是否关闭输出代币 ATA |
|
||||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | 持久 nonce 信息,包含 nonce 账户和当前 nonce 值 |
|
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | 持久 nonce 信息,包含 nonce 账户和当前 nonce 值 |
|
||||||
@@ -88,7 +88,7 @@
|
|||||||
这些参数控制交易的处理方式:
|
这些参数控制交易的处理方式:
|
||||||
|
|
||||||
- **slippage_basis_points**: 控制可接受的价格滑点
|
- **slippage_basis_points**: 控制可接受的价格滑点
|
||||||
- **wait_transaction_confirmed**: 控制是否等待确认
|
- **wait_tx_confirmed**: 控制是否等待确认
|
||||||
|
|
||||||
### 🔧 账户管理参数
|
### 🔧 账户管理参数
|
||||||
|
|
||||||
|
|||||||
@@ -5,9 +5,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sol-trade-sdk = { path = "../.." }
|
sol-trade-sdk = { path = "../.." }
|
||||||
solana-streamer-sdk = "0.5.0"
|
sol-parser-sdk = "0.2.2"
|
||||||
solana-sdk = "3.0.0"
|
solana-sdk = "3.0.0"
|
||||||
solana-address-lookup-table-interface = "3.0.0"
|
|
||||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
anyhow = "1.0.94"
|
|
||||||
|
|||||||
@@ -1,22 +1,3 @@
|
|||||||
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::AnyResult,
|
|
||||||
swqos::SwqosConfig,
|
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
|
||||||
SolanaTrade,
|
|
||||||
};
|
|
||||||
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::{
|
use std::{
|
||||||
str::FromStr,
|
str::FromStr,
|
||||||
sync::{
|
sync::{
|
||||||
@@ -25,94 +6,126 @@ use std::{
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Global static flag to ensure transaction is executed only once
|
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::{GasFeeStrategy, TradeConfig};
|
||||||
|
use sol_trade_sdk::{
|
||||||
|
common::AnyResult,
|
||||||
|
swqos::SwqosConfig,
|
||||||
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
|
SolanaTrade,
|
||||||
|
};
|
||||||
|
use solana_commitment_config::CommitmentConfig;
|
||||||
|
use solana_sdk::pubkey::Pubkey;
|
||||||
|
use solana_sdk::signature::Keypair;
|
||||||
|
|
||||||
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
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(
|
let config = ClientConfig {
|
||||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
enable_metrics: false,
|
||||||
None,
|
connection_timeout_ms: 10000,
|
||||||
)?;
|
request_timeout_ms: 30000,
|
||||||
|
enable_tls: true,
|
||||||
let callback = create_event_callback();
|
order_mode: OrderMode::Unordered,
|
||||||
let protocols = vec![Protocol::PumpFun];
|
..Default::default()
|
||||||
// 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,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Listen to account data belonging to owner programs -> account event monitoring
|
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
|
||||||
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
|
.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 protocols = vec![Protocol::PumpFun];
|
||||||
let event_type_filter =
|
let transaction_filter = TransactionFilter::for_protocols(&protocols);
|
||||||
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
|
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(
|
let queue = grpc
|
||||||
protocols,
|
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||||
None,
|
.await?;
|
||||||
vec![transaction_filter],
|
|
||||||
vec![account_filter],
|
loop {
|
||||||
Some(event_type_filter),
|
if let Some(event) = queue.pop() {
|
||||||
None,
|
let run = match &event {
|
||||||
callback,
|
DexEvent::PumpFunBuy(e)
|
||||||
)
|
| DexEvent::PumpFunSell(e)
|
||||||
.await?;
|
| 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?;
|
tokio::signal::ctrl_c().await?;
|
||||||
|
|
||||||
Ok(())
|
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> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
println!("🚀 Initializing SolanaTrade client...");
|
println!("🚀 Initializing SolanaTrade client...");
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PumpFun sniper trade
|
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
|
||||||
/// This function demonstrates how to snipe a new token from a PumpFun trade event
|
async fn pumpfun_copy_trade_with_grpc(
|
||||||
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
|
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||||
|
) -> AnyResult<()> {
|
||||||
println!("Testing PumpFun trading...");
|
println!("Testing PumpFun trading...");
|
||||||
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
@@ -122,20 +135,20 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
|
|
||||||
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
||||||
let address_lookup_table_account =
|
let address_lookup_table_account =
|
||||||
fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key).await.ok();
|
fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key)
|
||||||
|
.await
|
||||||
|
.ok();
|
||||||
|
|
||||||
let gas_fee_strategy = GasFeeStrategy::new();
|
let gas_fee_strategy = GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|
||||||
// Buy tokens
|
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
|
||||||
println!("Buying tokens from PumpFun...");
|
|
||||||
let buy_sol_amount = 100_000;
|
|
||||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
input_token_type: sol_trade_sdk::TradeTokenType::SOL,
|
input_token_type: sol_trade_sdk::TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: buy_sol_amount,
|
input_token_amount: 100_000,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||||
trade_info.bonding_curve,
|
trade_info.bonding_curve,
|
||||||
@@ -143,27 +156,29 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
trade_info.mint,
|
trade_info.mint,
|
||||||
trade_info.creator,
|
trade_info.creator,
|
||||||
trade_info.creator_vault,
|
trade_info.creator_vault,
|
||||||
trade_info.virtual_sol_reserves,
|
trade_info.virtual_token_reserves,
|
||||||
trade_info.virtual_sol_reserves,
|
trade_info.virtual_sol_reserves,
|
||||||
trade_info.real_token_reserves,
|
trade_info.real_token_reserves,
|
||||||
trade_info.real_sol_reserves,
|
trade_info.real_sol_reserves,
|
||||||
None,
|
None,
|
||||||
trade_info.fee_recipient,
|
trade_info.fee_recipient,
|
||||||
trade_info.token_program,
|
trade_info.token_program,
|
||||||
|
trade_info.is_cashback_coin,
|
||||||
|
Some(trade_info.mayhem_mode),
|
||||||
)),
|
)),
|
||||||
address_lookup_table_account: address_lookup_table_account,
|
address_lookup_table_account,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
create_input_token_ata: false,
|
create_input_token_ata: false,
|
||||||
close_input_token_ata: false,
|
close_input_token_ata: false,
|
||||||
create_mint_ata: true,
|
create_mint_ata: true,
|
||||||
durable_nonce: None,
|
durable_nonce: None,
|
||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
// Exit program
|
|
||||||
std::process::exit(0);
|
std::process::exit(0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ use sol_trade_sdk::common::{
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{BonkParams, DexParamEnum},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -110,7 +113,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
@@ -127,14 +137,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = GasFeeStrategy::new();
|
let gas_fee_strategy = GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buy tokens
|
// Buy tokens
|
||||||
println!("Buying tokens from Bonk...");
|
println!("Buying tokens from Bonk...");
|
||||||
@@ -176,6 +179,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -226,6 +230,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::common::TradeConfig;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{BonkParams, DexParamEnum},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -78,7 +81,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
@@ -95,14 +105,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
let token_type = if trade_info.quote_token_mint == sol_trade_sdk::constants::USD1_TOKEN_ACCOUNT
|
let token_type = if trade_info.quote_token_mint == sol_trade_sdk::constants::USD1_TOKEN_ACCOUNT
|
||||||
{
|
{
|
||||||
@@ -144,6 +147,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -187,6 +191,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ use sol_trade_sdk::{
|
|||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{
|
trading::{
|
||||||
core::params::{
|
core::params::{
|
||||||
BonkParams, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params, RaydiumCpmmParams, DexParamEnum,
|
BonkParams, DexParamEnum, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params,
|
||||||
|
RaydiumCpmmParams,
|
||||||
},
|
},
|
||||||
factory::DexType,
|
factory::DexType,
|
||||||
},
|
},
|
||||||
@@ -531,7 +532,7 @@ async fn handle_buy(
|
|||||||
|
|
||||||
let client = initialize_real_client().await?;
|
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?;
|
check_mint_ata(&client, mint).await?;
|
||||||
|
|
||||||
match dex {
|
match dex {
|
||||||
@@ -565,7 +566,7 @@ async fn handle_buy_rv4(
|
|||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
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?;
|
check_mint_ata(&client, mint).await?;
|
||||||
handle_buy_raydium_v4(mint, amm, sol_amount, slippage, create_mint_ata, use_seed, owner_pubkey)
|
handle_buy_raydium_v4(mint, amm, sol_amount, slippage, create_mint_ata, use_seed, owner_pubkey)
|
||||||
.await?;
|
.await?;
|
||||||
@@ -579,7 +580,7 @@ async fn handle_buy_rcpmm(
|
|||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
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?;
|
check_mint_ata(&client, mint).await?;
|
||||||
handle_buy_raydium_cpmm(
|
handle_buy_raydium_cpmm(
|
||||||
mint,
|
mint,
|
||||||
@@ -599,8 +600,8 @@ async fn handle_buy_pumpfun(
|
|||||||
sol_amount: f64,
|
sol_amount: f64,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("🔥 BUY PUMPFUN COMMAND");
|
println!("🔥 BUY PUMPFUN COMMAND");
|
||||||
println!(" Token Mint: {}", mint);
|
println!(" Token Mint: {}", mint);
|
||||||
@@ -635,6 +636,7 @@ async fn handle_buy_pumpfun(
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.buy(buy_params).await {
|
match client.buy(buy_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -654,7 +656,7 @@ async fn handle_buy_pumpswap(
|
|||||||
sol_amount: f64,
|
sol_amount: f64,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
_owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
@@ -690,6 +692,7 @@ async fn handle_buy_pumpswap(
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.buy(buy_params).await {
|
match client.buy(buy_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -708,8 +711,8 @@ async fn handle_buy_bonk(
|
|||||||
sol_amount: f64,
|
sol_amount: f64,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
println!("🔥 BUY BONK COMMAND");
|
println!("🔥 BUY BONK COMMAND");
|
||||||
@@ -719,7 +722,8 @@ async fn handle_buy_bonk(
|
|||||||
println!(" Slippage: {}%", slippage.unwrap());
|
println!(" Slippage: {}%", slippage.unwrap());
|
||||||
}
|
}
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
let param =
|
||||||
|
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -744,6 +748,7 @@ async fn handle_buy_bonk(
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.buy(buy_params).await {
|
match client.buy(buy_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -763,8 +768,8 @@ async fn handle_buy_raydium_v4(
|
|||||||
sol_amount: f64,
|
sol_amount: f64,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
println!("🔥 BUY RAYDIUM V4 COMMAND");
|
println!("🔥 BUY RAYDIUM V4 COMMAND");
|
||||||
@@ -777,7 +782,8 @@ async fn handle_buy_raydium_v4(
|
|||||||
|
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
let param =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -802,6 +808,7 @@ async fn handle_buy_raydium_v4(
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.buy(buy_params).await {
|
match client.buy(buy_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -821,8 +828,8 @@ async fn handle_buy_raydium_cpmm(
|
|||||||
sol_amount: f64,
|
sol_amount: f64,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
println!("🔥 BUY RAYDIUM CPMM COMMAND");
|
println!("🔥 BUY RAYDIUM CPMM COMMAND");
|
||||||
@@ -835,7 +842,9 @@ async fn handle_buy_raydium_cpmm(
|
|||||||
|
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
let param =
|
||||||
|
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||||
|
.await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -860,6 +869,7 @@ async fn handle_buy_raydium_cpmm(
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.buy(buy_params).await {
|
match client.buy(buy_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -987,11 +997,11 @@ async fn handle_sell_pumpfun(
|
|||||||
mint: &str,
|
mint: &str,
|
||||||
token_amount: Option<f64>,
|
token_amount: Option<f64>,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
_create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
amount_f64: f64,
|
amount_f64: f64,
|
||||||
decimals: u8,
|
_decimals: u8,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||||
|
|
||||||
@@ -1028,6 +1038,7 @@ async fn handle_sell_pumpfun(
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
|
|
||||||
match client.sell(sell_params).await {
|
match client.sell(sell_params).await {
|
||||||
@@ -1047,11 +1058,11 @@ async fn handle_sell_pumpswap(
|
|||||||
mint: &str,
|
mint: &str,
|
||||||
token_amount: Option<f64>,
|
token_amount: Option<f64>,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
_create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
amount_f64: f64,
|
amount_f64: f64,
|
||||||
decimals: u8,
|
_decimals: u8,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||||
@@ -1086,11 +1097,12 @@ async fn handle_sell_pumpswap(
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.sell(sell_params).await {
|
match client.sell(sell_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
println!(" ✅ Successfully sold tokens from PumpSwap!");
|
println!(" ✅ Successfully sold tokens from PumpSwap!");
|
||||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" ❌ Failed to sell tokens from PumpSwap: {}", e);
|
println!(" ❌ Failed to sell tokens from PumpSwap: {}", e);
|
||||||
@@ -1104,11 +1116,11 @@ async fn handle_sell_bonk(
|
|||||||
mint: &str,
|
mint: &str,
|
||||||
token_amount: Option<f64>,
|
token_amount: Option<f64>,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
_create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
amount_f64: f64,
|
amount_f64: f64,
|
||||||
decimals: u8,
|
_decimals: u8,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||||
@@ -1119,7 +1131,8 @@ async fn handle_sell_bonk(
|
|||||||
}
|
}
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
let param =
|
||||||
|
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
@@ -1143,6 +1156,7 @@ async fn handle_sell_bonk(
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.sell(sell_params).await {
|
match client.sell(sell_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -1162,11 +1176,11 @@ async fn handle_sell_raydium_v4(
|
|||||||
mint: &str,
|
mint: &str,
|
||||||
token_amount: Option<f64>,
|
token_amount: Option<f64>,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
_create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
amount_f64: f64,
|
amount_f64: f64,
|
||||||
decimals: u8,
|
_decimals: u8,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||||
println!("🔥 SELL RAYDIUM V4 COMMAND");
|
println!("🔥 SELL RAYDIUM V4 COMMAND");
|
||||||
@@ -1179,7 +1193,8 @@ async fn handle_sell_raydium_v4(
|
|||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
let param =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
@@ -1203,6 +1218,7 @@ async fn handle_sell_raydium_v4(
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.sell(sell_params).await {
|
match client.sell(sell_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -1222,11 +1238,11 @@ async fn handle_sell_raydium_cpmm(
|
|||||||
pool_address: &str,
|
pool_address: &str,
|
||||||
token_amount: Option<f64>,
|
token_amount: Option<f64>,
|
||||||
slippage: Option<u64>,
|
slippage: Option<u64>,
|
||||||
create_mint_ata: bool,
|
_create_mint_ata: bool,
|
||||||
use_seed: bool,
|
_use_seed: bool,
|
||||||
owner_pubkey: Pubkey,
|
_owner_pubkey: Pubkey,
|
||||||
amount_f64: f64,
|
amount_f64: f64,
|
||||||
decimals: u8,
|
_decimals: u8,
|
||||||
) -> Result<(), Box<dyn std::error::Error>> {
|
) -> Result<(), Box<dyn std::error::Error>> {
|
||||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||||
println!("🔥 SELL RAYDIUM CPMM COMMAND");
|
println!("🔥 SELL RAYDIUM CPMM COMMAND");
|
||||||
@@ -1239,7 +1255,9 @@ async fn handle_sell_raydium_cpmm(
|
|||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
let param =
|
||||||
|
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||||
|
.await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
@@ -1263,6 +1281,7 @@ async fn handle_sell_raydium_cpmm(
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
match client.sell(sell_params).await {
|
match client.sell(sell_params).await {
|
||||||
Ok((_, signature, _)) => {
|
Ok((_, signature, _)) => {
|
||||||
@@ -1373,7 +1392,14 @@ async fn initialize_real_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = RPC_URL.to_string();
|
let rpc_url = RPC_URL.to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(payer, trade_config).await;
|
let solana_trade = SolanaTrade::new(payer, trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
SolanaTrade, TradeTokenType, common::{
|
common::{
|
||||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
}, swqos::SwqosConfig, trading::{core::params::{MeteoraDammV2Params, DexParamEnum}, factory::DexType}
|
},
|
||||||
|
swqos::SwqosConfig,
|
||||||
|
trading::{
|
||||||
|
core::params::{DexParamEnum, MeteoraDammV2Params},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
@@ -32,7 +38,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points: slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::MeteoraDammV2(
|
extension_params: DexParamEnum::MeteoraDammV2(
|
||||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -44,6 +51,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -53,7 +61,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM;
|
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM;
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
println!("Token balance: {}", amount_token);
|
println!("Token balance: {}", amount_token);
|
||||||
@@ -66,7 +79,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
with_tip: false,
|
with_tip: false,
|
||||||
extension_params: DexParamEnum::MeteoraDammV2(
|
extension_params: DexParamEnum::MeteoraDammV2(
|
||||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -77,6 +91,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
fixed_output_token_amount: Some(1),
|
fixed_output_token_amount: Some(1),
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
@@ -92,7 +107,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
|
|||||||
@@ -1,9 +1,10 @@
|
|||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::{AnyResult, TradeConfig},
|
common::{AnyResult, TradeConfig},
|
||||||
swqos::{SwqosConfig, SwqosRegion},
|
swqos::SwqosConfig,
|
||||||
trading::{
|
trading::{
|
||||||
core::params::{PumpSwapParams, DexParamEnum}, factory::DexType, middleware::builtin::LoggingMiddleware,
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
InstructionMiddleware, MiddlewareManager,
|
InstructionMiddleware, MiddlewareManager,
|
||||||
},
|
},
|
||||||
SolanaTrade, TradeTokenType,
|
SolanaTrade, TradeTokenType,
|
||||||
@@ -30,8 +31,8 @@ impl InstructionMiddleware for CustomMiddleware {
|
|||||||
fn process_protocol_instructions(
|
fn process_protocol_instructions(
|
||||||
&self,
|
&self,
|
||||||
protocol_instructions: Vec<Instruction>,
|
protocol_instructions: Vec<Instruction>,
|
||||||
protocol_name: String,
|
_protocol_name: &str,
|
||||||
is_buy: bool,
|
_is_buy: bool,
|
||||||
) -> Result<Vec<Instruction>> {
|
) -> Result<Vec<Instruction>> {
|
||||||
// do anything you want here
|
// do anything you want here
|
||||||
// you can modify the instructions here
|
// you can modify the instructions here
|
||||||
@@ -41,8 +42,8 @@ impl InstructionMiddleware for CustomMiddleware {
|
|||||||
fn process_full_instructions(
|
fn process_full_instructions(
|
||||||
&self,
|
&self,
|
||||||
full_instructions: Vec<Instruction>,
|
full_instructions: Vec<Instruction>,
|
||||||
protocol_name: String,
|
_protocol_name: &str,
|
||||||
is_buy: bool,
|
_is_buy: bool,
|
||||||
) -> Result<Vec<Instruction>> {
|
) -> Result<Vec<Instruction>> {
|
||||||
// do anything you want here
|
// do anything you want here
|
||||||
// you can modify the instructions here
|
// you can modify the instructions here
|
||||||
@@ -62,7 +63,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
@@ -91,7 +99,8 @@ async fn test_middleware() -> AnyResult<()> {
|
|||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points: slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpSwap(
|
extension_params: DexParamEnum::PumpSwap(
|
||||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address).await?,
|
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -103,6 +112,7 @@ async fn test_middleware() -> AnyResult<()> {
|
|||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
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");
|
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");
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sol-trade-sdk = { path = "../.." }
|
sol-trade-sdk = { path = "../.." }
|
||||||
solana-streamer-sdk = "0.5.0"
|
sol-parser-sdk = "0.2.2"
|
||||||
solana-sdk = "3.0.0"
|
solana-sdk = "3.0.0"
|
||||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||||
spl-associated-token-account = "7.0.0"
|
spl-associated-token-account = "7.0.0"
|
||||||
|
|||||||
@@ -6,113 +6,125 @@ 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::common::{nonce_cache::fetch_nonce_info, TradeConfig};
|
||||||
use sol_trade_sdk::TradeTokenType;
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
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);
|
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
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(
|
let config = ClientConfig {
|
||||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
enable_metrics: false,
|
||||||
None,
|
connection_timeout_ms: 10000,
|
||||||
)?;
|
request_timeout_ms: 30000,
|
||||||
|
enable_tls: true,
|
||||||
let callback = create_event_callback();
|
order_mode: OrderMode::Unordered,
|
||||||
let protocols = vec![Protocol::PumpFun];
|
..Default::default()
|
||||||
// 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,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Listen to account data belonging to owner programs -> account event monitoring
|
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
|
||||||
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
|
.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 protocols = vec![Protocol::PumpFun];
|
||||||
let event_type_filter =
|
let transaction_filter = TransactionFilter::for_protocols(&protocols);
|
||||||
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
|
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(
|
let queue = grpc
|
||||||
protocols,
|
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||||
None,
|
.await?;
|
||||||
vec![transaction_filter],
|
|
||||||
vec![account_filter],
|
loop {
|
||||||
Some(event_type_filter),
|
if let Some(event) = queue.pop() {
|
||||||
None,
|
let run = match &event {
|
||||||
callback,
|
DexEvent::PumpFunBuy(e)
|
||||||
)
|
| DexEvent::PumpFunSell(e)
|
||||||
.await?;
|
| 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?;
|
tokio::signal::ctrl_c().await?;
|
||||||
|
|
||||||
Ok(())
|
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> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
println!("🚀 Initializing SolanaTrade client...");
|
println!("🚀 Initializing SolanaTrade client...");
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PumpFun sniper trade
|
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
|
||||||
/// This function demonstrates how to snipe a new token from a PumpFun trade event
|
async fn pumpfun_copy_trade_with_grpc(
|
||||||
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
|
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||||
|
) -> AnyResult<()> {
|
||||||
println!("Testing PumpFun trading...");
|
println!("Testing PumpFun trading...");
|
||||||
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
@@ -120,22 +132,19 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
let slippage_basis_points = Some(100);
|
let slippage_basis_points = Some(100);
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
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 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 durable_nonce = fetch_nonce_info(&client.infrastructure.rpc, nonce_account_str).await;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
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);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|
||||||
// Buy tokens
|
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
|
||||||
println!("Buying tokens from PumpFun...");
|
|
||||||
let buy_sol_amount = 100_000;
|
|
||||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
input_token_type: TradeTokenType::SOL,
|
input_token_type: TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: buy_sol_amount,
|
input_token_amount: 100_000,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||||
trade_info.bonding_curve,
|
trade_info.bonding_curve,
|
||||||
@@ -150,20 +159,22 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
None,
|
None,
|
||||||
trade_info.fee_recipient,
|
trade_info.fee_recipient,
|
||||||
trade_info.token_program,
|
trade_info.token_program,
|
||||||
|
trade_info.is_cashback_coin,
|
||||||
|
Some(trade_info.mayhem_mode),
|
||||||
)),
|
)),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
create_input_token_ata: false,
|
create_input_token_ata: false,
|
||||||
close_input_token_ata: false,
|
close_input_token_ata: false,
|
||||||
create_mint_ata: true,
|
create_mint_ata: true,
|
||||||
durable_nonce: durable_nonce,
|
durable_nonce,
|
||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
// Exit program
|
|
||||||
std::process::exit(0);
|
std::process::exit(0);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sol-trade-sdk = { path = "../.." }
|
sol-trade-sdk = { path = "../.." }
|
||||||
solana-streamer-sdk = "0.5.0"
|
sol-parser-sdk = "0.2.2"
|
||||||
solana-sdk = "3.0.0"
|
solana-sdk = "3.0.0"
|
||||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
|||||||
@@ -1,8 +1,17 @@
|
|||||||
|
//! PumpFun 跟单示例(仅使用 sol-parser-sdk 订阅 gRPC 事件)
|
||||||
|
//!
|
||||||
|
//! 收到 PumpFun 买卖事件后,用事件中的参数(含 is_cashback_coin)构造交易并执行一次买+卖。
|
||||||
|
|
||||||
use std::sync::{
|
use std::sync::{
|
||||||
atomic::{AtomicBool, Ordering},
|
atomic::{AtomicBool, Ordering},
|
||||||
Arc,
|
Arc,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
use sol_parser_sdk::grpc::{
|
||||||
|
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||||
|
TransactionFilter, YellowstoneGrpc,
|
||||||
|
};
|
||||||
|
use sol_parser_sdk::DexEvent;
|
||||||
use sol_trade_sdk::common::{
|
use sol_trade_sdk::common::{
|
||||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, TradeConfig,
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, TradeConfig,
|
||||||
};
|
};
|
||||||
@@ -10,149 +19,145 @@ use sol_trade_sdk::TradeTokenType;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
use solana_sdk::signer::Signer;
|
use solana_sdk::signer::Signer;
|
||||||
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);
|
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("Subscribing to GRPC events...");
|
println!("PumpFun 跟单示例(sol-parser-sdk gRPC)...");
|
||||||
|
|
||||||
let grpc = YellowstoneGrpc::new(
|
let config = ClientConfig {
|
||||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
enable_metrics: false,
|
||||||
None,
|
connection_timeout_ms: 10000,
|
||||||
)?;
|
request_timeout_ms: 30000,
|
||||||
|
enable_tls: true,
|
||||||
let callback = create_event_callback();
|
order_mode: OrderMode::Unordered,
|
||||||
let protocols = vec![Protocol::PumpFun];
|
..Default::default()
|
||||||
// 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,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Listen to account data belonging to owner programs -> account event monitoring
|
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
|
||||||
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
|
.unwrap_or_else(|_| "https://solana-yellowstone-grpc.publicnode.com:443".to_string());
|
||||||
|
let grpc = YellowstoneGrpc::new_with_config(
|
||||||
|
grpc_endpoint.clone(),
|
||||||
|
std::env::var("GRPC_AUTH_TOKEN").ok(),
|
||||||
|
config,
|
||||||
|
)?;
|
||||||
|
|
||||||
// listen to specific event type
|
let protocols = vec![Protocol::PumpFun];
|
||||||
let event_type_filter =
|
let transaction_filter = TransactionFilter::for_protocols(&protocols);
|
||||||
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
|
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(
|
let queue = grpc
|
||||||
protocols,
|
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||||
None,
|
.await?;
|
||||||
vec![transaction_filter],
|
|
||||||
vec![account_filter],
|
println!("订阅已启动,等待一条 PumpFun 交易后执行跟单(仅一次)...\n");
|
||||||
Some(event_type_filter),
|
|
||||||
None,
|
loop {
|
||||||
callback,
|
if let Some(event) = queue.pop() {
|
||||||
)
|
let run = match &event {
|
||||||
.await?;
|
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(e).await {
|
||||||
|
eprintln!("跟单执行错误: {:?}", 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?;
|
tokio::signal::ctrl_c().await?;
|
||||||
|
|
||||||
Ok(())
|
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> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
println!("🚀 Initializing SolanaTrade client...");
|
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = std::env::var("RPC_URL")
|
||||||
|
.unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
// .use_seed_optimize(true) // default: true
|
||||||
Ok(solana_trade)
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
|
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// PumpFun sniper trade
|
async fn pumpfun_copy_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||||
/// 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<()> {
|
|
||||||
println!("Testing PumpFun trading...");
|
|
||||||
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
let mint_pubkey = trade_info.mint;
|
let mint_pubkey = e.mint;
|
||||||
let slippage_basis_points = Some(100);
|
let slippage_basis_points = Some(100u64);
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buy tokens
|
// 买入:使用事件参数,含 is_cashback_coin(来自 sol-parser-sdk 解析)
|
||||||
println!("Buying tokens from PumpFun...");
|
let buy_sol_amount = 100_000u64;
|
||||||
let buy_sol_amount = 100_000;
|
|
||||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
input_token_type: TradeTokenType::SOL,
|
input_token_type: TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: buy_sol_amount,
|
input_token_amount: buy_sol_amount,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||||
trade_info.bonding_curve,
|
e.bonding_curve,
|
||||||
trade_info.associated_bonding_curve,
|
e.associated_bonding_curve,
|
||||||
trade_info.mint,
|
e.mint,
|
||||||
trade_info.creator,
|
e.creator,
|
||||||
trade_info.creator_vault,
|
e.creator_vault,
|
||||||
trade_info.virtual_token_reserves,
|
e.virtual_token_reserves,
|
||||||
trade_info.virtual_sol_reserves,
|
e.virtual_sol_reserves,
|
||||||
trade_info.real_token_reserves,
|
e.real_token_reserves,
|
||||||
trade_info.real_sol_reserves,
|
e.real_sol_reserves,
|
||||||
None,
|
None,
|
||||||
trade_info.fee_recipient,
|
e.fee_recipient,
|
||||||
trade_info.token_program,
|
e.token_program,
|
||||||
|
e.is_cashback_coin,
|
||||||
|
Some(e.mayhem_mode),
|
||||||
)),
|
)),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -164,46 +169,45 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
// Sell tokens
|
// 卖出:查询余额后卖出,同样传入 is_cashback_coin
|
||||||
println!("Selling tokens from PumpFun...");
|
|
||||||
|
|
||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
&payer,
|
&payer,
|
||||||
&mint_pubkey,
|
&mint_pubkey,
|
||||||
&trade_info.token_program,
|
&e.token_program,
|
||||||
client.use_seed_optimize,
|
client.use_seed_optimize,
|
||||||
);
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
println!("Balance: {:?}", balance);
|
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
output_token_type: TradeTokenType::SOL,
|
output_token_type: TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: amount_token,
|
input_token_amount: amount_token,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
with_tip: false,
|
with_tip: false,
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||||
trade_info.bonding_curve,
|
e.bonding_curve,
|
||||||
trade_info.associated_bonding_curve,
|
e.associated_bonding_curve,
|
||||||
trade_info.mint,
|
e.mint,
|
||||||
trade_info.creator,
|
e.creator,
|
||||||
trade_info.creator_vault,
|
e.creator_vault,
|
||||||
trade_info.virtual_token_reserves,
|
e.virtual_token_reserves,
|
||||||
trade_info.virtual_sol_reserves,
|
e.virtual_sol_reserves,
|
||||||
trade_info.real_token_reserves,
|
e.real_token_reserves,
|
||||||
trade_info.real_sol_reserves,
|
e.real_sol_reserves,
|
||||||
Some(true),
|
Some(true),
|
||||||
trade_info.fee_recipient,
|
e.fee_recipient,
|
||||||
trade_info.token_program,
|
e.token_program,
|
||||||
|
e.is_cashback_coin,
|
||||||
|
Some(e.mayhem_mode),
|
||||||
)),
|
)),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -212,14 +216,12 @@ async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResul
|
|||||||
close_mint_token_ata: false,
|
close_mint_token_ata: false,
|
||||||
durable_nonce: None,
|
durable_nonce: None,
|
||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
// PumpFunParams can also be set as PumpFunParams::immediate_sell(creator_vault, close_token_account_when_sell)
|
println!("跟单一次买+卖完成");
|
||||||
// creator_vault can be obtained from the trade event
|
Ok(())
|
||||||
|
|
||||||
// Exit program
|
|
||||||
std::process::exit(0);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -5,7 +5,7 @@ edition = "2021"
|
|||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
sol-trade-sdk = { path = "../.." }
|
sol-trade-sdk = { path = "../.." }
|
||||||
solana-streamer-sdk = "0.5.0"
|
sol-parser-sdk = "0.2.2"
|
||||||
solana-sdk = "3.0.0"
|
solana-sdk = "3.0.0"
|
||||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||||
tokio = { version = "1", features = ["full"] }
|
tokio = { version = "1", features = ["full"] }
|
||||||
|
|||||||
@@ -1,117 +1,153 @@
|
|||||||
|
//! PumpFun 狙击示例(仅使用 sol-parser-sdk 订阅 gRPC 事件)
|
||||||
|
//!
|
||||||
|
//! 监听创建者首次买入(Create 后同笔/首笔 Buy,is_created_buy == true),
|
||||||
|
//! 用事件参数(含 is_cashback_coin)构造 from_dev_trade 并执行一次买+卖。
|
||||||
|
|
||||||
|
use std::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::spl_associated_token_account::get_associated_token_address;
|
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
||||||
use sol_trade_sdk::common::TradeConfig;
|
use sol_trade_sdk::common::TradeConfig;
|
||||||
use sol_trade_sdk::TradeTokenType;
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
use solana_sdk::signer::Signer;
|
use solana_sdk::signer::Signer;
|
||||||
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::PumpFunTradeEvent;
|
|
||||||
use solana_streamer_sdk::streaming::event_parser::{Protocol, UnifiedEvent};
|
|
||||||
use solana_streamer_sdk::{match_event, streaming::ShredStreamGrpc};
|
|
||||||
use std::sync::{
|
|
||||||
atomic::{AtomicBool, Ordering},
|
|
||||||
Arc,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Atomic flag to ensure the sniper trade is executed only once
|
|
||||||
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
/// Main entry point - subscribes to PumpFun events and executes sniper trades on token creation
|
|
||||||
#[tokio::main]
|
#[tokio::main]
|
||||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||||
println!("Subscribing to ShredStream events...");
|
println!("PumpFun 狙击示例(sol-parser-sdk gRPC)...");
|
||||||
let shred_stream = ShredStreamGrpc::new("use_your_shred_stream_url_here".to_string()).await?;
|
|
||||||
let callback = create_event_callback();
|
let config = ClientConfig {
|
||||||
let protocols = vec![Protocol::PumpFun];
|
enable_metrics: false,
|
||||||
let event_type_filter = EventTypeFilter {
|
connection_timeout_ms: 10000,
|
||||||
include: vec![EventType::PumpFunBuy, EventType::PumpFunSell, EventType::PumpFunCreateToken],
|
request_timeout_ms: 30000,
|
||||||
|
enable_tls: true,
|
||||||
|
order_mode: OrderMode::Unordered,
|
||||||
|
..Default::default()
|
||||||
};
|
};
|
||||||
println!("Starting to listen for events, press Ctrl+C to stop...");
|
|
||||||
shred_stream.shredstream_subscribe(protocols, None, Some(event_type_filter), callback).await?;
|
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,
|
||||||
|
)?;
|
||||||
|
|
||||||
|
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::PumpFunCreate,
|
||||||
|
EventType::PumpFunBuy,
|
||||||
|
EventType::PumpFunBuyExactSolIn,
|
||||||
|
]);
|
||||||
|
|
||||||
|
let queue = grpc
|
||||||
|
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
println!("订阅已启动,等待创建者首次买入(is_created_buy)后执行狙击(仅一次)...\n");
|
||||||
|
|
||||||
|
loop {
|
||||||
|
if let Some(event) = queue.pop() {
|
||||||
|
let run = match &event {
|
||||||
|
DexEvent::PumpFunBuy(e) | DexEvent::PumpFunBuyExactSolIn(e) => {
|
||||||
|
if e.is_created_buy && !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_sniper_trade(e).await {
|
||||||
|
eprintln!("狙击执行错误: {:?}", 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?;
|
tokio::signal::ctrl_c().await?;
|
||||||
Ok(())
|
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| {
|
|
||||||
// Only process developer token creation events
|
|
||||||
if !e.is_dev_create_token_trade {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Ensure we only execute the trade once using atomic compare-and-swap
|
|
||||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
|
||||||
let event_clone = e.clone();
|
|
||||||
// Spawn a new task to handle the trading operation
|
|
||||||
tokio::spawn(async move {
|
|
||||||
if let Err(err) = pumpfun_sniper_trade_with_shreds(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> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
println!("🚀 Initializing SolanaTrade client...");
|
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = std::env::var("RPC_URL")
|
||||||
|
.unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
// .use_seed_optimize(true) // default: true
|
||||||
Ok(solana_trade)
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
|
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute PumpFun sniper trading strategy based on received token creation event
|
async fn pumpfun_sniper_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||||
/// This function buys tokens immediately after creation and then sells all tokens
|
|
||||||
async fn pumpfun_sniper_trade_with_shreds(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
|
|
||||||
println!("Testing PumpFun trading...");
|
|
||||||
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
let mint_pubkey = trade_info.mint;
|
let mint_pubkey = e.mint;
|
||||||
let slippage_basis_points = Some(300);
|
let slippage_basis_points = Some(300u64);
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
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);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|
||||||
// Buy tokens
|
// 创建者首次买入:用 from_dev_trade,max_sol_cost 用事件中的 sol_amount(可酌情加滑点)
|
||||||
println!("Buying tokens from PumpFun...");
|
let buy_sol_amount = 100_000u64;
|
||||||
let buy_sol_amount = 100_000;
|
let max_sol_cost = e.sol_amount.saturating_add(e.sol_amount / 10); // 约 +10% 作为上限
|
||||||
|
|
||||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
input_token_type: TradeTokenType::SOL,
|
input_token_type: TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: buy_sol_amount,
|
input_token_amount: buy_sol_amount,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_dev_trade(
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_dev_trade(
|
||||||
trade_info.mint,
|
e.mint,
|
||||||
trade_info.token_amount,
|
e.token_amount,
|
||||||
trade_info.max_sol_cost,
|
max_sol_cost,
|
||||||
trade_info.creator,
|
e.creator,
|
||||||
trade_info.bonding_curve,
|
e.bonding_curve,
|
||||||
trade_info.associated_bonding_curve,
|
e.associated_bonding_curve,
|
||||||
trade_info.creator_vault,
|
e.creator_vault,
|
||||||
None,
|
None,
|
||||||
trade_info.fee_recipient,
|
e.fee_recipient,
|
||||||
trade_info.token_program,
|
e.token_program,
|
||||||
|
e.is_cashback_coin,
|
||||||
|
Some(e.mayhem_mode),
|
||||||
)),
|
)),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -123,29 +159,40 @@ async fn pumpfun_sniper_trade_with_shreds(trade_info: PumpFunTradeEvent) -> AnyR
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
// Sell tokens
|
|
||||||
println!("Selling tokens from PumpFun...");
|
|
||||||
|
|
||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let account = get_associated_token_address(&payer, &mint_pubkey);
|
let account = get_associated_token_address(&payer, &mint_pubkey);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
println!("Balance: {:?}", balance);
|
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
dex_type: DexType::PumpFun,
|
dex_type: DexType::PumpFun,
|
||||||
output_token_type: TradeTokenType::SOL,
|
output_token_type: TradeTokenType::SOL,
|
||||||
mint: mint_pubkey,
|
mint: mint_pubkey,
|
||||||
input_token_amount: amount_token,
|
input_token_amount: amount_token,
|
||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
with_tip: false,
|
with_tip: false,
|
||||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::immediate_sell(trade_info.creator_vault, trade_info.token_program, true)),
|
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||||
|
e.bonding_curve,
|
||||||
|
e.associated_bonding_curve,
|
||||||
|
e.mint,
|
||||||
|
e.creator,
|
||||||
|
e.creator_vault,
|
||||||
|
e.virtual_token_reserves,
|
||||||
|
e.virtual_sol_reserves,
|
||||||
|
e.real_token_reserves,
|
||||||
|
e.real_sol_reserves,
|
||||||
|
Some(true),
|
||||||
|
e.fee_recipient,
|
||||||
|
e.token_program,
|
||||||
|
e.is_cashback_coin,
|
||||||
|
Some(e.mayhem_mode),
|
||||||
|
)),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
create_output_token_ata: true,
|
create_output_token_ata: true,
|
||||||
@@ -153,14 +200,12 @@ async fn pumpfun_sniper_trade_with_shreds(trade_info: PumpFunTradeEvent) -> AnyR
|
|||||||
close_mint_token_ata: false,
|
close_mint_token_ata: false,
|
||||||
durable_nonce: None,
|
durable_nonce: None,
|
||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
// PumpFunParams can also be set as PumpFunParams::immediate_sell(creator_vault, close_token_account_when_sell)
|
println!("狙击一次买+卖完成");
|
||||||
// creator_vault can be obtained from the trade event
|
Ok(())
|
||||||
|
|
||||||
// Exit program after completing the trade
|
|
||||||
std::process::exit(0);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
SolanaTrade, TradeTokenType, common::{
|
common::{
|
||||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
}, swqos::SwqosConfig, trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType}
|
},
|
||||||
|
swqos::SwqosConfig,
|
||||||
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
@@ -44,6 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -53,7 +60,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM_2022;
|
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM_2022;
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
@@ -72,6 +84,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
create_output_token_ata: true,
|
create_output_token_ata: true,
|
||||||
close_output_token_ata: true,
|
close_output_token_ata: true,
|
||||||
close_mint_token_ata: false,
|
close_mint_token_ata: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
durable_nonce: None,
|
durable_nonce: None,
|
||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
@@ -91,7 +104,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
|
|||||||
@@ -1,10 +1,14 @@
|
|||||||
use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed;
|
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::common::TradeConfig;
|
||||||
|
use sol_trade_sdk::instruction::utils::pumpswap::fetch_pool;
|
||||||
use sol_trade_sdk::TradeTokenType;
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -129,14 +133,23 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> AnyResult<()> {
|
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.pool,
|
||||||
trade_info.base_mint,
|
trade_info.base_mint,
|
||||||
trade_info.quote_mint,
|
trade_info.quote_mint,
|
||||||
@@ -149,6 +162,7 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
|
|||||||
trade_info.base_token_program,
|
trade_info.base_token_program,
|
||||||
trade_info.quote_token_program,
|
trade_info.quote_token_program,
|
||||||
trade_info.protocol_fee_recipient,
|
trade_info.protocol_fee_recipient,
|
||||||
|
pool_data.is_cashback_coin,
|
||||||
);
|
);
|
||||||
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
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
|
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
@@ -157,12 +171,14 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
|
|||||||
} else {
|
} else {
|
||||||
trade_info.base_mint
|
trade_info.base_mint
|
||||||
};
|
};
|
||||||
pumpswap_trade_with_grpc(mint, params).await?;
|
pumpswap_trade_with_grpc(&client, mint, params).await?;
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> AnyResult<()> {
|
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.pool,
|
||||||
trade_info.base_mint,
|
trade_info.base_mint,
|
||||||
trade_info.quote_mint,
|
trade_info.quote_mint,
|
||||||
@@ -175,6 +191,7 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
|
|||||||
trade_info.base_token_program,
|
trade_info.base_token_program,
|
||||||
trade_info.quote_token_program,
|
trade_info.quote_token_program,
|
||||||
trade_info.protocol_fee_recipient,
|
trade_info.protocol_fee_recipient,
|
||||||
|
pool_data.is_cashback_coin,
|
||||||
);
|
);
|
||||||
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
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
|
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
@@ -183,14 +200,16 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
|
|||||||
} else {
|
} else {
|
||||||
trade_info.base_mint
|
trade_info.base_mint
|
||||||
};
|
};
|
||||||
pumpswap_trade_with_grpc(mint, params).await?;
|
pumpswap_trade_with_grpc(&client, mint, params).await?;
|
||||||
Ok(())
|
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...");
|
println!("Testing PumpSwap trading...");
|
||||||
|
|
||||||
let client = create_solana_trade_client().await?;
|
|
||||||
let slippage_basis_points = Some(500);
|
let slippage_basis_points = Some(500);
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
@@ -221,6 +240,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -234,7 +254,12 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
|||||||
} else {
|
} else {
|
||||||
params.quote_token_program
|
params.quote_token_program
|
||||||
};
|
};
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
@@ -255,6 +280,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{RaydiumAmmV4Params, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, RaydiumAmmV4Params},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
@@ -106,7 +109,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
@@ -122,8 +132,12 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let amm_info = fetch_amm_info(&client.infrastructure.rpc, trade_info.amm).await?;
|
let amm_info = fetch_amm_info(&client.infrastructure.rpc, trade_info.amm).await?;
|
||||||
let (coin_reserve, pc_reserve) =
|
let (coin_reserve, pc_reserve) = get_multi_token_balances(
|
||||||
get_multi_token_balances(&client.infrastructure.rpc, &amm_info.token_coin, &amm_info.token_pc).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&amm_info.token_coin,
|
||||||
|
&amm_info.token_pc,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
let mint_pubkey = if amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
let mint_pubkey = if amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| amm_info.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
|| amm_info.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||||
{
|
{
|
||||||
@@ -142,14 +156,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
);
|
);
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buy tokens
|
// Buy tokens
|
||||||
println!("Buying tokens from Raydium_amm_v4...");
|
println!("Buying tokens from Raydium_amm_v4...");
|
||||||
@@ -174,6 +181,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -193,7 +201,9 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
println!("Selling {} tokens", amount_token);
|
||||||
let params = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm).await?;
|
let params =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm)
|
||||||
|
.await?;
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
dex_type: DexType::RaydiumAmmV4,
|
dex_type: DexType::RaydiumAmmV4,
|
||||||
output_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
output_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
||||||
@@ -212,6 +222,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
||||||
use sol_trade_sdk::common::TradeConfig;
|
use sol_trade_sdk::common::TradeConfig;
|
||||||
use sol_trade_sdk::constants::{WSOL_TOKEN_ACCOUNT, USDC_TOKEN_ACCOUNT};
|
use sol_trade_sdk::constants::{USDC_TOKEN_ACCOUNT, WSOL_TOKEN_ACCOUNT};
|
||||||
use sol_trade_sdk::trading::core::params::{RaydiumCpmmParams, DexParamEnum};
|
use sol_trade_sdk::trading::core::params::{DexParamEnum, RaydiumCpmmParams};
|
||||||
use sol_trade_sdk::trading::factory::DexType;
|
use sol_trade_sdk::trading::factory::DexType;
|
||||||
use sol_trade_sdk::TradeTokenType;
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{common::AnyResult, swqos::SwqosConfig, SolanaTrade};
|
use sol_trade_sdk::{common::AnyResult, swqos::SwqosConfig, SolanaTrade};
|
||||||
@@ -107,7 +107,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
@@ -132,9 +139,12 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
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);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|
||||||
let buy_params =
|
let buy_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&trade_info.pool_state,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let is_wsol = trade_info.input_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
let is_wsol = trade_info.input_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| trade_info.output_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
|| trade_info.output_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
|
|
||||||
@@ -159,6 +169,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -172,8 +183,11 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
println!("Balance: {:?}", balance);
|
println!("Balance: {:?}", balance);
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
let sell_params =
|
let sell_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&trade_info.pool_state,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
println!("Selling {} tokens", amount_token);
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
@@ -194,6 +208,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::{
|
|||||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
},
|
},
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade, TradeTokenType,
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -47,6 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||||
simulate: false,
|
simulate: false,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.buy(buy_params).await?;
|
client.buy(buy_params).await?;
|
||||||
|
|
||||||
@@ -87,6 +91,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
fixed_output_token_amount: None,
|
fixed_output_token_amount: None,
|
||||||
gas_fee_strategy: gas_fee_strategy,
|
gas_fee_strategy: gas_fee_strategy,
|
||||||
simulate: false,
|
simulate: false,
|
||||||
|
grpc_recv_us: None,
|
||||||
};
|
};
|
||||||
client.sell(sell_params).await?;
|
client.sell(sell_params).await?;
|
||||||
|
|
||||||
@@ -102,7 +107,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
|
|||||||
@@ -31,6 +31,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
SwqosConfig::Default(rpc_url.clone()),
|
SwqosConfig::Default(rpc_url.clone()),
|
||||||
SwqosConfig::Jito("your_uuid".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Jito("your_uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Bloxroute("your_api_token".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)
|
// Step 1: Create shared infrastructure (expensive, do once)
|
||||||
|
|||||||
@@ -10,7 +10,7 @@
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::{AnyResult, InfrastructureConfig, TradeConfig},
|
common::{AnyResult, InfrastructureConfig, TradeConfig},
|
||||||
swqos::{SwqosConfig, SwqosRegion},
|
swqos::{SwqosConfig, SwqosRegion},
|
||||||
TradingClient, TradingInfrastructure,
|
AstralaneTransport, TradingClient, TradingInfrastructure,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
@@ -46,17 +46,22 @@ async fn create_trading_client_simple() -> AnyResult<TradingClient> {
|
|||||||
SwqosConfig::ZeroSlot("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::ZeroSlot("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Temporal("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Temporal("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None, None),
|
||||||
SwqosConfig::BlockRazor("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(AstralaneTransport::Quic),
|
||||||
|
), // QUIC;None / Some(Binary) / Some(Plain) 为 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
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
.create_wsol_ata_on_startup(true)
|
||||||
.with_wsol_ata_config(
|
.use_seed_optimize(true)
|
||||||
true, // create_wsol_ata_on_startup: Check and create WSOL ATA on startup
|
.build();
|
||||||
true, // use_seed_optimize: Enable seed optimization for all ATA operations
|
|
||||||
);
|
|
||||||
|
|
||||||
// Creates new infrastructure internally
|
// Creates new infrastructure internally
|
||||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||||
|
|||||||
@@ -38,7 +38,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
// Example 2: Unwrap half of the WSOL back to SOL using seed account
|
// Example 2: Unwrap half of the WSOL back to SOL using seed account
|
||||||
println!("\n🔄 Example 2: Unwrapping half of WSOL back to SOL using seed account");
|
println!("\n🔄 Example 2: Unwrapping half of WSOL back to SOL using seed account");
|
||||||
let unwrap_amount = wrap_amount / 2; // Half of the wrapped amount
|
let unwrap_amount = wrap_amount / 2; // Half of the wrapped amount
|
||||||
println!("Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...", unwrap_amount);
|
println!(
|
||||||
|
"Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...",
|
||||||
|
unwrap_amount
|
||||||
|
);
|
||||||
|
|
||||||
match solana_trade.wrap_wsol_to_sol(unwrap_amount).await {
|
match solana_trade.wrap_wsol_to_sol(unwrap_amount).await {
|
||||||
Ok(signature) => {
|
Ok(signature) => {
|
||||||
@@ -81,7 +84,14 @@ async fn create_solana_trade_client() -> Result<SolanaTrade, Box<dyn std::error:
|
|||||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||||
let commitment = CommitmentConfig::confirmed();
|
let commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
// .create_wsol_ata_on_startup(true) // default: true
|
||||||
|
// .use_seed_optimize(true) // default: true
|
||||||
|
// .log_enabled(true) // default: true
|
||||||
|
// .check_min_tip(false) // default: false
|
||||||
|
// .swqos_cores_from_end(false) // default: false
|
||||||
|
// .mev_protection(false) // default: false
|
||||||
|
.build();
|
||||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||||
println!("✅ SolanaTrade client initialized successfully!");
|
println!("✅ SolanaTrade client initialized successfully!");
|
||||||
Ok(solana_trade)
|
Ok(solana_trade)
|
||||||
|
|||||||
+7098
File diff suppressed because it is too large
Load Diff
+6268
File diff suppressed because it is too large
Load Diff
+2761
File diff suppressed because it is too large
Load Diff
@@ -1,17 +1,39 @@
|
|||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_address_lookup_table_interface::state::AddressLookupTable;
|
use solana_message::AddressLookupTableAccount;
|
||||||
use solana_sdk::{message::AddressLookupTableAccount, pubkey::Pubkey};
|
use solana_sdk::pubkey::Pubkey;
|
||||||
|
|
||||||
pub async fn fetch_address_lookup_table_account(
|
pub async fn fetch_address_lookup_table_account(
|
||||||
rpc: &SolanaRpcClient,
|
rpc: &SolanaRpcClient,
|
||||||
lookup_table_address: &Pubkey,
|
lookup_table_address: &Pubkey,
|
||||||
) -> Result<AddressLookupTableAccount, anyhow::Error> {
|
) -> Result<AddressLookupTableAccount, anyhow::Error> {
|
||||||
let account = rpc.get_account(lookup_table_address).await?;
|
let account = rpc.get_account(lookup_table_address).await?;
|
||||||
let lookup_table = AddressLookupTable::deserialize(&account.data)?;
|
|
||||||
|
// Parse address lookup table manually
|
||||||
|
// Layout: 4 bytes (type) + 4 bytes (deactivation_slot) + 4 bytes (last_extended_slot) + 1 byte (last_extended_slot_start_index) + 1 byte (authority) + padding
|
||||||
|
// Then addresses start at offset 56, each address is 32 bytes
|
||||||
|
// First 4 bytes indicate if initialized (should be 1 or 2)
|
||||||
|
|
||||||
|
if account.data.len() < 56 {
|
||||||
|
return Err(anyhow::anyhow!("Address lookup table account data too short"));
|
||||||
|
}
|
||||||
|
|
||||||
|
// Read number of addresses (stored at offset 20 as u32, but we need to scan the bitmap)
|
||||||
|
// Actually simpler: addresses start at offset 56, count from bitmap at offset 8-20
|
||||||
|
let mut addresses = Vec::new();
|
||||||
|
let mut offset = 56;
|
||||||
|
while offset + 32 <= account.data.len() {
|
||||||
|
let addr_bytes: [u8; 32] = account.data[offset..offset + 32].try_into()?;
|
||||||
|
// Skip zero addresses (unused slots)
|
||||||
|
if addr_bytes != [0u8; 32] {
|
||||||
|
addresses.push(Pubkey::from(addr_bytes));
|
||||||
|
}
|
||||||
|
offset += 32;
|
||||||
|
}
|
||||||
|
|
||||||
let address_lookup_table_account = AddressLookupTableAccount {
|
let address_lookup_table_account = AddressLookupTableAccount {
|
||||||
key: *lookup_table_address,
|
key: *lookup_table_address,
|
||||||
addresses: lookup_table.addresses.to_vec(),
|
addresses,
|
||||||
};
|
};
|
||||||
Ok(address_lookup_table_account)
|
Ok(address_lookup_table_account)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -60,9 +60,13 @@ pub struct BondingCurveAccount {
|
|||||||
pub creator: Pubkey,
|
pub creator: Pubkey,
|
||||||
/// Whether this is a mayhem mode token (Token2022)
|
/// Whether this is a mayhem mode token (Token2022)
|
||||||
pub is_mayhem_mode: bool,
|
pub is_mayhem_mode: bool,
|
||||||
|
/// Whether this coin has cashback enabled (creator fee redirected to users)
|
||||||
|
pub is_cashback_coin: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl BondingCurveAccount {
|
impl BondingCurveAccount {
|
||||||
|
/// When building from event/parser data (e.g. sol-parser-sdk), pass the token's cashback flag
|
||||||
|
/// so that sell instructions include the correct remaining accounts. From RPC use `from_mint_by_rpc` instead.
|
||||||
pub fn from_dev_trade(
|
pub fn from_dev_trade(
|
||||||
bonding_curve: Pubkey,
|
bonding_curve: Pubkey,
|
||||||
mint: &Pubkey,
|
mint: &Pubkey,
|
||||||
@@ -70,6 +74,7 @@ impl BondingCurveAccount {
|
|||||||
dev_sol_amount: u64,
|
dev_sol_amount: u64,
|
||||||
creator: Pubkey,
|
creator: Pubkey,
|
||||||
is_mayhem_mode: bool,
|
is_mayhem_mode: bool,
|
||||||
|
is_cashback_coin: bool,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let account = if bonding_curve != Pubkey::default() {
|
let account = if bonding_curve != Pubkey::default() {
|
||||||
bonding_curve
|
bonding_curve
|
||||||
@@ -87,9 +92,12 @@ impl BondingCurveAccount {
|
|||||||
complete: false,
|
complete: false,
|
||||||
creator: creator,
|
creator: creator,
|
||||||
is_mayhem_mode: is_mayhem_mode,
|
is_mayhem_mode: is_mayhem_mode,
|
||||||
|
is_cashback_coin,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// When building from event/parser data (e.g. sol-parser-sdk), pass the token's cashback flag
|
||||||
|
/// so that sell instructions include the correct remaining accounts. From RPC use `from_mint_by_rpc` instead.
|
||||||
pub fn from_trade(
|
pub fn from_trade(
|
||||||
bonding_curve: Pubkey,
|
bonding_curve: Pubkey,
|
||||||
mint: Pubkey,
|
mint: Pubkey,
|
||||||
@@ -99,6 +107,7 @@ impl BondingCurveAccount {
|
|||||||
real_token_reserves: u64,
|
real_token_reserves: u64,
|
||||||
real_sol_reserves: u64,
|
real_sol_reserves: u64,
|
||||||
is_mayhem_mode: bool,
|
is_mayhem_mode: bool,
|
||||||
|
is_cashback_coin: bool,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
let account = if bonding_curve != Pubkey::default() {
|
let account = if bonding_curve != Pubkey::default() {
|
||||||
bonding_curve
|
bonding_curve
|
||||||
@@ -116,6 +125,7 @@ impl BondingCurveAccount {
|
|||||||
complete: false,
|
complete: false,
|
||||||
creator: creator,
|
creator: creator,
|
||||||
is_mayhem_mode: is_mayhem_mode,
|
is_mayhem_mode: is_mayhem_mode,
|
||||||
|
is_cashback_coin,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -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
|
||||||
|
}
|
||||||
@@ -46,7 +46,10 @@ static INSTRUCTION_CACHE: Lazy<DashMap<InstructionCacheKey, Arc<Vec<Instruction>
|
|||||||
/// Get cached instruction, compute and cache if not exists (lock-free)
|
/// Get cached instruction, compute and cache if not exists (lock-free)
|
||||||
/// 🚀 返回 Arc 避免每次调用克隆整个 Vec
|
/// 🚀 返回 Arc 避免每次调用克隆整个 Vec
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_cached_instructions<F>(cache_key: InstructionCacheKey, compute_fn: F) -> Arc<Vec<Instruction>>
|
pub fn get_cached_instructions<F>(
|
||||||
|
cache_key: InstructionCacheKey,
|
||||||
|
compute_fn: F,
|
||||||
|
) -> Arc<Vec<Instruction>>
|
||||||
where
|
where
|
||||||
F: FnOnce() -> Vec<Instruction>,
|
F: FnOnce() -> Vec<Instruction>,
|
||||||
{
|
{
|
||||||
@@ -63,10 +66,7 @@ where
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Lock-free cache lookup with entry API
|
// Lock-free cache lookup with entry API
|
||||||
INSTRUCTION_CACHE
|
INSTRUCTION_CACHE.entry(cache_key).or_insert_with(|| Arc::new(compute_fn())).clone()
|
||||||
.entry(cache_key)
|
|
||||||
.or_insert_with(|| Arc::new(compute_fn()))
|
|
||||||
.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --------------------- Associated Token Account ---------------------
|
// --------------------- Associated Token Account ---------------------
|
||||||
@@ -141,7 +141,7 @@ pub fn _create_associated_token_account_idempotent_fast(
|
|||||||
}]
|
}]
|
||||||
})
|
})
|
||||||
};
|
};
|
||||||
|
|
||||||
// 🚀 性能优化:尝试零开销解包 Arc,如果引用计数=1则直接移出,否则克隆
|
// 🚀 性能优化:尝试零开销解包 Arc,如果引用计数=1则直接移出,否则克隆
|
||||||
Arc::try_unwrap(arc_instructions).unwrap_or_else(|arc| (*arc).clone())
|
Arc::try_unwrap(arc_instructions).unwrap_or_else(|arc| (*arc).clone())
|
||||||
}
|
}
|
||||||
@@ -153,10 +153,12 @@ pub fn _create_associated_token_account_idempotent_fast(
|
|||||||
pub enum PdaCacheKey {
|
pub enum PdaCacheKey {
|
||||||
PumpFunUserVolume(Pubkey),
|
PumpFunUserVolume(Pubkey),
|
||||||
PumpFunBondingCurve(Pubkey),
|
PumpFunBondingCurve(Pubkey),
|
||||||
|
PumpFunBondingCurveV2(Pubkey),
|
||||||
PumpFunCreatorVault(Pubkey),
|
PumpFunCreatorVault(Pubkey),
|
||||||
BonkPool(Pubkey, Pubkey),
|
BonkPool(Pubkey, Pubkey),
|
||||||
BonkVault(Pubkey, Pubkey),
|
BonkVault(Pubkey, Pubkey),
|
||||||
PumpSwapUserVolume(Pubkey),
|
PumpSwapUserVolume(Pubkey),
|
||||||
|
PumpSwapPoolV2(Pubkey),
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Global lock-free PDA cache for storing computation results
|
/// Global lock-free PDA cache for storing computation results
|
||||||
|
|||||||
+10
-13
@@ -2,9 +2,9 @@
|
|||||||
//!
|
//!
|
||||||
//! 使用 syscall_bypass 提供的快速时间戳避免频繁的系统调用
|
//! 使用 syscall_bypass 提供的快速时间戳避免频繁的系统调用
|
||||||
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use crate::perf::syscall_bypass::SystemCallBypassManager;
|
use crate::perf::syscall_bypass::SystemCallBypassManager;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// 全局快速时间提供器
|
/// 全局快速时间提供器
|
||||||
static FAST_TIMER: Lazy<FastTimer> = Lazy::new(|| FastTimer::new());
|
static FAST_TIMER: Lazy<FastTimer> = Lazy::new(|| FastTimer::new());
|
||||||
@@ -26,11 +26,7 @@ impl FastTimer {
|
|||||||
let base_instant = Instant::now();
|
let base_instant = Instant::now();
|
||||||
let base_nanos = bypass_manager.fast_timestamp_nanos();
|
let base_nanos = bypass_manager.fast_timestamp_nanos();
|
||||||
|
|
||||||
Self {
|
Self { bypass_manager, _base_instant: base_instant, _base_nanos: base_nanos }
|
||||||
bypass_manager,
|
|
||||||
_base_instant: base_instant,
|
|
||||||
_base_nanos: base_nanos,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 获取当前时间戳(纳秒) - 使用快速系统调用绕过
|
/// 🚀 获取当前时间戳(纳秒) - 使用快速系统调用绕过
|
||||||
@@ -107,10 +103,7 @@ impl FastStopwatch {
|
|||||||
/// 创建并启动计时器
|
/// 创建并启动计时器
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn start(label: &'static str) -> Self {
|
pub fn start(label: &'static str) -> Self {
|
||||||
Self {
|
Self { start_nanos: fast_now_nanos(), label }
|
||||||
start_nanos: fast_now_nanos(),
|
|
||||||
label,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取已耗时(纳秒)
|
/// 获取已耗时(纳秒)
|
||||||
@@ -174,7 +167,9 @@ mod tests {
|
|||||||
let total_elapsed = start.elapsed();
|
let total_elapsed = start.elapsed();
|
||||||
let avg_per_call = total_elapsed.as_nanos() / iterations;
|
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)
|
// 快速时间戳应该非常快(< 100ns per call)
|
||||||
assert!(avg_per_call < 100);
|
assert!(avg_per_call < 100);
|
||||||
@@ -193,6 +188,8 @@ mod tests {
|
|||||||
let total_elapsed = start.elapsed();
|
let total_elapsed = start.elapsed();
|
||||||
let avg_per_call = total_elapsed.as_nanos() / iterations;
|
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);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -300,7 +300,7 @@ impl GasFeeStrategy {
|
|||||||
pub fn update_buy_tip(&self, buy_tip: f64) {
|
pub fn update_buy_tip(&self, buy_tip: f64) {
|
||||||
self.strategies.rcu(|current_map| {
|
self.strategies.rcu(|current_map| {
|
||||||
let mut new_map = (**current_map).clone();
|
let mut new_map = (**current_map).clone();
|
||||||
for ((swqos_type, trade_type, strategy_type), value) in new_map.iter_mut() {
|
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||||
if *trade_type == TradeType::Buy {
|
if *trade_type == TradeType::Buy {
|
||||||
value.tip = buy_tip;
|
value.tip = buy_tip;
|
||||||
}
|
}
|
||||||
@@ -314,7 +314,7 @@ impl GasFeeStrategy {
|
|||||||
pub fn update_sell_tip(&self, sell_tip: f64) {
|
pub fn update_sell_tip(&self, sell_tip: f64) {
|
||||||
self.strategies.rcu(|current_map| {
|
self.strategies.rcu(|current_map| {
|
||||||
let mut new_map = (**current_map).clone();
|
let mut new_map = (**current_map).clone();
|
||||||
for ((swqos_type, trade_type, strategy_type), value) in new_map.iter_mut() {
|
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||||
if *trade_type == TradeType::Sell {
|
if *trade_type == TradeType::Sell {
|
||||||
value.tip = sell_tip;
|
value.tip = sell_tip;
|
||||||
}
|
}
|
||||||
@@ -328,7 +328,7 @@ impl GasFeeStrategy {
|
|||||||
pub fn update_buy_cu_price(&self, buy_cu_price: u64) {
|
pub fn update_buy_cu_price(&self, buy_cu_price: u64) {
|
||||||
self.strategies.rcu(|current_map| {
|
self.strategies.rcu(|current_map| {
|
||||||
let mut new_map = (**current_map).clone();
|
let mut new_map = (**current_map).clone();
|
||||||
for ((swqos_type, trade_type, strategy_type), value) in new_map.iter_mut() {
|
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||||
if *trade_type == TradeType::Buy {
|
if *trade_type == TradeType::Buy {
|
||||||
value.cu_price = buy_cu_price;
|
value.cu_price = buy_cu_price;
|
||||||
}
|
}
|
||||||
@@ -342,7 +342,7 @@ impl GasFeeStrategy {
|
|||||||
pub fn update_sell_cu_price(&self, sell_cu_price: u64) {
|
pub fn update_sell_cu_price(&self, sell_cu_price: u64) {
|
||||||
self.strategies.rcu(|current_map| {
|
self.strategies.rcu(|current_map| {
|
||||||
let mut new_map = (**current_map).clone();
|
let mut new_map = (**current_map).clone();
|
||||||
for ((swqos_type, trade_type, strategy_type), value) in new_map.iter_mut() {
|
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||||
if *trade_type == TradeType::Sell {
|
if *trade_type == TradeType::Sell {
|
||||||
value.cu_price = sell_cu_price;
|
value.cu_price = sell_cu_price;
|
||||||
}
|
}
|
||||||
@@ -354,6 +354,9 @@ impl GasFeeStrategy {
|
|||||||
/// 打印所有策略。
|
/// 打印所有策略。
|
||||||
/// Print all strategies
|
/// Print all strategies
|
||||||
pub fn print_all_strategies(&self) {
|
pub fn print_all_strategies(&self) {
|
||||||
|
if !crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
return;
|
||||||
|
}
|
||||||
for strategy in self.get_strategies(TradeType::Buy) {
|
for strategy in self.get_strategies(TradeType::Buy) {
|
||||||
println!("[buy] - {:?}", strategy);
|
println!("[buy] - {:?}", strategy);
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-1
@@ -1,16 +1,18 @@
|
|||||||
|
pub mod address_lookup;
|
||||||
pub mod bonding_curve;
|
pub mod bonding_curve;
|
||||||
|
pub mod clock;
|
||||||
pub mod fast_fn;
|
pub mod fast_fn;
|
||||||
pub mod fast_timing;
|
pub mod fast_timing;
|
||||||
pub mod gas_fee_strategy;
|
pub mod gas_fee_strategy;
|
||||||
pub mod global;
|
pub mod global;
|
||||||
pub mod nonce_cache;
|
pub mod nonce_cache;
|
||||||
|
pub mod sdk_log;
|
||||||
pub mod seed;
|
pub mod seed;
|
||||||
pub mod spl_associated_token_account;
|
pub mod spl_associated_token_account;
|
||||||
pub mod spl_token;
|
pub mod spl_token;
|
||||||
pub mod spl_token_2022;
|
pub mod spl_token_2022;
|
||||||
pub mod subscription_handle;
|
pub mod subscription_handle;
|
||||||
pub mod types;
|
pub mod types;
|
||||||
pub mod address_lookup;
|
|
||||||
|
|
||||||
pub use gas_fee_strategy::*;
|
pub use gas_fee_strategy::*;
|
||||||
pub use types::*;
|
pub use types::*;
|
||||||
|
|||||||
+14
-14
@@ -1,8 +1,5 @@
|
|||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use solana_hash::Hash;
|
use solana_hash::Hash;
|
||||||
use solana_nonce::state::State;
|
|
||||||
use solana_nonce::versions::Versions;
|
|
||||||
use solana_sdk::account_utils::StateMut;
|
|
||||||
use solana_sdk::pubkey::Pubkey;
|
use solana_sdk::pubkey::Pubkey;
|
||||||
use tracing::error;
|
use tracing::error;
|
||||||
|
|
||||||
@@ -21,18 +18,21 @@ pub async fn fetch_nonce_info(
|
|||||||
nonce_account: Pubkey,
|
nonce_account: Pubkey,
|
||||||
) -> Option<DurableNonceInfo> {
|
) -> Option<DurableNonceInfo> {
|
||||||
match rpc.get_account(&nonce_account).await {
|
match rpc.get_account(&nonce_account).await {
|
||||||
Ok(account) => match account.state() {
|
Ok(account) => {
|
||||||
Ok(Versions::Current(state)) => {
|
// Parse nonce account manually: first 4 bytes is version, then 4 bytes authority type
|
||||||
if let State::Initialized(data) = *state {
|
// For initialized nonce: version=0, authority_type=0, then authority (32 bytes), then blockhash (32 bytes), then fee_calculator
|
||||||
let blockhash = data.durable_nonce.as_hash();
|
if account.data.len() >= 80 {
|
||||||
return Some(DurableNonceInfo {
|
// Skip version (4) + authority_type (4) + authority (32) = 40 bytes
|
||||||
nonce_account: Some(nonce_account),
|
// Then blockhash is at offset 40
|
||||||
current_nonce: Some(*blockhash),
|
let blockhash_bytes: [u8; 32] = account.data[40..72].try_into().ok()?;
|
||||||
});
|
return Some(DurableNonceInfo {
|
||||||
}
|
nonce_account: Some(nonce_account),
|
||||||
|
current_nonce: Some(Hash::from(blockhash_bytes)),
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
error!("Nonce account data too short");
|
||||||
}
|
}
|
||||||
_ => (),
|
}
|
||||||
},
|
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
error!("Failed to get nonce account information: {:?}", e);
|
error!("Failed to get nonce account information: {:?}", e);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,168 @@
|
|||||||
|
//! 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::fmt;
|
||||||
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
/// Format duration for log: "97.9396 ms" or "13.936 µs", 4 decimal places, space before unit.
|
||||||
|
fn format_elapsed(d: Duration) -> String {
|
||||||
|
let secs = d.as_secs_f64();
|
||||||
|
if secs < 0.001 {
|
||||||
|
format!("{:.4} µs", secs * 1_000_000.0)
|
||||||
|
} else {
|
||||||
|
format!("{:.4} ms", secs * 1000.0)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extract a short error message for SWQOS submission failed log.
|
||||||
|
/// Tries JSON "message"/"data" and quoted string; on any parse failure returns original (no panic).
|
||||||
|
fn extract_swqos_error_message(s: &str) -> String {
|
||||||
|
let s = s.trim();
|
||||||
|
if s.is_empty() {
|
||||||
|
return String::new();
|
||||||
|
}
|
||||||
|
// Plain double-quoted string (no inner JSON): unquote
|
||||||
|
if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
|
||||||
|
let inner = &s[1..s.len() - 1];
|
||||||
|
if !inner.contains('{') {
|
||||||
|
return inner.replace("\\\"", "\"");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// Try parse as JSON only when input looks like JSON (avoid parsing long non-JSON strings)
|
||||||
|
if s.starts_with('{') {
|
||||||
|
if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
|
||||||
|
let obj = v
|
||||||
|
.get("error")
|
||||||
|
.and_then(|e| e.as_object())
|
||||||
|
.or_else(|| v.as_object());
|
||||||
|
if let Some(o) = obj {
|
||||||
|
if let Some(m) = o.get("message").and_then(|x| x.as_str()) {
|
||||||
|
return m.to_string();
|
||||||
|
}
|
||||||
|
if let Some(d) = o.get("data").and_then(|x| x.as_str()) {
|
||||||
|
return d.to_string();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
s.to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
static SDK_LOG_ENABLED: AtomicBool = AtomicBool::new(true);
|
||||||
|
|
||||||
|
/// Width of [provider] label so SWQOS submit/confirm lines align (longest: Speedlanding).
|
||||||
|
pub const SWQOS_LABEL_WIDTH: usize = 12;
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aligned log: ` [Soyas ] Buy submitted: 13.936 µs`. Call only when sdk_log_enabled().
|
||||||
|
#[inline]
|
||||||
|
pub fn log_swqos_submitted(
|
||||||
|
provider: &str,
|
||||||
|
trade_type: impl fmt::Display,
|
||||||
|
elapsed: Duration,
|
||||||
|
) {
|
||||||
|
println!(
|
||||||
|
" [{:width$}] {} submitted: {}",
|
||||||
|
provider,
|
||||||
|
trade_type,
|
||||||
|
format_elapsed(elapsed),
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Prints one SDK timing block (build_instructions, before_submit, per-channel submit_done).
|
||||||
|
/// When confirm_us is Some, prints confirmed + total; when None, prints "confirmed: -, total: submit_ms".
|
||||||
|
/// Call only when sdk_log_enabled().
|
||||||
|
pub fn print_sdk_timing_block(
|
||||||
|
dir: &str,
|
||||||
|
start_us: Option<i64>,
|
||||||
|
build_end_us: Option<i64>,
|
||||||
|
before_submit_us: Option<i64>,
|
||||||
|
submit_timings: &[(crate::swqos::SwqosType, i64)],
|
||||||
|
confirm_us: Option<i64>,
|
||||||
|
) {
|
||||||
|
println!();
|
||||||
|
let start_us = match start_us {
|
||||||
|
Some(u) => u,
|
||||||
|
None => return,
|
||||||
|
};
|
||||||
|
if let Some(end_us) = build_end_us {
|
||||||
|
println!(
|
||||||
|
" [SDK][{:width$}] {} build_instructions: {:.4} ms",
|
||||||
|
"-",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0,
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(end_us) = before_submit_us {
|
||||||
|
println!(
|
||||||
|
" [SDK][{:width$}] {} before_submit: {:.4} ms",
|
||||||
|
"-",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0,
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if let Some(confirm_done_us) = confirm_us {
|
||||||
|
let total_ms = (confirm_done_us - start_us) as f64 / 1000.0;
|
||||||
|
for (swqos_type, submit_done_us) in submit_timings {
|
||||||
|
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||||
|
let confirmed_ms = (confirm_done_us - *submit_done_us).max(0) as f64 / 1000.0;
|
||||||
|
println!(
|
||||||
|
" [SDK][{:width$}] {} submit_done: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms",
|
||||||
|
swqos_type.as_str(),
|
||||||
|
dir,
|
||||||
|
submit_ms,
|
||||||
|
confirmed_ms,
|
||||||
|
total_ms,
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
for (swqos_type, submit_done_us) in submit_timings {
|
||||||
|
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||||
|
println!(
|
||||||
|
" [SDK][{:width$}] {} submit_done: {:.4} ms, confirmed: -, total: {:.4} ms",
|
||||||
|
swqos_type.as_str(),
|
||||||
|
dir,
|
||||||
|
submit_ms,
|
||||||
|
submit_ms,
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Aligned log: ` [Stellium ] Buy submission failed after 97.9396 ms: ...`. Call only when sdk_log_enabled().
|
||||||
|
/// Error is normalized: JSON "message"/"data" or quoted string is shown; raw JSON is not.
|
||||||
|
#[inline]
|
||||||
|
pub fn log_swqos_submission_failed(
|
||||||
|
provider: &str,
|
||||||
|
trade_type: impl fmt::Display,
|
||||||
|
elapsed: Duration,
|
||||||
|
err: impl fmt::Display,
|
||||||
|
) {
|
||||||
|
let msg = extract_swqos_error_message(&format!("{}", err));
|
||||||
|
eprintln!(
|
||||||
|
" [{:width$}] {} submission failed after {}, error: {}",
|
||||||
|
provider,
|
||||||
|
trade_type,
|
||||||
|
format_elapsed(elapsed),
|
||||||
|
msg,
|
||||||
|
width = SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
+25
-11
@@ -1,13 +1,13 @@
|
|||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use fnv::FnvHasher;
|
use fnv::FnvHasher;
|
||||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
|
||||||
use solana_system_interface::instruction::create_account_with_seed;
|
|
||||||
use std::hash::Hasher;
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use tokio::time::{sleep, Duration};
|
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
|
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
||||||
|
use solana_system_interface::instruction as system_instruction;
|
||||||
|
use std::hash::Hasher;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use tokio::time::{sleep, Duration};
|
||||||
|
|
||||||
// 🚀 优化:使用 AtomicU64 替代 RwLock,性能提升 5-10x
|
// 🚀 优化:使用 AtomicU64 替代 RwLock,性能提升 5-10x
|
||||||
// u64::MAX 表示未初始化状态
|
// u64::MAX 表示未初始化状态
|
||||||
@@ -17,7 +17,7 @@ static SPL_TOKEN_2022_RENT: Lazy<AtomicU64> = Lazy::new(|| AtomicU64::new(u64::M
|
|||||||
/// 更新租金缓存(后台任务调用)
|
/// 更新租金缓存(后台任务调用)
|
||||||
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
||||||
let rent = fetch_rent_for_token_account(client, false).await?;
|
let rent = fetch_rent_for_token_account(client, false).await?;
|
||||||
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
||||||
|
|
||||||
let rent = fetch_rent_for_token_account(client, true).await?;
|
let rent = fetch_rent_for_token_account(client, true).await?;
|
||||||
SPL_TOKEN_2022_RENT.store(rent, Ordering::Release);
|
SPL_TOKEN_2022_RENT.store(rent, Ordering::Release);
|
||||||
@@ -25,6 +25,15 @@ pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error>
|
|||||||
Ok(())
|
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>) {
|
pub fn start_rent_updater(client: Arc<SolanaRpcClient>) {
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
loop {
|
loop {
|
||||||
@@ -53,11 +62,15 @@ pub fn create_associated_token_account_use_seed(
|
|||||||
// Relaxed: 租金值不变,无需同步;Release/Acquire 在 update_rents 保证初始化可见性
|
// Relaxed: 租金值不变,无需同步;Release/Acquire 在 update_rents 保证初始化可见性
|
||||||
let rent = if is_2022_token {
|
let rent = if is_2022_token {
|
||||||
let v = SPL_TOKEN_2022_RENT.load(Ordering::Relaxed);
|
let v = SPL_TOKEN_2022_RENT.load(Ordering::Relaxed);
|
||||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
if v == u64::MAX {
|
||||||
|
return Err(anyhow!("Rent not initialized"));
|
||||||
|
}
|
||||||
v
|
v
|
||||||
} else {
|
} else {
|
||||||
let v = SPL_TOKEN_RENT.load(Ordering::Relaxed);
|
let v = SPL_TOKEN_RENT.load(Ordering::Relaxed);
|
||||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
if v == u64::MAX {
|
||||||
|
return Err(anyhow!("Rent not initialized"));
|
||||||
|
}
|
||||||
v
|
v
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -79,9 +92,10 @@ pub fn create_associated_token_account_use_seed(
|
|||||||
let ata_like = Pubkey::create_with_seed(payer, seed, token_program)?;
|
let ata_like = Pubkey::create_with_seed(payer, seed, token_program)?;
|
||||||
|
|
||||||
let len = 165;
|
let len = 165;
|
||||||
// 但账户的 owner 仍然使用正确的 token_program(Token 或 Token-2022)
|
// 🔧 修复:create_account_with_seed 的第3个参数必须是 payer(与第92行生成地址时使用的 base 一致)
|
||||||
|
// 否则创建的账户地址与 ata_like 不匹配,导致 initializeAccount3 失败
|
||||||
let create_acc =
|
let create_acc =
|
||||||
create_account_with_seed(payer, &ata_like, owner, seed, rent, len, token_program);
|
system_instruction::create_account_with_seed(payer, &ata_like, payer, seed, rent, len, token_program);
|
||||||
|
|
||||||
let init_acc = if is_2022_token {
|
let init_acc = if is_2022_token {
|
||||||
crate::common::spl_token_2022::initialize_account3(&token_program, &ata_like, mint, owner)?
|
crate::common::spl_token_2022::initialize_account3(&token_program, &ata_like, mint, owner)?
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
use solana_sdk::{
|
use solana_sdk::{
|
||||||
message::{AccountMeta, Instruction},
|
instruction::{AccountMeta, Instruction},
|
||||||
pubkey::Pubkey,
|
pubkey::Pubkey,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+6
-10
@@ -1,6 +1,6 @@
|
|||||||
use solana_program::pubkey;
|
use solana_program::pubkey;
|
||||||
use solana_sdk::{
|
use solana_sdk::{
|
||||||
message::{AccountMeta, Instruction},
|
instruction::{AccountMeta, Instruction},
|
||||||
program_error::ProgramError,
|
program_error::ProgramError,
|
||||||
pubkey::Pubkey,
|
pubkey::Pubkey,
|
||||||
};
|
};
|
||||||
@@ -18,14 +18,14 @@ pub fn close_account(
|
|||||||
let mut data = Vec::with_capacity(1);
|
let mut data = Vec::with_capacity(1);
|
||||||
data.push(9);
|
data.push(9);
|
||||||
let mut accounts = Vec::with_capacity(3 + signer_pubkeys.len());
|
let mut accounts = Vec::with_capacity(3 + signer_pubkeys.len());
|
||||||
accounts.push(solana_sdk::message::AccountMeta::new(*account_pubkey, false));
|
accounts.push(AccountMeta::new(*account_pubkey, false));
|
||||||
accounts.push(solana_sdk::message::AccountMeta::new(*destination_pubkey, false));
|
accounts.push(AccountMeta::new(*destination_pubkey, false));
|
||||||
accounts.push(solana_sdk::message::AccountMeta::new_readonly(
|
accounts.push(AccountMeta::new_readonly(
|
||||||
*owner_pubkey,
|
*owner_pubkey,
|
||||||
signer_pubkeys.is_empty(),
|
signer_pubkeys.is_empty(),
|
||||||
));
|
));
|
||||||
for signer_pubkey in signer_pubkeys.iter() {
|
for signer_pubkey in signer_pubkeys.iter() {
|
||||||
accounts.push(solana_sdk::message::AccountMeta::new_readonly(**signer_pubkey, true));
|
accounts.push(AccountMeta::new_readonly(**signer_pubkey, true));
|
||||||
}
|
}
|
||||||
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
||||||
}
|
}
|
||||||
@@ -52,11 +52,7 @@ pub fn transfer(
|
|||||||
accounts.push(AccountMeta::new_readonly(**signer, true));
|
accounts.push(AccountMeta::new_readonly(**signer, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Instruction {
|
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
||||||
program_id: *token_program_id,
|
|
||||||
accounts,
|
|
||||||
data,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn initialize_account3(
|
pub fn initialize_account3(
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
use solana_program::pubkey;
|
use solana_program::pubkey;
|
||||||
use solana_sdk::{
|
use solana_sdk::{
|
||||||
message::{AccountMeta, Instruction},
|
instruction::{AccountMeta, Instruction},
|
||||||
program_error::ProgramError,
|
program_error::ProgramError,
|
||||||
pubkey::Pubkey,
|
pubkey::Pubkey,
|
||||||
};
|
};
|
||||||
|
|||||||
+134
-13
@@ -9,6 +9,12 @@ pub struct InfrastructureConfig {
|
|||||||
pub rpc_url: String,
|
pub rpc_url: String,
|
||||||
pub swqos_configs: Vec<SwqosConfig>,
|
pub swqos_configs: Vec<SwqosConfig>,
|
||||||
pub commitment: CommitmentConfig,
|
pub commitment: CommitmentConfig,
|
||||||
|
/// When true, SWQOS sender threads use the *last* N cores instead of the first N. Reduces contention with main thread / default tokio workers that often use low-numbered cores. Default false.
|
||||||
|
pub swqos_cores_from_end: bool,
|
||||||
|
/// Global MEV protection flag. When true, SWQOS providers that support MEV protection
|
||||||
|
/// (Astralane QUIC `:9000` or HTTP `mev-protect=true`, BlockRazor) use MEV-protected
|
||||||
|
/// endpoints/modes. Default false.
|
||||||
|
pub mev_protection: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl InfrastructureConfig {
|
impl InfrastructureConfig {
|
||||||
@@ -21,6 +27,8 @@ impl InfrastructureConfig {
|
|||||||
rpc_url,
|
rpc_url,
|
||||||
swqos_configs,
|
swqos_configs,
|
||||||
commitment,
|
commitment,
|
||||||
|
swqos_cores_from_end: false,
|
||||||
|
mev_protection: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -30,6 +38,8 @@ impl InfrastructureConfig {
|
|||||||
rpc_url: config.rpc_url.clone(),
|
rpc_url: config.rpc_url.clone(),
|
||||||
swqos_configs: config.swqos_configs.clone(),
|
swqos_configs: config.swqos_configs.clone(),
|
||||||
commitment: config.commitment.clone(),
|
commitment: config.commitment.clone(),
|
||||||
|
swqos_cores_from_end: config.swqos_cores_from_end,
|
||||||
|
mev_protection: config.mev_protection,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,8 +57,9 @@ impl Hash for InfrastructureConfig {
|
|||||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||||
self.rpc_url.hash(state);
|
self.rpc_url.hash(state);
|
||||||
self.swqos_configs.hash(state);
|
self.swqos_configs.hash(state);
|
||||||
// Hash commitment level as string since CommitmentConfig doesn't impl Hash
|
|
||||||
format!("{:?}", self.commitment).hash(state);
|
format!("{:?}", self.commitment).hash(state);
|
||||||
|
self.swqos_cores_from_end.hash(state);
|
||||||
|
self.mev_protection.hash(state);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -57,6 +68,8 @@ impl PartialEq for InfrastructureConfig {
|
|||||||
self.rpc_url == other.rpc_url
|
self.rpc_url == other.rpc_url
|
||||||
&& self.swqos_configs == other.swqos_configs
|
&& self.swqos_configs == other.swqos_configs
|
||||||
&& self.commitment == other.commitment
|
&& self.commitment == other.commitment
|
||||||
|
&& self.swqos_cores_from_end == other.swqos_cores_from_end
|
||||||
|
&& self.mev_protection == other.mev_protection
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -72,35 +85,143 @@ pub struct TradeConfig {
|
|||||||
pub create_wsol_ata_on_startup: bool,
|
pub create_wsol_ata_on_startup: bool,
|
||||||
/// Whether to use seed optimization for all ATA operations (default: true)
|
/// Whether to use seed optimization for all ATA operations (default: true)
|
||||||
pub use_seed_optimize: bool,
|
pub use_seed_optimize: 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,
|
||||||
|
/// When true, SWQOS uses the *last* N cores (instead of the first N). Use when main thread / tokio use low-numbered cores to reduce CPU contention. Default false.
|
||||||
|
pub swqos_cores_from_end: bool,
|
||||||
|
/// Global MEV protection flag. When true, SWQOS providers that support MEV protection
|
||||||
|
/// (Astralane QUIC `:9000` or Plain/Binary HTTP `mev-protect=true`, BlockRazor sandwichMitigation)
|
||||||
|
/// use their MEV-protected endpoints/modes. Default false (no MEV protection, lower latency).
|
||||||
|
pub mev_protection: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TradeConfig {
|
impl TradeConfig {
|
||||||
|
/// Create a new TradeConfig using the builder pattern.
|
||||||
|
///
|
||||||
|
/// # Available builder methods
|
||||||
|
/// - `.create_wsol_ata_on_startup(bool)` — check & create WSOL ATA on init (default: true)
|
||||||
|
/// - `.use_seed_optimize(bool)` — seed optimization for ATA ops (default: true)
|
||||||
|
/// - `.log_enabled(bool)` — SDK timing/SWQOS logs (default: true)
|
||||||
|
/// - `.check_min_tip(bool)` — filter SWQOS below min tip (default: false)
|
||||||
|
/// - `.swqos_cores_from_end(bool)` — bind SWQOS to last N cores (default: false)
|
||||||
|
/// - `.mev_protection(bool)` — MEV protection for Astralane/BlockRazor (default: false)
|
||||||
|
///
|
||||||
|
/// # Example
|
||||||
|
/// ```rust
|
||||||
|
/// let config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||||
|
/// .mev_protection(true)
|
||||||
|
/// .check_min_tip(true)
|
||||||
|
/// .log_enabled(false)
|
||||||
|
/// .build();
|
||||||
|
/// ```
|
||||||
|
pub fn builder(
|
||||||
|
rpc_url: String,
|
||||||
|
swqos_configs: Vec<SwqosConfig>,
|
||||||
|
commitment: CommitmentConfig,
|
||||||
|
) -> TradeConfigBuilder {
|
||||||
|
TradeConfigBuilder::new(rpc_url, swqos_configs, commitment)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Shortcut: create a TradeConfig with all defaults. Equivalent to `builder(...).build()`.
|
||||||
pub fn new(
|
pub fn new(
|
||||||
rpc_url: String,
|
rpc_url: String,
|
||||||
swqos_configs: Vec<SwqosConfig>,
|
swqos_configs: Vec<SwqosConfig>,
|
||||||
commitment: CommitmentConfig,
|
commitment: CommitmentConfig,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
println!("🔧 TradeConfig create_wsol_ata_on_startup default value: true");
|
Self::builder(rpc_url, swqos_configs, commitment).build()
|
||||||
println!("🔧 TradeConfig use_seed_optimize default value: true");
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Builder for [`TradeConfig`]. Created via [`TradeConfig::builder`].
|
||||||
|
///
|
||||||
|
/// All fields are optional and pre-filled with sensible defaults.
|
||||||
|
/// Call `.build()` to produce the final [`TradeConfig`].
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct TradeConfigBuilder {
|
||||||
|
rpc_url: String,
|
||||||
|
swqos_configs: Vec<SwqosConfig>,
|
||||||
|
commitment: CommitmentConfig,
|
||||||
|
create_wsol_ata_on_startup: bool,
|
||||||
|
use_seed_optimize: bool,
|
||||||
|
log_enabled: bool,
|
||||||
|
check_min_tip: bool,
|
||||||
|
swqos_cores_from_end: bool,
|
||||||
|
mev_protection: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TradeConfigBuilder {
|
||||||
|
fn new(rpc_url: String, swqos_configs: Vec<SwqosConfig>, commitment: CommitmentConfig) -> Self {
|
||||||
Self {
|
Self {
|
||||||
rpc_url,
|
rpc_url,
|
||||||
swqos_configs,
|
swqos_configs,
|
||||||
commitment,
|
commitment,
|
||||||
create_wsol_ata_on_startup: true, // 默认:启动时检查并创建
|
create_wsol_ata_on_startup: true,
|
||||||
use_seed_optimize: true, // 默认:使用seed优化
|
use_seed_optimize: true,
|
||||||
|
log_enabled: true,
|
||||||
|
check_min_tip: false,
|
||||||
|
swqos_cores_from_end: false,
|
||||||
|
mev_protection: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a TradeConfig with custom WSOL ATA settings
|
/// Check and create WSOL ATA on SDK initialization. Default: `true`.
|
||||||
pub fn with_wsol_ata_config(
|
pub fn create_wsol_ata_on_startup(mut self, v: bool) -> Self {
|
||||||
mut self,
|
self.create_wsol_ata_on_startup = v;
|
||||||
create_wsol_ata_on_startup: bool,
|
|
||||||
use_seed_optimize: bool,
|
|
||||||
) -> Self {
|
|
||||||
self.create_wsol_ata_on_startup = create_wsol_ata_on_startup;
|
|
||||||
self.use_seed_optimize = use_seed_optimize;
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Enable seed optimization for all ATA operations. Default: `true`.
|
||||||
|
pub fn use_seed_optimize(mut self, v: bool) -> Self {
|
||||||
|
self.use_seed_optimize = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enable SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default: `true`.
|
||||||
|
pub fn log_enabled(mut self, v: bool) -> Self {
|
||||||
|
self.log_enabled = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Filter out SWQOS providers whose tip is below their minimum requirement.
|
||||||
|
/// Adds a small check on the hot path; disable for lowest latency. Default: `false`.
|
||||||
|
pub fn check_min_tip(mut self, v: bool) -> Self {
|
||||||
|
self.check_min_tip = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Bind SWQOS sender threads to the *last* N CPU cores instead of the first N.
|
||||||
|
/// Useful when main thread / tokio workers occupy low-numbered cores. Default: `false`.
|
||||||
|
pub fn swqos_cores_from_end(mut self, v: bool) -> Self {
|
||||||
|
self.swqos_cores_from_end = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Enable global MEV protection. When `true`:
|
||||||
|
/// - **Astralane QUIC** uses port `9000`; **Astralane HTTP** adds `mev-protect=true`
|
||||||
|
/// - **BlockRazor** uses `mode=sandwichMitigation` (skips blacklisted Leader slots)
|
||||||
|
///
|
||||||
|
/// May reduce landing speed. Default: `false`.
|
||||||
|
pub fn mev_protection(mut self, v: bool) -> Self {
|
||||||
|
self.mev_protection = v;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Consume the builder and produce a [`TradeConfig`].
|
||||||
|
pub fn build(self) -> TradeConfig {
|
||||||
|
TradeConfig {
|
||||||
|
rpc_url: self.rpc_url,
|
||||||
|
swqos_configs: self.swqos_configs,
|
||||||
|
commitment: self.commitment,
|
||||||
|
create_wsol_ata_on_startup: self.create_wsol_ata_on_startup,
|
||||||
|
use_seed_optimize: self.use_seed_optimize,
|
||||||
|
log_enabled: self.log_enabled,
|
||||||
|
check_min_tip: self.check_min_tip,
|
||||||
|
swqos_cores_from_end: self.swqos_cores_from_end,
|
||||||
|
mev_protection: self.mev_protection,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub type SolanaRpcClient = solana_client::nonblocking::rpc_client::RpcClient;
|
pub type SolanaRpcClient = solana_client::nonblocking::rpc_client::RpcClient;
|
||||||
|
|||||||
@@ -43,8 +43,7 @@ pub const USD1_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
|||||||
};
|
};
|
||||||
|
|
||||||
// USDC (mainnet) mint and meta
|
// USDC (mainnet) mint and meta
|
||||||
pub const USDC_TOKEN_ACCOUNT: Pubkey =
|
pub const USDC_TOKEN_ACCOUNT: Pubkey = pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
||||||
pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
||||||
pub const USDC_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
pub const USDC_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
||||||
solana_sdk::instruction::AccountMeta {
|
solana_sdk::instruction::AccountMeta {
|
||||||
pubkey: USDC_TOKEN_ACCOUNT,
|
pubkey: USDC_TOKEN_ACCOUNT,
|
||||||
|
|||||||
+291
-65
@@ -1,7 +1,6 @@
|
|||||||
use solana_program::pubkey;
|
use solana_program::pubkey;
|
||||||
use solana_sdk::pubkey::Pubkey;
|
use solana_sdk::pubkey::Pubkey;
|
||||||
|
|
||||||
|
|
||||||
pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
pubkey!("96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"),
|
pubkey!("96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"),
|
||||||
pubkey!("HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe"),
|
pubkey!("HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe"),
|
||||||
@@ -13,6 +12,20 @@ pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
|||||||
pubkey!("3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT"),
|
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] = &[
|
pub const NEXTBLOCK_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
pubkey!("NextbLoCkVtMGcV47JzewQdvBpLqT9TxQFozQkN98pE"),
|
pubkey!("NextbLoCkVtMGcV47JzewQdvBpLqT9TxQFozQkN98pE"),
|
||||||
pubkey!("NexTbLoCkWykbLuB1NkjXgFWkX9oAtcoagQegygXXA2"),
|
pubkey!("NexTbLoCkWykbLuB1NkjXgFWkX9oAtcoagQegygXXA2"),
|
||||||
@@ -98,6 +111,7 @@ pub const BLOCKRAZOR_TIP_ACCOUNTS: &[Pubkey] = &[
|
|||||||
pubkey!("AP6qExwrbRgBAVaehg4b5xHENX815sMabtBzUzVB4v8S"),
|
pubkey!("AP6qExwrbRgBAVaehg4b5xHENX815sMabtBzUzVB4v8S"),
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// Astralane tip wallets. Extended with new addresses for improved routing and reduced write-lock contention (see portal.astralane.io/blockline).
|
||||||
pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
pubkey!("astrazznxsGUhWShqgNtAdfrzP2G83DzcWVJDxwV9bF"),
|
pubkey!("astrazznxsGUhWShqgNtAdfrzP2G83DzcWVJDxwV9bF"),
|
||||||
pubkey!("astra4uejePWneqNaJKuFFA8oonqCE1sqF6b45kDMZm"),
|
pubkey!("astra4uejePWneqNaJKuFFA8oonqCE1sqF6b45kDMZm"),
|
||||||
@@ -107,6 +121,16 @@ pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
|||||||
pubkey!("astraubkDw81n4LuutzSQ8uzHCv4BhPVhfvTcYv8SKC"),
|
pubkey!("astraubkDw81n4LuutzSQ8uzHCv4BhPVhfvTcYv8SKC"),
|
||||||
pubkey!("astraZW5GLFefxNPAatceHhYjfA1ciq9gvfEg2S47xk"),
|
pubkey!("astraZW5GLFefxNPAatceHhYjfA1ciq9gvfEg2S47xk"),
|
||||||
pubkey!("astrawVNP4xDBKT7rAdxrLYiTSTdqtUr63fSMduivXK"),
|
pubkey!("astrawVNP4xDBKT7rAdxrLYiTSTdqtUr63fSMduivXK"),
|
||||||
|
// New tip wallets (2025) for improved performance and reduced write-lock delays
|
||||||
|
pubkey!("AstrA1ejL4UeXC2SBP4cpeEmtcFPZVLxx3XGKXyCW6to"),
|
||||||
|
pubkey!("AsTra79FET4aCKWspPqeSFvjJNyp96SvAnrmyAxqg5b7"),
|
||||||
|
pubkey!("AstrABAu8CBTyuPXpV4eSCJ5fePEPnxN8NqBaPKQ9fHR"),
|
||||||
|
pubkey!("AsTRADtvb6tTmrsqULQ9Wji9PigDMjhfEMza6zkynEvV"),
|
||||||
|
pubkey!("AsTRAEoyMofR3vUPpf9k68Gsfb6ymTZttEtsAbv8Bk4d"),
|
||||||
|
pubkey!("AStrAJv2RN2hKCHxwUMtqmSxgdcNZbihCwc1mCSnG83W"),
|
||||||
|
pubkey!("Astran35aiQUF57XZsmkWMtNCtXGLzs8upfiqXxth2bz"),
|
||||||
|
pubkey!("AStRAnpi6kFrKypragExgeRoJ1QnKH7pbSjLAKQVWUum"),
|
||||||
|
pubkey!("ASTRaoF93eYt73TYvwtsv6fMWHWbGmMUZfVZPo3CRU9C"),
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const STELLIUM_TIP_ACCOUNTS: &[Pubkey] = &[
|
pub const STELLIUM_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
@@ -128,6 +152,12 @@ pub const SOYAS_TIP_ACCOUNTS: &[Pubkey] = &[
|
|||||||
pubkey!("soyascXFW5wEEYiwfEmHy2pNwomqzvggJosGVD6TJdY"),
|
pubkey!("soyascXFW5wEEYiwfEmHy2pNwomqzvggJosGVD6TJdY"),
|
||||||
pubkey!("soyasDBdKjADwPz3xk82U3TNPRDKEWJj7wWLajNHZ1L"),
|
pubkey!("soyasDBdKjADwPz3xk82U3TNPRDKEWJj7wWLajNHZ1L"),
|
||||||
pubkey!("soyasE2abjBAynmHbGWgEwk4ctBy7JMTUCNrMbjcnyH"),
|
pubkey!("soyasE2abjBAynmHbGWgEwk4ctBy7JMTUCNrMbjcnyH"),
|
||||||
|
pubkey!("soyasi59njacMUPvo3TM5paHjeK8pYSdovXgFi32gRt"),
|
||||||
|
pubkey!("soyasQYhJxv8uZgWDxhg72td6piAf7XTkoyWHtSATEz"),
|
||||||
|
pubkey!("soyastP66xyYC8XADXZjdMM5BAVGD2YRvz8dwtLsqb8"),
|
||||||
|
pubkey!("soyasvdgUJWYcUCzDxpmjUnNjH7KamXLXTzLwFvdVPE"),
|
||||||
|
pubkey!("soyasvxAunisNxaoRxkKGjNir7KmbwYnr37JmefkX9G"),
|
||||||
|
pubkey!("soyas5doVFUwH8s5zK8gEvCL5KR5ogDmf52LsrJEZ9h"),
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SPEEDLANDING_TIP_ACCOUNTS: &[Pubkey] = &[
|
pub const SPEEDLANDING_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
@@ -141,145 +171,267 @@ pub const SPEEDLANDING_TIP_ACCOUNTS: &[Pubkey] = &[
|
|||||||
pubkey!("speede8xCcUq2Tiv1efXeTuE3k9TDNq8TnGKaKSc6J4"),
|
pubkey!("speede8xCcUq2Tiv1efXeTuE3k9TDNq8TnGKaKSc6J4"),
|
||||||
];
|
];
|
||||||
|
|
||||||
// NewYork,
|
// `SwqosRegion` 与下列各 `SWQOS_ENDPOINTS_*` 下标严格对应(共 10 项):
|
||||||
// Frankfurt,
|
// 0 NewYork, 1 Frankfurt, 2 Amsterdam, 3 Dublin, 4 SLC, 5 Tokyo, 6 Singapore, 7 London, 8 LosAngeles, 9 Default。
|
||||||
// Amsterdam,
|
//
|
||||||
// SLC,
|
// **地理就近(用户语义)**:当某枚举区域没有该服务商**独立公布**的 PoP 时,在**该服务商已出现的端点集合内**,按真实地理位置选**大圆距离最近**的一项作为填充;行尾注释说明依据。
|
||||||
// Tokyo,
|
// **例外**:`SwqosRegion::Default`(下标 9)不表示地球上的点,表中为全局 URL 或文档默认枢纽,**不适用**地理就近,仅表示「未指定区域时的回退」。
|
||||||
// London,
|
// 若某区域仅有一种「大区」级入口(例如全美只有一个美东 PoP),则地理上非最优但只能复用,注释会标明「受服务商可用区限制」。
|
||||||
// LosAngeles,
|
|
||||||
// Default,
|
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_JITO: [&str; 8] = [
|
/// Jito mainnet block engines (`https://<region>.mainnet.block-engine.jito.wtf`).
|
||||||
"https://ny.mainnet.block-engine.jito.wtf",
|
/// There is no Los Angeles engine → use Salt Lake City for `LosAngeles`; `SwqosRegion::Default` uses the global mainnet URL.
|
||||||
|
pub const SWQOS_ENDPOINTS_JITO: [&str; 10] = [
|
||||||
|
"https://ny.mainnet.block-engine.jito.wtf",
|
||||||
"https://frankfurt.mainnet.block-engine.jito.wtf",
|
"https://frankfurt.mainnet.block-engine.jito.wtf",
|
||||||
"https://amsterdam.mainnet.block-engine.jito.wtf",
|
"https://amsterdam.mainnet.block-engine.jito.wtf",
|
||||||
|
"https://dublin.mainnet.block-engine.jito.wtf",
|
||||||
"https://slc.mainnet.block-engine.jito.wtf",
|
"https://slc.mainnet.block-engine.jito.wtf",
|
||||||
"https://tokyo.mainnet.block-engine.jito.wtf",
|
"https://tokyo.mainnet.block-engine.jito.wtf",
|
||||||
|
"https://singapore.mainnet.block-engine.jito.wtf",
|
||||||
"https://london.mainnet.block-engine.jito.wtf",
|
"https://london.mainnet.block-engine.jito.wtf",
|
||||||
"https://ny.mainnet.block-engine.jito.wtf",
|
"https://slc.mainnet.block-engine.jito.wtf", // LosAngeles: no LA PoP; nearest US-West is SLC
|
||||||
"https://mainnet.block-engine.jito.wtf",
|
"https://mainnet.block-engine.jito.wtf",
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_NEXTBLOCK: [&str; 8] = [
|
/// NextBlock regional HTTP hosts (see provider docs). `SwqosRegion` order; no dedicated LA PoP → SLC as US-West fallback.
|
||||||
|
pub const SWQOS_ENDPOINTS_NEXTBLOCK: [&str; 10] = [
|
||||||
"http://ny.nextblock.io",
|
"http://ny.nextblock.io",
|
||||||
"http://frankfurt.nextblock.io",
|
"http://fra.nextblock.io",
|
||||||
"http://amsterdam.nextblock.io",
|
"http://ams.nextblock.io",
|
||||||
|
"http://dublin.nextblock.io",
|
||||||
"http://slc.nextblock.io",
|
"http://slc.nextblock.io",
|
||||||
"http://tokyo.nextblock.io",
|
"http://tokyo.nextblock.io",
|
||||||
"http://london.nextblock.io",
|
"http://sgp.nextblock.io",
|
||||||
"http://singapore.nextblock.io",
|
"http://london.nextblock.io",
|
||||||
"http://frankfurt.nextblock.io",
|
"http://slc.nextblock.io",
|
||||||
|
"http://fra.nextblock.io", // Default: 非地理区域;服务商无「全局」主机名时用 EU 枢纽作未选区回退
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_ZERO_SLOT: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_ZERO_SLOT: [&str; 10] = [
|
||||||
"http://ny.0slot.trade",
|
"http://ny.0slot.trade",
|
||||||
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
|
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
|
||||||
"http://ams.0slot.trade",
|
"http://ams.0slot.trade",
|
||||||
"http://ny.0slot.trade",
|
"http://ams.0slot.trade", // Dublin: 无 IE 专用;在已公布 EU 点中选距爱尔兰最近的 ams(相对 de2 等)
|
||||||
|
"http://la.0slot.trade", // SLC: no UT PoP; nearest US-West published host
|
||||||
"http://jp.0slot.trade",
|
"http://jp.0slot.trade",
|
||||||
"http://ams.0slot.trade",
|
"http://jp.0slot.trade", // SG: 无本地 PoP;已公布 APAC 仅 jp,为表中离新加坡最近的大圆距离
|
||||||
|
"http://ams.0slot.trade", // London: 无 UK 专用;已公布 EU 点中 ams 距伦敦最近之一
|
||||||
"http://la.0slot.trade",
|
"http://la.0slot.trade",
|
||||||
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
|
"http://de2.0slot.trade", // Default: 非地理区域;EU 枢纽 de2 作未选区回退
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_TEMPORAL: [&str; 8] = [
|
/// Nozomi Direct regions: ewr1, fra2, ams1, lon1, lax1, tyo1, sgp1, …
|
||||||
"http://ewr1.nozomi.temporal.xyz",
|
pub const SWQOS_ENDPOINTS_TEMPORAL: [&str; 10] = [
|
||||||
|
"http://ewr1.nozomi.temporal.xyz", // NewYork → Newark
|
||||||
"http://fra2.nozomi.temporal.xyz",
|
"http://fra2.nozomi.temporal.xyz",
|
||||||
"http://ams1.nozomi.temporal.xyz",
|
"http://ams1.nozomi.temporal.xyz",
|
||||||
"http://ewr1.nozomi.temporal.xyz",
|
"http://lon1.nozomi.temporal.xyz", // Dublin: no IE host; UK nearest Direct PoP
|
||||||
|
"http://lax1.nozomi.temporal.xyz", // SLC: US-West
|
||||||
"http://tyo1.nozomi.temporal.xyz",
|
"http://tyo1.nozomi.temporal.xyz",
|
||||||
"http://sgp1.nozomi.temporal.xyz",
|
"http://sgp1.nozomi.temporal.xyz",
|
||||||
"http://pit1.nozomi.temporal.xyz",
|
"http://lon1.nozomi.temporal.xyz",
|
||||||
"http://fra2.nozomi.temporal.xyz",
|
"http://lax1.nozomi.temporal.xyz",
|
||||||
|
"http://fra2.nozomi.temporal.xyz", // Default: 非地理区域;EU Direct 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_BLOX: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_BLOX: [&str; 10] = [
|
||||||
"https://ny.solana.dex.blxrbdn.com",
|
"https://ny.solana.dex.blxrbdn.com",
|
||||||
"https://germany.solana.dex.blxrbdn.com",
|
"https://germany.solana.dex.blxrbdn.com",
|
||||||
"https://amsterdam.solana.dex.blxrbdn.com",
|
"https://amsterdam.solana.dex.blxrbdn.com",
|
||||||
"https://ny.solana.dex.blxrbdn.com",
|
"https://uk.solana.dex.blxrbdn.com", // Dublin: IE/UK edge
|
||||||
|
"https://la.solana.dex.blxrbdn.com", // SLC: no Mountain PoP; US-West LA
|
||||||
"https://tokyo.solana.dex.blxrbdn.com",
|
"https://tokyo.solana.dex.blxrbdn.com",
|
||||||
|
"https://tokyo.solana.dex.blxrbdn.com", // SG: 文档无 SGP 区域;已公布 APAC 仅 Tokyo,为距 SG 最近选项
|
||||||
"https://uk.solana.dex.blxrbdn.com",
|
"https://uk.solana.dex.blxrbdn.com",
|
||||||
"https://la.solana.dex.blxrbdn.com",
|
"https://la.solana.dex.blxrbdn.com",
|
||||||
"https://global.solana.dex.blxrbdn.com",
|
"https://global.solana.dex.blxrbdn.com", // Default: 非地理区域;全球任播
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_NODE1: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_NODE1: [&str; 10] = [
|
||||||
"http://ny.node1.me",
|
"http://ny.node1.me",
|
||||||
"http://fra.node1.me",
|
"http://fra.node1.me",
|
||||||
"http://ams.node1.me",
|
"http://ams.node1.me",
|
||||||
"http://ny.node1.me",
|
"http://lon.node1.me", // Dublin: 已公布中英爱区域用 lon(地理上近爱尔兰)
|
||||||
|
"http://ny.node1.me", // SLC: 已公布美国仅 ny;美西无 PoP,受可用区限制复用美东
|
||||||
"http://tk.node1.me",
|
"http://tk.node1.me",
|
||||||
|
"http://tk.node1.me", // SG: 已公布 APAC 仅 tk;地理上为表中离 SG 最近
|
||||||
"http://lon.node1.me",
|
"http://lon.node1.me",
|
||||||
"http://ny.node1.me",
|
"http://ny.node1.me", // LosAngeles: 同上,美国仅 ny 入口
|
||||||
"http://fra.node1.me",
|
"http://fra.node1.me", // Default: 非地理区域;与 QUIC 对齐为 EU 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
/// Node1 QUIC: port 16666. Region order matches [`SwqosRegion`].
|
||||||
|
/// server_name = host part (e.g. ny.node1.me). Auth: first bi stream = 16-byte UUID; each tx = new bi stream, bincode body.
|
||||||
|
pub const SWQOS_ENDPOINTS_NODE1_QUIC: [&str; 10] = [
|
||||||
|
"ny.node1.me:16666",
|
||||||
|
"fra.node1.me:16666",
|
||||||
|
"ams.node1.me:16666",
|
||||||
|
"lon.node1.me:16666",
|
||||||
|
"ny.node1.me:16666",
|
||||||
|
"tk.node1.me:16666",
|
||||||
|
"tk.node1.me:16666",
|
||||||
|
"lon.node1.me:16666",
|
||||||
|
"ny.node1.me:16666",
|
||||||
|
"fra.node1.me:16666", // Default: 非地理区域;与 HTTP 对齐为 EU 枢纽
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Published: ny, slc, ams, fra, singapore, london, tokyo (no IE/UK split → london for Dublin).
|
||||||
|
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 10] = [
|
||||||
"http://ny.flashblock.trade",
|
"http://ny.flashblock.trade",
|
||||||
"http://fra.flashblock.trade",
|
"http://fra.flashblock.trade",
|
||||||
"http://ams.flashblock.trade",
|
"http://ams.flashblock.trade",
|
||||||
|
"http://london.flashblock.trade", // Dublin: no IE host; UK nearest
|
||||||
"http://slc.flashblock.trade",
|
"http://slc.flashblock.trade",
|
||||||
|
"http://tokyo.flashblock.trade",
|
||||||
"http://singapore.flashblock.trade",
|
"http://singapore.flashblock.trade",
|
||||||
"http://london.flashblock.trade",
|
"http://london.flashblock.trade",
|
||||||
"http://ny.flashblock.trade",
|
"http://slc.flashblock.trade",
|
||||||
"http://ny.flashblock.trade",
|
"http://fra.flashblock.trade", // Default: 非地理区域;EU 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 8] = [
|
/// BlockRazor Send Transaction v2: plain-text Base64 body, auth in URI, Content-Type: text/plain. Keep-alive: POST /v2/health.
|
||||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
/// 若 HTTP 返回 500,可尝试 HTTPS:https://<region>.solana.blockrazor.io/v2/sendTransaction(Frankfurt/NewYork/Tokyo),通过 custom_url 覆盖。
|
||||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 10] = [
|
||||||
"http://amsterdam.solana.blockrazor.xyz:443/sendTransaction",
|
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||||
"http://tokyo.solana.blockrazor.xyz:443/sendTransaction",
|
"http://amsterdam.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
"http://london.solana.blockrazor.xyz:443/v2/sendTransaction", // Dublin: UK nearest published
|
||||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction", // SLC: 文档无美西;美国仅 NY,受可用区限制
|
||||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
"http://tokyo.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||||
|
"http://tokyo.solana.blockrazor.xyz:443/v2/sendTransaction", // SG: 已公布 APAC 仅 Tokyo,为距 SG 最近
|
||||||
|
"http://london.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||||
|
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction", // LosAngeles: 无美西入口;美国仅 NY
|
||||||
|
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction", // Default: 非地理区域;EU 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_ASTRALANE: [&str; 8] = [
|
/// BlockRazor gRPC endpoints. Region order matches [`SwqosRegion`].
|
||||||
|
/// Port 80 for gRPC protocol. Auth: apikey metadata in gRPC headers.
|
||||||
|
pub const SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC: [&str; 10] = [
|
||||||
|
"http://newyork.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://frankfurt.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://amsterdam.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://london.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://newyork.solana-grpc.blockrazor.xyz:80", // SLC: 与 HTTP 一致;美国仅 NY
|
||||||
|
"http://tokyo.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://tokyo.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://london.solana-grpc.blockrazor.xyz:80",
|
||||||
|
"http://newyork.solana-grpc.blockrazor.xyz:80", // LosAngeles: 与 HTTP 一致
|
||||||
|
"http://frankfurt.solana-grpc.blockrazor.xyz:80", // Default: 非地理区域
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Plain HTTP API path (`/iris?api-key=…&method=…`).
|
||||||
|
pub const ASTRALANE_PATH_IRIS: &str = "iris";
|
||||||
|
/// Binary HTTP API path (`/irisb?api-key=…&method=sendTransaction`, raw bincode body).
|
||||||
|
pub const ASTRALANE_PATH_IRISB: &str = "irisb";
|
||||||
|
|
||||||
|
/// Astralane **Plain** HTTP gateways (`/iris`). Pair with [`ASTRALANE_PATH_IRIS`].
|
||||||
|
pub const SWQOS_ENDPOINTS_ASTRALANE_PLAIN: [&str; 10] = [
|
||||||
"http://ny.gateway.astralane.io/iris",
|
"http://ny.gateway.astralane.io/iris",
|
||||||
"http://fr.gateway.astralane.io/iris",
|
"http://fr.gateway.astralane.io/iris",
|
||||||
"http://ams.gateway.astralane.io/iris",
|
"http://ams.gateway.astralane.io/iris",
|
||||||
"http://ny.gateway.astralane.io/iris",
|
"http://ams.gateway.astralane.io/iris", // Dublin: 无 IE 专用;在已公布 EU 点中选距爱尔兰最近的 ams
|
||||||
|
"http://la.gateway.astralane.io/iris",
|
||||||
"http://jp.gateway.astralane.io/iris",
|
"http://jp.gateway.astralane.io/iris",
|
||||||
"http://ny.gateway.astralane.io/iris",
|
"http://sg.gateway.astralane.io/iris",
|
||||||
"http://lax.gateway.astralane.io/iris",
|
"http://ams.gateway.astralane.io/iris", // London: 无 UK 专用;在已公布 EU 点中选距英国最近的 ams
|
||||||
"http://lim.gateway.astralane.io/iris",
|
"http://la.gateway.astralane.io/iris",
|
||||||
|
"https://edge.astralane.io/iris", // Default: 非地理区域;全局任播边缘
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
|
/// Astralane **Binary** HTTP gateways (`/irisb`). Pair with [`ASTRALANE_PATH_IRISB`].
|
||||||
|
pub const SWQOS_ENDPOINTS_ASTRALANE_BINARY: [&str; 10] = [
|
||||||
|
"http://ny.gateway.astralane.io/irisb",
|
||||||
|
"http://fr.gateway.astralane.io/irisb",
|
||||||
|
"http://ams.gateway.astralane.io/irisb",
|
||||||
|
"http://ams.gateway.astralane.io/irisb", // Dublin: 同 Plain
|
||||||
|
"http://la.gateway.astralane.io/irisb",
|
||||||
|
"http://jp.gateway.astralane.io/irisb",
|
||||||
|
"http://sg.gateway.astralane.io/irisb",
|
||||||
|
"http://ams.gateway.astralane.io/irisb", // London: 同 Plain
|
||||||
|
"http://la.gateway.astralane.io/irisb",
|
||||||
|
"https://edge.astralane.io/irisb", // Default: 同 Plain
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Astralane QUIC endpoints (port 7000). Region order matches [`SwqosRegion`].
|
||||||
|
/// See: https://github.com/Astralane/astralane-quic-client.
|
||||||
|
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 10] = [
|
||||||
|
"ny.gateway.astralane.io:7000",
|
||||||
|
"fr.gateway.astralane.io:7000",
|
||||||
|
"ams.gateway.astralane.io:7000",
|
||||||
|
"ams.gateway.astralane.io:7000", // Dublin: 同 HTTP
|
||||||
|
"la.gateway.astralane.io:7000", // SLC: 美西 la 为最近已公布美区入口
|
||||||
|
"jp.gateway.astralane.io:7000",
|
||||||
|
"sg.gateway.astralane.io:7000",
|
||||||
|
"ams.gateway.astralane.io:7000", // London: 同 HTTP
|
||||||
|
"la.gateway.astralane.io:7000",
|
||||||
|
"lim.gateway.astralane.io:7000", // Default: 非地理区域;全局边缘
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Astralane QUIC MEV-protected endpoints (port 9000). Same region order as SWQOS_ENDPOINTS_ASTRALANE_QUIC.
|
||||||
|
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV: [&str; 10] = [
|
||||||
|
"ny.gateway.astralane.io:9000",
|
||||||
|
"fr.gateway.astralane.io:9000",
|
||||||
|
"ams.gateway.astralane.io:9000",
|
||||||
|
"ams.gateway.astralane.io:9000",
|
||||||
|
"la.gateway.astralane.io:9000",
|
||||||
|
"jp.gateway.astralane.io:9000",
|
||||||
|
"sg.gateway.astralane.io:9000",
|
||||||
|
"ams.gateway.astralane.io:9000",
|
||||||
|
"la.gateway.astralane.io:9000",
|
||||||
|
"lim.gateway.astralane.io:9000",
|
||||||
|
];
|
||||||
|
|
||||||
|
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 10] = [
|
||||||
"http://ewr1.flashrpc.com",
|
"http://ewr1.flashrpc.com",
|
||||||
"http://fra1.flashrpc.com",
|
"http://fra1.flashrpc.com",
|
||||||
"http://ams1.flashrpc.com",
|
"http://ams1.flashrpc.com",
|
||||||
"http://ewr1.flashrpc.com",
|
"http://lhr1.flashrpc.com", // Dublin: 已公布 UK 用 lhr;地理上近爱尔兰
|
||||||
|
"http://ewr1.flashrpc.com", // SLC: 已公布美国仅 ewr;无美西 PoP,受可用区限制
|
||||||
"http://tyo1.flashrpc.com",
|
"http://tyo1.flashrpc.com",
|
||||||
|
"http://tyo1.flashrpc.com", // SG: 表中无 SGP;APAC 仅 tyo,为距 SG 最近
|
||||||
"http://lhr1.flashrpc.com",
|
"http://lhr1.flashrpc.com",
|
||||||
"http://ewr1.flashrpc.com",
|
"http://ewr1.flashrpc.com", // LosAngeles: 同上,美国仅 ewr
|
||||||
"http://fra1.flashrpc.com",
|
"http://fra1.flashrpc.com", // Default: 非地理区域;EU 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_SOYAS: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_SOYAS: [&str; 10] = [
|
||||||
"nyc.landing.soyas.xyz:9000",
|
"nyc.landing.soyas.xyz:9000",
|
||||||
"fra.landing.soyas.xyz:9000",
|
"fra.landing.soyas.xyz:9000",
|
||||||
"ams.landing.soyas.xyz:9000",
|
"ams.landing.soyas.xyz:9000",
|
||||||
"nyc.landing.soyas.xyz:9000",
|
"lon.landing.soyas.xyz:9000", // Dublin: 已公布用 lon;地理近爱尔兰
|
||||||
|
"nyc.landing.soyas.xyz:9000", // SLC: 已公布美国仅 nyc;无美西
|
||||||
"tyo.landing.soyas.xyz:9000",
|
"tyo.landing.soyas.xyz:9000",
|
||||||
|
"tyo.landing.soyas.xyz:9000", // SG: 表中 APAC 仅 tyo
|
||||||
"lon.landing.soyas.xyz:9000",
|
"lon.landing.soyas.xyz:9000",
|
||||||
"nyc.landing.soyas.xyz:9000",
|
"nyc.landing.soyas.xyz:9000", // LosAngeles: 同上
|
||||||
"fra.landing.soyas.xyz:9000",
|
"fra.landing.soyas.xyz:9000", // Default: 非地理区域;EU 枢纽
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_SPEEDLANDING: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_SPEEDLANDING: [&str; 10] = [
|
||||||
"nyc.speedlanding.trade:17778",
|
"nyc.speedlanding.trade:17778",
|
||||||
"fra.speedlanding.trade:17778",
|
"fra.speedlanding.trade:17778",
|
||||||
"ams.speedlanding.trade:17778",
|
"ams.speedlanding.trade:17778",
|
||||||
"nyc.speedlanding.trade:17778",
|
"ams.speedlanding.trade:17778", // Dublin: 已公布 EU 点中 ams 地理近爱尔兰
|
||||||
|
"nyc.speedlanding.trade:17778", // SLC: 表中美国仅 nyc;无美西 PoP,受可用区限制
|
||||||
"tyo.speedlanding.trade:17778",
|
"tyo.speedlanding.trade:17778",
|
||||||
"fra.speedlanding.trade:17778",
|
"sgp.speedlanding.trade:17778",
|
||||||
"nyc.speedlanding.trade:17778",
|
"ams.speedlanding.trade:17778", // London: 已公布 EU 中 ams 距英国最近之一
|
||||||
"fra.speedlanding.trade:17778",
|
"nyc.speedlanding.trade:17778", // LosAngeles: 同上,美国仅 nyc
|
||||||
|
"fra.speedlanding.trade:17778", // Default: 非地理区域;EU 枢纽
|
||||||
|
];
|
||||||
|
|
||||||
|
/// Helius Sender: POST /fast, dual routing to validators and Jito. API key optional (custom TPS only).
|
||||||
|
pub const SWQOS_ENDPOINTS_HELIUS: [&str; 10] = [
|
||||||
|
"http://ewr-sender.helius-rpc.com/fast",
|
||||||
|
"http://fra-sender.helius-rpc.com/fast",
|
||||||
|
"http://ams-sender.helius-rpc.com/fast",
|
||||||
|
"http://lon-sender.helius-rpc.com/fast", // Dublin: IE → UK/EU routing
|
||||||
|
"http://slc-sender.helius-rpc.com/fast",
|
||||||
|
"http://tyo-sender.helius-rpc.com/fast",
|
||||||
|
"http://sg-sender.helius-rpc.com/fast",
|
||||||
|
"http://lon-sender.helius-rpc.com/fast",
|
||||||
|
"http://slc-sender.helius-rpc.com/fast",
|
||||||
|
"https://sender.helius-rpc.com/fast", // Default: 非地理区域;全局 Sender
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_MIN_TIP_DEFAULT: f64 = 0.00001; // 其它SWQOS默认最低小费
|
pub const SWQOS_MIN_TIP_DEFAULT: f64 = 0.00001; // 其它SWQOS默认最低小费
|
||||||
@@ -296,3 +448,77 @@ 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_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_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
|
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;
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
const SWQOS_REGION_ENDPOINT_TABLES: &[&[&str]] = &[
|
||||||
|
&SWQOS_ENDPOINTS_JITO,
|
||||||
|
&SWQOS_ENDPOINTS_NEXTBLOCK,
|
||||||
|
&SWQOS_ENDPOINTS_ZERO_SLOT,
|
||||||
|
&SWQOS_ENDPOINTS_TEMPORAL,
|
||||||
|
&SWQOS_ENDPOINTS_BLOX,
|
||||||
|
&SWQOS_ENDPOINTS_NODE1,
|
||||||
|
&SWQOS_ENDPOINTS_NODE1_QUIC,
|
||||||
|
&SWQOS_ENDPOINTS_FLASHBLOCK,
|
||||||
|
&SWQOS_ENDPOINTS_BLOCKRAZOR,
|
||||||
|
&SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC,
|
||||||
|
&SWQOS_ENDPOINTS_ASTRALANE_PLAIN,
|
||||||
|
&SWQOS_ENDPOINTS_ASTRALANE_BINARY,
|
||||||
|
&SWQOS_ENDPOINTS_ASTRALANE_QUIC,
|
||||||
|
&SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV,
|
||||||
|
&SWQOS_ENDPOINTS_STELLIUM,
|
||||||
|
&SWQOS_ENDPOINTS_SOYAS,
|
||||||
|
&SWQOS_ENDPOINTS_SPEEDLANDING,
|
||||||
|
&SWQOS_ENDPOINTS_HELIUS,
|
||||||
|
];
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn all_swqos_endpoint_tables_align_with_swqos_region() {
|
||||||
|
const EXPECT: usize = 10;
|
||||||
|
for (idx, table) in SWQOS_REGION_ENDPOINT_TABLES.iter().enumerate() {
|
||||||
|
assert_eq!(
|
||||||
|
table.len(),
|
||||||
|
EXPECT,
|
||||||
|
"SWQOS endpoint table index {} length must match SwqosRegion (10 variants)",
|
||||||
|
idx
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn astralane_quic_hosts_match_mev_row_by_row() {
|
||||||
|
for i in 0..10 {
|
||||||
|
let base = SWQOS_ENDPOINTS_ASTRALANE_QUIC[i].trim_end_matches(":7000");
|
||||||
|
let mev = SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV[i].trim_end_matches(":9000");
|
||||||
|
assert_eq!(base, mev, "Astralane QUIC vs MEV host mismatch at index {}", i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn node1_http_host_matches_quic_without_port() {
|
||||||
|
for i in 0..10 {
|
||||||
|
let http_host = SWQOS_ENDPOINTS_NODE1[i]
|
||||||
|
.strip_prefix("http://")
|
||||||
|
.expect("NODE1 HTTP URL");
|
||||||
|
let quic_host = SWQOS_ENDPOINTS_NODE1_QUIC[i]
|
||||||
|
.strip_suffix(":16666")
|
||||||
|
.expect("NODE1 QUIC endpoint");
|
||||||
|
assert_eq!(http_host, quic_host, "Node1 HTTP vs QUIC host mismatch at index {}", i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn astralane_plain_and_binary_same_origin_per_region() {
|
||||||
|
for i in 0..10 {
|
||||||
|
let plain = SWQOS_ENDPOINTS_ASTRALANE_PLAIN[i].trim_end_matches("/iris");
|
||||||
|
let binary = SWQOS_ENDPOINTS_ASTRALANE_BINARY[i].trim_end_matches("/irisb");
|
||||||
|
assert_eq!(plain, binary, "Astralane Plain vs Binary base URL mismatch at index {}", i);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -6,4 +6,4 @@ pub mod trade {
|
|||||||
pub const DEFAULT_SELL_TIP_FEE: f64 = 0.0001;
|
pub const DEFAULT_SELL_TIP_FEE: f64 = 0.0001;
|
||||||
pub const DEFAULT_RPC_UNIT_LIMIT: u32 = 150000;
|
pub const DEFAULT_RPC_UNIT_LIMIT: u32 = 150000;
|
||||||
pub const DEFAULT_RPC_UNIT_PRICE: u64 = 500000;
|
pub const DEFAULT_RPC_UNIT_PRICE: u64 = 500000;
|
||||||
}
|
}
|
||||||
|
|||||||
+7
-23
@@ -4,12 +4,9 @@ use crate::{
|
|||||||
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
|
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
|
||||||
SELL_EXECT_IN_DISCRIMINATOR,
|
SELL_EXECT_IN_DISCRIMINATOR,
|
||||||
},
|
},
|
||||||
trading::{
|
trading::core::{
|
||||||
common::utils::get_token_balance,
|
params::{BonkParams, SwapParams},
|
||||||
core::{
|
traits::InstructionBuilder,
|
||||||
params::{BonkParams, SwapParams},
|
|
||||||
traits::InstructionBuilder,
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
utils::calc::bonk::{
|
utils::calc::bonk::{
|
||||||
get_buy_token_amount_from_sol_amount, get_sell_sol_amount_from_token_amount,
|
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
|
// Parameter validation and basic data preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
if params.rpc.is_none() {
|
let amount = params
|
||||||
return Err(anyhow!("RPC is not set"));
|
.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
|
let protocol_params = params
|
||||||
.protocol_params
|
.protocol_params
|
||||||
@@ -189,20 +187,6 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
|||||||
|
|
||||||
let usd1_pool = protocol_params.global_config == accounts::USD1_GLOBAL_CONFIG;
|
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(), ¶ms.payer.pubkey(), ¶ms.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() {
|
let pool_state = if protocol_params.pool_state == Pubkey::default() {
|
||||||
if usd1_pool {
|
if usd1_pool {
|
||||||
get_pool_pda(¶ms.input_mint, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
get_pool_pda(¶ms.input_mint, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
||||||
|
|||||||
@@ -27,10 +27,12 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
.protocol_params
|
.protocol_params
|
||||||
.as_any()
|
.as_any()
|
||||||
.downcast_ref::<MeteoraDammV2Params>()
|
.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_wsol = protocol_params.token_a_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;
|
|| 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;
|
||||||
if !is_wsol && !is_usdc {
|
if !is_wsol && !is_usdc {
|
||||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||||
}
|
}
|
||||||
@@ -38,7 +40,8 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||||
Some(fixed) => fixed,
|
Some(fixed) => fixed,
|
||||||
@@ -84,7 +87,11 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
¶ms.output_mint,
|
¶ms.output_mint,
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
if is_a_in {
|
||||||
|
&protocol_params.token_b_program
|
||||||
|
} else {
|
||||||
|
&protocol_params.token_a_program
|
||||||
|
},
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
),
|
),
|
||||||
);
|
);
|
||||||
@@ -135,14 +142,16 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
.protocol_params
|
.protocol_params
|
||||||
.as_any()
|
.as_any()
|
||||||
.downcast_ref::<MeteoraDammV2Params>()
|
.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 {
|
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||||
return Err(anyhow!("Token amount is not set"));
|
return Err(anyhow!("Token amount is not set"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
|
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
if !is_wsol && !is_usdc {
|
if !is_wsol && !is_usdc {
|
||||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||||
}
|
}
|
||||||
@@ -150,7 +159,8 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||||
Some(fixed) => fixed,
|
Some(fixed) => fixed,
|
||||||
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
pub mod bonk;
|
||||||
|
pub mod meteora_damm_v2;
|
||||||
pub mod pumpfun;
|
pub mod pumpfun;
|
||||||
pub mod pumpswap;
|
pub mod pumpswap;
|
||||||
pub mod bonk;
|
|
||||||
pub mod raydium_cpmm;
|
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod meteora_damm_v2;
|
pub mod raydium_cpmm;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
|
|||||||
+104
-66
@@ -8,8 +8,11 @@ use crate::{
|
|||||||
};
|
};
|
||||||
use crate::{
|
use crate::{
|
||||||
instruction::utils::pumpfun::{
|
instruction::utils::pumpfun::{
|
||||||
accounts, get_bonding_curve_pda, get_creator, get_user_volume_accumulator_pda,
|
accounts, get_bonding_curve_pda, get_bonding_curve_v2_pda,
|
||||||
global_constants::{self}, BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR,
|
get_protocol_extra_fee_recipient_random, get_user_volume_accumulator_pda,
|
||||||
|
pump_fun_fee_recipient_meta, resolve_creator_vault_for_ix,
|
||||||
|
global_constants::{self},
|
||||||
|
BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||||
},
|
},
|
||||||
utils::calc::{
|
utils::calc::{
|
||||||
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
|
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
|
||||||
@@ -40,8 +43,20 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let bonding_curve = &protocol_params.bonding_curve;
|
let bonding_curve = &protocol_params.bonding_curve;
|
||||||
let creator_vault_pda = protocol_params.creator_vault;
|
// creator_vault must be PDA(creator) per bonding curve. Event vault: use only if == derived;
|
||||||
let creator = get_creator(&creator_vault_pda);
|
// if stream sends a mismatched vault (wrong token / stale), fall back to derived.
|
||||||
|
let creator = bonding_curve.creator;
|
||||||
|
let creator_vault_pda = resolve_creator_vault_for_ix(
|
||||||
|
&creator,
|
||||||
|
protocol_params.creator_vault,
|
||||||
|
¶ms.output_mint,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow!(
|
||||||
|
"creator_vault PDA derivation failed (creator={})",
|
||||||
|
creator
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
@@ -62,11 +77,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||||
);
|
);
|
||||||
|
|
||||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
// 始终用 mint 推导 canonical bonding curve PDA。缓存里的 `bonding_curve.account` 可能指向其它池子,
|
||||||
get_bonding_curve_pda(¶ms.output_mint).unwrap()
|
// 会导致链上读到错误 `creator`,从而 creator_vault seeds 与传入的 vault 不一致(Anchor 2006)。
|
||||||
} else {
|
let bonding_curve_addr = get_bonding_curve_pda(¶ms.output_mint).ok_or_else(|| {
|
||||||
bonding_curve.account
|
anyhow!("bonding_curve PDA derivation failed for mint {}", params.output_mint)
|
||||||
};
|
})?;
|
||||||
|
|
||||||
// Determine token program based on mayhem mode
|
// Determine token program based on mayhem mode
|
||||||
let is_mayhem_mode = bonding_curve.is_mayhem_mode;
|
let is_mayhem_mode = bonding_curve.is_mayhem_mode;
|
||||||
@@ -78,15 +93,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let associated_bonding_curve =
|
let associated_bonding_curve =
|
||||||
if protocol_params.associated_bonding_curve == Pubkey::default() {
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
&bonding_curve_addr,
|
||||||
&bonding_curve_addr,
|
¶ms.output_mint,
|
||||||
¶ms.output_mint,
|
&token_program,
|
||||||
&token_program,
|
);
|
||||||
)
|
|
||||||
} else {
|
|
||||||
protocol_params.associated_bonding_curve
|
|
||||||
};
|
|
||||||
|
|
||||||
let user_token_account =
|
let user_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
@@ -96,12 +107,14 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
|
|
||||||
let user_volume_accumulator =
|
let user_volume_accumulator = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap();
|
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||||
|
|
||||||
// ========================================
|
// ========================================
|
||||||
// Build instructions
|
// Build instructions
|
||||||
// ========================================
|
// ========================================
|
||||||
|
// Hot path: no RPC here (latency). For legacy curves <151 bytes, use
|
||||||
|
// `extend_bonding_curve_account_instruction` from a cold path or separate tx.
|
||||||
let mut instructions = Vec::with_capacity(2);
|
let mut instructions = Vec::with_capacity(2);
|
||||||
|
|
||||||
// Create associated token account
|
// Create associated token account
|
||||||
@@ -117,10 +130,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) {
|
if params.use_exact_sol_amount.unwrap_or(true) {
|
||||||
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64)
|
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64, track_volume)
|
||||||
// Spend exactly the input SOL amount, get at least min_tokens_out
|
|
||||||
let min_tokens_out = calculate_with_slippage_sell(
|
let min_tokens_out = calculate_with_slippage_sell(
|
||||||
buy_token_amount,
|
buy_token_amount,
|
||||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||||
@@ -128,22 +142,23 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
buy_data[..8].copy_from_slice(&BUY_EXACT_SOL_IN_DISCRIMINATOR);
|
buy_data[..8].copy_from_slice(&BUY_EXACT_SOL_IN_DISCRIMINATOR);
|
||||||
buy_data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
buy_data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||||
buy_data[16..24].copy_from_slice(&min_tokens_out.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 {
|
} else {
|
||||||
// buy(token_amount: u64, max_sol_cost: u64)
|
// buy(token_amount: u64, max_sol_cost: u64, track_volume)
|
||||||
// Buy exactly token_amount tokens, pay up to max_sol_cost
|
|
||||||
buy_data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
buy_data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||||
buy_data[8..16].copy_from_slice(&buy_token_amount.to_le_bytes());
|
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[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
|
// Fee recipient: gRPC/ShredStream 填入的 `PumpFunParams.fee_recipient`(同笔 create_v2+buy 或 trade 日志)优先;热路径无 RPC。
|
||||||
let fee_recipient_meta = if is_mayhem_mode {
|
let fee_recipient_meta =
|
||||||
global_constants::MAYHEM_FEE_RECIPIENT_META
|
pump_fun_fee_recipient_meta(protocol_params.fee_recipient, is_mayhem_mode);
|
||||||
} else {
|
|
||||||
global_constants::FEE_RECIPIENT_META
|
|
||||||
};
|
|
||||||
|
|
||||||
let accounts: [AccountMeta; 16] = [
|
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.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,
|
global_constants::GLOBAL_ACCOUNT_META,
|
||||||
fee_recipient_meta,
|
fee_recipient_meta,
|
||||||
AccountMeta::new_readonly(params.output_mint, false),
|
AccountMeta::new_readonly(params.output_mint, false),
|
||||||
@@ -161,12 +176,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
accounts::FEE_CONFIG_META,
|
accounts::FEE_CONFIG_META,
|
||||||
accounts::FEE_PROGRAM_META,
|
accounts::FEE_PROGRAM_META,
|
||||||
];
|
];
|
||||||
|
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // remainingAccounts: @pump-fun/pump-sdk 要求末尾传 bondingCurveV2Pda(mint),勿删
|
||||||
|
// Apr 2026: extra protocol fee recipient after bonding-curve-v2 (writable)
|
||||||
|
accounts.push(AccountMeta::new(get_protocol_extra_fee_recipient_random(), false));
|
||||||
|
|
||||||
instructions.push(Instruction::new_with_bytes(
|
instructions.push(Instruction::new_with_bytes(accounts::PUMPFUN, &buy_data, accounts));
|
||||||
accounts::PUMPFUN,
|
|
||||||
&buy_data,
|
|
||||||
accounts.to_vec(),
|
|
||||||
));
|
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
}
|
}
|
||||||
@@ -191,8 +205,18 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let bonding_curve = &protocol_params.bonding_curve;
|
let bonding_curve = &protocol_params.bonding_curve;
|
||||||
let creator_vault_pda = protocol_params.creator_vault;
|
let creator = bonding_curve.creator;
|
||||||
let creator = get_creator(&creator_vault_pda);
|
let creator_vault_pda = resolve_creator_vault_for_ix(
|
||||||
|
&creator,
|
||||||
|
protocol_params.creator_vault,
|
||||||
|
¶ms.input_mint,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| {
|
||||||
|
anyhow!(
|
||||||
|
"creator_vault PDA derivation failed (creator={})",
|
||||||
|
creator
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
@@ -212,11 +236,9 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
),
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
let bonding_curve_addr = get_bonding_curve_pda(¶ms.input_mint).ok_or_else(|| {
|
||||||
get_bonding_curve_pda(¶ms.input_mint).unwrap()
|
anyhow!("bonding_curve PDA derivation failed for mint {}", params.input_mint)
|
||||||
} else {
|
})?;
|
||||||
bonding_curve.account
|
|
||||||
};
|
|
||||||
|
|
||||||
// Determine token program based on mayhem mode
|
// Determine token program based on mayhem mode
|
||||||
let is_mayhem_mode = bonding_curve.is_mayhem_mode;
|
let is_mayhem_mode = bonding_curve.is_mayhem_mode;
|
||||||
@@ -228,15 +250,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let associated_bonding_curve =
|
let associated_bonding_curve =
|
||||||
if protocol_params.associated_bonding_curve == Pubkey::default() {
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
&bonding_curve_addr,
|
||||||
&bonding_curve_addr,
|
¶ms.input_mint,
|
||||||
¶ms.input_mint,
|
&token_program,
|
||||||
&token_program,
|
);
|
||||||
)
|
|
||||||
} else {
|
|
||||||
protocol_params.associated_bonding_curve
|
|
||||||
};
|
|
||||||
|
|
||||||
let user_token_account =
|
let user_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
@@ -252,18 +270,14 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
let mut instructions = Vec::with_capacity(2);
|
let mut instructions = Vec::with_capacity(2);
|
||||||
|
|
||||||
let mut sell_data = [0u8; 24];
|
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[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||||
sell_data[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
|
sell_data[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
|
||||||
|
|
||||||
// Determine fee recipient based on mayhem mode
|
let fee_recipient_meta =
|
||||||
let fee_recipient_meta = if is_mayhem_mode {
|
pump_fun_fee_recipient_meta(protocol_params.fee_recipient, is_mayhem_mode);
|
||||||
global_constants::MAYHEM_FEE_RECIPIENT_META
|
|
||||||
} else {
|
|
||||||
global_constants::FEE_RECIPIENT_META
|
|
||||||
};
|
|
||||||
|
|
||||||
let accounts: [AccountMeta; 14] = [
|
let mut accounts: Vec<AccountMeta> = vec![
|
||||||
global_constants::GLOBAL_ACCOUNT_META,
|
global_constants::GLOBAL_ACCOUNT_META,
|
||||||
fee_recipient_meta,
|
fee_recipient_meta,
|
||||||
AccountMeta::new_readonly(params.input_mint, false),
|
AccountMeta::new_readonly(params.input_mint, false),
|
||||||
@@ -280,11 +294,21 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
accounts::FEE_PROGRAM_META,
|
accounts::FEE_PROGRAM_META,
|
||||||
];
|
];
|
||||||
|
|
||||||
instructions.push(Instruction::new_with_bytes(
|
// Cashback: Bonding Curve Sell expects UserVolumeAccumulator PDA at 0th remaining account (writable)
|
||||||
accounts::PUMPFUN,
|
if bonding_curve.is_cashback_coin {
|
||||||
&sell_data,
|
let user_volume_accumulator =
|
||||||
accounts.to_vec(),
|
get_user_volume_accumulator_pda(¶ms.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(¶ms.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));
|
||||||
|
accounts.push(AccountMeta::new(get_protocol_extra_fee_recipient_random(), false));
|
||||||
|
|
||||||
|
instructions.push(Instruction::new_with_bytes(accounts::PUMPFUN, &sell_data, accounts));
|
||||||
|
|
||||||
// Optional: Close token account
|
// Optional: Close token account
|
||||||
if protocol_params.close_token_account_when_sell.unwrap_or(false)
|
if protocol_params.close_token_account_when_sell.unwrap_or(false)
|
||||||
@@ -302,3 +326,17 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Claim cashback for Bonding Curve (Pump program). Transfers native lamports from UserVolumeAccumulator to user.
|
||||||
|
pub fn claim_cashback_pumpfun_instruction(payer: &Pubkey) -> Option<Instruction> {
|
||||||
|
const CLAIM_CASHBACK_DISCRIMINATOR: [u8; 8] = [37, 58, 35, 126, 190, 53, 228, 197];
|
||||||
|
let user_volume_accumulator = get_user_volume_accumulator_pda(payer)?;
|
||||||
|
let accounts = vec![
|
||||||
|
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||||
|
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable, not signer)
|
||||||
|
crate::constants::SYSTEM_PROGRAM_META,
|
||||||
|
accounts::EVENT_AUTHORITY_META,
|
||||||
|
accounts::PUMPFUN_META,
|
||||||
|
];
|
||||||
|
Some(Instruction::new_with_bytes(accounts::PUMPFUN, &CLAIM_CASHBACK_DISCRIMINATOR, accounts))
|
||||||
|
}
|
||||||
|
|||||||
+139
-62
@@ -1,8 +1,10 @@
|
|||||||
use crate::{
|
use crate::{
|
||||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||||
instruction::utils::pumpswap::{
|
instruction::utils::pumpswap::{
|
||||||
accounts, fee_recipient_ata, get_user_volume_accumulator_pda, BUY_DISCRIMINATOR,
|
accounts, fee_recipient_ata, get_mayhem_fee_recipient_random, get_pool_v2_pda,
|
||||||
BUY_EXACT_QUOTE_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
get_protocol_extra_fee_recipient_random, 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::{
|
trading::{
|
||||||
common::wsol_manager,
|
common::wsol_manager,
|
||||||
@@ -118,16 +120,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
params.open_seed_optimize,
|
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 is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||||
let fee_recipient =
|
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
get_mayhem_fee_recipient_random()
|
||||||
let fee_recipient_meta = if is_mayhem_mode {
|
|
||||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
|
||||||
} else {
|
} 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
|
// Build instructions
|
||||||
@@ -135,8 +139,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
let mut instructions = Vec::with_capacity(6);
|
let mut instructions = Vec::with_capacity(6);
|
||||||
|
|
||||||
if create_wsol_ata {
|
if create_wsol_ata {
|
||||||
|
// Determine wrap amount based on instruction type:
|
||||||
|
// - buy_exact_quote_in: program spends exactly input_amount, wrap input_amount
|
||||||
|
// - buy: program may spend up to max_quote, wrap max_quote
|
||||||
|
let wrap_amount = if quote_is_wsol_or_usdc
|
||||||
|
&& params.use_exact_sol_amount.unwrap_or(true)
|
||||||
|
{
|
||||||
|
params.input_amount.unwrap_or(0)
|
||||||
|
} else {
|
||||||
|
sol_amount
|
||||||
|
};
|
||||||
instructions
|
instructions
|
||||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), sol_amount));
|
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), wrap_amount));
|
||||||
}
|
}
|
||||||
|
|
||||||
if params.create_output_mint_ata {
|
if params.create_output_mint_ata {
|
||||||
@@ -152,7 +166,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create buy instruction
|
// Create buy instruction
|
||||||
let mut accounts = Vec::with_capacity(23);
|
let mut accounts = Vec::with_capacity(28);
|
||||||
accounts.extend([
|
accounts.extend([
|
||||||
AccountMeta::new(pool, false), // pool_id
|
AccountMeta::new(pool, false), // pool_id
|
||||||
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
||||||
@@ -176,53 +190,59 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
]);
|
]);
|
||||||
if quote_is_wsol_or_usdc {
|
if quote_is_wsol_or_usdc {
|
||||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||||
accounts.push(AccountMeta::new(
|
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||||
false,
|
accounts.push(AccountMeta::new(uva, false));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
accounts.push(accounts::FEE_CONFIG_META);
|
accounts.push(accounts::FEE_CONFIG_META);
|
||||||
accounts.push(accounts::FEE_PROGRAM_META);
|
accounts.push(accounts::FEE_PROGRAM_META);
|
||||||
|
// Cashback: remaining_accounts[0] = WSOL ATA of UserVolumeAccumulator (after named accounts per IDL)
|
||||||
|
if protocol_params.is_cashback_coin {
|
||||||
|
if let Some(wsol_ata) = get_user_volume_accumulator_wsol_ata(¶ms.payer.pubkey()) {
|
||||||
|
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));
|
||||||
|
// Apr 2026: protocol fee recipient + quote ATA (after pool-v2)
|
||||||
|
let protocol_extra = get_protocol_extra_fee_recipient_random();
|
||||||
|
accounts.push(AccountMeta::new_readonly(protocol_extra, false));
|
||||||
|
accounts.push(AccountMeta::new(
|
||||||
|
crate::instruction::utils::pumpswap::fee_recipient_ata(protocol_extra, quote_mint),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
|
||||||
// Create instruction data
|
// Create instruction data(buy/buy_exact_quote_in 第三参数 track_volume: OptionBool,仅代币支持返现时传 Some(true);sell 仅两参数)
|
||||||
let mut data = [0u8; 24];
|
let track_volume = if protocol_params.is_cashback_coin { [1u8, 1u8] } else { [1u8, 0u8] }; // Some(true) / Some(false)
|
||||||
if quote_is_wsol_or_usdc {
|
let data: Vec<u8> = if quote_is_wsol_or_usdc {
|
||||||
|
let mut buf = [0u8; 26];
|
||||||
if params.use_exact_sol_amount.unwrap_or(true) {
|
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(
|
let min_base_amount_out = crate::utils::calc::common::calculate_with_slippage_sell(
|
||||||
token_amount,
|
token_amount,
|
||||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||||
);
|
);
|
||||||
data[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
buf[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
||||||
// spendable_quote_in (exact SOL amount to spend)
|
buf[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||||
data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
buf[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
||||||
// min_base_amount_out (minimum tokens to receive)
|
buf[24..26].copy_from_slice(&track_volume);
|
||||||
data[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
|
||||||
} else {
|
} else {
|
||||||
// buy(base_amount_out: u64, max_quote_amount_in: u64)
|
buf[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||||
// Buy exactly base_amount_out tokens, pay up to max_quote_amount_in
|
buf[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||||
data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
buf[16..24].copy_from_slice(&sol_amount.to_le_bytes());
|
||||||
// base_amount_out
|
buf[24..26].copy_from_slice(&track_volume);
|
||||||
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.to_vec()
|
||||||
} else {
|
} else {
|
||||||
data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
let mut buf = [0u8; 24];
|
||||||
// base_amount_in
|
buf[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||||
data[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
buf[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
||||||
// min_quote_amount_out
|
buf[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
buf.to_vec()
|
||||||
}
|
|
||||||
|
|
||||||
let buy_instruction = Instruction {
|
|
||||||
program_id: accounts::AMM_PROGRAM,
|
|
||||||
accounts: accounts.clone(),
|
|
||||||
data: data.to_vec(),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
instructions.push(buy_instruction);
|
instructions.push(Instruction { program_id: accounts::AMM_PROGRAM, accounts, data });
|
||||||
if close_wsol_ata {
|
if close_wsol_ata {
|
||||||
// Close wSOL ATA account, reclaim rent
|
// Close wSOL ATA account, reclaim rent
|
||||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||||
@@ -308,16 +328,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
sol_amount = params.fixed_output_amount.unwrap();
|
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 is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||||
let fee_recipient =
|
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
get_mayhem_fee_recipient_random()
|
||||||
let fee_recipient_meta = if is_mayhem_mode {
|
|
||||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
|
||||||
} else {
|
} 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 =
|
let user_base_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
@@ -344,7 +366,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Create sell instruction
|
// Create sell instruction
|
||||||
let mut accounts = Vec::with_capacity(23);
|
let mut accounts = Vec::with_capacity(28);
|
||||||
accounts.extend([
|
accounts.extend([
|
||||||
AccountMeta::new(pool, false), // pool_id
|
AccountMeta::new(pool, false), // pool_id
|
||||||
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
||||||
@@ -368,14 +390,36 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
]);
|
]);
|
||||||
if !quote_is_wsol_or_usdc {
|
if !quote_is_wsol_or_usdc {
|
||||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||||
accounts.push(AccountMeta::new(
|
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||||
false,
|
accounts.push(AccountMeta::new(uva, false));
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
accounts.push(accounts::FEE_CONFIG_META);
|
accounts.push(accounts::FEE_CONFIG_META);
|
||||||
accounts.push(accounts::FEE_PROGRAM_META);
|
accounts.push(accounts::FEE_PROGRAM_META);
|
||||||
|
// Cashback sell: 官方 remainingAccounts = [accumulator 的 quote_mint ATA, accumulator PDA, poolV2](用 quote_mint 非固定 WSOL)
|
||||||
|
if protocol_params.is_cashback_coin {
|
||||||
|
if let (Some(quote_ata), Some(accumulator)) = (
|
||||||
|
get_user_volume_accumulator_quote_ata(
|
||||||
|
¶ms.payer.pubkey(),
|
||||||
|
"e_mint,
|
||||||
|
"e_token_program,
|
||||||
|
),
|
||||||
|
get_user_volume_accumulator_pda(¶ms.payer.pubkey()),
|
||||||
|
) {
|
||||||
|
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));
|
||||||
|
let protocol_extra = get_protocol_extra_fee_recipient_random();
|
||||||
|
accounts.push(AccountMeta::new_readonly(protocol_extra, false));
|
||||||
|
accounts.push(AccountMeta::new(
|
||||||
|
crate::instruction::utils::pumpswap::fee_recipient_ata(protocol_extra, quote_mint),
|
||||||
|
false,
|
||||||
|
));
|
||||||
|
|
||||||
// Create instruction data
|
// Create instruction data
|
||||||
let mut data = [0u8; 24];
|
let mut data = [0u8; 24];
|
||||||
@@ -393,13 +437,11 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||||
}
|
}
|
||||||
|
|
||||||
let sell_instruction = Instruction {
|
instructions.push(Instruction {
|
||||||
program_id: accounts::AMM_PROGRAM,
|
program_id: accounts::AMM_PROGRAM,
|
||||||
accounts: accounts.clone(),
|
accounts,
|
||||||
data: data.to_vec(),
|
data: data.to_vec(),
|
||||||
};
|
});
|
||||||
|
|
||||||
instructions.push(sell_instruction);
|
|
||||||
|
|
||||||
if close_wsol_ata {
|
if close_wsol_ata {
|
||||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||||
@@ -420,3 +462,38 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Claim cashback for PumpSwap (AMM). Transfers WSOL from UserVolumeAccumulator's WSOL ATA to user's WSOL ATA.
|
||||||
|
/// Caller should ensure user's WSOL ATA exists (e.g. create idempotent ATA instruction) before this instruction.
|
||||||
|
pub fn claim_cashback_pumpswap_instruction(
|
||||||
|
payer: &Pubkey,
|
||||||
|
quote_mint: Pubkey,
|
||||||
|
quote_token_program: Pubkey,
|
||||||
|
) -> Option<solana_sdk::instruction::Instruction> {
|
||||||
|
const CLAIM_CASHBACK_DISCRIMINATOR: [u8; 8] = [37, 58, 35, 126, 190, 53, 228, 197];
|
||||||
|
let user_volume_accumulator = get_user_volume_accumulator_pda(payer)?;
|
||||||
|
let user_volume_accumulator_wsol_ata = get_user_volume_accumulator_wsol_ata(payer)?;
|
||||||
|
let user_wsol_ata = crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
|
payer,
|
||||||
|
"e_mint,
|
||||||
|
"e_token_program,
|
||||||
|
);
|
||||||
|
// IDL order: user, user_volume_accumulator, quote_mint, quote_token_program,
|
||||||
|
// user_volume_accumulator_wsol_token_account, user_wsol_token_account, system_program, event_authority, program
|
||||||
|
let accounts = vec![
|
||||||
|
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||||
|
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable)
|
||||||
|
AccountMeta::new_readonly(quote_mint, false),
|
||||||
|
AccountMeta::new_readonly(quote_token_program, false),
|
||||||
|
AccountMeta::new(user_volume_accumulator_wsol_ata, false), // writable
|
||||||
|
AccountMeta::new(user_wsol_ata, false), // writable
|
||||||
|
crate::constants::SYSTEM_PROGRAM_META,
|
||||||
|
accounts::EVENT_AUTHORITY_META,
|
||||||
|
accounts::AMM_PROGRAM_META,
|
||||||
|
];
|
||||||
|
Some(solana_sdk::instruction::Instruction::new_with_bytes(
|
||||||
|
accounts::AMM_PROGRAM,
|
||||||
|
&CLAIM_CASHBACK_DISCRIMINATOR,
|
||||||
|
accounts,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|||||||
@@ -29,7 +29,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
.protocol_params
|
.protocol_params
|
||||||
.as_any()
|
.as_any()
|
||||||
.downcast_ref::<RaydiumAmmV4Params>()
|
.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
|
let is_wsol = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
|| protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
@@ -44,7 +44,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_base_in = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
let is_base_in = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| protocol_params.coin_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.coin_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||||
let swap_result = compute_swap_amount(
|
let swap_result = compute_swap_amount(
|
||||||
@@ -62,7 +62,11 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
let user_source_token_account =
|
let user_source_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -144,7 +148,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
.protocol_params
|
.protocol_params
|
||||||
.as_any()
|
.as_any()
|
||||||
.downcast_ref::<RaydiumAmmV4Params>()
|
.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 {
|
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||||
return Err(anyhow!("Token amount is not set"));
|
return Err(anyhow!("Token amount is not set"));
|
||||||
@@ -187,7 +191,11 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
let user_destination_token_account =
|
let user_destination_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -61,7 +61,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_base_in = protocol_params.base_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
let is_base_in = protocol_params.base_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let mint_token_program = if is_base_in {
|
let mint_token_program = if is_base_in {
|
||||||
protocol_params.quote_token_program
|
protocol_params.quote_token_program
|
||||||
@@ -84,7 +84,11 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -97,10 +101,15 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let input_vault_account = get_vault_account(
|
let input_vault_account = get_vault_account(
|
||||||
&pool_state,
|
&pool_state,
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
protocol_params,
|
protocol_params,
|
||||||
);
|
);
|
||||||
let output_vault_account = get_vault_account(&pool_state, ¶ms.output_mint, protocol_params);
|
let output_vault_account =
|
||||||
|
get_vault_account(&pool_state, ¶ms.output_mint, protocol_params);
|
||||||
|
|
||||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||||
get_observation_state_pda(&pool_state).unwrap()
|
get_observation_state_pda(&pool_state).unwrap()
|
||||||
@@ -136,13 +145,17 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
accounts::AUTHORITY_META, // Authority (readonly)
|
accounts::AUTHORITY_META, // Authority (readonly)
|
||||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||||
AccountMeta::new(pool_state, false), // Pool State
|
AccountMeta::new(pool_state, false), // Pool State
|
||||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||||
crate::constants::TOKEN_PROGRAM_META, // Input Token Program (readonly)
|
crate::constants::TOKEN_PROGRAM_META, // Input Token Program (readonly)
|
||||||
AccountMeta::new_readonly(mint_token_program, false), // Output Token Program (readonly)
|
AccountMeta::new_readonly(mint_token_program, false), // Output Token Program (readonly)
|
||||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Input token mint (readonly)
|
if is_wsol {
|
||||||
|
crate::constants::WSOL_TOKEN_ACCOUNT_META
|
||||||
|
} else {
|
||||||
|
crate::constants::USDC_TOKEN_ACCOUNT_META
|
||||||
|
}, // Input token mint (readonly)
|
||||||
AccountMeta::new_readonly(params.output_mint, false), // Output token mint (readonly)
|
AccountMeta::new_readonly(params.output_mint, false), // Output token mint (readonly)
|
||||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||||
];
|
];
|
||||||
@@ -196,7 +209,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let is_usdc = protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
let is_usdc = protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|| protocol_params.quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
|
|
||||||
if !is_wsol && !is_usdc {
|
if !is_wsol && !is_usdc {
|
||||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||||
}
|
}
|
||||||
@@ -228,7 +241,11 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -241,10 +258,15 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let output_vault_account = get_vault_account(
|
let output_vault_account = get_vault_account(
|
||||||
&pool_state,
|
&pool_state,
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
protocol_params,
|
protocol_params,
|
||||||
);
|
);
|
||||||
let input_vault_account = get_vault_account(&pool_state, ¶ms.input_mint, protocol_params);
|
let input_vault_account =
|
||||||
|
get_vault_account(&pool_state, ¶ms.input_mint, protocol_params);
|
||||||
|
|
||||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||||
get_observation_state_pda(&pool_state).unwrap()
|
get_observation_state_pda(&pool_state).unwrap()
|
||||||
@@ -267,14 +289,18 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
accounts::AUTHORITY_META, // Authority (readonly)
|
accounts::AUTHORITY_META, // Authority (readonly)
|
||||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||||
AccountMeta::new(pool_state, false), // Pool State
|
AccountMeta::new(pool_state, false), // Pool State
|
||||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||||
AccountMeta::new_readonly(mint_token_program, false), // Input Token Program (readonly)
|
AccountMeta::new_readonly(mint_token_program, false), // Input Token Program (readonly)
|
||||||
crate::constants::TOKEN_PROGRAM_META, // Output Token Program (readonly)
|
crate::constants::TOKEN_PROGRAM_META, // Output Token Program (readonly)
|
||||||
AccountMeta::new_readonly(params.input_mint, false), // Input token mint (readonly)
|
AccountMeta::new_readonly(params.input_mint, false), // Input token mint (readonly)
|
||||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Output token mint (readonly)
|
if is_wsol {
|
||||||
|
crate::constants::WSOL_TOKEN_ACCOUNT_META
|
||||||
|
} else {
|
||||||
|
crate::constants::USDC_TOKEN_ACCOUNT_META
|
||||||
|
}, // Output token mint (readonly)
|
||||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||||
];
|
];
|
||||||
// Create instruction data
|
// Create instruction data
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
pub mod bonk;
|
pub mod bonk;
|
||||||
|
pub mod meteora_damm_v2;
|
||||||
pub mod pumpfun;
|
pub mod pumpfun;
|
||||||
pub mod pumpswap;
|
pub mod pumpswap;
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod raydium_cpmm;
|
pub mod raydium_cpmm;
|
||||||
pub mod meteora_damm_v2;
|
|
||||||
|
|
||||||
// types
|
// types
|
||||||
pub mod bonk_types;
|
pub mod bonk_types;
|
||||||
|
pub mod meteora_damm_v2_types;
|
||||||
pub mod pumpswap_types;
|
pub mod pumpswap_types;
|
||||||
pub mod raydium_amm_v4_types;
|
pub mod raydium_amm_v4_types;
|
||||||
pub mod raydium_cpmm_types;
|
pub mod raydium_cpmm_types;
|
||||||
pub mod meteora_damm_v2_types;
|
|
||||||
@@ -1,12 +1,46 @@
|
|||||||
use crate::common::{bonding_curve::BondingCurveAccount, SolanaRpcClient};
|
use crate::common::{bonding_curve::BondingCurveAccount, SolanaRpcClient};
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use solana_sdk::pubkey::Pubkey;
|
use rand::seq::IndexedRandom;
|
||||||
|
use solana_sdk::{
|
||||||
|
instruction::{AccountMeta, Instruction},
|
||||||
|
pubkey::Pubkey,
|
||||||
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
|
// --- Aligned with official `@pump-fun/pump-sdk` (npm) ---
|
||||||
|
// - `src/fees.ts` `getFeeRecipient(global, mayhemMode)` — fee recipient pools
|
||||||
|
// - `src/bondingCurve.ts` `CURRENT_FEE_RECIPIENTS` / `getStaticRandomFeeRecipient`
|
||||||
|
// - `src/sdk.ts` `BONDING_CURVE_NEW_SIZE` (151) + `extendAccountInstruction` — **not** called from the
|
||||||
|
// trade hot path here (no RPC in `PumpFunInstructionBuilder`); use these helpers from a cold path if needed.
|
||||||
|
|
||||||
|
/// Minimum bonding curve account data length after protocol upgrades (`sdk.ts` `BONDING_CURVE_NEW_SIZE`).
|
||||||
|
pub const PUMP_BONDING_CURVE_MIN_DATA_LEN: usize = 151;
|
||||||
|
|
||||||
|
/// Anchor discriminator for `extend_account` (`pump.json`); same as `PumpSdk.extendAccountInstruction`.
|
||||||
|
pub const EXTEND_ACCOUNT_DISCRIMINATOR: [u8; 8] = [234, 102, 194, 203, 150, 72, 62, 229];
|
||||||
|
|
||||||
|
/// Build `extend_account` for bonding curve (cold path / separate tx only — do not add RPC to hot-path builds).
|
||||||
|
#[inline]
|
||||||
|
pub fn extend_bonding_curve_account_instruction(bonding_curve: &Pubkey, user: &Pubkey) -> Instruction {
|
||||||
|
Instruction {
|
||||||
|
program_id: accounts::PUMPFUN,
|
||||||
|
accounts: vec![
|
||||||
|
AccountMeta::new(*bonding_curve, false),
|
||||||
|
AccountMeta::new(*user, true),
|
||||||
|
crate::constants::SYSTEM_PROGRAM_META,
|
||||||
|
accounts::EVENT_AUTHORITY_META,
|
||||||
|
accounts::PUMPFUN_META,
|
||||||
|
],
|
||||||
|
data: EXTEND_ACCOUNT_DISCRIMINATOR.to_vec(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||||
pub mod seeds {
|
pub mod seeds {
|
||||||
/// Seed for bonding curve PDAs
|
/// Seed for bonding curve PDAs
|
||||||
pub const BONDING_CURVE_SEED: &[u8] = b"bonding-curve";
|
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
|
/// Seed for creator vault PDAs
|
||||||
pub const CREATOR_VAULT_SEED: &[u8] = b"creator-vault";
|
pub const CREATOR_VAULT_SEED: &[u8] = b"creator-vault";
|
||||||
@@ -21,6 +55,9 @@ pub mod seeds {
|
|||||||
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
|
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
|
||||||
|
|
||||||
pub const FEE_CONFIG_SEED: &[u8] = b"fee_config";
|
pub const FEE_CONFIG_SEED: &[u8] = b"fee_config";
|
||||||
|
|
||||||
|
/// `feeSharingConfig` PDA under pump-fees (`@pump-fun/pump-sdk` `feeSharingConfigPda`)
|
||||||
|
pub const SHARING_CONFIG_SEED: &[u8] = b"sharing-config";
|
||||||
}
|
}
|
||||||
|
|
||||||
pub mod global_constants {
|
pub mod global_constants {
|
||||||
@@ -57,8 +94,18 @@ pub mod global_constants {
|
|||||||
is_writable: true,
|
is_writable: true,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
/// Mayhem fee recipients (pump-public-docs: use any one randomly)
|
||||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
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 =
|
pub const MAYHEM_FEE_RECIPIENT_META: solana_sdk::instruction::AccountMeta =
|
||||||
solana_sdk::instruction::AccountMeta {
|
solana_sdk::instruction::AccountMeta {
|
||||||
pubkey: MAYHEM_FEE_RECIPIENT,
|
pubkey: MAYHEM_FEE_RECIPIENT,
|
||||||
@@ -89,6 +136,19 @@ pub mod global_constants {
|
|||||||
pub const PUMPFUN_AMM_FEE_6: Pubkey = pubkey!("FWsW1xNtWscwNmKv6wVsU1iTzRN6wmmk3MjxRP5tT7hz"); // Pump.fun AMM: Protocol Fee 6
|
pub const PUMPFUN_AMM_FEE_6: Pubkey = pubkey!("FWsW1xNtWscwNmKv6wVsU1iTzRN6wmmk3MjxRP5tT7hz"); // Pump.fun AMM: Protocol Fee 6
|
||||||
pub const PUMPFUN_AMM_FEE_7: Pubkey = pubkey!("G5UZAVbAf46s7cKWoyKu8kYTip9DGTpbLZ2qa9Aq69dP");
|
pub const PUMPFUN_AMM_FEE_7: Pubkey = pubkey!("G5UZAVbAf46s7cKWoyKu8kYTip9DGTpbLZ2qa9Aq69dP");
|
||||||
// Pump.fun AMM: Protocol Fee 7
|
// Pump.fun AMM: Protocol Fee 7
|
||||||
|
|
||||||
|
/// Protocol extra fee recipients (Apr 2026 breaking upgrade). One is appended after `bonding-curve-v2`, **writable**.
|
||||||
|
/// See: <https://github.com/pump-fun/pump-public-docs/blob/main/docs/BREAKING_FEE_RECIPIENT.md>
|
||||||
|
pub const PROTOCOL_EXTRA_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||||
|
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
|
||||||
|
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
|
||||||
|
pubkey!("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
|
||||||
|
pubkey!("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
|
||||||
|
pubkey!("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
|
||||||
|
pubkey!("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
|
||||||
|
pubkey!("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
|
||||||
|
pubkey!("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
|
||||||
|
];
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Constants related to program accounts and authorities
|
/// Constants related to program accounts and authorities
|
||||||
@@ -159,6 +219,82 @@ 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 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];
|
pub const SELL_DISCRIMINATOR: [u8; 8] = [51, 230, 133, 164, 1, 127, 131, 173];
|
||||||
|
|
||||||
|
/// Check if a pubkey is one of the Mayhem fee recipients
|
||||||
|
#[inline]
|
||||||
|
pub fn is_mayhem_fee_recipient(pubkey: &Pubkey) -> bool {
|
||||||
|
global_constants::MAYHEM_FEE_RECIPIENTS.iter().any(|p| p == pubkey)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Check if a pubkey is a Pump.fun AMM protocol fee recipient (PUMPFUN_AMM_FEE_1..7)
|
||||||
|
#[inline]
|
||||||
|
pub fn is_amm_fee_recipient(pubkey: &Pubkey) -> bool {
|
||||||
|
pubkey == &global_constants::PUMPFUN_AMM_FEE_1
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_2
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_3
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_4
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_5
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_6
|
||||||
|
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_7
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Mayhem: random among `Global.reservedFeeRecipient` + `Global.reservedFeeRecipients` (`fees.ts` `getFeeRecipient` when `mayhemMode === true`).
|
||||||
|
/// Uses hardcoded `MAYHEM_FEE_RECIPIENTS`; prefer gRPC/event `PumpFunParams.fee_recipient` when set.
|
||||||
|
#[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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Non-mayhem: random among `Global::fee_recipient` + `Global::fee_recipients[0..7]`.
|
||||||
|
/// Same pubkey set as `bondingCurve.ts` `CURRENT_FEE_RECIPIENTS` / `getStaticRandomFeeRecipient` and `fees.ts` `getFeeRecipient` when `mayhemMode === false`.
|
||||||
|
#[inline]
|
||||||
|
pub fn get_standard_fee_recipient_meta_random() -> AccountMeta {
|
||||||
|
const POOL: &[Pubkey] = &[
|
||||||
|
global_constants::FEE_RECIPIENT,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_1,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_2,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_3,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_4,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_5,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_6,
|
||||||
|
global_constants::PUMPFUN_AMM_FEE_7,
|
||||||
|
];
|
||||||
|
let recipient = *POOL
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.unwrap_or(&global_constants::FEE_RECIPIENT);
|
||||||
|
AccountMeta {
|
||||||
|
pubkey: recipient,
|
||||||
|
is_signer: false,
|
||||||
|
is_writable: true,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Random entry from [`global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS`] (must be last account after bonding-curve-v2, writable).
|
||||||
|
#[inline]
|
||||||
|
pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
|
||||||
|
*global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.unwrap_or(&global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 账户 #2 fee recipient:优先使用 gRPC/ShredStream 解析值(同笔 create_v2+buy 的 `observed_fee_recipient` 或 `tradeEvent.feeRecipient`);未提供时按 mayhem 从静态池随机。
|
||||||
|
#[inline]
|
||||||
|
pub fn pump_fun_fee_recipient_meta(from_stream: Pubkey, is_mayhem_mode: bool) -> AccountMeta {
|
||||||
|
if from_stream != Pubkey::default() {
|
||||||
|
AccountMeta {
|
||||||
|
pubkey: from_stream,
|
||||||
|
is_signer: false,
|
||||||
|
is_writable: true,
|
||||||
|
}
|
||||||
|
} else if is_mayhem_mode {
|
||||||
|
get_mayhem_fee_recipient_meta_random()
|
||||||
|
} else {
|
||||||
|
get_standard_fee_recipient_meta_random()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub struct Symbol;
|
pub struct Symbol;
|
||||||
|
|
||||||
impl Symbol {
|
impl Symbol {
|
||||||
@@ -178,6 +314,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]
|
#[inline]
|
||||||
pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
|
pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
|
||||||
if creator_vault_pda.eq(&Pubkey::default()) {
|
if creator_vault_pda.eq(&Pubkey::default()) {
|
||||||
@@ -186,10 +336,9 @@ pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
|
|||||||
// Fast check against cached default creator vault
|
// Fast check against cached default creator vault
|
||||||
static DEFAULT_CREATOR_VAULT: std::sync::LazyLock<Option<Pubkey>> =
|
static DEFAULT_CREATOR_VAULT: std::sync::LazyLock<Option<Pubkey>> =
|
||||||
std::sync::LazyLock::new(|| get_creator_vault_pda(&Pubkey::default()));
|
std::sync::LazyLock::new(|| get_creator_vault_pda(&Pubkey::default()));
|
||||||
if creator_vault_pda.eq(&DEFAULT_CREATOR_VAULT.unwrap()) {
|
match DEFAULT_CREATOR_VAULT.as_ref() {
|
||||||
Pubkey::default()
|
Some(default) if creator_vault_pda.eq(default) => Pubkey::default(),
|
||||||
} else {
|
_ => *creator_vault_pda,
|
||||||
*creator_vault_pda
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -207,6 +356,76 @@ pub fn get_creator_vault_pda(creator: &Pubkey) -> Option<Pubkey> {
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// `feeSharingConfig` PDA per mint (`pump-sdk` `feeSharingConfigPda` → `pump-fees` program).
|
||||||
|
#[inline]
|
||||||
|
pub fn get_fee_sharing_config_pda(mint: &Pubkey) -> Option<Pubkey> {
|
||||||
|
Pubkey::try_find_program_address(
|
||||||
|
&[seeds::SHARING_CONFIG_SEED, mint.as_ref()],
|
||||||
|
&accounts::FEE_PROGRAM,
|
||||||
|
)
|
||||||
|
.map(|(p, _)| p)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// PDA of `["creator-vault", Pubkey::default()]`. Never use as a real vault — it is only produced when
|
||||||
|
/// `creator` was missing and code incorrectly derived a vault; on-chain this fails with Anchor 2006.
|
||||||
|
#[inline]
|
||||||
|
pub fn phantom_default_creator_vault() -> Pubkey {
|
||||||
|
solana_sdk::pubkey!("2DR3iqRPVThyRLVJnwjPW1qiGWrp8RUFfHVjMbZyhdNc")
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
pub fn is_phantom_default_creator_vault(pk: &Pubkey) -> bool {
|
||||||
|
*pk == phantom_default_creator_vault()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `creator_vault` for Pump buy/sell account #10.
|
||||||
|
///
|
||||||
|
/// - If `creator` is **missing** in the outer trade-event borsh (`Pubkey::default()`) but
|
||||||
|
/// `creator_vault` was filled from **instruction accounts** (e.g. `fill_trade_accounts` index 9),
|
||||||
|
/// **trust that vault** — unless it equals [`phantom_default_creator_vault`] (bad derivation / cache).
|
||||||
|
/// - If event `creator_vault` is **missing** → [`get_creator_vault_pda`]`(creator)` (never `PDA(default)`).
|
||||||
|
/// - If it **matches** `PDA(creator)` or `PDA(fee_sharing_config(mint))` → use it (fast path, matches ix).
|
||||||
|
/// - If it **does not match** either (e.g. stale vault but `creator` from tradeEvent is correct) → use
|
||||||
|
/// [`get_creator_vault_pda`]`(creator)` so seeds match on-chain bonding curve (fixes 2006 Left≠Right).
|
||||||
|
#[inline]
|
||||||
|
pub fn resolve_creator_vault_for_ix(
|
||||||
|
creator: &Pubkey,
|
||||||
|
creator_vault_from_event: Pubkey,
|
||||||
|
mint: &Pubkey,
|
||||||
|
) -> Option<Pubkey> {
|
||||||
|
let phantom = phantom_default_creator_vault();
|
||||||
|
|
||||||
|
if *creator == Pubkey::default() {
|
||||||
|
if creator_vault_from_event == Pubkey::default() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
if creator_vault_from_event == phantom {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
return Some(creator_vault_from_event);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Real creator: poisoned cache may hold phantom vault — always remap to PDA(creator).
|
||||||
|
if creator_vault_from_event == phantom {
|
||||||
|
return get_creator_vault_pda(creator);
|
||||||
|
}
|
||||||
|
|
||||||
|
let v_derived = get_creator_vault_pda(creator)?;
|
||||||
|
if creator_vault_from_event == Pubkey::default() {
|
||||||
|
return Some(v_derived);
|
||||||
|
}
|
||||||
|
if creator_vault_from_event == v_derived {
|
||||||
|
return Some(creator_vault_from_event);
|
||||||
|
}
|
||||||
|
if let Some(sharing) = get_fee_sharing_config_pda(mint) {
|
||||||
|
let v_sharing = get_creator_vault_pda(&sharing)?;
|
||||||
|
if creator_vault_from_event == v_sharing {
|
||||||
|
return Some(creator_vault_from_event);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Some(v_derived)
|
||||||
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
|
pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
|
||||||
crate::common::fast_fn::get_cached_pda(
|
crate::common::fast_fn::get_cached_pda(
|
||||||
@@ -259,3 +478,83 @@ pub fn get_buy_price(
|
|||||||
|
|
||||||
s_u64.min(real_token_reserves)
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn fee_sharing_config_pda_deterministic() {
|
||||||
|
let mint = Pubkey::new_unique();
|
||||||
|
let a = get_fee_sharing_config_pda(&mint).unwrap();
|
||||||
|
let b = get_fee_sharing_config_pda(&mint).unwrap();
|
||||||
|
assert_eq!(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn default_creator_yields_fixed_creator_vault() {
|
||||||
|
let v = get_creator_vault_pda(&Pubkey::default()).unwrap();
|
||||||
|
assert_eq!(v, phantom_default_creator_vault(), "phantom vault constant must match PDA(default creator)");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_uses_ix_vault_when_creator_borsh_is_default() {
|
||||||
|
let mint = Pubkey::new_unique();
|
||||||
|
let ix_vault = Pubkey::new_unique();
|
||||||
|
let resolved = resolve_creator_vault_for_ix(&Pubkey::default(), ix_vault, &mint);
|
||||||
|
assert_eq!(resolved, Some(ix_vault));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_returns_none_when_creator_and_vault_missing() {
|
||||||
|
let mint = Pubkey::new_unique();
|
||||||
|
assert_eq!(
|
||||||
|
resolve_creator_vault_for_ix(&Pubkey::default(), Pubkey::default(), &mint),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_rejects_phantom_vault_when_creator_borsh_is_default() {
|
||||||
|
let mint = Pubkey::new_unique();
|
||||||
|
assert_eq!(
|
||||||
|
resolve_creator_vault_for_ix(&Pubkey::default(), phantom_default_creator_vault(), &mint),
|
||||||
|
None
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn resolve_remaps_phantom_vault_when_creator_known() {
|
||||||
|
let creator = Pubkey::new_unique();
|
||||||
|
let mint = Pubkey::new_unique();
|
||||||
|
let expected = get_creator_vault_pda(&creator).unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
resolve_creator_vault_for_ix(&creator, phantom_default_creator_vault(), &mint),
|
||||||
|
Some(expected)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,12 +2,15 @@ use crate::{
|
|||||||
common::{
|
common::{
|
||||||
spl_associated_token_account::get_associated_token_address_with_program_id, SolanaRpcClient,
|
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},
|
instruction::utils::pumpswap_types::{pool_decode, Pool},
|
||||||
};
|
};
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
|
use rand::seq::IndexedRandom;
|
||||||
use solana_account_decoder::UiAccountEncoding;
|
use solana_account_decoder::UiAccountEncoding;
|
||||||
use solana_sdk::pubkey::Pubkey;
|
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
|
||||||
|
|
||||||
|
// Pool account sizes moved to find_by_base_mint/find_by_quote_mint (POOL_DATA_LEN_SPL, POOL_DATA_LEN_T22)
|
||||||
|
|
||||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||||
pub mod seeds {
|
pub mod seeds {
|
||||||
@@ -26,6 +29,13 @@ pub mod seeds {
|
|||||||
pub const USER_VOLUME_ACCUMULATOR_SEED: &[u8] = b"user_volume_accumulator";
|
pub const USER_VOLUME_ACCUMULATOR_SEED: &[u8] = b"user_volume_accumulator";
|
||||||
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
|
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
|
||||||
pub const FEE_CONFIG_SEED: &[u8] = b"fee_config";
|
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
|
/// Constants related to program accounts and authorities
|
||||||
@@ -50,6 +60,8 @@ pub mod accounts {
|
|||||||
pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
|
pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
|
||||||
|
|
||||||
pub const AMM_PROGRAM: Pubkey = pubkey!("pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA");
|
pub const AMM_PROGRAM: Pubkey = pubkey!("pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA");
|
||||||
|
/// Pump Bonding Curve program(canonical pool 的 creator 来自此程序的 pool-authority PDA)
|
||||||
|
pub const PUMP_PROGRAM_ID: Pubkey = pubkey!("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P");
|
||||||
|
|
||||||
pub const LP_FEE_BASIS_POINTS: u64 = 25;
|
pub const LP_FEE_BASIS_POINTS: u64 = 25;
|
||||||
pub const PROTOCOL_FEE_BASIS_POINTS: u64 = 5;
|
pub const PROTOCOL_FEE_BASIS_POINTS: u64 = 5;
|
||||||
@@ -65,9 +77,31 @@ pub mod accounts {
|
|||||||
pub const DEFAULT_COIN_CREATOR_VAULT_AUTHORITY: Pubkey =
|
pub const DEFAULT_COIN_CREATOR_VAULT_AUTHORITY: Pubkey =
|
||||||
pubkey!("8N3GDaZ2iwN65oxVatKTLPNooAVUJTbfiVJ1ahyqwjSk");
|
pubkey!("8N3GDaZ2iwN65oxVatKTLPNooAVUJTbfiVJ1ahyqwjSk");
|
||||||
|
|
||||||
/// Mayhem fee recipient (for mayhem mode coins)
|
/// Mayhem fee recipients (pump-public-docs: use any one randomly for throughput)
|
||||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
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];
|
||||||
|
|
||||||
|
/// Protocol extra fee recipients (Apr 2026 breaking upgrade). After `pool-v2`: recipient (readonly), then quote ATA (writable).
|
||||||
|
pub const PROTOCOL_EXTRA_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||||
|
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
|
||||||
|
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
|
||||||
|
pubkey!("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
|
||||||
|
pubkey!("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
|
||||||
|
pubkey!("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
|
||||||
|
pubkey!("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
|
||||||
|
pubkey!("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
|
||||||
|
pubkey!("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
|
||||||
|
];
|
||||||
|
|
||||||
// META
|
// META
|
||||||
|
|
||||||
@@ -139,6 +173,63 @@ 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 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];
|
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)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Random entry from [`accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS`] (readonly; paired with [`fee_recipient_ata`] as last account).
|
||||||
|
#[inline]
|
||||||
|
pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
|
||||||
|
*accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.unwrap_or(&accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 PDA(canonical 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 池 PDA:index=0,creator=pumpPoolAuthorityPda(mint),base_mint=mint,quote_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
|
// Find a pool for a specific mint
|
||||||
pub async fn find_pool(rpc: &SolanaRpcClient, mint: &Pubkey) -> Result<Pubkey, anyhow::Error> {
|
pub async fn find_pool(rpc: &SolanaRpcClient, mint: &Pubkey) -> Result<Pubkey, anyhow::Error> {
|
||||||
let (pool_address, _) = find_by_mint(rpc, mint).await?;
|
let (pool_address, _) = find_by_mint(rpc, mint).await?;
|
||||||
@@ -178,16 +269,40 @@ pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
|
|||||||
crate::common::fast_fn::PdaCacheKey::PumpSwapUserVolume(*user),
|
crate::common::fast_fn::PdaCacheKey::PumpSwapUserVolume(*user),
|
||||||
|| {
|
|| {
|
||||||
let seeds: &[&[u8]; 2] = &[&seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
|
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);
|
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||||
pda.map(|pubkey| pubkey.0)
|
pda.map(|pubkey| pubkey.0)
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 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(
|
||||||
|
&accumulator,
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||||
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Quote-mint ATA of UserVolumeAccumulator(sell 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> {
|
pub fn get_global_volume_accumulator_pda() -> Option<Pubkey> {
|
||||||
let seeds: &[&[u8]; 1] = &[&seeds::GLOBAL_VOLUME_ACCUMULATOR_SEED];
|
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);
|
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||||
pda.map(|pubkey| pubkey.0)
|
pda.map(|pubkey| pubkey.0)
|
||||||
}
|
}
|
||||||
@@ -204,117 +319,142 @@ pub async fn fetch_pool(
|
|||||||
Ok(pool)
|
Ok(pool)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn find_by_base_mint(
|
/// Known pool account sizes: 252 (SPL Token) and 643 (Token2022)
|
||||||
|
const POOL_DATA_LEN_SPL: u64 = 8 + 244;
|
||||||
|
const POOL_DATA_LEN_T22: u64 = 643;
|
||||||
|
|
||||||
|
/// Run getProgramAccounts with a Memcmp filter, querying both pool sizes in parallel.
|
||||||
|
async fn get_program_accounts_both_sizes(
|
||||||
rpc: &SolanaRpcClient,
|
rpc: &SolanaRpcClient,
|
||||||
base_mint: &Pubkey,
|
memcmp_offset: usize,
|
||||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
mint: &Pubkey,
|
||||||
// Use getProgramAccounts to find pools for the given mint
|
) -> Result<Vec<(Pubkey, solana_sdk::account::Account)>, anyhow::Error> {
|
||||||
let filters = vec![
|
let make_config = |data_size: u64| {
|
||||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
||||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
filters: Some(vec![
|
||||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, &base_mint.to_bytes()),
|
solana_rpc_client_api::filter::RpcFilterType::DataSize(data_size),
|
||||||
),
|
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
||||||
];
|
solana_client::rpc_filter::Memcmp::new_base58_encoded(memcmp_offset, mint.as_ref()),
|
||||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
),
|
||||||
filters: Some(filters),
|
]),
|
||||||
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
|
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
|
||||||
encoding: Some(UiAccountEncoding::Base64),
|
encoding: Some(UiAccountEncoding::Base64),
|
||||||
data_slice: None,
|
data_slice: None,
|
||||||
commitment: None,
|
commitment: None,
|
||||||
min_context_slot: None,
|
min_context_slot: None,
|
||||||
},
|
},
|
||||||
with_context: None,
|
with_context: None,
|
||||||
sort_results: None,
|
sort_results: None,
|
||||||
|
}
|
||||||
};
|
};
|
||||||
let program_id = accounts::AMM_PROGRAM;
|
let program_id = accounts::AMM_PROGRAM;
|
||||||
let accounts = rpc.get_program_accounts_with_config(&program_id, config).await?;
|
#[allow(deprecated)]
|
||||||
if accounts.is_empty() {
|
let (spl_result, t22_result) = tokio::join!(
|
||||||
return Err(anyhow!("No pool found for mint {}", base_mint));
|
rpc.get_program_accounts_with_config(&program_id, make_config(POOL_DATA_LEN_SPL)),
|
||||||
}
|
rpc.get_program_accounts_with_config(&program_id, make_config(POOL_DATA_LEN_T22)),
|
||||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
);
|
||||||
let mut pools: Vec<_> = accounts
|
let mut all = spl_result.unwrap_or_default();
|
||||||
|
all.extend(t22_result.unwrap_or_default());
|
||||||
|
Ok(all)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn decode_pool_accounts(accounts: Vec<(Pubkey, solana_sdk::account::Account)>) -> Vec<(Pubkey, Pool)> {
|
||||||
|
accounts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|(addr, acc)| {
|
.filter_map(|(addr, acc)| {
|
||||||
// 🔧 修复:跳过8字节的discriminator
|
|
||||||
if acc.data.len() > 8 {
|
if acc.data.len() > 8 {
|
||||||
pool_decode(&acc.data[8..]).map(|pool| (addr, pool))
|
pool_decode(&acc.data[8..]).map(|pool| (addr, pool))
|
||||||
} else {
|
} else {
|
||||||
None
|
None
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
.collect();
|
.collect()
|
||||||
|
}
|
||||||
|
|
||||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
pub async fn find_by_base_mint(
|
||||||
|
rpc: &SolanaRpcClient,
|
||||||
|
base_mint: &Pubkey,
|
||||||
|
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||||
|
// base_mint offset: 8(discriminator) + 1(bump) + 2(index) + 32(creator) = 43
|
||||||
|
let accounts = get_program_accounts_both_sizes(rpc, 43, base_mint).await?;
|
||||||
|
if accounts.is_empty() {
|
||||||
|
return Err(anyhow!("No pool found for mint {}", base_mint));
|
||||||
|
}
|
||||||
|
let mut pools = decode_pool_accounts(accounts);
|
||||||
if pools.is_empty() {
|
if pools.is_empty() {
|
||||||
return Err(anyhow!("No valid pool decoded for mint {} (found {} accounts but all decode failed)", base_mint, accounts_count));
|
return Err(anyhow!("No valid pool decoded for mint {}", base_mint));
|
||||||
}
|
}
|
||||||
|
|
||||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||||
let (address, pool) = pools[0].clone();
|
Ok((pools[0].0, pools[0].1.clone()))
|
||||||
Ok((address, pool))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn find_by_quote_mint(
|
pub async fn find_by_quote_mint(
|
||||||
rpc: &SolanaRpcClient,
|
rpc: &SolanaRpcClient,
|
||||||
quote_mint: &Pubkey,
|
quote_mint: &Pubkey,
|
||||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||||
// Use getProgramAccounts to find pools for the given mint
|
// quote_mint offset: 8 + 1 + 2 + 32 + 32 = 75
|
||||||
let filters = vec![
|
let accounts = get_program_accounts_both_sizes(rpc, 75, quote_mint).await?;
|
||||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
|
||||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
|
||||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, "e_mint.to_bytes()),
|
|
||||||
),
|
|
||||||
];
|
|
||||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
|
||||||
filters: Some(filters),
|
|
||||||
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
|
|
||||||
encoding: Some(UiAccountEncoding::Base64),
|
|
||||||
data_slice: None,
|
|
||||||
commitment: None,
|
|
||||||
min_context_slot: None,
|
|
||||||
},
|
|
||||||
with_context: None,
|
|
||||||
sort_results: None,
|
|
||||||
};
|
|
||||||
let program_id = accounts::AMM_PROGRAM;
|
|
||||||
let accounts = rpc.get_program_accounts_with_config(&program_id, config).await?;
|
|
||||||
if accounts.is_empty() {
|
if accounts.is_empty() {
|
||||||
return Err(anyhow!("No pool found for mint {}", quote_mint));
|
return Err(anyhow!("No pool found for mint {}", quote_mint));
|
||||||
}
|
}
|
||||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
let mut pools = decode_pool_accounts(accounts);
|
||||||
let mut pools: Vec<_> = accounts
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|(addr, acc)| {
|
|
||||||
// 🔧 修复:跳过8字节的discriminator
|
|
||||||
if acc.data.len() > 8 {
|
|
||||||
pool_decode(&acc.data[8..]).map(|pool| (addr, pool))
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
|
||||||
if pools.is_empty() {
|
if pools.is_empty() {
|
||||||
return Err(anyhow!("No valid pool decoded for quote_mint {} (found {} accounts but all decode failed)", quote_mint, accounts_count));
|
return Err(anyhow!("No valid pool decoded for quote_mint {}", quote_mint));
|
||||||
}
|
}
|
||||||
|
|
||||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||||
let (address, pool) = pools[0].clone();
|
Ok((pools[0].0, pools[0].1.clone()))
|
||||||
Ok((address, pool))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 按 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(
|
pub async fn find_by_mint(
|
||||||
rpc: &SolanaRpcClient,
|
rpc: &SolanaRpcClient,
|
||||||
mint: &Pubkey,
|
mint: &Pubkey,
|
||||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||||
if let Ok((address, pool)) = find_by_base_mint(rpc, mint).await {
|
let mut diag = Vec::<String>::new();
|
||||||
return Ok((address, pool));
|
|
||||||
|
// 1. PumpSwap v2 PDA(seeds: ["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. Fallback: getProgramAccounts by base_mint / quote_mint (with 3s timeout to avoid blocking)
|
||||||
|
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_base_mint(rpc, mint)).await {
|
||||||
|
Ok(Ok((address, pool))) => return Ok((address, pool)),
|
||||||
|
Ok(Err(e)) => diag.push(format!("getProgramAccounts(base_mint): {}", e)),
|
||||||
|
Err(_) => diag.push("getProgramAccounts(base_mint): timed out (3s)".into()),
|
||||||
|
}
|
||||||
|
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_quote_mint(rpc, mint)).await {
|
||||||
|
Ok(Ok((address, pool))) => return Ok((address, pool)),
|
||||||
|
Ok(Err(e)) => diag.push(format!("getProgramAccounts(quote_mint): {}", e)),
|
||||||
|
Err(_) => diag.push("getProgramAccounts(quote_mint): timed out (3s)".into()),
|
||||||
|
}
|
||||||
|
|
||||||
|
let diag_str = diag.join("; ");
|
||||||
|
eprintln!("[find_by_mint] {} failed: {}", mint, diag_str);
|
||||||
|
Err(anyhow!(
|
||||||
|
"No pool found for mint {}. diag: {}",
|
||||||
|
mint,
|
||||||
|
diag_str
|
||||||
|
))
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_token_balances(
|
pub async fn get_token_balances(
|
||||||
@@ -337,3 +477,31 @@ pub fn get_fee_config_pda() -> Option<Pubkey> {
|
|||||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||||
pda.map(|pubkey| pubkey.0)
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -15,9 +15,14 @@ pub struct Pool {
|
|||||||
pub lp_supply: u64,
|
pub lp_supply: u64,
|
||||||
pub coin_creator: Pubkey,
|
pub coin_creator: Pubkey,
|
||||||
pub is_mayhem_mode: bool,
|
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;
|
/// Borsh 解码用的 Pool 长度。链上池为 244 字节(pump-public-docs Breaking Change),与 POOL_SIZE 一致。
|
||||||
|
pub const POOL_SIZE: usize = 244;
|
||||||
|
|
||||||
pub fn pool_decode(data: &[u8]) -> Option<Pool> {
|
pub fn pool_decode(data: &[u8]) -> Option<Pool> {
|
||||||
if data.len() < POOL_SIZE {
|
if data.len() < POOL_SIZE {
|
||||||
|
|||||||
@@ -135,9 +135,11 @@ pub fn get_vault_account(
|
|||||||
) -> Pubkey {
|
) -> Pubkey {
|
||||||
if protocol_params.base_mint == *token_mint && protocol_params.base_vault != Pubkey::default() {
|
if protocol_params.base_mint == *token_mint && protocol_params.base_vault != Pubkey::default() {
|
||||||
protocol_params.base_vault
|
protocol_params.base_vault
|
||||||
} else if protocol_params.quote_mint == *token_mint && protocol_params.quote_vault != Pubkey::default() {
|
} else if protocol_params.quote_mint == *token_mint
|
||||||
|
&& protocol_params.quote_vault != Pubkey::default()
|
||||||
|
{
|
||||||
protocol_params.quote_vault
|
protocol_params.quote_vault
|
||||||
} else {
|
} else {
|
||||||
get_vault_pda(pool_state, token_mint).unwrap()
|
get_vault_pda(pool_state, token_mint).unwrap()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+522
-138
@@ -6,8 +6,10 @@ pub mod swqos;
|
|||||||
pub mod trading;
|
pub mod trading;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
use crate::common::nonce_cache::DurableNonceInfo;
|
use crate::common::nonce_cache::DurableNonceInfo;
|
||||||
|
use crate::common::sdk_log;
|
||||||
use crate::common::GasFeeStrategy;
|
use crate::common::GasFeeStrategy;
|
||||||
use crate::common::{TradeConfig, InfrastructureConfig};
|
use crate::common::{InfrastructureConfig, TradeConfig};
|
||||||
|
#[cfg(feature = "perf-trace")]
|
||||||
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
|
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
|
||||||
use crate::constants::SOL_TOKEN_ACCOUNT;
|
use crate::constants::SOL_TOKEN_ACCOUNT;
|
||||||
use crate::constants::USD1_TOKEN_ACCOUNT;
|
use crate::constants::USD1_TOKEN_ACCOUNT;
|
||||||
@@ -17,13 +19,15 @@ use crate::swqos::common::TradeError;
|
|||||||
use crate::swqos::SwqosClient;
|
use crate::swqos::SwqosClient;
|
||||||
use crate::swqos::SwqosConfig;
|
use crate::swqos::SwqosConfig;
|
||||||
use crate::swqos::TradeType;
|
use crate::swqos::TradeType;
|
||||||
|
// Re-export for SwqosConfig (Node1/BlockRazor transport; Astralane submission mode)
|
||||||
|
pub use crate::swqos::{AstralaneTransport, SwqosTransport};
|
||||||
use crate::trading::core::params::BonkParams;
|
use crate::trading::core::params::BonkParams;
|
||||||
|
use crate::trading::core::params::DexParamEnum;
|
||||||
use crate::trading::core::params::MeteoraDammV2Params;
|
use crate::trading::core::params::MeteoraDammV2Params;
|
||||||
use crate::trading::core::params::PumpFunParams;
|
use crate::trading::core::params::PumpFunParams;
|
||||||
use crate::trading::core::params::PumpSwapParams;
|
use crate::trading::core::params::PumpSwapParams;
|
||||||
use crate::trading::core::params::RaydiumAmmV4Params;
|
use crate::trading::core::params::RaydiumAmmV4Params;
|
||||||
use crate::trading::core::params::RaydiumCpmmParams;
|
use crate::trading::core::params::RaydiumCpmmParams;
|
||||||
use crate::trading::core::params::DexParamEnum;
|
|
||||||
use crate::trading::factory::DexType;
|
use crate::trading::factory::DexType;
|
||||||
use crate::trading::MiddlewareManager;
|
use crate::trading::MiddlewareManager;
|
||||||
use crate::trading::SwapParams;
|
use crate::trading::SwapParams;
|
||||||
@@ -36,6 +40,35 @@ use solana_sdk::message::AddressLookupTableAccount;
|
|||||||
use solana_sdk::signer::Signer;
|
use solana_sdk::signer::Signer;
|
||||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signature::Signature};
|
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signature::Signature};
|
||||||
use std::sync::Arc;
|
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
|
/// Type of the token to buy
|
||||||
#[derive(Clone, PartialEq)]
|
#[derive(Clone, PartialEq)]
|
||||||
@@ -53,10 +86,14 @@ pub enum TradeTokenType {
|
|||||||
pub struct TradingInfrastructure {
|
pub struct TradingInfrastructure {
|
||||||
/// Shared RPC client for blockchain interactions
|
/// Shared RPC client for blockchain interactions
|
||||||
pub rpc: Arc<SolanaRpcClient>,
|
pub rpc: Arc<SolanaRpcClient>,
|
||||||
/// Shared SWQOS clients for transaction priority and routing
|
/// Shared SWQOS clients for transaction priority and routing. Arc<Vec<..>> so cloning into SwapParams is a single Arc clone.
|
||||||
pub swqos_clients: Vec<Arc<SwqosClient>>,
|
pub swqos_clients: Arc<Vec<Arc<SwqosClient>>>,
|
||||||
/// Configuration used to create this infrastructure
|
/// Configuration used to create this infrastructure
|
||||||
pub config: InfrastructureConfig,
|
pub config: InfrastructureConfig,
|
||||||
|
/// Precomputed at init: min(swqos_clients.len(), 2/3 * num_cores). Not computed on trade hot path.
|
||||||
|
pub max_sender_concurrency: usize,
|
||||||
|
/// Precomputed at init: first max_sender_concurrency CoreIds for job affinity. Empty if no cores. Not computed on trade hot path.
|
||||||
|
pub effective_core_ids: Arc<Vec<core_affinity::CoreId>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TradingInfrastructure {
|
impl TradingInfrastructure {
|
||||||
@@ -80,39 +117,171 @@ impl TradingInfrastructure {
|
|||||||
config.commitment.clone(),
|
config.commitment.clone(),
|
||||||
));
|
));
|
||||||
|
|
||||||
// Initialize rent cache and start background updater
|
// Initialize rent cache (with timeout so slow RPC doesn't block forever)
|
||||||
common::seed::update_rents(&rpc).await.unwrap();
|
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());
|
common::seed::start_rent_updater(rpc.clone());
|
||||||
|
|
||||||
// Create SWQOS clients with blacklist checking
|
// Create SWQOS clients with blacklist checking(QUIC 握手可能较慢,单节点超时 15s)
|
||||||
|
const SWQOS_CLIENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||||
let mut swqos_clients: Vec<Arc<SwqosClient>> = vec![];
|
let mut swqos_clients: Vec<Arc<SwqosClient>> = vec![];
|
||||||
for swqos in &config.swqos_configs {
|
for swqos in &config.swqos_configs {
|
||||||
// Check blacklist, skip disabled providers
|
|
||||||
if swqos.is_blacklisted() {
|
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;
|
continue;
|
||||||
}
|
}
|
||||||
|
match tokio::time::timeout(
|
||||||
|
SWQOS_CLIENT_TIMEOUT,
|
||||||
|
SwqosConfig::get_swqos_client(
|
||||||
|
config.rpc_url.clone(),
|
||||||
|
config.commitment.clone(),
|
||||||
|
swqos.clone(),
|
||||||
|
config.mev_protection,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
Ok(Ok(swqos_client)) => swqos_clients.push(swqos_client),
|
||||||
|
Ok(Err(err)) => {
|
||||||
|
eprintln!(
|
||||||
|
"⚠️ SWQOS {:?} 初始化失败: {}(已从列表中排除)",
|
||||||
|
swqos.swqos_type(),
|
||||||
|
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(_) => {
|
||||||
|
eprintln!(
|
||||||
|
"⚠️ SWQOS {:?} 初始化超时({}s),已跳过",
|
||||||
|
swqos.swqos_type(),
|
||||||
|
SWQOS_CLIENT_TIMEOUT.as_secs()
|
||||||
|
);
|
||||||
|
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()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 若全部失败、被黑名单跳过或仅配置了不可用通道,至少保留一条 Rpc Default,否则 execute_parallel 会因 swqos_clients 为空直接报错。
|
||||||
|
if swqos_clients.is_empty() {
|
||||||
|
eprintln!(
|
||||||
|
"⚠️ 无任何 SWQOS 客户端初始化成功,将回退为普通 RPC 发送: {}",
|
||||||
|
config.rpc_url
|
||||||
|
);
|
||||||
|
if sdk_log::sdk_log_enabled() {
|
||||||
|
warn!(
|
||||||
|
target: "sol_trade_sdk",
|
||||||
|
"no SWQOS clients initialized; falling back to Rpc Default ({})",
|
||||||
|
config.rpc_url
|
||||||
|
);
|
||||||
|
}
|
||||||
match SwqosConfig::get_swqos_client(
|
match SwqosConfig::get_swqos_client(
|
||||||
config.rpc_url.clone(),
|
config.rpc_url.clone(),
|
||||||
config.commitment.clone(),
|
config.commitment.clone(),
|
||||||
swqos.clone(),
|
SwqosConfig::Default(config.rpc_url.clone()),
|
||||||
).await {
|
config.mev_protection,
|
||||||
Ok(swqos_client) => swqos_clients.push(swqos_client),
|
)
|
||||||
Err(err) => eprintln!(
|
.await
|
||||||
"failed to create {:?} swqos client: {err}. Excluding from swqos list",
|
{
|
||||||
swqos.swqos_type()
|
Ok(c) => swqos_clients.push(c),
|
||||||
),
|
Err(e) => {
|
||||||
|
if sdk_log::sdk_log_enabled() {
|
||||||
|
warn!(
|
||||||
|
target: "sol_trade_sdk",
|
||||||
|
"fallback Rpc Default client failed: {}",
|
||||||
|
e
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if !swqos_clients.is_empty() {
|
||||||
|
let labels: Vec<&str> = swqos_clients
|
||||||
|
.iter()
|
||||||
|
.map(|c| c.get_swqos_type().as_str())
|
||||||
|
.collect();
|
||||||
|
eprintln!(
|
||||||
|
"ℹ️ SWQOS 通道已就绪: {} 条 → [{}]",
|
||||||
|
swqos_clients.len(),
|
||||||
|
labels.join(", ")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let swqos_count = swqos_clients.len();
|
||||||
|
let (max_sender_concurrency, effective_core_ids) = {
|
||||||
|
let num_cores = core_affinity::get_core_ids().map(|c| c.len()).unwrap_or(0);
|
||||||
|
let max_by_cores = (num_cores * 2 / 3).max(1);
|
||||||
|
let cap = swqos_count.min(max_by_cores).max(1);
|
||||||
|
let ids = core_affinity::get_core_ids()
|
||||||
|
.map(|all| {
|
||||||
|
let v: Vec<_> = all.into_iter().collect();
|
||||||
|
let len = v.len();
|
||||||
|
if config.swqos_cores_from_end && len >= cap {
|
||||||
|
v.into_iter().skip(len - cap).collect()
|
||||||
|
} else {
|
||||||
|
v.into_iter().take(cap).collect()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
(cap, Arc::new(ids))
|
||||||
|
};
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
rpc,
|
rpc,
|
||||||
swqos_clients,
|
swqos_clients: Arc::new(swqos_clients),
|
||||||
config,
|
config,
|
||||||
|
max_sender_concurrency,
|
||||||
|
effective_core_ids,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// When using `TradeConfig::with_swqos_cores_from_end(true)`, returns the same "last N" core indices
|
||||||
|
/// that the infrastructure uses. Pass the result to `TradingClient::with_dedicated_sender_threads`
|
||||||
|
/// for 方式 C (组合使用): SWQOS on last N cores and dedicated sender threads pinned to those cores.
|
||||||
|
///
|
||||||
|
/// Returns `None` if core count cannot be determined. `swqos_count` is typically `swqos_configs.len()`.
|
||||||
|
pub fn recommended_sender_thread_core_indices(swqos_count: usize) -> Option<Vec<usize>> {
|
||||||
|
let all = core_affinity::get_core_ids()?;
|
||||||
|
let num_cores = all.len();
|
||||||
|
if num_cores == 0 {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
let max_by_cores = (num_cores * 2 / 3).max(1);
|
||||||
|
let cap = swqos_count.min(max_by_cores).max(1).min(num_cores);
|
||||||
|
let start = num_cores.saturating_sub(cap);
|
||||||
|
Some((start..num_cores).collect())
|
||||||
|
}
|
||||||
|
|
||||||
/// Main trading client for Solana DeFi protocols
|
/// Main trading client for Solana DeFi protocols
|
||||||
///
|
///
|
||||||
/// `SolTradingSDK` provides a unified interface for trading across multiple Solana DEXs
|
/// `SolTradingSDK` provides a unified interface for trading across multiple Solana DEXs
|
||||||
@@ -129,6 +298,18 @@ pub struct TradingClient {
|
|||||||
/// Whether to use seed optimization for all ATA operations (default: true)
|
/// Whether to use seed optimization for all ATA operations (default: true)
|
||||||
/// Applies to all token account creations across buy and sell operations
|
/// Applies to all token account creations across buy and sell operations
|
||||||
pub use_seed_optimize: bool,
|
pub use_seed_optimize: bool,
|
||||||
|
/// Internal: use dedicated sender threads (default false). Set via with_dedicated_sender_threads() for advanced use.
|
||||||
|
pub use_dedicated_sender_threads: bool,
|
||||||
|
/// Internal: core indices for dedicated sender threads. Trimmed to ≤ max_sender_concurrency at set.
|
||||||
|
pub sender_thread_cores: Option<Arc<Vec<usize>>>,
|
||||||
|
/// Internal: precomputed at infra init (min(swqos_count, 2/3*cores)). Not user-configurable.
|
||||||
|
pub max_sender_concurrency: usize,
|
||||||
|
/// Internal: precomputed at infra init for job affinity. Not user-configurable.
|
||||||
|
pub effective_core_ids: Arc<Vec<core_affinity::CoreId>>,
|
||||||
|
/// 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);
|
static INSTANCE: Mutex<Option<Arc<TradingClient>>> = Mutex::new(None);
|
||||||
@@ -143,6 +324,12 @@ impl Clone for TradingClient {
|
|||||||
infrastructure: self.infrastructure.clone(),
|
infrastructure: self.infrastructure.clone(),
|
||||||
middleware_manager: self.middleware_manager.clone(),
|
middleware_manager: self.middleware_manager.clone(),
|
||||||
use_seed_optimize: self.use_seed_optimize,
|
use_seed_optimize: self.use_seed_optimize,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
|
max_sender_concurrency: self.max_sender_concurrency,
|
||||||
|
effective_core_ids: self.effective_core_ids.clone(),
|
||||||
|
log_enabled: self.log_enabled,
|
||||||
|
check_min_tip: self.check_min_tip,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -172,7 +359,7 @@ pub struct TradeBuyParams {
|
|||||||
/// Optional address lookup table for transaction size optimization
|
/// Optional address lookup table for transaction size optimization
|
||||||
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||||
/// Whether to wait for transaction confirmation before returning
|
/// Whether to wait for transaction confirmation before returning
|
||||||
pub wait_transaction_confirmed: bool,
|
pub wait_tx_confirmed: bool,
|
||||||
/// Whether to create input token associated token account
|
/// Whether to create input token associated token account
|
||||||
pub create_input_token_ata: bool,
|
pub create_input_token_ata: bool,
|
||||||
/// Whether to close input token associated token account after trade
|
/// Whether to close input token associated token account after trade
|
||||||
@@ -192,6 +379,8 @@ pub struct TradeBuyParams {
|
|||||||
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
|
/// 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.
|
/// This option only applies to PumpFun and PumpSwap DEXes; it is ignored for other DEXes.
|
||||||
pub use_exact_sol_amount: Option<bool>,
|
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
|
/// Parameters for executing sell orders across different DEX protocols
|
||||||
@@ -221,7 +410,7 @@ pub struct TradeSellParams {
|
|||||||
/// Optional address lookup table for transaction size optimization
|
/// Optional address lookup table for transaction size optimization
|
||||||
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||||
/// Whether to wait for transaction confirmation before returning
|
/// Whether to wait for transaction confirmation before returning
|
||||||
pub wait_transaction_confirmed: bool,
|
pub wait_tx_confirmed: bool,
|
||||||
/// Whether to create output token associated token account
|
/// Whether to create output token associated token account
|
||||||
pub create_output_token_ata: bool,
|
pub create_output_token_ata: bool,
|
||||||
/// Whether to close output token associated token account after trade
|
/// Whether to close output token associated token account after trade
|
||||||
@@ -236,6 +425,8 @@ pub struct TradeSellParams {
|
|||||||
pub gas_fee_strategy: GasFeeStrategy,
|
pub gas_fee_strategy: GasFeeStrategy,
|
||||||
/// Whether to simulate the transaction instead of executing it
|
/// Whether to simulate the transaction instead of executing it
|
||||||
pub simulate: bool,
|
pub simulate: bool,
|
||||||
|
/// 可选:事件收到时间(微秒,与 sol-parser-sdk clock 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点。
|
||||||
|
pub grpc_recv_us: Option<i64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl TradingClient {
|
impl TradingClient {
|
||||||
@@ -259,12 +450,20 @@ impl TradingClient {
|
|||||||
) -> Self {
|
) -> Self {
|
||||||
// Initialize wallet-specific caches (fast, synchronous)
|
// Initialize wallet-specific caches (fast, synchronous)
|
||||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||||
|
let max_sender_concurrency = infrastructure.max_sender_concurrency;
|
||||||
|
let effective_core_ids = infrastructure.effective_core_ids.clone();
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
payer,
|
payer,
|
||||||
infrastructure,
|
infrastructure,
|
||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize,
|
use_seed_optimize,
|
||||||
|
use_dedicated_sender_threads: false,
|
||||||
|
sender_thread_cores: None,
|
||||||
|
max_sender_concurrency,
|
||||||
|
effective_core_ids,
|
||||||
|
log_enabled: true,
|
||||||
|
check_min_tip: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -286,71 +485,144 @@ impl TradingClient {
|
|||||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||||
|
|
||||||
if create_wsol_ata {
|
if create_wsol_ata {
|
||||||
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
|
// 在后台异步创建 WSOL ATA,不阻塞启动
|
||||||
|
let payer_clone = payer.clone();
|
||||||
|
let rpc_clone = infrastructure.rpc.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
Self::ensure_wsol_ata(&payer_clone, &rpc_clone).await;
|
||||||
|
});
|
||||||
|
if sdk_log::sdk_log_enabled() {
|
||||||
|
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA creation started in background, does not block bot startup");
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let max_sender_concurrency = infrastructure.max_sender_concurrency;
|
||||||
|
let effective_core_ids = infrastructure.effective_core_ids.clone();
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
payer,
|
payer,
|
||||||
infrastructure,
|
infrastructure,
|
||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize,
|
use_seed_optimize,
|
||||||
|
use_dedicated_sender_threads: false,
|
||||||
|
sender_thread_cores: None,
|
||||||
|
max_sender_concurrency,
|
||||||
|
effective_core_ids,
|
||||||
|
log_enabled: true,
|
||||||
|
check_min_tip: false,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Helper to ensure WSOL ATA exists for a wallet
|
/// 单次尝试创建 WSOL ATA:获取 blockhash、组交易、发送并确认。成功或账户已存在返回 Ok(()),否则返回 Err(错误信息)。
|
||||||
async fn ensure_wsol_ata(payer: &Arc<Keypair>, rpc: &Arc<SolanaRpcClient>) {
|
async fn try_create_wsol_ata_once(
|
||||||
let wsol_ata =
|
rpc: &SolanaRpcClient,
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
payer: &Arc<Keypair>,
|
||||||
&payer.pubkey(),
|
wsol_ata: &solana_sdk::pubkey::Pubkey,
|
||||||
&WSOL_TOKEN_ACCOUNT,
|
create_ata_ixs: &[solana_sdk::instruction::Instruction],
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
timeout_secs: u64,
|
||||||
);
|
) -> Result<(), String> {
|
||||||
|
use solana_sdk::transaction::Transaction;
|
||||||
match rpc.get_account(&wsol_ata).await {
|
let recent_blockhash = rpc
|
||||||
Ok(_) => {
|
.get_latest_blockhash()
|
||||||
println!("✅ WSOL ATA已存在: {}", wsol_ata);
|
.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(_) => Err(format!("Transaction confirmation timeout ({}s)", timeout_secs)),
|
||||||
println!("🔨 创建WSOL ATA: {}", wsol_ata);
|
}
|
||||||
let create_ata_ixs =
|
}
|
||||||
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
|
||||||
|
|
||||||
if !create_ata_ixs.is_empty() {
|
/// 确保钱包存在 WSOL ATA;不存在则发交易创建(会花费租金 + 手续费,初始化阶段唯一会扣钱的逻辑)
|
||||||
use solana_sdk::transaction::Transaction;
|
async fn ensure_wsol_ata(payer: &Arc<Keypair>, rpc: &Arc<SolanaRpcClient>) {
|
||||||
let recent_blockhash = rpc.get_latest_blockhash().await.unwrap();
|
const MAX_RETRIES: usize = 3;
|
||||||
let tx = Transaction::new_signed_with_payer(
|
const TIMEOUT_SECS: u64 = 10;
|
||||||
&create_ata_ixs,
|
|
||||||
Some(&payer.pubkey()),
|
|
||||||
&[payer.as_ref()],
|
|
||||||
recent_blockhash,
|
|
||||||
);
|
|
||||||
|
|
||||||
match rpc.send_and_confirm_transaction(&tx).await {
|
let wsol_ata = crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
Ok(signature) => {
|
&payer.pubkey(),
|
||||||
println!("✅ WSOL ATA创建成功: {}", signature);
|
&WSOL_TOKEN_ACCOUNT,
|
||||||
}
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
Err(e) => {
|
);
|
||||||
match rpc.get_account(&wsol_ata).await {
|
|
||||||
Ok(_) => {
|
if rpc.get_account(&wsol_ata).await.is_ok() {
|
||||||
println!(
|
if sdk_log::sdk_log_enabled() {
|
||||||
"✅ WSOL ATA已存在(交易失败但账户存在): {}",
|
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists: {}", wsol_ata);
|
||||||
wsol_ata
|
}
|
||||||
);
|
return;
|
||||||
}
|
}
|
||||||
Err(_) => {
|
|
||||||
panic!(
|
let create_ata_ixs = crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
||||||
"❌ WSOL ATA创建失败且账户不存在: {}. 错误: {}",
|
if create_ata_ixs.is_empty() {
|
||||||
wsol_ata, e
|
if sdk_log::sdk_log_enabled() {
|
||||||
);
|
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA already exists (no need to create)");
|
||||||
}
|
}
|
||||||
}
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
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");
|
||||||
|
}
|
||||||
|
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
|
/// Creates a new SolTradingSDK instance with the specified configuration
|
||||||
@@ -366,6 +638,10 @@ impl TradingClient {
|
|||||||
/// Returns a configured `SolTradingSDK` instance ready for trading operations
|
/// Returns a configured `SolTradingSDK` instance ready for trading operations
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn new(payer: Arc<Keypair>, trade_config: TradeConfig) -> Self {
|
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
|
// Create infrastructure from trade config
|
||||||
let infra_config = InfrastructureConfig::from_trade_config(&trade_config);
|
let infra_config = InfrastructureConfig::from_trade_config(&trade_config);
|
||||||
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);
|
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);
|
||||||
@@ -373,16 +649,46 @@ impl TradingClient {
|
|||||||
// Initialize wallet-specific caches
|
// Initialize wallet-specific caches
|
||||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||||
|
|
||||||
// Handle WSOL ATA creation if configured
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// 初始化阶段会花费租金/手续费的唯一路径:创建 WSOL ATA(ensure_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 {
|
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
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 并发/核心相关由 infrastructure 预计算,用户无需配置
|
||||||
let instance = Self {
|
let instance = Self {
|
||||||
payer,
|
payer,
|
||||||
infrastructure,
|
infrastructure: infrastructure.clone(),
|
||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize: trade_config.use_seed_optimize,
|
use_seed_optimize: trade_config.use_seed_optimize,
|
||||||
|
use_dedicated_sender_threads: false,
|
||||||
|
sender_thread_cores: None,
|
||||||
|
max_sender_concurrency: infrastructure.max_sender_concurrency,
|
||||||
|
effective_core_ids: infrastructure.effective_core_ids.clone(),
|
||||||
|
log_enabled: trade_config.log_enabled,
|
||||||
|
check_min_tip: trade_config.check_min_tip,
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut current = INSTANCE.lock();
|
let mut current = INSTANCE.lock();
|
||||||
@@ -406,6 +712,34 @@ impl TradingClient {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// **Advanced.** Use dedicated OS threads for sender pool (and optionally pin to cores).
|
||||||
|
/// By default the SDK uses a shared tokio pool; this can reduce scheduling contention when sending many txs.
|
||||||
|
/// Concurrency and core count are capped internally (≤ swqos count, ≤ 2/3 of CPU cores).
|
||||||
|
/// - `None`: keep default (shared tokio pool).
|
||||||
|
/// - `Some(vec![])`: dedicated threads with default count, no core pinning.
|
||||||
|
/// - `Some(indices)`: dedicated threads pinned to those core indices (trimmed to cap).
|
||||||
|
///
|
||||||
|
/// **Latency note:** If a core is busy with other work (node, bot), SWQOS submit on that core can be delayed.
|
||||||
|
/// For lowest latency, pass core indices that are *reserved* for SWQOS (do not run other CPU-heavy work on those cores).
|
||||||
|
pub fn with_dedicated_sender_threads(mut self, core_indices: Option<Vec<usize>>) -> Self {
|
||||||
|
match core_indices {
|
||||||
|
None => {
|
||||||
|
self.use_dedicated_sender_threads = false;
|
||||||
|
self.sender_thread_cores = None;
|
||||||
|
}
|
||||||
|
Some(v) if v.is_empty() => {
|
||||||
|
self.use_dedicated_sender_threads = true;
|
||||||
|
self.sender_thread_cores = None;
|
||||||
|
}
|
||||||
|
Some(v) => {
|
||||||
|
self.use_dedicated_sender_threads = true;
|
||||||
|
let cap = v.len().min(self.max_sender_concurrency);
|
||||||
|
self.sender_thread_cores = Some(Arc::new(if cap < v.len() { v[..cap].to_vec() } else { v }));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
/// Gets the RPC client instance for direct Solana blockchain interactions
|
/// Gets the RPC client instance for direct Solana blockchain interactions
|
||||||
///
|
///
|
||||||
/// This provides access to the underlying Solana RPC client that can be used
|
/// This provides access to the underlying Solana RPC client that can be used
|
||||||
@@ -463,17 +797,30 @@ impl TradingClient {
|
|||||||
pub async fn buy(
|
pub async fn buy(
|
||||||
&self,
|
&self,
|
||||||
params: TradeBuyParams,
|
params: TradeBuyParams,
|
||||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), 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")]
|
#[cfg(feature = "perf-trace")]
|
||||||
if params.slippage_basis_points.is_none() {
|
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
|
||||||
log::debug!(
|
debug!(
|
||||||
|
target: "sol_trade_sdk",
|
||||||
"slippage_basis_points is none, use default slippage basis points: {}",
|
"slippage_basis_points is none, use default slippage basis points: {}",
|
||||||
DEFAULT_SLIPPAGE
|
DEFAULT_SLIPPAGE
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
if params.input_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
if params.input_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||||
return Err(anyhow::anyhow!(
|
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 {
|
let input_token_mint = if params.input_token_type == TradeTokenType::SOL {
|
||||||
@@ -485,8 +832,7 @@ impl TradingClient {
|
|||||||
} else {
|
} else {
|
||||||
USD1_TOKEN_ACCOUNT
|
USD1_TOKEN_ACCOUNT
|
||||||
};
|
};
|
||||||
let executor = TradeFactory::create_executor(params.dex_type.clone());
|
let executor = TradeFactory::create_executor(params.dex_type);
|
||||||
let protocol_params = params.extension_params;
|
|
||||||
let buy_params = SwapParams {
|
let buy_params = SwapParams {
|
||||||
rpc: Some(self.infrastructure.rpc.clone()),
|
rpc: Some(self.infrastructure.rpc.clone()),
|
||||||
payer: self.payer.clone(),
|
payer: self.payer.clone(),
|
||||||
@@ -499,8 +845,8 @@ impl TradingClient {
|
|||||||
slippage_basis_points: params.slippage_basis_points,
|
slippage_basis_points: params.slippage_basis_points,
|
||||||
address_lookup_table_account: params.address_lookup_table_account,
|
address_lookup_table_account: params.address_lookup_table_account,
|
||||||
recent_blockhash: params.recent_blockhash,
|
recent_blockhash: params.recent_blockhash,
|
||||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
wait_tx_confirmed: params.wait_tx_confirmed,
|
||||||
protocol_params: protocol_params.clone(),
|
protocol_params,
|
||||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||||
middleware_manager: self.middleware_manager.clone(),
|
middleware_manager: self.middleware_manager.clone(),
|
||||||
@@ -513,35 +859,20 @@ impl TradingClient {
|
|||||||
fixed_output_amount: params.fixed_output_token_amount,
|
fixed_output_amount: params.fixed_output_token_amount,
|
||||||
gas_fee_strategy: params.gas_fee_strategy,
|
gas_fee_strategy: params.gas_fee_strategy,
|
||||||
simulate: params.simulate,
|
simulate: params.simulate,
|
||||||
|
log_enabled: self.log_enabled,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
|
max_sender_concurrency: self.max_sender_concurrency,
|
||||||
|
effective_core_ids: self.effective_core_ids.clone(),
|
||||||
|
check_min_tip: self.check_min_tip,
|
||||||
|
grpc_recv_us: params.grpc_recv_us,
|
||||||
use_exact_sol_amount: params.use_exact_sol_amount,
|
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 swap_result = executor.swap(buy_params).await;
|
||||||
let result =
|
let result =
|
||||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
swap_result.map(|(success, sigs, err, timings)| (success, sigs, err.map(TradeError::from), timings));
|
||||||
return result;
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute a sell order for a specified token
|
/// Execute a sell order for a specified token
|
||||||
@@ -573,21 +904,33 @@ impl TradingClient {
|
|||||||
pub async fn sell(
|
pub async fn sell(
|
||||||
&self,
|
&self,
|
||||||
params: TradeSellParams,
|
params: TradeSellParams,
|
||||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), anyhow::Error> {
|
||||||
#[cfg(feature = "perf-trace")]
|
#[cfg(feature = "perf-trace")]
|
||||||
if params.slippage_basis_points.is_none() {
|
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
|
||||||
log::debug!(
|
debug!(
|
||||||
|
target: "sol_trade_sdk",
|
||||||
"slippage_basis_points is none, use default slippage basis points: {}",
|
"slippage_basis_points is none, use default slippage basis points: {}",
|
||||||
DEFAULT_SLIPPAGE
|
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!(
|
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;
|
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 {
|
let output_token_mint = if params.output_token_type == TradeTokenType::SOL {
|
||||||
SOL_TOKEN_ACCOUNT
|
SOL_TOKEN_ACCOUNT
|
||||||
} else if params.output_token_type == TradeTokenType::WSOL {
|
} else if params.output_token_type == TradeTokenType::WSOL {
|
||||||
@@ -609,8 +952,8 @@ impl TradingClient {
|
|||||||
slippage_basis_points: params.slippage_basis_points,
|
slippage_basis_points: params.slippage_basis_points,
|
||||||
address_lookup_table_account: params.address_lookup_table_account,
|
address_lookup_table_account: params.address_lookup_table_account,
|
||||||
recent_blockhash: params.recent_blockhash,
|
recent_blockhash: params.recent_blockhash,
|
||||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
wait_tx_confirmed: params.wait_tx_confirmed,
|
||||||
protocol_params: protocol_params.clone(),
|
protocol_params,
|
||||||
with_tip: params.with_tip,
|
with_tip: params.with_tip,
|
||||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||||
@@ -623,36 +966,20 @@ impl TradingClient {
|
|||||||
fixed_output_amount: params.fixed_output_token_amount,
|
fixed_output_amount: params.fixed_output_token_amount,
|
||||||
gas_fee_strategy: params.gas_fee_strategy,
|
gas_fee_strategy: params.gas_fee_strategy,
|
||||||
simulate: params.simulate,
|
simulate: params.simulate,
|
||||||
|
log_enabled: self.log_enabled,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
|
max_sender_concurrency: self.max_sender_concurrency,
|
||||||
|
effective_core_ids: self.effective_core_ids.clone(),
|
||||||
|
check_min_tip: self.check_min_tip,
|
||||||
|
grpc_recv_us: params.grpc_recv_us,
|
||||||
use_exact_sol_amount: None,
|
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 swap_result = executor.swap(sell_params).await;
|
||||||
let result =
|
let result =
|
||||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
swap_result.map(|(success, sigs, err, timings)| (success, sigs, err.map(TradeError::from), timings));
|
||||||
return result;
|
result
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Execute a sell order for a percentage of the specified token amount
|
/// Execute a sell order for a percentage of the specified token amount
|
||||||
@@ -686,7 +1013,7 @@ impl TradingClient {
|
|||||||
mut params: TradeSellParams,
|
mut params: TradeSellParams,
|
||||||
amount_token: u64,
|
amount_token: u64,
|
||||||
percent: u64,
|
percent: u64,
|
||||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), anyhow::Error> {
|
||||||
if percent == 0 || percent > 100 {
|
if percent == 0 || percent > 100 {
|
||||||
return Err(anyhow::anyhow!("Percentage must be between 1 and 100"));
|
return Err(anyhow::anyhow!("Percentage must be between 1 and 100"));
|
||||||
}
|
}
|
||||||
@@ -815,8 +1142,10 @@ impl TradingClient {
|
|||||||
/// - 交易执行或确认失败
|
/// - 交易执行或确认失败
|
||||||
/// - 网络或 RPC 错误
|
/// - 网络或 RPC 错误
|
||||||
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
||||||
use crate::trading::common::wsol_manager::{wrap_wsol_to_sol as wrap_wsol_to_sol_internal, wrap_wsol_to_sol_without_create};
|
|
||||||
use crate::common::seed::get_associated_token_address_with_program_id_use_seed;
|
use crate::common::seed::get_associated_token_address_with_program_id_use_seed;
|
||||||
|
use crate::trading::common::wsol_manager::{
|
||||||
|
wrap_wsol_to_sol as wrap_wsol_to_sol_internal, wrap_wsol_to_sol_without_create,
|
||||||
|
};
|
||||||
use solana_sdk::transaction::Transaction;
|
use solana_sdk::transaction::Transaction;
|
||||||
|
|
||||||
// 检查临时seed账户是否已存在
|
// 检查临时seed账户是否已存在
|
||||||
@@ -837,7 +1166,62 @@ impl TradingClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let mut transaction = Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
let mut transaction =
|
||||||
|
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||||
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
|
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||||
|
Ok(signature.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claim Bonding Curve (Pump) cashback.
|
||||||
|
///
|
||||||
|
/// Transfers native SOL from the user's UserVolumeAccumulator to the wallet.
|
||||||
|
/// If there is nothing to claim, the transaction may still succeed with no SOL transferred.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// * `Ok(String)` - Transaction signature
|
||||||
|
/// * `Err(anyhow::Error)` - Build or send failure (e.g. invalid PDA)
|
||||||
|
pub async fn claim_cashback_pumpfun(&self) -> Result<String, anyhow::Error> {
|
||||||
|
use solana_sdk::transaction::Transaction;
|
||||||
|
let ix = crate::instruction::pumpfun::claim_cashback_pumpfun_instruction(
|
||||||
|
&self.payer.pubkey(),
|
||||||
|
)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Failed to build PumpFun claim_cashback instruction"))?;
|
||||||
|
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
let mut transaction = Transaction::new_with_payer(&[ix], Some(&self.payer.pubkey()));
|
||||||
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
|
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||||
|
Ok(signature.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Claim PumpSwap (AMM) cashback.
|
||||||
|
///
|
||||||
|
/// Transfers WSOL from the UserVolumeAccumulator to the user's WSOL ATA.
|
||||||
|
/// Creates the user's WSOL ATA idempotently if it does not exist, then claims.
|
||||||
|
///
|
||||||
|
/// # Returns
|
||||||
|
/// * `Ok(String)` - Transaction signature
|
||||||
|
/// * `Err(anyhow::Error)` - Build or send failure
|
||||||
|
pub async fn claim_cashback_pumpswap(&self) -> Result<String, anyhow::Error> {
|
||||||
|
use solana_sdk::transaction::Transaction;
|
||||||
|
let mut instructions =
|
||||||
|
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||||
|
&self.payer.pubkey(),
|
||||||
|
&self.payer.pubkey(),
|
||||||
|
&WSOL_TOKEN_ACCOUNT,
|
||||||
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
|
self.use_seed_optimize,
|
||||||
|
);
|
||||||
|
let ix = crate::instruction::pumpswap::claim_cashback_pumpswap_instruction(
|
||||||
|
&self.payer.pubkey(),
|
||||||
|
WSOL_TOKEN_ACCOUNT,
|
||||||
|
crate::constants::TOKEN_PROGRAM,
|
||||||
|
)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Failed to build PumpSwap claim_cashback instruction"))?;
|
||||||
|
instructions.push(ix);
|
||||||
|
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
let mut transaction =
|
||||||
|
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||||
Ok(signature.to_string())
|
Ok(signature.to_string())
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
//! 🚀 编译器级性能优化 - 极致编译时优化
|
//! 🚀 编译器级性能优化 - 极致编译时优化
|
||||||
//!
|
//!
|
||||||
//! 实现编译时的极致性能优化,包括:
|
//! 实现编译时的极致性能优化,包括:
|
||||||
//! - 编译器标志优化配置
|
//! - 编译器标志优化配置
|
||||||
//! - 编译时代码生成
|
//! - 编译时代码生成
|
||||||
@@ -137,100 +137,110 @@ impl CompilerOptimizer {
|
|||||||
stats: CompilerOptimizationStats::default(),
|
stats: CompilerOptimizationStats::default(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 生成超高性能编译配置
|
/// 🚀 生成超高性能编译配置
|
||||||
pub fn generate_ultra_performance_config(&self) -> Result<CompilerConfig> {
|
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();
|
let mut rustflags = Vec::new();
|
||||||
|
|
||||||
// 基础优化标志
|
// 基础优化标志
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push("opt-level=3".to_string()); // 最高优化级别
|
rustflags.push("opt-level=3".to_string()); // 最高优化级别
|
||||||
|
|
||||||
// 链接时优化
|
// 链接时优化
|
||||||
if self.optimization_flags.enable_lto {
|
if self.optimization_flags.enable_lto {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push("lto=fat".to_string()); // 胖LTO获得最佳优化
|
rustflags.push("lto=fat".to_string()); // 胖LTO获得最佳优化
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目标CPU优化
|
// 目标CPU优化
|
||||||
if !self.optimization_flags.target_cpu.is_empty() {
|
if !self.optimization_flags.target_cpu.is_empty() {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("target-cpu={}", self.optimization_flags.target_cpu));
|
rustflags.push(format!("target-cpu={}", self.optimization_flags.target_cpu));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 目标特性
|
// 目标特性
|
||||||
if !self.optimization_flags.target_features.is_empty() {
|
if !self.optimization_flags.target_features.is_empty() {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("target-feature={}", self.optimization_flags.target_features.join(",")));
|
rustflags.push(format!(
|
||||||
|
"target-feature={}",
|
||||||
|
self.optimization_flags.target_features.join(",")
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 代码模型
|
// 代码模型
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
rustflags
|
||||||
|
.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
||||||
|
|
||||||
// 恐慌处理
|
// 恐慌处理
|
||||||
if self.codegen_config.panic_abort {
|
if self.codegen_config.panic_abort {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push("panic=abort".to_string());
|
rustflags.push("panic=abort".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 溢出检查
|
// 溢出检查
|
||||||
if !self.codegen_config.overflow_checks {
|
if !self.codegen_config.overflow_checks {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push("overflow-checks=no".to_string());
|
rustflags.push("overflow-checks=no".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
// 代码生成单元
|
// 代码生成单元
|
||||||
if let Some(units) = self.optimization_flags.codegen_units {
|
if let Some(units) = self.optimization_flags.codegen_units {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("codegen-units={}", units));
|
rustflags.push(format!("codegen-units={}", units));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 内联阈值
|
// 内联阈值
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("inline-threshold={}", self.inline_strategy.inline_threshold));
|
rustflags.push(format!("inline-threshold={}", self.inline_strategy.inline_threshold));
|
||||||
|
|
||||||
// 额外的性能优化标志
|
// 额外的性能优化标志
|
||||||
rustflags.extend([
|
rustflags.extend([
|
||||||
"-C".to_string(), "embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
"-C".to_string(),
|
||||||
"-C".to_string(), "debuginfo=0".to_string(), // 禁用调试信息
|
"embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
||||||
"-C".to_string(), "rpath=no".to_string(), // 禁用rpath
|
"-C".to_string(),
|
||||||
"-C".to_string(), "force-frame-pointers=no".to_string(), // 禁用帧指针
|
"debuginfo=0".to_string(), // 禁用调试信息
|
||||||
|
"-C".to_string(),
|
||||||
|
"rpath=no".to_string(), // 禁用rpath
|
||||||
|
"-C".to_string(),
|
||||||
|
"force-frame-pointers=no".to_string(), // 禁用帧指针
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let config = CompilerConfig {
|
let config = CompilerConfig {
|
||||||
rustflags,
|
rustflags,
|
||||||
env_vars: self.generate_env_vars(),
|
env_vars: self.generate_env_vars(),
|
||||||
cargo_config: self.generate_cargo_config(),
|
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)
|
Ok(config)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 生成环境变量配置
|
/// 生成环境变量配置
|
||||||
fn generate_env_vars(&self) -> HashMap<String, String> {
|
fn generate_env_vars(&self) -> HashMap<String, String> {
|
||||||
let mut env_vars = HashMap::new();
|
let mut env_vars = HashMap::new();
|
||||||
|
|
||||||
// CPU特定优化
|
// CPU特定优化
|
||||||
env_vars.insert("CARGO_CFG_TARGET_FEATURE".to_string(),
|
env_vars.insert(
|
||||||
self.optimization_flags.target_features.join(","));
|
"CARGO_CFG_TARGET_FEATURE".to_string(),
|
||||||
|
self.optimization_flags.target_features.join(","),
|
||||||
|
);
|
||||||
|
|
||||||
// 启用不稳定特性
|
// 启用不稳定特性
|
||||||
env_vars.insert("RUSTC_BOOTSTRAP".to_string(), "1".to_string());
|
env_vars.insert("RUSTC_BOOTSTRAP".to_string(), "1".to_string());
|
||||||
|
|
||||||
// 编译缓存设置
|
// 编译缓存设置
|
||||||
if self.optimization_flags.incremental {
|
if self.optimization_flags.incremental {
|
||||||
env_vars.insert("CARGO_INCREMENTAL".to_string(), "1".to_string());
|
env_vars.insert("CARGO_INCREMENTAL".to_string(), "1".to_string());
|
||||||
} else {
|
} else {
|
||||||
env_vars.insert("CARGO_INCREMENTAL".to_string(), "0".to_string());
|
env_vars.insert("CARGO_INCREMENTAL".to_string(), "0".to_string());
|
||||||
}
|
}
|
||||||
|
|
||||||
env_vars
|
env_vars
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 生成Cargo配置
|
/// 生成Cargo配置
|
||||||
fn generate_cargo_config(&self) -> CargoConfig {
|
fn generate_cargo_config(&self) -> CargoConfig {
|
||||||
CargoConfig {
|
CargoConfig {
|
||||||
@@ -244,17 +254,21 @@ impl CompilerOptimizer {
|
|||||||
debug_assertions: false,
|
debug_assertions: false,
|
||||||
rpath: false,
|
rpath: false,
|
||||||
strip: true, // 去除符号表
|
strip: true, // 去除符号表
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取统计信息
|
/// 获取统计信息
|
||||||
pub fn get_stats(&self) -> CompilerOptimizationStats {
|
pub fn get_stats(&self) -> CompilerOptimizationStats {
|
||||||
CompilerOptimizationStats {
|
CompilerOptimizationStats {
|
||||||
inlined_functions: AtomicU64::new(self.stats.inlined_functions.load(Ordering::Relaxed)),
|
inlined_functions: AtomicU64::new(self.stats.inlined_functions.load(Ordering::Relaxed)),
|
||||||
constant_folding: AtomicU64::new(self.stats.constant_folding.load(Ordering::Relaxed)),
|
constant_folding: AtomicU64::new(self.stats.constant_folding.load(Ordering::Relaxed)),
|
||||||
dead_code_elimination: AtomicU64::new(self.stats.dead_code_elimination.load(Ordering::Relaxed)),
|
dead_code_elimination: AtomicU64::new(
|
||||||
loop_optimizations: AtomicU64::new(self.stats.loop_optimizations.load(Ordering::Relaxed)),
|
self.stats.dead_code_elimination.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
loop_optimizations: AtomicU64::new(
|
||||||
|
self.stats.loop_optimizations.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,12 +293,12 @@ impl OptimizationFlags {
|
|||||||
Self {
|
Self {
|
||||||
opt_level: OptLevel::Aggressive,
|
opt_level: OptLevel::Aggressive,
|
||||||
enable_lto: true,
|
enable_lto: true,
|
||||||
enable_pgo: false, // PGO需要多阶段构建
|
enable_pgo: false, // PGO需要多阶段构建
|
||||||
target_cpu: "native".to_string(), // 使用本机CPU特性
|
target_cpu: "native".to_string(), // 使用本机CPU特性
|
||||||
target_features,
|
target_features,
|
||||||
code_model: CodeModel::Small,
|
code_model: CodeModel::Small,
|
||||||
debug_info: false,
|
debug_info: false,
|
||||||
incremental: false, // 发布版本禁用增量编译
|
incremental: false, // 发布版本禁用增量编译
|
||||||
codegen_units: Some(1), // 单个代码生成单元获得最佳优化
|
codegen_units: Some(1), // 单个代码生成单元获得最佳优化
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,7 +308,7 @@ impl CodegenConfig {
|
|||||||
/// 超高性能配置
|
/// 超高性能配置
|
||||||
pub fn ultra_performance() -> Self {
|
pub fn ultra_performance() -> Self {
|
||||||
Self {
|
Self {
|
||||||
panic_abort: true, // 恐慌即中止,避免展开开销
|
panic_abort: true, // 恐慌即中止,避免展开开销
|
||||||
overflow_checks: false, // 生产环境禁用溢出检查
|
overflow_checks: false, // 生产环境禁用溢出检查
|
||||||
fat_lto: true,
|
fat_lto: true,
|
||||||
enable_simd: true,
|
enable_simd: true,
|
||||||
@@ -353,14 +367,14 @@ macro_rules! compile_time_optimize {
|
|||||||
(const $expr:expr) => {
|
(const $expr:expr) => {
|
||||||
const { $expr }
|
const { $expr }
|
||||||
};
|
};
|
||||||
|
|
||||||
// 强制内联热路径
|
// 强制内联热路径
|
||||||
(inline_hot $fn_name:ident) => {
|
(inline_hot $fn_name:ident) => {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
#[hot]
|
#[hot]
|
||||||
$fn_name
|
$fn_name
|
||||||
};
|
};
|
||||||
|
|
||||||
// 标记冷路径
|
// 标记冷路径
|
||||||
(cold $fn_name:ident) => {
|
(cold $fn_name:ident) => {
|
||||||
#[inline(never)]
|
#[inline(never)]
|
||||||
@@ -372,10 +386,10 @@ macro_rules! compile_time_optimize {
|
|||||||
/// 🚀 零成本抽象特征
|
/// 🚀 零成本抽象特征
|
||||||
pub trait ZeroCostAbstraction {
|
pub trait ZeroCostAbstraction {
|
||||||
type Output;
|
type Output;
|
||||||
|
|
||||||
/// 编译时计算
|
/// 编译时计算
|
||||||
fn compute_at_compile_time(&self) -> Self::Output;
|
fn compute_at_compile_time(&self) -> Self::Output;
|
||||||
|
|
||||||
/// 内联操作
|
/// 内联操作
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn inline_operation(&self) -> Self::Output {
|
fn inline_operation(&self) -> Self::Output {
|
||||||
@@ -399,35 +413,35 @@ impl CompileTimeOptimizedEventProcessor {
|
|||||||
route_table: Self::precompute_route_table(),
|
route_table: Self::precompute_route_table(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 编译时预计算哈希表
|
/// 编译时预计算哈希表
|
||||||
const fn precompute_hash_table() -> [u64; 256] {
|
const fn precompute_hash_table() -> [u64; 256] {
|
||||||
let mut table = [0u64; 256];
|
let mut table = [0u64; 256];
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
|
|
||||||
while i < 256 {
|
while i < 256 {
|
||||||
// 使用编译时常量计算哈希值
|
// 使用编译时常量计算哈希值
|
||||||
table[i] = Self::const_hash(i as u8);
|
table[i] = Self::const_hash(i as u8);
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
table
|
table
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 编译时预计算路由表
|
/// 编译时预计算路由表
|
||||||
const fn precompute_route_table() -> [u32; 1024] {
|
const fn precompute_route_table() -> [u32; 1024] {
|
||||||
let mut table = [0u32; 1024];
|
let mut table = [0u32; 1024];
|
||||||
let mut i = 0;
|
let mut i = 0;
|
||||||
|
|
||||||
while i < 1024 {
|
while i < 1024 {
|
||||||
// 预计算路由信息
|
// 预计算路由信息
|
||||||
table[i] = (i as u32) % 16; // 16个工作线程
|
table[i] = (i as u32) % 16; // 16个工作线程
|
||||||
i += 1;
|
i += 1;
|
||||||
}
|
}
|
||||||
|
|
||||||
table
|
table
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 编译时常量哈希函数
|
/// 编译时常量哈希函数
|
||||||
const fn const_hash(input: u8) -> u64 {
|
const fn const_hash(input: u8) -> u64 {
|
||||||
// 使用简单的编译时常量哈希
|
// 使用简单的编译时常量哈希
|
||||||
@@ -437,16 +451,14 @@ impl CompileTimeOptimizedEventProcessor {
|
|||||||
hash ^= hash << 17;
|
hash ^= hash << 17;
|
||||||
hash
|
hash
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 零开销事件路由
|
/// 🚀 零开销事件路由
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn route_event_zero_cost(&self, event_id: u8) -> u32 {
|
pub fn route_event_zero_cost(&self, event_id: u8) -> u32 {
|
||||||
// 编译时优化:直接数组访问,无边界检查
|
// 编译时优化:直接数组访问,无边界检查
|
||||||
unsafe {
|
unsafe { *self.route_table.get_unchecked((event_id as usize) & 1023) }
|
||||||
*self.route_table.get_unchecked((event_id as usize) & 1023)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 编译时优化的哈希查找
|
/// 🚀 编译时优化的哈希查找
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn hash_lookup_optimized(&self, key: u8) -> u64 {
|
pub fn hash_lookup_optimized(&self, key: u8) -> u64 {
|
||||||
@@ -464,28 +476,28 @@ impl SIMDCompileTimeOptimizer {
|
|||||||
#[target_feature(enable = "avx2")]
|
#[target_feature(enable = "avx2")]
|
||||||
pub unsafe fn vectorized_sum_compile_time(data: &[u64]) -> u64 {
|
pub unsafe fn vectorized_sum_compile_time(data: &[u64]) -> u64 {
|
||||||
use std::arch::x86_64::*;
|
use std::arch::x86_64::*;
|
||||||
|
|
||||||
if data.len() < 4 {
|
if data.len() < 4 {
|
||||||
return data.iter().sum();
|
return data.iter().sum();
|
||||||
}
|
}
|
||||||
|
|
||||||
let chunks = data.len() / 4;
|
let chunks = data.len() / 4;
|
||||||
let mut sum_vec = _mm256_setzero_si256();
|
let mut sum_vec = _mm256_setzero_si256();
|
||||||
|
|
||||||
for i in 0..chunks {
|
for i in 0..chunks {
|
||||||
let ptr = data.as_ptr().add(i * 4) as *const __m256i;
|
let ptr = data.as_ptr().add(i * 4) as *const __m256i;
|
||||||
let vec = _mm256_loadu_si256(ptr);
|
let vec = _mm256_loadu_si256(ptr);
|
||||||
sum_vec = _mm256_add_epi64(sum_vec, vec);
|
sum_vec = _mm256_add_epi64(sum_vec, vec);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 水平求和
|
// 水平求和
|
||||||
let mut result = [0u64; 4];
|
let mut result = [0u64; 4];
|
||||||
_mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, sum_vec);
|
_mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, sum_vec);
|
||||||
let partial_sum: u64 = result.iter().sum();
|
let partial_sum: u64 = result.iter().sum();
|
||||||
|
|
||||||
// 处理剩余元素
|
// 处理剩余元素
|
||||||
let remaining: u64 = data[chunks * 4..].iter().sum();
|
let remaining: u64 = data[chunks * 4..].iter().sum();
|
||||||
|
|
||||||
partial_sum + remaining
|
partial_sum + remaining
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -523,7 +535,8 @@ fn main() {
|
|||||||
println!("cargo:rustc-link-arg=-fprofile-use");
|
println!("cargo:rustc-link-arg=-fprofile-use");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"#.to_string()
|
"#
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 生成.cargo/config.toml
|
/// 🚀 生成.cargo/config.toml
|
||||||
@@ -576,56 +589,58 @@ rustflags = [
|
|||||||
rustflags = [
|
rustflags = [
|
||||||
"-C", "target-feature=+sse4.2,+avx,+avx2,+fma,+bmi1,+bmi2,+lzcnt,+popcnt",
|
"-C", "target-feature=+sse4.2,+avx,+avx2,+fma,+bmi1,+bmi2,+lzcnt,+popcnt",
|
||||||
]
|
]
|
||||||
"#.to_string()
|
"#
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compiler_optimizer_creation() {
|
fn test_compiler_optimizer_creation() {
|
||||||
let optimizer = CompilerOptimizer::new();
|
let optimizer = CompilerOptimizer::new();
|
||||||
assert!(optimizer.optimization_flags.enable_lto);
|
assert!(optimizer.optimization_flags.enable_lto);
|
||||||
assert_eq!(optimizer.optimization_flags.opt_level as u8, OptLevel::Aggressive as u8);
|
assert_eq!(optimizer.optimization_flags.opt_level as u8, OptLevel::Aggressive as u8);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compile_time_processor() {
|
fn test_compile_time_processor() {
|
||||||
const PROCESSOR: CompileTimeOptimizedEventProcessor = CompileTimeOptimizedEventProcessor::new();
|
const PROCESSOR: CompileTimeOptimizedEventProcessor =
|
||||||
|
CompileTimeOptimizedEventProcessor::new();
|
||||||
|
|
||||||
let route = PROCESSOR.route_event_zero_cost(42);
|
let route = PROCESSOR.route_event_zero_cost(42);
|
||||||
assert!(route < 16); // 应该路由到16个工作线程之一
|
assert!(route < 16); // 应该路由到16个工作线程之一
|
||||||
|
|
||||||
let hash = PROCESSOR.hash_lookup_optimized(100);
|
let hash = PROCESSOR.hash_lookup_optimized(100);
|
||||||
assert!(hash > 0); // 哈希值应该非零
|
assert!(hash > 0); // 哈希值应该非零
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_ultra_performance_config() {
|
fn test_ultra_performance_config() {
|
||||||
let flags = OptimizationFlags::ultra_performance();
|
let flags = OptimizationFlags::ultra_performance();
|
||||||
assert!(flags.enable_lto);
|
assert!(flags.enable_lto);
|
||||||
assert_eq!(flags.target_cpu, "native");
|
assert_eq!(flags.target_cpu, "native");
|
||||||
assert!(!flags.target_features.is_empty());
|
assert!(!flags.target_features.is_empty());
|
||||||
|
|
||||||
let codegen = CodegenConfig::ultra_performance();
|
let codegen = CodegenConfig::ultra_performance();
|
||||||
assert!(codegen.panic_abort);
|
assert!(codegen.panic_abort);
|
||||||
assert!(!codegen.overflow_checks);
|
assert!(!codegen.overflow_checks);
|
||||||
assert!(codegen.enable_simd);
|
assert!(codegen.enable_simd);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compiler_config_generation() {
|
fn test_compiler_config_generation() {
|
||||||
let optimizer = CompilerOptimizer::new();
|
let optimizer = CompilerOptimizer::new();
|
||||||
let config = optimizer.generate_ultra_performance_config().unwrap();
|
let config = optimizer.generate_ultra_performance_config().unwrap();
|
||||||
|
|
||||||
assert!(!config.rustflags.is_empty());
|
assert!(!config.rustflags.is_empty());
|
||||||
assert!(config.rustflags.contains(&"-C".to_string()));
|
assert!(config.rustflags.contains(&"-C".to_string()));
|
||||||
assert!(config.rustflags.contains(&"opt-level=3".to_string()));
|
assert!(config.rustflags.contains(&"opt-level=3".to_string()));
|
||||||
|
|
||||||
assert!(config.env_vars.contains_key("CARGO_INCREMENTAL"));
|
assert!(config.env_vars.contains_key("CARGO_INCREMENTAL"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_simd_compile_time_optimization() {
|
fn test_simd_compile_time_optimization() {
|
||||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||||
@@ -642,7 +657,7 @@ mod tests {
|
|||||||
assert_eq!(sum, 36); // 1+2+3+4+5+6+7+8 = 36
|
assert_eq!(sum, 36); // 1+2+3+4+5+6+7+8 = 36
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_build_script_generation() {
|
fn test_build_script_generation() {
|
||||||
let build_script = generate_build_script();
|
let build_script = generate_build_script();
|
||||||
@@ -650,7 +665,7 @@ mod tests {
|
|||||||
assert!(build_script.contains("TARGET_FEATURE"));
|
assert!(build_script.contains("TARGET_FEATURE"));
|
||||||
assert!(build_script.contains("lld"));
|
assert!(build_script.contains("lld"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cargo_config_generation() {
|
fn test_cargo_config_generation() {
|
||||||
let config = generate_cargo_config_toml();
|
let config = generate_cargo_config_toml();
|
||||||
@@ -659,4 +674,4 @@ mod tests {
|
|||||||
assert!(config.contains("target-cpu=native"));
|
assert!(config.contains("target-cpu=native"));
|
||||||
assert!(config.contains("panic = \"abort\""));
|
assert!(config.contains("panic = \"abort\""));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+121
-171
@@ -1,38 +1,29 @@
|
|||||||
//! 🚀 硬件级性能优化 - CPU缓存行对齐 & SIMD加速
|
//! Hardware-oriented optimizations: cache-line alignment, prefetch, SIMD, branch hints, memory barriers.
|
||||||
//!
|
//! 硬件级优化:缓存行对齐与预取、SIMD、分支提示、内存屏障。
|
||||||
//! 实现CPU硬件特性的深度利用,包括:
|
|
||||||
//! - 缓存行对齐和缓存预取
|
|
||||||
//! - SIMD指令集优化
|
|
||||||
//! - 分支预测优化
|
|
||||||
//! - 内存屏障控制
|
|
||||||
//! - CPU指令流水线优化
|
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use anyhow::Result;
|
||||||
|
use crossbeam_utils::CachePadded;
|
||||||
use std::mem::size_of;
|
use std::mem::size_of;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use crossbeam_utils::CachePadded;
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use anyhow::Result;
|
|
||||||
|
|
||||||
// CPU缓存行大小常量 (通常为64字节)
|
/// Typical CPU cache line size in bytes. 典型 CPU 缓存行大小(字节)。
|
||||||
pub const CACHE_LINE_SIZE: usize = 64;
|
pub const CACHE_LINE_SIZE: usize = 64;
|
||||||
|
|
||||||
/// 🚀 硬件优化的数据结构基础特征
|
/// Trait for cache-line-aligned data and prefetch. 缓存行对齐与预取 trait。
|
||||||
pub trait CacheLineAligned {
|
pub trait CacheLineAligned {
|
||||||
/// 确保数据结构按缓存行对齐
|
|
||||||
fn ensure_cache_aligned(&self) -> bool;
|
fn ensure_cache_aligned(&self) -> bool;
|
||||||
/// 预取数据到CPU缓存
|
|
||||||
fn prefetch_data(&self);
|
fn prefetch_data(&self);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 SIMD优化的内存操作
|
/// SIMD-accelerated memory operations. SIMD 加速的内存操作。
|
||||||
pub struct SIMDMemoryOps;
|
pub struct SIMDMemoryOps;
|
||||||
|
|
||||||
impl SIMDMemoryOps {
|
impl SIMDMemoryOps {
|
||||||
/// 🚀 SIMD加速的内存拷贝 - 针对小数据包优化
|
/// SIMD-optimized copy by size class. 按长度分派的 SIMD 拷贝。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn memcpy_simd_optimized(dst: *mut u8, src: *const u8, len: usize) {
|
pub unsafe fn memcpy_simd_optimized(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
match len {
|
match len {
|
||||||
// 针对不同数据大小使用不同优化策略
|
|
||||||
0 => return,
|
0 => return,
|
||||||
1..=8 => Self::memcpy_small(dst, src, len),
|
1..=8 => Self::memcpy_small(dst, src, len),
|
||||||
9..=16 => Self::memcpy_sse(dst, src, len),
|
9..=16 => Self::memcpy_sse(dst, src, len),
|
||||||
@@ -41,8 +32,8 @@ impl SIMDMemoryOps {
|
|||||||
_ => Self::memcpy_avx512_or_fallback(dst, src, len),
|
_ => Self::memcpy_avx512_or_fallback(dst, src, len),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 小数据拷贝优化 (1-8字节)
|
/// Copy 1–8 bytes (scalar / small word). 小数据拷贝(1–8 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcpy_small(dst: *mut u8, src: *const u8, len: usize) {
|
unsafe fn memcpy_small(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
match len {
|
match len {
|
||||||
@@ -62,58 +53,55 @@ impl SIMDMemoryOps {
|
|||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SSE优化拷贝 (9-16字节)
|
/// Copy 9–16 bytes using SSE (128-bit). SSE 拷贝(9–16 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcpy_sse(dst: *mut u8, src: *const u8, len: usize) {
|
unsafe fn memcpy_sse(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_storeu_si128};
|
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_storeu_si128};
|
||||||
|
|
||||||
if len <= 16 {
|
if len <= 16 {
|
||||||
let chunk = _mm_loadu_si128(src as *const __m128i);
|
let chunk = _mm_loadu_si128(src as *const __m128i);
|
||||||
_mm_storeu_si128(dst as *mut __m128i, chunk);
|
_mm_storeu_si128(dst as *mut __m128i, chunk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
ptr::copy_nonoverlapping(src, dst, len);
|
ptr::copy_nonoverlapping(src, dst, len);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AVX优化拷贝 (17-32字节)
|
/// Copy 17–32 bytes using AVX (256-bit). AVX 拷贝(17–32 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcpy_avx(dst: *mut u8, src: *const u8, len: usize) {
|
unsafe fn memcpy_avx(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
||||||
|
|
||||||
if len <= 32 {
|
if len <= 32 {
|
||||||
let chunk = _mm256_loadu_si256(src as *const __m256i);
|
let chunk = _mm256_loadu_si256(src as *const __m256i);
|
||||||
_mm256_storeu_si256(dst as *mut __m256i, chunk);
|
_mm256_storeu_si256(dst as *mut __m256i, chunk);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
ptr::copy_nonoverlapping(src, dst, len);
|
ptr::copy_nonoverlapping(src, dst, len);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AVX2优化拷贝 (33-64字节)
|
/// Copy 33–64 bytes using AVX2 (256-bit, two chunks). AVX2 拷贝(33–64 字节,两段)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcpy_avx2(dst: *mut u8, src: *const u8, len: usize) {
|
unsafe fn memcpy_avx2(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
||||||
|
|
||||||
// 拷贝前32字节
|
|
||||||
let chunk1 = _mm256_loadu_si256(src as *const __m256i);
|
let chunk1 = _mm256_loadu_si256(src as *const __m256i);
|
||||||
_mm256_storeu_si256(dst as *mut __m256i, chunk1);
|
_mm256_storeu_si256(dst as *mut __m256i, chunk1);
|
||||||
|
|
||||||
if len > 32 {
|
if len > 32 {
|
||||||
// 拷贝剩余字节
|
|
||||||
let remaining = len - 32;
|
let remaining = len - 32;
|
||||||
if remaining <= 32 {
|
if remaining <= 32 {
|
||||||
let chunk2 = _mm256_loadu_si256(src.add(32) as *const __m256i);
|
let chunk2 = _mm256_loadu_si256(src.add(32) as *const __m256i);
|
||||||
@@ -121,56 +109,53 @@ impl SIMDMemoryOps {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
ptr::copy_nonoverlapping(src, dst, len);
|
ptr::copy_nonoverlapping(src, dst, len);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AVX512或回退拷贝 (>64字节)
|
/// Copy >64 bytes: AVX-512 64-byte chunks when available, else AVX2 32-byte chunks. >64 字节:有 AVX512 用 64 字节块,否则 AVX2 32 字节块。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcpy_avx512_or_fallback(dst: *mut u8, src: *const u8, len: usize) {
|
unsafe fn memcpy_avx512_or_fallback(dst: *mut u8, src: *const u8, len: usize) {
|
||||||
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
|
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m512i, _mm512_loadu_si512, _mm512_storeu_si512};
|
use std::arch::x86_64::{__m512i, _mm512_loadu_si512, _mm512_storeu_si512};
|
||||||
|
|
||||||
let chunks = len / 64;
|
let chunks = len / 64;
|
||||||
let mut offset = 0;
|
let mut offset = 0;
|
||||||
|
|
||||||
// 使用AVX512处理64字节块
|
|
||||||
for _ in 0..chunks {
|
for _ in 0..chunks {
|
||||||
let chunk = _mm512_loadu_si512(src.add(offset) as *const __m512i);
|
let chunk = _mm512_loadu_si512(src.add(offset) as *const __m512i);
|
||||||
_mm512_storeu_si512(dst.add(offset) as *mut __m512i, chunk);
|
_mm512_storeu_si512(dst.add(offset) as *mut __m512i, chunk);
|
||||||
offset += 64;
|
offset += 64;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理剩余字节
|
|
||||||
let remaining = len % 64;
|
let remaining = len % 64;
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
Self::memcpy_avx2(dst.add(offset), src.add(offset), remaining);
|
Self::memcpy_avx2(dst.add(offset), src.add(offset), remaining);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
|
#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
|
||||||
{
|
{
|
||||||
// 回退到AVX2分块处理
|
|
||||||
let chunks = len / 32;
|
let chunks = len / 32;
|
||||||
let mut offset = 0;
|
let mut offset = 0;
|
||||||
|
|
||||||
for _ in 0..chunks {
|
for _ in 0..chunks {
|
||||||
Self::memcpy_avx2(dst.add(offset), src.add(offset), 32);
|
Self::memcpy_avx2(dst.add(offset), src.add(offset), 32);
|
||||||
offset += 32;
|
offset += 32;
|
||||||
}
|
}
|
||||||
|
|
||||||
let remaining = len % 32;
|
let remaining = len % 32;
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
Self::memcpy_avx(dst.add(offset), src.add(offset), remaining);
|
Self::memcpy_avx(dst.add(offset), src.add(offset), remaining);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 SIMD加速的内存比较
|
/// SIMD-optimized byte equality; dispatches by length (small / SSE / AVX2 / large). SIMD 加速的内存比较,按长度分派。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn memcmp_simd_optimized(a: *const u8, b: *const u8, len: usize) -> bool {
|
pub unsafe fn memcmp_simd_optimized(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
match len {
|
match len {
|
||||||
@@ -181,111 +166,108 @@ impl SIMDMemoryOps {
|
|||||||
_ => Self::memcmp_large(a, b, len),
|
_ => Self::memcmp_large(a, b, len),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 小数据比较
|
/// Compare 1–8 bytes (scalar). 小数据比较(1–8 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcmp_small(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_small(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
match len {
|
match len {
|
||||||
1 => *a == *b,
|
1 => *a == *b,
|
||||||
2 => *(a as *const u16) == *(b as *const u16),
|
2 => *(a as *const u16) == *(b as *const u16),
|
||||||
3 => {
|
3 => *(a as *const u16) == *(b as *const u16) && *a.add(2) == *b.add(2),
|
||||||
*(a as *const u16) == *(b as *const u16) &&
|
|
||||||
*a.add(2) == *b.add(2)
|
|
||||||
}
|
|
||||||
4 => *(a as *const u32) == *(b as *const u32),
|
4 => *(a as *const u32) == *(b as *const u32),
|
||||||
5..=8 => *(a as *const u64) == *(b as *const u64),
|
5..=8 => *(a as *const u64) == *(b as *const u64),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// SSE比较
|
/// Compare 9–16 bytes using SSE. SSE 比较(9–16 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_cmpeq_epi8, _mm_movemask_epi8};
|
use std::arch::x86_64::{__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8};
|
||||||
|
|
||||||
let chunk_a = _mm_loadu_si128(a as *const __m128i);
|
let chunk_a = _mm_loadu_si128(a as *const __m128i);
|
||||||
let chunk_b = _mm_loadu_si128(b as *const __m128i);
|
let chunk_b = _mm_loadu_si128(b as *const __m128i);
|
||||||
let cmp_result = _mm_cmpeq_epi8(chunk_a, chunk_b);
|
let cmp_result = _mm_cmpeq_epi8(chunk_a, chunk_b);
|
||||||
let mask = _mm_movemask_epi8(cmp_result) as u32;
|
let mask = _mm_movemask_epi8(cmp_result) as u32;
|
||||||
|
|
||||||
// 检查前len字节是否相等
|
|
||||||
let valid_mask = if len >= 16 { 0xFFFF } else { (1u32 << len) - 1 };
|
let valid_mask = if len >= 16 { 0xFFFF } else { (1u32 << len) - 1 };
|
||||||
(mask & valid_mask) == valid_mask
|
(mask & valid_mask) == valid_mask
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
(0..len).all(|i| *a.add(i) == *b.add(i))
|
(0..len).all(|i| *a.add(i) == *b.add(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// AVX2比较
|
/// Compare 17–32 bytes using AVX2. AVX2 比较(17–32 字节)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_cmpeq_epi8, _mm256_movemask_epi8};
|
use std::arch::x86_64::{
|
||||||
|
__m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8,
|
||||||
|
};
|
||||||
|
|
||||||
let chunk_a = _mm256_loadu_si256(a as *const __m256i);
|
let chunk_a = _mm256_loadu_si256(a as *const __m256i);
|
||||||
let chunk_b = _mm256_loadu_si256(b as *const __m256i);
|
let chunk_b = _mm256_loadu_si256(b as *const __m256i);
|
||||||
let cmp_result = _mm256_cmpeq_epi8(chunk_a, chunk_b);
|
let cmp_result = _mm256_cmpeq_epi8(chunk_a, chunk_b);
|
||||||
let mask = _mm256_movemask_epi8(cmp_result) as u32;
|
let mask = _mm256_movemask_epi8(cmp_result) as u32;
|
||||||
|
|
||||||
let valid_mask = if len >= 32 { 0xFFFFFFFF } else { (1u32 << len) - 1 };
|
let valid_mask = if len >= 32 { 0xFFFFFFFF } else { (1u32 << len) - 1 };
|
||||||
(mask & valid_mask) == valid_mask
|
(mask & valid_mask) == valid_mask
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
(0..len).all(|i| *a.add(i) == *b.add(i))
|
(0..len).all(|i| *a.add(i) == *b.add(i))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 大数据比较
|
/// Compare >32 bytes in 32-byte AVX2 chunks. 大数据比较(32 字节 AVX2 分块)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
unsafe fn memcmp_large(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_large(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
let chunks = len / 32;
|
let chunks = len / 32;
|
||||||
|
|
||||||
for i in 0..chunks {
|
for i in 0..chunks {
|
||||||
let offset = i * 32;
|
let offset = i * 32;
|
||||||
if !Self::memcmp_avx2(a.add(offset), b.add(offset), 32) {
|
if !Self::memcmp_avx2(a.add(offset), b.add(offset), 32) {
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let remaining = len % 32;
|
let remaining = len % 32;
|
||||||
if remaining > 0 {
|
if remaining > 0 {
|
||||||
return Self::memcmp_avx2(a.add(chunks * 32), b.add(chunks * 32), remaining);
|
return Self::memcmp_avx2(a.add(chunks * 32), b.add(chunks * 32), remaining);
|
||||||
}
|
}
|
||||||
|
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 SIMD加速的内存清零
|
/// SIMD-optimized zero memory. SIMD 加速的内存清零。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn memzero_simd_optimized(ptr: *mut u8, len: usize) {
|
pub unsafe fn memzero_simd_optimized(ptr: *mut u8, len: usize) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m256i, _mm256_setzero_si256, _mm256_storeu_si256};
|
use std::arch::x86_64::{__m256i, _mm256_setzero_si256, _mm256_storeu_si256};
|
||||||
|
|
||||||
let zero = _mm256_setzero_si256();
|
let zero = _mm256_setzero_si256();
|
||||||
let chunks = len / 32;
|
let chunks = len / 32;
|
||||||
let mut offset = 0;
|
let mut offset = 0;
|
||||||
|
|
||||||
for _ in 0..chunks {
|
for _ in 0..chunks {
|
||||||
_mm256_storeu_si256(ptr.add(offset) as *mut __m256i, zero);
|
_mm256_storeu_si256(ptr.add(offset) as *mut __m256i, zero);
|
||||||
offset += 32;
|
offset += 32;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 处理剩余字节
|
|
||||||
let remaining = len % 32;
|
let remaining = len % 32;
|
||||||
for i in 0..remaining {
|
for i in 0..remaining {
|
||||||
*ptr.add(offset + i) = 0;
|
*ptr.add(offset + i) = 0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(target_arch = "x86_64"))]
|
#[cfg(not(target_arch = "x86_64"))]
|
||||||
{
|
{
|
||||||
ptr::write_bytes(ptr, 0, len);
|
ptr::write_bytes(ptr, 0, len);
|
||||||
@@ -293,31 +275,32 @@ impl SIMDMemoryOps {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 缓存行对齐的原子计数器
|
/// Cache-line-aligned atomic counter. 缓存行对齐的原子计数器。
|
||||||
#[repr(align(64))] // 强制64字节对齐
|
#[repr(align(64))]
|
||||||
pub struct CacheAlignedCounter {
|
pub struct CacheAlignedCounter {
|
||||||
value: AtomicU64,
|
value: AtomicU64,
|
||||||
_padding: [u8; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
|
_padding: [u8; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
|
||||||
}
|
}
|
||||||
|
|
||||||
impl CacheAlignedCounter {
|
impl CacheAlignedCounter {
|
||||||
|
/// Create counter with initial value. 创建并设置初值。
|
||||||
pub fn new(initial: u64) -> Self {
|
pub fn new(initial: u64) -> Self {
|
||||||
Self {
|
Self {
|
||||||
value: AtomicU64::new(initial),
|
value: AtomicU64::new(initial),
|
||||||
_padding: [0; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
|
_padding: [0; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn increment(&self) -> u64 {
|
pub fn increment(&self) -> u64 {
|
||||||
self.value.fetch_add(1, Ordering::Relaxed)
|
self.value.fetch_add(1, Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn load(&self) -> u64 {
|
pub fn load(&self) -> u64 {
|
||||||
self.value.load(Ordering::Relaxed)
|
self.value.load(Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn store(&self, val: u64) {
|
pub fn store(&self, val: u64) {
|
||||||
self.value.store(val, Ordering::Relaxed)
|
self.value.store(val, Ordering::Relaxed)
|
||||||
@@ -328,7 +311,7 @@ impl CacheLineAligned for CacheAlignedCounter {
|
|||||||
fn ensure_cache_aligned(&self) -> bool {
|
fn ensure_cache_aligned(&self) -> bool {
|
||||||
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prefetch_data(&self) {
|
fn prefetch_data(&self) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
unsafe {
|
unsafe {
|
||||||
@@ -339,31 +322,26 @@ impl CacheLineAligned for CacheAlignedCounter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 缓存友好的环形缓冲区
|
/// Cache-friendly lock-free ring buffer. 缓存友好的无锁环形缓冲区。
|
||||||
#[repr(align(64))]
|
#[repr(align(64))]
|
||||||
pub struct CacheOptimizedRingBuffer<T> {
|
pub struct CacheOptimizedRingBuffer<T> {
|
||||||
/// 数据缓冲区
|
|
||||||
buffer: Vec<T>,
|
buffer: Vec<T>,
|
||||||
/// 生产者头指针 (独占缓存行)
|
|
||||||
producer_head: CachePadded<AtomicU64>,
|
producer_head: CachePadded<AtomicU64>,
|
||||||
/// 消费者尾指针 (独占缓存行)
|
|
||||||
consumer_tail: CachePadded<AtomicU64>,
|
consumer_tail: CachePadded<AtomicU64>,
|
||||||
/// 容量 (2的幂次方)
|
|
||||||
capacity: usize,
|
capacity: usize,
|
||||||
/// 掩码 (capacity - 1)
|
|
||||||
mask: usize,
|
mask: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||||
/// 创建缓存优化的环形缓冲区
|
/// Create ring buffer; capacity must be a power of 2. 创建环形缓冲区,容量须为 2 的幂。
|
||||||
pub fn new(capacity: usize) -> Result<Self> {
|
pub fn new(capacity: usize) -> Result<Self> {
|
||||||
if !capacity.is_power_of_two() {
|
if !capacity.is_power_of_two() {
|
||||||
return Err(anyhow::anyhow!("Capacity must be a power of 2"));
|
return Err(anyhow::anyhow!("Capacity must be a power of 2"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let mut buffer = Vec::with_capacity(capacity);
|
let mut buffer = Vec::with_capacity(capacity);
|
||||||
buffer.resize_with(capacity, Default::default);
|
buffer.resize_with(capacity, Default::default);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
buffer,
|
buffer,
|
||||||
producer_head: CachePadded::new(AtomicU64::new(0)),
|
producer_head: CachePadded::new(AtomicU64::new(0)),
|
||||||
@@ -372,66 +350,53 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
|||||||
mask: capacity - 1,
|
mask: capacity - 1,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 无锁写入元素
|
/// Lock-free push; returns false if full. 无锁写入,满则返回 false。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn try_push(&self, item: T) -> bool {
|
pub fn try_push(&self, item: T) -> bool {
|
||||||
let current_head = self.producer_head.load(Ordering::Relaxed);
|
let current_head = self.producer_head.load(Ordering::Relaxed);
|
||||||
let current_tail = self.consumer_tail.load(Ordering::Acquire);
|
let current_tail = self.consumer_tail.load(Ordering::Acquire);
|
||||||
|
|
||||||
// 检查是否还有空间
|
|
||||||
if (current_head + 1) & self.mask as u64 == current_tail & self.mask as u64 {
|
if (current_head + 1) & self.mask as u64 == current_tail & self.mask as u64 {
|
||||||
return false; // 缓冲区满
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 写入数据
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let index = current_head & self.mask as u64;
|
let index = current_head & self.mask as u64;
|
||||||
let ptr = self.buffer.as_ptr().add(index as usize) as *mut T;
|
let ptr = self.buffer.as_ptr().add(index as usize) as *mut T;
|
||||||
ptr.write(item);
|
ptr.write(item);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 发布新的头指针
|
|
||||||
self.producer_head.store(current_head + 1, Ordering::Release);
|
self.producer_head.store(current_head + 1, Ordering::Release);
|
||||||
true
|
true
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 无锁读取元素
|
/// Lock-free pop; returns None if empty. 无锁读取,空则返回 None。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn try_pop(&self) -> Option<T> {
|
pub fn try_pop(&self) -> Option<T> {
|
||||||
let current_tail = self.consumer_tail.load(Ordering::Relaxed);
|
let current_tail = self.consumer_tail.load(Ordering::Relaxed);
|
||||||
let current_head = self.producer_head.load(Ordering::Acquire);
|
let current_head = self.producer_head.load(Ordering::Acquire);
|
||||||
|
|
||||||
// 检查是否有数据
|
|
||||||
if current_tail == current_head {
|
if current_tail == current_head {
|
||||||
return None; // 缓冲区空
|
return None;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 读取数据
|
|
||||||
let item = unsafe {
|
let item = unsafe {
|
||||||
let index = current_tail & self.mask as u64;
|
let index = current_tail & self.mask as u64;
|
||||||
let ptr = self.buffer.as_ptr().add(index as usize);
|
let ptr = self.buffer.as_ptr().add(index as usize);
|
||||||
ptr.read()
|
ptr.read()
|
||||||
};
|
};
|
||||||
|
|
||||||
// 发布新的尾指针
|
|
||||||
self.consumer_tail.store(current_tail + 1, Ordering::Release);
|
self.consumer_tail.store(current_tail + 1, Ordering::Release);
|
||||||
Some(item)
|
Some(item)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取当前元素数量
|
/// Current number of elements. 当前元素个数。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn len(&self) -> usize {
|
pub fn len(&self) -> usize {
|
||||||
let head = self.producer_head.load(Ordering::Relaxed);
|
let head = self.producer_head.load(Ordering::Relaxed);
|
||||||
let tail = self.consumer_tail.load(Ordering::Relaxed);
|
let tail = self.consumer_tail.load(Ordering::Relaxed);
|
||||||
((head + self.capacity as u64 - tail) & self.mask as u64) as usize
|
((head + self.capacity as u64 - tail) & self.mask as u64) as usize
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 检查是否为空
|
/// True if no elements. 是否为空。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.producer_head.load(Ordering::Relaxed) ==
|
self.producer_head.load(Ordering::Relaxed) == self.consumer_tail.load(Ordering::Relaxed)
|
||||||
self.consumer_tail.load(Ordering::Relaxed)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -439,54 +404,48 @@ impl<T> CacheLineAligned for CacheOptimizedRingBuffer<T> {
|
|||||||
fn ensure_cache_aligned(&self) -> bool {
|
fn ensure_cache_aligned(&self) -> bool {
|
||||||
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
||||||
}
|
}
|
||||||
|
|
||||||
fn prefetch_data(&self) {
|
fn prefetch_data(&self) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
unsafe {
|
unsafe {
|
||||||
use std::arch::x86_64::_mm_prefetch;
|
use std::arch::x86_64::_mm_prefetch;
|
||||||
use std::arch::x86_64::_MM_HINT_T0;
|
use std::arch::x86_64::_MM_HINT_T0;
|
||||||
|
|
||||||
// 预取头指针
|
|
||||||
_mm_prefetch(self.producer_head.as_ptr() as *const i8, _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.consumer_tail.as_ptr() as *const i8, _MM_HINT_T0);
|
||||||
|
|
||||||
// 预取缓冲区开始位置
|
|
||||||
_mm_prefetch(self.buffer.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;
|
pub struct BranchOptimizer;
|
||||||
|
|
||||||
impl BranchOptimizer {
|
impl BranchOptimizer {
|
||||||
/// likely宏 - 告诉编译器条件大概率为真
|
/// Hint: condition is usually true. 提示编译器条件大概率为真。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn likely(condition: bool) -> bool {
|
pub fn likely(condition: bool) -> bool {
|
||||||
#[cold]
|
#[cold]
|
||||||
fn cold() {}
|
fn cold() {}
|
||||||
|
|
||||||
if !condition {
|
if !condition {
|
||||||
cold();
|
cold();
|
||||||
}
|
}
|
||||||
condition
|
condition
|
||||||
}
|
}
|
||||||
|
|
||||||
/// unlikely宏 - 告诉编译器条件大概率为假
|
/// Hint: condition is usually false. 提示编译器条件大概率为假。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn unlikely(condition: bool) -> bool {
|
pub fn unlikely(condition: bool) -> bool {
|
||||||
#[cold]
|
#[cold]
|
||||||
fn cold() {}
|
fn cold() {}
|
||||||
|
|
||||||
if condition {
|
if condition {
|
||||||
cold();
|
cold();
|
||||||
}
|
}
|
||||||
condition
|
condition
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 预取指令 - 提前加载数据到缓存
|
/// Prefetch: load cache line at ptr into L1. Caller must ensure ptr is valid, read-only, no concurrent write. 预取:将 ptr 所在缓存行加载到 L1;调用方需保证有效、只读、无并发写。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn prefetch_read_data<T>(ptr: *const T) {
|
pub unsafe fn prefetch_read_data<T>(ptr: *const T) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
@@ -496,8 +455,8 @@ impl BranchOptimizer {
|
|||||||
_mm_prefetch(ptr as *const i8, _MM_HINT_T0);
|
_mm_prefetch(ptr as *const i8, _MM_HINT_T0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 预取指令 - 提前加载数据到缓存(写优化)
|
/// Prefetch for write (T1 hint). 写预取(T1 提示)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn prefetch_write_data<T>(ptr: *const T) {
|
pub unsafe fn prefetch_write_data<T>(ptr: *const T) {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
@@ -509,35 +468,35 @@ impl BranchOptimizer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 内存屏障控制
|
/// Memory barrier helpers. 内存屏障辅助。
|
||||||
pub struct MemoryBarriers;
|
pub struct MemoryBarriers;
|
||||||
|
|
||||||
impl MemoryBarriers {
|
impl MemoryBarriers {
|
||||||
/// 编译器屏障 - 防止编译器重排序
|
/// Compiler barrier only (no CPU reorder). 仅编译器屏障,防止重排序。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn compiler_barrier() {
|
pub fn compiler_barrier() {
|
||||||
std::sync::atomic::compiler_fence(Ordering::SeqCst);
|
std::sync::atomic::compiler_fence(Ordering::SeqCst);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 轻量级内存屏障 - 仅CPU重排序保护
|
/// Light barrier (Acquire). 轻量级屏障(Acquire)。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn memory_barrier_light() {
|
pub fn memory_barrier_light() {
|
||||||
std::sync::atomic::fence(Ordering::Acquire);
|
std::sync::atomic::fence(Ordering::Acquire);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 重量级内存屏障 - 全序一致性
|
/// Full sequential consistency barrier. 全序一致性屏障。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn memory_barrier_heavy() {
|
pub fn memory_barrier_heavy() {
|
||||||
std::sync::atomic::fence(Ordering::SeqCst);
|
std::sync::atomic::fence(Ordering::SeqCst);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 存储屏障 - 确保写入可见性
|
/// Store/release barrier. 存储屏障,保证写入可见性。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn store_barrier() {
|
pub fn store_barrier() {
|
||||||
std::sync::atomic::fence(Ordering::Release);
|
std::sync::atomic::fence(Ordering::Release);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 加载屏障 - 确保读取正确性
|
/// Load/acquire barrier. 加载屏障,保证读取顺序。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn load_barrier() {
|
pub fn load_barrier() {
|
||||||
std::sync::atomic::fence(Ordering::Acquire);
|
std::sync::atomic::fence(Ordering::Acquire);
|
||||||
@@ -547,63 +506,54 @@ impl MemoryBarriers {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cache_aligned_counter() {
|
fn test_cache_aligned_counter() {
|
||||||
let counter = CacheAlignedCounter::new(0);
|
let counter = CacheAlignedCounter::new(0);
|
||||||
assert!(counter.ensure_cache_aligned());
|
assert!(counter.ensure_cache_aligned());
|
||||||
|
|
||||||
assert_eq!(counter.load(), 0);
|
assert_eq!(counter.load(), 0);
|
||||||
counter.increment();
|
counter.increment();
|
||||||
assert_eq!(counter.load(), 1);
|
assert_eq!(counter.load(), 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_simd_memcpy() {
|
fn test_simd_memcpy() {
|
||||||
let src = [1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
let src = [1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||||
let mut dst = [0u8; 10];
|
let mut dst = [0u8; 10];
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
SIMDMemoryOps::memcpy_simd_optimized(
|
SIMDMemoryOps::memcpy_simd_optimized(dst.as_mut_ptr(), src.as_ptr(), src.len());
|
||||||
dst.as_mut_ptr(),
|
|
||||||
src.as_ptr(),
|
|
||||||
src.len()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
assert_eq!(src, dst);
|
assert_eq!(src, dst);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cache_optimized_ring_buffer() {
|
fn test_cache_optimized_ring_buffer() {
|
||||||
let buffer: CacheOptimizedRingBuffer<u64> =
|
let buffer: CacheOptimizedRingBuffer<u64> = CacheOptimizedRingBuffer::new(16).unwrap();
|
||||||
CacheOptimizedRingBuffer::new(16).unwrap();
|
|
||||||
|
|
||||||
assert!(buffer.is_empty());
|
assert!(buffer.is_empty());
|
||||||
|
|
||||||
// 测试推入
|
// 测试推入
|
||||||
assert!(buffer.try_push(42));
|
assert!(buffer.try_push(42));
|
||||||
assert_eq!(buffer.len(), 1);
|
assert_eq!(buffer.len(), 1);
|
||||||
|
|
||||||
// 测试弹出
|
// 测试弹出
|
||||||
assert_eq!(buffer.try_pop(), Some(42));
|
assert_eq!(buffer.try_pop(), Some(42));
|
||||||
assert!(buffer.is_empty());
|
assert!(buffer.is_empty());
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_simd_memcmp() {
|
fn test_simd_memcmp() {
|
||||||
let a = [1u8, 2, 3, 4, 5];
|
let a = [1u8, 2, 3, 4, 5];
|
||||||
let b = [1u8, 2, 3, 4, 5];
|
let b = [1u8, 2, 3, 4, 5];
|
||||||
let c = [1u8, 2, 3, 4, 6];
|
let c = [1u8, 2, 3, 4, 6];
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
assert!(SIMDMemoryOps::memcmp_simd_optimized(
|
assert!(SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), b.as_ptr(), a.len()));
|
||||||
a.as_ptr(), b.as_ptr(), a.len()
|
|
||||||
));
|
assert!(!SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), c.as_ptr(), a.len()));
|
||||||
|
|
||||||
assert!(!SIMDMemoryOps::memcmp_simd_optimized(
|
|
||||||
a.as_ptr(), c.as_ptr(), a.len()
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+10
-16
@@ -1,20 +1,14 @@
|
|||||||
//! 🚀 性能优化模块
|
//! Performance: SIMD, cache prefetch, branch hints, zero-copy I/O, syscall bypass, compiler hints.
|
||||||
//!
|
//! 性能优化:SIMD、缓存预取、分支提示、零拷贝 I/O、系统调用绕过、编译器提示。
|
||||||
//! 提供多层次性能优化:
|
|
||||||
//! - SIMD 向量化:AVX2 内存操作、批量计算
|
|
||||||
//! - 硬件级优化:分支预测、缓存预取
|
|
||||||
//! - 零拷贝 I/O:内存映射、DMA传输
|
|
||||||
//! - 系统调用绕过:批处理、快速时间
|
|
||||||
//! - 编译器优化:内联、向量化
|
|
||||||
|
|
||||||
pub mod simd;
|
|
||||||
pub mod hardware_optimizations;
|
|
||||||
pub mod zero_copy_io;
|
|
||||||
pub mod syscall_bypass;
|
|
||||||
pub mod compiler_optimization;
|
pub mod compiler_optimization;
|
||||||
|
pub mod hardware_optimizations;
|
||||||
|
pub mod simd;
|
||||||
|
pub mod syscall_bypass;
|
||||||
|
pub mod zero_copy_io;
|
||||||
|
|
||||||
pub use simd::*;
|
|
||||||
pub use hardware_optimizations::*;
|
|
||||||
pub use zero_copy_io::*;
|
|
||||||
pub use syscall_bypass::*;
|
|
||||||
pub use compiler_optimization::*;
|
pub use compiler_optimization::*;
|
||||||
|
pub use hardware_optimizations::*;
|
||||||
|
pub use simd::*;
|
||||||
|
pub use syscall_bypass::*;
|
||||||
|
pub use zero_copy_io::*;
|
||||||
|
|||||||
+1
-1
@@ -235,7 +235,7 @@ impl SIMDHash {
|
|||||||
/// 批量计算 SHA256 哈希
|
/// 批量计算 SHA256 哈希
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn hash_batch_sha256(data: &[&[u8]]) -> Vec<[u8; 32]> {
|
pub fn hash_batch_sha256(data: &[&[u8]]) -> Vec<[u8; 32]> {
|
||||||
use sha2::{Sha256, Digest};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
data.iter()
|
data.iter()
|
||||||
.map(|item| {
|
.map(|item| {
|
||||||
|
|||||||
+181
-213
@@ -1,55 +1,34 @@
|
|||||||
//! 🚀 系统调用绕过机制 - 最小化系统调用开销
|
//! Syscall bypass: batching, vDSO fast time, io_uring, mmap, userspace impl.
|
||||||
//!
|
//! 系统调用绕过:批处理、vDSO 快速时间、io_uring、mmap、用户态实现。
|
||||||
//! 实现系统调用级别的极致优化,包括:
|
|
||||||
//! - 系统调用批处理
|
|
||||||
//! - vDSO快速系统调用
|
|
||||||
//! - io_uring异步I/O优化
|
|
||||||
//! - 内存映射系统调用
|
|
||||||
//! - 用户空间系统调用实现
|
|
||||||
//! - 系统调用拦截与优化
|
|
||||||
//! - 直接硬件访问
|
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH, Duration, Instant};
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use std::fs::OpenOptions;
|
use std::fs::OpenOptions;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crossbeam_utils::CachePadded;
|
use crossbeam_utils::CachePadded;
|
||||||
|
|
||||||
/// 🚀 系统调用绕过管理器
|
/// Syscall bypass manager (batch, fast time, I/O). 系统调用绕过管理器。
|
||||||
pub struct SystemCallBypassManager {
|
pub struct SystemCallBypassManager {
|
||||||
/// 绕过配置
|
|
||||||
config: SyscallBypassConfig,
|
config: SyscallBypassConfig,
|
||||||
/// 批处理器
|
|
||||||
batch_processor: Arc<SyscallBatchProcessor>,
|
batch_processor: Arc<SyscallBatchProcessor>,
|
||||||
/// 快速时间获取器
|
|
||||||
fast_time_provider: Arc<FastTimeProvider>,
|
fast_time_provider: Arc<FastTimeProvider>,
|
||||||
/// I/O优化器
|
|
||||||
_io_optimizer: Arc<IOOptimizer>,
|
_io_optimizer: Arc<IOOptimizer>,
|
||||||
/// 统计信息
|
|
||||||
stats: Arc<SyscallBypassStats>,
|
stats: Arc<SyscallBypassStats>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 系统调用绕过配置
|
/// Syscall bypass configuration. 系统调用绕过配置。
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct SyscallBypassConfig {
|
pub struct SyscallBypassConfig {
|
||||||
/// 启用系统调用批处理
|
|
||||||
pub enable_batch_processing: bool,
|
pub enable_batch_processing: bool,
|
||||||
/// 批处理大小
|
|
||||||
pub batch_size: usize,
|
pub batch_size: usize,
|
||||||
/// 启用快速时间获取
|
|
||||||
pub enable_fast_time: bool,
|
pub enable_fast_time: bool,
|
||||||
/// 启用vDSO优化
|
|
||||||
pub enable_vdso: bool,
|
pub enable_vdso: bool,
|
||||||
/// 启用io_uring
|
|
||||||
pub enable_io_uring: bool,
|
pub enable_io_uring: bool,
|
||||||
/// 启用内存映射优化
|
|
||||||
pub enable_mmap_optimization: bool,
|
pub enable_mmap_optimization: bool,
|
||||||
/// 启用用户空间实现
|
|
||||||
pub enable_userspace_impl: bool,
|
pub enable_userspace_impl: bool,
|
||||||
/// 系统调用缓存大小
|
|
||||||
pub syscall_cache_size: usize,
|
pub syscall_cache_size: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -68,33 +47,38 @@ impl Default for SyscallBypassConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 系统调用批处理器
|
|
||||||
pub struct SyscallBatchProcessor {
|
pub struct SyscallBatchProcessor {
|
||||||
/// 待处理的系统调用队列
|
|
||||||
pending_calls: crossbeam_queue::ArrayQueue<SyscallRequest>,
|
pending_calls: crossbeam_queue::ArrayQueue<SyscallRequest>,
|
||||||
/// 批处理线程池
|
|
||||||
_executor: tokio::runtime::Handle,
|
_executor: tokio::runtime::Handle,
|
||||||
/// 批处理统计
|
|
||||||
batch_stats: CachePadded<AtomicU64>,
|
batch_stats: CachePadded<AtomicU64>,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 系统调用请求
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum SyscallRequest {
|
pub enum SyscallRequest {
|
||||||
/// 文件写入
|
Write {
|
||||||
Write { fd: i32, data: Vec<u8> },
|
fd: i32,
|
||||||
/// 文件读取
|
data: Vec<u8>,
|
||||||
Read { fd: i32, size: usize },
|
},
|
||||||
/// 网络发送
|
Read {
|
||||||
Send { socket: i32, data: Vec<u8> },
|
fd: i32,
|
||||||
/// 网络接收
|
size: usize,
|
||||||
Recv { socket: i32, size: usize },
|
},
|
||||||
/// 时间获取
|
Send {
|
||||||
|
socket: i32,
|
||||||
|
data: Vec<u8>,
|
||||||
|
},
|
||||||
|
Recv {
|
||||||
|
socket: i32,
|
||||||
|
size: usize,
|
||||||
|
},
|
||||||
GetTime,
|
GetTime,
|
||||||
/// 内存分配
|
MemAlloc {
|
||||||
MemAlloc { size: usize },
|
size: usize,
|
||||||
|
},
|
||||||
/// 内存释放
|
/// 内存释放
|
||||||
MemFree { ptr: usize },
|
MemFree {
|
||||||
|
ptr: usize,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速时间提供器 - 绕过系统调用获取时间
|
/// 🚀 快速时间提供器 - 绕过系统调用获取时间
|
||||||
@@ -118,24 +102,22 @@ impl FastTimeProvider {
|
|||||||
pub fn new(enable_vdso: bool) -> Result<Self> {
|
pub fn new(enable_vdso: bool) -> Result<Self> {
|
||||||
let now = SystemTime::now();
|
let now = SystemTime::now();
|
||||||
let instant_now = Instant::now();
|
let instant_now = Instant::now();
|
||||||
|
|
||||||
let provider = Self {
|
let provider = Self {
|
||||||
_base_time: now,
|
_base_time: now,
|
||||||
monotonic_start: instant_now,
|
monotonic_start: instant_now,
|
||||||
time_cache: CachePadded::new(AtomicU64::new(
|
time_cache: CachePadded::new(AtomicU64::new(
|
||||||
now.duration_since(UNIX_EPOCH)?.as_nanos() as u64
|
now.duration_since(UNIX_EPOCH)?.as_nanos() as u64,
|
||||||
)),
|
)),
|
||||||
cache_update_interval_ns: 1_000_000, // 1ms
|
cache_update_interval_ns: 1_000_000, // 1ms
|
||||||
last_update: CachePadded::new(AtomicU64::new(
|
last_update: CachePadded::new(AtomicU64::new(instant_now.elapsed().as_nanos() as u64)),
|
||||||
instant_now.elapsed().as_nanos() as u64
|
|
||||||
)),
|
|
||||||
vdso_enabled: enable_vdso,
|
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)
|
Ok(provider)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 超快速获取当前时间 - 绕过系统调用
|
/// 🚀 超快速获取当前时间 - 绕过系统调用
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn fast_now_nanos(&self) -> u64 {
|
pub fn fast_now_nanos(&self) -> u64 {
|
||||||
@@ -143,19 +125,19 @@ impl FastTimeProvider {
|
|||||||
// 使用vDSO快速获取时间
|
// 使用vDSO快速获取时间
|
||||||
return self.vdso_time_nanos();
|
return self.vdso_time_nanos();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用缓存的时间
|
// 使用缓存的时间
|
||||||
let now_mono = self.monotonic_start.elapsed().as_nanos() as u64;
|
let now_mono = self.monotonic_start.elapsed().as_nanos() as u64;
|
||||||
let last_update = self.last_update.load(Ordering::Relaxed);
|
let last_update = self.last_update.load(Ordering::Relaxed);
|
||||||
|
|
||||||
if now_mono.saturating_sub(last_update) > self.cache_update_interval_ns {
|
if now_mono.saturating_sub(last_update) > self.cache_update_interval_ns {
|
||||||
// 需要更新缓存
|
// 需要更新缓存
|
||||||
self.update_time_cache();
|
self.update_time_cache();
|
||||||
}
|
}
|
||||||
|
|
||||||
self.time_cache.load(Ordering::Relaxed)
|
self.time_cache.load(Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// vDSO时间获取
|
/// vDSO时间获取
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
fn vdso_time_nanos(&self) -> u64 {
|
fn vdso_time_nanos(&self) -> u64 {
|
||||||
@@ -164,36 +146,34 @@ impl FastTimeProvider {
|
|||||||
// 在Linux上使用vDSO获取时间,避免系统调用
|
// 在Linux上使用vDSO获取时间,避免系统调用
|
||||||
unsafe {
|
unsafe {
|
||||||
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
|
let mut ts = libc::timespec { tv_sec: 0, tv_nsec: 0 };
|
||||||
|
|
||||||
// CLOCK_MONOTONIC_RAW不受NTP调整影响,更适合性能测量
|
// CLOCK_MONOTONIC_RAW不受NTP调整影响,更适合性能测量
|
||||||
if libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut ts) == 0 {
|
if libc::clock_gettime(libc::CLOCK_MONOTONIC_RAW, &mut ts) == 0 {
|
||||||
return (ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64);
|
return (ts.tv_sec as u64) * 1_000_000_000 + (ts.tv_nsec as u64);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 回退到缓存时间
|
// 回退到缓存时间
|
||||||
self.time_cache.load(Ordering::Relaxed)
|
self.time_cache.load(Ordering::Relaxed)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 更新时间缓存
|
/// 更新时间缓存
|
||||||
fn update_time_cache(&self) {
|
fn update_time_cache(&self) {
|
||||||
if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) {
|
if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||||
let nanos = now.as_nanos() as u64;
|
let nanos = now.as_nanos() as u64;
|
||||||
self.time_cache.store(nanos, Ordering::Relaxed);
|
self.time_cache.store(nanos, Ordering::Relaxed);
|
||||||
self.last_update.store(
|
self.last_update
|
||||||
self.monotonic_start.elapsed().as_nanos() as u64,
|
.store(self.monotonic_start.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||||
Ordering::Relaxed
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速获取微秒时间戳
|
/// 🚀 快速获取微秒时间戳
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn fast_now_micros(&self) -> u64 {
|
pub fn fast_now_micros(&self) -> u64 {
|
||||||
self.fast_now_nanos() / 1000
|
self.fast_now_nanos() / 1000
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速获取毫秒时间戳
|
/// 🚀 快速获取毫秒时间戳
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn fast_now_millis(&self) -> u64 {
|
pub fn fast_now_millis(&self) -> u64 {
|
||||||
@@ -232,16 +212,16 @@ impl IOOptimizer {
|
|||||||
/// 创建I/O优化器
|
/// 创建I/O优化器
|
||||||
pub fn new(_config: &SyscallBypassConfig) -> Result<Self> {
|
pub fn new(_config: &SyscallBypassConfig) -> Result<Self> {
|
||||||
let io_uring_available = Self::check_io_uring_support();
|
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 {
|
Ok(Self {
|
||||||
io_uring_available,
|
io_uring_available,
|
||||||
async_io_stats: Arc::new(AsyncIOStats::default()),
|
async_io_stats: Arc::new(AsyncIOStats::default()),
|
||||||
mmap_regions: Vec::new(),
|
mmap_regions: Vec::new(),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 检查io_uring支持
|
/// 检查io_uring支持
|
||||||
fn check_io_uring_support() -> bool {
|
fn check_io_uring_support() -> bool {
|
||||||
#[cfg(target_os = "linux")]
|
#[cfg(target_os = "linux")]
|
||||||
@@ -249,8 +229,8 @@ impl IOOptimizer {
|
|||||||
// 检查内核版本和io_uring支持
|
// 检查内核版本和io_uring支持
|
||||||
if let Ok(uname) = std::process::Command::new("uname").arg("-r").output() {
|
if let Ok(uname) = std::process::Command::new("uname").arg("-r").output() {
|
||||||
let kernel_version = String::from_utf8_lossy(&uname.stdout);
|
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
|
// 简单检查:内核版本 >= 5.1 支持io_uring
|
||||||
if let Some(version_str) = kernel_version.split('.').next() {
|
if let Some(version_str) = kernel_version.split('.').next() {
|
||||||
if let Ok(major_version) = version_str.parse::<u32>() {
|
if let Ok(major_version) = version_str.parse::<u32>() {
|
||||||
@@ -259,60 +239,62 @@ impl IOOptimizer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
false
|
false
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 批量异步写入 - 绕过多次系统调用
|
/// 🚀 批量异步写入 - 绕过多次系统调用
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub async fn batch_async_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
pub async fn batch_async_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
||||||
if self.io_uring_available && requests.len() > 1 {
|
if self.io_uring_available && requests.len() > 1 {
|
||||||
return self.io_uring_batch_write(requests).await;
|
return self.io_uring_batch_write(requests).await;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 回退到标准批量写入
|
// 回退到标准批量写入
|
||||||
self.standard_batch_write(requests).await
|
self.standard_batch_write(requests).await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 使用io_uring进行批量写入
|
/// 使用io_uring进行批量写入
|
||||||
async fn io_uring_batch_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
async fn io_uring_batch_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
||||||
// 这里是伪代码 - 实际实现需要io_uring库
|
// 这里是伪代码 - 实际实现需要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());
|
let mut results = Vec::with_capacity(requests.len());
|
||||||
|
|
||||||
// 模拟批量提交到io_uring
|
// 模拟批量提交到io_uring
|
||||||
for (_fd, data) in requests {
|
for (_fd, data) in requests {
|
||||||
self.async_io_stats.operations_queued.fetch_add(1, Ordering::Relaxed);
|
self.async_io_stats.operations_queued.fetch_add(1, Ordering::Relaxed);
|
||||||
|
|
||||||
// 实际的io_uring实现会在这里提交所有操作
|
// 实际的io_uring实现会在这里提交所有操作
|
||||||
// 然后等待完成,避免多次系统调用
|
// 然后等待完成,避免多次系统调用
|
||||||
|
|
||||||
results.push(data.len()); // 模拟写入成功
|
results.push(data.len()); // 模拟写入成功
|
||||||
self.async_io_stats.bytes_transferred.fetch_add(data.len() as u64, Ordering::Relaxed);
|
self.async_io_stats.bytes_transferred.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||||
self.async_io_stats.operations_completed.fetch_add(1, Ordering::Relaxed);
|
self.async_io_stats.operations_completed.fetch_add(1, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 这是一个系统调用而不是N个
|
// 这是一个系统调用而不是N个
|
||||||
self.async_io_stats.syscalls_avoided.fetch_add(requests.len() as u64 - 1, Ordering::Relaxed);
|
self.async_io_stats
|
||||||
|
.syscalls_avoided
|
||||||
|
.fetch_add(requests.len() as u64 - 1, Ordering::Relaxed);
|
||||||
|
|
||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 标准批量写入
|
/// 标准批量写入
|
||||||
async fn standard_batch_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
async fn standard_batch_write(&self, requests: &[(i32, &[u8])]) -> Result<Vec<usize>> {
|
||||||
let mut results = Vec::with_capacity(requests.len());
|
let mut results = Vec::with_capacity(requests.len());
|
||||||
|
|
||||||
// 将所有写入打包成一个写操作
|
// 将所有写入打包成一个写操作
|
||||||
for (_fd, data) in requests {
|
for (_fd, data) in requests {
|
||||||
// 模拟写入操作
|
// 模拟写入操作
|
||||||
results.push(data.len());
|
results.push(data.len());
|
||||||
self.async_io_stats.bytes_transferred.fetch_add(data.len() as u64, Ordering::Relaxed);
|
self.async_io_stats.bytes_transferred.fetch_add(data.len() as u64, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 内存映射文件I/O - 避免read/write系统调用
|
/// 🚀 内存映射文件I/O - 避免read/write系统调用
|
||||||
pub fn create_memory_mapped_io(&mut self, file_path: &str, size: usize) -> Result<usize> {
|
pub fn create_memory_mapped_io(&mut self, file_path: &str, size: usize) -> Result<usize> {
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -330,16 +312,12 @@ impl IOOptimizer {
|
|||||||
.custom_flags(libc::O_DIRECT) // 直接I/O,绕过页面缓存
|
.custom_flags(libc::O_DIRECT) // 直接I/O,绕过页面缓存
|
||||||
.open(file_path)?
|
.open(file_path)?
|
||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
let file = OpenOptions::new()
|
let file = OpenOptions::new().read(true).write(true).create(true).open(file_path)?;
|
||||||
.read(true)
|
|
||||||
.write(true)
|
|
||||||
.create(true)
|
|
||||||
.open(file_path)?;
|
|
||||||
|
|
||||||
let fd = file.as_raw_fd();
|
let fd = file.as_raw_fd();
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
let addr = libc::mmap(
|
let addr = libc::mmap(
|
||||||
std::ptr::null_mut(),
|
std::ptr::null_mut(),
|
||||||
@@ -349,37 +327,42 @@ impl IOOptimizer {
|
|||||||
fd,
|
fd,
|
||||||
0,
|
0,
|
||||||
);
|
);
|
||||||
|
|
||||||
if addr == libc::MAP_FAILED {
|
if addr == libc::MAP_FAILED {
|
||||||
return Err(anyhow::anyhow!("Memory mapping failed"));
|
return Err(anyhow::anyhow!("Memory mapping failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let region = MemoryMappedRegion {
|
let region =
|
||||||
address: addr as usize,
|
MemoryMappedRegion { address: addr as usize, size, file_descriptor: fd };
|
||||||
size,
|
|
||||||
file_descriptor: fd,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.mmap_regions.push(region);
|
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)
|
Ok(addr as usize)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(not(unix))]
|
#[cfg(not(unix))]
|
||||||
{
|
{
|
||||||
Err(anyhow::anyhow!("Memory mapped I/O not supported on this platform"))
|
Err(anyhow::anyhow!("Memory mapped I/O not supported on this platform"))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取I/O统计
|
/// 获取I/O统计
|
||||||
pub fn get_stats(&self) -> AsyncIOStats {
|
pub fn get_stats(&self) -> AsyncIOStats {
|
||||||
AsyncIOStats {
|
AsyncIOStats {
|
||||||
operations_queued: AtomicU64::new(self.async_io_stats.operations_queued.load(Ordering::Relaxed)),
|
operations_queued: AtomicU64::new(
|
||||||
operations_completed: AtomicU64::new(self.async_io_stats.operations_completed.load(Ordering::Relaxed)),
|
self.async_io_stats.operations_queued.load(Ordering::Relaxed),
|
||||||
bytes_transferred: AtomicU64::new(self.async_io_stats.bytes_transferred.load(Ordering::Relaxed)),
|
),
|
||||||
syscalls_avoided: AtomicU64::new(self.async_io_stats.syscalls_avoided.load(Ordering::Relaxed)),
|
operations_completed: AtomicU64::new(
|
||||||
|
self.async_io_stats.operations_completed.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
bytes_transferred: AtomicU64::new(
|
||||||
|
self.async_io_stats.bytes_transferred.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
syscalls_avoided: AtomicU64::new(
|
||||||
|
self.async_io_stats.syscalls_avoided.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -389,47 +372,46 @@ impl SyscallBatchProcessor {
|
|||||||
pub fn new(batch_size: usize) -> Result<Self> {
|
pub fn new(batch_size: usize) -> Result<Self> {
|
||||||
let pending_calls = crossbeam_queue::ArrayQueue::new(batch_size * 10);
|
let pending_calls = crossbeam_queue::ArrayQueue::new(batch_size * 10);
|
||||||
let executor = tokio::runtime::Handle::current();
|
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 {
|
Ok(Self {
|
||||||
pending_calls,
|
pending_calls,
|
||||||
_executor: executor,
|
_executor: executor,
|
||||||
batch_stats: CachePadded::new(AtomicU64::new(0)),
|
batch_stats: CachePadded::new(AtomicU64::new(0)),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 提交系统调用请求到批处理队列
|
/// 🚀 提交系统调用请求到批处理队列
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn submit_request(&self, request: SyscallRequest) -> Result<()> {
|
pub fn submit_request(&self, request: SyscallRequest) -> Result<()> {
|
||||||
self.pending_calls.push(request)
|
self.pending_calls.push(request).map_err(|_| anyhow::anyhow!("Batch queue full"))?;
|
||||||
.map_err(|_| anyhow::anyhow!("Batch queue full"))?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 执行批量系统调用
|
/// 🚀 执行批量系统调用
|
||||||
pub async fn execute_batch(&self) -> Result<usize> {
|
pub async fn execute_batch(&self) -> Result<usize> {
|
||||||
let mut batch = Vec::new();
|
let mut batch = Vec::new();
|
||||||
|
|
||||||
// 收集批量请求
|
// 收集批量请求
|
||||||
while batch.len() < 100 && !self.pending_calls.is_empty() {
|
while batch.len() < 100 && !self.pending_calls.is_empty() {
|
||||||
if let Some(request) = self.pending_calls.pop() {
|
if let Some(request) = self.pending_calls.pop() {
|
||||||
batch.push(request);
|
batch.push(request);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if batch.is_empty() {
|
if batch.is_empty() {
|
||||||
return Ok(0);
|
return Ok(0);
|
||||||
}
|
}
|
||||||
|
|
||||||
let batch_size = batch.len();
|
let batch_size = batch.len();
|
||||||
|
|
||||||
// 按类型分组批量执行
|
// 按类型分组批量执行
|
||||||
let mut write_requests = Vec::new();
|
let mut write_requests = Vec::new();
|
||||||
let mut read_requests = Vec::new();
|
let mut read_requests = Vec::new();
|
||||||
let mut network_requests = Vec::new();
|
let mut network_requests = Vec::new();
|
||||||
|
|
||||||
for request in batch {
|
for request in batch {
|
||||||
match request {
|
match request {
|
||||||
SyscallRequest::Write { fd, data } => {
|
SyscallRequest::Write { fd, data } => {
|
||||||
@@ -446,52 +428,52 @@ impl SyscallBatchProcessor {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 批量执行写入
|
// 批量执行写入
|
||||||
if !write_requests.is_empty() {
|
if !write_requests.is_empty() {
|
||||||
self.batch_write_operations(write_requests).await?;
|
self.batch_write_operations(write_requests).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 批量执行读取
|
// 批量执行读取
|
||||||
if !read_requests.is_empty() {
|
if !read_requests.is_empty() {
|
||||||
self.batch_read_operations(read_requests).await?;
|
self.batch_read_operations(read_requests).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
// 批量执行网络操作
|
// 批量执行网络操作
|
||||||
if !network_requests.is_empty() {
|
if !network_requests.is_empty() {
|
||||||
self.batch_network_operations(network_requests).await?;
|
self.batch_network_operations(network_requests).await?;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.batch_stats.fetch_add(1, Ordering::Relaxed);
|
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)
|
Ok(batch_size)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 批量写入操作
|
/// 批量写入操作
|
||||||
async fn batch_write_operations(&self, requests: Vec<(i32, Vec<u8>)>) -> Result<()> {
|
async fn batch_write_operations(&self, requests: Vec<(i32, Vec<u8>)>) -> Result<()> {
|
||||||
// 使用writev系统调用进行批量写入
|
// 使用writev系统调用进行批量写入
|
||||||
for (fd, data) in requests {
|
for (fd, data) in requests {
|
||||||
// 实际实现会使用writev或io_uring
|
// 实际实现会使用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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 批量读取操作
|
/// 批量读取操作
|
||||||
async fn batch_read_operations(&self, requests: Vec<(i32, usize)>) -> Result<()> {
|
async fn batch_read_operations(&self, requests: Vec<(i32, usize)>) -> Result<()> {
|
||||||
// 使用readv系统调用进行批量读取
|
// 使用readv系统调用进行批量读取
|
||||||
for (fd, size) in requests {
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 批量网络操作
|
/// 批量网络操作
|
||||||
async fn batch_network_operations(&self, requests: Vec<(i32, Vec<u8>)>) -> Result<()> {
|
async fn batch_network_operations(&self, requests: Vec<(i32, Vec<u8>)>) -> Result<()> {
|
||||||
// 使用sendmsg/recvmsg进行批量网络操作
|
// 使用sendmsg/recvmsg进行批量网络操作
|
||||||
for (socket, data) in requests {
|
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(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -514,22 +496,16 @@ impl SystemCallBypassManager {
|
|||||||
let fast_time_provider = Arc::new(FastTimeProvider::new(config.enable_vdso)?);
|
let fast_time_provider = Arc::new(FastTimeProvider::new(config.enable_vdso)?);
|
||||||
let io_optimizer = Arc::new(IOOptimizer::new(&config)?);
|
let io_optimizer = Arc::new(IOOptimizer::new(&config)?);
|
||||||
let stats = Arc::new(SyscallBypassStats::default());
|
let stats = Arc::new(SyscallBypassStats::default());
|
||||||
|
|
||||||
log::info!("🚀 System Call Bypass Manager initialized");
|
tracing::info!(target: "sol_trade_sdk","🚀 System Call Bypass Manager initialized");
|
||||||
log::info!(" 📦 Batch Processing: {}", config.enable_batch_processing);
|
tracing::info!(target: "sol_trade_sdk"," 📦 Batch Processing: {}", config.enable_batch_processing);
|
||||||
log::info!(" ⏰ Fast Time: {}", config.enable_fast_time);
|
tracing::info!(target: "sol_trade_sdk"," ⏰ Fast Time: {}", config.enable_fast_time);
|
||||||
log::info!(" 🚀 vDSO: {}", config.enable_vdso);
|
tracing::info!(target: "sol_trade_sdk"," 🚀 vDSO: {}", config.enable_vdso);
|
||||||
log::info!(" 📁 io_uring: {}", config.enable_io_uring);
|
tracing::info!(target: "sol_trade_sdk"," 📁 io_uring: {}", config.enable_io_uring);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self { config, batch_processor, fast_time_provider, _io_optimizer: io_optimizer, stats })
|
||||||
config,
|
|
||||||
batch_processor,
|
|
||||||
fast_time_provider,
|
|
||||||
_io_optimizer: io_optimizer,
|
|
||||||
stats,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速获取当前时间戳 - 绕过系统调用
|
/// 🚀 快速获取当前时间戳 - 绕过系统调用
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn fast_timestamp_nanos(&self) -> u64 {
|
pub fn fast_timestamp_nanos(&self) -> u64 {
|
||||||
@@ -537,28 +513,25 @@ impl SystemCallBypassManager {
|
|||||||
self.stats.time_calls_cached.fetch_add(1, Ordering::Relaxed);
|
self.stats.time_calls_cached.fetch_add(1, Ordering::Relaxed);
|
||||||
return self.fast_time_provider.fast_now_nanos();
|
return self.fast_time_provider.fast_now_nanos();
|
||||||
}
|
}
|
||||||
|
|
||||||
// 回退到标准时间获取
|
// 回退到标准时间获取
|
||||||
SystemTime::now()
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos() as u64
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_nanos() as u64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 提交批量I/O操作
|
/// 🚀 提交批量I/O操作
|
||||||
pub async fn submit_batch_io(&self, operations: Vec<SyscallRequest>) -> Result<()> {
|
pub async fn submit_batch_io(&self, operations: Vec<SyscallRequest>) -> Result<()> {
|
||||||
if !self.config.enable_batch_processing {
|
if !self.config.enable_batch_processing {
|
||||||
return Err(anyhow::anyhow!("Batch processing disabled"));
|
return Err(anyhow::anyhow!("Batch processing disabled"));
|
||||||
}
|
}
|
||||||
|
|
||||||
for op in operations {
|
for op in operations {
|
||||||
self.batch_processor.submit_request(op)?;
|
self.batch_processor.submit_request(op)?;
|
||||||
}
|
}
|
||||||
|
|
||||||
self.stats.syscalls_batched.fetch_add(1, Ordering::Relaxed);
|
self.stats.syscalls_batched.fetch_add(1, Ordering::Relaxed);
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 执行优化的内存分配 - 绕过malloc系统调用
|
/// 🚀 执行优化的内存分配 - 绕过malloc系统调用
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn fast_allocate(&self, size: usize) -> Result<*mut u8> {
|
pub fn fast_allocate(&self, size: usize) -> Result<*mut u8> {
|
||||||
@@ -566,34 +539,30 @@ impl SystemCallBypassManager {
|
|||||||
self.stats.memory_operations_avoided.fetch_add(1, Ordering::Relaxed);
|
self.stats.memory_operations_avoided.fetch_add(1, Ordering::Relaxed);
|
||||||
return self.userspace_allocate(size);
|
return self.userspace_allocate(size);
|
||||||
}
|
}
|
||||||
|
|
||||||
// 回退到标准分配
|
// 回退到标准分配
|
||||||
let layout = std::alloc::Layout::from_size_align(size, 8)?;
|
let layout = std::alloc::Layout::from_size_align(size, 8)?;
|
||||||
let ptr = unsafe { std::alloc::alloc(layout) };
|
let ptr = unsafe { std::alloc::alloc(layout) };
|
||||||
|
|
||||||
if ptr.is_null() {
|
if ptr.is_null() {
|
||||||
Err(anyhow::anyhow!("Allocation failed"))
|
Err(anyhow::anyhow!("Allocation failed"))
|
||||||
} else {
|
} else {
|
||||||
Ok(ptr)
|
Ok(ptr)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 用户空间内存分配
|
/// 用户空间内存分配
|
||||||
fn userspace_allocate(&self, size: usize) -> Result<*mut u8> {
|
fn userspace_allocate(&self, size: usize) -> Result<*mut u8> {
|
||||||
use std::sync::Mutex;
|
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
struct MemoryPool {
|
struct MemoryPool {
|
||||||
pool: Box<[u8; 1024 * 1024]>,
|
pool: Box<[u8; 1024 * 1024]>,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
static MEMORY_POOL: Lazy<Mutex<MemoryPool>> = Lazy::new(|| {
|
static MEMORY_POOL: Lazy<Mutex<MemoryPool>> =
|
||||||
Mutex::new(MemoryPool {
|
Lazy::new(|| Mutex::new(MemoryPool { pool: Box::new([0; 1024 * 1024]), offset: 0 }));
|
||||||
pool: Box::new([0; 1024 * 1024]),
|
|
||||||
offset: 0,
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut pool = MEMORY_POOL.lock().unwrap();
|
let mut pool = MEMORY_POOL.lock().unwrap();
|
||||||
|
|
||||||
@@ -606,18 +575,18 @@ impl SystemCallBypassManager {
|
|||||||
|
|
||||||
Ok(ptr)
|
Ok(ptr)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 启动批处理工作线程
|
/// 启动批处理工作线程
|
||||||
pub async fn start_batch_processing(&self) -> Result<()> {
|
pub async fn start_batch_processing(&self) -> Result<()> {
|
||||||
let processor = Arc::clone(&self.batch_processor);
|
let processor = Arc::clone(&self.batch_processor);
|
||||||
let stats = Arc::clone(&self.stats);
|
let stats = Arc::clone(&self.stats);
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut interval = tokio::time::interval(Duration::from_micros(100)); // 100μs间隔
|
let mut interval = tokio::time::interval(Duration::from_micros(100)); // 100μs间隔
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
interval.tick().await;
|
interval.tick().await;
|
||||||
|
|
||||||
if let Ok(processed) = processor.execute_batch().await {
|
if let Ok(processed) = processor.execute_batch().await {
|
||||||
if processed > 0 {
|
if processed > 0 {
|
||||||
stats.syscalls_bypassed.fetch_add(processed as u64, Ordering::Relaxed);
|
stats.syscalls_bypassed.fetch_add(processed as u64, Ordering::Relaxed);
|
||||||
@@ -625,11 +594,11 @@ impl SystemCallBypassManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
log::info!("✅ Batch processing worker started");
|
tracing::info!(target: "sol_trade_sdk","✅ Batch processing worker started");
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取绕过统计
|
/// 获取绕过统计
|
||||||
pub fn get_bypass_stats(&self) -> SyscallBypassStatsSnapshot {
|
pub fn get_bypass_stats(&self) -> SyscallBypassStatsSnapshot {
|
||||||
SyscallBypassStatsSnapshot {
|
SyscallBypassStatsSnapshot {
|
||||||
@@ -640,7 +609,7 @@ impl SystemCallBypassManager {
|
|||||||
memory_operations_avoided: self.stats.memory_operations_avoided.load(Ordering::Relaxed),
|
memory_operations_avoided: self.stats.memory_operations_avoided.load(Ordering::Relaxed),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 极致优化配置
|
/// 🚀 极致优化配置
|
||||||
pub fn extreme_bypass_config() -> SyscallBypassConfig {
|
pub fn extreme_bypass_config() -> SyscallBypassConfig {
|
||||||
SyscallBypassConfig {
|
SyscallBypassConfig {
|
||||||
@@ -669,16 +638,18 @@ pub struct SyscallBypassStatsSnapshot {
|
|||||||
impl SyscallBypassStatsSnapshot {
|
impl SyscallBypassStatsSnapshot {
|
||||||
/// 打印统计信息
|
/// 打印统计信息
|
||||||
pub fn print_stats(&self) {
|
pub fn print_stats(&self) {
|
||||||
log::info!("📊 System Call Bypass Stats:");
|
tracing::info!(target: "sol_trade_sdk","📊 System Call Bypass Stats:");
|
||||||
log::info!(" 🚫 Syscalls Bypassed: {}", self.syscalls_bypassed);
|
tracing::info!(target: "sol_trade_sdk"," 🚫 Syscalls Bypassed: {}", self.syscalls_bypassed);
|
||||||
log::info!(" 📦 Syscalls Batched: {}", self.syscalls_batched);
|
tracing::info!(target: "sol_trade_sdk"," 📦 Syscalls Batched: {}", self.syscalls_batched);
|
||||||
log::info!(" ⏰ Time Calls Cached: {}", self.time_calls_cached);
|
tracing::info!(target: "sol_trade_sdk"," ⏰ Time Calls Cached: {}", self.time_calls_cached);
|
||||||
log::info!(" 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
|
tracing::info!(target: "sol_trade_sdk"," 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
|
||||||
log::info!(" 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
|
tracing::info!(target: "sol_trade_sdk"," 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
|
||||||
|
|
||||||
let total_optimizations = self.syscalls_bypassed + self.time_calls_cached +
|
let total_optimizations = self.syscalls_bypassed
|
||||||
self.io_operations_optimized + self.memory_operations_avoided;
|
+ self.time_calls_cached
|
||||||
log::info!(" 🏆 Total Optimizations: {}", total_optimizations);
|
+ self.io_operations_optimized
|
||||||
|
+ self.memory_operations_avoided;
|
||||||
|
tracing::info!(target: "sol_trade_sdk"," 🏆 Total Optimizations: {}", total_optimizations);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -689,7 +660,7 @@ macro_rules! bypass_syscall {
|
|||||||
// 使用快速时间而不是系统调用
|
// 使用快速时间而不是系统调用
|
||||||
crate::performance::syscall_bypass::GLOBAL_TIME_PROVIDER.fast_now_nanos()
|
crate::performance::syscall_bypass::GLOBAL_TIME_PROVIDER.fast_now_nanos()
|
||||||
};
|
};
|
||||||
|
|
||||||
(batch_io $ops:expr) => {
|
(batch_io $ops:expr) => {
|
||||||
// 批量提交I/O操作
|
// 批量提交I/O操作
|
||||||
crate::performance::syscall_bypass::GLOBAL_BYPASS_MANAGER.submit_batch_io($ops).await
|
crate::performance::syscall_bypass::GLOBAL_BYPASS_MANAGER.submit_batch_io($ops).await
|
||||||
@@ -699,60 +670,57 @@ macro_rules! bypass_syscall {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_fast_time_provider() {
|
async fn test_fast_time_provider() {
|
||||||
let provider = FastTimeProvider::new(false).unwrap();
|
let provider = FastTimeProvider::new(false).unwrap();
|
||||||
|
|
||||||
let time1 = provider.fast_now_nanos();
|
let time1 = provider.fast_now_nanos();
|
||||||
tokio::time::sleep(Duration::from_millis(1)).await;
|
tokio::time::sleep(Duration::from_millis(1)).await;
|
||||||
let time2 = provider.fast_now_nanos();
|
let time2 = provider.fast_now_nanos();
|
||||||
|
|
||||||
assert!(time2 > time1);
|
assert!(time2 > time1);
|
||||||
assert!(time2 - time1 >= 1_000_000); // 至少1ms差异
|
assert!(time2 - time1 >= 1_000_000); // 至少1ms差异
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_syscall_batch_processor() {
|
async fn test_syscall_batch_processor() {
|
||||||
let processor = SyscallBatchProcessor::new(10).unwrap();
|
let processor = SyscallBatchProcessor::new(10).unwrap();
|
||||||
|
|
||||||
let request = SyscallRequest::Write {
|
let request = SyscallRequest::Write { fd: 1, data: vec![1, 2, 3, 4, 5] };
|
||||||
fd: 1,
|
|
||||||
data: vec![1, 2, 3, 4, 5],
|
|
||||||
};
|
|
||||||
|
|
||||||
processor.submit_request(request).unwrap();
|
processor.submit_request(request).unwrap();
|
||||||
|
|
||||||
let processed = processor.execute_batch().await.unwrap();
|
let processed = processor.execute_batch().await.unwrap();
|
||||||
assert_eq!(processed, 1);
|
assert_eq!(processed, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_io_optimizer() {
|
async fn test_io_optimizer() {
|
||||||
let config = SyscallBypassConfig::default();
|
let config = SyscallBypassConfig::default();
|
||||||
let optimizer = IOOptimizer::new(&config).unwrap();
|
let optimizer = IOOptimizer::new(&config).unwrap();
|
||||||
|
|
||||||
let requests = vec![(1, b"test data".as_ref())];
|
let requests = vec![(1, b"test data".as_ref())];
|
||||||
let results = optimizer.batch_async_write(&requests).await.unwrap();
|
let results = optimizer.batch_async_write(&requests).await.unwrap();
|
||||||
|
|
||||||
assert_eq!(results.len(), 1);
|
assert_eq!(results.len(), 1);
|
||||||
assert_eq!(results[0], 9); // "test data".len()
|
assert_eq!(results[0], 9); // "test data".len()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_system_call_bypass_manager() {
|
async fn test_system_call_bypass_manager() {
|
||||||
let config = SyscallBypassConfig::default();
|
let config = SyscallBypassConfig::default();
|
||||||
let manager = SystemCallBypassManager::new(config).unwrap();
|
let manager = SystemCallBypassManager::new(config).unwrap();
|
||||||
|
|
||||||
// 测试快速时间戳
|
// 测试快速时间戳
|
||||||
let timestamp = manager.fast_timestamp_nanos();
|
let timestamp = manager.fast_timestamp_nanos();
|
||||||
assert!(timestamp > 0);
|
assert!(timestamp > 0);
|
||||||
|
|
||||||
// 测试统计
|
// 测试统计
|
||||||
let stats = manager.get_bypass_stats();
|
let stats = manager.get_bypass_stats();
|
||||||
assert_eq!(stats.time_calls_cached, 1);
|
assert_eq!(stats.time_calls_cached, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_extreme_bypass_config() {
|
fn test_extreme_bypass_config() {
|
||||||
let config = SystemCallBypassManager::extreme_bypass_config();
|
let config = SystemCallBypassManager::extreme_bypass_config();
|
||||||
@@ -763,16 +731,16 @@ mod tests {
|
|||||||
assert_eq!(config.batch_size, 1000);
|
assert_eq!(config.batch_size, 1000);
|
||||||
assert_eq!(config.syscall_cache_size, 10000);
|
assert_eq!(config.syscall_cache_size, 10000);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_userspace_allocation() {
|
fn test_userspace_allocation() {
|
||||||
let config = SyscallBypassConfig::default();
|
let config = SyscallBypassConfig::default();
|
||||||
let manager = SystemCallBypassManager::new(config).unwrap();
|
let manager = SystemCallBypassManager::new(config).unwrap();
|
||||||
|
|
||||||
let ptr = manager.fast_allocate(64).unwrap();
|
let ptr = manager.fast_allocate(64).unwrap();
|
||||||
assert!(!ptr.is_null());
|
assert!(!ptr.is_null());
|
||||||
|
|
||||||
let stats = manager.get_bypass_stats();
|
let stats = manager.get_bypass_stats();
|
||||||
assert_eq!(stats.memory_operations_avoided, 1);
|
assert_eq!(stats.memory_operations_avoided, 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+145
-138
@@ -1,5 +1,5 @@
|
|||||||
//! 🚀 零拷贝内存映射IO - 完全消除数据拷贝开销
|
//! 🚀 零拷贝内存映射IO - 完全消除数据拷贝开销
|
||||||
//!
|
//!
|
||||||
//! 实现极致的零拷贝策略,包括:
|
//! 实现极致的零拷贝策略,包括:
|
||||||
//! - 内存映射文件IO
|
//! - 内存映射文件IO
|
||||||
//! - 共享内存环形缓冲区
|
//! - 共享内存环形缓冲区
|
||||||
@@ -10,11 +10,11 @@
|
|||||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
// use std::mem::{size_of, MaybeUninit};
|
// use std::mem::{size_of, MaybeUninit};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use crossbeam_utils::CachePadded;
|
||||||
|
use memmap2::{MmapMut, MmapOptions};
|
||||||
use std::ptr::NonNull;
|
use std::ptr::NonNull;
|
||||||
use std::slice;
|
use std::slice;
|
||||||
use memmap2::{MmapMut, MmapOptions};
|
|
||||||
use anyhow::{Result, Context};
|
|
||||||
use crossbeam_utils::CachePadded;
|
|
||||||
|
|
||||||
/// 🚀 零拷贝内存管理器
|
/// 🚀 零拷贝内存管理器
|
||||||
pub struct ZeroCopyMemoryManager {
|
pub struct ZeroCopyMemoryManager {
|
||||||
@@ -50,17 +50,17 @@ impl SharedMemoryPool {
|
|||||||
// 确保块大小是64字节对齐(缓存行对齐)
|
// 确保块大小是64字节对齐(缓存行对齐)
|
||||||
let aligned_block_size = (block_size + 63) & !63;
|
let aligned_block_size = (block_size + 63) & !63;
|
||||||
let total_blocks = total_size / aligned_block_size;
|
let total_blocks = total_size / aligned_block_size;
|
||||||
|
|
||||||
// 创建内存映射文件
|
// 创建内存映射文件
|
||||||
let memory_region = MmapOptions::new()
|
let memory_region = MmapOptions::new()
|
||||||
.len(total_blocks * aligned_block_size)
|
.len(total_blocks * aligned_block_size)
|
||||||
.map_anon()
|
.map_anon()
|
||||||
.context("Failed to create memory mapped region")?;
|
.context("Failed to create memory mapped region")?;
|
||||||
|
|
||||||
// 初始化空闲块位图 (每个u64可以管理64个块)
|
// 初始化空闲块位图 (每个u64可以管理64个块)
|
||||||
let bitmap_size = (total_blocks + 63) / 64;
|
let bitmap_size = (total_blocks + 63) / 64;
|
||||||
let mut free_blocks = Vec::with_capacity(bitmap_size);
|
let mut free_blocks = Vec::with_capacity(bitmap_size);
|
||||||
|
|
||||||
// 将所有块标记为空闲(全1)
|
// 将所有块标记为空闲(全1)
|
||||||
for i in 0..bitmap_size {
|
for i in 0..bitmap_size {
|
||||||
let bits = if i == bitmap_size - 1 && total_blocks % 64 != 0 {
|
let bits = if i == bitmap_size - 1 && total_blocks % 64 != 0 {
|
||||||
@@ -72,10 +72,10 @@ impl SharedMemoryPool {
|
|||||||
};
|
};
|
||||||
free_blocks.push(AtomicU64::new(bits));
|
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);
|
pool_id, total_blocks, aligned_block_size);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
memory_region,
|
memory_region,
|
||||||
free_blocks,
|
free_blocks,
|
||||||
@@ -85,31 +85,31 @@ impl SharedMemoryPool {
|
|||||||
pool_id,
|
pool_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 零拷贝分配内存块
|
/// 🚀 零拷贝分配内存块
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn allocate_block(&self) -> Option<ZeroCopyBlock> {
|
pub fn allocate_block(&self) -> Option<ZeroCopyBlock> {
|
||||||
// 快速路径:尝试从预期位置分配
|
// 快速路径:尝试从预期位置分配
|
||||||
let start_index = self.allocator_head.load(Ordering::Relaxed) / 64;
|
let start_index = self.allocator_head.load(Ordering::Relaxed) / 64;
|
||||||
|
|
||||||
// 遍历所有位图寻找空闲块
|
// 遍历所有位图寻找空闲块
|
||||||
for attempt in 0..self.free_blocks.len() {
|
for attempt in 0..self.free_blocks.len() {
|
||||||
let bitmap_index = (start_index + attempt) % self.free_blocks.len();
|
let bitmap_index = (start_index + attempt) % self.free_blocks.len();
|
||||||
let bitmap = &self.free_blocks[bitmap_index];
|
let bitmap = &self.free_blocks[bitmap_index];
|
||||||
|
|
||||||
let mut current = bitmap.load(Ordering::Acquire);
|
let mut current = bitmap.load(Ordering::Acquire);
|
||||||
|
|
||||||
while current != 0 {
|
while current != 0 {
|
||||||
// 找到最低位的1(最小的空闲块)
|
// 找到最低位的1(最小的空闲块)
|
||||||
let bit_pos = current.trailing_zeros() as usize;
|
let bit_pos = current.trailing_zeros() as usize;
|
||||||
let mask = 1u64 << bit_pos;
|
let mask = 1u64 << bit_pos;
|
||||||
|
|
||||||
// 尝试原子地清除这一位(标记为已分配)
|
// 尝试原子地清除这一位(标记为已分配)
|
||||||
match bitmap.compare_exchange_weak(
|
match bitmap.compare_exchange_weak(
|
||||||
current,
|
current,
|
||||||
current & !mask,
|
current & !mask,
|
||||||
Ordering::AcqRel,
|
Ordering::AcqRel,
|
||||||
Ordering::Relaxed
|
Ordering::Relaxed,
|
||||||
) {
|
) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
// 成功分配
|
// 成功分配
|
||||||
@@ -119,20 +119,17 @@ impl SharedMemoryPool {
|
|||||||
bitmap.fetch_or(mask, Ordering::Relaxed);
|
bitmap.fetch_or(mask, Ordering::Relaxed);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
let offset = block_index * self.block_size;
|
let offset = block_index * self.block_size;
|
||||||
let ptr = unsafe {
|
let ptr = unsafe {
|
||||||
NonNull::new_unchecked(
|
NonNull::new_unchecked(
|
||||||
self.memory_region.as_ptr().add(offset) as *mut u8
|
self.memory_region.as_ptr().add(offset) as *mut u8
|
||||||
)
|
)
|
||||||
};
|
};
|
||||||
|
|
||||||
// 更新分配器头指针
|
// 更新分配器头指针
|
||||||
self.allocator_head.store(
|
self.allocator_head.store((block_index + 1) * 64, Ordering::Relaxed);
|
||||||
(block_index + 1) * 64,
|
|
||||||
Ordering::Relaxed
|
|
||||||
);
|
|
||||||
|
|
||||||
return Some(ZeroCopyBlock {
|
return Some(ZeroCopyBlock {
|
||||||
ptr,
|
ptr,
|
||||||
size: self.block_size,
|
size: self.block_size,
|
||||||
@@ -147,31 +144,32 @@ impl SharedMemoryPool {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
None // 没有可用块
|
None // 没有可用块
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 零拷贝释放内存块
|
/// 🚀 零拷贝释放内存块
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn deallocate_block(&self, block: ZeroCopyBlock) {
|
pub fn deallocate_block(&self, block: ZeroCopyBlock) {
|
||||||
if block.pool_id != self.pool_id {
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let bitmap_index = block.block_index / 64;
|
let bitmap_index = block.block_index / 64;
|
||||||
let bit_pos = block.block_index % 64;
|
let bit_pos = block.block_index % 64;
|
||||||
let mask = 1u64 << bit_pos;
|
let mask = 1u64 << bit_pos;
|
||||||
|
|
||||||
if bitmap_index < self.free_blocks.len() {
|
if bitmap_index < self.free_blocks.len() {
|
||||||
// 原子地设置位为1(标记为空闲)
|
// 原子地设置位为1(标记为空闲)
|
||||||
self.free_blocks[bitmap_index].fetch_or(mask, Ordering::Release);
|
self.free_blocks[bitmap_index].fetch_or(mask, Ordering::Release);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取可用块数量
|
/// 获取可用块数量
|
||||||
pub fn available_blocks(&self) -> usize {
|
pub fn available_blocks(&self) -> usize {
|
||||||
self.free_blocks.iter()
|
self.free_blocks
|
||||||
|
.iter()
|
||||||
.map(|bitmap| bitmap.load(Ordering::Relaxed).count_ones() as usize)
|
.map(|bitmap| bitmap.load(Ordering::Relaxed).count_ones() as usize)
|
||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
@@ -195,49 +193,49 @@ impl ZeroCopyBlock {
|
|||||||
pub fn as_ptr(&self) -> *mut u8 {
|
pub fn as_ptr(&self) -> *mut u8 {
|
||||||
self.ptr.as_ptr()
|
self.ptr.as_ptr()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取只读切片
|
/// 获取只读切片
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn as_slice(&self) -> &[u8] {
|
pub unsafe fn as_slice(&self) -> &[u8] {
|
||||||
slice::from_raw_parts(self.ptr.as_ptr(), self.size)
|
slice::from_raw_parts(self.ptr.as_ptr(), self.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取可变切片
|
/// 获取可变切片
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
|
pub unsafe fn as_mut_slice(&mut self) -> &mut [u8] {
|
||||||
slice::from_raw_parts_mut(self.ptr.as_ptr(), self.size)
|
slice::from_raw_parts_mut(self.ptr.as_ptr(), self.size)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取块大小
|
/// 获取块大小
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn size(&self) -> usize {
|
pub fn size(&self) -> usize {
|
||||||
self.size
|
self.size
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 零拷贝写入数据
|
/// 零拷贝写入数据
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn write_bytes(&mut self, data: &[u8]) -> Result<()> {
|
pub unsafe fn write_bytes(&mut self, data: &[u8]) -> Result<()> {
|
||||||
if data.len() > self.size {
|
if data.len() > self.size {
|
||||||
return Err(anyhow::anyhow!("Data too large for block"));
|
return Err(anyhow::anyhow!("Data too large for block"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用硬件优化的内存拷贝
|
// 使用硬件优化的内存拷贝
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
self.ptr.as_ptr(),
|
self.ptr.as_ptr(),
|
||||||
data.as_ptr(),
|
data.as_ptr(),
|
||||||
data.len()
|
data.len(),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 零拷贝读取数据
|
/// 零拷贝读取数据
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub unsafe fn read_bytes(&self, len: usize) -> Result<&[u8]> {
|
pub unsafe fn read_bytes(&self, len: usize) -> Result<&[u8]> {
|
||||||
if len > self.size {
|
if len > self.size {
|
||||||
return Err(anyhow::anyhow!("Read length exceeds block size"));
|
return Err(anyhow::anyhow!("Read length exceeds block size"));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(slice::from_raw_parts(self.ptr.as_ptr(), len))
|
Ok(slice::from_raw_parts(self.ptr.as_ptr(), len))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -266,9 +264,9 @@ impl MemoryMappedBuffer {
|
|||||||
.len(size)
|
.len(size)
|
||||||
.map_anon()
|
.map_anon()
|
||||||
.context("Failed to create memory mapped buffer")?;
|
.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 {
|
Ok(Self {
|
||||||
mmap,
|
mmap,
|
||||||
read_pos: CachePadded::new(AtomicUsize::new(0)),
|
read_pos: CachePadded::new(AtomicUsize::new(0)),
|
||||||
@@ -277,128 +275,136 @@ impl MemoryMappedBuffer {
|
|||||||
_buffer_id: buffer_id,
|
_buffer_id: buffer_id,
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 零拷贝写入数据
|
/// 🚀 零拷贝写入数据
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn write_data(&self, data: &[u8]) -> Result<usize> {
|
pub fn write_data(&self, data: &[u8]) -> Result<usize> {
|
||||||
let data_len = data.len();
|
let data_len = data.len();
|
||||||
let current_write = self.write_pos.load(Ordering::Relaxed);
|
let current_write = self.write_pos.load(Ordering::Relaxed);
|
||||||
let current_read = self.read_pos.load(Ordering::Acquire);
|
let current_read = self.read_pos.load(Ordering::Acquire);
|
||||||
|
|
||||||
// 计算可用空间
|
// 计算可用空间
|
||||||
let available_space = if current_write >= current_read {
|
let available_space = if current_write >= current_read {
|
||||||
self.size - (current_write - current_read) - 1
|
self.size - (current_write - current_read) - 1
|
||||||
} else {
|
} else {
|
||||||
current_read - current_write - 1
|
current_read - current_write - 1
|
||||||
};
|
};
|
||||||
|
|
||||||
if data_len > available_space {
|
if data_len > available_space {
|
||||||
return Err(anyhow::anyhow!("Insufficient buffer space"));
|
return Err(anyhow::anyhow!("Insufficient buffer space"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 零拷贝写入
|
// 零拷贝写入
|
||||||
unsafe {
|
unsafe {
|
||||||
let write_ptr = self.mmap.as_ptr().add(current_write) as *mut u8;
|
let write_ptr = self.mmap.as_ptr().add(current_write) as *mut u8;
|
||||||
|
|
||||||
if current_write + data_len <= self.size {
|
if current_write + data_len <= self.size {
|
||||||
// 数据不跨越缓冲区边界
|
// 数据不跨越缓冲区边界
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
write_ptr, data.as_ptr(), data_len
|
write_ptr,
|
||||||
|
data.as_ptr(),
|
||||||
|
data_len,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// 数据跨越缓冲区边界,分两段写入
|
// 数据跨越缓冲区边界,分两段写入
|
||||||
let first_part = self.size - current_write;
|
let first_part = self.size - current_write;
|
||||||
let second_part = data_len - first_part;
|
let second_part = data_len - first_part;
|
||||||
|
|
||||||
// 写入第一部分
|
// 写入第一部分
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
write_ptr, data.as_ptr(), first_part
|
write_ptr,
|
||||||
|
data.as_ptr(),
|
||||||
|
first_part,
|
||||||
);
|
);
|
||||||
|
|
||||||
// 写入第二部分(从缓冲区开头)
|
// 写入第二部分(从缓冲区开头)
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
self.mmap.as_ptr() as *mut u8,
|
self.mmap.as_ptr() as *mut u8,
|
||||||
data.as_ptr().add(first_part),
|
data.as_ptr().add(first_part),
|
||||||
second_part
|
second_part,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新写指针
|
// 更新写指针
|
||||||
let new_write_pos = (current_write + data_len) % self.size;
|
let new_write_pos = (current_write + data_len) % self.size;
|
||||||
self.write_pos.store(new_write_pos, Ordering::Release);
|
self.write_pos.store(new_write_pos, Ordering::Release);
|
||||||
|
|
||||||
Ok(data_len)
|
Ok(data_len)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 零拷贝读取数据
|
/// 🚀 零拷贝读取数据
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn read_data(&self, buffer: &mut [u8]) -> Result<usize> {
|
pub fn read_data(&self, buffer: &mut [u8]) -> Result<usize> {
|
||||||
let buffer_len = buffer.len();
|
let buffer_len = buffer.len();
|
||||||
let current_read = self.read_pos.load(Ordering::Relaxed);
|
let current_read = self.read_pos.load(Ordering::Relaxed);
|
||||||
let current_write = self.write_pos.load(Ordering::Acquire);
|
let current_write = self.write_pos.load(Ordering::Acquire);
|
||||||
|
|
||||||
// 计算可读数据量
|
// 计算可读数据量
|
||||||
let available_data = if current_write >= current_read {
|
let available_data = if current_write >= current_read {
|
||||||
current_write - current_read
|
current_write - current_read
|
||||||
} else {
|
} else {
|
||||||
self.size - (current_read - current_write)
|
self.size - (current_read - current_write)
|
||||||
};
|
};
|
||||||
|
|
||||||
if available_data == 0 {
|
if available_data == 0 {
|
||||||
return Ok(0); // 无数据可读
|
return Ok(0); // 无数据可读
|
||||||
}
|
}
|
||||||
|
|
||||||
let read_len = buffer_len.min(available_data);
|
let read_len = buffer_len.min(available_data);
|
||||||
|
|
||||||
// 零拷贝读取
|
// 零拷贝读取
|
||||||
unsafe {
|
unsafe {
|
||||||
let read_ptr = self.mmap.as_ptr().add(current_read);
|
let read_ptr = self.mmap.as_ptr().add(current_read);
|
||||||
|
|
||||||
if current_read + read_len <= self.size {
|
if current_read + read_len <= self.size {
|
||||||
// 数据不跨越缓冲区边界
|
// 数据不跨越缓冲区边界
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr(), read_ptr, read_len
|
buffer.as_mut_ptr(),
|
||||||
|
read_ptr,
|
||||||
|
read_len,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// 数据跨越缓冲区边界,分两段读取
|
// 数据跨越缓冲区边界,分两段读取
|
||||||
let first_part = self.size - current_read;
|
let first_part = self.size - current_read;
|
||||||
let second_part = read_len - first_part;
|
let second_part = read_len - first_part;
|
||||||
|
|
||||||
// 读取第一部分
|
// 读取第一部分
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr(), read_ptr, first_part
|
buffer.as_mut_ptr(),
|
||||||
|
read_ptr,
|
||||||
|
first_part,
|
||||||
);
|
);
|
||||||
|
|
||||||
// 读取第二部分(从缓冲区开头)
|
// 读取第二部分(从缓冲区开头)
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr().add(first_part),
|
buffer.as_mut_ptr().add(first_part),
|
||||||
self.mmap.as_ptr(),
|
self.mmap.as_ptr(),
|
||||||
second_part
|
second_part,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 更新读指针
|
// 更新读指针
|
||||||
let new_read_pos = (current_read + read_len) % self.size;
|
let new_read_pos = (current_read + read_len) % self.size;
|
||||||
self.read_pos.store(new_read_pos, Ordering::Release);
|
self.read_pos.store(new_read_pos, Ordering::Release);
|
||||||
|
|
||||||
Ok(read_len)
|
Ok(read_len)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取可读数据量
|
/// 获取可读数据量
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn available_data(&self) -> usize {
|
pub fn available_data(&self) -> usize {
|
||||||
let current_read = self.read_pos.load(Ordering::Relaxed);
|
let current_read = self.read_pos.load(Ordering::Relaxed);
|
||||||
let current_write = self.write_pos.load(Ordering::Relaxed);
|
let current_write = self.write_pos.load(Ordering::Relaxed);
|
||||||
|
|
||||||
if current_write >= current_read {
|
if current_write >= current_read {
|
||||||
current_write - current_read
|
current_write - current_read
|
||||||
} else {
|
} else {
|
||||||
self.size - (current_read - current_write)
|
self.size - (current_read - current_write)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取可用空间
|
/// 获取可用空间
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn available_space(&self) -> usize {
|
pub fn available_space(&self) -> usize {
|
||||||
@@ -420,38 +426,39 @@ impl DirectMemoryAccessManager {
|
|||||||
/// 创建DMA管理器
|
/// 创建DMA管理器
|
||||||
pub fn new(num_channels: usize) -> Result<Self> {
|
pub fn new(num_channels: usize) -> Result<Self> {
|
||||||
let mut dma_channels = Vec::with_capacity(num_channels);
|
let mut dma_channels = Vec::with_capacity(num_channels);
|
||||||
|
|
||||||
for i in 0..num_channels {
|
for i in 0..num_channels {
|
||||||
dma_channels.push(Arc::new(DMAChannel::new(i)?));
|
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 {
|
Ok(Self {
|
||||||
dma_channels,
|
dma_channels,
|
||||||
channel_allocator: AtomicUsize::new(0),
|
channel_allocator: AtomicUsize::new(0),
|
||||||
dma_stats: Arc::new(DMAStats::new()),
|
dma_stats: Arc::new(DMAStats::new()),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 执行零拷贝DMA传输
|
/// 🚀 执行零拷贝DMA传输
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub async fn dma_transfer(&self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
|
pub async fn dma_transfer(&self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
|
||||||
if src.len() != dst.len() {
|
if src.len() != dst.len() {
|
||||||
return Err(anyhow::anyhow!("Source and destination sizes don't match"));
|
return Err(anyhow::anyhow!("Source and destination sizes don't match"));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 选择DMA通道(轮询分配)
|
// 选择DMA通道(轮询分配)
|
||||||
let channel_index = self.channel_allocator.fetch_add(1, Ordering::Relaxed) % self.dma_channels.len();
|
let channel_index =
|
||||||
|
self.channel_allocator.fetch_add(1, Ordering::Relaxed) % self.dma_channels.len();
|
||||||
let channel = &self.dma_channels[channel_index];
|
let channel = &self.dma_channels[channel_index];
|
||||||
|
|
||||||
// 执行DMA传输
|
// 执行DMA传输
|
||||||
let transferred = channel.transfer(src, dst).await?;
|
let transferred = channel.transfer(src, dst).await?;
|
||||||
|
|
||||||
// 更新统计
|
// 更新统计
|
||||||
self.dma_stats.bytes_transferred.fetch_add(transferred as u64, Ordering::Relaxed);
|
self.dma_stats.bytes_transferred.fetch_add(transferred as u64, Ordering::Relaxed);
|
||||||
self.dma_stats.transfers_completed.fetch_add(1, Ordering::Relaxed);
|
self.dma_stats.transfers_completed.fetch_add(1, Ordering::Relaxed);
|
||||||
|
|
||||||
Ok(transferred)
|
Ok(transferred)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -475,21 +482,21 @@ impl DMAChannel {
|
|||||||
_status: AtomicU64::new(0),
|
_status: AtomicU64::new(0),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 执行零拷贝传输
|
/// 🚀 执行零拷贝传输
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub async fn transfer(&self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
|
pub async fn transfer(&self, src: &[u8], dst: &mut [u8]) -> Result<usize> {
|
||||||
let transfer_size = src.len();
|
let transfer_size = src.len();
|
||||||
|
|
||||||
// 使用硬件优化的SIMD内存拷贝
|
// 使用硬件优化的SIMD内存拷贝
|
||||||
unsafe {
|
unsafe {
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
dst.as_mut_ptr(),
|
dst.as_mut_ptr(),
|
||||||
src.as_ptr(),
|
src.as_ptr(),
|
||||||
transfer_size
|
transfer_size,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(transfer_size)
|
Ok(transfer_size)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -541,20 +548,20 @@ impl ZeroCopyStats {
|
|||||||
mmap_buffer_usage: AtomicU64::new(0),
|
mmap_buffer_usage: AtomicU64::new(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 打印统计信息
|
/// 打印统计信息
|
||||||
pub fn print_stats(&self) {
|
pub fn print_stats(&self) {
|
||||||
let allocated = self.blocks_allocated.load(Ordering::Relaxed);
|
let allocated = self.blocks_allocated.load(Ordering::Relaxed);
|
||||||
let freed = self.blocks_freed.load(Ordering::Relaxed);
|
let freed = self.blocks_freed.load(Ordering::Relaxed);
|
||||||
let bytes = self.bytes_transferred.load(Ordering::Relaxed);
|
let bytes = self.bytes_transferred.load(Ordering::Relaxed);
|
||||||
let mmap_usage = self.mmap_buffer_usage.load(Ordering::Relaxed);
|
let mmap_usage = self.mmap_buffer_usage.load(Ordering::Relaxed);
|
||||||
|
|
||||||
log::info!("🚀 Zero-Copy Stats:");
|
tracing::info!(target: "sol_trade_sdk","🚀 Zero-Copy Stats:");
|
||||||
log::info!(" 📦 Blocks: Allocated={}, Freed={}, Active={}",
|
tracing::info!(target: "sol_trade_sdk"," 📦 Blocks: Allocated={}, Freed={}, Active={}",
|
||||||
allocated, freed, allocated.saturating_sub(freed));
|
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);
|
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);
|
mmap_usage, mmap_usage as f64 / 1024.0 / 1024.0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -564,36 +571,36 @@ impl ZeroCopyMemoryManager {
|
|||||||
pub fn new() -> Result<Self> {
|
pub fn new() -> Result<Self> {
|
||||||
let mut shared_pools = Vec::new();
|
let mut shared_pools = Vec::new();
|
||||||
let mut mmap_buffers = Vec::new();
|
let mut mmap_buffers = Vec::new();
|
||||||
|
|
||||||
// 创建不同大小的内存池
|
// 创建不同大小的内存池
|
||||||
// 小块池: 64KB blocks, 1GB total
|
// 小块池: 64KB blocks, 1GB total
|
||||||
shared_pools.push(Arc::new(SharedMemoryPool::new(0, 1024 * 1024 * 1024, 64 * 1024)?));
|
shared_pools.push(Arc::new(SharedMemoryPool::new(0, 1024 * 1024 * 1024, 64 * 1024)?));
|
||||||
// 中块池: 1MB blocks, 4GB total
|
// 中块池: 1MB blocks, 4GB total
|
||||||
shared_pools.push(Arc::new(SharedMemoryPool::new(1, 4 * 1024 * 1024 * 1024, 1024 * 1024)?));
|
shared_pools.push(Arc::new(SharedMemoryPool::new(1, 4 * 1024 * 1024 * 1024, 1024 * 1024)?));
|
||||||
// 大块池: 16MB blocks, 8GB total
|
// 大块池: 16MB blocks, 8GB total
|
||||||
shared_pools.push(Arc::new(SharedMemoryPool::new(2, 8 * 1024 * 1024 * 1024, 16 * 1024 * 1024)?));
|
shared_pools.push(Arc::new(SharedMemoryPool::new(
|
||||||
|
2,
|
||||||
|
8 * 1024 * 1024 * 1024,
|
||||||
|
16 * 1024 * 1024,
|
||||||
|
)?));
|
||||||
|
|
||||||
// 创建内存映射缓冲区
|
// 创建内存映射缓冲区
|
||||||
for i in 0..8 {
|
for i in 0..8 {
|
||||||
mmap_buffers.push(Arc::new(MemoryMappedBuffer::new(i, 256 * 1024 * 1024)?)); // 256MB each
|
mmap_buffers.push(Arc::new(MemoryMappedBuffer::new(i, 256 * 1024 * 1024)?));
|
||||||
|
// 256MB each
|
||||||
}
|
}
|
||||||
|
|
||||||
let dma_manager = Arc::new(DirectMemoryAccessManager::new(16)?); // 16 DMA channels
|
let dma_manager = Arc::new(DirectMemoryAccessManager::new(16)?); // 16 DMA channels
|
||||||
let stats = Arc::new(ZeroCopyStats::new());
|
let stats = Arc::new(ZeroCopyStats::new());
|
||||||
|
|
||||||
log::info!("🚀 Zero-Copy Memory Manager initialized");
|
tracing::info!(target: "sol_trade_sdk","🚀 Zero-Copy Memory Manager initialized");
|
||||||
log::info!(" 📦 Memory Pools: {}", shared_pools.len());
|
tracing::info!(target: "sol_trade_sdk"," 📦 Memory Pools: {}", shared_pools.len());
|
||||||
log::info!(" 💾 Mapped Buffers: {}", mmap_buffers.len());
|
tracing::info!(target: "sol_trade_sdk"," 💾 Mapped Buffers: {}", mmap_buffers.len());
|
||||||
log::info!(" 🔄 DMA Channels: 16");
|
tracing::info!(target: "sol_trade_sdk"," 🔄 DMA Channels: 16");
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self { shared_pools, mmap_buffers, dma_manager, stats })
|
||||||
shared_pools,
|
|
||||||
mmap_buffers,
|
|
||||||
dma_manager,
|
|
||||||
stats,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 分配零拷贝内存块
|
/// 🚀 分配零拷贝内存块
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn allocate(&self, size: usize) -> Option<ZeroCopyBlock> {
|
pub fn allocate(&self, size: usize) -> Option<ZeroCopyBlock> {
|
||||||
@@ -605,7 +612,7 @@ impl ZeroCopyMemoryManager {
|
|||||||
} else {
|
} else {
|
||||||
&self.shared_pools[2] // 大块池
|
&self.shared_pools[2] // 大块池
|
||||||
};
|
};
|
||||||
|
|
||||||
if let Some(block) = pool.allocate_block() {
|
if let Some(block) = pool.allocate_block() {
|
||||||
self.stats.blocks_allocated.fetch_add(1, Ordering::Relaxed);
|
self.stats.blocks_allocated.fetch_add(1, Ordering::Relaxed);
|
||||||
Some(block)
|
Some(block)
|
||||||
@@ -613,7 +620,7 @@ impl ZeroCopyMemoryManager {
|
|||||||
None
|
None
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 释放零拷贝内存块
|
/// 🚀 释放零拷贝内存块
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn deallocate(&self, block: ZeroCopyBlock) {
|
pub fn deallocate(&self, block: ZeroCopyBlock) {
|
||||||
@@ -623,19 +630,19 @@ impl ZeroCopyMemoryManager {
|
|||||||
self.stats.blocks_freed.fetch_add(1, Ordering::Relaxed);
|
self.stats.blocks_freed.fetch_add(1, Ordering::Relaxed);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取内存映射缓冲区
|
/// 获取内存映射缓冲区
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn get_mmap_buffer(&self, buffer_id: usize) -> Option<Arc<MemoryMappedBuffer>> {
|
pub fn get_mmap_buffer(&self, buffer_id: usize) -> Option<Arc<MemoryMappedBuffer>> {
|
||||||
self.mmap_buffers.get(buffer_id).cloned()
|
self.mmap_buffers.get(buffer_id).cloned()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取DMA管理器
|
/// 获取DMA管理器
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn get_dma_manager(&self) -> Arc<DirectMemoryAccessManager> {
|
pub fn get_dma_manager(&self) -> Arc<DirectMemoryAccessManager> {
|
||||||
self.dma_manager.clone()
|
self.dma_manager.clone()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取统计信息
|
/// 获取统计信息
|
||||||
pub fn get_stats(&self) -> Arc<ZeroCopyStats> {
|
pub fn get_stats(&self) -> Arc<ZeroCopyStats> {
|
||||||
self.stats.clone()
|
self.stats.clone()
|
||||||
@@ -645,73 +652,73 @@ impl ZeroCopyMemoryManager {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_shared_memory_pool() -> Result<()> {
|
async fn test_shared_memory_pool() -> Result<()> {
|
||||||
let pool = SharedMemoryPool::new(0, 1024 * 1024, 4096)?;
|
let pool = SharedMemoryPool::new(0, 1024 * 1024, 4096)?;
|
||||||
|
|
||||||
// 测试分配
|
// 测试分配
|
||||||
let block1 = pool.allocate_block().expect("Should allocate block");
|
let block1 = pool.allocate_block().expect("Should allocate block");
|
||||||
assert_eq!(block1.size(), 4096);
|
assert_eq!(block1.size(), 4096);
|
||||||
|
|
||||||
let block2 = pool.allocate_block().expect("Should allocate another block");
|
let block2 = pool.allocate_block().expect("Should allocate another block");
|
||||||
assert_eq!(block2.size(), 4096);
|
assert_eq!(block2.size(), 4096);
|
||||||
|
|
||||||
// 测试释放
|
// 测试释放
|
||||||
pool.deallocate_block(block1);
|
pool.deallocate_block(block1);
|
||||||
pool.deallocate_block(block2);
|
pool.deallocate_block(block2);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_memory_mapped_buffer() -> Result<()> {
|
async fn test_memory_mapped_buffer() -> Result<()> {
|
||||||
let buffer = MemoryMappedBuffer::new(0, 1024 * 1024)?;
|
let buffer = MemoryMappedBuffer::new(0, 1024 * 1024)?;
|
||||||
|
|
||||||
let test_data = b"Hello, Zero-Copy World!";
|
let test_data = b"Hello, Zero-Copy World!";
|
||||||
|
|
||||||
// 测试写入
|
// 测试写入
|
||||||
let written = buffer.write_data(test_data)?;
|
let written = buffer.write_data(test_data)?;
|
||||||
assert_eq!(written, test_data.len());
|
assert_eq!(written, test_data.len());
|
||||||
|
|
||||||
// 测试读取
|
// 测试读取
|
||||||
let mut read_buffer = vec![0u8; test_data.len()];
|
let mut read_buffer = vec![0u8; test_data.len()];
|
||||||
let read = buffer.read_data(&mut read_buffer)?;
|
let read = buffer.read_data(&mut read_buffer)?;
|
||||||
assert_eq!(read, test_data.len());
|
assert_eq!(read, test_data.len());
|
||||||
assert_eq!(&read_buffer, test_data);
|
assert_eq!(&read_buffer, test_data);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_dma_transfer() -> Result<()> {
|
async fn test_dma_transfer() -> Result<()> {
|
||||||
let dma_manager = DirectMemoryAccessManager::new(4)?;
|
let dma_manager = DirectMemoryAccessManager::new(4)?;
|
||||||
|
|
||||||
let src = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
|
let src = vec![1u8, 2, 3, 4, 5, 6, 7, 8];
|
||||||
let mut dst = vec![0u8; 8];
|
let mut dst = vec![0u8; 8];
|
||||||
|
|
||||||
let transferred = dma_manager.dma_transfer(&src, &mut dst).await?;
|
let transferred = dma_manager.dma_transfer(&src, &mut dst).await?;
|
||||||
assert_eq!(transferred, 8);
|
assert_eq!(transferred, 8);
|
||||||
assert_eq!(src, dst);
|
assert_eq!(src, dst);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn test_zero_copy_manager() -> Result<()> {
|
async fn test_zero_copy_manager() -> Result<()> {
|
||||||
let manager = ZeroCopyMemoryManager::new()?;
|
let manager = ZeroCopyMemoryManager::new()?;
|
||||||
|
|
||||||
// 测试小块分配
|
// 测试小块分配
|
||||||
let small_block = manager.allocate(1024).expect("Should allocate small block");
|
let small_block = manager.allocate(1024).expect("Should allocate small block");
|
||||||
assert_eq!(small_block.size(), 65536); // 小块池的块大小
|
assert_eq!(small_block.size(), 65536); // 小块池的块大小
|
||||||
|
|
||||||
// 测试大块分配
|
// 测试大块分配
|
||||||
let large_block = manager.allocate(5 * 1024 * 1024).expect("Should allocate large block");
|
let large_block = manager.allocate(5 * 1024 * 1024).expect("Should allocate large block");
|
||||||
assert_eq!(large_block.size(), 16 * 1024 * 1024); // 大块池的块大小
|
assert_eq!(large_block.size(), 16 * 1024 * 1024); // 大块池的块大小
|
||||||
|
|
||||||
manager.deallocate(small_block);
|
manager.deallocate(small_block);
|
||||||
manager.deallocate(large_block);
|
manager.deallocate(large_block);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+191
-154
@@ -1,44 +1,75 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
use tracing::warn;
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
|
||||||
|
|
||||||
use anyhow::Result;
|
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
|
use anyhow::Result;
|
||||||
|
use bincode::serialize as bincode_serialize;
|
||||||
|
use solana_client::rpc_client::SerializableTransaction;
|
||||||
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::ASTRALANE_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::ASTRALANE_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
|
/// 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,
|
||||||
|
/// Mirrors global `mev_protection`: adds `mev-protect=true` on HTTP sends (QUIC uses :9000 instead).
|
||||||
|
mev_http: bool,
|
||||||
|
http_client: Client,
|
||||||
|
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||||
|
stop_ping: Arc<AtomicBool>,
|
||||||
|
},
|
||||||
|
Quic(Arc<AstralaneQuicClient>),
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct AstralaneClient {
|
pub struct AstralaneClient {
|
||||||
pub endpoint: String,
|
|
||||||
pub auth_token: String,
|
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
pub http_client: Client,
|
backend: AstralaneBackend,
|
||||||
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
|
||||||
pub stop_ping: Arc<AtomicBool>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for AstralaneClient {
|
impl SwqosClientTrait for AstralaneClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
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<()> {
|
async fn send_transactions(
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
for transaction in transactions {
|
||||||
|
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *ASTRALANE_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| ASTRALANE_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *ASTRALANE_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| ASTRALANE_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,160 +79,165 @@ impl SwqosClientTrait for AstralaneClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AstralaneClient {
|
impl AstralaneClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
/// HTTP 提交:`/iris`(Plain)或 `/irisb`(Binary),由 `endpoint` URL 路径区分;`mev_http` 为 true 时附加 `mev-protect=true`。
|
||||||
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String, mev_http: bool) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// Optimized connection pool settings for high performance
|
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
let stop_ping = Arc::new(AtomicBool::new(false));
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
|
||||||
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
|
let client = Self {
|
||||||
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
|
rpc_client: Arc::new(rpc_client),
|
||||||
.http2_keep_alive_interval(Duration::from_secs(10))
|
backend: AstralaneBackend::Http {
|
||||||
.http2_keep_alive_timeout(Duration::from_secs(5))
|
endpoint,
|
||||||
.http2_adaptive_window(true) // Enable adaptive flow control
|
auth_token,
|
||||||
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
|
mev_http,
|
||||||
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
|
http_client,
|
||||||
.build()
|
ping_handle,
|
||||||
.unwrap();
|
stop_ping,
|
||||||
|
},
|
||||||
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)),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Start ping task
|
|
||||||
let client_clone = client.clone();
|
let client_clone = client.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
client_clone.start_ping_task().await;
|
client_clone.start_ping_task().await;
|
||||||
});
|
});
|
||||||
|
|
||||||
client
|
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) {
|
async fn start_ping_task(&self) {
|
||||||
let endpoint = self.endpoint.clone();
|
match &self.backend {
|
||||||
let auth_token = self.auth_token.clone();
|
AstralaneBackend::Http {
|
||||||
let http_client = self.http_client.clone();
|
endpoint,
|
||||||
let stop_ping = self.stop_ping.clone();
|
auth_token,
|
||||||
|
http_client,
|
||||||
let handle = tokio::spawn(async move {
|
ping_handle,
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(60)); // Ping every 60 seconds
|
stop_ping,
|
||||||
|
..
|
||||||
loop {
|
} => {
|
||||||
interval.tick().await;
|
let endpoint = endpoint.clone();
|
||||||
|
let auth_token = auth_token.clone();
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
let http_client = http_client.clone();
|
||||||
break;
|
let ping_handle = ping_handle.clone();
|
||||||
}
|
let stop_ping = stop_ping.clone();
|
||||||
|
let handle = tokio::spawn(async move {
|
||||||
// Send ping request
|
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
loop {
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
interval.tick().await;
|
||||||
eprintln!("Astralane ping request failed: {}", e);
|
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();
|
||||||
}
|
}
|
||||||
|
*guard = Some(handle);
|
||||||
}
|
}
|
||||||
});
|
AstralaneBackend::Quic(_) => {}
|
||||||
|
|
||||||
// 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();
|
|
||||||
}
|
|
||||||
*ping_guard = Some(handle);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 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<()> {
|
async fn send_ping_request(
|
||||||
// Build ping URL by replacing /iris with /gethealth
|
http_client: &Client,
|
||||||
let ping_url = if endpoint.ends_with("/iris") {
|
endpoint: &str,
|
||||||
endpoint.replace("/iris", "/gethealth")
|
auth_token: &str,
|
||||||
} else if endpoint.ends_with("/iris/") {
|
) -> Result<()> {
|
||||||
endpoint.replace("/iris/", "/gethealth")
|
let response = http_client
|
||||||
} else if endpoint.ends_with('/') {
|
.post(endpoint)
|
||||||
format!("{}gethealth", endpoint)
|
.query(&[("api-key", auth_token), ("method", "getHealth")])
|
||||||
} else {
|
.timeout(Duration::from_millis(1500))
|
||||||
format!("{}/gethealth", endpoint)
|
.body(PING_BODY)
|
||||||
};
|
|
||||||
|
|
||||||
// Send GET request to /gethealth endpoint with api_key header
|
|
||||||
let response = http_client.get(&ping_url)
|
|
||||||
.header("api_key", auth_token)
|
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
let status = response.status();
|
||||||
if response.status().is_success() {
|
let _ = response.bytes().await;
|
||||||
// ping successful, connection remains active
|
if !status.is_success() {
|
||||||
// println!("send getHealth to keep connection alive");
|
warn!(target: "sol_trade_sdk", "Astralane ping request returned non-success status: {}", status);
|
||||||
} else {
|
|
||||||
eprintln!("Astralane ping request returned non-success status: {}", response.status());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
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 start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
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!({
|
match &self.backend {
|
||||||
"jsonrpc": "2.0",
|
AstralaneBackend::Http { endpoint, auth_token, mev_http, http_client, .. } => {
|
||||||
"id": 1,
|
let mut req = http_client
|
||||||
"method": "sendTransaction",
|
.post(endpoint)
|
||||||
"params": [
|
.query(&[("api-key", auth_token.as_str()), ("method", "sendTransaction")]);
|
||||||
content,
|
if *mev_http {
|
||||||
{ "encoding": "base64", "skipPreflight": true },
|
req = req.query(&[("mev-protect", "true")]);
|
||||||
{ "mevProtect": false }
|
}
|
||||||
]
|
let response = req
|
||||||
}))?;
|
.header("Content-Type", "application/octet-stream")
|
||||||
|
.body(body_bytes)
|
||||||
// Send request with api_key header
|
.send()
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
.await?;
|
||||||
.body(request_body)
|
let status = response.status();
|
||||||
.header("Content-Type", "application/json")
|
let _ = response.bytes().await;
|
||||||
.header("api_key", &self.auth_token)
|
if status.is_success() {
|
||||||
.send()
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
.await?
|
crate::common::sdk_log::log_swqos_submitted("Astralane", trade_type, start_time.elapsed());
|
||||||
.text()
|
}
|
||||||
.await?;
|
} else {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
// Parse JSON response
|
crate::common::sdk_log::log_swqos_submission_failed("Astralane", trade_type, start_time.elapsed(), format!("status {}", status));
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
}
|
||||||
if response_json.get("result").is_some() {
|
return Err(anyhow::anyhow!("Astralane sendTransaction failed: {}", status));
|
||||||
println!(" [astralane] {} submitted: {:?}", trade_type, start_time.elapsed());
|
}
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
}
|
||||||
eprintln!(" [astralane] {} submission failed: {:?}", trade_type, _error);
|
AstralaneBackend::Quic(quic) => {
|
||||||
|
if let Err(e) = quic.send_transaction(&body_bytes).await {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("Astralane", trade_type, start_time.elapsed(), &e);
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("Astralane", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
eprintln!(" [astralane] {} submission failed: {:?}", trade_type, response_text);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [astralane] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(" [{:width$}] {} confirmation failed: {:?}", "Astralane", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [astralane] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "Astralane", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
|
||||||
|
|
||||||
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?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -209,18 +245,19 @@ impl AstralaneClient {
|
|||||||
|
|
||||||
impl Drop for AstralaneClient {
|
impl Drop for AstralaneClient {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Ensure ping task stops when client is destroyed
|
match &self.backend {
|
||||||
self.stop_ping.store(true, Ordering::Relaxed);
|
AstralaneBackend::Http { stop_ping, ping_handle, .. } => {
|
||||||
|
stop_ping.store(true, Ordering::Relaxed);
|
||||||
// Try to stop ping task immediately
|
let ping_handle = ping_handle.clone();
|
||||||
// Use tokio::spawn to avoid blocking Drop
|
tokio::spawn(async move {
|
||||||
let ping_handle = self.ping_handle.clone();
|
let mut guard = ping_handle.lock().await;
|
||||||
tokio::spawn(async move {
|
if let Some(handle) = guard.as_ref() {
|
||||||
let mut ping_guard = ping_handle.lock().await;
|
handle.abort();
|
||||||
if let Some(handle) = ping_guard.as_ref() {
|
}
|
||||||
handle.abort();
|
*guard = None;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
*ping_guard = None;
|
AstralaneBackend::Quic(_) => {}
|
||||||
});
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,360 @@
|
|||||||
|
//! 内联自 [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::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||||
|
use std::str::FromStr;
|
||||||
|
use std::sync::atomic::{AtomicUsize, Ordering};
|
||||||
|
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,
|
||||||
|
server_candidates: Vec<SocketAddr>,
|
||||||
|
next_server_idx: AtomicUsize,
|
||||||
|
#[allow(dead_code)]
|
||||||
|
api_key: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl AstralaneQuicClient {
|
||||||
|
#[inline]
|
||||||
|
fn astralane_quic_ip_candidates(host: &str, port: u16) -> Vec<SocketAddr> {
|
||||||
|
// Official recommended direct-IP list (faster/more stable than DNS-only for QUIC).
|
||||||
|
// We intentionally avoid fr2/ams2 per prior guidance.
|
||||||
|
// Both port 7000 (standard) and port 9000 (MEV-protected) use the same IPs.
|
||||||
|
match host {
|
||||||
|
"fr.gateway.astralane.io" => vec![
|
||||||
|
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(185, 191, 117, 97)), port),
|
||||||
|
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(45, 139, 132, 160)), port),
|
||||||
|
],
|
||||||
|
"ny.gateway.astralane.io" => {
|
||||||
|
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(64, 130, 45, 19)), port)]
|
||||||
|
}
|
||||||
|
"ams.gateway.astralane.io" => vec![
|
||||||
|
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(64, 130, 43, 43)), port),
|
||||||
|
SocketAddr::new(IpAddr::V4(Ipv4Addr::new(84, 32, 186, 73)), port),
|
||||||
|
],
|
||||||
|
"la.gateway.astralane.io" => {
|
||||||
|
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(74, 118, 142, 151)), port)]
|
||||||
|
}
|
||||||
|
"lim.gateway.astralane.io" => {
|
||||||
|
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(162, 19, 222, 232)), port)]
|
||||||
|
}
|
||||||
|
"sg.gateway.astralane.io" => {
|
||||||
|
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(67, 209, 54, 176)), port)]
|
||||||
|
}
|
||||||
|
"lit.gateway.astralane.io" => {
|
||||||
|
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(84, 32, 97, 47)), port)]
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
Vec::new()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn parse_host_port(server_addr: &str) -> Option<(&str, u16)> {
|
||||||
|
let (host, port_str) = server_addr.rsplit_once(':')?;
|
||||||
|
let port = port_str.parse::<u16>().ok()?;
|
||||||
|
Some((host, port))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Resolve `host:port` and prefer IPv4 result to avoid v6-remote/v4-local mismatch.
|
||||||
|
#[inline]
|
||||||
|
fn resolve_server_candidates(server_addr: &str) -> Result<Vec<SocketAddr>> {
|
||||||
|
if let Ok(addr) = SocketAddr::from_str(server_addr) {
|
||||||
|
return Ok(vec![addr]);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut candidates: Vec<SocketAddr> = Vec::with_capacity(8);
|
||||||
|
if let Some((host, port)) = Self::parse_host_port(server_addr) {
|
||||||
|
candidates.extend(Self::astralane_quic_ip_candidates(host, port));
|
||||||
|
}
|
||||||
|
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
|
let mut addrs: Vec<SocketAddr> = server_addr
|
||||||
|
.to_socket_addrs()
|
||||||
|
.with_context(|| format!("Cannot resolve address: {}", server_addr))?
|
||||||
|
.collect();
|
||||||
|
if addrs.is_empty() && candidates.is_empty() {
|
||||||
|
anyhow::bail!("Cannot resolve address: {}", server_addr);
|
||||||
|
}
|
||||||
|
// QUIC in many bot/VPS environments is primarily IPv4; prefer A over AAAA.
|
||||||
|
addrs.sort_by_key(|a| if a.is_ipv4() { 0 } else { 1 });
|
||||||
|
for addr in addrs {
|
||||||
|
if !candidates.contains(&addr) {
|
||||||
|
candidates.push(addr);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Ok(candidates)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[inline]
|
||||||
|
fn local_bind_for_remote(remote: SocketAddr) -> SocketAddr {
|
||||||
|
match remote.ip() {
|
||||||
|
IpAddr::V4(_) => SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), 0),
|
||||||
|
IpAddr::V6(_) => SocketAddr::new(IpAddr::V6(Ipv6Addr::UNSPECIFIED), 0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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 candidates = Self::resolve_server_candidates(server_addr)
|
||||||
|
.context("Invalid server address")?;
|
||||||
|
let addr = candidates[0];
|
||||||
|
|
||||||
|
info!("[astralane-quic] Building TLS config (CN = api_key)");
|
||||||
|
let client_config = Self::build_client_config(api_key)?;
|
||||||
|
|
||||||
|
let mut endpoint = Endpoint::client(Self::local_bind_for_remote(addr))
|
||||||
|
.context("Failed to create QUIC endpoint")?;
|
||||||
|
endpoint.set_default_client_config(client_config);
|
||||||
|
|
||||||
|
info!("[astralane-quic] Connecting to {} ...", addr);
|
||||||
|
let mut last_err: Option<anyhow::Error> = None;
|
||||||
|
let mut selected_addr = addr;
|
||||||
|
let mut connection_opt: Option<Connection> = None;
|
||||||
|
for candidate in &candidates {
|
||||||
|
selected_addr = *candidate;
|
||||||
|
match endpoint.connect(*candidate, "astralane") {
|
||||||
|
Ok(connecting) => match connecting.await {
|
||||||
|
Ok(conn) => {
|
||||||
|
connection_opt = Some(conn);
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
warn!("[astralane-quic] connect failed for {}: {}", candidate, e);
|
||||||
|
last_err = Some(e.into());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
warn!("[astralane-quic] connect setup failed for {}: {}", candidate, e);
|
||||||
|
last_err = Some(e.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let connection = connection_opt.ok_or_else(|| {
|
||||||
|
last_err.unwrap_or_else(|| anyhow::anyhow!("Failed to connect to Astralane QUIC server"))
|
||||||
|
})?;
|
||||||
|
|
||||||
|
info!("[astralane-quic] Connected at {}", selected_addr);
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
endpoint,
|
||||||
|
connection: Mutex::new(connection),
|
||||||
|
server_addr: selected_addr,
|
||||||
|
server_candidates: candidates,
|
||||||
|
next_server_idx: AtomicUsize::new(0),
|
||||||
|
api_key: api_key.to_string(),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn reconnect_next_candidate(&self) -> Result<Connection> {
|
||||||
|
let total = self.server_candidates.len().max(1);
|
||||||
|
let start = self.next_server_idx.fetch_add(1, Ordering::Relaxed) % total;
|
||||||
|
let mut last_err: Option<anyhow::Error> = None;
|
||||||
|
for offset in 0..total {
|
||||||
|
let idx = (start + offset) % total;
|
||||||
|
let addr = self.server_candidates[idx];
|
||||||
|
match self.endpoint.connect(addr, "astralane") {
|
||||||
|
Ok(connecting) => match connecting.await {
|
||||||
|
Ok(conn) => return Ok(conn),
|
||||||
|
Err(e) => {
|
||||||
|
warn!("[astralane-quic] reconnect failed for {}: {}", addr, e);
|
||||||
|
last_err = Some(e.into());
|
||||||
|
}
|
||||||
|
},
|
||||||
|
Err(e) => {
|
||||||
|
warn!("[astralane-quic] reconnect setup failed for {}: {}", addr, e);
|
||||||
|
last_err = Some(e.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("Failed to reconnect to Astralane QUIC server")))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// 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);
|
||||||
|
let new_conn = self.reconnect_next_candidate().await?;
|
||||||
|
*guard = new_conn.clone();
|
||||||
|
info!("[astralane-quic] Reconnected");
|
||||||
|
}
|
||||||
|
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.reconnect_next_candidate().await?;
|
||||||
|
info!("[astralane-quic] Reconnected");
|
||||||
|
}
|
||||||
|
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,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
+433
-149
@@ -1,44 +1,142 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::{Client, header::{HeaderMap, HeaderValue, CONTENT_TYPE}};
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
use arc_swap::ArcSwap;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
use tonic::transport::Channel;
|
||||||
|
use tonic::metadata::AsciiMetadataValue;
|
||||||
|
|
||||||
|
// Include pre-generated gRPC code
|
||||||
|
pub mod serverpb {
|
||||||
|
include!("pb/serverpb.rs");
|
||||||
|
}
|
||||||
|
|
||||||
|
// gRPC client wrapper
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub struct BlockRazorGrpcClient {
|
||||||
|
channel: Channel,
|
||||||
|
auth_token: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BlockRazorGrpcClient {
|
||||||
|
pub fn new(channel: Channel, auth_token: String) -> Self {
|
||||||
|
Self { channel, auth_token }
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_health(&self) -> Result<String> {
|
||||||
|
let mut client = serverpb::server_client::ServerClient::new(self.channel.clone());
|
||||||
|
let apikey = AsciiMetadataValue::try_from(self.auth_token.as_str())
|
||||||
|
.map_err(|e| anyhow::anyhow!("Invalid API key format: {}", e))?;
|
||||||
|
|
||||||
|
let mut request = tonic::Request::new(serverpb::HealthRequest {});
|
||||||
|
request.metadata_mut().insert("apikey", apikey);
|
||||||
|
|
||||||
|
let response = client.get_health(request).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("gRPC health check failed: {}", e))?;
|
||||||
|
Ok(response.into_inner().status)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
transaction: String,
|
||||||
|
mode: String,
|
||||||
|
safe_window: Option<i32>,
|
||||||
|
revert_protection: bool,
|
||||||
|
) -> Result<String> {
|
||||||
|
// 检查交易数据大小
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor transaction size: {} bytes", transaction.len());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut client = serverpb::server_client::ServerClient::new(self.channel.clone());
|
||||||
|
let apikey = AsciiMetadataValue::try_from(self.auth_token.as_str())
|
||||||
|
.map_err(|e| anyhow::anyhow!("Invalid API key format: {}", e))?;
|
||||||
|
|
||||||
|
let mut request = tonic::Request::new(serverpb::SendRequest {
|
||||||
|
transaction,
|
||||||
|
mode: String::from(mode),
|
||||||
|
safe_window,
|
||||||
|
revert_protection,
|
||||||
|
});
|
||||||
|
request.metadata_mut().insert("apikey", apikey);
|
||||||
|
|
||||||
|
let response = client.send_transaction(request).await
|
||||||
|
.map_err(|e| anyhow::anyhow!("gRPC send transaction failed: {}", e))?;
|
||||||
|
Ok(response.into_inner().signature)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub enum BlockRazorBackend {
|
||||||
|
Grpc {
|
||||||
|
endpoint: String,
|
||||||
|
auth_token: String,
|
||||||
|
grpc_client: Arc<ArcSwap<BlockRazorGrpcClient>>,
|
||||||
|
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||||
|
stop_ping: Arc<AtomicBool>,
|
||||||
|
/// When true, gRPC send_transaction sets revert_protection=true for MEV protection.
|
||||||
|
mev_protection: bool,
|
||||||
|
},
|
||||||
|
Http {
|
||||||
|
endpoint: String,
|
||||||
|
auth_token: String,
|
||||||
|
http_client: Client,
|
||||||
|
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||||
|
stop_ping: Arc<AtomicBool>,
|
||||||
|
/// When true, HTTP request adds revertProtection=true query param for MEV protection.
|
||||||
|
mev_protection: bool,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BlockRazorClient {
|
pub struct BlockRazorClient {
|
||||||
pub endpoint: String,
|
|
||||||
pub auth_token: String,
|
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
pub http_client: Client,
|
backend: BlockRazorBackend,
|
||||||
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
|
||||||
pub stop_ping: Arc<AtomicBool>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for BlockRazorClient {
|
impl SwqosClientTrait for BlockRazorClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
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<()> {
|
async fn send_transactions(
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
for transaction in transactions {
|
||||||
|
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *BLOCKRAZOR_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| BLOCKRAZOR_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *BLOCKRAZOR_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| BLOCKRAZOR_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,181 +146,367 @@ impl SwqosClientTrait for BlockRazorClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl BlockRazorClient {
|
impl BlockRazorClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub async fn new(rpc_url: String, endpoint: String, auth_token: String) -> Result<Self> {
|
||||||
|
// 默认使用 HTTP 模式,避免 gRPC FRAME_SIZE_ERROR
|
||||||
|
Ok(Self::new_http(rpc_url, endpoint, auth_token, false))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn new_grpc(rpc_url: String, endpoint: String, auth_token: String, mev_protection: bool) -> Result<Self> {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
|
||||||
// Optimized connection pool settings for high performance
|
// 配置 Channel,增加连接超时
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
let channel = tonic::transport::Channel::from_shared(endpoint.clone())
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
.map_err(|e| anyhow::anyhow!("Invalid gRPC endpoint: {}", e))?
|
||||||
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
|
.timeout(Duration::from_secs(30))
|
||||||
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
|
.connect()
|
||||||
.http2_keep_alive_interval(Duration::from_secs(10))
|
.await
|
||||||
.http2_keep_alive_timeout(Duration::from_secs(5))
|
.map_err(|e| anyhow::anyhow!("Failed to connect to gRPC endpoint: {}", e))?;
|
||||||
.http2_adaptive_window(true) // Enable adaptive flow control
|
|
||||||
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
|
let grpc_client = Arc::new(ArcSwap::from_pointee(BlockRazorGrpcClient::new(
|
||||||
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
|
channel,
|
||||||
.build()
|
auth_token.clone(),
|
||||||
.unwrap();
|
)));
|
||||||
|
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
|
||||||
let client = Self {
|
let stop_ping = Arc::new(AtomicBool::new(false));
|
||||||
rpc_client: Arc::new(rpc_client),
|
|
||||||
endpoint,
|
let client = Self {
|
||||||
auth_token,
|
rpc_client: Arc::new(rpc_client),
|
||||||
http_client,
|
backend: BlockRazorBackend::Grpc {
|
||||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
endpoint,
|
||||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
auth_token,
|
||||||
|
grpc_client,
|
||||||
|
ping_handle,
|
||||||
|
stop_ping,
|
||||||
|
mev_protection,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
// Start ping task
|
|
||||||
let client_clone = client.clone();
|
let client_clone = client.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
client_clone.start_ping_task().await;
|
client_clone.start_ping_task().await;
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Ok(client)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn new_http(rpc_url: String, endpoint: String, auth_token: String, mev_protection: bool) -> Self {
|
||||||
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
|
let http_client = default_http_client_builder().user_agent("").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: BlockRazorBackend::Http {
|
||||||
|
endpoint,
|
||||||
|
auth_token,
|
||||||
|
http_client,
|
||||||
|
ping_handle,
|
||||||
|
stop_ping,
|
||||||
|
mev_protection,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
let client_clone = client.clone();
|
||||||
|
tokio::spawn(async move {
|
||||||
|
client_clone.start_ping_task().await;
|
||||||
|
});
|
||||||
|
|
||||||
client
|
client
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Start periodic ping task to keep connections active
|
|
||||||
async fn start_ping_task(&self) {
|
async fn start_ping_task(&self) {
|
||||||
let endpoint = self.endpoint.clone();
|
match &self.backend {
|
||||||
let auth_token = self.auth_token.clone();
|
BlockRazorBackend::Grpc {
|
||||||
let http_client = self.http_client.clone();
|
grpc_client,
|
||||||
let stop_ping = self.stop_ping.clone();
|
ping_handle,
|
||||||
|
stop_ping,
|
||||||
let handle = tokio::spawn(async move {
|
endpoint,
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(60)); // Ping every 60 seconds
|
auth_token,
|
||||||
|
..
|
||||||
loop {
|
} => {
|
||||||
interval.tick().await;
|
let grpc_client = grpc_client.clone();
|
||||||
|
let ping_handle = ping_handle.clone();
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
let stop_ping = stop_ping.clone();
|
||||||
break;
|
let endpoint = endpoint.clone();
|
||||||
|
let auth_token = auth_token.clone();
|
||||||
|
|
||||||
|
let handle = tokio::spawn(async move {
|
||||||
|
let mut delay = 1u64;
|
||||||
|
|
||||||
|
// 初始健康检查
|
||||||
|
{
|
||||||
|
let client = grpc_client.load();
|
||||||
|
if let Err(e) = client.get_health().await {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor gRPC initial health check failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||||
|
loop {
|
||||||
|
interval.tick().await;
|
||||||
|
|
||||||
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 健康检查(使用 load() 无锁读取)
|
||||||
|
let client = grpc_client.load();
|
||||||
|
match client.get_health().await {
|
||||||
|
Ok(_) => {
|
||||||
|
delay = 1; // 成功,重置延迟
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor gRPC health check failed: {} - reconnecting in {}s", e, delay);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 等待指数退避时间
|
||||||
|
tokio::time::sleep(Duration::from_secs(delay)).await;
|
||||||
|
delay = (delay * 2).min(60);
|
||||||
|
|
||||||
|
// 尝试重连
|
||||||
|
match Self::reconnect_grpc(&endpoint, &auth_token).await {
|
||||||
|
Ok(new_client) => {
|
||||||
|
// 使用 swap() 无锁替换客户端
|
||||||
|
grpc_client.swap(Arc::new(new_client));
|
||||||
|
delay = 1; // 重置延迟
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor gRPC reconnected successfully");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(reconnect_err) => {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor gRPC reconnect failed: {}", reconnect_err);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut ping_guard = ping_handle.lock().await;
|
||||||
|
if let Some(old_handle) = ping_guard.as_ref() {
|
||||||
|
old_handle.abort();
|
||||||
}
|
}
|
||||||
|
*ping_guard = Some(handle);
|
||||||
// Send ping request
|
}
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
BlockRazorBackend::Http {
|
||||||
eprintln!("BlockRazor ping request failed: {}", e);
|
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 {
|
||||||
|
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor HTTP 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_http_ping(&http_client, &endpoint, &auth_token).await {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("BlockRazor HTTP ping request failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
let mut ping_guard = ping_handle.lock().await;
|
||||||
|
if let Some(old_handle) = ping_guard.as_ref() {
|
||||||
|
old_handle.abort();
|
||||||
}
|
}
|
||||||
|
*ping_guard = Some(handle);
|
||||||
}
|
}
|
||||||
});
|
|
||||||
|
|
||||||
// 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();
|
|
||||||
}
|
|
||||||
*ping_guard = Some(handle);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request to /health endpoint
|
async fn send_http_ping(
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
|
http_client: &Client,
|
||||||
// Build health URL by replacing sendTransaction with health
|
endpoint: &str,
|
||||||
let ping_url = if endpoint.ends_with("sendTransaction") {
|
auth_token: &str,
|
||||||
endpoint.replace("sendTransaction", "health")
|
) -> Result<()> {
|
||||||
} else if endpoint.ends_with("/sendTransaction") {
|
let ping_url = endpoint.replace("/v2/sendTransaction", "/v2/health");
|
||||||
endpoint.replace("/sendTransaction", "/health")
|
let response = http_client
|
||||||
} else {
|
.post(&ping_url)
|
||||||
// Fallback to original logic if endpoint doesn't end with sendTransaction
|
.query(&[("auth", auth_token)])
|
||||||
if endpoint.ends_with('/') {
|
.header("Content-Type", "text/plain")
|
||||||
format!("{}health", endpoint)
|
.timeout(Duration::from_millis(1500))
|
||||||
} else {
|
.body(&[] as &[u8])
|
||||||
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"));
|
|
||||||
|
|
||||||
// Send GET request to /health endpoint with headers
|
|
||||||
let response = http_client.get(&ping_url)
|
|
||||||
.headers(headers)
|
|
||||||
.send()
|
.send()
|
||||||
.await?;
|
.await?;
|
||||||
|
let status = response.status();
|
||||||
if response.status().is_success() {
|
let _ = response.bytes().await;
|
||||||
// ping successful, connection remains active
|
if !status.is_success() {
|
||||||
// Can optionally log, but to reduce noise, not printing here
|
eprintln!("BlockRazor HTTP ping request failed with status: {}", status);
|
||||||
} else {
|
|
||||||
eprintln!("BlockRazor ping request failed with status: {}", response.status());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
/// 重新建立 gRPC 连接
|
||||||
|
async fn reconnect_grpc(endpoint: &str, auth_token: &str) -> Result<BlockRazorGrpcClient> {
|
||||||
|
let channel = tonic::transport::Channel::from_shared(endpoint.to_string())
|
||||||
|
.map_err(|e| anyhow::anyhow!("Invalid gRPC endpoint: {}", e))?
|
||||||
|
.timeout(Duration::from_secs(30))
|
||||||
|
.connect()
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("Failed to reconnect to gRPC endpoint: {}", e))?;
|
||||||
|
|
||||||
|
Ok(BlockRazorGrpcClient::new(channel, auth_token.to_string()))
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_transaction_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
|
||||||
|
|
||||||
// BlockRazor使用fast模式的请求格式
|
match &self.backend {
|
||||||
let request_body = serde_json::to_string(&json!({
|
BlockRazorBackend::Grpc {
|
||||||
"transaction": content,
|
grpc_client,
|
||||||
"mode": "fast"
|
mev_protection,
|
||||||
}))?;
|
..
|
||||||
|
} => {
|
||||||
|
let (content, _signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// BlockRazor使用apikey header
|
// 使用 load() 无锁获取客户端引用
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let client = grpc_client.load();
|
||||||
.body(request_body)
|
let signature = client.send_transaction(
|
||||||
.header("Content-Type", "application/json")
|
content,
|
||||||
.header("apikey", &self.auth_token)
|
// mev_protection=true: sandwichMitigation mode skips blacklisted Leader slots (MEV protection).
|
||||||
.send()
|
// revert_protection is unrelated to MEV; keep false.
|
||||||
.await?
|
if *mev_protection { "sandwichMitigation".to_string() } else { "fast".to_string() },
|
||||||
.text()
|
None,
|
||||||
.await?;
|
false,
|
||||||
|
).await;
|
||||||
|
match signature {
|
||||||
|
Ok(sig) => {
|
||||||
|
if !sig.is_empty() {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("BlockRazor", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), "empty signature".to_string());
|
||||||
|
}
|
||||||
|
return Err(anyhow::anyhow!("BlockRazor gRPC returned empty signature"));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), format!("gRPC error: {}", e));
|
||||||
|
}
|
||||||
|
return Err(anyhow::anyhow!("BlockRazor gRPC sendTransaction failed: {}", e));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
BlockRazorBackend::Http {
|
||||||
|
endpoint,
|
||||||
|
auth_token,
|
||||||
|
http_client,
|
||||||
|
mev_protection,
|
||||||
|
..
|
||||||
|
} => {
|
||||||
|
let (content, _signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Parse JSON response
|
let mut query_params: Vec<(&str, &str)> = vec![
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
("auth", auth_token.as_str()),
|
||||||
if response_json.get("result").is_some() || response_json.get("signature").is_some() {
|
// mev_protection=true: sandwichMitigation mode skips blacklisted Leader slots (MEV protection).
|
||||||
println!(" [blockrazor] {} submitted: {:?}", trade_type, start_time.elapsed());
|
// revertProtection is unrelated to MEV; not set.
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
("mode", if *mev_protection { "sandwichMitigation" } else { "fast" }),
|
||||||
eprintln!(" [blockrazor] {} submission failed: {:?}", trade_type, _error);
|
];
|
||||||
|
|
||||||
|
let response = http_client
|
||||||
|
.post(endpoint)
|
||||||
|
.query(&query_params)
|
||||||
|
.header("Content-Type", "text/plain")
|
||||||
|
.body(content)
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
|
||||||
|
let status = response.status();
|
||||||
|
if status.is_success() {
|
||||||
|
let _ = response.bytes().await;
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("blockrazor", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
let body = response.text().await.unwrap_or_default();
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("blockrazor", trade_type, start_time.elapsed(), format!("status {} body: {}", status, body));
|
||||||
|
}
|
||||||
|
return Err(anyhow::anyhow!(
|
||||||
|
"BlockRazor HTTP sendTransaction failed: status {} body: {}",
|
||||||
|
status,
|
||||||
|
body
|
||||||
|
));
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
eprintln!(" [blockrazor] {} submission failed: {:?}", trade_type, response_text);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time = Instant::now();
|
||||||
|
let signature = transaction.signatures[0];
|
||||||
|
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [blockrazor] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"blockrazor",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [blockrazor] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "blockrazor", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
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?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for BlockRazorClient {
|
impl Drop for BlockRazorClient {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Ensure ping task stops when client is destroyed
|
match &self.backend {
|
||||||
self.stop_ping.store(true, Ordering::Relaxed);
|
BlockRazorBackend::Grpc { stop_ping, ping_handle, .. } | BlockRazorBackend::Http { stop_ping, ping_handle, .. } => {
|
||||||
|
stop_ping.store(true, Ordering::Relaxed);
|
||||||
// Try to stop ping task immediately
|
|
||||||
// Use tokio::spawn to avoid blocking Drop
|
let ping_handle = ping_handle.clone();
|
||||||
let ping_handle = self.ping_handle.clone();
|
tokio::spawn(async move {
|
||||||
tokio::spawn(async move {
|
let mut ping_guard = ping_handle.lock().await;
|
||||||
let mut ping_guard = ping_handle.lock().await;
|
if let Some(handle) = ping_guard.as_ref() {
|
||||||
if let Some(handle) = ping_guard.as_ref() {
|
handle.abort();
|
||||||
handle.abort();
|
}
|
||||||
|
*ping_guard = None;
|
||||||
|
});
|
||||||
}
|
}
|
||||||
*ping_guard = None;
|
}
|
||||||
});
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+94
-64
@@ -1,19 +1,21 @@
|
|||||||
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode, FormatBase64VersionedTransaction};
|
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;
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::BLOX_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::BLOX_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BloxrouteClient {
|
pub struct BloxrouteClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -24,16 +26,29 @@ pub struct BloxrouteClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for BloxrouteClient {
|
impl SwqosClientTrait for BloxrouteClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *BLOX_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| BLOX_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *BLOX_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| BLOX_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -45,106 +60,121 @@ impl SwqosClientTrait for BloxrouteClient {
|
|||||||
impl BloxrouteClient {
|
impl BloxrouteClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder()
|
||||||
// Optimized connection pool settings for high performance
|
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
.pool_idle_timeout(Duration::from_secs(120))
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
.pool_max_idle_per_host(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()
|
.build()
|
||||||
.unwrap();
|
.unwrap();
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let body = serde_json::json!({
|
// Single format! for body to avoid json! + to_string() double allocation
|
||||||
"transaction": {
|
let body = format!(
|
||||||
"content": content,
|
r#"{{"transaction":{{"content":"{}"}},"frontRunningProtection":false,"useStakedRPCs":true}}"#,
|
||||||
},
|
content
|
||||||
"frontRunningProtection": false,
|
);
|
||||||
"useStakedRPCs": true,
|
|
||||||
});
|
|
||||||
|
|
||||||
let endpoint = format!("{}/api/v2/submit", self.endpoint);
|
let endpoint = format!("{}/api/v2/submit", self.endpoint);
|
||||||
let response_text = self.http_client.post(&endpoint)
|
let response_text = self
|
||||||
.body(body.to_string())
|
.http_client
|
||||||
|
.post(&endpoint)
|
||||||
|
.body(body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Authorization", self.auth_token.clone())
|
.header("Authorization", self.auth_token.as_str())
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await?
|
||||||
.text()
|
.text()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// 5. Use `serde_json::from_str()` to parse JSON, reducing extra wait from `.json().await?`
|
// 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 let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [bloxroute] {} submitted: {:?}", trade_type, start_time.elapsed());
|
if response_json.get("result").is_some() {
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
crate::common::sdk_log::log_swqos_submitted("bloxroute", trade_type, start_time.elapsed());
|
||||||
eprintln!(" [bloxroute] {} submission failed: {:?}", trade_type, _error);
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
|
eprintln!(" [bloxroute] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [bloxroute] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("bloxroute", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [bloxroute] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"bloxroute",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [bloxroute] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "bloxroute", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
_wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
|
|
||||||
let body = serde_json::json!({
|
let contents = serialization::serialize_transactions_batch_sync(
|
||||||
"entries": transactions
|
transactions.as_slice(),
|
||||||
.iter()
|
UiTransactionEncoding::Base64,
|
||||||
.map(|tx| {
|
)?;
|
||||||
serde_json::json!({
|
let entries: String = contents
|
||||||
"transaction": {
|
.iter()
|
||||||
"content": tx.to_base64_string(),
|
.map(|c| format!(r#"{{"transaction":{{"content":"{}"}}}}"#, c))
|
||||||
},
|
.collect::<Vec<_>>()
|
||||||
})
|
.join(",");
|
||||||
})
|
let body = format!(r#"{{"entries":[{}]}}"#, entries);
|
||||||
.collect::<Vec<_>>(),
|
|
||||||
});
|
|
||||||
|
|
||||||
let endpoint = format!("{}/api/v2/submit-batch", self.endpoint);
|
let endpoint = format!("{}/api/v2/submit-batch", self.endpoint);
|
||||||
let response_text = self.http_client.post(&endpoint)
|
let response_text = self
|
||||||
.body(body.to_string())
|
.http_client
|
||||||
|
.post(&endpoint)
|
||||||
|
.body(body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Authorization", self.auth_token.clone())
|
.header("Authorization", self.auth_token.as_str())
|
||||||
.send()
|
.send()
|
||||||
.await?
|
.await?
|
||||||
.text()
|
.text()
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
if response_json.get("result").is_some() {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
println!(" bloxroute {} submitted: {:?}", trade_type, start_time.elapsed());
|
if response_json.get("result").is_some() {
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
println!(" bloxroute {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||||
eprintln!(" bloxroute {} submission failed: {:?}", trade_type, _error);
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
|
eprintln!(" bloxroute {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+104
-54
@@ -1,4 +1,5 @@
|
|||||||
use crate::common::types::SolanaRpcClient;
|
use crate::common::types::SolanaRpcClient;
|
||||||
|
use crate::swqos::serialization;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use base64::engine::general_purpose::{self, STANDARD};
|
use base64::engine::general_purpose::{self, STANDARD};
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
@@ -16,6 +17,36 @@ use std::str::FromStr;
|
|||||||
use std::time::{Duration, Instant};
|
use std::time::{Duration, Instant};
|
||||||
use tokio::time::sleep;
|
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)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct TradeError {
|
pub struct TradeError {
|
||||||
pub code: u32,
|
pub code: u32,
|
||||||
@@ -40,7 +71,7 @@ impl From<anyhow::Error> for TradeError {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// 使用高性能序列化
|
// High-performance serialization
|
||||||
|
|
||||||
pub trait FormatBase64VersionedTransaction {
|
pub trait FormatBase64VersionedTransaction {
|
||||||
fn to_base64_string(&self) -> String;
|
fn to_base64_string(&self) -> String;
|
||||||
@@ -58,51 +89,68 @@ pub async fn poll_transaction_confirmation(
|
|||||||
txt_sig: Signature,
|
txt_sig: Signature,
|
||||||
wait_confirmation: bool,
|
wait_confirmation: bool,
|
||||||
) -> Result<Signature> {
|
) -> Result<Signature> {
|
||||||
// 如果不需要等待确认,立即返回签名
|
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 {
|
if !wait_confirmation {
|
||||||
return Ok(txt_sig);
|
return Ok(signatures[0]);
|
||||||
}
|
}
|
||||||
|
|
||||||
let timeout: Duration = Duration::from_secs(15); // 🔧 增加到15秒,避免网络拥堵时超时
|
let timeout: Duration = Duration::from_secs(15);
|
||||||
let interval: Duration = Duration::from_millis(1000);
|
let interval: Duration = Duration::from_millis(1000);
|
||||||
let start: Instant = Instant::now();
|
let start: Instant = Instant::now();
|
||||||
let mut poll_count = 0u32;
|
let mut poll_count = 0u32;
|
||||||
|
// Track which signature landed (confirmed or failed on-chain)
|
||||||
|
let mut landed_sig: Option<Signature> = None;
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
if start.elapsed() >= timeout {
|
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;
|
poll_count += 1;
|
||||||
|
|
||||||
let status = rpc.get_signature_statuses(&[txt_sig]).await?;
|
let status = rpc.get_signature_statuses(signatures).await?;
|
||||||
match status.value[0].clone() {
|
// Check all signatures for any that confirmed successfully
|
||||||
Some(status) => {
|
for (i, maybe_status) in status.value.iter().enumerate() {
|
||||||
if status.err.is_none()
|
if let Some(s) = maybe_status {
|
||||||
&& (status.confirmation_status
|
if s.err.is_none()
|
||||||
== Some(TransactionConfirmationStatus::Confirmed)
|
&& (s.confirmation_status == Some(TransactionConfirmationStatus::Confirmed)
|
||||||
|| status.confirmation_status
|
|| s.confirmation_status == Some(TransactionConfirmationStatus::Finalized))
|
||||||
== Some(TransactionConfirmationStatus::Finalized))
|
|
||||||
{
|
{
|
||||||
return Ok(txt_sig);
|
return Ok(signatures[i]);
|
||||||
}
|
}
|
||||||
// 如果 getSignatureStatuses 返回了错误,立即获取详细信息
|
// Track the first signature that landed on-chain (even if errored)
|
||||||
if status.err.is_some() {
|
if landed_sig.is_none() {
|
||||||
// 直接跳转到获取交易详情
|
landed_sig = Some(signatures[i]);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
|
||||||
// 交易还未上链,继续等待,不调用 getTransaction
|
|
||||||
sleep(interval).await;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// 优化:只在以下情况调用 getTransaction
|
// If no signature has any status yet, keep waiting
|
||||||
// 1. getSignatureStatuses 返回了错误
|
if landed_sig.is_none() {
|
||||||
// 2. 或者已经轮询了较长时间(超过10次,即10秒)
|
sleep(interval).await;
|
||||||
let should_get_transaction = status.value[0].as_ref().map(|s| s.err.is_some()).unwrap_or(false)
|
continue;
|
||||||
|| poll_count >= 10;
|
}
|
||||||
|
|
||||||
|
let landed = landed_sig.unwrap();
|
||||||
|
let should_get_transaction = poll_count >= 10;
|
||||||
|
|
||||||
if !should_get_transaction {
|
if !should_get_transaction {
|
||||||
sleep(interval).await;
|
sleep(interval).await;
|
||||||
@@ -111,7 +159,7 @@ pub async fn poll_transaction_confirmation(
|
|||||||
|
|
||||||
let tx_details = match rpc
|
let tx_details = match rpc
|
||||||
.get_transaction_with_config(
|
.get_transaction_with_config(
|
||||||
&txt_sig,
|
&landed,
|
||||||
RpcTransactionConfig {
|
RpcTransactionConfig {
|
||||||
encoding: Some(UiTransactionEncoding::JsonParsed),
|
encoding: Some(UiTransactionEncoding::JsonParsed),
|
||||||
max_supported_transaction_version: Some(0),
|
max_supported_transaction_version: Some(0),
|
||||||
@@ -122,7 +170,7 @@ pub async fn poll_transaction_confirmation(
|
|||||||
{
|
{
|
||||||
Ok(details) => details,
|
Ok(details) => details,
|
||||||
Err(_) => {
|
Err(_) => {
|
||||||
// 交易可能还未上链,继续等待
|
// Tx may not be on chain yet, keep waiting
|
||||||
sleep(interval).await;
|
sleep(interval).await;
|
||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
@@ -134,9 +182,9 @@ pub async fn poll_transaction_confirmation(
|
|||||||
} else {
|
} else {
|
||||||
let meta = meta.unwrap();
|
let meta = meta.unwrap();
|
||||||
if meta.err.is_none() {
|
if meta.err.is_none() {
|
||||||
return Ok(txt_sig);
|
return Ok(landed);
|
||||||
} else {
|
} else {
|
||||||
// 从 log_messages 中提取错误信息
|
// Extract error message from log_messages
|
||||||
let mut error_msg = String::new();
|
let mut error_msg = String::new();
|
||||||
if let solana_transaction_status::option_serializer::OptionSerializer::Some(logs) =
|
if let solana_transaction_status::option_serializer::OptionSerializer::Some(logs) =
|
||||||
&meta.log_messages
|
&meta.log_messages
|
||||||
@@ -161,13 +209,13 @@ pub async fn poll_transaction_confirmation(
|
|||||||
let ui_err = meta.err.unwrap();
|
let ui_err = meta.err.unwrap();
|
||||||
let tx_err: TransactionError =
|
let tx_err: TransactionError =
|
||||||
serde_json::from_value(serde_json::to_value(&ui_err)?)?;
|
serde_json::from_value(serde_json::to_value(&ui_err)?)?;
|
||||||
|
|
||||||
// 直接使用Solana原生的InstructionError中的错误码
|
// Use Solana InstructionError codes directly
|
||||||
let mut code = 0u32;
|
let mut code = 0u32;
|
||||||
let mut index = None;
|
let mut index = None;
|
||||||
match &tx_err {
|
match &tx_err {
|
||||||
TransactionError::InstructionError(i, i_error) => {
|
TransactionError::InstructionError(i, i_error) => {
|
||||||
// 直接匹配所有InstructionError类型,Custom也是其中之一
|
// Match all InstructionError variants including Custom
|
||||||
code = match i_error {
|
code = match i_error {
|
||||||
solana_sdk::instruction::InstructionError::Custom(c) => *c,
|
solana_sdk::instruction::InstructionError::Custom(c) => *c,
|
||||||
solana_sdk::instruction::InstructionError::GenericError => 1,
|
solana_sdk::instruction::InstructionError::GenericError => 1,
|
||||||
@@ -180,13 +228,13 @@ pub async fn poll_transaction_confirmation(
|
|||||||
solana_sdk::instruction::InstructionError::MissingRequiredSignature => 8,
|
solana_sdk::instruction::InstructionError::MissingRequiredSignature => 8,
|
||||||
solana_sdk::instruction::InstructionError::AccountAlreadyInitialized => 9,
|
solana_sdk::instruction::InstructionError::AccountAlreadyInitialized => 9,
|
||||||
solana_sdk::instruction::InstructionError::UninitializedAccount => 10,
|
solana_sdk::instruction::InstructionError::UninitializedAccount => 10,
|
||||||
_ => 999, // 其他未知错误
|
_ => 999, // Other unknown errors
|
||||||
};
|
};
|
||||||
index = Some(*i);
|
index = Some(*i);
|
||||||
}
|
}
|
||||||
_ => {}
|
_ => {}
|
||||||
}
|
}
|
||||||
|
|
||||||
return Err(anyhow::Error::new(TradeError {
|
return Err(anyhow::Error::new(TradeError {
|
||||||
code: code,
|
code: code,
|
||||||
message: format!("{} {:?}", tx_err, error_msg),
|
message: format!("{} {:?}", tx_err, error_msg),
|
||||||
@@ -197,12 +245,17 @@ pub async fn poll_transaction_confirmation(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_nb_transaction(client: Client, endpoint: &str, auth_token: &str, transaction: &Transaction) -> Result<Signature, anyhow::Error> {
|
pub async fn send_nb_transaction(
|
||||||
// 序列化交易
|
client: Client,
|
||||||
|
endpoint: &str,
|
||||||
|
auth_token: &str,
|
||||||
|
transaction: &Transaction,
|
||||||
|
) -> Result<Signature, anyhow::Error> {
|
||||||
|
// Serialize transaction
|
||||||
let serialized = bincode::serialize(transaction)
|
let serialized = bincode::serialize(transaction)
|
||||||
.map_err(|e| anyhow::anyhow!("Transaction serialization failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Transaction serialization failed: {}", e))?;
|
||||||
|
|
||||||
// Base64编码
|
// Base64 encode
|
||||||
let encoded = STANDARD.encode(serialized);
|
let encoded = STANDARD.encode(serialized);
|
||||||
|
|
||||||
let request_data = json!({
|
let request_data = json!({
|
||||||
@@ -222,18 +275,21 @@ pub async fn send_nb_transaction(client: Client, endpoint: &str, auth_token: &st
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("Request failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Request failed: {}", e))?;
|
||||||
|
|
||||||
let resp = response.json::<serde_json::Value>().await
|
let resp = response
|
||||||
|
.json::<serde_json::Value>()
|
||||||
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("Response parsing failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Response parsing failed: {}", e))?;
|
||||||
|
|
||||||
if let Some(reason) = resp["reason"].as_str() {
|
if let Some(reason) = resp["reason"].as_str() {
|
||||||
return Err(anyhow::anyhow!(reason.to_string()));
|
return Err(anyhow::anyhow!(reason.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let signature = resp["signature"].as_str()
|
let signature = resp["signature"]
|
||||||
|
.as_str()
|
||||||
.ok_or_else(|| anyhow::anyhow!("Missing signature field in response"))?;
|
.ok_or_else(|| anyhow::anyhow!("Missing signature field in response"))?;
|
||||||
|
|
||||||
let signature = Signature::from_str(signature)
|
let signature =
|
||||||
.map_err(|e| anyhow::anyhow!("Invalid signature: {}", e))?;
|
Signature::from_str(signature).map_err(|e| anyhow::anyhow!("Invalid signature: {}", e))?;
|
||||||
|
|
||||||
Ok(signature)
|
Ok(signature)
|
||||||
}
|
}
|
||||||
@@ -250,18 +306,12 @@ pub async fn serialize_and_encode(
|
|||||||
Ok(serialized)
|
Ok(serialized)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn serialize_transaction_and_encode(
|
/// Sync serialize and encode; uses buffer pool when possible for lower allocs and latency.
|
||||||
|
pub fn serialize_transaction_and_encode(
|
||||||
transaction: &impl SerializableTransaction,
|
transaction: &impl SerializableTransaction,
|
||||||
encoding: UiTransactionEncoding,
|
encoding: UiTransactionEncoding,
|
||||||
) -> Result<(String, Signature)> {
|
) -> Result<(String, Signature)> {
|
||||||
let signature = transaction.get_signature();
|
serialization::serialize_transaction_sync(transaction, encoding)
|
||||||
let serialized_tx = serialize(transaction)?;
|
|
||||||
let serialized = match encoding {
|
|
||||||
UiTransactionEncoding::Base58 => bs58::encode(serialized_tx).into_string(),
|
|
||||||
UiTransactionEncoding::Base64 => STANDARD.encode(serialized_tx),
|
|
||||||
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
|
||||||
};
|
|
||||||
Ok((serialized, *signature))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn serialize_smart_transaction_and_encode(
|
pub async fn serialize_smart_transaction_and_encode(
|
||||||
@@ -276,4 +326,4 @@ pub async fn serialize_smart_transaction_and_encode(
|
|||||||
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
||||||
};
|
};
|
||||||
Ok((serialized, *signature))
|
Ok((serialized, *signature))
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-31
@@ -1,20 +1,20 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::FLASHBLOCK_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::FLASHBLOCK_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FlashBlockClient {
|
pub struct FlashBlockClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -25,16 +25,29 @@ pub struct FlashBlockClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for FlashBlockClient {
|
impl SwqosClientTrait for FlashBlockClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *FLASHBLOCK_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| FLASHBLOCK_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *FLASHBLOCK_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| FLASHBLOCK_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,25 +59,19 @@ impl SwqosClientTrait for FlashBlockClient {
|
|||||||
impl FlashBlockClient {
|
impl FlashBlockClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// 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();
|
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// FlashBlock API format
|
// FlashBlock API format
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -74,7 +81,9 @@ impl FlashBlockClient {
|
|||||||
let url = format!("{}/api/v2/submit-batch", self.endpoint);
|
let url = format!("{}/api/v2/submit-batch", self.endpoint);
|
||||||
|
|
||||||
// Send request to FlashBlock
|
// Send request to FlashBlock
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Authorization", &self.auth_token)
|
.header("Authorization", &self.auth_token)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
@@ -88,12 +97,12 @@ impl FlashBlockClient {
|
|||||||
// Parse response
|
// Parse response
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("success").is_some() || response_json.get("result").is_some() {
|
if response_json.get("success").is_some() || response_json.get("result").is_some() {
|
||||||
println!(" [FlashBlock] {} submitted: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submitted("FlashBlock", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
eprintln!(" [FlashBlock] {} submission failed: {:?}", trade_type, _error);
|
eprintln!(" [FlashBlock] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!(" [FlashBlock] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("FlashBlock", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
@@ -101,19 +110,30 @@ impl FlashBlockClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [FlashBlock] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"FlashBlock",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [FlashBlock] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "FlashBlock", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,204 @@
|
|||||||
|
//! 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 after {:?} status={} body={}",
|
||||||
|
trade_type, start_time.elapsed(), 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() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("helius", trade_type, start_time.elapsed(), 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() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("helius", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
|
} else if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("helius", trade_type, start_time.elapsed(), 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!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"helius",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return Err(e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(" [{:width$}] {} confirmed: {:?}", "helius", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
|
}
|
||||||
|
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
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+45
-37
@@ -1,21 +1,21 @@
|
|||||||
|
use crate::swqos::common::{
|
||||||
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode, FormatBase64VersionedTransaction};
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
FormatBase64VersionedTransaction,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::JITO_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::JITO_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
pub struct JitoClient {
|
pub struct JitoClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
pub auth_token: String,
|
pub auth_token: String,
|
||||||
@@ -25,11 +25,21 @@ pub struct JitoClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for JitoClient {
|
impl SwqosClientTrait for JitoClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction_impl(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<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions_impl(trade_type, transactions, wait_confirmation).await
|
self.send_transactions_impl(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,25 +59,19 @@ impl SwqosClientTrait for JitoClient {
|
|||||||
impl JitoClient {
|
impl JitoClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// 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();
|
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction_impl(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -89,8 +93,7 @@ impl JitoClient {
|
|||||||
let response = if self.auth_token.is_empty() {
|
let response = if self.auth_token.is_empty() {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint)
|
||||||
} else {
|
} else {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint).header("x-jito-auth", &self.auth_token)
|
||||||
.header("x-jito-auth", &self.auth_token)
|
|
||||||
};
|
};
|
||||||
let response_text = response
|
let response_text = response
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
@@ -102,12 +105,12 @@ impl JitoClient {
|
|||||||
|
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if response_json.get("result").is_some() {
|
||||||
println!(" [jito] {} submitted: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submitted("jito", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
eprintln!(" [jito] {} submission failed: {:?}", trade_type, _error);
|
eprintln!(" [jito] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!(" [jito] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("jito", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
@@ -115,21 +118,27 @@ impl JitoClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [jito] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmation failed: {:?}", "jito", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [jito] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "jito", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions_impl(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, _wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
_wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let txs_base64 = transactions.iter().map(|tx| tx.to_base64_string()).collect::<Vec<String>>();
|
let txs_base64 =
|
||||||
|
transactions.iter().map(|tx| tx.to_base64_string()).collect::<Vec<String>>();
|
||||||
let body = serde_json::json!({
|
let body = serde_json::json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"method": "sendBundle",
|
"method": "sendBundle",
|
||||||
@@ -148,8 +157,7 @@ impl JitoClient {
|
|||||||
let response = if self.auth_token.is_empty() {
|
let response = if self.auth_token.is_empty() {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint)
|
||||||
} else {
|
} else {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint).header("x-jito-auth", &self.auth_token)
|
||||||
.header("x-jito-auth", &self.auth_token)
|
|
||||||
};
|
};
|
||||||
let response_text = response
|
let response_text = response
|
||||||
.body(body.to_string())
|
.body(body.to_string())
|
||||||
@@ -163,10 +171,10 @@ impl JitoClient {
|
|||||||
if response_json.get("result").is_some() {
|
if response_json.get("result").is_some() {
|
||||||
println!(" jito {} submitted: {:?}", trade_type, start_time.elapsed());
|
println!(" jito {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
eprintln!(" jito {} submission failed: {:?}", trade_type, _error);
|
eprintln!(" jito {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+51
-30
@@ -1,16 +1,17 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::LIGHTSPEED_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::LIGHTSPEED_TIP_ACCOUNTS};
|
||||||
|
|
||||||
@@ -24,16 +25,29 @@ pub struct LightspeedClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for LightspeedClient {
|
impl SwqosClientTrait for LightspeedClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *LIGHTSPEED_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| LIGHTSPEED_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *LIGHTSPEED_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| LIGHTSPEED_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -47,25 +61,19 @@ impl LightspeedClient {
|
|||||||
// Lightspeed endpoint should already include /lightspeed path
|
// Lightspeed endpoint should already include /lightspeed path
|
||||||
// Format: https://<tier>.rpc.solanavibestation.com/lightspeed?api_key=<key>
|
// Format: https://<tier>.rpc.solanavibestation.com/lightspeed?api_key=<key>
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// 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();
|
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Lightspeed uses standard Solana JSON-RPC format for sendTransaction
|
// Lightspeed uses standard Solana JSON-RPC format for sendTransaction
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -83,7 +91,9 @@ impl LightspeedClient {
|
|||||||
]
|
]
|
||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.send()
|
.send()
|
||||||
@@ -93,12 +103,12 @@ impl LightspeedClient {
|
|||||||
|
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if response_json.get("result").is_some() {
|
||||||
println!(" [lightspeed] {} submitted: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submitted("lightspeed", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
eprintln!(" [lightspeed] {} submission failed: {:?}", trade_type, _error);
|
crate::common::sdk_log::log_swqos_submission_failed("lightspeed", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!(" [lightspeed] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("lightspeed", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
@@ -106,19 +116,30 @@ impl LightspeedClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [lightspeed] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"lightspeed",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [lightspeed] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "lightspeed", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+294
-148
@@ -1,73 +1,91 @@
|
|||||||
|
pub mod astralane;
|
||||||
|
pub mod astralane_quic;
|
||||||
|
pub mod blockrazor;
|
||||||
|
pub mod bloxroute;
|
||||||
pub mod common;
|
pub mod common;
|
||||||
|
pub mod flashblock;
|
||||||
|
pub mod helius;
|
||||||
|
pub mod jito;
|
||||||
|
pub mod lightspeed;
|
||||||
|
pub mod nextblock;
|
||||||
|
pub mod node1;
|
||||||
|
pub mod node1_quic;
|
||||||
pub mod serialization;
|
pub mod serialization;
|
||||||
pub mod solana_rpc;
|
pub mod solana_rpc;
|
||||||
pub mod jito;
|
|
||||||
pub mod nextblock;
|
|
||||||
pub mod zeroslot;
|
|
||||||
pub mod temporal;
|
|
||||||
pub mod bloxroute;
|
|
||||||
pub mod node1;
|
|
||||||
pub mod flashblock;
|
|
||||||
pub mod blockrazor;
|
|
||||||
pub mod astralane;
|
|
||||||
pub mod stellium;
|
|
||||||
pub mod lightspeed;
|
|
||||||
pub mod soyas;
|
pub mod soyas;
|
||||||
pub mod speedlanding;
|
pub mod speedlanding;
|
||||||
|
pub mod stellium;
|
||||||
|
pub mod temporal;
|
||||||
|
pub mod zeroslot;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use tokio::sync::RwLock;
|
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
common::SolanaRpcClient,
|
common::SolanaRpcClient,
|
||||||
constants::swqos::{
|
constants::swqos::{
|
||||||
SWQOS_ENDPOINTS_BLOX,
|
SWQOS_ENDPOINTS_ASTRALANE_BINARY, SWQOS_ENDPOINTS_ASTRALANE_PLAIN,
|
||||||
SWQOS_ENDPOINTS_JITO,
|
SWQOS_ENDPOINTS_ASTRALANE_QUIC, SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV,
|
||||||
SWQOS_ENDPOINTS_NEXTBLOCK,
|
|
||||||
SWQOS_ENDPOINTS_TEMPORAL,
|
|
||||||
SWQOS_ENDPOINTS_ZERO_SLOT,
|
|
||||||
SWQOS_ENDPOINTS_NODE1,
|
|
||||||
SWQOS_ENDPOINTS_FLASHBLOCK,
|
|
||||||
SWQOS_ENDPOINTS_BLOCKRAZOR,
|
SWQOS_ENDPOINTS_BLOCKRAZOR,
|
||||||
SWQOS_ENDPOINTS_ASTRALANE,
|
SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC, SWQOS_ENDPOINTS_BLOX, SWQOS_ENDPOINTS_FLASHBLOCK,
|
||||||
SWQOS_ENDPOINTS_STELLIUM,
|
SWQOS_ENDPOINTS_HELIUS, SWQOS_ENDPOINTS_JITO, SWQOS_ENDPOINTS_NEXTBLOCK,
|
||||||
SWQOS_ENDPOINTS_SOYAS,
|
SWQOS_ENDPOINTS_NODE1, SWQOS_ENDPOINTS_NODE1_QUIC, SWQOS_ENDPOINTS_SOYAS,
|
||||||
SWQOS_ENDPOINTS_SPEEDLANDING
|
SWQOS_ENDPOINTS_SPEEDLANDING, SWQOS_ENDPOINTS_STELLIUM, SWQOS_ENDPOINTS_TEMPORAL,
|
||||||
|
SWQOS_ENDPOINTS_ZERO_SLOT, SWQOS_MIN_TIP_ASTRALANE, SWQOS_MIN_TIP_BLOCKRAZOR,
|
||||||
|
SWQOS_MIN_TIP_BLOXROUTE, SWQOS_MIN_TIP_DEFAULT, SWQOS_MIN_TIP_FLASHBLOCK,
|
||||||
|
SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_JITO, SWQOS_MIN_TIP_LIGHTSPEED,
|
||||||
|
SWQOS_MIN_TIP_NEXTBLOCK, SWQOS_MIN_TIP_NODE1, SWQOS_MIN_TIP_SOYAS,
|
||||||
|
SWQOS_MIN_TIP_SPEEDLANDING, SWQOS_MIN_TIP_STELLIUM, SWQOS_MIN_TIP_TEMPORAL,
|
||||||
|
SWQOS_MIN_TIP_ZERO_SLOT,
|
||||||
},
|
},
|
||||||
swqos::{
|
swqos::{
|
||||||
bloxroute::BloxrouteClient,
|
astralane::AstralaneClient, blockrazor::BlockRazorClient, bloxroute::BloxrouteClient,
|
||||||
jito::JitoClient,
|
flashblock::FlashBlockClient, helius::HeliusClient, jito::JitoClient,
|
||||||
nextblock::NextBlockClient,
|
lightspeed::LightspeedClient, nextblock::NextBlockClient, node1::Node1Client,
|
||||||
solana_rpc::SolRpcClient,
|
node1_quic::Node1QuicClient, solana_rpc::SolRpcClient, soyas::SoyasClient,
|
||||||
temporal::TemporalClient,
|
speedlanding::SpeedlandingClient, stellium::StelliumClient, temporal::TemporalClient,
|
||||||
zeroslot::ZeroSlotClient,
|
zeroslot::ZeroSlotClient,
|
||||||
node1::Node1Client,
|
},
|
||||||
flashblock::FlashBlockClient,
|
|
||||||
blockrazor::BlockRazorClient,
|
|
||||||
astralane::AstralaneClient,
|
|
||||||
stellium::StelliumClient,
|
|
||||||
lightspeed::LightspeedClient,
|
|
||||||
soyas::SoyasClient,
|
|
||||||
speedlanding::SpeedlandingClient,
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
// Tip 账户:`SwqosClient::get_tip_account()` 在各实现里多为静态常量;同一批多路提交时,
|
||||||
static ref TIP_ACCOUNT_CACHE: RwLock<Vec<String>> = RwLock::new(Vec::new());
|
// 在 `trading::core::async_executor::execute_parallel` 内用局部 `tip_cache`(按 client 指针)去重解析。
|
||||||
}
|
|
||||||
|
|
||||||
/// SWQOS provider blacklist configuration
|
/// SWQOS provider blacklist configuration
|
||||||
/// Providers added here will be disabled even if configured by user
|
/// Providers added here will be disabled even if configured by user
|
||||||
/// To enable a provider, remove it from this list
|
/// To enable a provider, remove it from this list
|
||||||
pub const SWQOS_BLACKLIST: &[SwqosType] = &[
|
pub const SWQOS_BLACKLIST: &[SwqosType] = &[
|
||||||
SwqosType::NextBlock, // NextBlock is disabled by default
|
SwqosType::NextBlock, // NextBlock is disabled by default
|
||||||
];
|
];
|
||||||
|
|
||||||
|
/// SWQOS 提交通道:HTTP、gRPC 或 QUIC(低延迟)。
|
||||||
|
/// BlockRazor 支持 gRPC 和 HTTP。
|
||||||
|
/// Node1 支持 QUIC。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||||
|
pub enum SwqosTransport {
|
||||||
|
#[default]
|
||||||
|
Http,
|
||||||
|
Grpc,
|
||||||
|
Quic,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Astralane 三种提交方式:QUIC TPU、Plain HTTP(`/iris`)、Binary HTTP(`/irisb` + bincode)。
|
||||||
|
/// 与全局 [`crate::common::TradeConfig::mev_protection`] 配合:HTTP 加 `mev-protect=true`;QUIC 选 `:9000` / `:7000`。
|
||||||
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||||
|
pub enum AstralaneTransport {
|
||||||
|
/// Binary over HTTP:`…/irisb?api-key=…&method=sendTransaction`(与 `AstralaneClient` 当前序列化一致)。
|
||||||
|
#[default]
|
||||||
|
Binary,
|
||||||
|
/// Plain HTTP:`…/iris?…`(非 irisb 路径)。
|
||||||
|
Plain,
|
||||||
|
/// QUIC(`host:7000`;MEV 时 `host:9000`)。
|
||||||
|
Quic,
|
||||||
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||||
pub enum TradeType {
|
pub enum TradeType {
|
||||||
Create,
|
Create,
|
||||||
@@ -103,10 +121,33 @@ pub enum SwqosType {
|
|||||||
Lightspeed,
|
Lightspeed,
|
||||||
Soyas,
|
Soyas,
|
||||||
Speedlanding,
|
Speedlanding,
|
||||||
|
Helius,
|
||||||
Default,
|
Default,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SwqosType {
|
impl SwqosType {
|
||||||
|
/// Label for log alignment; same as Debug output (e.g. "Soyas", "Speedlanding").
|
||||||
|
#[inline]
|
||||||
|
pub fn as_str(self) -> &'static str {
|
||||||
|
match self {
|
||||||
|
Self::Jito => "Jito",
|
||||||
|
Self::NextBlock => "NextBlock",
|
||||||
|
Self::ZeroSlot => "ZeroSlot",
|
||||||
|
Self::Temporal => "Temporal",
|
||||||
|
Self::Bloxroute => "Bloxroute",
|
||||||
|
Self::Node1 => "Node1",
|
||||||
|
Self::FlashBlock => "FlashBlock",
|
||||||
|
Self::BlockRazor => "BlockRazor",
|
||||||
|
Self::Astralane => "Astralane",
|
||||||
|
Self::Stellium => "Stellium",
|
||||||
|
Self::Lightspeed => "Lightspeed",
|
||||||
|
Self::Soyas => "Soyas",
|
||||||
|
Self::Speedlanding => "Speedlanding",
|
||||||
|
Self::Helius => "Helius",
|
||||||
|
Self::Default => "Default",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub fn values() -> Vec<Self> {
|
pub fn values() -> Vec<Self> {
|
||||||
vec![
|
vec![
|
||||||
Self::Jito,
|
Self::Jito,
|
||||||
@@ -121,6 +162,8 @@ impl SwqosType {
|
|||||||
Self::Stellium,
|
Self::Stellium,
|
||||||
Self::Lightspeed,
|
Self::Lightspeed,
|
||||||
Self::Soyas,
|
Self::Soyas,
|
||||||
|
Self::Speedlanding,
|
||||||
|
Self::Helius,
|
||||||
Self::Default,
|
Self::Default,
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -130,21 +173,60 @@ pub type SwqosClient = dyn SwqosClientTrait + Send + Sync + 'static;
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait SwqosClientTrait {
|
pub trait SwqosClientTrait {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()>;
|
async fn send_transaction(
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()>;
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()>;
|
||||||
fn get_tip_account(&self) -> Result<String>;
|
fn get_tip_account(&self) -> Result<String>;
|
||||||
fn get_swqos_type(&self) -> SwqosType;
|
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,
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// 地理区域,用于默认 SWQOS 端点下标(见 `constants::swqos`)。
|
||||||
|
///
|
||||||
|
/// 各服务商常量表在**缺独立 PoP**时,于**已公布的端点集合内**按地理距离选最近项;[`SwqosRegion::Default`] 不表示地球上的位置,表中为全局/枢纽回退,不适用地理就近。
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
pub enum SwqosRegion {
|
pub enum SwqosRegion {
|
||||||
NewYork,
|
NewYork,
|
||||||
Frankfurt,
|
Frankfurt,
|
||||||
Amsterdam,
|
Amsterdam,
|
||||||
|
/// Ireland (EU); Jito publishes `dublin.mainnet.block-engine.jito.wtf`.
|
||||||
|
Dublin,
|
||||||
SLC,
|
SLC,
|
||||||
Tokyo,
|
Tokyo,
|
||||||
|
/// Southeast Asia (Singapore); not interchangeable with [`SwqosRegion::Tokyo`].
|
||||||
|
Singapore,
|
||||||
London,
|
London,
|
||||||
LosAngeles,
|
LosAngeles,
|
||||||
|
/// 非地理区域:未指定区域时的回退,对应表中全局 URL 或枢纽,**不按地理距离选取**。
|
||||||
Default,
|
Default,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -161,14 +243,14 @@ pub enum SwqosConfig {
|
|||||||
Temporal(String, SwqosRegion, Option<String>),
|
Temporal(String, SwqosRegion, Option<String>),
|
||||||
/// ZeroSlot(api_token, region, custom_url)
|
/// ZeroSlot(api_token, region, custom_url)
|
||||||
ZeroSlot(String, SwqosRegion, Option<String>),
|
ZeroSlot(String, SwqosRegion, Option<String>),
|
||||||
/// Node1(api_token, region, custom_url)
|
/// Node1(api_token, region, custom_url, transport). transport=None => HTTP; Some(Quic) => QUIC (port 16666, UUID auth).
|
||||||
Node1(String, SwqosRegion, Option<String>),
|
Node1(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||||
/// FlashBlock(api_token, region, custom_url)
|
/// FlashBlock(api_token, region, custom_url)
|
||||||
FlashBlock(String, SwqosRegion, Option<String>),
|
FlashBlock(String, SwqosRegion, Option<String>),
|
||||||
/// BlockRazor(api_token, region, custom_url)
|
/// BlockRazor(api_token, region, custom_url, transport). transport=None 或 Grpc => gRPC; Some(Http) => HTTP.
|
||||||
BlockRazor(String, SwqosRegion, Option<String>),
|
BlockRazor(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||||
/// Astralane(api_token, region, custom_url)
|
/// Astralane(api_token, region, custom_url, mode). `None` => [`AstralaneTransport::Binary`](`/irisb`)。
|
||||||
Astralane(String, SwqosRegion, Option<String>),
|
Astralane(String, SwqosRegion, Option<String>, Option<AstralaneTransport>),
|
||||||
/// Stellium(api_token, region, custom_url)
|
/// Stellium(api_token, region, custom_url)
|
||||||
Stellium(String, SwqosRegion, Option<String>),
|
Stellium(String, SwqosRegion, Option<String>),
|
||||||
/// Lightspeed(api_key, region, custom_url) - Solana Vibe Station
|
/// Lightspeed(api_key, region, custom_url) - Solana Vibe Station
|
||||||
@@ -180,10 +262,13 @@ pub enum SwqosConfig {
|
|||||||
/// To apply for an API key, please contact -> https://t.me/speedlanding_bot?start=0xzero
|
/// To apply for an API key, please contact -> https://t.me/speedlanding_bot?start=0xzero
|
||||||
/// Minimum tip: 0.001 SOL
|
/// Minimum tip: 0.001 SOL
|
||||||
Speedlanding(String, SwqosRegion, Option<String>),
|
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 {
|
impl SwqosConfig {
|
||||||
pub fn swqos_type(&self) -> SwqosType{
|
pub fn swqos_type(&self) -> SwqosType {
|
||||||
match self {
|
match self {
|
||||||
SwqosConfig::Default(_) => SwqosType::Default,
|
SwqosConfig::Default(_) => SwqosType::Default,
|
||||||
SwqosConfig::Jito(_, _, _) => SwqosType::Jito,
|
SwqosConfig::Jito(_, _, _) => SwqosType::Jito,
|
||||||
@@ -191,14 +276,15 @@ impl SwqosConfig {
|
|||||||
SwqosConfig::Bloxroute(_, _, _) => SwqosType::Bloxroute,
|
SwqosConfig::Bloxroute(_, _, _) => SwqosType::Bloxroute,
|
||||||
SwqosConfig::Temporal(_, _, _) => SwqosType::Temporal,
|
SwqosConfig::Temporal(_, _, _) => SwqosType::Temporal,
|
||||||
SwqosConfig::ZeroSlot(_, _, _) => SwqosType::ZeroSlot,
|
SwqosConfig::ZeroSlot(_, _, _) => SwqosType::ZeroSlot,
|
||||||
SwqosConfig::Node1(_, _, _) => SwqosType::Node1,
|
SwqosConfig::Node1(_, _, _, _) => SwqosType::Node1,
|
||||||
SwqosConfig::FlashBlock(_, _, _) => SwqosType::FlashBlock,
|
SwqosConfig::FlashBlock(_, _, _) => SwqosType::FlashBlock,
|
||||||
SwqosConfig::BlockRazor(_, _, _) => SwqosType::BlockRazor,
|
SwqosConfig::BlockRazor(_, _, _, _) => SwqosType::BlockRazor,
|
||||||
SwqosConfig::Astralane(_, _, _) => SwqosType::Astralane,
|
SwqosConfig::Astralane(_, _, _, _) => SwqosType::Astralane,
|
||||||
SwqosConfig::Stellium(_, _, _) => SwqosType::Stellium,
|
SwqosConfig::Stellium(_, _, _) => SwqosType::Stellium,
|
||||||
SwqosConfig::Lightspeed(_, _, _) => SwqosType::Lightspeed,
|
SwqosConfig::Lightspeed(_, _, _) => SwqosType::Lightspeed,
|
||||||
SwqosConfig::Soyas(_, _, _) => SwqosType::Soyas,
|
SwqosConfig::Soyas(_, _, _) => SwqosType::Soyas,
|
||||||
SwqosConfig::Speedlanding(_, _, _) => SwqosType::Speedlanding,
|
SwqosConfig::Speedlanding(_, _, _) => SwqosType::Speedlanding,
|
||||||
|
SwqosConfig::Helius(_, _, _, _) => SwqosType::Helius,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -221,142 +307,202 @@ impl SwqosConfig {
|
|||||||
SwqosType::Node1 => SWQOS_ENDPOINTS_NODE1[region as usize].to_string(),
|
SwqosType::Node1 => SWQOS_ENDPOINTS_NODE1[region as usize].to_string(),
|
||||||
SwqosType::FlashBlock => SWQOS_ENDPOINTS_FLASHBLOCK[region as usize].to_string(),
|
SwqosType::FlashBlock => SWQOS_ENDPOINTS_FLASHBLOCK[region as usize].to_string(),
|
||||||
SwqosType::BlockRazor => SWQOS_ENDPOINTS_BLOCKRAZOR[region as usize].to_string(),
|
SwqosType::BlockRazor => SWQOS_ENDPOINTS_BLOCKRAZOR[region as usize].to_string(),
|
||||||
SwqosType::Astralane => SWQOS_ENDPOINTS_ASTRALANE[region as usize].to_string(),
|
SwqosType::Astralane => SWQOS_ENDPOINTS_ASTRALANE_BINARY[region as usize].to_string(),
|
||||||
SwqosType::Stellium => SWQOS_ENDPOINTS_STELLIUM[region as usize].to_string(),
|
SwqosType::Stellium => SWQOS_ENDPOINTS_STELLIUM[region as usize].to_string(),
|
||||||
SwqosType::Lightspeed => "".to_string(), // Lightspeed requires custom URL with api_key
|
SwqosType::Lightspeed => "".to_string(), // Lightspeed requires custom URL with api_key
|
||||||
SwqosType::Soyas => SWQOS_ENDPOINTS_SOYAS[region as usize].to_string(),
|
SwqosType::Soyas => SWQOS_ENDPOINTS_SOYAS[region as usize].to_string(),
|
||||||
SwqosType::Speedlanding => SWQOS_ENDPOINTS_SPEEDLANDING[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(),
|
SwqosType::Default => "".to_string(),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_swqos_client(rpc_url: String, commitment: CommitmentConfig, swqos_config: SwqosConfig) -> Result<Arc<SwqosClient>> {
|
pub fn get_endpoint_with_transport(
|
||||||
|
swqos_type: SwqosType,
|
||||||
|
region: SwqosRegion,
|
||||||
|
url: Option<String>,
|
||||||
|
transport: Option<SwqosTransport>,
|
||||||
|
_mev_protection: bool,
|
||||||
|
) -> String {
|
||||||
|
if let Some(custom_url) = url {
|
||||||
|
return custom_url;
|
||||||
|
}
|
||||||
|
|
||||||
|
match swqos_type {
|
||||||
|
SwqosType::BlockRazor => {
|
||||||
|
// transport=None 或 transport=Grpc => gRPC; transport=Http => HTTP
|
||||||
|
let use_http = transport.map_or(false, |t| t == SwqosTransport::Http);
|
||||||
|
if use_http {
|
||||||
|
SWQOS_ENDPOINTS_BLOCKRAZOR[region as usize].to_string()
|
||||||
|
} else {
|
||||||
|
SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC[region as usize].to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SwqosType::Node1 => {
|
||||||
|
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||||
|
if use_quic {
|
||||||
|
SWQOS_ENDPOINTS_NODE1_QUIC[region as usize].to_string()
|
||||||
|
} else {
|
||||||
|
SWQOS_ENDPOINTS_NODE1[region as usize].to_string()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
_ => Self::get_endpoint(swqos_type, region, None),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_swqos_client(
|
||||||
|
rpc_url: String,
|
||||||
|
commitment: CommitmentConfig,
|
||||||
|
swqos_config: SwqosConfig,
|
||||||
|
mev_protection: bool,
|
||||||
|
) -> Result<Arc<SwqosClient>> {
|
||||||
match swqos_config {
|
match swqos_config {
|
||||||
SwqosConfig::Jito(auth_token, region, url) => {
|
SwqosConfig::Jito(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Jito, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Jito, region, url);
|
||||||
let jito_client = JitoClient::new(
|
let jito_client = JitoClient::new(rpc_url.clone(), endpoint, auth_token);
|
||||||
rpc_url.clone(),
|
|
||||||
endpoint,
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(jito_client))
|
Ok(Arc::new(jito_client))
|
||||||
}
|
}
|
||||||
SwqosConfig::NextBlock(auth_token, region, url) => {
|
SwqosConfig::NextBlock(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::NextBlock, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::NextBlock, region, url);
|
||||||
let nextblock_client = NextBlockClient::new(
|
let nextblock_client =
|
||||||
rpc_url.clone(),
|
NextBlockClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(nextblock_client))
|
Ok(Arc::new(nextblock_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::ZeroSlot(auth_token, region, url) => {
|
SwqosConfig::ZeroSlot(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::ZeroSlot, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::ZeroSlot, region, url);
|
||||||
let zeroslot_client = ZeroSlotClient::new(
|
let zeroslot_client =
|
||||||
rpc_url.clone(),
|
ZeroSlotClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(zeroslot_client))
|
Ok(Arc::new(zeroslot_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Temporal(auth_token, region, url) => {
|
SwqosConfig::Temporal(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Temporal, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Temporal, region, url);
|
||||||
let temporal_client = TemporalClient::new(
|
let temporal_client =
|
||||||
rpc_url.clone(),
|
TemporalClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(temporal_client))
|
Ok(Arc::new(temporal_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Bloxroute(auth_token, region, url) => {
|
SwqosConfig::Bloxroute(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Bloxroute, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Bloxroute, region, url);
|
||||||
let bloxroute_client = BloxrouteClient::new(
|
let bloxroute_client =
|
||||||
rpc_url.clone(),
|
BloxrouteClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(bloxroute_client))
|
Ok(Arc::new(bloxroute_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Node1(auth_token, region, url) => {
|
SwqosConfig::Node1(auth_token, region, url, transport) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Node1, region, url);
|
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||||
let node1_client = Node1Client::new(
|
if use_quic {
|
||||||
rpc_url.clone(),
|
let quic_endpoint = url
|
||||||
endpoint.to_string(),
|
.unwrap_or_else(|| SWQOS_ENDPOINTS_NODE1_QUIC[region as usize].to_string());
|
||||||
auth_token
|
let node1_quic =
|
||||||
);
|
Node1QuicClient::connect(&quic_endpoint, &auth_token, rpc_url.clone())
|
||||||
Ok(Arc::new(node1_client))
|
.await?;
|
||||||
},
|
Ok(Arc::new(node1_quic))
|
||||||
|
} else {
|
||||||
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Node1, region, url);
|
||||||
|
let node1_client =
|
||||||
|
Node1Client::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
|
Ok(Arc::new(node1_client))
|
||||||
|
}
|
||||||
|
}
|
||||||
SwqosConfig::FlashBlock(auth_token, region, url) => {
|
SwqosConfig::FlashBlock(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::FlashBlock, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::FlashBlock, region, url);
|
||||||
let flashblock_client = FlashBlockClient::new(
|
let flashblock_client =
|
||||||
rpc_url.clone(),
|
FlashBlockClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(flashblock_client))
|
Ok(Arc::new(flashblock_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::BlockRazor(auth_token, region, url) => {
|
SwqosConfig::BlockRazor(auth_token, region, url, transport) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
// BlockRazor: transport=None 或 transport=Grpc 时使用 gRPC,transport=Http 时使用 HTTP
|
||||||
let blockrazor_client = BlockRazorClient::new(
|
let use_http = transport.map_or(false, |t| t == SwqosTransport::Http);
|
||||||
rpc_url.clone(),
|
let endpoint = SwqosConfig::get_endpoint_with_transport(SwqosType::BlockRazor, region, url, transport, mev_protection);
|
||||||
endpoint.to_string(),
|
if use_http {
|
||||||
auth_token
|
let blockrazor_client =
|
||||||
);
|
BlockRazorClient::new_http(rpc_url.clone(), endpoint.to_string(), auth_token, mev_protection);
|
||||||
Ok(Arc::new(blockrazor_client))
|
Ok(Arc::new(blockrazor_client))
|
||||||
},
|
} else {
|
||||||
SwqosConfig::Astralane(auth_token, region, url) => {
|
// 使用 gRPC 模式(默认或用户明确指定了 gRPC)
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
|
let blockrazor_client =
|
||||||
let astralane_client = AstralaneClient::new(
|
BlockRazorClient::new_grpc(rpc_url.clone(), endpoint.to_string(), auth_token, mev_protection).await?;
|
||||||
rpc_url.clone(),
|
Ok(Arc::new(blockrazor_client))
|
||||||
endpoint.to_string(),
|
}
|
||||||
auth_token
|
}
|
||||||
);
|
SwqosConfig::Astralane(auth_token, region, url, mode) => {
|
||||||
Ok(Arc::new(astralane_client))
|
let mode = mode.unwrap_or_default();
|
||||||
},
|
match mode {
|
||||||
|
AstralaneTransport::Quic => {
|
||||||
|
let quic_endpoint = url.unwrap_or_else(|| {
|
||||||
|
if mev_protection {
|
||||||
|
SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV[region as usize].to_string()
|
||||||
|
} else {
|
||||||
|
SWQOS_ENDPOINTS_ASTRALANE_QUIC[region as usize].to_string()
|
||||||
|
}
|
||||||
|
});
|
||||||
|
let astralane_client =
|
||||||
|
AstralaneClient::new_quic(rpc_url.clone(), &quic_endpoint, auth_token)
|
||||||
|
.await?;
|
||||||
|
Ok(Arc::new(astralane_client))
|
||||||
|
}
|
||||||
|
AstralaneTransport::Plain => {
|
||||||
|
let endpoint = url.unwrap_or_else(|| {
|
||||||
|
SWQOS_ENDPOINTS_ASTRALANE_PLAIN[region as usize].to_string()
|
||||||
|
});
|
||||||
|
let astralane_client = AstralaneClient::new(
|
||||||
|
rpc_url.clone(),
|
||||||
|
endpoint,
|
||||||
|
auth_token,
|
||||||
|
mev_protection,
|
||||||
|
);
|
||||||
|
Ok(Arc::new(astralane_client))
|
||||||
|
}
|
||||||
|
AstralaneTransport::Binary => {
|
||||||
|
let endpoint = url.unwrap_or_else(|| {
|
||||||
|
SWQOS_ENDPOINTS_ASTRALANE_BINARY[region as usize].to_string()
|
||||||
|
});
|
||||||
|
let astralane_client = AstralaneClient::new(
|
||||||
|
rpc_url.clone(),
|
||||||
|
endpoint,
|
||||||
|
auth_token,
|
||||||
|
mev_protection,
|
||||||
|
);
|
||||||
|
Ok(Arc::new(astralane_client))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
SwqosConfig::Stellium(auth_token, region, url) => {
|
SwqosConfig::Stellium(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
|
||||||
let stellium_client = StelliumClient::new(
|
let stellium_client =
|
||||||
rpc_url.clone(),
|
StelliumClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(stellium_client))
|
Ok(Arc::new(stellium_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Lightspeed(auth_token, region, url) => {
|
SwqosConfig::Lightspeed(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Lightspeed, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Lightspeed, region, url);
|
||||||
let lightspeed_client = LightspeedClient::new(
|
let lightspeed_client =
|
||||||
rpc_url.clone(),
|
LightspeedClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(lightspeed_client))
|
Ok(Arc::new(lightspeed_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Soyas(auth_token, region, url) => {
|
SwqosConfig::Soyas(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Soyas, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Soyas, region, url);
|
||||||
let soyas_client = SoyasClient::new(
|
let soyas_client =
|
||||||
rpc_url.clone(),
|
SoyasClient::new(rpc_url.clone(), endpoint.to_string(), auth_token).await?;
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
).await?;
|
|
||||||
Ok(Arc::new(soyas_client))
|
Ok(Arc::new(soyas_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Speedlanding(auth_token, region, url) => {
|
SwqosConfig::Speedlanding(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Speedlanding, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Speedlanding, region, url);
|
||||||
let speedlanding_client = SpeedlandingClient::new(
|
let speedlanding_client =
|
||||||
rpc_url.clone(),
|
SpeedlandingClient::new(rpc_url.clone(), endpoint.to_string(), auth_token)
|
||||||
endpoint.to_string(),
|
.await?;
|
||||||
auth_token
|
|
||||||
).await?;
|
|
||||||
Ok(Arc::new(speedlanding_client))
|
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) => {
|
SwqosConfig::Default(endpoint) => {
|
||||||
let rpc = SolanaRpcClient::new_with_commitment(
|
let rpc = SolanaRpcClient::new_with_commitment(endpoint, commitment);
|
||||||
endpoint,
|
|
||||||
commitment
|
|
||||||
);
|
|
||||||
let rpc_client = SolRpcClient::new(Arc::new(rpc));
|
let rpc_client = SolRpcClient::new(Arc::new(rpc));
|
||||||
Ok(Arc::new(rpc_client))
|
Ok(Arc::new(rpc_client))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+52
-31
@@ -1,16 +1,17 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NEXTBLOCK_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NEXTBLOCK_TIP_ACCOUNTS};
|
||||||
|
|
||||||
@@ -24,16 +25,29 @@ pub struct NextBlockClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for NextBlockClient {
|
impl SwqosClientTrait for NextBlockClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *NEXTBLOCK_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NEXTBLOCK_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NEXTBLOCK_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NEXTBLOCK_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -51,25 +65,19 @@ impl NextBlockClient {
|
|||||||
format!("{}/api/v2/submit", endpoint.trim_end_matches('/'))
|
format!("{}/api/v2/submit", endpoint.trim_end_matches('/'))
|
||||||
};
|
};
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// 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();
|
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"transaction": {
|
"transaction": {
|
||||||
@@ -78,7 +86,9 @@ impl NextBlockClient {
|
|||||||
"frontRunningProtection": false
|
"frontRunningProtection": false
|
||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Authorization", &self.auth_token)
|
.header("Authorization", &self.auth_token)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
@@ -89,12 +99,12 @@ impl NextBlockClient {
|
|||||||
|
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if response_json.get("result").is_some() {
|
||||||
println!(" [nextblock] {} submitted: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submitted("nextblock", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
eprintln!(" [nextblock] {} submission failed: {:?}", trade_type, _error);
|
crate::common::sdk_log::log_swqos_submission_failed("nextblock", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!(" [nextblock] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("nextblock", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
@@ -102,22 +112,33 @@ impl NextBlockClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nextblock] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"nextblock",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nextblock] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "nextblock", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+100
-69
@@ -1,21 +1,23 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NODE1_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NODE1_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Node1Client {
|
pub struct Node1Client {
|
||||||
@@ -29,16 +31,29 @@ pub struct Node1Client {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for Node1Client {
|
impl SwqosClientTrait for Node1Client {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *NODE1_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NODE1_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NODE1_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NODE1_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,35 +65,23 @@ impl SwqosClientTrait for Node1Client {
|
|||||||
impl Node1Client {
|
impl Node1Client {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// Optimized connection pool settings for high performance
|
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
let client = Self {
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
rpc_client: Arc::new(rpc_client),
|
||||||
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
|
endpoint,
|
||||||
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
|
auth_token,
|
||||||
.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,
|
http_client,
|
||||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Start ping task
|
// Start ping task
|
||||||
let client_clone = client.clone();
|
let client_clone = client.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
client_clone.start_ping_task().await;
|
client_clone.start_ping_task().await;
|
||||||
});
|
});
|
||||||
|
|
||||||
client
|
client
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -88,24 +91,29 @@ impl Node1Client {
|
|||||||
let auth_token = self.auth_token.clone();
|
let auth_token = self.auth_token.clone();
|
||||||
let http_client = self.http_client.clone();
|
let http_client = self.http_client.clone();
|
||||||
let stop_ping = self.stop_ping.clone();
|
let stop_ping = self.stop_ping.clone();
|
||||||
|
|
||||||
let handle = tokio::spawn(async move {
|
let handle = tokio::spawn(async move {
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(60)); // Ping every 60 seconds
|
// 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 {
|
||||||
loop {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
interval.tick().await;
|
|
||||||
|
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Send ping request
|
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
|
||||||
eprintln!("Node1 ping request failed: {}", e);
|
eprintln!("Node1 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
|
||||||
|
{
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("Node1 ping request failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update ping_handle - use Mutex to safely update
|
// Update ping_handle - use Mutex to safely update
|
||||||
{
|
{
|
||||||
let mut ping_guard = self.ping_handle.lock().await;
|
let mut ping_guard = self.ping_handle.lock().await;
|
||||||
@@ -117,7 +125,11 @@ impl Node1Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request to /ping endpoint
|
/// Send ping request to /ping endpoint
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, _auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
_auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
// Build ping URL
|
// Build ping URL
|
||||||
let ping_url = if endpoint.ends_with('/') {
|
let ping_url = if endpoint.ends_with('/') {
|
||||||
format!("{}ping", endpoint)
|
format!("{}ping", endpoint)
|
||||||
@@ -125,24 +137,26 @@ impl Node1Client {
|
|||||||
format!("{}/ping", endpoint)
|
format!("{}/ping", endpoint)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send GET request to /ping endpoint (no api-key required)
|
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
||||||
let response = http_client.get(&ping_url)
|
let response =
|
||||||
.send()
|
http_client.get(&ping_url).timeout(Duration::from_millis(1500)).send().await?;
|
||||||
.await?;
|
let status = response.status();
|
||||||
|
let _ = response.bytes().await;
|
||||||
if response.status().is_success() {
|
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
// ping successful, connection remains active
|
eprintln!("Node1 ping request returned non-success status: {}", status);
|
||||||
// Can optionally log, but to reduce noise, not printing here
|
|
||||||
} else {
|
|
||||||
eprintln!("Node1 ping request returned non-success status: {}", response.status());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -155,7 +169,9 @@ impl Node1Client {
|
|||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
// Node1 uses api-key header instead of URL parameter
|
// Node1 uses api-key header instead of URL parameter
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("api-key", &self.auth_token)
|
.header("api-key", &self.auth_token)
|
||||||
@@ -166,33 +182,48 @@ impl Node1Client {
|
|||||||
|
|
||||||
// Parse JSON response
|
// Parse JSON response
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [node1] {} submitted: {:?}", trade_type, start_time.elapsed());
|
if response_json.get("result").is_some() {
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
crate::common::sdk_log::log_swqos_submitted("node1", trade_type, start_time.elapsed());
|
||||||
eprintln!(" [node1] {} submission failed: {:?}", trade_type, _error);
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
|
eprintln!(" [node1] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [node1] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("node1", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [node1] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"node1",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [node1] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "node1", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
@@ -204,7 +235,7 @@ impl Drop for Node1Client {
|
|||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Ensure ping task stops when client is destroyed
|
// Ensure ping task stops when client is destroyed
|
||||||
self.stop_ping.store(true, Ordering::Relaxed);
|
self.stop_ping.store(true, Ordering::Relaxed);
|
||||||
|
|
||||||
// Try to stop ping task immediately
|
// Try to stop ping task immediately
|
||||||
// Use tokio::spawn to avoid blocking Drop
|
// Use tokio::spawn to avoid blocking Drop
|
||||||
let ping_handle = self.ping_handle.clone();
|
let ping_handle = self.ping_handle.clone();
|
||||||
|
|||||||
@@ -0,0 +1,306 @@
|
|||||||
|
//! Node1 QUIC SWQOS client.
|
||||||
|
//!
|
||||||
|
//! Protocol: first bi stream = auth (16-byte UUID); each transaction uses a new bi stream.
|
||||||
|
//! Request body = bincode(VersionedTransaction); response = 2 bytes status (BE) + 4 bytes msg_len (BE) + msg.
|
||||||
|
//! Reuses a single authenticated connection; reconnects and re-auth when connection is closed.
|
||||||
|
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use quinn::crypto::rustls::QuicClientConfig;
|
||||||
|
use quinn::{ClientConfig, Connection, Endpoint, IdleTimeout, RecvStream, TransportConfig};
|
||||||
|
use std::net::ToSocketAddrs;
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::Duration;
|
||||||
|
use tokio::sync::Mutex;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
use crate::common::SolanaRpcClient;
|
||||||
|
use crate::constants::swqos::NODE1_TIP_ACCOUNTS;
|
||||||
|
use crate::swqos::common::poll_transaction_confirmation;
|
||||||
|
use crate::swqos::{SwqosClientTrait, SwqosType, TradeType};
|
||||||
|
use rand::seq::IndexedRandom;
|
||||||
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
|
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const AUTH_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const SEND_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(15);
|
||||||
|
const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(60);
|
||||||
|
const MAX_TX_SIZE: usize = 1232;
|
||||||
|
|
||||||
|
/// Node1 QUIC client: one authenticated connection, reuse for all transactions.
|
||||||
|
pub struct Node1QuicClient {
|
||||||
|
endpoint: Endpoint,
|
||||||
|
connection: Mutex<Connection>,
|
||||||
|
server_addr: String,
|
||||||
|
server_name: String,
|
||||||
|
api_key_uuid: [u8; 16],
|
||||||
|
rpc_client: Arc<SolanaRpcClient>,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Node1QuicClient {
|
||||||
|
/// Connect and authenticate. Reuse the returned client for all subsequent sends.
|
||||||
|
pub async fn connect(server_addr: &str, api_key: &str, rpc_url: String) -> Result<Self> {
|
||||||
|
let socket_addr = server_addr
|
||||||
|
.to_socket_addrs()
|
||||||
|
.context("resolve Node1 QUIC server address")?
|
||||||
|
.next()
|
||||||
|
.context("no socket address for Node1 QUIC")?;
|
||||||
|
|
||||||
|
let api_key_uuid =
|
||||||
|
Uuid::parse_str(api_key).context("Node1 API key must be a valid UUID")?;
|
||||||
|
let api_key_bytes: [u8; 16] = *api_key_uuid.as_bytes();
|
||||||
|
|
||||||
|
let server_name = server_addr.split(':').next().unwrap_or(server_addr);
|
||||||
|
|
||||||
|
let client_config = Self::build_client_config()?;
|
||||||
|
let mut endpoint =
|
||||||
|
Endpoint::client("0.0.0.0:0".parse()?).context("create QUIC endpoint")?;
|
||||||
|
endpoint.set_default_client_config(client_config);
|
||||||
|
|
||||||
|
let connecting =
|
||||||
|
endpoint.connect(socket_addr, server_name).context("Node1 QUIC connect failed")?;
|
||||||
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
|
.await
|
||||||
|
.context("Node1 QUIC connect timeout")?
|
||||||
|
.context("Node1 QUIC handshake failed")?;
|
||||||
|
|
||||||
|
timeout(AUTH_TIMEOUT, Self::authenticate(&connection, &api_key_bytes))
|
||||||
|
.await
|
||||||
|
.context("Node1 QUIC auth timeout")??;
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
endpoint,
|
||||||
|
connection: Mutex::new(connection),
|
||||||
|
server_addr: server_addr.to_string(),
|
||||||
|
server_name: server_name.to_string(),
|
||||||
|
api_key_uuid: api_key_bytes,
|
||||||
|
rpc_client: Arc::new(SolanaRpcClient::new(rpc_url)),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
fn build_client_config() -> Result<ClientConfig> {
|
||||||
|
let crypto = rustls::ClientConfig::builder()
|
||||||
|
.dangerous()
|
||||||
|
.with_custom_certificate_verifier(Arc::new(SkipServerVerification))
|
||||||
|
.with_no_client_auth();
|
||||||
|
|
||||||
|
let client_crypto = QuicClientConfig::try_from(crypto).context("build QUIC TLS config")?;
|
||||||
|
let mut client_config = ClientConfig::new(Arc::new(client_crypto));
|
||||||
|
|
||||||
|
let mut transport = TransportConfig::default();
|
||||||
|
transport.max_idle_timeout(Some(IdleTimeout::try_from(MAX_IDLE_TIMEOUT).unwrap()));
|
||||||
|
transport.keep_alive_interval(Some(KEEP_ALIVE_INTERVAL));
|
||||||
|
client_config.transport_config(Arc::new(transport));
|
||||||
|
|
||||||
|
Ok(client_config)
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn authenticate(connection: &Connection, api_key_bytes: &[u8; 16]) -> Result<()> {
|
||||||
|
let (mut send, mut recv) = connection.open_bi().await.context("open_bi for auth")?;
|
||||||
|
send.write_all(api_key_bytes).await.context("write auth bytes")?;
|
||||||
|
send.finish().context("finish auth stream")?;
|
||||||
|
|
||||||
|
let mut reply = [0u8; 1];
|
||||||
|
recv.read_exact(&mut reply).await.context("read auth reply")?;
|
||||||
|
match reply[0] {
|
||||||
|
0 => Ok(()),
|
||||||
|
code => anyhow::bail!("Node1 QUIC auth rejected, reply={}", code),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn ensure_connected(&self) -> Result<Connection> {
|
||||||
|
let guard = self.connection.lock().await;
|
||||||
|
if let Some(_reason) = guard.close_reason() {
|
||||||
|
drop(guard);
|
||||||
|
let socket_addr = self
|
||||||
|
.server_addr
|
||||||
|
.to_socket_addrs()
|
||||||
|
.context("resolve Node1 QUIC server address")?
|
||||||
|
.next()
|
||||||
|
.context("no socket address")?;
|
||||||
|
let connecting = self
|
||||||
|
.endpoint
|
||||||
|
.connect(socket_addr, &self.server_name)
|
||||||
|
.context("Node1 QUIC reconnect failed")?;
|
||||||
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
|
.await
|
||||||
|
.context("Node1 QUIC reconnect timeout")?
|
||||||
|
.context("Node1 QUIC re-handshake failed")?;
|
||||||
|
|
||||||
|
timeout(AUTH_TIMEOUT, Self::authenticate(&connection, &self.api_key_uuid))
|
||||||
|
.await
|
||||||
|
.context("Node1 QUIC re-auth timeout")??;
|
||||||
|
|
||||||
|
let mut g = self.connection.lock().await;
|
||||||
|
*g = connection.clone();
|
||||||
|
Ok(connection)
|
||||||
|
} else {
|
||||||
|
Ok(guard.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn read_response(recv: &mut RecvStream) -> Result<(u16, String)> {
|
||||||
|
let mut header = [0u8; 6];
|
||||||
|
recv.read_exact(&mut header)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("read response header: {:?}", e))?;
|
||||||
|
let status = u16::from_be_bytes(header[0..2].try_into().unwrap());
|
||||||
|
let msg_len = u32::from_be_bytes(header[2..6].try_into().unwrap()) as usize;
|
||||||
|
let mut msg = vec![0u8; msg_len];
|
||||||
|
if msg_len > 0 {
|
||||||
|
recv.read_exact(&mut msg)
|
||||||
|
.await
|
||||||
|
.map_err(|e| anyhow::anyhow!("read response body: {:?}", e))?;
|
||||||
|
}
|
||||||
|
Ok((status, String::from_utf8_lossy(&msg).into_owned()))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send one transaction over QUIC (opens new bi stream, writes bincode tx, reads status+msg).
|
||||||
|
pub async fn send_transaction_bytes(&self, tx_bytes: &[u8]) -> Result<(u16, String)> {
|
||||||
|
if tx_bytes.len() > MAX_TX_SIZE {
|
||||||
|
anyhow::bail!(
|
||||||
|
"Node1 QUIC: transaction too large ({} > {})",
|
||||||
|
tx_bytes.len(),
|
||||||
|
MAX_TX_SIZE
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
let conn = self.ensure_connected().await?;
|
||||||
|
let (mut send, mut recv) = conn.open_bi().await.context("open_bi for tx")?;
|
||||||
|
send.write_all(tx_bytes).await.context("write tx")?;
|
||||||
|
send.finish().context("finish tx stream")?;
|
||||||
|
Self::read_response(&mut recv).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[async_trait::async_trait]
|
||||||
|
impl SwqosClientTrait for Node1QuicClient {
|
||||||
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
let start = Instant::now();
|
||||||
|
let signature = transaction.signatures.first().copied().unwrap_or_default();
|
||||||
|
let tx_bytes = bincode::serialize(transaction).context("Node1 QUIC: bincode serialize")?;
|
||||||
|
|
||||||
|
let (status, msg) = timeout(SEND_TIMEOUT, self.send_transaction_bytes(&tx_bytes))
|
||||||
|
.await
|
||||||
|
.context("Node1 QUIC send timeout")??;
|
||||||
|
|
||||||
|
if status != 200 {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!(
|
||||||
|
" [node1-quic] {} submit failed: status={} msg={}",
|
||||||
|
trade_type, status, msg
|
||||||
|
);
|
||||||
|
}
|
||||||
|
anyhow::bail!("Node1 QUIC submit failed: status={} msg={}", status, msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
println!(" [node1-quic] {} submitted: {:?}", trade_type, start.elapsed());
|
||||||
|
}
|
||||||
|
|
||||||
|
let start = Instant::now();
|
||||||
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
|
Ok(_) => {
|
||||||
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
println!(" [node1-quic] {} confirmed: {:?}", trade_type, start.elapsed());
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!(
|
||||||
|
" [node1-quic] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start.elapsed()
|
||||||
|
);
|
||||||
|
}
|
||||||
|
Err(e)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
|
for tx in transactions {
|
||||||
|
self.send_transaction(trade_type, tx, wait_confirmation).await?;
|
||||||
|
}
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
|
let tip = *NODE1_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NODE1_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
|
Ok(tip.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn get_swqos_type(&self) -> SwqosType {
|
||||||
|
SwqosType::Node1
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for Node1QuicClient {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
self.connection.get_mut().close(0u32.into(), b"client closing");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct SkipServerVerification;
|
||||||
|
|
||||||
|
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
|
||||||
|
fn verify_server_cert(
|
||||||
|
&self,
|
||||||
|
_: &rustls::pki_types::CertificateDer<'_>,
|
||||||
|
_: &[rustls::pki_types::CertificateDer<'_>],
|
||||||
|
_: &rustls::pki_types::ServerName<'_>,
|
||||||
|
_: &[u8],
|
||||||
|
_: rustls::pki_types::UnixTime,
|
||||||
|
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||||
|
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls12_signature(
|
||||||
|
&self,
|
||||||
|
_: &[u8],
|
||||||
|
_: &rustls::pki_types::CertificateDer<'_>,
|
||||||
|
_: &rustls::DigitallySignedStruct,
|
||||||
|
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||||
|
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn verify_tls13_signature(
|
||||||
|
&self,
|
||||||
|
_: &[u8],
|
||||||
|
_: &rustls::pki_types::CertificateDer<'_>,
|
||||||
|
_: &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,
|
||||||
|
]
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,42 @@
|
|||||||
|
# Proto 生成的代码说明
|
||||||
|
|
||||||
|
## 概述
|
||||||
|
|
||||||
|
这个目录包含了从 `.proto` 文件预生成的 Rust 代码。
|
||||||
|
|
||||||
|
## 文件说明
|
||||||
|
|
||||||
|
- `serverpb.rs` - 从 `blockrazor.proto` 生成的 gRPC 代码
|
||||||
|
- 消息类型: `SendRequest`, `SendResponse`, `HealthRequest`, `HealthResponse`
|
||||||
|
- gRPC 客户端: `server_client::ServerClient`
|
||||||
|
- gRPC 服务端: `server_server::Server`
|
||||||
|
|
||||||
|
## 用户使用
|
||||||
|
|
||||||
|
用户**不需要**安装 `protoc` 或编译 proto 文件。这些代码已经预生成好了,可以直接使用。
|
||||||
|
|
||||||
|
在 `blockrazor.rs` 中使用:
|
||||||
|
```rust
|
||||||
|
pub mod serverpb {
|
||||||
|
include!("pb/serverpb.rs");
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## 开发者如何重新生成代码
|
||||||
|
|
||||||
|
如果你修改了 `.proto` 文件并需要重新生成代码:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd sol-trade-sdk/proto/gen
|
||||||
|
cargo run
|
||||||
|
```
|
||||||
|
|
||||||
|
这会在 `src/swqos/pb/serverpb.rs` 生成新的代码。
|
||||||
|
|
||||||
|
## 技术细节
|
||||||
|
|
||||||
|
生成工具使用 `tonic-prost-build` crate:
|
||||||
|
- 输出目录: `src/swqos/pb`
|
||||||
|
- Proto 文件: `proto/blockrazor.proto`
|
||||||
|
- 生成工具: `proto/gen/`
|
||||||
|
- 包含完整的客户端和服务端代码
|
||||||
@@ -0,0 +1,383 @@
|
|||||||
|
// This file is @generated by prost-build.
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||||
|
pub struct SendRequest {
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub transaction: ::prost::alloc::string::String,
|
||||||
|
#[prost(string, tag = "2")]
|
||||||
|
pub mode: ::prost::alloc::string::String,
|
||||||
|
/// only take effect in sandwichMitigation mode
|
||||||
|
#[prost(int32, optional, tag = "3")]
|
||||||
|
pub safe_window: ::core::option::Option<i32>,
|
||||||
|
#[prost(bool, tag = "4")]
|
||||||
|
pub revert_protection: bool,
|
||||||
|
}
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||||
|
pub struct SendResponse {
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub signature: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
|
#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
|
||||||
|
pub struct HealthRequest {}
|
||||||
|
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||||
|
pub struct HealthResponse {
|
||||||
|
#[prost(string, tag = "1")]
|
||||||
|
pub status: ::prost::alloc::string::String,
|
||||||
|
}
|
||||||
|
/// Generated client implementations.
|
||||||
|
pub mod server_client {
|
||||||
|
#![allow(
|
||||||
|
unused_variables,
|
||||||
|
dead_code,
|
||||||
|
missing_docs,
|
||||||
|
clippy::wildcard_imports,
|
||||||
|
clippy::let_unit_value,
|
||||||
|
)]
|
||||||
|
use tonic::codegen::*;
|
||||||
|
use tonic::codegen::http::Uri;
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct ServerClient<T> {
|
||||||
|
inner: tonic::client::Grpc<T>,
|
||||||
|
}
|
||||||
|
impl ServerClient<tonic::transport::Channel> {
|
||||||
|
/// Attempt to create a new client by connecting to a given endpoint.
|
||||||
|
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||||
|
where
|
||||||
|
D: TryInto<tonic::transport::Endpoint>,
|
||||||
|
D::Error: Into<StdError>,
|
||||||
|
{
|
||||||
|
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||||
|
Ok(Self::new(conn))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> ServerClient<T>
|
||||||
|
where
|
||||||
|
T: tonic::client::GrpcService<tonic::body::BoxBody>,
|
||||||
|
T::Error: Into<StdError>,
|
||||||
|
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||||
|
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||||
|
{
|
||||||
|
pub fn new(inner: T) -> Self {
|
||||||
|
let inner = tonic::client::Grpc::new(inner);
|
||||||
|
Self { inner }
|
||||||
|
}
|
||||||
|
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||||
|
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||||
|
Self { inner }
|
||||||
|
}
|
||||||
|
pub fn with_interceptor<F>(
|
||||||
|
inner: T,
|
||||||
|
interceptor: F,
|
||||||
|
) -> ServerClient<InterceptedService<T, F>>
|
||||||
|
where
|
||||||
|
F: tonic::service::Interceptor,
|
||||||
|
T::ResponseBody: Default,
|
||||||
|
T: tonic::codegen::Service<
|
||||||
|
http::Request<tonic::body::BoxBody>,
|
||||||
|
Response = http::Response<
|
||||||
|
<T as tonic::client::GrpcService<tonic::body::BoxBody>>::ResponseBody,
|
||||||
|
>,
|
||||||
|
>,
|
||||||
|
<T as tonic::codegen::Service<
|
||||||
|
http::Request<tonic::body::BoxBody>,
|
||||||
|
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||||
|
{
|
||||||
|
ServerClient::new(InterceptedService::new(inner, interceptor))
|
||||||
|
}
|
||||||
|
/// Compress requests with the given encoding.
|
||||||
|
///
|
||||||
|
/// This requires the server to support it otherwise it might respond with an
|
||||||
|
/// error.
|
||||||
|
#[must_use]
|
||||||
|
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.inner = self.inner.send_compressed(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Enable decompressing responses.
|
||||||
|
#[must_use]
|
||||||
|
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.inner = self.inner.accept_compressed(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of a decoded message.
|
||||||
|
///
|
||||||
|
/// Default: `4MB`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.inner = self.inner.max_decoding_message_size(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of an encoded message.
|
||||||
|
///
|
||||||
|
/// Default: `usize::MAX`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.inner = self.inner.max_encoding_message_size(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
pub async fn send_transaction(
|
||||||
|
&mut self,
|
||||||
|
request: impl tonic::IntoRequest<super::SendRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::SendResponse>, tonic::Status> {
|
||||||
|
self.inner
|
||||||
|
.ready()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tonic::Status::unknown(
|
||||||
|
format!("Service was not ready: {}", e.into()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let path = http::uri::PathAndQuery::from_static(
|
||||||
|
"/serverpb.Server/SendTransaction",
|
||||||
|
);
|
||||||
|
let mut req = request.into_request();
|
||||||
|
req.extensions_mut()
|
||||||
|
.insert(GrpcMethod::new("serverpb.Server", "SendTransaction"));
|
||||||
|
self.inner.unary(req, path, codec).await
|
||||||
|
}
|
||||||
|
pub async fn get_health(
|
||||||
|
&mut self,
|
||||||
|
request: impl tonic::IntoRequest<super::HealthRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::HealthResponse>, tonic::Status> {
|
||||||
|
self.inner
|
||||||
|
.ready()
|
||||||
|
.await
|
||||||
|
.map_err(|e| {
|
||||||
|
tonic::Status::unknown(
|
||||||
|
format!("Service was not ready: {}", e.into()),
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let path = http::uri::PathAndQuery::from_static(
|
||||||
|
"/serverpb.Server/GetHealth",
|
||||||
|
);
|
||||||
|
let mut req = request.into_request();
|
||||||
|
req.extensions_mut().insert(GrpcMethod::new("serverpb.Server", "GetHealth"));
|
||||||
|
self.inner.unary(req, path, codec).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Generated server implementations.
|
||||||
|
pub mod server_server {
|
||||||
|
#![allow(
|
||||||
|
unused_variables,
|
||||||
|
dead_code,
|
||||||
|
missing_docs,
|
||||||
|
clippy::wildcard_imports,
|
||||||
|
clippy::let_unit_value,
|
||||||
|
)]
|
||||||
|
use tonic::codegen::*;
|
||||||
|
/// Generated trait containing gRPC methods that should be implemented for use with ServerServer.
|
||||||
|
#[async_trait]
|
||||||
|
pub trait Server: std::marker::Send + std::marker::Sync + 'static {
|
||||||
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
request: tonic::Request<super::SendRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::SendResponse>, tonic::Status>;
|
||||||
|
async fn get_health(
|
||||||
|
&self,
|
||||||
|
request: tonic::Request<super::HealthRequest>,
|
||||||
|
) -> std::result::Result<tonic::Response<super::HealthResponse>, tonic::Status>;
|
||||||
|
}
|
||||||
|
#[derive(Debug)]
|
||||||
|
pub struct ServerServer<T> {
|
||||||
|
inner: Arc<T>,
|
||||||
|
accept_compression_encodings: EnabledCompressionEncodings,
|
||||||
|
send_compression_encodings: EnabledCompressionEncodings,
|
||||||
|
max_decoding_message_size: Option<usize>,
|
||||||
|
max_encoding_message_size: Option<usize>,
|
||||||
|
}
|
||||||
|
impl<T> ServerServer<T> {
|
||||||
|
pub fn new(inner: T) -> Self {
|
||||||
|
Self::from_arc(Arc::new(inner))
|
||||||
|
}
|
||||||
|
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
accept_compression_encodings: Default::default(),
|
||||||
|
send_compression_encodings: Default::default(),
|
||||||
|
max_decoding_message_size: None,
|
||||||
|
max_encoding_message_size: None,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
pub fn with_interceptor<F>(
|
||||||
|
inner: T,
|
||||||
|
interceptor: F,
|
||||||
|
) -> InterceptedService<Self, F>
|
||||||
|
where
|
||||||
|
F: tonic::service::Interceptor,
|
||||||
|
{
|
||||||
|
InterceptedService::new(Self::new(inner), interceptor)
|
||||||
|
}
|
||||||
|
/// Enable decompressing requests with the given encoding.
|
||||||
|
#[must_use]
|
||||||
|
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.accept_compression_encodings.enable(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Compress responses with the given encoding, if the client supports it.
|
||||||
|
#[must_use]
|
||||||
|
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||||
|
self.send_compression_encodings.enable(encoding);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of a decoded message.
|
||||||
|
///
|
||||||
|
/// Default: `4MB`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.max_decoding_message_size = Some(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
/// Limits the maximum size of an encoded message.
|
||||||
|
///
|
||||||
|
/// Default: `usize::MAX`
|
||||||
|
#[must_use]
|
||||||
|
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||||
|
self.max_encoding_message_size = Some(limit);
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T, B> tonic::codegen::Service<http::Request<B>> for ServerServer<T>
|
||||||
|
where
|
||||||
|
T: Server,
|
||||||
|
B: Body + std::marker::Send + 'static,
|
||||||
|
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||||
|
{
|
||||||
|
type Response = http::Response<tonic::body::BoxBody>;
|
||||||
|
type Error = std::convert::Infallible;
|
||||||
|
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||||
|
fn poll_ready(
|
||||||
|
&mut self,
|
||||||
|
_cx: &mut Context<'_>,
|
||||||
|
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||||
|
Poll::Ready(Ok(()))
|
||||||
|
}
|
||||||
|
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||||
|
match req.uri().path() {
|
||||||
|
"/serverpb.Server/SendTransaction" => {
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
struct SendTransactionSvc<T: Server>(pub Arc<T>);
|
||||||
|
impl<T: Server> tonic::server::UnaryService<super::SendRequest>
|
||||||
|
for SendTransactionSvc<T> {
|
||||||
|
type Response = super::SendResponse;
|
||||||
|
type Future = BoxFuture<
|
||||||
|
tonic::Response<Self::Response>,
|
||||||
|
tonic::Status,
|
||||||
|
>;
|
||||||
|
fn call(
|
||||||
|
&mut self,
|
||||||
|
request: tonic::Request<super::SendRequest>,
|
||||||
|
) -> Self::Future {
|
||||||
|
let inner = Arc::clone(&self.0);
|
||||||
|
let fut = async move {
|
||||||
|
<T as Server>::send_transaction(&inner, request).await
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let accept_compression_encodings = self.accept_compression_encodings;
|
||||||
|
let send_compression_encodings = self.send_compression_encodings;
|
||||||
|
let max_decoding_message_size = self.max_decoding_message_size;
|
||||||
|
let max_encoding_message_size = self.max_encoding_message_size;
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
let fut = async move {
|
||||||
|
let method = SendTransactionSvc(inner);
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let mut grpc = tonic::server::Grpc::new(codec)
|
||||||
|
.apply_compression_config(
|
||||||
|
accept_compression_encodings,
|
||||||
|
send_compression_encodings,
|
||||||
|
)
|
||||||
|
.apply_max_message_size_config(
|
||||||
|
max_decoding_message_size,
|
||||||
|
max_encoding_message_size,
|
||||||
|
);
|
||||||
|
let res = grpc.unary(method, req).await;
|
||||||
|
Ok(res)
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
"/serverpb.Server/GetHealth" => {
|
||||||
|
#[allow(non_camel_case_types)]
|
||||||
|
struct GetHealthSvc<T: Server>(pub Arc<T>);
|
||||||
|
impl<T: Server> tonic::server::UnaryService<super::HealthRequest>
|
||||||
|
for GetHealthSvc<T> {
|
||||||
|
type Response = super::HealthResponse;
|
||||||
|
type Future = BoxFuture<
|
||||||
|
tonic::Response<Self::Response>,
|
||||||
|
tonic::Status,
|
||||||
|
>;
|
||||||
|
fn call(
|
||||||
|
&mut self,
|
||||||
|
request: tonic::Request<super::HealthRequest>,
|
||||||
|
) -> Self::Future {
|
||||||
|
let inner = Arc::clone(&self.0);
|
||||||
|
let fut = async move {
|
||||||
|
<T as Server>::get_health(&inner, request).await
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let accept_compression_encodings = self.accept_compression_encodings;
|
||||||
|
let send_compression_encodings = self.send_compression_encodings;
|
||||||
|
let max_decoding_message_size = self.max_decoding_message_size;
|
||||||
|
let max_encoding_message_size = self.max_encoding_message_size;
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
let fut = async move {
|
||||||
|
let method = GetHealthSvc(inner);
|
||||||
|
let codec = tonic::codec::ProstCodec::default();
|
||||||
|
let mut grpc = tonic::server::Grpc::new(codec)
|
||||||
|
.apply_compression_config(
|
||||||
|
accept_compression_encodings,
|
||||||
|
send_compression_encodings,
|
||||||
|
)
|
||||||
|
.apply_max_message_size_config(
|
||||||
|
max_decoding_message_size,
|
||||||
|
max_encoding_message_size,
|
||||||
|
);
|
||||||
|
let res = grpc.unary(method, req).await;
|
||||||
|
Ok(res)
|
||||||
|
};
|
||||||
|
Box::pin(fut)
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
Box::pin(async move {
|
||||||
|
let mut response = http::Response::new(
|
||||||
|
tonic::body::BoxBody::default(),
|
||||||
|
);
|
||||||
|
let headers = response.headers_mut();
|
||||||
|
headers
|
||||||
|
.insert(
|
||||||
|
tonic::Status::GRPC_STATUS,
|
||||||
|
(tonic::Code::Unimplemented as i32).into(),
|
||||||
|
);
|
||||||
|
headers
|
||||||
|
.insert(
|
||||||
|
http::header::CONTENT_TYPE,
|
||||||
|
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||||
|
);
|
||||||
|
Ok(response)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl<T> Clone for ServerServer<T> {
|
||||||
|
fn clone(&self) -> Self {
|
||||||
|
let inner = self.inner.clone();
|
||||||
|
Self {
|
||||||
|
inner,
|
||||||
|
accept_compression_encodings: self.accept_compression_encodings,
|
||||||
|
send_compression_encodings: self.send_compression_encodings,
|
||||||
|
max_decoding_message_size: self.max_decoding_message_size,
|
||||||
|
max_encoding_message_size: self.max_encoding_message_size,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// Generated gRPC service name
|
||||||
|
pub const SERVICE_NAME: &str = "serverpb.Server";
|
||||||
|
impl<T> tonic::server::NamedService for ServerServer<T> {
|
||||||
|
const NAME: &'static str = SERVICE_NAME;
|
||||||
|
}
|
||||||
|
}
|
||||||
+232
-55
@@ -1,20 +1,26 @@
|
|||||||
//! 交易序列化模块
|
//! Transaction serialization module.
|
||||||
|
|
||||||
|
use crate::perf::{
|
||||||
|
compiler_optimization::CompileTimeOptimizedEventProcessor, simd::SIMDSerializer,
|
||||||
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use base64::Engine;
|
|
||||||
use base64::engine::general_purpose::STANDARD;
|
use base64::engine::general_purpose::STANDARD;
|
||||||
|
use base64::Engine;
|
||||||
|
use crossbeam_queue::ArrayQueue;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use solana_client::rpc_client::SerializableTransaction;
|
use solana_client::rpc_client::SerializableTransaction;
|
||||||
use solana_sdk::signature::Signature;
|
use solana_sdk::signature::Signature;
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
use std::sync::Arc;
|
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 {
|
pub struct ZeroAllocSerializer {
|
||||||
buffer_pool: Arc<ArrayQueue<Vec<u8>>>,
|
buffer_pool: Arc<ArrayQueue<Vec<u8>>>,
|
||||||
buffer_size: usize,
|
buffer_size: usize,
|
||||||
@@ -22,30 +28,32 @@ pub struct ZeroAllocSerializer {
|
|||||||
|
|
||||||
impl ZeroAllocSerializer {
|
impl ZeroAllocSerializer {
|
||||||
pub fn new(pool_size: usize, buffer_size: usize) -> Self {
|
pub fn new(pool_size: usize, buffer_size: usize) -> Self {
|
||||||
let pool = ArrayQueue::new(pool_size);
|
Self::new_with_prewarm(pool_size, buffer_size, SERIALIZER_PREWARM_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,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
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 mut buffer = self.buffer_pool.pop().unwrap_or_else(|| {
|
let prewarm_count = prewarm_buffers.min(pool_size);
|
||||||
let mut buf = Vec::with_capacity(self.buffer_size);
|
|
||||||
buf.resize(self.buffer_size, 0);
|
|
||||||
buf
|
|
||||||
});
|
|
||||||
|
|
||||||
// 序列化到缓冲区
|
// 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(|| Vec::with_capacity(self.buffer_size));
|
||||||
|
|
||||||
|
// Serialize into buffer
|
||||||
let serialized = bincode::serialize(data)?;
|
let serialized = bincode::serialize(data)?;
|
||||||
buffer.clear();
|
buffer.clear();
|
||||||
buffer.extend_from_slice(&serialized);
|
buffer.extend_from_slice(&serialized);
|
||||||
@@ -54,11 +62,11 @@ impl ZeroAllocSerializer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub fn return_buffer(&self, buffer: Vec<u8>) {
|
pub fn return_buffer(&self, buffer: Vec<u8>) {
|
||||||
// 归还缓冲区到池中
|
// Return buffer to the pool
|
||||||
let _ = self.buffer_pool.push(buffer);
|
let _ = self.buffer_pool.push(buffer);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取池统计信息
|
/// Get pool statistics.
|
||||||
pub fn get_pool_stats(&self) -> (usize, usize) {
|
pub fn get_pool_stats(&self) -> (usize, usize) {
|
||||||
let available = self.buffer_pool.len();
|
let available = self.buffer_pool.len();
|
||||||
let capacity = self.buffer_pool.capacity();
|
let capacity = self.buffer_pool.capacity();
|
||||||
@@ -66,32 +74,28 @@ impl ZeroAllocSerializer {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 全局序列化器实例
|
/// Global serializer instance.
|
||||||
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> = Lazy::new(|| {
|
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> =
|
||||||
Arc::new(ZeroAllocSerializer::new(
|
Lazy::new(|| Arc::new(ZeroAllocSerializer::new(SERIALIZER_POOL_SIZE, SERIALIZER_BUFFER_SIZE)));
|
||||||
10_000, // 池大小
|
|
||||||
256 * 1024, // 缓冲区大小: 256KB
|
|
||||||
))
|
|
||||||
});
|
|
||||||
|
|
||||||
/// 🚀 编译时优化的事件处理器 (零运行时开销)
|
/// Compile-time optimized event processor (zero runtime cost).
|
||||||
static COMPILE_TIME_PROCESSOR: CompileTimeOptimizedEventProcessor =
|
static COMPILE_TIME_PROCESSOR: CompileTimeOptimizedEventProcessor =
|
||||||
CompileTimeOptimizedEventProcessor::new();
|
CompileTimeOptimizedEventProcessor::new();
|
||||||
|
|
||||||
/// Base64 编码器
|
/// Base64 encoder.
|
||||||
pub struct Base64Encoder;
|
pub struct Base64Encoder;
|
||||||
|
|
||||||
impl Base64Encoder {
|
impl Base64Encoder {
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn encode(data: &[u8]) -> String {
|
pub fn encode(data: &[u8]) -> String {
|
||||||
// 使用编译时优化的哈希进行快速路由
|
// Use compile-time optimized hash for fast routing
|
||||||
let _route = if !data.is_empty() {
|
let _route = if !data.is_empty() {
|
||||||
COMPILE_TIME_PROCESSOR.route_event_zero_cost(data[0])
|
COMPILE_TIME_PROCESSOR.route_event_zero_cost(data[0])
|
||||||
} else {
|
} else {
|
||||||
0
|
0
|
||||||
};
|
};
|
||||||
|
|
||||||
// 使用 SIMD 加速的 Base64 编码
|
// Use SIMD-accelerated Base64 encoding
|
||||||
SIMDSerializer::encode_base64_simd(data)
|
SIMDSerializer::encode_base64_simd(data)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -101,36 +105,104 @@ impl Base64Encoder {
|
|||||||
event_type: &str,
|
event_type: &str,
|
||||||
) -> Result<String> {
|
) -> Result<String> {
|
||||||
let serialized = SERIALIZER.serialize_zero_alloc(value, event_type)?;
|
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,
|
||||||
|
) -> Result<(String, Signature)> {
|
||||||
|
let signature = transaction.get_signature();
|
||||||
|
let serialized_tx = SERIALIZER.serialize_zero_alloc(transaction, "transaction")?;
|
||||||
|
let serialized = match encoding {
|
||||||
|
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
|
||||||
|
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
|
||||||
|
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
||||||
|
};
|
||||||
|
SERIALIZER.return_buffer(serialized_tx);
|
||||||
|
Ok((serialized, *signature))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Serialize a transaction (async; no I/O, kept for API compatibility).
|
||||||
pub async fn serialize_transaction(
|
pub async fn serialize_transaction(
|
||||||
transaction: &impl SerializableTransaction,
|
transaction: &impl SerializableTransaction,
|
||||||
encoding: UiTransactionEncoding,
|
encoding: UiTransactionEncoding,
|
||||||
) -> Result<(String, Signature)> {
|
) -> Result<(String, Signature)> {
|
||||||
let signature = transaction.get_signature();
|
let signature = transaction.get_signature();
|
||||||
|
|
||||||
// 使用零分配序列化
|
// Use zero-allocation serialization
|
||||||
let serialized_tx = SERIALIZER.serialize_zero_alloc(transaction, "transaction")?;
|
let serialized_tx = SERIALIZER.serialize_zero_alloc(transaction, "transaction")?;
|
||||||
|
|
||||||
let serialized = match encoding {
|
let serialized = match encoding {
|
||||||
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
|
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
|
||||||
UiTransactionEncoding::Base64 => {
|
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
|
||||||
// 使用 SIMD 优化的 Base64 编码
|
|
||||||
STANDARD.encode(&serialized_tx)
|
|
||||||
}
|
|
||||||
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
||||||
};
|
};
|
||||||
|
|
||||||
// 立即归还缓冲区到池中
|
// Return buffer to pool immediately
|
||||||
SERIALIZER.return_buffer(serialized_tx);
|
SERIALIZER.return_buffer(serialized_tx);
|
||||||
|
|
||||||
Ok((serialized, *signature))
|
Ok((serialized, *signature))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 批量交易序列化
|
/// Sync batch serialize + encode using buffer pool.
|
||||||
|
pub fn serialize_transactions_batch_sync(
|
||||||
|
transactions: &[impl SerializableTransaction],
|
||||||
|
encoding: UiTransactionEncoding,
|
||||||
|
) -> Result<Vec<String>> {
|
||||||
|
let mut results = Vec::with_capacity(transactions.len());
|
||||||
|
for tx in transactions {
|
||||||
|
let serialized_tx = SERIALIZER.serialize_zero_alloc(tx, "transaction")?;
|
||||||
|
let encoded = match encoding {
|
||||||
|
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
|
||||||
|
UiTransactionEncoding::Base64 => SIMDSerializer::encode_base64_simd(&serialized_tx),
|
||||||
|
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
||||||
|
};
|
||||||
|
SERIALIZER.return_buffer(serialized_tx);
|
||||||
|
results.push(encoded);
|
||||||
|
}
|
||||||
|
Ok(results)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Batch transaction serialization.
|
||||||
pub async fn serialize_transactions_batch(
|
pub async fn serialize_transactions_batch(
|
||||||
transactions: &[impl SerializableTransaction],
|
transactions: &[impl SerializableTransaction],
|
||||||
encoding: UiTransactionEncoding,
|
encoding: UiTransactionEncoding,
|
||||||
@@ -142,7 +214,7 @@ pub async fn serialize_transactions_batch(
|
|||||||
|
|
||||||
let encoded = match encoding {
|
let encoded = match encoding {
|
||||||
UiTransactionEncoding::Base58 => bs58::encode(&serialized_tx).into_string(),
|
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")),
|
_ => return Err(anyhow::anyhow!("Unsupported encoding")),
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -153,7 +225,7 @@ pub async fn serialize_transactions_batch(
|
|||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取序列化器统计信息
|
/// Get serializer statistics.
|
||||||
pub fn get_serializer_stats() -> (usize, usize) {
|
pub fn get_serializer_stats() -> (usize, usize) {
|
||||||
SERIALIZER.get_pool_stats()
|
SERIALIZER.get_pool_stats()
|
||||||
}
|
}
|
||||||
@@ -161,6 +233,7 @@ pub fn get_serializer_stats() -> (usize, usize) {
|
|||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
use super::*;
|
use super::*;
|
||||||
|
use std::time::Instant;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_base64_encode() {
|
fn test_base64_encode() {
|
||||||
@@ -168,7 +241,7 @@ mod tests {
|
|||||||
let encoded = Base64Encoder::encode(data);
|
let encoded = Base64Encoder::encode(data);
|
||||||
assert!(!encoded.is_empty());
|
assert!(!encoded.is_empty());
|
||||||
|
|
||||||
// 验证可以正确解码
|
// Verify it decodes correctly
|
||||||
let decoded = STANDARD.decode(&encoded).unwrap();
|
let decoded = STANDARD.decode(&encoded).unwrap();
|
||||||
assert_eq!(&decoded[..data.len()], data);
|
assert_eq!(&decoded[..data.len()], data);
|
||||||
}
|
}
|
||||||
@@ -177,6 +250,110 @@ mod tests {
|
|||||||
fn test_serializer_stats() {
|
fn test_serializer_stats() {
|
||||||
let (available, capacity) = get_serializer_stats();
|
let (available, capacity) = get_serializer_stats();
|
||||||
assert!(available <= capacity);
|
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);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -7,7 +7,7 @@ use solana_transaction_status::UiTransactionEncoding;
|
|||||||
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
use crate::swqos::SwqosClientTrait;
|
||||||
use crate::{
|
use crate::{
|
||||||
common::SolanaRpcClient,
|
common::{sdk_log, SolanaRpcClient},
|
||||||
swqos::{common::poll_transaction_confirmation, SwqosType, TradeType},
|
swqos::{common::poll_transaction_confirmation, SwqosType, TradeType},
|
||||||
};
|
};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
@@ -25,6 +25,7 @@ impl SwqosClientTrait for SolRpcClient {
|
|||||||
transaction: &VersionedTransaction,
|
transaction: &VersionedTransaction,
|
||||||
wait_confirmation: bool,
|
wait_confirmation: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
|
let submit_start = Instant::now();
|
||||||
let signature = self
|
let signature = self
|
||||||
.rpc_client
|
.rpc_client
|
||||||
.send_transaction_with_config(
|
.send_transaction_with_config(
|
||||||
@@ -39,6 +40,8 @@ impl SwqosClientTrait for SolRpcClient {
|
|||||||
)
|
)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
|
sdk_log::log_swqos_submitted("Default", trade_type, submit_start.elapsed());
|
||||||
|
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
|
|||||||
+85
-9
@@ -6,9 +6,11 @@ use quinn::{
|
|||||||
TransportConfig,
|
TransportConfig,
|
||||||
};
|
};
|
||||||
use rand::seq::IndexedRandom as _;
|
use rand::seq::IndexedRandom as _;
|
||||||
|
use rcgen::{CertificateParams, KeyPair as RcgenKeyPair};
|
||||||
|
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||||
use solana_client::rpc_client::SerializableTransaction;
|
use solana_client::rpc_client::SerializableTransaction;
|
||||||
|
use solana_sdk::signer::Signer;
|
||||||
use solana_sdk::{signature::Keypair, transaction::VersionedTransaction};
|
use solana_sdk::{signature::Keypair, transaction::VersionedTransaction};
|
||||||
use solana_tls_utils::{new_dummy_x509_certificate, SkipServerVerification};
|
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
use std::{
|
use std::{
|
||||||
net::{SocketAddr, ToSocketAddrs as _},
|
net::{SocketAddr, ToSocketAddrs as _},
|
||||||
@@ -25,6 +27,65 @@ use crate::{
|
|||||||
swqos::{SwqosType, TradeType},
|
swqos::{SwqosType, TradeType},
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Skip server verification implementation
|
||||||
|
#[derive(Debug)]
|
||||||
|
struct SkipServerVerification;
|
||||||
|
|
||||||
|
impl SkipServerVerification {
|
||||||
|
fn new() -> Arc<Self> {
|
||||||
|
Arc::new(Self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
|
||||||
|
fn verify_server_cert(
|
||||||
|
&self,
|
||||||
|
_end_entity: &rustls::pki_types::CertificateDer<'_>,
|
||||||
|
_intermediates: &[rustls::pki_types::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: &rustls::pki_types::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: &rustls::pki_types::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]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// TLS 客户端证书:ECDSA P-256 + CN=钱包公钥(与 Speedlanding / Astralane QUIC 策略一致)。
|
||||||
|
fn generate_client_tls_credentials(keypair: &Keypair) -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>)> {
|
||||||
|
let tls_key = RcgenKeyPair::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(keypair.pubkey().to_string()),
|
||||||
|
);
|
||||||
|
let cert = cert_params.self_signed(&tls_key)?;
|
||||||
|
let cert_der = CertificateDer::from(cert.der().to_vec());
|
||||||
|
let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(tls_key.serialize_der()));
|
||||||
|
Ok((cert_der, key_der))
|
||||||
|
}
|
||||||
|
|
||||||
const ALPN_TPU_PROTOCOL_ID: &[u8] = b"solana-tpu";
|
const ALPN_TPU_PROTOCOL_ID: &[u8] = b"solana-tpu";
|
||||||
const SOYAS_SERVER: &str = "soyas-landing";
|
const SOYAS_SERVER: &str = "soyas-landing";
|
||||||
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(25);
|
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(25);
|
||||||
@@ -42,8 +103,13 @@ pub struct SoyasClient {
|
|||||||
impl SoyasClient {
|
impl SoyasClient {
|
||||||
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
|
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let keypair = Keypair::from_base58_string(&api_key);
|
let keypair = Keypair::try_from_base58_string(api_key.trim()).map_err(|e| {
|
||||||
let (cert, key) = new_dummy_x509_certificate(&keypair);
|
anyhow::anyhow!(
|
||||||
|
"Soyas api_token 无法解析为 Solana keypair base58(QUIC mTLS 用): {}",
|
||||||
|
e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
let (cert, key) = generate_client_tls_credentials(&keypair)?;
|
||||||
let mut crypto = rustls::ClientConfig::builder()
|
let mut crypto = rustls::ClientConfig::builder()
|
||||||
.dangerous()
|
.dangerous()
|
||||||
.with_custom_certificate_verifier(SkipServerVerification::new())
|
.with_custom_certificate_verifier(SkipServerVerification::new())
|
||||||
@@ -109,25 +175,35 @@ impl SwqosClientTrait for SoyasClient {
|
|||||||
let serialized_tx = bincode::serialize(transaction)?;
|
let serialized_tx = bincode::serialize(transaction)?;
|
||||||
let connection = self.connection.load_full();
|
let connection = self.connection.load_full();
|
||||||
if Self::try_send_bytes(&connection, &serialized_tx).await.is_err() {
|
if Self::try_send_bytes(&connection, &serialized_tx).await.is_err() {
|
||||||
eprintln!(" [soyas] {} submission failed, reconnecting", trade_type);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("Soyas", trade_type, start_time.elapsed(), "reconnecting");
|
||||||
|
}
|
||||||
self.reconnect().await?;
|
self.reconnect().await?;
|
||||||
let connection = self.connection.load_full();
|
let connection = self.connection.load_full();
|
||||||
if let Err(e) = Self::try_send_bytes(&connection, &serialized_tx).await {
|
if let Err(e) = Self::try_send_bytes(&connection, &serialized_tx).await {
|
||||||
eprintln!(" [soyas] {} submission failed: {:?}", trade_type, e);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("Soyas", trade_type, start_time.elapsed(), &e);
|
||||||
|
}
|
||||||
return Err(e.into());
|
return Err(e.into());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("Soyas", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
|
let start_time = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [soyas] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(" [{:width$}] {} confirmation failed: {:?}", "Soyas", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [soyas] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "Soyas", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+108
-23
@@ -6,7 +6,7 @@ use quinn::{
|
|||||||
TransportConfig,
|
TransportConfig,
|
||||||
};
|
};
|
||||||
use rand::seq::IndexedRandom as _;
|
use rand::seq::IndexedRandom as _;
|
||||||
use solana_rpc_client::rpc_client::SerializableTransaction;
|
use solana_sdk::signer::Signer;
|
||||||
use solana_sdk::{signature::Keypair, transaction::VersionedTransaction};
|
use solana_sdk::{signature::Keypair, transaction::VersionedTransaction};
|
||||||
use solana_tls_utils::{new_dummy_x509_certificate, SkipServerVerification};
|
use solana_tls_utils::{new_dummy_x509_certificate, SkipServerVerification};
|
||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
@@ -16,9 +16,11 @@ use std::{
|
|||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
use tokio::time::timeout;
|
||||||
|
|
||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use crate::swqos::common::poll_transaction_confirmation;
|
use crate::swqos::common::poll_transaction_confirmation;
|
||||||
|
use crate::swqos::serialization::serialize_transaction_bincode_sync;
|
||||||
use crate::swqos::SwqosClientTrait;
|
use crate::swqos::SwqosClientTrait;
|
||||||
use crate::{
|
use crate::{
|
||||||
constants::swqos::SPEEDLANDING_TIP_ACCOUNTS,
|
constants::swqos::SPEEDLANDING_TIP_ACCOUNTS,
|
||||||
@@ -26,9 +28,12 @@ use crate::{
|
|||||||
};
|
};
|
||||||
|
|
||||||
const ALPN_TPU_PROTOCOL_ID: &[u8] = b"solana-tpu";
|
const ALPN_TPU_PROTOCOL_ID: &[u8] = b"solana-tpu";
|
||||||
|
/// QUIC TLS SNI:与 Speedlanding 官方客户端一致,固定为 `speed-landing`(勿用 PoP 主机名,否则易握手失败)。
|
||||||
const SPEED_SERVER: &str = "speed-landing";
|
const SPEED_SERVER: &str = "speed-landing";
|
||||||
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(25);
|
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(25);
|
||||||
const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
const MAX_IDLE_TIMEOUT: Duration = Duration::from_secs(5 * 60);
|
||||||
|
const CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
const SEND_TIMEOUT: Duration = Duration::from_secs(5);
|
||||||
|
|
||||||
pub struct SpeedlandingClient {
|
pub struct SpeedlandingClient {
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
@@ -42,7 +47,13 @@ pub struct SpeedlandingClient {
|
|||||||
impl SpeedlandingClient {
|
impl SpeedlandingClient {
|
||||||
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
|
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let keypair = Keypair::from_base58_string(&api_key);
|
// Speedlanding QUIC:与官方一致使用 `solana_tls_utils::new_dummy_x509_certificate`(Ed25519 dummy cert)+ SNI `speed-landing`。
|
||||||
|
let keypair = Keypair::try_from_base58_string(api_key.trim()).map_err(|e| {
|
||||||
|
anyhow::anyhow!(
|
||||||
|
"Speedlanding api_token 无法解析为 Solana keypair base58(用于 mTLS);请确认粘贴的是机器人提供的密钥而非其它字符串: {}",
|
||||||
|
e
|
||||||
|
)
|
||||||
|
})?;
|
||||||
let (cert, key) = new_dummy_x509_certificate(&keypair);
|
let (cert, key) = new_dummy_x509_certificate(&keypair);
|
||||||
let mut crypto = rustls::ClientConfig::builder()
|
let mut crypto = rustls::ClientConfig::builder()
|
||||||
.dangerous()
|
.dangerous()
|
||||||
@@ -66,7 +77,17 @@ impl SpeedlandingClient {
|
|||||||
.to_socket_addrs()?
|
.to_socket_addrs()?
|
||||||
.next()
|
.next()
|
||||||
.ok_or_else(|| anyhow::anyhow!("Address not resolved"))?;
|
.ok_or_else(|| anyhow::anyhow!("Address not resolved"))?;
|
||||||
let connection = endpoint.connect(addr, SPEED_SERVER)?.await?;
|
let connecting = endpoint.connect(addr, SPEED_SERVER)?;
|
||||||
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
|
.await
|
||||||
|
.context("Speedlanding QUIC connect timeout")?
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Speedlanding QUIC handshake failed(请确认:1) 机器人登记的身份与钱包公钥 {} 一致 2) 本机 UDP 可访问 {} 3) region 与 PoP 匹配)",
|
||||||
|
keypair.pubkey(),
|
||||||
|
endpoint_string
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
rpc_client: Arc::new(rpc_client),
|
rpc_client: Arc::new(rpc_client),
|
||||||
@@ -78,14 +99,37 @@ impl SpeedlandingClient {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn reconnect(&self) -> Result<()> {
|
/// Ensure we have a live connection: if current one is closed, reconnect under lock so
|
||||||
let _guard = self.reconnect.try_lock()?;
|
/// concurrent senders wait and then all use the new connection. Uses blocking lock so
|
||||||
let connection = self
|
/// waiters get the updated connection.
|
||||||
.endpoint
|
async fn ensure_connected(&self) -> Result<Arc<Connection>> {
|
||||||
.connect_with(self.client_config.clone(), self.addr, SPEED_SERVER)?
|
let guard = self.reconnect.lock().await;
|
||||||
.await?;
|
let current = self.connection.load_full();
|
||||||
self.connection.store(Arc::new(connection));
|
if current.close_reason().is_none() {
|
||||||
Ok(())
|
return Ok(current);
|
||||||
|
}
|
||||||
|
drop(guard);
|
||||||
|
let _guard = self.reconnect.lock().await;
|
||||||
|
let current = self.connection.load_full();
|
||||||
|
if current.close_reason().is_some() {
|
||||||
|
let connecting = self.endpoint.connect_with(
|
||||||
|
self.client_config.clone(),
|
||||||
|
self.addr,
|
||||||
|
SPEED_SERVER,
|
||||||
|
)?;
|
||||||
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
|
.await
|
||||||
|
.context("Speedlanding QUIC reconnect timeout")?
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Speedlanding QUIC re-handshake failed(对端 {} SNI {})",
|
||||||
|
self.addr, SPEED_SERVER
|
||||||
|
)
|
||||||
|
})?;
|
||||||
|
self.connection.store(Arc::new(connection));
|
||||||
|
return Ok(self.connection.load_full());
|
||||||
|
}
|
||||||
|
Ok(current)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn try_send_bytes(connection: &Connection, payload: &[u8]) -> Result<()> {
|
async fn try_send_bytes(connection: &Connection, payload: &[u8]) -> Result<()> {
|
||||||
@@ -105,29 +149,70 @@ impl SwqosClientTrait for SpeedlandingClient {
|
|||||||
wait_confirmation: bool,
|
wait_confirmation: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let signature = transaction.get_signature();
|
let (buf_guard, signature) = serialize_transaction_bincode_sync(transaction)?;
|
||||||
let serialized_tx = bincode::serialize(transaction)?;
|
let connection = self.ensure_connected().await?;
|
||||||
let connection = self.connection.load_full();
|
let mut send_result =
|
||||||
if Self::try_send_bytes(&connection, &serialized_tx).await.is_err() {
|
timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||||
eprintln!(" [speedlanding] {} submission failed, reconnecting", trade_type);
|
let need_retry = match &send_result {
|
||||||
self.reconnect().await?;
|
Ok(Ok(())) => false,
|
||||||
let connection = self.connection.load_full();
|
Ok(Err(_)) | Err(_) => true,
|
||||||
if let Err(e) = Self::try_send_bytes(&connection, &serialized_tx).await {
|
};
|
||||||
eprintln!(" [speedlanding] {} submission failed: {:?}", trade_type, e);
|
if need_retry {
|
||||||
|
eprintln!(
|
||||||
|
" [Speedlanding] {} QUIC 首次发送失败 {:?},正在重试",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
|
let connection = self.ensure_connected().await?;
|
||||||
|
send_result =
|
||||||
|
timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||||
|
}
|
||||||
|
match send_result.context("Speedlanding QUIC send timeout") {
|
||||||
|
Ok(Ok(())) => {
|
||||||
|
// 提交结果与「详细耗时/SDK 开关」无关,便于确认当前通道确实在执行
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("Speedlanding", trade_type, start_time.elapsed());
|
||||||
|
}
|
||||||
|
Ok(Err(e)) => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed(
|
||||||
|
"Speedlanding",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
&e,
|
||||||
|
);
|
||||||
|
return Err(e.into());
|
||||||
|
}
|
||||||
|
Err(e) => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed(
|
||||||
|
"Speedlanding",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
"timeout",
|
||||||
|
);
|
||||||
return Err(e.into());
|
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(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [speedlanding] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submission_failed(
|
||||||
|
"Speedlanding",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
&e,
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [speedlanding] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [{:width$}] {} confirmed: {:?}",
|
||||||
|
"Speedlanding",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+82
-46
@@ -1,21 +1,22 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::STELLIUM_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::STELLIUM_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct StelliumClient {
|
pub struct StelliumClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -27,16 +28,29 @@ pub struct StelliumClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for StelliumClient {
|
impl SwqosClientTrait for StelliumClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *STELLIUM_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| STELLIUM_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *STELLIUM_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| STELLIUM_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -48,19 +62,7 @@ impl SwqosClientTrait for StelliumClient {
|
|||||||
impl StelliumClient {
|
impl StelliumClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// 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 keep_alive_running = Arc::new(AtomicBool::new(true));
|
let keep_alive_running = Arc::new(AtomicBool::new(true));
|
||||||
|
|
||||||
@@ -89,34 +91,51 @@ impl StelliumClient {
|
|||||||
let stop_ping = self.keep_alive_running.clone();
|
let stop_ping = self.keep_alive_running.clone();
|
||||||
|
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(60)); // Ping every 60 seconds
|
// Immediate first ping to warm connection and reduce first-submit cold start latency
|
||||||
|
let url = format!("{}/{}", endpoint, auth_token);
|
||||||
|
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() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!(" [Stellium] Ping failed with status: {}", status);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||||
loop {
|
loop {
|
||||||
interval.tick().await;
|
interval.tick().await;
|
||||||
|
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Send ping request
|
|
||||||
let url = format!("{}/{}", endpoint, auth_token);
|
let url = format!("{}/{}", endpoint, auth_token);
|
||||||
match http_client.get(&url).send().await {
|
match http_client.get(&url).timeout(Duration::from_millis(1500)).send().await {
|
||||||
Ok(response) => {
|
Ok(response) => {
|
||||||
if !response.status().is_success() {
|
let status = response.status();
|
||||||
eprintln!(" [Stellium] Ping failed with status: {}", response.status());
|
let _ = response.bytes().await;
|
||||||
|
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!(" [Stellium] Ping failed with status: {}", status);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
eprintln!(" [Stellium] Ping request error: {:?}", e);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!(" [Stellium] Ping request error: {:?}", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Stellium uses standard Solana sendTransaction format
|
// Stellium uses standard Solana sendTransaction format
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -133,7 +152,9 @@ impl StelliumClient {
|
|||||||
let url = format!("{}/{}", self.endpoint, self.auth_token);
|
let url = format!("{}/{}", self.endpoint, self.auth_token);
|
||||||
|
|
||||||
// Send request to Stellium
|
// Send request to Stellium
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Connection", "keep-alive")
|
.header("Connection", "keep-alive")
|
||||||
@@ -145,33 +166,48 @@ impl StelliumClient {
|
|||||||
|
|
||||||
// Parse response
|
// Parse response
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [Stellium] {} submitted: {:?}", trade_type, start_time.elapsed());
|
if response_json.get("result").is_some() {
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
crate::common::sdk_log::log_swqos_submitted("Stellium", trade_type, start_time.elapsed());
|
||||||
eprintln!(" [Stellium] {} submission failed: {:?}", trade_type, _error);
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("Stellium", trade_type, start_time.elapsed(), _error);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [Stellium] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("Stellium", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" [Stellium] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" signature: {:?}", signature);
|
||||||
|
println!(
|
||||||
|
" [{:width$}] {} confirmation failed: {:?}",
|
||||||
|
"Stellium",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed(),
|
||||||
|
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
|
||||||
|
);
|
||||||
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [Stellium] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "Stellium", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+88
-66
@@ -1,27 +1,29 @@
|
|||||||
|
use crate::swqos::common::{
|
||||||
use crate::swqos::common::{poll_transaction_confirmation, serialize_transaction_and_encode};
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use sha2::{Digest, Sha256};
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
use sha2::{Sha256, Digest};
|
use std::time::Duration;
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NOZOMI_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NOZOMI_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
const SPECIAL_API_KEY_PREFIX: &str = "298b5025";
|
const SPECIAL_API_KEY_PREFIX: &str = "298b5025";
|
||||||
const SPECIAL_API_KEY_SUFFIX: &str = "a055323";
|
const SPECIAL_API_KEY_SUFFIX: &str = "a055323";
|
||||||
|
|
||||||
const SPECIAL_API_KEY_HASH: &str = "e7be933c8058aebcb4d08a6120fb4dfd2ead568d42527a3fc2b60a703f25e48d";
|
const SPECIAL_API_KEY_HASH: &str =
|
||||||
|
"e7be933c8058aebcb4d08a6120fb4dfd2ead568d42527a3fc2b60a703f25e48d";
|
||||||
const TEMPORAL_COMMUNITY_TIP_ADDRESS: &str = "mwGELGMgGGrNL1UibNCQeJHDE7qdPptWRYB6noUHmTj";
|
const TEMPORAL_COMMUNITY_TIP_ADDRESS: &str = "mwGELGMgGGrNL1UibNCQeJHDE7qdPptWRYB6noUHmTj";
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -31,7 +33,6 @@ fn fast_sha256_hex(input: &str) -> String {
|
|||||||
format!("{:x}", hasher.finalize())
|
format!("{:x}", hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct TemporalClient {
|
pub struct TemporalClient {
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
@@ -44,18 +45,30 @@ pub struct TemporalClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for TemporalClient {
|
impl SwqosClientTrait for TemporalClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let api_key = &self.auth_token;
|
let api_key = &self.auth_token;
|
||||||
if api_key.len() >= SPECIAL_API_KEY_PREFIX.len() + SPECIAL_API_KEY_SUFFIX.len() {
|
if api_key.len() >= SPECIAL_API_KEY_PREFIX.len() + SPECIAL_API_KEY_SUFFIX.len() {
|
||||||
if api_key.starts_with(SPECIAL_API_KEY_PREFIX) && api_key.ends_with(SPECIAL_API_KEY_SUFFIX) {
|
if api_key.starts_with(SPECIAL_API_KEY_PREFIX)
|
||||||
|
&& api_key.ends_with(SPECIAL_API_KEY_SUFFIX)
|
||||||
|
{
|
||||||
let current_api_key_hash = fast_sha256_hex(api_key);
|
let current_api_key_hash = fast_sha256_hex(api_key);
|
||||||
|
|
||||||
if current_api_key_hash == SPECIAL_API_KEY_HASH {
|
if current_api_key_hash == SPECIAL_API_KEY_HASH {
|
||||||
@@ -64,7 +77,10 @@ impl SwqosClientTrait for TemporalClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let tip_account = *NOZOMI_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NOZOMI_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NOZOMI_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NOZOMI_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -76,35 +92,23 @@ impl SwqosClientTrait for TemporalClient {
|
|||||||
impl TemporalClient {
|
impl TemporalClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// Optimized connection pool settings for high performance
|
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
let client = Self {
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
rpc_client: Arc::new(rpc_client),
|
||||||
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
|
endpoint,
|
||||||
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
|
auth_token,
|
||||||
.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,
|
http_client,
|
||||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Start ping task
|
// Start ping task
|
||||||
let client_clone = client.clone();
|
let client_clone = client.clone();
|
||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
client_clone.start_ping_task().await;
|
client_clone.start_ping_task().await;
|
||||||
});
|
});
|
||||||
|
|
||||||
client
|
client
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,24 +118,25 @@ impl TemporalClient {
|
|||||||
let auth_token = self.auth_token.clone();
|
let auth_token = self.auth_token.clone();
|
||||||
let http_client = self.http_client.clone();
|
let http_client = self.http_client.clone();
|
||||||
let stop_ping = self.stop_ping.clone();
|
let stop_ping = self.stop_ping.clone();
|
||||||
|
|
||||||
let handle = tokio::spawn(async move {
|
let handle = tokio::spawn(async move {
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(60)); // Ping every 60 seconds
|
// 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!("Temporal ping request failed: {}", e);
|
||||||
|
}
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||||
loop {
|
loop {
|
||||||
interval.tick().await;
|
interval.tick().await;
|
||||||
|
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||||
// Send ping request
|
{
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
|
||||||
eprintln!("Temporal ping request failed: {}", e);
|
eprintln!("Temporal ping request failed: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Update ping_handle - use Mutex to safely update
|
// Update ping_handle - use Mutex to safely update
|
||||||
{
|
{
|
||||||
let mut ping_guard = self.ping_handle.lock().await;
|
let mut ping_guard = self.ping_handle.lock().await;
|
||||||
@@ -143,7 +148,11 @@ impl TemporalClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request to /ping endpoint
|
/// Send ping request to /ping endpoint
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, _auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
_auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
// Build ping URL (no auth token required for ping endpoint)
|
// Build ping URL (no auth token required for ping endpoint)
|
||||||
let ping_url = if endpoint.ends_with('/') {
|
let ping_url = if endpoint.ends_with('/') {
|
||||||
format!("{}ping", endpoint)
|
format!("{}ping", endpoint)
|
||||||
@@ -151,24 +160,26 @@ impl TemporalClient {
|
|||||||
format!("{}/ping", endpoint)
|
format!("{}/ping", endpoint)
|
||||||
};
|
};
|
||||||
|
|
||||||
// Send GET request to /ping endpoint
|
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
||||||
let response = http_client.get(&ping_url)
|
let response =
|
||||||
.send()
|
http_client.get(&ping_url).timeout(Duration::from_millis(1500)).send().await?;
|
||||||
.await?;
|
let status = response.status();
|
||||||
|
let _ = response.bytes().await;
|
||||||
if response.status().is_success() {
|
if !status.is_success() {
|
||||||
// ping successful, connection remains active
|
eprintln!("Temporal ping request returned non-success status: {}", status);
|
||||||
// Can optionally log, but to reduce noise, not printing here
|
|
||||||
} else {
|
|
||||||
eprintln!("Temporal ping request returned non-success status: {}", response.status());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Build request body according to Nozomi documentation requirements
|
// Build request body according to Nozomi documentation requirements
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -186,7 +197,9 @@ impl TemporalClient {
|
|||||||
url.push_str("/?c=");
|
url.push_str("/?c=");
|
||||||
url.push_str(&self.auth_token);
|
url.push_str(&self.auth_token);
|
||||||
|
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.send()
|
.send()
|
||||||
@@ -196,12 +209,12 @@ impl TemporalClient {
|
|||||||
|
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
if response_json.get("result").is_some() {
|
if response_json.get("result").is_some() {
|
||||||
println!(" [nozomi] {} submitted: {:?}", trade_type, start_time.elapsed());
|
crate::common::sdk_log::log_swqos_submitted("nozomi", trade_type, start_time.elapsed());
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
} else if let Some(_error) = response_json.get("error") {
|
||||||
// eprintln!("nozomi transaction submission failed: {:?}", _error);
|
crate::common::sdk_log::log_swqos_submission_failed("nozomi", trade_type, start_time.elapsed(), _error);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
eprintln!(" [nozomi] {} submission failed: {:?}", trade_type, response_text);
|
crate::common::sdk_log::log_swqos_submission_failed("nozomi", trade_type, start_time.elapsed(), response_text);
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
let start_time: Instant = Instant::now();
|
||||||
@@ -209,19 +222,28 @@ impl TemporalClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nozomi] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [nozomi] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nozomi] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "nozomi", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
@@ -233,7 +255,7 @@ impl Drop for TemporalClient {
|
|||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
// Ensure ping task stops when client is destroyed
|
// Ensure ping task stops when client is destroyed
|
||||||
self.stop_ping.store(true, Ordering::Relaxed);
|
self.stop_ping.store(true, Ordering::Relaxed);
|
||||||
|
|
||||||
// Try to stop ping task immediately
|
// Try to stop ping task immediately
|
||||||
// Use tokio::spawn to avoid blocking Drop
|
// Use tokio::spawn to avoid blocking Drop
|
||||||
let ping_handle = self.ping_handle.clone();
|
let ping_handle = self.ping_handle.clone();
|
||||||
@@ -245,4 +267,4 @@ impl Drop for TemporalClient {
|
|||||||
*ping_guard = None;
|
*ping_guard = None;
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
+197
-58
@@ -1,40 +1,55 @@
|
|||||||
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 rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use std::{sync::Arc, time::Instant, time::Duration};
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
use std::time::Duration;
|
use bincode;
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::ZEROSLOT_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::ZEROSLOT_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ZeroSlotClient {
|
pub struct ZeroSlotClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
pub auth_token: String,
|
pub auth_token: String,
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
pub http_client: Client,
|
pub http_client: Client,
|
||||||
|
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||||
|
pub stop_ping: Arc<AtomicBool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for ZeroSlotClient {
|
impl SwqosClientTrait for ZeroSlotClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
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(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *ZEROSLOT_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| ZEROSLOT_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *ZEROSLOT_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| ZEROSLOT_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -46,82 +61,206 @@ impl SwqosClientTrait for ZeroSlotClient {
|
|||||||
impl ZeroSlotClient {
|
impl ZeroSlotClient {
|
||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = Client::builder()
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
// Optimized connection pool settings for high performance
|
|
||||||
.pool_idle_timeout(Duration::from_secs(120))
|
let client = Self {
|
||||||
.pool_max_idle_per_host(256) // Increased from 64 to 256
|
rpc_client: Arc::new(rpc_client),
|
||||||
.tcp_keepalive(Some(Duration::from_secs(60))) // Reduced from 1200 to 60
|
endpoint,
|
||||||
.tcp_nodelay(true) // Disable Nagle's algorithm for lower latency
|
auth_token,
|
||||||
.http2_keep_alive_interval(Duration::from_secs(10))
|
http_client,
|
||||||
.http2_keep_alive_timeout(Duration::from_secs(5))
|
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||||
.http2_adaptive_window(true) // Enable adaptive flow control
|
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||||
.timeout(Duration::from_millis(3000)) // Reduced from 10s to 3s
|
};
|
||||||
.connect_timeout(Duration::from_millis(2000)) // Reduced from 5s to 2s
|
|
||||||
.build()
|
// Start ping task
|
||||||
.unwrap();
|
let client_clone = client.clone();
|
||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
tokio::spawn(async move {
|
||||||
|
client_clone.start_ping_task().await;
|
||||||
|
});
|
||||||
|
|
||||||
|
client
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
/// Start periodic ping task to keep connections active
|
||||||
|
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 {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("0slot ping request failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive under 65s server timeout
|
||||||
|
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 {
|
||||||
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
|
eprintln!("0slot ping request failed: {}", e);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// 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();
|
||||||
|
}
|
||||||
|
*ping_guard = Some(handle);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Send ping request: POST with getHealth method (Keep Alive). Free operation, not counted toward TPS.
|
||||||
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
|
let url = format!("{}/?api-key={}", endpoint, auth_token);
|
||||||
|
let response = http_client
|
||||||
|
.post(&url)
|
||||||
|
.header("Content-Type", "application/json")
|
||||||
|
.timeout(Duration::from_millis(1500))
|
||||||
|
.body(r#"{"jsonrpc":"2.0","id":1,"method":"getHealth"}"#)
|
||||||
|
.send()
|
||||||
|
.await?;
|
||||||
|
let _ = response.bytes().await;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64).await?;
|
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
// Binary-Tx: Send raw binary transaction bytes directly
|
||||||
"jsonrpc": "2.0",
|
// This is faster than JSON-RPC as it avoids unnecessary encoding/decoding
|
||||||
"id": 1,
|
let tx_bytes = bincode::serialize(transaction)?;
|
||||||
"method": "sendTransaction",
|
|
||||||
"params": [
|
|
||||||
content,
|
|
||||||
{ "encoding": "base64", "skipPreflight": true }
|
|
||||||
]
|
|
||||||
}))?;
|
|
||||||
|
|
||||||
|
// Build URL for Binary-Tx endpoint: {endpoint}/txb?api-key={auth_token}
|
||||||
let mut url = String::with_capacity(self.endpoint.len() + self.auth_token.len() + 20);
|
let mut url = String::with_capacity(self.endpoint.len() + self.auth_token.len() + 20);
|
||||||
url.push_str(&self.endpoint);
|
url.push_str(&self.endpoint);
|
||||||
url.push_str("/?api-key=");
|
url.push_str("/txb?api-key=");
|
||||||
url.push_str(&self.auth_token);
|
url.push_str(&self.auth_token);
|
||||||
|
|
||||||
// 4. Use `text().await?` directly, avoiding async JSON parsing from `json().await?`
|
// Send binary transaction directly
|
||||||
let response_text = self.http_client.post(&url)
|
let response = self
|
||||||
.body(request_body) // Pass string directly, avoiding `json()` overhead
|
.http_client
|
||||||
.header("Content-Type", "application/json") // Explicitly specify JSON header
|
.post(&url)
|
||||||
|
.header("User-Agent", "") // Optional: 0slot recommends empty User-Agent
|
||||||
|
.body(tx_bytes)
|
||||||
.send()
|
.send()
|
||||||
.await?
|
|
||||||
.text()
|
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// 5. Use `serde_json::from_str()` to parse JSON, reducing extra wait from `.json().await?`
|
let status = response.status();
|
||||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
let response_text = response.text().await?;
|
||||||
if response_json.get("result").is_some() {
|
|
||||||
println!(" [0slot] {} submitted: {:?}", trade_type, start_time.elapsed());
|
// Binary-Tx returns JSON-RPC 2.0 format responses
|
||||||
} else if let Some(_error) = response_json.get("error") {
|
// 200: success with result field containing signature, or error field with code/message
|
||||||
eprintln!(" [0slot] {} submission failed: {:?}", trade_type, _error);
|
// 403: api-key error (null, doesn't exist, or expired)
|
||||||
|
// 419: rate limit exceeded
|
||||||
|
// 500: submission failed
|
||||||
|
match status.as_u16() {
|
||||||
|
200 => {
|
||||||
|
if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||||
|
if json_value.get("result").is_some() {
|
||||||
|
crate::common::sdk_log::log_swqos_submitted("0slot", trade_type, start_time.elapsed());
|
||||||
|
} else if let Some(error) = json_value.get("error") {
|
||||||
|
let code = error.get("code")
|
||||||
|
.and_then(|c| c.as_i64())
|
||||||
|
.map(|c| c.to_string())
|
||||||
|
.unwrap_or_else(|| "unknown".to_string());
|
||||||
|
let message = error.get("message")
|
||||||
|
.and_then(|m| m.as_str())
|
||||||
|
.unwrap_or("unknown error");
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("code {}: {}", code, message));
|
||||||
|
return Err(anyhow::anyhow!("0slot Binary-Tx error: {}", message));
|
||||||
|
} else {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("unexpected JSON: {}", response_text));
|
||||||
|
return Err(anyhow::anyhow!("0slot Binary-Tx unexpected JSON: {}", response_text));
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("invalid JSON: {}", response_text));
|
||||||
|
return Err(anyhow::anyhow!("0slot Binary-Tx invalid JSON: {}", response_text));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
403 => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
|
||||||
|
return Err(anyhow::anyhow!("0slot API key error: {}", response_text));
|
||||||
|
}
|
||||||
|
419 => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
|
||||||
|
return Err(anyhow::anyhow!("0slot rate limit exceeded"));
|
||||||
|
}
|
||||||
|
500 => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), "submission failed".to_string());
|
||||||
|
return Err(anyhow::anyhow!("0slot transaction submission failed"));
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("status {} body: {}", status, response_text));
|
||||||
|
return Err(anyhow::anyhow!("0slot Binary-Tx failed with status {}: {}", status, response_text));
|
||||||
}
|
}
|
||||||
} else {
|
|
||||||
eprintln!(" [0slot] {} submission failed: {:?}", trade_type, response_text);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
let start_time: Instant = Instant::now();
|
// Get transaction signature from the transaction for confirmation polling
|
||||||
|
let signature = transaction.signatures[0];
|
||||||
|
|
||||||
|
let start_time = Instant::now();
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [0slot] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmation failed: {:?}", "0slot", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [0slot] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
println!(" [{:width$}] {} confirmed: {:?}", "0slot", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl Drop for ZeroSlotClient {
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
*ping_guard = None;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -1,8 +1,9 @@
|
|||||||
use dashmap::DashMap;
|
use dashmap::DashMap;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use solana_sdk::instruction::Instruction;
|
|
||||||
use solana_compute_budget_interface::ComputeBudgetInstruction;
|
use solana_compute_budget_interface::ComputeBudgetInstruction;
|
||||||
|
use solana_sdk::instruction::Instruction;
|
||||||
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Cache key containing all parameters for compute budget instructions
|
/// Cache key containing all parameters for compute budget instructions
|
||||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||||
@@ -11,43 +12,52 @@ struct ComputeBudgetCacheKey {
|
|||||||
unit_limit: u32,
|
unit_limit: u32,
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Global cache storing compute budget instructions
|
/// Global cache storing compute budget instructions (Arc to avoid clone on hit).
|
||||||
/// Uses DashMap for high-performance lock-free concurrent access
|
/// Uses DashMap for high-performance lock-free concurrent access.
|
||||||
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 2]>>> =
|
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, Arc<SmallVec<[Instruction; 2]>>>> =
|
||||||
Lazy::new(|| DashMap::new());
|
Lazy::new(|| DashMap::new());
|
||||||
|
|
||||||
|
/// Extend `instructions` with compute budget instructions; on cache hit extends from cached Arc (no SmallVec clone).
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn compute_budget_instructions(
|
pub fn extend_compute_budget_instructions(
|
||||||
|
instructions: &mut Vec<Instruction>,
|
||||||
unit_price: u64,
|
unit_price: u64,
|
||||||
unit_limit: u32,
|
unit_limit: u32,
|
||||||
) -> SmallVec<[Instruction; 2]> {
|
) {
|
||||||
// Create cache key
|
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
|
||||||
let cache_key = ComputeBudgetCacheKey {
|
|
||||||
unit_price: unit_price,
|
|
||||||
unit_limit: unit_limit,
|
|
||||||
};
|
|
||||||
|
|
||||||
// Try to get from cache first
|
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
||||||
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
instructions.extend(cached.iter().cloned());
|
||||||
return cached_insts.clone();
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Cache miss, generate new instructions
|
|
||||||
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
||||||
|
|
||||||
// Only add compute unit price instruction if > 0
|
|
||||||
if unit_price > 0 {
|
if unit_price > 0 {
|
||||||
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
|
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
|
||||||
}
|
}
|
||||||
|
|
||||||
// Only add compute unit limit instruction if > 0
|
|
||||||
if unit_limit > 0 {
|
if unit_limit > 0 {
|
||||||
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
|
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
|
/// Returns compute budget instructions (allocates on cache hit; prefer `extend_compute_budget_instructions` on hot path).
|
||||||
let insts_clone = insts.clone();
|
#[inline(always)]
|
||||||
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
|
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
|
insts
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
|
pub mod compute_budget_manager;
|
||||||
pub mod nonce_manager;
|
pub mod nonce_manager;
|
||||||
pub mod transaction_builder;
|
pub mod transaction_builder;
|
||||||
pub mod compute_budget_manager;
|
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
pub mod wsol_manager;
|
pub mod wsol_manager;
|
||||||
|
|
||||||
// Re-export commonly used functions
|
// Re-export commonly used functions
|
||||||
|
pub use compute_budget_manager::*;
|
||||||
pub use nonce_manager::*;
|
pub use nonce_manager::*;
|
||||||
pub use transaction_builder::*;
|
pub use transaction_builder::*;
|
||||||
pub use compute_budget_manager::*;
|
|
||||||
pub use utils::*;
|
pub use utils::*;
|
||||||
pub use wsol_manager::*;
|
pub use wsol_manager::*;
|
||||||
|
|||||||
@@ -12,29 +12,33 @@ use crate::common::nonce_cache::DurableNonceInfo;
|
|||||||
pub fn add_nonce_instruction(
|
pub fn add_nonce_instruction(
|
||||||
instructions: &mut Vec<Instruction>,
|
instructions: &mut Vec<Instruction>,
|
||||||
payer: &Keypair,
|
payer: &Keypair,
|
||||||
// nonce_account: Option<Pubkey>,
|
durable_nonce: Option<&DurableNonceInfo>,
|
||||||
// current_nonce: Option<Hash>,
|
|
||||||
durable_nonce: Option<DurableNonceInfo>,
|
|
||||||
) -> Result<(), anyhow::Error> {
|
) -> Result<(), anyhow::Error> {
|
||||||
if let Some(durable_nonce) = durable_nonce {
|
if let Some(durable_nonce) = durable_nonce {
|
||||||
let nonce_advance_ix = advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
|
let nonce_advance_ix =
|
||||||
|
advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
|
||||||
instructions.push(nonce_advance_ix);
|
instructions.push(nonce_advance_ix);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Get blockhash for transaction
|
/// Get blockhash for transaction.
|
||||||
/// If nonce account is used, return blockhash from nonce, otherwise return the provided recent_blockhash
|
/// 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(
|
pub fn get_transaction_blockhash(
|
||||||
recent_blockhash: Option<Hash>,
|
recent_blockhash: Option<Hash>,
|
||||||
durable_nonce: Option<DurableNonceInfo>,
|
durable_nonce: Option<&DurableNonceInfo>,
|
||||||
// nonce_account: Option<Pubkey>,
|
) -> Result<Hash, anyhow::Error> {
|
||||||
// current_nonce: Option<Hash>,
|
|
||||||
) -> Hash {
|
|
||||||
if let Some(durable_nonce) = durable_nonce {
|
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 {
|
} else {
|
||||||
recent_blockhash.unwrap()
|
Err(anyhow::anyhow!(
|
||||||
|
"Must provide either recent_blockhash or durable_nonce for transaction"
|
||||||
|
))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,70 +1,70 @@
|
|||||||
use solana_hash::Hash;
|
use solana_hash::Hash;
|
||||||
use solana_sdk::{
|
use solana_sdk::{
|
||||||
instruction::Instruction, message::AddressLookupTableAccount, native_token::sol_str_to_lamports, pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::VersionedTransaction
|
instruction::Instruction, pubkey::Pubkey,
|
||||||
|
signature::Keypair, signer::Signer, transaction::VersionedTransaction,
|
||||||
};
|
};
|
||||||
use solana_system_interface::instruction::transfer;
|
use solana_message::AddressLookupTableAccount;
|
||||||
|
use solana_system_interface::instruction as system_instruction;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use super::{
|
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
|
||||||
compute_budget_manager::compute_budget_instructions,
|
|
||||||
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
|
|
||||||
};
|
|
||||||
use crate::{
|
use crate::{
|
||||||
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
|
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
|
||||||
constants::swqos::NODE1_TIP_ACCOUNTS,
|
trading::{
|
||||||
trading::{MiddlewareManager, core::transaction_pool::{acquire_builder, release_builder}},
|
core::transaction_pool::{acquire_builder, release_builder},
|
||||||
|
MiddlewareManager,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// 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 (worker hot path).
|
||||||
|
/// Takes Arc/refs only; one Vec allocation (with_capacity), extend_from_slice for business_instructions, no extra clone of payer/rpc/middleware.
|
||||||
pub async fn build_transaction(
|
pub async fn build_transaction(
|
||||||
payer: Arc<Keypair>,
|
payer: &Arc<Keypair>,
|
||||||
rpc: Option<Arc<SolanaRpcClient>>,
|
_rpc: Option<&Arc<SolanaRpcClient>>,
|
||||||
unit_limit: u32,
|
unit_limit: u32,
|
||||||
unit_price: u64,
|
unit_price: u64,
|
||||||
business_instructions: Vec<Instruction>,
|
business_instructions: &[Instruction],
|
||||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
address_lookup_table_account: Option<&AddressLookupTableAccount>,
|
||||||
recent_blockhash: Option<Hash>,
|
recent_blockhash: Option<Hash>,
|
||||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
middleware_manager: Option<&Arc<MiddlewareManager>>,
|
||||||
protocol_name: &str,
|
protocol_name: &str,
|
||||||
is_buy: bool,
|
is_buy: bool,
|
||||||
with_tip: bool,
|
with_tip: bool,
|
||||||
tip_account: &Pubkey,
|
tip_account: &Pubkey,
|
||||||
tip_amount: f64,
|
tip_amount: f64,
|
||||||
durable_nonce: Option<DurableNonceInfo>,
|
durable_nonce: Option<&DurableNonceInfo>,
|
||||||
// nonce_account: Option<Pubkey>,
|
|
||||||
// current_nonce: Option<Hash>,
|
|
||||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||||
let mut instructions = Vec::with_capacity(business_instructions.len() + 5);
|
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) {
|
||||||
if let Err(e) =
|
|
||||||
add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce.clone())
|
|
||||||
{
|
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add tip transfer instruction
|
|
||||||
if with_tip && tip_amount > 0.0 {
|
if with_tip && tip_amount > 0.0 {
|
||||||
instructions.push(transfer(
|
let tip_lamports = sol_f64_to_lamports(tip_amount);
|
||||||
&payer.pubkey(),
|
instructions.push(system_instruction::transfer(&payer.pubkey(), tip_account, tip_lamports));
|
||||||
tip_account,
|
|
||||||
sol_str_to_lamports(tip_amount.to_string().as_str()).unwrap_or(0),
|
|
||||||
));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Add compute budget instructions
|
super::compute_budget_manager::extend_compute_budget_instructions(
|
||||||
instructions.extend(compute_budget_instructions(
|
&mut instructions,
|
||||||
unit_price,
|
unit_price,
|
||||||
unit_limit,
|
unit_limit,
|
||||||
));
|
);
|
||||||
|
|
||||||
// Add business instructions
|
instructions.extend_from_slice(business_instructions);
|
||||||
instructions.extend(business_instructions);
|
|
||||||
|
|
||||||
// Get blockhash for transaction
|
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce)?;
|
||||||
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce.clone());
|
|
||||||
|
|
||||||
// Build transaction
|
|
||||||
build_versioned_transaction(
|
build_versioned_transaction(
|
||||||
payer,
|
payer,
|
||||||
instructions,
|
instructions,
|
||||||
@@ -77,23 +77,18 @@ pub async fn build_transaction(
|
|||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Low-level function for building versioned transactions
|
|
||||||
async fn build_versioned_transaction(
|
async fn build_versioned_transaction(
|
||||||
payer: Arc<Keypair>,
|
payer: &Arc<Keypair>,
|
||||||
instructions: Vec<Instruction>,
|
instructions: Vec<Instruction>,
|
||||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
address_lookup_table_account: Option<&AddressLookupTableAccount>,
|
||||||
blockhash: Hash,
|
blockhash: Hash,
|
||||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
middleware_manager: Option<&Arc<MiddlewareManager>>,
|
||||||
protocol_name: &str,
|
protocol_name: &str,
|
||||||
is_buy: bool,
|
is_buy: bool,
|
||||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||||
let full_instructions = match middleware_manager {
|
let full_instructions = match middleware_manager {
|
||||||
Some(middleware_manager) => middleware_manager
|
Some(middleware_manager) => middleware_manager
|
||||||
.apply_middlewares_process_full_instructions(
|
.apply_middlewares_process_full_instructions(instructions, protocol_name, is_buy)?,
|
||||||
instructions,
|
|
||||||
protocol_name.to_string(),
|
|
||||||
is_buy,
|
|
||||||
)?,
|
|
||||||
None => instructions,
|
None => instructions,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -108,7 +103,7 @@ async fn build_versioned_transaction(
|
|||||||
);
|
);
|
||||||
|
|
||||||
let msg_bytes = versioned_msg.serialize();
|
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 };
|
let tx = VersionedTransaction { signatures: vec![signature], message: versioned_msg };
|
||||||
|
|
||||||
// 归还构建器到池
|
// 归还构建器到池
|
||||||
|
|||||||
@@ -1,8 +1,12 @@
|
|||||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::Transaction};
|
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::Transaction};
|
||||||
use solana_system_interface::instruction::transfer;
|
use solana_system_interface::instruction as system_instruction;
|
||||||
|
|
||||||
use crate::common::{
|
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,
|
SolanaRpcClient,
|
||||||
};
|
};
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
@@ -36,10 +40,23 @@ pub async fn get_token_balance(
|
|||||||
payer: &Pubkey,
|
payer: &Pubkey,
|
||||||
mint: &Pubkey,
|
mint: &Pubkey,
|
||||||
) -> Result<u64, anyhow::Error> {
|
) -> 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,
|
payer,
|
||||||
mint,
|
mint,
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
token_program,
|
||||||
|
use_seed,
|
||||||
);
|
);
|
||||||
let balance = rpc.get_token_account_balance(&ata).await?;
|
let balance = rpc.get_token_account_balance(&ata).await?;
|
||||||
let balance_u64 =
|
let balance_u64 =
|
||||||
@@ -71,7 +88,7 @@ pub async fn transfer_sol(
|
|||||||
return Err(anyhow!("Insufficient balance"));
|
return Err(anyhow!("Insufficient balance"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let transfer_instruction = transfer(&payer.pubkey(), receive_wallet, amount);
|
let transfer_instruction = system_instruction::transfer(&payer.pubkey(), receive_wallet, amount);
|
||||||
|
|
||||||
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
let recent_blockhash = rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
use crate::common::{
|
use crate::common::{
|
||||||
fast_fn::create_associated_token_account_idempotent_fast,
|
fast_fn::create_associated_token_account_idempotent_fast,
|
||||||
|
seed::{
|
||||||
|
create_associated_token_account_use_seed,
|
||||||
|
get_associated_token_address_with_program_id_use_seed,
|
||||||
|
},
|
||||||
spl_token::close_account,
|
spl_token::close_account,
|
||||||
seed::{create_associated_token_account_use_seed, get_associated_token_address_with_program_id_use_seed},
|
|
||||||
};
|
};
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use solana_sdk::{instruction::Instruction, message::AccountMeta, pubkey::Pubkey};
|
use solana_sdk::{instruction::Instruction, instruction::AccountMeta, pubkey::Pubkey};
|
||||||
use solana_system_interface::instruction::transfer;
|
use solana_system_interface::instruction as system_instruction;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]> {
|
pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]> {
|
||||||
@@ -24,7 +27,7 @@ pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]>
|
|||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
));
|
));
|
||||||
insts.extend([
|
insts.extend([
|
||||||
transfer(&payer, &wsol_token_account, amount_in),
|
system_instruction::transfer(&payer, &wsol_token_account, amount_in),
|
||||||
// sync_native
|
// sync_native
|
||||||
Instruction {
|
Instruction {
|
||||||
program_id: crate::constants::TOKEN_PROGRAM,
|
program_id: crate::constants::TOKEN_PROGRAM,
|
||||||
@@ -38,7 +41,7 @@ pub fn handle_wsol(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 3]>
|
|||||||
|
|
||||||
pub fn close_wsol(payer: &Pubkey) -> Vec<Instruction> {
|
pub fn close_wsol(payer: &Pubkey) -> Vec<Instruction> {
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
let wsol_token_account =
|
let wsol_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
&payer,
|
&payer,
|
||||||
@@ -61,7 +64,7 @@ pub fn close_wsol(payer: &Pubkey) -> Vec<Instruction> {
|
|||||||
.unwrap()]
|
.unwrap()]
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// 🚀 性能优化:尝试零开销解包 Arc
|
// 🚀 性能优化:尝试零开销解包 Arc
|
||||||
Arc::try_unwrap(arc_instructions).unwrap_or_else(|arc| (*arc).clone())
|
Arc::try_unwrap(arc_instructions).unwrap_or_else(|arc| (*arc).clone())
|
||||||
}
|
}
|
||||||
@@ -88,7 +91,7 @@ pub fn wrap_sol_only(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 2
|
|||||||
|
|
||||||
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
||||||
insts.extend([
|
insts.extend([
|
||||||
transfer(&payer, &wsol_token_account, amount_in),
|
system_instruction::transfer(&payer, &wsol_token_account, amount_in),
|
||||||
// sync_native
|
// sync_native
|
||||||
Instruction {
|
Instruction {
|
||||||
program_id: crate::constants::TOKEN_PROGRAM,
|
program_id: crate::constants::TOKEN_PROGRAM,
|
||||||
@@ -109,10 +112,7 @@ pub fn wrap_sol_only(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 2
|
|||||||
///
|
///
|
||||||
/// 注意:此函数只生成指令,不检查账户是否存在(需要调用方在发送交易前检查)
|
/// 注意:此函数只生成指令,不检查账户是否存在(需要调用方在发送交易前检查)
|
||||||
/// 如果临时账户已存在,可以安全地跳过创建步骤,直接转账并关闭
|
/// 如果临时账户已存在,可以安全地跳过创建步骤,直接转账并关闭
|
||||||
pub fn wrap_wsol_to_sol(
|
pub fn wrap_wsol_to_sol(payer: &Pubkey, amount: u64) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||||
payer: &Pubkey,
|
|
||||||
amount: u64,
|
|
||||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
|
||||||
let mut instructions = Vec::new();
|
let mut instructions = Vec::new();
|
||||||
|
|
||||||
// 1. 创建 WSOL seed 账户(注意:如果账户已存在会失败)
|
// 1. 创建 WSOL seed 账户(注意:如果账户已存在会失败)
|
||||||
@@ -151,13 +151,8 @@ pub fn wrap_wsol_to_sol(
|
|||||||
instructions.push(transfer_instruction);
|
instructions.push(transfer_instruction);
|
||||||
|
|
||||||
// 5. 添加关闭 WSOL seed 账户的指令
|
// 5. 添加关闭 WSOL seed 账户的指令
|
||||||
let close_instruction = close_account(
|
let close_instruction =
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
close_account(&crate::constants::TOKEN_PROGRAM, &seed_ata_address, payer, payer, &[])?;
|
||||||
&seed_ata_address,
|
|
||||||
payer,
|
|
||||||
payer,
|
|
||||||
&[],
|
|
||||||
)?;
|
|
||||||
instructions.push(close_instruction);
|
instructions.push(close_instruction);
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
@@ -197,13 +192,8 @@ pub fn wrap_wsol_to_sol_without_create(
|
|||||||
instructions.push(transfer_instruction);
|
instructions.push(transfer_instruction);
|
||||||
|
|
||||||
// 4. 添加关闭 WSOL seed 账户的指令
|
// 4. 添加关闭 WSOL seed 账户的指令
|
||||||
let close_instruction = close_account(
|
let close_instruction =
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
close_account(&crate::constants::TOKEN_PROGRAM, &seed_ata_address, payer, payer, &[])?;
|
||||||
&seed_ata_address,
|
|
||||||
payer,
|
|
||||||
payer,
|
|
||||||
&[],
|
|
||||||
)?;
|
|
||||||
instructions.push(close_instruction);
|
instructions.push(close_instruction);
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user