Compare commits
19 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| d7b0985844 | |||
| 2e39649ebc | |||
| 0201d3443a | |||
| 9872b1b4a7 | |||
| e16cd6620f | |||
| 9f79e865ab | |||
| e32e7ee6ab | |||
| 30c91a74af | |||
| 6c41e1cfe6 | |||
| a003fd4d2f | |||
| fd5af3ab61 | |||
| 7e2860d8de | |||
| 07487c06cb | |||
| 1142829394 | |||
| d2ce193e2c | |||
| 46564f1bb5 | |||
| 63afac7aea | |||
| d9b9ddc53f | |||
| d610745c7e |
+4
-2
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sol-trade-sdk"
|
||||
version = "3.5.6"
|
||||
version = "3.6.2"
|
||||
edition = "2021"
|
||||
authors = [
|
||||
"William <byteblock6@gmail.com>",
|
||||
@@ -107,7 +107,9 @@ parking_lot = "0.12"
|
||||
arc-swap = "1.7"
|
||||
sha2 = "0.10"
|
||||
tonic-prost = "0.14.2"
|
||||
quinn = {version = "0.11", default-features = false, features = ["rustls"]}
|
||||
quinn = { version = "0.11", default-features = false, features = ["rustls"] }
|
||||
rcgen = "0.13"
|
||||
uuid = "1.11"
|
||||
|
||||
# Performance optimization dependencies
|
||||
crossbeam-queue = "0.3"
|
||||
|
||||
@@ -48,6 +48,7 @@
|
||||
- [⚡ Trading Parameters](#-trading-parameters)
|
||||
- [📊 Usage Examples Summary Table](#-usage-examples-summary-table)
|
||||
- [⚙️ SWQoS Service Configuration](#️-swqos-service-configuration)
|
||||
- [Astralane QUIC (Low-Latency)](#astralane-quic-low-latency)
|
||||
- [🔧 Middleware System](#-middleware-system)
|
||||
- [🔍 Address Lookup Tables](#-address-lookup-tables)
|
||||
- [🔍 Nonce Cache](#-nonce-cache)
|
||||
@@ -89,14 +90,14 @@ Add the dependency to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.5.6" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.2" }
|
||||
```
|
||||
|
||||
### Use crates.io
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = "3.5.6"
|
||||
sol-trade-sdk = "3.6.2"
|
||||
```
|
||||
|
||||
## 🛠️ Usage Examples
|
||||
@@ -119,6 +120,14 @@ let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
// Astralane: HTTP (4th param None) or QUIC (Some(SwqosTransport::Quic)); same API key
|
||||
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // HTTP
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt,
|
||||
None,
|
||||
Some(SwqosTransport::Quic),
|
||||
), // QUIC
|
||||
];
|
||||
// Create TradeConfig instance
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
@@ -257,6 +266,29 @@ let bloxroute_config = SwqosConfig::Bloxroute(
|
||||
|
||||
When using multiple MEV services, you need to use `Durable Nonce`. You need to use the `fetch_nonce_info` function to get the latest `nonce` value, and use it as the `durable_nonce` when trading.
|
||||
|
||||
#### Astralane QUIC (Low-Latency)
|
||||
|
||||
Astralane supports both HTTP and **QUIC** transport. QUIC reduces connection overhead and can lower submission latency. To use the QUIC channel, pass `Some(SwqosTransport::Quic)` as the fourth parameter of `SwqosConfig::Astralane`. Astralane’s QUIC service uses a **single endpoint** (no per-region endpoints); the SDK ignores the `region` (and optional custom URL) when QUIC is selected. You can pass the same region as your other SWQoS configs for consistency.
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{SwqosConfig, SwqosRegion, SwqosTransport};
|
||||
|
||||
// Astralane over QUIC (low-latency); region is ignored (single QUIC endpoint)
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt, // same as other services; ignored for QUIC
|
||||
None,
|
||||
Some(SwqosTransport::Quic),
|
||||
),
|
||||
];
|
||||
// Then create TradeConfig / TradingClient as usual with swqos_configs
|
||||
```
|
||||
|
||||
- **HTTP** (default): use `None` or `Some(SwqosTransport::Http)`; region and optional custom URL apply.
|
||||
- **QUIC**: use `Some(SwqosTransport::Quic)`; the SDK uses a single QUIC endpoint and ignores region. Same API key as HTTP.
|
||||
|
||||
---
|
||||
|
||||
### 🔧 Middleware System
|
||||
@@ -289,6 +321,24 @@ PumpFun and PumpSwap support **cashback** for eligible tokens: part of the tradi
|
||||
- The **pumpfun_copy_trading** and **pumpfun_sniper_trading** examples use sol-parser-sdk for gRPC subscription and pass `e.is_cashback_coin` when building params.
|
||||
- **Claim**: Use `client.claim_cashback_pumpfun()` and `client.claim_cashback_pumpswap(...)` to claim accumulated cashback.
|
||||
|
||||
#### PumpFun: Creator Rewards Sharing (creator_vault)
|
||||
|
||||
Some PumpFun coins use **Creator Rewards Sharing**, so the on-chain `creator_vault` can differ from the default derivation. If you reuse cached params from a **buy** when **selling**, you may see program error **2006 (seeds constraint violated)**. To avoid this:
|
||||
|
||||
- **From gRPC/events (no RPC needed)**: You can get both `creator` and `creator_vault` from parsed transaction events:
|
||||
- **sol-parser-sdk**: Before pushing events, the pipeline calls `fill_trade_accounts`, which fills `creator_vault` from the buy/sell instruction accounts (buy index 9, sell index 8). `creator` comes from the TradeEvent log. Use `PumpFunParams::from_trade(..., e.creator, e.creator_vault, ...)` or `from_dev_trade(..., e.creator, e.creator_vault, ...)` with the event `e`.
|
||||
- **solana-streamer**: Instruction parsers set `creator_vault` from accounts[9] (buy) or accounts[8] (sell); `creator` comes from the merged CPI TradeEvent log. Use the same `from_trade` / `from_dev_trade` with `e.creator` and `e.creator_vault`.
|
||||
- **Override after RPC**: If you get params via `PumpFunParams::from_mint_by_rpc` but later receive a newer `creator_vault` from gRPC, call `.with_creator_vault(latest_creator_vault)` on the params before selling.
|
||||
|
||||
The SDK does not fetch creator_vault from RPC on every sell (to avoid latency); pass the up-to-date vault from gRPC/events when available.
|
||||
|
||||
#### PumpSwap: coin_creator_vault from events (no RPC)
|
||||
|
||||
For **PumpSwap** (Pump AMM), `coin_creator_vault_ata` and `coin_creator_vault_authority` are required in buy/sell instructions. Both are available from parsed events without RPC:
|
||||
|
||||
- **sol-parser-sdk**: Instruction parser sets them from accounts 17 and 18; the account filler also fills them when the event comes from logs. Use `PumpSwapParams::from_trade(..., e.coin_creator_vault_ata, e.coin_creator_vault_authority, ...)` with the buy/sell event `e`.
|
||||
- **solana-streamer**: Instruction parser sets them from `accounts.get(17)` and `accounts.get(18)`. Use the same `from_trade` with the event’s `coin_creator_vault_ata` and `coin_creator_vault_authority`.
|
||||
|
||||
## 🛡️ MEV Protection Services
|
||||
|
||||
You can apply for a key through the official website: [Community Website](https://fnzero.dev/swqos)
|
||||
@@ -297,10 +347,10 @@ You can apply for a key through the official website: [Community Website](https:
|
||||
- **ZeroSlot**: Zero-latency transactions
|
||||
- **Temporal**: Time-sensitive transactions
|
||||
- **Bloxroute**: Blockchain network acceleration
|
||||
- **FlashBlock**: High-speed transaction execution with API key authentication - [Official Documentation](https://doc.flashblock.trade/)
|
||||
- **BlockRazor**: High-speed transaction execution with API key authentication - [Official Documentation](https://blockrazor.gitbook.io/blockrazor/)
|
||||
- **Node1**: High-speed transaction execution with API key authentication - [Official Documentation](https://node1.me/docs.html)
|
||||
- **Astralane**: Blockchain network acceleration
|
||||
- **FlashBlock**: High-speed transaction execution with API key authentication
|
||||
- **BlockRazor**: High-speed transaction execution with API key authentication
|
||||
- **Node1**: High-speed transaction execution with API key authentication
|
||||
- **Astralane**: Blockchain network acceleration (supports HTTP and QUIC; see [Astralane QUIC](#astralane-quic-low-latency) above)
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
@@ -333,6 +383,10 @@ MIT License
|
||||
- Telegram Group: https://t.me/fnzero_group
|
||||
- Discord: https://discord.gg/vuazbGkqQE
|
||||
|
||||
## ⏱️ Timing metrics (v3.5.0+)
|
||||
|
||||
When `log_enabled` and SDK log are on, the executor prints `[SDK] Buy/Sell timing(...)`. **Semantics changed in v3.5.0**: `submit` is now only the send to SWQOS/RPC; `confirm` is separate; `start_to_submit` (when `grpc_recv_us` is set) is **end-to-end from gRPC event to submit**, so it is larger than in-process timings. See [docs/TIMING_METRICS.md](docs/TIMING_METRICS.md) for definitions and how to compare with older versions.
|
||||
|
||||
## ⚠️ Important Notes
|
||||
|
||||
1. Test thoroughly before using on mainnet
|
||||
|
||||
+56
-6
@@ -48,6 +48,7 @@
|
||||
- [⚡ 交易参数](#-交易参数)
|
||||
- [📊 使用示例汇总表格](#-使用示例汇总表格)
|
||||
- [⚙️ SWQoS 服务配置说明](#️-swqos-服务配置说明)
|
||||
- [Astralane QUIC(低延迟)](#astralane-quic低延迟)
|
||||
- [🔧 中间件系统说明](#-中间件系统说明)
|
||||
- [🔍 地址查找表](#-地址查找表)
|
||||
- [🔍 Nonce 缓存](#-nonce-缓存)
|
||||
@@ -89,14 +90,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.5.6" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.2" }
|
||||
```
|
||||
|
||||
### 使用 crates.io
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = "3.5.6"
|
||||
sol-trade-sdk = "3.6.2"
|
||||
```
|
||||
|
||||
## 🛠️ 使用示例
|
||||
@@ -119,6 +120,14 @@ let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Jito("your uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Bloxroute("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
// Astralane:第4个参数 None 为 HTTP,Some(SwqosTransport::Quic) 为 QUIC;同一 API key
|
||||
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // HTTP
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt,
|
||||
None,
|
||||
Some(SwqosTransport::Quic),
|
||||
), // QUIC
|
||||
];
|
||||
// 创建 TradeConfig 实例
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
@@ -256,6 +265,29 @@ let bloxroute_config = SwqosConfig::Bloxroute(
|
||||
|
||||
当使用多个MEV服务时,需要使用`Durable Nonce`。你需要使用`fetch_nonce_info`函数获取最新的`nonce`值,并在交易的时候将`durable_nonce`填入交易参数。
|
||||
|
||||
#### Astralane QUIC(低延迟)
|
||||
|
||||
Astralane 支持 **HTTP** 与 **QUIC** 两种传输方式。QUIC 可减少连接开销,降低提交延迟。使用 QUIC 时,将 `SwqosConfig::Astralane` 的第四个参数设为 `Some(SwqosTransport::Quic)`。Astralane 的 QUIC 服务使用**单一端点**(无分区域端点),选 QUIC 时 SDK 会忽略 `region` 与可选自定义 URL;为与其他 SWQoS 配置一致,可传入相同 region。
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{SwqosConfig, SwqosRegion, SwqosTransport};
|
||||
|
||||
// Astralane 使用 QUIC(低延迟);region 会被忽略(QUIC 单一端点)
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt, // 与其他服务一致即可;QUIC 时会被忽略
|
||||
None,
|
||||
Some(SwqosTransport::Quic),
|
||||
),
|
||||
];
|
||||
// 然后照常使用 swqos_configs 创建 TradeConfig / TradingClient
|
||||
```
|
||||
|
||||
- **HTTP**(默认):第四个参数为 `None` 或 `Some(SwqosTransport::Http)`;region 与可选自定义 URL 生效。
|
||||
- **QUIC**:第四个参数为 `Some(SwqosTransport::Quic)`;SDK 使用单一 QUIC 端点并忽略 region。与 HTTP 使用同一 API key。
|
||||
|
||||
---
|
||||
|
||||
### 🔧 中间件系统说明
|
||||
@@ -288,6 +320,24 @@ PumpFun 与 PumpSwap 支持**返现(Cashback)**:部分手续费可返还
|
||||
- **pumpfun_copy_trading**、**pumpfun_sniper_trading** 示例使用 sol-parser-sdk 订阅 gRPC 事件,并在构造参数时传入 `e.is_cashback_coin`。
|
||||
- **领取返现**:使用 `client.claim_cashback_pumpfun()` 和 `client.claim_cashback_pumpswap(...)` 领取累计的返现。
|
||||
|
||||
#### 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 保护服务
|
||||
|
||||
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
|
||||
@@ -296,10 +346,10 @@ PumpFun 与 PumpSwap 支持**返现(Cashback)**:部分手续费可返还
|
||||
- **ZeroSlot**: 零延迟交易
|
||||
- **Temporal**: 时间敏感交易
|
||||
- **Bloxroute**: 区块链网络加速
|
||||
- **FlashBlock**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://doc.flashblock.trade/)
|
||||
- **BlockRazor**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://blockrazor.gitbook.io/blockrazor/)
|
||||
- **Node1**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://node1.me/docs.html)
|
||||
- **Astralane**: 高速交易执行,支持 API 密钥认证
|
||||
- **FlashBlock**: 高速交易执行,支持 API 密钥认证
|
||||
- **BlockRazor**: 高速交易执行,支持 API 密钥认证
|
||||
- **Node1**: 高速交易执行,支持 API 密钥认证
|
||||
- **Astralane**: 区块链网络加速(支持 HTTP 与 QUIC,见上方 [Astralane QUIC](#astralane-quic低延迟))
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
## sol-trade-sdk v3.6.2
|
||||
|
||||
### Changes
|
||||
|
||||
- **Node1 QUIC support** — Node1 SWQOS can use QUIC transport: `SwqosConfig::Node1(api_token, region, custom_url, Some(SwqosTransport::Quic))`. Uses UUID auth on first bi stream, one bi stream per transaction, bincode-serialized `VersionedTransaction`. Region endpoints: `SWQOS_ENDPOINTS_NODE1_QUIC` (ny, fra, ams, lon, tk). New dependency: `uuid`.
|
||||
- **Speedlanding QUIC reliability** — Proactive connection check before send (`ensure_connected()`); 5s connect and send timeouts; reconnect uses `lock().await` so concurrent senders wait for the new connection instead of failing on `try_lock()`; TLS SNI is derived from the endpoint host (e.g. `nyc.speedlanding.trade`) with fallback to `speed-landing` for IP or unknown host. Addresses user reports of transactions failing to send.
|
||||
|
||||
### Crates.io
|
||||
|
||||
```toml
|
||||
sol-trade-sdk = "3.6.2"
|
||||
```
|
||||
|
||||
### Repository
|
||||
|
||||
- **Tag:** [v3.6.2](https://github.com/0xfnzero/sol-trade-sdk/releases/tag/v3.6.2)
|
||||
@@ -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 或链上程序有未公开变更,建议再与官方实现或链上行为做一次对照验证。*
|
||||
@@ -531,7 +531,7 @@ async fn handle_buy(
|
||||
|
||||
let client = initialize_real_client().await?;
|
||||
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
|
||||
match dex {
|
||||
@@ -565,7 +565,7 @@ async fn handle_buy_rv4(
|
||||
slippage: Option<u64>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
handle_buy_raydium_v4(mint, amm, sol_amount, slippage, create_mint_ata, use_seed, owner_pubkey)
|
||||
.await?;
|
||||
@@ -579,7 +579,7 @@ async fn handle_buy_rcpmm(
|
||||
slippage: Option<u64>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
handle_buy_raydium_cpmm(
|
||||
mint,
|
||||
@@ -599,8 +599,8 @@ async fn handle_buy_pumpfun(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🔥 BUY PUMPFUN COMMAND");
|
||||
println!(" Token Mint: {}", mint);
|
||||
@@ -655,7 +655,7 @@ async fn handle_buy_pumpswap(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
@@ -710,8 +710,8 @@ async fn handle_buy_bonk(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY BONK COMMAND");
|
||||
@@ -766,8 +766,8 @@ async fn handle_buy_raydium_v4(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY RAYDIUM V4 COMMAND");
|
||||
@@ -825,8 +825,8 @@ async fn handle_buy_raydium_cpmm(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY RAYDIUM CPMM COMMAND");
|
||||
@@ -992,11 +992,11 @@ async fn handle_sell_pumpfun(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
|
||||
@@ -1053,11 +1053,11 @@ async fn handle_sell_pumpswap(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||
@@ -1111,11 +1111,11 @@ async fn handle_sell_bonk(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||
@@ -1170,11 +1170,11 @@ async fn handle_sell_raydium_v4(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL RAYDIUM V4 COMMAND");
|
||||
@@ -1231,11 +1231,11 @@ async fn handle_sell_raydium_cpmm(
|
||||
pool_address: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL RAYDIUM CPMM COMMAND");
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
use sol_trade_sdk::{
|
||||
common::{AnyResult, InfrastructureConfig, TradeConfig},
|
||||
swqos::{SwqosConfig, SwqosRegion},
|
||||
TradingClient, TradingInfrastructure,
|
||||
SwqosTransport, TradingClient, TradingInfrastructure,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::signature::Keypair;
|
||||
@@ -46,9 +46,9 @@ async fn create_trading_client_simple() -> AnyResult<TradingClient> {
|
||||
SwqosConfig::ZeroSlot("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::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::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None, Some(SwqosTransport::Quic)), // QUIC; use None for HTTP
|
||||
// Helius Sender: 4th param swqos_only Some(true) => min tip 0.000005 SOL; None => 0.0002 SOL
|
||||
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
|
||||
];
|
||||
|
||||
@@ -768,21 +768,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "bonding_curve_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [98, 111, 110, 100, 105, 110, 103, 45, 99, 117, 114, 118, 101, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -1179,21 +1164,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "bonding_curve_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [98, 111, 110, 100, 105, 110, 103, 45, 99, 117, 114, 118, 101, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -3987,21 +3957,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "bonding_curve_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [98, 111, 110, 100, 105, 110, 103, 45, 99, 117, 114, 118, 101, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
|
||||
@@ -688,21 +688,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -1134,21 +1119,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -3192,21 +3162,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
# sol-trade-sdk v3.4.1
|
||||
|
||||
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
|
||||
|
||||
## What's Changed
|
||||
|
||||
### New Features
|
||||
|
||||
- **PumpFun & PumpSwap Cashback** (#77): Support for cashback in PumpFun and PumpSwap trading flows. See [Cashback documentation](docs/PUMP_CASHBACK_README.md).
|
||||
- **Events**: `is_cashback_coin` is now passed from events; PumpFun examples use `sol-parser-sdk` only for event parsing.
|
||||
|
||||
### Performance
|
||||
|
||||
- **SWQoS**: Reduced submit latency; fixed high latency after ~5 minutes idle.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **WSOL ATA**: WSOL Associated Token Account creation now runs in background with retry and timeout for more reliable setup.
|
||||
- Silenced unused and deprecated compiler warnings.
|
||||
|
||||
### Documentation
|
||||
|
||||
- README (EN/中文): Added Cashback section, outline, examples and tables.
|
||||
- Updated crates.io / docs references in README.
|
||||
|
||||
---
|
||||
|
||||
## Cargo
|
||||
|
||||
**From Git (this release):**
|
||||
```toml
|
||||
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.4.1" }
|
||||
```
|
||||
|
||||
**From crates.io** (when published):
|
||||
```toml
|
||||
sol-trade-sdk = "3.4.1"
|
||||
```
|
||||
|
||||
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.0...v3.4.1
|
||||
@@ -1,37 +0,0 @@
|
||||
# sol-trade-sdk v3.5.0
|
||||
|
||||
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Performance
|
||||
|
||||
- **Executor hot path**: Sample `Instant::now()` only when `log_enabled` or `simulate` (total, build, submit, confirm) to reduce cold-path syscalls.
|
||||
- **SWQOS**: `execute_parallel` now takes `&[Arc<SwqosClient>]` to avoid cloning the client list on each swap.
|
||||
- **Constants**: Named constants for instruction/account sizes and HTTP client timeouts; no magic numbers in hot paths.
|
||||
|
||||
### Code Quality
|
||||
|
||||
- **Protocol params**: Single `validate_protocol_params()` used for both buy and sell; removed duplicate match blocks in `lib.rs`.
|
||||
- **Comments**: Bilingual (English + 中文) doc and inline comments across execution, executor, perf (hardware_optimizations, syscall_bypass), and swqos/common.
|
||||
- **Prefetch/safety**: Clearer docs for cache prefetch and `unsafe` usage (valid read-only ref, no concurrent write).
|
||||
|
||||
### Documentation
|
||||
|
||||
- README (EN/CN): Version references updated to 3.5.0 for path and crates.io usage.
|
||||
|
||||
---
|
||||
|
||||
## Cargo
|
||||
|
||||
**From Git (this release):**
|
||||
```toml
|
||||
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.5.0" }
|
||||
```
|
||||
|
||||
**From crates.io:**
|
||||
```toml
|
||||
sol-trade-sdk = "3.5.0"
|
||||
```
|
||||
|
||||
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.1...v3.5.0
|
||||
@@ -25,6 +25,15 @@ pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 165 字节 Token 账户的典型租金(lamports),RPC 超时时用作回退
|
||||
const DEFAULT_TOKEN_ACCOUNT_RENT: u64 = 2_039_280;
|
||||
|
||||
/// 当 RPC 超时或不可用时设置默认租金,避免客户端创建卡死
|
||||
pub fn set_default_rents() {
|
||||
SPL_TOKEN_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
|
||||
SPL_TOKEN_2022_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn start_rent_updater(client: Arc<SolanaRpcClient>) {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
|
||||
@@ -230,6 +230,19 @@ pub const SWQOS_ENDPOINTS_NODE1: [&str; 8] = [
|
||||
"http://fra.node1.me",
|
||||
];
|
||||
|
||||
/// Node1 QUIC: port 16666. Region order: NewYork, Frankfurt, Amsterdam, SLC→ny, Tokyo, London, LosAngeles→ny, Default→ny.
|
||||
/// 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; 8] = [
|
||||
"ny.node1.me:16666",
|
||||
"fra.node1.me:16666",
|
||||
"ams.node1.me:16666",
|
||||
"ny.node1.me:16666", // SLC → ny
|
||||
"tk.node1.me:16666",
|
||||
"lon.node1.me:16666",
|
||||
"ny.node1.me:16666", // LA → ny
|
||||
"ny.node1.me:16666", // Default → ny
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
||||
"http://ny.flashblock.trade",
|
||||
"http://fra.flashblock.trade",
|
||||
@@ -242,6 +255,7 @@ pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
||||
];
|
||||
|
||||
/// BlockRazor Send Transaction v2: plain-text Base64 body, auth in URI, Content-Type: text/plain. Keep-alive: POST /v2/health.
|
||||
/// 若 HTTP 返回 500,可尝试 HTTPS:https://<region>.solana.blockrazor.io/v2/sendTransaction(Frankfurt/NewYork/Tokyo),通过 custom_url 覆盖。
|
||||
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 8] = [
|
||||
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
@@ -267,6 +281,19 @@ pub const SWQOS_ENDPOINTS_ASTRALANE: [&str; 8] = [
|
||||
"http://lim.gateway.astralane.io/irisb",
|
||||
];
|
||||
|
||||
/// Astralane QUIC endpoints (port 7000). Region order: NewYork, Frankfurt, Amsterdam, SLC, Tokyo, London, LosAngeles, Default.
|
||||
/// See: https://github.com/Astralane/astralane-quic-client. We use fr, ams, la, ny, lim, sg only (avoid ams2/fr2 for lower latency).
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 8] = [
|
||||
"ny.gateway.astralane.io:7000", // NewYork
|
||||
"fr.gateway.astralane.io:7000", // Frankfurt
|
||||
"ams.gateway.astralane.io:7000", // Amsterdam
|
||||
"lim.gateway.astralane.io:7000", // SLC (no slc, use lim)
|
||||
"sg.gateway.astralane.io:7000", // Tokyo (Asia)
|
||||
"ams.gateway.astralane.io:7000", // London (Europe, avoid ams2)
|
||||
"la.gateway.astralane.io:7000", // LosAngeles
|
||||
"lim.gateway.astralane.io:7000", // Default
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
|
||||
"http://ewr1.flashrpc.com",
|
||||
"http://fra1.flashrpc.com",
|
||||
|
||||
+7
-23
@@ -4,12 +4,9 @@ use crate::{
|
||||
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
|
||||
SELL_EXECT_IN_DISCRIMINATOR,
|
||||
},
|
||||
trading::{
|
||||
common::utils::get_token_balance,
|
||||
core::{
|
||||
params::{BonkParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
},
|
||||
trading::core::{
|
||||
params::{BonkParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
},
|
||||
utils::calc::bonk::{
|
||||
get_buy_token_amount_from_sol_amount, get_sell_sol_amount_from_token_amount,
|
||||
@@ -177,9 +174,10 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
// ========================================
|
||||
// Parameter validation and basic data preparation
|
||||
// ========================================
|
||||
if params.rpc.is_none() {
|
||||
return Err(anyhow!("RPC is not set"));
|
||||
}
|
||||
let amount = params
|
||||
.input_amount
|
||||
.filter(|&a| a > 0)
|
||||
.ok_or_else(|| anyhow!("Bonk sell requires input_amount (token amount to sell); fetch balance via RPC before calling build_sell"))?;
|
||||
|
||||
let protocol_params = params
|
||||
.protocol_params
|
||||
@@ -189,20 +187,6 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
|
||||
let usd1_pool = protocol_params.global_config == accounts::USD1_GLOBAL_CONFIG;
|
||||
|
||||
let rpc = params.rpc.as_ref().unwrap().clone();
|
||||
|
||||
let mut amount = params.input_amount;
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
let balance_u64 =
|
||||
get_token_balance(rpc.as_ref(), ¶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() {
|
||||
if usd1_pool {
|
||||
get_pool_pda(¶ms.input_mint, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
||||
|
||||
@@ -27,7 +27,7 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<MeteoraDammV2Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
||||
|
||||
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
@@ -135,7 +135,7 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<MeteoraDammV2Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
||||
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
return Err(anyhow!("Token amount is not set"));
|
||||
|
||||
+28
-22
@@ -9,8 +9,8 @@ use crate::{
|
||||
use crate::{
|
||||
instruction::utils::pumpfun::{
|
||||
accounts, get_bonding_curve_pda, get_bonding_curve_v2_pda, get_creator,
|
||||
get_user_volume_accumulator_pda, global_constants::{self}, BUY_DISCRIMINATOR,
|
||||
BUY_EXACT_SOL_IN_DISCRIMINATOR,
|
||||
get_mayhem_fee_recipient_meta_random, get_user_volume_accumulator_pda,
|
||||
global_constants::{self}, BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||
},
|
||||
utils::calc::{
|
||||
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
|
||||
@@ -64,7 +64,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
);
|
||||
|
||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
||||
get_bonding_curve_pda(¶ms.output_mint).unwrap()
|
||||
get_bonding_curve_pda(¶ms.output_mint)
|
||||
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.output_mint))?
|
||||
} else {
|
||||
bonding_curve.account
|
||||
};
|
||||
@@ -97,8 +98,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
let user_volume_accumulator =
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap();
|
||||
let user_volume_accumulator = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||
|
||||
// ========================================
|
||||
// Build instructions
|
||||
@@ -118,10 +119,11 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
);
|
||||
}
|
||||
|
||||
let mut buy_data = [0u8; 24];
|
||||
// IDL: buy/buy_exact_sol_in 第三参数 track_volume: OptionBool,仅代币支持返现时传 Some(true)
|
||||
let track_volume = if bonding_curve.is_cashback_coin { [1u8, 1u8] } else { [1u8, 0u8] }; // Some(true) / Some(false)
|
||||
let mut buy_data = [0u8; 26];
|
||||
if params.use_exact_sol_amount.unwrap_or(true) {
|
||||
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64)
|
||||
// Spend exactly the input SOL amount, get at least min_tokens_out
|
||||
// buy_exact_sol_in(spendable_sol_in: u64, min_tokens_out: u64, track_volume)
|
||||
let min_tokens_out = calculate_with_slippage_sell(
|
||||
buy_token_amount,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
@@ -129,22 +131,24 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
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[16..24].copy_from_slice(&min_tokens_out.to_le_bytes());
|
||||
buy_data[24..26].copy_from_slice(&track_volume);
|
||||
} else {
|
||||
// buy(token_amount: u64, max_sol_cost: u64)
|
||||
// Buy exactly token_amount tokens, pay up to max_sol_cost
|
||||
// buy(token_amount: u64, max_sol_cost: u64, track_volume)
|
||||
buy_data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
buy_data[8..16].copy_from_slice(&buy_token_amount.to_le_bytes());
|
||||
buy_data[16..24].copy_from_slice(&max_sol_cost.to_le_bytes());
|
||||
buy_data[24..26].copy_from_slice(&track_volume);
|
||||
}
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 2nd account = Mayhem fee recipient; use any one randomly)
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
global_constants::MAYHEM_FEE_RECIPIENT_META
|
||||
get_mayhem_fee_recipient_meta_random()
|
||||
} else {
|
||||
global_constants::FEE_RECIPIENT_META
|
||||
};
|
||||
|
||||
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.output_mint).unwrap();
|
||||
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,
|
||||
fee_recipient_meta,
|
||||
@@ -163,7 +167,7 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
accounts::FEE_CONFIG_META,
|
||||
accounts::FEE_PROGRAM_META,
|
||||
];
|
||||
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // bonding_curve_v2 (readonly) at end
|
||||
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // remainingAccounts: @pump-fun/pump-sdk 要求末尾传 bondingCurveV2Pda(mint),勿删
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::PUMPFUN,
|
||||
@@ -216,7 +220,8 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
};
|
||||
|
||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
||||
get_bonding_curve_pda(¶ms.input_mint).unwrap()
|
||||
get_bonding_curve_pda(¶ms.input_mint)
|
||||
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.input_mint))?
|
||||
} else {
|
||||
bonding_curve.account
|
||||
};
|
||||
@@ -255,13 +260,13 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
let mut instructions = Vec::with_capacity(2);
|
||||
|
||||
let mut sell_data = [0u8; 24];
|
||||
sell_data[..8].copy_from_slice(&[51, 230, 133, 164, 1, 127, 131, 173]); // Method ID
|
||||
sell_data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
sell_data[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
sell_data[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 2nd account = Mayhem fee recipient; use any one randomly)
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
global_constants::MAYHEM_FEE_RECIPIENT_META
|
||||
get_mayhem_fee_recipient_meta_random()
|
||||
} else {
|
||||
global_constants::FEE_RECIPIENT_META
|
||||
};
|
||||
@@ -285,12 +290,13 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
||||
|
||||
// Cashback: Bonding Curve Sell expects UserVolumeAccumulator PDA at 0th remaining account (writable)
|
||||
if bonding_curve.is_cashback_coin {
|
||||
let user_volume_accumulator =
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap();
|
||||
let user_volume_accumulator = 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));
|
||||
}
|
||||
// Program upgrade: bonding_curve_v2 (readonly) at end of account list
|
||||
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.input_mint).unwrap();
|
||||
// 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));
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
|
||||
+70
-73
@@ -1,9 +1,10 @@
|
||||
use crate::{
|
||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||
instruction::utils::pumpswap::{
|
||||
accounts, fee_recipient_ata, get_pool_v2_pda, get_user_volume_accumulator_pda,
|
||||
get_user_volume_accumulator_wsol_ata, BUY_DISCRIMINATOR,
|
||||
BUY_EXACT_QUOTE_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||
accounts, fee_recipient_ata, get_mayhem_fee_recipient_random, get_pool_v2_pda,
|
||||
get_user_volume_accumulator_pda, get_user_volume_accumulator_quote_ata,
|
||||
get_user_volume_accumulator_wsol_ata, BUY_DISCRIMINATOR, BUY_EXACT_QUOTE_IN_DISCRIMINATOR,
|
||||
SELL_DISCRIMINATOR,
|
||||
},
|
||||
trading::{
|
||||
common::wsol_manager,
|
||||
@@ -119,16 +120,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
|
||||
let is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||
let fee_recipient =
|
||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
||||
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||
get_mayhem_fee_recipient_random()
|
||||
} else {
|
||||
accounts::FEE_RECIPIENT_META
|
||||
(accounts::FEE_RECIPIENT, accounts::FEE_RECIPIENT_META)
|
||||
};
|
||||
let fee_recipient_ata = if is_mayhem_mode {
|
||||
fee_recipient_ata(fee_recipient, crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
} else {
|
||||
fee_recipient_ata(fee_recipient, quote_mint)
|
||||
};
|
||||
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
|
||||
|
||||
// ========================================
|
||||
// Build instructions
|
||||
@@ -177,10 +180,9 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
]);
|
||||
if quote_is_wsol_or_usdc {
|
||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||
accounts.push(AccountMeta::new(
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
||||
false,
|
||||
));
|
||||
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||
accounts.push(AccountMeta::new(uva, false));
|
||||
}
|
||||
accounts.push(accounts::FEE_CONFIG_META);
|
||||
accounts.push(accounts::FEE_PROGRAM_META);
|
||||
@@ -190,51 +192,44 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
accounts.push(AccountMeta::new(wsol_ata, false));
|
||||
}
|
||||
}
|
||||
// Program upgrade: pool_v2 (readonly) at end of account list
|
||||
accounts.push(AccountMeta::new_readonly(
|
||||
get_pool_v2_pda(&base_mint).unwrap(),
|
||||
false,
|
||||
));
|
||||
// remainingAccounts: @pump-fun/pump-swap-sdk 要求末尾传 poolV2Pda(baseMint),勿删
|
||||
let pool_v2 = get_pool_v2_pda(&base_mint)
|
||||
.ok_or_else(|| anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint))?;
|
||||
accounts.push(AccountMeta::new_readonly(pool_v2, false));
|
||||
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
if quote_is_wsol_or_usdc {
|
||||
// Create instruction data(buy/buy_exact_quote_in 第三参数 track_volume: OptionBool,仅代币支持返现时传 Some(true);sell 仅两参数)
|
||||
let track_volume = if protocol_params.is_cashback_coin { [1u8, 1u8] } else { [1u8, 0u8] }; // Some(true) / Some(false)
|
||||
let data: Vec<u8> = if quote_is_wsol_or_usdc {
|
||||
let mut buf = [0u8; 26];
|
||||
if params.use_exact_sol_amount.unwrap_or(true) {
|
||||
// buy_exact_quote_in(spendable_quote_in: u64, min_base_amount_out: u64)
|
||||
// Spend exactly the input SOL/quote amount, get at least min_base_amount_out
|
||||
let min_base_amount_out = crate::utils::calc::common::calculate_with_slippage_sell(
|
||||
token_amount,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
);
|
||||
data[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
||||
// spendable_quote_in (exact SOL amount to spend)
|
||||
data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||
// min_base_amount_out (minimum tokens to receive)
|
||||
data[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
||||
buf[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
||||
buf[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||
buf[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
||||
buf[24..26].copy_from_slice(&track_volume);
|
||||
} else {
|
||||
// buy(base_amount_out: u64, max_quote_amount_in: u64)
|
||||
// Buy exactly base_amount_out tokens, pay up to max_quote_amount_in
|
||||
data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
// base_amount_out
|
||||
data[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
// max_quote_amount_in
|
||||
data[16..24].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
buf[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
buf[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
buf[16..24].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
buf[24..26].copy_from_slice(&track_volume);
|
||||
}
|
||||
buf.to_vec()
|
||||
} else {
|
||||
data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
// base_amount_in
|
||||
data[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
// min_quote_amount_out
|
||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||
}
|
||||
|
||||
let buy_instruction = Instruction {
|
||||
program_id: accounts::AMM_PROGRAM,
|
||||
accounts: accounts.clone(),
|
||||
data: data.to_vec(),
|
||||
let mut buf = [0u8; 24];
|
||||
buf[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
buf[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
buf[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||
buf.to_vec()
|
||||
};
|
||||
|
||||
instructions.push(buy_instruction);
|
||||
instructions.push(Instruction {
|
||||
program_id: accounts::AMM_PROGRAM,
|
||||
accounts,
|
||||
data,
|
||||
});
|
||||
if close_wsol_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
@@ -320,16 +315,18 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
sol_amount = params.fixed_output_amount.unwrap();
|
||||
}
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
|
||||
let is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||
let fee_recipient =
|
||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
||||
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||
get_mayhem_fee_recipient_random()
|
||||
} else {
|
||||
accounts::FEE_RECIPIENT_META
|
||||
(accounts::FEE_RECIPIENT, accounts::FEE_RECIPIENT_META)
|
||||
};
|
||||
let fee_recipient_ata = if is_mayhem_mode {
|
||||
fee_recipient_ata(fee_recipient, crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
} else {
|
||||
fee_recipient_ata(fee_recipient, quote_mint)
|
||||
};
|
||||
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
|
||||
|
||||
let user_base_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
@@ -380,28 +377,30 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
]);
|
||||
if !quote_is_wsol_or_usdc {
|
||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||
accounts.push(AccountMeta::new(
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
||||
false,
|
||||
));
|
||||
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||
accounts.push(AccountMeta::new(uva, false));
|
||||
}
|
||||
accounts.push(accounts::FEE_CONFIG_META);
|
||||
accounts.push(accounts::FEE_PROGRAM_META);
|
||||
// Cashback: remaining_accounts[0] = WSOL ATA of UserVolumeAccumulator, remaining_accounts[1] = UserVolumeAccumulator PDA
|
||||
// Cashback sell: 官方 remainingAccounts = [accumulator 的 quote_mint ATA, accumulator PDA, poolV2](用 quote_mint 非固定 WSOL)
|
||||
if protocol_params.is_cashback_coin {
|
||||
if let (Some(wsol_ata), Some(accumulator)) = (
|
||||
get_user_volume_accumulator_wsol_ata(¶ms.payer.pubkey()),
|
||||
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(wsol_ata, false));
|
||||
accounts.push(AccountMeta::new(quote_ata, false));
|
||||
accounts.push(AccountMeta::new(accumulator, false));
|
||||
}
|
||||
}
|
||||
// Program upgrade: pool_v2 (readonly) at end of account list
|
||||
accounts.push(AccountMeta::new_readonly(
|
||||
get_pool_v2_pda(&base_mint).unwrap(),
|
||||
false,
|
||||
));
|
||||
// remainingAccounts: @pump-fun/pump-swap-sdk sell 要求末尾传 poolV2Pda(baseMint),勿删
|
||||
let pool_v2 = get_pool_v2_pda(&base_mint)
|
||||
.ok_or_else(|| anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint))?;
|
||||
accounts.push(AccountMeta::new_readonly(pool_v2, false));
|
||||
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
@@ -419,13 +418,11 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||
}
|
||||
|
||||
let sell_instruction = Instruction {
|
||||
instructions.push(Instruction {
|
||||
program_id: accounts::AMM_PROGRAM,
|
||||
accounts: accounts.clone(),
|
||||
accounts,
|
||||
data: data.to_vec(),
|
||||
};
|
||||
|
||||
instructions.push(sell_instruction);
|
||||
});
|
||||
|
||||
if close_wsol_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
|
||||
@@ -29,7 +29,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<RaydiumAmmV4Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
|
||||
|
||||
let is_wsol = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
@@ -144,7 +144,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<RaydiumAmmV4Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
|
||||
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
return Err(anyhow!("Token amount is not set"));
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
use crate::common::{bonding_curve::BondingCurveAccount, SolanaRpcClient};
|
||||
use anyhow::anyhow;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use rand::seq::IndexedRandom;
|
||||
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||
@@ -59,8 +60,18 @@ pub mod global_constants {
|
||||
is_writable: true,
|
||||
};
|
||||
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
||||
/// Mayhem fee recipients (pump-public-docs: use any one randomly)
|
||||
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
|
||||
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
|
||||
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
|
||||
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
|
||||
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
|
||||
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
|
||||
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
|
||||
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
|
||||
];
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
|
||||
pub const MAYHEM_FEE_RECIPIENT_META: solana_sdk::instruction::AccountMeta =
|
||||
solana_sdk::instruction::AccountMeta {
|
||||
pubkey: MAYHEM_FEE_RECIPIENT,
|
||||
@@ -161,6 +172,19 @@ pub const BUY_DISCRIMINATOR: [u8; 8] = [102, 6, 61, 18, 1, 218, 235, 234];
|
||||
pub const BUY_EXACT_SOL_IN_DISCRIMINATOR: [u8; 8] = [56, 252, 116, 8, 158, 223, 205, 95];
|
||||
pub const SELL_DISCRIMINATOR: [u8; 8] = [51, 230, 133, 164, 1, 127, 131, 173];
|
||||
|
||||
/// Returns a random Mayhem fee recipient AccountMeta (pump-public-docs: Bonding Curve 2nd account = Mayhem fee recipient; use any one randomly).
|
||||
#[inline]
|
||||
pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
|
||||
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
|
||||
.choose(&mut rand::rng())
|
||||
.unwrap_or(&global_constants::MAYHEM_FEE_RECIPIENTS[0]);
|
||||
AccountMeta {
|
||||
pubkey: recipient,
|
||||
is_signer: false,
|
||||
is_writable: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Symbol;
|
||||
|
||||
impl Symbol {
|
||||
@@ -202,10 +226,9 @@ pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
|
||||
// Fast check against cached default creator vault
|
||||
static DEFAULT_CREATOR_VAULT: std::sync::LazyLock<Option<Pubkey>> =
|
||||
std::sync::LazyLock::new(|| get_creator_vault_pda(&Pubkey::default()));
|
||||
if creator_vault_pda.eq(&DEFAULT_CREATOR_VAULT.unwrap()) {
|
||||
Pubkey::default()
|
||||
} else {
|
||||
*creator_vault_pda
|
||||
match DEFAULT_CREATOR_VAULT.as_ref() {
|
||||
Some(default) if creator_vault_pda.eq(default) => Pubkey::default(),
|
||||
_ => *creator_vault_pda,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -275,3 +298,32 @@ pub fn get_buy_price(
|
||||
|
||||
s_u64.min(real_token_reserves)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
#[test]
|
||||
fn pumpfun_discriminators_are_8_bytes() {
|
||||
assert_eq!(BUY_DISCRIMINATOR.len(), 8);
|
||||
assert_eq!(BUY_EXACT_SOL_IN_DISCRIMINATOR.len(), 8);
|
||||
assert_eq!(SELL_DISCRIMINATOR.len(), 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpfun_bonding_curve_and_v2_pda_differ_for_same_mint() {
|
||||
let mint = Pubkey::new_unique();
|
||||
let pda = get_bonding_curve_pda(&mint).unwrap();
|
||||
let pda_v2 = get_bonding_curve_v2_pda(&mint).unwrap();
|
||||
assert_ne!(pda, pda_v2, "bonding_curve and bonding_curve_v2 PDAs must differ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpfun_creator_vault_pda_deterministic() {
|
||||
let creator = Pubkey::new_unique();
|
||||
let a = get_creator_vault_pda(&creator).unwrap();
|
||||
let b = get_creator_vault_pda(&creator).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,17 @@ use crate::{
|
||||
common::{
|
||||
spl_associated_token_account::get_associated_token_address_with_program_id, SolanaRpcClient,
|
||||
},
|
||||
constants::TOKEN_PROGRAM,
|
||||
constants::{TOKEN_PROGRAM, WSOL_TOKEN_ACCOUNT},
|
||||
instruction::utils::pumpswap_types::{pool_decode, Pool},
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use rand::seq::IndexedRandom;
|
||||
use solana_account_decoder::UiAccountEncoding;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
|
||||
|
||||
/// PumpSwap 池账户总长度(见 pump-public-docs Breaking Change):8 字节 discriminator + 244 字节 Pool。
|
||||
/// 官方文档:pool structure needs to be 244 bytes (was 243),含 is_mayhem_mode。DataSize 必须与此一致,否则 getProgramAccounts 会返回 0。
|
||||
const POOL_ACCOUNT_DATA_LEN: u64 = 8 + 244;
|
||||
|
||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||
pub mod seeds {
|
||||
@@ -29,6 +34,10 @@ pub mod seeds {
|
||||
|
||||
/// 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
|
||||
@@ -53,6 +62,8 @@ pub mod accounts {
|
||||
pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
|
||||
|
||||
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 PROTOCOL_FEE_BASIS_POINTS: u64 = 5;
|
||||
@@ -68,9 +79,19 @@ pub mod accounts {
|
||||
pub const DEFAULT_COIN_CREATOR_VAULT_AUTHORITY: Pubkey =
|
||||
pubkey!("8N3GDaZ2iwN65oxVatKTLPNooAVUJTbfiVJ1ahyqwjSk");
|
||||
|
||||
/// Mayhem fee recipient (for mayhem mode coins)
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
||||
/// Mayhem fee recipients (pump-public-docs: use any one randomly for throughput)
|
||||
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
|
||||
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
|
||||
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
|
||||
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
|
||||
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
|
||||
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
|
||||
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
|
||||
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
|
||||
];
|
||||
/// Default Mayhem fee recipient (first of MAYHEM_FEE_RECIPIENTS)
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
|
||||
|
||||
// META
|
||||
|
||||
@@ -142,6 +163,20 @@ pub const BUY_DISCRIMINATOR: [u8; 8] = [102, 6, 61, 18, 1, 218, 235, 234];
|
||||
pub const BUY_EXACT_QUOTE_IN_DISCRIMINATOR: [u8; 8] = [198, 46, 21, 82, 180, 217, 232, 112];
|
||||
pub const SELL_DISCRIMINATOR: [u8; 8] = [51, 230, 133, 164, 1, 127, 131, 173];
|
||||
|
||||
/// Returns a random Mayhem fee recipient and its AccountMeta (pump-public-docs: use any one randomly).
|
||||
#[inline]
|
||||
pub fn get_mayhem_fee_recipient_random() -> (Pubkey, AccountMeta) {
|
||||
let recipient = *accounts::MAYHEM_FEE_RECIPIENTS
|
||||
.choose(&mut rand::rng())
|
||||
.unwrap_or(&accounts::MAYHEM_FEE_RECIPIENTS[0]);
|
||||
let meta = AccountMeta {
|
||||
pubkey: recipient,
|
||||
is_signer: false,
|
||||
is_writable: false,
|
||||
};
|
||||
(recipient, meta)
|
||||
}
|
||||
|
||||
/// Pool v2 PDA (seeds: ["pool-v2", base_mint]). Required at end of buy/sell/buy_exact_quote_in accounts.
|
||||
#[inline]
|
||||
pub fn get_pool_v2_pda(base_mint: &Pubkey) -> Option<Pubkey> {
|
||||
@@ -152,6 +187,35 @@ pub fn get_pool_v2_pda(base_mint: &Pubkey) -> Option<Pubkey> {
|
||||
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
|
||||
pub async fn find_pool(rpc: &SolanaRpcClient, mint: &Pubkey) -> Result<Pubkey, anyhow::Error> {
|
||||
let (pool_address, _) = find_by_mint(rpc, mint).await?;
|
||||
@@ -191,14 +255,14 @@ pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
|
||||
crate::common::fast_fn::PdaCacheKey::PumpSwapUserVolume(*user),
|
||||
|| {
|
||||
let seeds: &[&[u8]; 2] = &[&seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
|
||||
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
|
||||
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (used for cashback remaining accounts).
|
||||
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (buy cashback: remaining_accounts[0] 官方用 NATIVE_MINT).
|
||||
pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
|
||||
let accumulator = get_user_volume_accumulator_pda(user)?;
|
||||
Some(crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
@@ -208,9 +272,23 @@ pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
|
||||
))
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
let seeds: &[&[u8]; 1] = &[&seeds::GLOBAL_VOLUME_ACCUMULATOR_SEED];
|
||||
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
|
||||
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
}
|
||||
@@ -231,11 +309,12 @@ pub async fn find_by_base_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
base_mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
// Use getProgramAccounts to find pools for the given mint
|
||||
// Use getProgramAccounts to find pools for the given mint.
|
||||
// base_mint 在账户布局中的偏移:8(discriminator) + 1(bump) + 2(index) + 32(creator) = 43
|
||||
let filters = vec![
|
||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
||||
solana_rpc_client_api::filter::RpcFilterType::DataSize(POOL_ACCOUNT_DATA_LEN),
|
||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, &base_mint.to_bytes()),
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, base_mint.as_ref()),
|
||||
),
|
||||
];
|
||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
||||
@@ -274,19 +353,20 @@ pub async fn find_by_base_mint(
|
||||
}
|
||||
|
||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||
let (address, pool) = pools[0].clone();
|
||||
Ok((address, pool))
|
||||
let first = &pools[0];
|
||||
Ok((first.0, first.1.clone()))
|
||||
}
|
||||
|
||||
pub async fn find_by_quote_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
quote_mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
// Use getProgramAccounts to find pools for the given mint
|
||||
// Use getProgramAccounts to find pools for the given mint.
|
||||
// quote_mint 在账户布局中的偏移:8 + 1 + 2 + 32 + 32 = 75
|
||||
let filters = vec![
|
||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
||||
solana_rpc_client_api::filter::RpcFilterType::DataSize(POOL_ACCOUNT_DATA_LEN),
|
||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, "e_mint.to_bytes()),
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, quote_mint.as_ref()),
|
||||
),
|
||||
];
|
||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
||||
@@ -325,21 +405,56 @@ pub async fn find_by_quote_mint(
|
||||
}
|
||||
|
||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||
let (address, pool) = pools[0].clone();
|
||||
Ok((address, pool))
|
||||
let first = &pools[0];
|
||||
Ok((first.0, first.1.clone()))
|
||||
}
|
||||
|
||||
/// 按 mint 查找 PumpSwap 池(本函数仅用于 PumpSwap,其他 DEX 勿用)。
|
||||
///
|
||||
/// 查找顺序(与 @pump-fun/pump-swap-sdk 一致):
|
||||
/// 1. Pool v2 PDA ["pool-v2", base_mint] — 一次 getAccount
|
||||
/// 2. Canonical pool PDA ["pool", 0, pumpPoolAuthority(mint), mint, WSOL] — 迁移后的标准池
|
||||
/// 3. getProgramAccounts 按 base_mint / quote_mint 过滤
|
||||
pub async fn find_by_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
if let Ok((address, pool)) = find_by_base_mint(rpc, mint).await {
|
||||
return Ok((address, pool));
|
||||
let mut diag = Vec::<String>::new();
|
||||
|
||||
// 1. PumpSwap v2 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. 回退:getProgramAccounts 按 base_mint / quote_mint
|
||||
match find_by_base_mint(rpc, mint).await {
|
||||
Ok((address, pool)) => return Ok((address, pool)),
|
||||
Err(e) => diag.push(format!("getProgramAccounts(base_mint): {}", e)),
|
||||
}
|
||||
match find_by_quote_mint(rpc, mint).await {
|
||||
Ok((address, pool)) => return Ok((address, pool)),
|
||||
Err(e) => diag.push(format!("getProgramAccounts(quote_mint): {}", e)),
|
||||
}
|
||||
|
||||
Err(anyhow!(
|
||||
"No pool found for mint {}. 诊断: {}。若使用自建 RPC 请确认已开启 getProgramAccounts 或换用公共 RPC 重试;若代币未在 PumpSwap 建池请先在 pump.fun/DEX 上确认",
|
||||
mint,
|
||||
diag.join("; ")
|
||||
))
|
||||
}
|
||||
|
||||
pub async fn get_token_balances(
|
||||
@@ -362,3 +477,31 @@ pub fn get_fee_config_pda() -> Option<Pubkey> {
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
#[test]
|
||||
fn pumpswap_user_volume_accumulator_pda_deterministic() {
|
||||
let user = Pubkey::new_unique();
|
||||
let a = get_user_volume_accumulator_pda(&user).unwrap();
|
||||
let b = get_user_volume_accumulator_pda(&user).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_global_volume_accumulator_matches_constant() {
|
||||
let pda = get_global_volume_accumulator_pda().unwrap();
|
||||
assert_eq!(pda, accounts::GLOBAL_VOLUME_ACCUMULATOR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_pool_v2_pda_deterministic() {
|
||||
let base_mint = Pubkey::new_unique();
|
||||
let a = get_pool_v2_pda(&base_mint).unwrap();
|
||||
let b = get_pool_v2_pda(&base_mint).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,9 +17,12 @@ pub struct Pool {
|
||||
pub is_mayhem_mode: bool,
|
||||
/// Whether this pool's coin has cashback enabled
|
||||
pub is_cashback_coin: bool,
|
||||
/// Reserved for future fields (pump-public-docs: pool structure = 244 bytes total)
|
||||
pub _reserved: [u8; 7],
|
||||
}
|
||||
|
||||
pub const POOL_SIZE: usize = 1 + 2 + 32 * 6 + 8 + 32 + 1 + 1;
|
||||
/// Borsh 解码用的 Pool 长度。链上池为 244 字节(pump-public-docs Breaking Change),与 POOL_SIZE 一致。
|
||||
pub const POOL_SIZE: usize = 244;
|
||||
|
||||
pub fn pool_decode(data: &[u8]) -> Option<Pool> {
|
||||
if data.len() < POOL_SIZE {
|
||||
|
||||
+202
-135
@@ -19,6 +19,8 @@ use crate::swqos::common::TradeError;
|
||||
use crate::swqos::SwqosClient;
|
||||
use crate::swqos::SwqosConfig;
|
||||
use crate::swqos::TradeType;
|
||||
// Re-export for SWQOS HTTP/QUIC choice in SwqosConfig (e.g. Astralane)
|
||||
pub use crate::swqos::SwqosTransport;
|
||||
use crate::trading::core::params::BonkParams;
|
||||
use crate::trading::core::params::MeteoraDammV2Params;
|
||||
use crate::trading::core::params::PumpFunParams;
|
||||
@@ -54,6 +56,25 @@ fn validate_protocol_params(dex_type: DexType, params: &DexParamEnum) -> bool {
|
||||
}
|
||||
}
|
||||
|
||||
/// 按 mint 查找池地址(通用入口,根据 DEX 类型分发,仅 PumpSwap 等已实现的类型会走优化路径)。
|
||||
///
|
||||
/// * `dex_type`:PumpSwap 时先走 PDA 再回退 getProgramAccounts,其他类型返回未实现错误。
|
||||
pub async fn find_pool_by_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
mint: &Pubkey,
|
||||
dex_type: DexType,
|
||||
) -> Result<Pubkey, anyhow::Error> {
|
||||
match dex_type {
|
||||
DexType::PumpSwap => {
|
||||
crate::instruction::utils::pumpswap::find_pool(rpc, mint).await
|
||||
}
|
||||
_ => Err(anyhow::anyhow!(
|
||||
"find_pool_by_mint not implemented for {:?}",
|
||||
dex_type
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Type of the token to buy
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub enum TradeTokenType {
|
||||
@@ -97,27 +118,47 @@ impl TradingInfrastructure {
|
||||
config.commitment.clone(),
|
||||
));
|
||||
|
||||
// Initialize rent cache and start background updater
|
||||
common::seed::update_rents(&rpc).await.unwrap();
|
||||
// Initialize rent cache (with timeout so slow RPC doesn't block forever)
|
||||
const RENT_UPDATE_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(15);
|
||||
match tokio::time::timeout(RENT_UPDATE_TIMEOUT, common::seed::update_rents(&rpc)).await {
|
||||
Ok(Ok(())) => {}
|
||||
Ok(Err(e)) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "rent update failed: {}, using defaults", e);
|
||||
}
|
||||
common::seed::set_default_rents();
|
||||
}
|
||||
Err(_) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "rent update timed out ({}s), using defaults; check RPC", RENT_UPDATE_TIMEOUT.as_secs());
|
||||
}
|
||||
common::seed::set_default_rents();
|
||||
}
|
||||
}
|
||||
common::seed::start_rent_updater(rpc.clone());
|
||||
|
||||
// Create SWQOS clients with blacklist checking
|
||||
// Create SWQOS clients with blacklist checking(单节点超时 5s,避免某一家卡死整段初始化)
|
||||
const SWQOS_CLIENT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
let mut swqos_clients: Vec<Arc<SwqosClient>> = vec![];
|
||||
for swqos in &config.swqos_configs {
|
||||
// Check blacklist, skip disabled providers
|
||||
if swqos.is_blacklisted() {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ SWQOS {:?} is blacklisted, skipping", swqos.swqos_type());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match SwqosConfig::get_swqos_client(
|
||||
config.rpc_url.clone(),
|
||||
config.commitment.clone(),
|
||||
swqos.clone(),
|
||||
).await {
|
||||
Ok(swqos_client) => swqos_clients.push(swqos_client),
|
||||
Err(err) => {
|
||||
match tokio::time::timeout(
|
||||
SWQOS_CLIENT_TIMEOUT,
|
||||
SwqosConfig::get_swqos_client(
|
||||
config.rpc_url.clone(),
|
||||
config.commitment.clone(),
|
||||
swqos.clone(),
|
||||
),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(swqos_client)) => swqos_clients.push(swqos_client),
|
||||
Ok(Err(err)) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(
|
||||
target: "sol_trade_sdk",
|
||||
@@ -126,6 +167,16 @@ impl TradingInfrastructure {
|
||||
);
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(
|
||||
target: "sol_trade_sdk",
|
||||
"swqos {:?} init timed out ({}s), skipping",
|
||||
swqos.swqos_type(),
|
||||
SWQOS_CLIENT_TIMEOUT.as_secs()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -348,8 +399,44 @@ impl TradingClient {
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to ensure WSOL ATA exists for a wallet
|
||||
/// 单次尝试创建 WSOL ATA:获取 blockhash、组交易、发送并确认。成功或账户已存在返回 Ok(()),否则返回 Err(错误信息)。
|
||||
async fn try_create_wsol_ata_once(
|
||||
rpc: &SolanaRpcClient,
|
||||
payer: &Arc<Keypair>,
|
||||
wsol_ata: &solana_sdk::pubkey::Pubkey,
|
||||
create_ata_ixs: &[solana_sdk::instruction::Instruction],
|
||||
timeout_secs: u64,
|
||||
) -> Result<(), String> {
|
||||
use solana_sdk::transaction::Transaction;
|
||||
let recent_blockhash = rpc.get_latest_blockhash().await
|
||||
.map_err(|e| format!("Failed to get blockhash: {}", e))?;
|
||||
let tx = Transaction::new_signed_with_payer(
|
||||
create_ata_ixs,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
let send_result = tokio::time::timeout(
|
||||
tokio::time::Duration::from_secs(timeout_secs),
|
||||
rpc.send_and_confirm_transaction(&tx),
|
||||
).await;
|
||||
match send_result {
|
||||
Ok(Ok(_signature)) => Ok(()),
|
||||
Ok(Err(e)) => {
|
||||
if rpc.get_account(wsol_ata).await.is_ok() {
|
||||
return Ok(());
|
||||
}
|
||||
Err(format!("{}", e))
|
||||
}
|
||||
Err(_) => Err(format!("Transaction confirmation timeout ({}s)", timeout_secs)),
|
||||
}
|
||||
}
|
||||
|
||||
/// 确保钱包存在 WSOL ATA;不存在则发交易创建(会花费租金 + 手续费,初始化阶段唯一会扣钱的逻辑)
|
||||
async fn ensure_wsol_ata(payer: &Arc<Keypair>, rpc: &Arc<SolanaRpcClient>) {
|
||||
const MAX_RETRIES: usize = 3;
|
||||
const TIMEOUT_SECS: u64 = 10;
|
||||
|
||||
let wsol_ata =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
&payer.pubkey(),
|
||||
@@ -357,119 +444,62 @@ impl TradingClient {
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
);
|
||||
|
||||
match rpc.get_account(&wsol_ata).await {
|
||||
Ok(_) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists: {}", wsol_ata);
|
||||
}
|
||||
return;
|
||||
if rpc.get_account(&wsol_ata).await.is_ok() {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists: {}", wsol_ata);
|
||||
}
|
||||
Err(_) => {
|
||||
return;
|
||||
}
|
||||
|
||||
let create_ata_ixs =
|
||||
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
||||
if create_ata_ixs.is_empty() {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA already exists (no need to create)");
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
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", "🔨 Creating WSOL ATA: {}", wsol_ata);
|
||||
info!(target: "sol_trade_sdk", "🔄 Retrying WSOL ATA creation (attempt {}/{})...", attempt, MAX_RETRIES);
|
||||
}
|
||||
let create_ata_ixs =
|
||||
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
||||
|
||||
if !create_ata_ixs.is_empty() {
|
||||
use solana_sdk::transaction::Transaction;
|
||||
|
||||
// 重试逻辑:最多尝试3次,每次超时10秒
|
||||
const MAX_RETRIES: usize = 3;
|
||||
const TIMEOUT_SECS: u64 = 10;
|
||||
let mut last_error = None;
|
||||
|
||||
for attempt in 1..=MAX_RETRIES {
|
||||
if attempt > 1 {
|
||||
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;
|
||||
}
|
||||
|
||||
let recent_blockhash = match rpc.get_latest_blockhash().await {
|
||||
Ok(hash) => hash,
|
||||
Err(e) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Failed to get latest blockhash: {}", e);
|
||||
}
|
||||
last_error = Some(format!("Failed to get blockhash: {}", e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let tx = Transaction::new_signed_with_payer(
|
||||
&create_ata_ixs,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
// 使用超时包装 send_and_confirm_transaction
|
||||
let send_result = tokio::time::timeout(
|
||||
tokio::time::Duration::from_secs(TIMEOUT_SECS),
|
||||
rpc.send_and_confirm_transaction(&tx)
|
||||
).await;
|
||||
|
||||
match send_result {
|
||||
Ok(Ok(signature)) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA created successfully: {}", signature);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
last_error = Some(format!("{}", e));
|
||||
|
||||
// 检查账户是否实际已存在
|
||||
if let Ok(_) = rpc.get_account(&wsol_ata).await {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists (tx failed but account exists): {}", wsol_ata);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if attempt < MAX_RETRIES && sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Attempt {} failed: {}", attempt, e);
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
last_error = Some(format!("Transaction confirmation timeout ({}s)", TIMEOUT_SECS));
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Attempt {} timed out", attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有重试都失败了
|
||||
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:");
|
||||
error!(target: "sol_trade_sdk", " 1. Insufficient SOL balance (need ~0.002 SOL for rent exemption)");
|
||||
error!(target: "sol_trade_sdk", " 2. RPC timeout or network congestion");
|
||||
error!(target: "sol_trade_sdk", " 3. Insufficient transaction fee");
|
||||
error!(target: "sol_trade_sdk", " 🔧 Solutions:");
|
||||
error!(target: "sol_trade_sdk", " 1. Fund wallet with at least 0.1 SOL");
|
||||
error!(target: "sol_trade_sdk", " 2. Retry after a few seconds");
|
||||
error!(target: "sol_trade_sdk", " 3. Check RPC connection");
|
||||
error!(target: "sol_trade_sdk", " ⚠️ Process will exit in 5 seconds, restart after fixing the above");
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
panic!(
|
||||
"❌ WSOL ATA creation failed and account does not exist: {}. Error: {}",
|
||||
wsol_ata, err
|
||||
);
|
||||
}
|
||||
} else {
|
||||
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 already exists (no need to create)");
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
@@ -496,9 +526,32 @@ impl TradingClient {
|
||||
// Initialize wallet-specific caches
|
||||
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 {
|
||||
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
|
||||
const MIN_SOL_FOR_WSOL_ATA_LAMPORTS: u64 = 500_000; // 约 0.0005 SOL,用于 ATA 租金 + 手续费
|
||||
const BALANCE_CHECK_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
|
||||
let balance = tokio::time::timeout(
|
||||
BALANCE_CHECK_TIMEOUT,
|
||||
infrastructure.rpc.get_balance(&payer.pubkey()),
|
||||
)
|
||||
.await
|
||||
.unwrap_or(Ok(0))
|
||||
.unwrap_or(0);
|
||||
if balance >= MIN_SOL_FOR_WSOL_ATA_LAMPORTS {
|
||||
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
|
||||
} else if sdk_log::sdk_log_enabled() {
|
||||
info!(
|
||||
target: "sol_trade_sdk",
|
||||
"⏭️ 跳过创建 WSOL ATA:钱包 SOL 不足(当前 {} lamports,需要至少 {})",
|
||||
balance,
|
||||
MIN_SOL_FOR_WSOL_ATA_LAMPORTS
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let instance = Self {
|
||||
@@ -590,6 +643,11 @@ impl TradingClient {
|
||||
&self,
|
||||
params: TradeBuyParams,
|
||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
||||
if params.recent_blockhash.is_none() && params.durable_nonce.is_none() {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Must provide either recent_blockhash or durable_nonce for buy (required for transaction validity)"
|
||||
));
|
||||
}
|
||||
#[cfg(feature = "perf-trace")]
|
||||
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
|
||||
debug!(
|
||||
@@ -600,7 +658,14 @@ impl TradingClient {
|
||||
}
|
||||
if params.input_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||
return Err(anyhow::anyhow!(
|
||||
" Current version only support USD1 trading on Bonk protocols"
|
||||
" Current version only supports USD1 trading on Bonk protocols"
|
||||
));
|
||||
}
|
||||
let protocol_params = params.extension_params;
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid protocol params for Trade (dex={:?})",
|
||||
params.dex_type
|
||||
));
|
||||
}
|
||||
let input_token_mint = if params.input_token_type == TradeTokenType::SOL {
|
||||
@@ -612,8 +677,7 @@ impl TradingClient {
|
||||
} else {
|
||||
USD1_TOKEN_ACCOUNT
|
||||
};
|
||||
let executor = TradeFactory::create_executor(params.dex_type.clone());
|
||||
let protocol_params = params.extension_params;
|
||||
let executor = TradeFactory::create_executor(params.dex_type);
|
||||
let buy_params = SwapParams {
|
||||
rpc: Some(self.infrastructure.rpc.clone()),
|
||||
payer: self.payer.clone(),
|
||||
@@ -627,7 +691,7 @@ impl TradingClient {
|
||||
address_lookup_table_account: params.address_lookup_table_account,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: protocol_params.clone(),
|
||||
protocol_params,
|
||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||
middleware_manager: self.middleware_manager.clone(),
|
||||
@@ -647,10 +711,6 @@ impl TradingClient {
|
||||
use_exact_sol_amount: params.use_exact_sol_amount,
|
||||
};
|
||||
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
|
||||
}
|
||||
|
||||
let swap_result = executor.swap(buy_params).await;
|
||||
let result =
|
||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
||||
@@ -695,13 +755,24 @@ impl TradingClient {
|
||||
DEFAULT_SLIPPAGE
|
||||
);
|
||||
}
|
||||
if params.output_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||
if params.recent_blockhash.is_none() && params.durable_nonce.is_none() {
|
||||
return Err(anyhow::anyhow!(
|
||||
" Current version only support USD1 trading on Bonk protocols"
|
||||
"Must provide either recent_blockhash or durable_nonce for sell (required for transaction validity)"
|
||||
));
|
||||
}
|
||||
if params.output_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||
return Err(anyhow::anyhow!(
|
||||
" Current version only supports USD1 trading on Bonk protocols"
|
||||
));
|
||||
}
|
||||
let executor = TradeFactory::create_executor(params.dex_type.clone());
|
||||
let protocol_params = params.extension_params;
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!(
|
||||
"Invalid protocol params for Trade (dex={:?})",
|
||||
params.dex_type
|
||||
));
|
||||
}
|
||||
let executor = TradeFactory::create_executor(params.dex_type);
|
||||
let output_token_mint = if params.output_token_type == TradeTokenType::SOL {
|
||||
SOL_TOKEN_ACCOUNT
|
||||
} else if params.output_token_type == TradeTokenType::WSOL {
|
||||
@@ -724,7 +795,7 @@ impl TradingClient {
|
||||
address_lookup_table_account: params.address_lookup_table_account,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: protocol_params.clone(),
|
||||
protocol_params,
|
||||
with_tip: params.with_tip,
|
||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||
@@ -744,10 +815,6 @@ impl TradingClient {
|
||||
use_exact_sol_amount: None,
|
||||
};
|
||||
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
|
||||
}
|
||||
|
||||
let swap_result = executor.swap(sell_params).await;
|
||||
let result =
|
||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
||||
|
||||
+111
-87
@@ -2,6 +2,7 @@ use crate::swqos::common::{default_http_client_builder, poll_transaction_confirm
|
||||
use rand::seq::IndexedRandom;
|
||||
use reqwest::Client;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
use tracing::{error, info, warn};
|
||||
|
||||
use std::time::Duration;
|
||||
use anyhow::Result;
|
||||
@@ -19,24 +20,37 @@ use std::sync::atomic::{AtomicBool, Ordering};
|
||||
/// Empty body for getHealth POST; avoid per-request allocation.
|
||||
static PING_BODY: &[u8] = &[];
|
||||
|
||||
use crate::swqos::astralane_quic::AstralaneQuicClient;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum AstralaneBackend {
|
||||
Http {
|
||||
endpoint: String,
|
||||
auth_token: String,
|
||||
http_client: Client,
|
||||
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
stop_ping: Arc<AtomicBool>,
|
||||
},
|
||||
Quic(Arc<AstralaneQuicClient>),
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct AstralaneClient {
|
||||
pub endpoint: String,
|
||||
pub auth_token: String,
|
||||
pub rpc_client: Arc<SolanaRpcClient>,
|
||||
pub http_client: Client,
|
||||
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
pub stop_ping: Arc<AtomicBool>,
|
||||
backend: AstralaneBackend,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl SwqosClientTrait for AstralaneClient {
|
||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
||||
}
|
||||
|
||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||
for transaction in transactions {
|
||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_tip_account(&self) -> Result<String> {
|
||||
@@ -50,59 +64,71 @@ impl SwqosClientTrait for AstralaneClient {
|
||||
}
|
||||
|
||||
impl AstralaneClient {
|
||||
/// 使用 HTTP(irisb)提交。
|
||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let http_client = default_http_client_builder().build().unwrap();
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
|
||||
let stop_ping = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
backend: AstralaneBackend::Http {
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle,
|
||||
stop_ping,
|
||||
},
|
||||
};
|
||||
|
||||
// Start ping task
|
||||
let client_clone = client.clone();
|
||||
tokio::spawn(async move {
|
||||
client_clone.start_ping_task().await;
|
||||
});
|
||||
|
||||
client
|
||||
}
|
||||
|
||||
/// Start periodic ping task to keep connections active
|
||||
/// 使用 QUIC 提交。
|
||||
pub async fn new_quic(rpc_url: String, quic_endpoint: &str, api_key: String) -> Result<Self> {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let quic_client = AstralaneQuicClient::connect(quic_endpoint, &api_key).await?;
|
||||
Ok(Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
backend: AstralaneBackend::Quic(Arc::new(quic_client)),
|
||||
})
|
||||
}
|
||||
|
||||
async fn start_ping_task(&self) {
|
||||
let endpoint = self.endpoint.clone();
|
||||
let auth_token = self.auth_token.clone();
|
||||
let http_client = self.http_client.clone();
|
||||
let stop_ping = self.stop_ping.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await; // first tick completes immediately → one ping at start
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
||||
eprintln!("Astralane ping request failed: {}", e);
|
||||
match &self.backend {
|
||||
AstralaneBackend::Http { endpoint, auth_token, http_client, ping_handle, stop_ping } => {
|
||||
let endpoint = endpoint.clone();
|
||||
let auth_token = auth_token.clone();
|
||||
let http_client = http_client.clone();
|
||||
let ping_handle = ping_handle.clone();
|
||||
let stop_ping = stop_ping.clone();
|
||||
let handle = tokio::spawn(async move {
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
||||
warn!(target: "sol_trade_sdk", "Astralane ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut guard = ping_handle.lock().await;
|
||||
if let Some(old) = guard.as_ref() {
|
||||
old.abort();
|
||||
}
|
||||
});
|
||||
|
||||
// Update ping_handle - use Mutex to safely update
|
||||
{
|
||||
let mut ping_guard = self.ping_handle.lock().await;
|
||||
if let Some(old_handle) = ping_guard.as_ref() {
|
||||
old_handle.abort();
|
||||
*guard = Some(handle);
|
||||
}
|
||||
*ping_guard = Some(handle);
|
||||
AstralaneBackend::Quic(_) => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Send ping request: POST endpoint?api-key=...&method=getHealth (endpoint is irisb from constants).
|
||||
/// Send ping request: POST endpoint?api-key=...&method=getHealth
|
||||
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
|
||||
let response = http_client
|
||||
.post(endpoint)
|
||||
@@ -112,57 +138,54 @@ impl AstralaneClient {
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let _ = response.bytes().await; // consume body so connection returns to pool
|
||||
let _ = response.bytes().await;
|
||||
if !status.is_success() {
|
||||
eprintln!("Astralane ping request returned non-success status: {}", status);
|
||||
warn!(target: "sol_trade_sdk", "Astralane ping request returned non-success status: {}", status);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send transaction via /irisb binary API (no Base64; lower latency).
|
||||
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 signature = transaction.get_signature();
|
||||
|
||||
let body_bytes = bincode_serialize(transaction).map_err(|e| anyhow::anyhow!("Astralane binary serialize failed: {}", e))?;
|
||||
|
||||
let response = self.http_client
|
||||
.post(&self.endpoint)
|
||||
.query(&[("api-key", self.auth_token.as_str()), ("method", "sendTransaction")])
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.body(body_bytes)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = response.status();
|
||||
let _ = response.bytes().await;
|
||||
if status.is_success() {
|
||||
println!(" [astralane] {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||
} else {
|
||||
eprintln!(" [astralane] {} submission failed: status {}", trade_type, status);
|
||||
return Err(anyhow::anyhow!("Astralane sendTransaction failed: {}", status));
|
||||
match &self.backend {
|
||||
AstralaneBackend::Http { endpoint, auth_token, http_client, .. } => {
|
||||
let response = http_client
|
||||
.post(endpoint)
|
||||
.query(&[("api-key", auth_token.as_str()), ("method", "sendTransaction")])
|
||||
.header("Content-Type", "application/octet-stream")
|
||||
.body(body_bytes)
|
||||
.send()
|
||||
.await?;
|
||||
let status = response.status();
|
||||
let _ = response.bytes().await;
|
||||
if status.is_success() {
|
||||
info!(target: "sol_trade_sdk", "[astralane] {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||
} else {
|
||||
error!(target: "sol_trade_sdk", "[astralane] {} submission failed: status {}", trade_type, status);
|
||||
return Err(anyhow::anyhow!("Astralane sendTransaction failed: {}", status));
|
||||
}
|
||||
}
|
||||
AstralaneBackend::Quic(quic) => {
|
||||
quic.send_transaction(&body_bytes).await?;
|
||||
info!(target: "sol_trade_sdk", "[astralane-quic] {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||
}
|
||||
}
|
||||
|
||||
let start_time = Instant::now();
|
||||
match poll_transaction_confirmation(&self.rpc_client, *signature, wait_confirmation).await {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
println!(" signature: {:?}", signature);
|
||||
println!(" [astralane] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
||||
info!(target: "sol_trade_sdk", "signature: {:?}", signature);
|
||||
error!(target: "sol_trade_sdk", "[astralane] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
||||
return Err(e);
|
||||
},
|
||||
}
|
||||
}
|
||||
if wait_confirmation {
|
||||
println!(" signature: {:?}", signature);
|
||||
println!(" [astralane] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
||||
for transaction in transactions {
|
||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||
info!(target: "sol_trade_sdk", "signature: {:?}", signature);
|
||||
info!(target: "sol_trade_sdk", "[astralane] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -170,18 +193,19 @@ impl AstralaneClient {
|
||||
|
||||
impl Drop for AstralaneClient {
|
||||
fn drop(&mut self) {
|
||||
// Ensure ping task stops when client is destroyed
|
||||
self.stop_ping.store(true, Ordering::Relaxed);
|
||||
|
||||
// Try to stop ping task immediately
|
||||
// Use tokio::spawn to avoid blocking Drop
|
||||
let ping_handle = self.ping_handle.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(handle) = ping_guard.as_ref() {
|
||||
handle.abort();
|
||||
match &self.backend {
|
||||
AstralaneBackend::Http { stop_ping, ping_handle, .. } => {
|
||||
stop_ping.store(true, Ordering::Relaxed);
|
||||
let ping_handle = ping_handle.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut guard = ping_handle.lock().await;
|
||||
if let Some(handle) = guard.as_ref() {
|
||||
handle.abort();
|
||||
}
|
||||
*guard = None;
|
||||
});
|
||||
}
|
||||
*ping_guard = None;
|
||||
});
|
||||
AstralaneBackend::Quic(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,252 @@
|
||||
//! 内联自 [Astralane/astralane-quic-client](https://github.com/Astralane/astralane-quic-client),
|
||||
//! 用于向 Astralane QUIC TPU 提交交易,不依赖外部 crate,便于审计与安全可控。
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use quinn::crypto::rustls::QuicClientConfig;
|
||||
use quinn::{ClientConfig, Connection, Endpoint, IdleTimeout, TransportConfig};
|
||||
use rcgen::{CertificateParams, KeyPair};
|
||||
use rustls::pki_types::{CertificateDer, PrivateKeyDer, PrivatePkcs8KeyDer};
|
||||
use std::net::SocketAddr;
|
||||
use std::str::FromStr;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{info, warn};
|
||||
|
||||
/// ALPN protocol identifier for Astralane TPU.
|
||||
const ALPN_ASTRALANE_TPU: &[u8] = b"astralane-tpu";
|
||||
|
||||
/// Maximum Solana transaction size.
|
||||
pub const MAX_TRANSACTION_SIZE: usize = 1232;
|
||||
|
||||
/// QUIC application error codes returned by the server.
|
||||
pub mod error_code {
|
||||
pub const OK: u32 = 0;
|
||||
pub const UNKNOWN_API_KEY: u32 = 1;
|
||||
pub const CONNECTION_LIMIT: u32 = 2;
|
||||
|
||||
pub fn describe(code: u32) -> &'static str {
|
||||
match code {
|
||||
OK => "OK",
|
||||
UNKNOWN_API_KEY => "Unknown API key",
|
||||
CONNECTION_LIMIT => "Connection limit exceeded",
|
||||
_ => "Unknown error",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// QUIC client for sending transactions to Astralane's TPU endpoint.
|
||||
pub struct AstralaneQuicClient {
|
||||
endpoint: Endpoint,
|
||||
connection: Mutex<Connection>,
|
||||
server_addr: SocketAddr,
|
||||
#[allow(dead_code)]
|
||||
api_key: String,
|
||||
}
|
||||
|
||||
impl AstralaneQuicClient {
|
||||
/// Connect to an Astralane QUIC server.
|
||||
/// Generates a self-signed TLS certificate with the API key as the Common Name (CN).
|
||||
pub async fn connect(server_addr: &str, api_key: &str) -> Result<Self> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
let addr = SocketAddr::from_str(server_addr).or_else(|_| {
|
||||
use std::net::ToSocketAddrs;
|
||||
server_addr
|
||||
.to_socket_addrs()
|
||||
.ok()
|
||||
.and_then(|mut addrs| addrs.next())
|
||||
.ok_or_else(|| anyhow::anyhow!("Cannot resolve address: {}", server_addr))
|
||||
}).context("Invalid server address")?;
|
||||
|
||||
info!("[astralane-quic] Building TLS config (CN = api_key)");
|
||||
let client_config = Self::build_client_config(api_key)?;
|
||||
|
||||
let mut endpoint =
|
||||
Endpoint::client("0.0.0.0:0".parse()?).context("Failed to create QUIC endpoint")?;
|
||||
endpoint.set_default_client_config(client_config);
|
||||
|
||||
info!("[astralane-quic] Connecting to {} ...", addr);
|
||||
let connection = endpoint
|
||||
.connect(addr, "astralane")?
|
||||
.await
|
||||
.context("Failed to connect to Astralane QUIC server")?;
|
||||
|
||||
info!("[astralane-quic] Connected at {}", addr);
|
||||
|
||||
Ok(Self {
|
||||
endpoint,
|
||||
connection: Mutex::new(connection),
|
||||
server_addr: addr,
|
||||
api_key: api_key.to_string(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Send a single bincode-serialized `VersionedTransaction`.
|
||||
/// Fire-and-forget; automatically reconnects if the connection is dead.
|
||||
pub async fn send_transaction(&self, transaction_bytes: &[u8]) -> Result<()> {
|
||||
if transaction_bytes.len() > MAX_TRANSACTION_SIZE {
|
||||
anyhow::bail!(
|
||||
"Transaction too large: {} bytes (max {})",
|
||||
transaction_bytes.len(),
|
||||
MAX_TRANSACTION_SIZE
|
||||
);
|
||||
}
|
||||
|
||||
let conn = {
|
||||
let mut guard = self.connection.lock().await;
|
||||
if let Some(reason) = guard.close_reason() {
|
||||
if let quinn::ConnectionError::ApplicationClosed(ref info) = reason {
|
||||
let code = info.error_code.into_inner();
|
||||
if code != error_code::OK as u64 {
|
||||
anyhow::bail!(
|
||||
"Server closed connection: {} (code {})",
|
||||
error_code::describe(code as u32),
|
||||
code
|
||||
);
|
||||
}
|
||||
}
|
||||
warn!("[astralane-quic] Connection dead, reconnecting to {} ...", self.server_addr);
|
||||
*guard = self
|
||||
.endpoint
|
||||
.connect(self.server_addr, "astralane")?
|
||||
.await
|
||||
.context("Failed to reconnect to Astralane QUIC server")?;
|
||||
info!("[astralane-quic] Reconnected to {}", self.server_addr);
|
||||
}
|
||||
guard.clone()
|
||||
};
|
||||
|
||||
let mut send_stream = conn
|
||||
.open_uni()
|
||||
.await
|
||||
.context("Failed to open unidirectional stream")?;
|
||||
|
||||
send_stream
|
||||
.write_all(transaction_bytes)
|
||||
.await
|
||||
.context("Failed to write transaction data")?;
|
||||
|
||||
send_stream.finish().context("Failed to finish stream")?;
|
||||
info!("[astralane-quic] Transaction sent ({} bytes)", transaction_bytes.len());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Reconnect to the server if the connection was closed.
|
||||
pub async fn reconnect(&self) -> Result<()> {
|
||||
let mut guard = self.connection.lock().await;
|
||||
if guard.close_reason().is_some() {
|
||||
info!("[astralane-quic] Reconnecting at {}", self.server_addr);
|
||||
*guard = self
|
||||
.endpoint
|
||||
.connect(self.server_addr, "astralane")?
|
||||
.await
|
||||
.context("Failed to reconnect to Astralane QUIC server")?;
|
||||
info!("[astralane-quic] Reconnected to {}", self.server_addr);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if the connection is still alive.
|
||||
pub async fn is_connected(&self) -> bool {
|
||||
self.connection.lock().await.close_reason().is_none()
|
||||
}
|
||||
|
||||
/// Close the connection gracefully.
|
||||
pub async fn close(&self) {
|
||||
self.connection
|
||||
.lock()
|
||||
.await
|
||||
.close(error_code::OK.into(), b"client closing");
|
||||
}
|
||||
|
||||
fn build_client_config(api_key: &str) -> Result<ClientConfig> {
|
||||
let key_pair = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||
let mut cert_params = CertificateParams::new(vec![])?;
|
||||
cert_params.distinguished_name.push(
|
||||
rcgen::DnType::CommonName,
|
||||
rcgen::DnValue::Utf8String(api_key.to_string()),
|
||||
);
|
||||
let cert = cert_params.self_signed(&key_pair)?;
|
||||
|
||||
let cert_der = CertificateDer::from(cert.der().to_vec());
|
||||
let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(key_pair.serialize_der()));
|
||||
|
||||
let mut crypto = rustls::ClientConfig::builder()
|
||||
.dangerous()
|
||||
.with_custom_certificate_verifier(Arc::new(SkipServerVerification))
|
||||
.with_client_auth_cert(vec![cert_der], key_der)
|
||||
.context("Failed to set client certificate")?;
|
||||
|
||||
crypto.alpn_protocols = vec![ALPN_ASTRALANE_TPU.to_vec()];
|
||||
|
||||
let mut transport = TransportConfig::default();
|
||||
transport.max_idle_timeout(Some(
|
||||
IdleTimeout::try_from(Duration::from_secs(30)).unwrap(),
|
||||
));
|
||||
transport.keep_alive_interval(Some(Duration::from_secs(25)));
|
||||
|
||||
let mut client_config =
|
||||
ClientConfig::new(Arc::new(QuicClientConfig::try_from(crypto).unwrap()));
|
||||
client_config.transport_config(Arc::new(transport));
|
||||
|
||||
Ok(client_config)
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for AstralaneQuicClient {
|
||||
fn drop(&mut self) {
|
||||
self.connection
|
||||
.get_mut()
|
||||
.close(error_code::OK.into(), b"client closing");
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip server certificate verification (Astralane server may use self-signed cert).
|
||||
#[derive(Debug)]
|
||||
struct SkipServerVerification;
|
||||
|
||||
impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
|
||||
fn verify_server_cert(
|
||||
&self,
|
||||
_end_entity: &CertificateDer<'_>,
|
||||
_intermediates: &[CertificateDer<'_>],
|
||||
_server_name: &rustls::pki_types::ServerName<'_>,
|
||||
_ocsp_response: &[u8],
|
||||
_now: rustls::pki_types::UnixTime,
|
||||
) -> Result<rustls::client::danger::ServerCertVerified, rustls::Error> {
|
||||
Ok(rustls::client::danger::ServerCertVerified::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls12_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &CertificateDer<'_>,
|
||||
_dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn verify_tls13_signature(
|
||||
&self,
|
||||
_message: &[u8],
|
||||
_cert: &CertificateDer<'_>,
|
||||
_dss: &rustls::DigitallySignedStruct,
|
||||
) -> Result<rustls::client::danger::HandshakeSignatureValid, rustls::Error> {
|
||||
Ok(rustls::client::danger::HandshakeSignatureValid::assertion())
|
||||
}
|
||||
|
||||
fn supported_verify_schemes(&self) -> Vec<rustls::SignatureScheme> {
|
||||
vec![
|
||||
rustls::SignatureScheme::ECDSA_NISTP256_SHA256,
|
||||
rustls::SignatureScheme::ECDSA_NISTP384_SHA384,
|
||||
rustls::SignatureScheme::RSA_PSS_SHA256,
|
||||
rustls::SignatureScheme::RSA_PSS_SHA384,
|
||||
rustls::SignatureScheme::RSA_PSS_SHA512,
|
||||
rustls::SignatureScheme::RSA_PKCS1_SHA256,
|
||||
rustls::SignatureScheme::RSA_PKCS1_SHA384,
|
||||
rustls::SignatureScheme::RSA_PKCS1_SHA512,
|
||||
rustls::SignatureScheme::ED25519,
|
||||
]
|
||||
}
|
||||
}
|
||||
+14
-4
@@ -49,7 +49,11 @@ impl SwqosClientTrait for BlockRazorClient {
|
||||
impl BlockRazorClient {
|
||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let http_client = default_http_client_builder().build().unwrap();
|
||||
// 官方文档:請求中唯一允許的 header 是 Content-Type: text/plain;避免默认 User-Agent 等导致 500
|
||||
let http_client = default_http_client_builder()
|
||||
.user_agent("")
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
@@ -127,6 +131,7 @@ impl BlockRazorClient {
|
||||
}
|
||||
|
||||
/// Send transaction via v2 API: plain Base64 body, Content-Type: text/plain. Only required URI param: auth.
|
||||
/// 文档要求:auth 以 URI 参数传入;body 为纯 Base64 编码交易;唯一允许的 header 为 Content-Type: text/plain。
|
||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
||||
let start_time = Instant::now();
|
||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||
@@ -140,16 +145,21 @@ impl BlockRazorClient {
|
||||
.await?;
|
||||
|
||||
let status = response.status();
|
||||
let _ = response.bytes().await;
|
||||
if status.is_success() {
|
||||
let _ = response.bytes().await;
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
println!(" [blockrazor] {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||
}
|
||||
} else {
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!(" [blockrazor] {} submission failed: status {}", trade_type, status);
|
||||
eprintln!(" [blockrazor] {} submission failed: status {} body: {}", trade_type, status, body);
|
||||
}
|
||||
return Err(anyhow::anyhow!("BlockRazor sendTransaction failed: {}", status));
|
||||
return Err(anyhow::anyhow!(
|
||||
"BlockRazor sendTransaction failed: status {} body: {}",
|
||||
status,
|
||||
body
|
||||
));
|
||||
}
|
||||
|
||||
let start_time = Instant::now();
|
||||
|
||||
+59
-22
@@ -1,3 +1,4 @@
|
||||
pub mod astralane_quic;
|
||||
pub mod common;
|
||||
pub mod serialization;
|
||||
pub mod solana_rpc;
|
||||
@@ -7,6 +8,7 @@ pub mod zeroslot;
|
||||
pub mod temporal;
|
||||
pub mod bloxroute;
|
||||
pub mod node1;
|
||||
pub mod node1_quic;
|
||||
pub mod flashblock;
|
||||
pub mod blockrazor;
|
||||
pub mod astralane;
|
||||
@@ -33,9 +35,11 @@ use crate::{
|
||||
SWQOS_ENDPOINTS_TEMPORAL,
|
||||
SWQOS_ENDPOINTS_ZERO_SLOT,
|
||||
SWQOS_ENDPOINTS_NODE1,
|
||||
SWQOS_ENDPOINTS_NODE1_QUIC,
|
||||
SWQOS_ENDPOINTS_FLASHBLOCK,
|
||||
SWQOS_ENDPOINTS_BLOCKRAZOR,
|
||||
SWQOS_ENDPOINTS_ASTRALANE,
|
||||
SWQOS_ENDPOINTS_ASTRALANE_QUIC,
|
||||
SWQOS_ENDPOINTS_STELLIUM,
|
||||
SWQOS_ENDPOINTS_SOYAS,
|
||||
SWQOS_ENDPOINTS_SPEEDLANDING,
|
||||
@@ -64,6 +68,7 @@ use crate::{
|
||||
temporal::TemporalClient,
|
||||
zeroslot::ZeroSlotClient,
|
||||
node1::Node1Client,
|
||||
node1_quic::Node1QuicClient,
|
||||
flashblock::FlashBlockClient,
|
||||
blockrazor::BlockRazorClient,
|
||||
astralane::AstralaneClient,
|
||||
@@ -76,6 +81,8 @@ use crate::{
|
||||
};
|
||||
|
||||
lazy_static::lazy_static! {
|
||||
/// Reserved for future per-SWQOS tip account caching (currently unused).
|
||||
#[allow(dead_code)]
|
||||
static ref TIP_ACCOUNT_CACHE: RwLock<Vec<String>> = RwLock::new(Vec::new());
|
||||
}
|
||||
|
||||
@@ -86,6 +93,14 @@ pub const SWQOS_BLACKLIST: &[SwqosType] = &[
|
||||
SwqosType::NextBlock, // NextBlock is disabled by default
|
||||
];
|
||||
|
||||
/// SWQOS 提交通道:HTTP 或 QUIC(低延迟)。部分提供商(如 Astralane)支持 QUIC。
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
|
||||
pub enum SwqosTransport {
|
||||
#[default]
|
||||
Http,
|
||||
Quic,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub enum TradeType {
|
||||
Create,
|
||||
@@ -203,14 +218,14 @@ pub enum SwqosConfig {
|
||||
Temporal(String, SwqosRegion, Option<String>),
|
||||
/// ZeroSlot(api_token, region, custom_url)
|
||||
ZeroSlot(String, SwqosRegion, Option<String>),
|
||||
/// Node1(api_token, region, custom_url)
|
||||
Node1(String, SwqosRegion, Option<String>),
|
||||
/// Node1(api_token, region, custom_url, transport). transport=None => HTTP; Some(Quic) => QUIC (port 16666, UUID auth).
|
||||
Node1(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||
/// FlashBlock(api_token, region, custom_url)
|
||||
FlashBlock(String, SwqosRegion, Option<String>),
|
||||
/// BlockRazor(api_token, region, custom_url)
|
||||
BlockRazor(String, SwqosRegion, Option<String>),
|
||||
/// Astralane(api_token, region, custom_url)
|
||||
Astralane(String, SwqosRegion, Option<String>),
|
||||
/// Astralane(api_token, region, custom_url, transport). transport=None 表示 Http。
|
||||
Astralane(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||
/// Stellium(api_token, region, custom_url)
|
||||
Stellium(String, SwqosRegion, Option<String>),
|
||||
/// Lightspeed(api_key, region, custom_url) - Solana Vibe Station
|
||||
@@ -236,10 +251,10 @@ impl SwqosConfig {
|
||||
SwqosConfig::Bloxroute(_, _, _) => SwqosType::Bloxroute,
|
||||
SwqosConfig::Temporal(_, _, _) => SwqosType::Temporal,
|
||||
SwqosConfig::ZeroSlot(_, _, _) => SwqosType::ZeroSlot,
|
||||
SwqosConfig::Node1(_, _, _) => SwqosType::Node1,
|
||||
SwqosConfig::Node1(_, _, _, _) => SwqosType::Node1,
|
||||
SwqosConfig::FlashBlock(_, _, _) => SwqosType::FlashBlock,
|
||||
SwqosConfig::BlockRazor(_, _, _) => SwqosType::BlockRazor,
|
||||
SwqosConfig::Astralane(_, _, _) => SwqosType::Astralane,
|
||||
SwqosConfig::Astralane(_, _, _, _) => SwqosType::Astralane,
|
||||
SwqosConfig::Stellium(_, _, _) => SwqosType::Stellium,
|
||||
SwqosConfig::Lightspeed(_, _, _) => SwqosType::Lightspeed,
|
||||
SwqosConfig::Soyas(_, _, _) => SwqosType::Soyas,
|
||||
@@ -324,14 +339,27 @@ impl SwqosConfig {
|
||||
);
|
||||
Ok(Arc::new(bloxroute_client))
|
||||
},
|
||||
SwqosConfig::Node1(auth_token, region, url) => {
|
||||
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::Node1(auth_token, region, url, transport) => {
|
||||
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||
if use_quic {
|
||||
let quic_endpoint = url
|
||||
.unwrap_or_else(|| SWQOS_ENDPOINTS_NODE1_QUIC[region as usize].to_string());
|
||||
let node1_quic = Node1QuicClient::connect(
|
||||
&quic_endpoint,
|
||||
&auth_token,
|
||||
rpc_url.clone(),
|
||||
)
|
||||
.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) => {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::FlashBlock, region, url);
|
||||
@@ -351,14 +379,23 @@ impl SwqosConfig {
|
||||
);
|
||||
Ok(Arc::new(blockrazor_client))
|
||||
},
|
||||
SwqosConfig::Astralane(auth_token, region, url) => {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
|
||||
let astralane_client = AstralaneClient::new(
|
||||
rpc_url.clone(),
|
||||
endpoint.to_string(),
|
||||
auth_token
|
||||
);
|
||||
Ok(Arc::new(astralane_client))
|
||||
SwqosConfig::Astralane(auth_token, region, url, transport) => {
|
||||
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||
if use_quic {
|
||||
let quic_endpoint = url
|
||||
.unwrap_or_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))
|
||||
} else {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
|
||||
let astralane_client = AstralaneClient::new(
|
||||
rpc_url.clone(),
|
||||
endpoint.to_string(),
|
||||
auth_token,
|
||||
);
|
||||
Ok(Arc::new(astralane_client))
|
||||
}
|
||||
},
|
||||
SwqosConfig::Stellium(auth_token, region, url) => {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
//! 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::time::timeout;
|
||||
use tokio::sync::Mutex;
|
||||
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,
|
||||
]
|
||||
}
|
||||
}
|
||||
+144
-33
@@ -1,18 +1,24 @@
|
||||
//! Transaction serialization module.
|
||||
|
||||
use crate::perf::{
|
||||
compiler_optimization::CompileTimeOptimizedEventProcessor, simd::SIMDSerializer,
|
||||
};
|
||||
use anyhow::Result;
|
||||
use base64::Engine;
|
||||
use base64::engine::general_purpose::STANDARD;
|
||||
use base64::Engine;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use once_cell::sync::Lazy;
|
||||
use solana_client::rpc_client::SerializableTransaction;
|
||||
use solana_sdk::signature::Signature;
|
||||
use solana_transaction_status::UiTransactionEncoding;
|
||||
use std::sync::Arc;
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use crate::perf::{
|
||||
simd::SIMDSerializer,
|
||||
compiler_optimization::CompileTimeOptimizedEventProcessor,
|
||||
};
|
||||
|
||||
/// Max number of reusable buffers kept in the queue.
|
||||
const SERIALIZER_POOL_SIZE: usize = 10_000;
|
||||
/// Per-buffer reserved capacity (bytes).
|
||||
const SERIALIZER_BUFFER_SIZE: usize = 256 * 1024;
|
||||
/// Cold-start prewarm count. Keep small to avoid first-submit spikes.
|
||||
const SERIALIZER_PREWARM_BUFFERS: usize = 64;
|
||||
|
||||
/// Zero-allocation serializer using a buffer pool to avoid runtime allocation.
|
||||
pub struct ZeroAllocSerializer {
|
||||
@@ -22,28 +28,30 @@ pub struct ZeroAllocSerializer {
|
||||
|
||||
impl ZeroAllocSerializer {
|
||||
pub fn new(pool_size: usize, buffer_size: usize) -> Self {
|
||||
let pool = ArrayQueue::new(pool_size);
|
||||
|
||||
// Pre-allocate buffers
|
||||
for _ in 0..pool_size {
|
||||
let mut buffer = Vec::with_capacity(buffer_size);
|
||||
buffer.resize(buffer_size, 0);
|
||||
let _ = pool.push(buffer);
|
||||
}
|
||||
|
||||
Self {
|
||||
buffer_pool: Arc::new(pool),
|
||||
buffer_size,
|
||||
}
|
||||
Self::new_with_prewarm(pool_size, buffer_size, SERIALIZER_PREWARM_BUFFERS)
|
||||
}
|
||||
|
||||
pub fn serialize_zero_alloc<T: serde::Serialize>(&self, data: &T, _label: &str) -> Result<Vec<u8>> {
|
||||
fn new_with_prewarm(pool_size: usize, buffer_size: usize, prewarm_buffers: usize) -> Self {
|
||||
let pool = ArrayQueue::new(pool_size);
|
||||
let prewarm_count = prewarm_buffers.min(pool_size);
|
||||
|
||||
// Prewarm only a small hot set to avoid large cold-start blocking.
|
||||
// Remaining buffers are allocated lazily and returned to this pool.
|
||||
for _ in 0..prewarm_count {
|
||||
let _ = pool.push(Vec::with_capacity(buffer_size));
|
||||
}
|
||||
|
||||
Self { buffer_pool: Arc::new(pool), buffer_size }
|
||||
}
|
||||
|
||||
pub fn serialize_zero_alloc<T: serde::Serialize>(
|
||||
&self,
|
||||
data: &T,
|
||||
_label: &str,
|
||||
) -> Result<Vec<u8>> {
|
||||
// Try to get a buffer from the pool
|
||||
let mut buffer = self.buffer_pool.pop().unwrap_or_else(|| {
|
||||
let mut buf = Vec::with_capacity(self.buffer_size);
|
||||
buf.resize(self.buffer_size, 0);
|
||||
buf
|
||||
});
|
||||
let mut buffer =
|
||||
self.buffer_pool.pop().unwrap_or_else(|| Vec::with_capacity(self.buffer_size));
|
||||
|
||||
// Serialize into buffer
|
||||
let serialized = bincode::serialize(data)?;
|
||||
@@ -67,12 +75,8 @@ impl ZeroAllocSerializer {
|
||||
}
|
||||
|
||||
/// Global serializer instance.
|
||||
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> = Lazy::new(|| {
|
||||
Arc::new(ZeroAllocSerializer::new(
|
||||
10_000, // Pool size
|
||||
256 * 1024, // Buffer size: 256KB
|
||||
))
|
||||
});
|
||||
static SERIALIZER: Lazy<Arc<ZeroAllocSerializer>> =
|
||||
Lazy::new(|| Arc::new(ZeroAllocSerializer::new(SERIALIZER_POOL_SIZE, SERIALIZER_BUFFER_SIZE)));
|
||||
|
||||
/// Compile-time optimized event processor (zero runtime cost).
|
||||
static COMPILE_TIME_PROCESSOR: CompileTimeOptimizedEventProcessor =
|
||||
@@ -101,7 +105,9 @@ impl Base64Encoder {
|
||||
event_type: &str,
|
||||
) -> Result<String> {
|
||||
let serialized = SERIALIZER.serialize_zero_alloc(value, event_type)?;
|
||||
Ok(STANDARD.encode(&serialized))
|
||||
let encoded = STANDARD.encode(&serialized);
|
||||
SERIALIZER.return_buffer(serialized);
|
||||
Ok(encoded)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -227,6 +233,7 @@ pub fn get_serializer_stats() -> (usize, usize) {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::time::Instant;
|
||||
|
||||
#[test]
|
||||
fn test_base64_encode() {
|
||||
@@ -243,6 +250,110 @@ mod tests {
|
||||
fn test_serializer_stats() {
|
||||
let (available, capacity) = get_serializer_stats();
|
||||
assert!(available <= capacity);
|
||||
assert_eq!(capacity, 10_000);
|
||||
assert_eq!(capacity, SERIALIZER_POOL_SIZE);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serializer_prewarm_is_bounded() {
|
||||
let serializer = ZeroAllocSerializer::new_with_prewarm(128, 1024, 8);
|
||||
let (available, capacity) = serializer.get_pool_stats();
|
||||
assert_eq!(capacity, 128);
|
||||
assert_eq!(available, 8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_serializer_lazy_alloc_and_return() {
|
||||
let serializer = ZeroAllocSerializer::new_with_prewarm(8, 1024, 0);
|
||||
let (available_before, capacity) = serializer.get_pool_stats();
|
||||
assert_eq!(capacity, 8);
|
||||
assert_eq!(available_before, 0);
|
||||
|
||||
let buf = serializer.serialize_zero_alloc(&"hello", "test").unwrap();
|
||||
assert!(buf.capacity() >= 1024);
|
||||
serializer.return_buffer(buf);
|
||||
|
||||
let (available_after, _) = serializer.get_pool_stats();
|
||||
assert_eq!(available_after, 1);
|
||||
}
|
||||
|
||||
fn legacy_eager_zero_fill_serializer(
|
||||
pool_size: usize,
|
||||
buffer_size: usize,
|
||||
) -> ZeroAllocSerializer {
|
||||
let pool = ArrayQueue::new(pool_size);
|
||||
for _ in 0..pool_size {
|
||||
let mut buffer = Vec::with_capacity(buffer_size);
|
||||
buffer.resize(buffer_size, 0);
|
||||
let _ = pool.push(buffer);
|
||||
}
|
||||
ZeroAllocSerializer { buffer_pool: Arc::new(pool), buffer_size }
|
||||
}
|
||||
|
||||
/// Manual perf test: compares old eager cold-start behavior to current bounded prewarm.
|
||||
/// Run with:
|
||||
/// cargo test --release perf_serializer_cold_start_vs_legacy_eager -- --ignored --nocapture
|
||||
#[test]
|
||||
#[ignore = "manual perf benchmark"]
|
||||
fn perf_serializer_cold_start_vs_legacy_eager() {
|
||||
const POOL_SIZE: usize = 4096;
|
||||
const BUFFER_SIZE: usize = 32 * 1024;
|
||||
const PREWARM: usize = 64;
|
||||
let payload = vec![7u8; 4096];
|
||||
|
||||
let legacy_init_start = Instant::now();
|
||||
let legacy = legacy_eager_zero_fill_serializer(POOL_SIZE, BUFFER_SIZE);
|
||||
let legacy_init = legacy_init_start.elapsed();
|
||||
|
||||
let current_init_start = Instant::now();
|
||||
let current = ZeroAllocSerializer::new_with_prewarm(POOL_SIZE, BUFFER_SIZE, PREWARM);
|
||||
let current_init = current_init_start.elapsed();
|
||||
|
||||
let legacy_first_start = Instant::now();
|
||||
let legacy_buf = legacy.serialize_zero_alloc(&payload, "perf").unwrap();
|
||||
let legacy_first = legacy_first_start.elapsed();
|
||||
legacy.return_buffer(legacy_buf);
|
||||
|
||||
let current_first_start = Instant::now();
|
||||
let current_buf = current.serialize_zero_alloc(&payload, "perf").unwrap();
|
||||
let current_first = current_first_start.elapsed();
|
||||
current.return_buffer(current_buf);
|
||||
|
||||
println!(
|
||||
"[perf] serializer cold-start compare\n pool_size={POOL_SIZE} buffer_size={BUFFER_SIZE} prewarm={PREWARM}\n legacy_init={legacy_init:?} current_init={current_init:?}\n legacy_first_serialize={legacy_first:?} current_first_serialize={current_first:?}"
|
||||
);
|
||||
|
||||
assert!(
|
||||
current_init <= legacy_init,
|
||||
"expected bounded prewarm init ({current_init:?}) to be <= legacy eager init ({legacy_init:?})"
|
||||
);
|
||||
}
|
||||
|
||||
/// Manual perf test: demonstrates lazy allocation amortization.
|
||||
/// Run with:
|
||||
/// cargo test --release perf_serializer_lazy_growth_amortization -- --ignored --nocapture
|
||||
#[test]
|
||||
#[ignore = "manual perf benchmark"]
|
||||
fn perf_serializer_lazy_growth_amortization() {
|
||||
const POOL_SIZE: usize = 128;
|
||||
const BUFFER_SIZE: usize = 256 * 1024;
|
||||
let serializer = ZeroAllocSerializer::new_with_prewarm(POOL_SIZE, BUFFER_SIZE, 0);
|
||||
let payload = vec![1u8; 8 * 1024];
|
||||
|
||||
let first_start = Instant::now();
|
||||
let first_buf = serializer.serialize_zero_alloc(&payload, "perf").unwrap();
|
||||
let first = first_start.elapsed();
|
||||
serializer.return_buffer(first_buf);
|
||||
|
||||
let second_start = Instant::now();
|
||||
let second_buf = serializer.serialize_zero_alloc(&payload, "perf").unwrap();
|
||||
let second = second_start.elapsed();
|
||||
serializer.return_buffer(second_buf);
|
||||
|
||||
let (available, capacity) = serializer.get_pool_stats();
|
||||
println!(
|
||||
"[perf] serializer lazy growth\n pool_size={POOL_SIZE} buffer_size={BUFFER_SIZE}\n first_serialize={first:?} second_serialize={second:?}\n available={available} capacity={capacity}"
|
||||
);
|
||||
assert!(available >= 1);
|
||||
assert_eq!(capacity, POOL_SIZE);
|
||||
}
|
||||
}
|
||||
|
||||
+66
-21
@@ -15,6 +15,7 @@ use std::{
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::sync::Mutex;
|
||||
use tokio::time::timeout;
|
||||
|
||||
use crate::common::SolanaRpcClient;
|
||||
use crate::swqos::common::poll_transaction_confirmation;
|
||||
@@ -26,22 +27,44 @@ use crate::{
|
||||
};
|
||||
|
||||
const ALPN_TPU_PROTOCOL_ID: &[u8] = b"solana-tpu";
|
||||
const SPEED_SERVER: &str = "speed-landing";
|
||||
/// Fallback SNI when endpoint is IP or cannot extract host (keeps legacy behavior).
|
||||
const SPEED_SERVER_FALLBACK: &str = "speed-landing";
|
||||
const KEEP_ALIVE_INTERVAL: Duration = Duration::from_secs(25);
|
||||
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 rpc_client: Arc<SolanaRpcClient>,
|
||||
endpoint: Endpoint,
|
||||
client_config: ClientConfig,
|
||||
addr: SocketAddr,
|
||||
/// TLS SNI: host from endpoint URL so server presents the right cert (e.g. nyc.speedlanding.trade).
|
||||
server_name: String,
|
||||
connection: ArcSwap<Connection>,
|
||||
reconnect: Mutex<()>,
|
||||
}
|
||||
|
||||
impl SpeedlandingClient {
|
||||
/// Extract TLS SNI (host) from endpoint URL. Uses fallback "speed-landing" for IP or when host cannot be determined.
|
||||
fn server_name_from_endpoint(endpoint: &str) -> String {
|
||||
let without_scheme = endpoint
|
||||
.strip_prefix("https://")
|
||||
.or_else(|| endpoint.strip_prefix("http://"))
|
||||
.unwrap_or(endpoint);
|
||||
let host = without_scheme.split(':').next().unwrap_or("").trim();
|
||||
if host.is_empty() {
|
||||
return SPEED_SERVER_FALLBACK.to_string();
|
||||
}
|
||||
if !host.chars().any(|c| c.is_ascii_alphabetic()) {
|
||||
return SPEED_SERVER_FALLBACK.to_string();
|
||||
}
|
||||
host.to_string()
|
||||
}
|
||||
|
||||
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let server_name = Self::server_name_from_endpoint(&endpoint_string);
|
||||
let keypair = Keypair::from_base58_string(&api_key);
|
||||
let (cert, key) = new_dummy_x509_certificate(&keypair);
|
||||
let mut crypto = rustls::ClientConfig::builder()
|
||||
@@ -66,26 +89,47 @@ impl SpeedlandingClient {
|
||||
.to_socket_addrs()?
|
||||
.next()
|
||||
.ok_or_else(|| anyhow::anyhow!("Address not resolved"))?;
|
||||
let connection = endpoint.connect(addr, SPEED_SERVER)?.await?;
|
||||
let connecting = endpoint.connect(addr, &server_name)?;
|
||||
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||
.await
|
||||
.context("Speedlanding QUIC connect timeout")?
|
||||
.context("Speedlanding QUIC handshake failed")?;
|
||||
|
||||
Ok(Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
endpoint,
|
||||
client_config,
|
||||
addr,
|
||||
server_name,
|
||||
connection: ArcSwap::from_pointee(connection),
|
||||
reconnect: Mutex::new(()),
|
||||
})
|
||||
}
|
||||
|
||||
async fn reconnect(&self) -> Result<()> {
|
||||
let _guard = self.reconnect.try_lock()?;
|
||||
let connection = self
|
||||
.endpoint
|
||||
.connect_with(self.client_config.clone(), self.addr, SPEED_SERVER)?
|
||||
.await?;
|
||||
self.connection.store(Arc::new(connection));
|
||||
Ok(())
|
||||
/// Ensure we have a live connection: if current one is closed, reconnect under lock so
|
||||
/// concurrent senders wait and then all use the new connection. Uses blocking lock so
|
||||
/// waiters get the updated connection.
|
||||
async fn ensure_connected(&self) -> Result<Arc<Connection>> {
|
||||
let guard = self.reconnect.lock().await;
|
||||
let current = self.connection.load_full();
|
||||
if current.close_reason().is_none() {
|
||||
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, self.server_name.as_str())?;
|
||||
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||
.await
|
||||
.context("Speedlanding QUIC reconnect timeout")?
|
||||
.context("Speedlanding QUIC re-handshake failed")?;
|
||||
self.connection.store(Arc::new(connection));
|
||||
return Ok(self.connection.load_full());
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
|
||||
async fn try_send_bytes(connection: &Connection, payload: &[u8]) -> Result<()> {
|
||||
@@ -106,20 +150,21 @@ impl SwqosClientTrait for SpeedlandingClient {
|
||||
) -> Result<()> {
|
||||
let start_time = Instant::now();
|
||||
let (buf_guard, signature) = serialize_transaction_bincode_sync(transaction)?;
|
||||
let connection = self.connection.load_full();
|
||||
if Self::try_send_bytes(&connection, &*buf_guard).await.is_err() {
|
||||
let connection = self.ensure_connected().await?;
|
||||
let mut send_result = timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||
let need_retry = match &send_result {
|
||||
Ok(Ok(())) => false,
|
||||
Ok(Err(_)) | Err(_) => true,
|
||||
};
|
||||
if need_retry {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!(" [speedlanding] {} submission failed, reconnecting", trade_type);
|
||||
}
|
||||
self.reconnect().await?;
|
||||
let connection = self.connection.load_full();
|
||||
if let Err(e) = Self::try_send_bytes(&connection, &*buf_guard).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!(" [speedlanding] {} submission failed: {:?}", trade_type, e);
|
||||
}
|
||||
return Err(e.into());
|
||||
eprintln!(" [speedlanding] {} send failed or timeout, reconnecting", trade_type);
|
||||
}
|
||||
let connection = self.ensure_connected().await?;
|
||||
send_result = timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||
}
|
||||
send_result
|
||||
.context("Speedlanding QUIC send timeout")??;
|
||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ use once_cell::sync::Lazy;
|
||||
use smallvec::SmallVec;
|
||||
use solana_sdk::instruction::Instruction;
|
||||
use solana_compute_budget_interface::ComputeBudgetInstruction;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Cache key containing all parameters for compute budget instructions
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
|
||||
@@ -11,43 +12,52 @@ struct ComputeBudgetCacheKey {
|
||||
unit_limit: u32,
|
||||
}
|
||||
|
||||
/// Global cache storing compute budget instructions
|
||||
/// Uses DashMap for high-performance lock-free concurrent access
|
||||
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, SmallVec<[Instruction; 2]>>> =
|
||||
/// Global cache storing compute budget instructions (Arc to avoid clone on hit).
|
||||
/// Uses DashMap for high-performance lock-free concurrent access.
|
||||
static COMPUTE_BUDGET_CACHE: Lazy<DashMap<ComputeBudgetCacheKey, Arc<SmallVec<[Instruction; 2]>>>> =
|
||||
Lazy::new(|| DashMap::new());
|
||||
|
||||
/// Extend `instructions` with compute budget instructions; on cache hit extends from cached Arc (no SmallVec clone).
|
||||
#[inline(always)]
|
||||
pub fn compute_budget_instructions(
|
||||
pub fn extend_compute_budget_instructions(
|
||||
instructions: &mut Vec<Instruction>,
|
||||
unit_price: u64,
|
||||
unit_limit: u32,
|
||||
) -> SmallVec<[Instruction; 2]> {
|
||||
// Create cache key
|
||||
let cache_key = ComputeBudgetCacheKey {
|
||||
unit_price: unit_price,
|
||||
unit_limit: unit_limit,
|
||||
};
|
||||
) {
|
||||
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
|
||||
|
||||
// Try to get from cache first
|
||||
if let Some(cached_insts) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
||||
return cached_insts.clone();
|
||||
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
||||
instructions.extend(cached.iter().cloned());
|
||||
return;
|
||||
}
|
||||
|
||||
// Cache miss, generate new instructions
|
||||
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
||||
|
||||
// Only add compute unit price instruction if > 0
|
||||
if unit_price > 0 {
|
||||
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
|
||||
}
|
||||
|
||||
// Only add compute unit limit instruction if > 0
|
||||
if unit_limit > 0 {
|
||||
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
|
||||
}
|
||||
let arc = Arc::new(insts);
|
||||
instructions.extend(arc.iter().cloned());
|
||||
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
|
||||
}
|
||||
|
||||
// Store result in cache
|
||||
let insts_clone = insts.clone();
|
||||
COMPUTE_BUDGET_CACHE.insert(cache_key, insts_clone);
|
||||
|
||||
/// Returns compute budget instructions (allocates on cache hit; prefer `extend_compute_budget_instructions` on hot path).
|
||||
#[inline(always)]
|
||||
pub fn compute_budget_instructions(unit_price: u64, unit_limit: u32) -> SmallVec<[Instruction; 2]> {
|
||||
let cache_key = ComputeBudgetCacheKey { unit_price, unit_limit };
|
||||
if let Some(cached) = COMPUTE_BUDGET_CACHE.get(&cache_key) {
|
||||
return (**cached).clone();
|
||||
}
|
||||
let mut insts = SmallVec::<[Instruction; 2]>::new();
|
||||
if unit_price > 0 {
|
||||
insts.push(ComputeBudgetInstruction::set_compute_unit_price(unit_price));
|
||||
}
|
||||
if unit_limit > 0 {
|
||||
insts.push(ComputeBudgetInstruction::set_compute_unit_limit(unit_limit));
|
||||
}
|
||||
let arc = Arc::new(insts.clone());
|
||||
COMPUTE_BUDGET_CACHE.insert(cache_key, arc);
|
||||
insts
|
||||
}
|
||||
|
||||
@@ -12,9 +12,7 @@ use crate::common::nonce_cache::DurableNonceInfo;
|
||||
pub fn add_nonce_instruction(
|
||||
instructions: &mut Vec<Instruction>,
|
||||
payer: &Keypair,
|
||||
// nonce_account: Option<Pubkey>,
|
||||
// current_nonce: Option<Hash>,
|
||||
durable_nonce: Option<DurableNonceInfo>,
|
||||
durable_nonce: Option<&DurableNonceInfo>,
|
||||
) -> Result<(), anyhow::Error> {
|
||||
if let Some(durable_nonce) = durable_nonce {
|
||||
let nonce_advance_ix = advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
|
||||
@@ -24,17 +22,22 @@ pub fn add_nonce_instruction(
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Get blockhash for transaction
|
||||
/// If nonce account is used, return blockhash from nonce, otherwise return the provided recent_blockhash
|
||||
/// Get blockhash for transaction.
|
||||
/// If nonce account is used, returns blockhash from nonce; otherwise returns the provided recent_blockhash.
|
||||
/// Returns error when neither durable_nonce nor recent_blockhash is set (caller must provide one for low latency).
|
||||
pub fn get_transaction_blockhash(
|
||||
recent_blockhash: Option<Hash>,
|
||||
durable_nonce: Option<DurableNonceInfo>,
|
||||
// nonce_account: Option<Pubkey>,
|
||||
// current_nonce: Option<Hash>,
|
||||
) -> Hash {
|
||||
durable_nonce: Option<&DurableNonceInfo>,
|
||||
) -> Result<Hash, anyhow::Error> {
|
||||
if let Some(durable_nonce) = durable_nonce {
|
||||
durable_nonce.current_nonce.unwrap()
|
||||
durable_nonce
|
||||
.current_nonce
|
||||
.ok_or_else(|| anyhow::anyhow!("durable_nonce.current_nonce is None"))
|
||||
} else if let Some(hash) = recent_blockhash {
|
||||
Ok(hash)
|
||||
} else {
|
||||
recent_blockhash.unwrap()
|
||||
Err(anyhow::anyhow!(
|
||||
"Must provide either recent_blockhash or durable_nonce for transaction"
|
||||
))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,70 +1,66 @@
|
||||
use solana_hash::Hash;
|
||||
use solana_sdk::{
|
||||
instruction::Instruction, message::AddressLookupTableAccount, native_token::sol_str_to_lamports, pubkey::Pubkey, signature::Keypair, signer::Signer, transaction::VersionedTransaction
|
||||
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
|
||||
signature::Keypair, signer::Signer, transaction::VersionedTransaction,
|
||||
};
|
||||
use solana_system_interface::instruction::transfer;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{
|
||||
compute_budget_manager::compute_budget_instructions,
|
||||
nonce_manager::{add_nonce_instruction, get_transaction_blockhash},
|
||||
};
|
||||
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
|
||||
use crate::{
|
||||
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
|
||||
trading::{MiddlewareManager, core::transaction_pool::{acquire_builder, release_builder}},
|
||||
};
|
||||
|
||||
/// Convert SOL amount (f64) to lamports without string allocation (hot path).
|
||||
#[inline(always)]
|
||||
fn sol_f64_to_lamports(sol: f64) -> u64 {
|
||||
if sol <= 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let lamports = sol * 1_000_000_000.0;
|
||||
(lamports.min(u64::MAX as f64)).round() as u64
|
||||
}
|
||||
|
||||
/// Build standard RPC transaction.
|
||||
/// Takes `business_instructions` by reference to avoid per-task Vec clone in execute_parallel.
|
||||
/// Takes Arc/context by reference to avoid clone in worker hot path (Arc::clone is cheap but ref is zero-cost).
|
||||
pub async fn build_transaction(
|
||||
payer: Arc<Keypair>,
|
||||
_rpc: Option<Arc<SolanaRpcClient>>,
|
||||
payer: &Arc<Keypair>,
|
||||
_rpc: Option<&Arc<SolanaRpcClient>>,
|
||||
unit_limit: u32,
|
||||
unit_price: u64,
|
||||
business_instructions: &[Instruction],
|
||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
address_lookup_table_account: Option<&AddressLookupTableAccount>,
|
||||
recent_blockhash: Option<Hash>,
|
||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
middleware_manager: Option<&Arc<MiddlewareManager>>,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
with_tip: bool,
|
||||
tip_account: &Pubkey,
|
||||
tip_amount: f64,
|
||||
durable_nonce: Option<DurableNonceInfo>,
|
||||
// nonce_account: Option<Pubkey>,
|
||||
// current_nonce: Option<Hash>,
|
||||
durable_nonce: Option<&DurableNonceInfo>,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let mut instructions = Vec::with_capacity(business_instructions.len() + 5);
|
||||
|
||||
// Add nonce instruction
|
||||
if let Err(e) =
|
||||
add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce.clone())
|
||||
{
|
||||
if let Err(e) = add_nonce_instruction(&mut instructions, payer.as_ref(), durable_nonce) {
|
||||
return Err(e);
|
||||
}
|
||||
|
||||
// Add tip transfer instruction
|
||||
if with_tip && tip_amount > 0.0 {
|
||||
instructions.push(transfer(
|
||||
&payer.pubkey(),
|
||||
tip_account,
|
||||
sol_str_to_lamports(tip_amount.to_string().as_str()).unwrap_or(0),
|
||||
));
|
||||
let tip_lamports = sol_f64_to_lamports(tip_amount);
|
||||
instructions.push(transfer(&payer.pubkey(), tip_account, tip_lamports));
|
||||
}
|
||||
|
||||
// Add compute budget instructions
|
||||
instructions.extend(compute_budget_instructions(
|
||||
super::compute_budget_manager::extend_compute_budget_instructions(
|
||||
&mut instructions,
|
||||
unit_price,
|
||||
unit_limit,
|
||||
));
|
||||
);
|
||||
|
||||
// Add business instructions (clone only here; avoids per-task Vec clone in execute_parallel)
|
||||
instructions.extend_from_slice(business_instructions);
|
||||
|
||||
// Get blockhash for transaction
|
||||
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce.clone());
|
||||
let blockhash = get_transaction_blockhash(recent_blockhash, durable_nonce)?;
|
||||
|
||||
// Build transaction
|
||||
build_versioned_transaction(
|
||||
payer,
|
||||
instructions,
|
||||
@@ -77,23 +73,18 @@ pub async fn build_transaction(
|
||||
.await
|
||||
}
|
||||
|
||||
/// Low-level function for building versioned transactions
|
||||
async fn build_versioned_transaction(
|
||||
payer: Arc<Keypair>,
|
||||
payer: &Arc<Keypair>,
|
||||
instructions: Vec<Instruction>,
|
||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
address_lookup_table_account: Option<&AddressLookupTableAccount>,
|
||||
blockhash: Hash,
|
||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
middleware_manager: Option<&Arc<MiddlewareManager>>,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<VersionedTransaction, anyhow::Error> {
|
||||
let full_instructions = match middleware_manager {
|
||||
Some(middleware_manager) => middleware_manager
|
||||
.apply_middlewares_process_full_instructions(
|
||||
instructions,
|
||||
protocol_name.to_string(),
|
||||
is_buy,
|
||||
)?,
|
||||
.apply_middlewares_process_full_instructions(instructions, protocol_name, is_buy)?,
|
||||
None => instructions,
|
||||
};
|
||||
|
||||
@@ -108,7 +99,7 @@ async fn build_versioned_transaction(
|
||||
);
|
||||
|
||||
let msg_bytes = versioned_msg.serialize();
|
||||
let signature = payer.try_sign_message(&msg_bytes).expect("sign failed");
|
||||
let signature = payer.as_ref().try_sign_message(&msg_bytes).expect("sign failed");
|
||||
let tx = VersionedTransaction { signatures: vec![signature], message: versioned_msg };
|
||||
|
||||
// 归还构建器到池
|
||||
|
||||
@@ -2,7 +2,11 @@ use solana_sdk::{pubkey::Pubkey, signature::Keypair, signer::Signer, transaction
|
||||
use solana_system_interface::instruction::transfer;
|
||||
|
||||
use crate::common::{
|
||||
fast_fn::get_associated_token_address_with_program_id_fast, spl_token::close_account,
|
||||
fast_fn::{
|
||||
get_associated_token_address_with_program_id_fast,
|
||||
get_associated_token_address_with_program_id_fast_use_seed,
|
||||
},
|
||||
spl_token::close_account,
|
||||
SolanaRpcClient,
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
@@ -36,10 +40,30 @@ pub async fn get_token_balance(
|
||||
payer: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
) -> Result<u64, anyhow::Error> {
|
||||
let ata = crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
get_token_balance_with_options(
|
||||
rpc,
|
||||
payer,
|
||||
mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
false,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
/// 使用与交易指令一致的 ATA 推导(可选 seed)查询余额;卖出/余额查询应与买入使用同一 ATA 地址。
|
||||
#[inline]
|
||||
pub async fn get_token_balance_with_options(
|
||||
rpc: &SolanaRpcClient,
|
||||
payer: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
use_seed: bool,
|
||||
) -> Result<u64, anyhow::Error> {
|
||||
let ata = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
payer,
|
||||
mint,
|
||||
token_program,
|
||||
use_seed,
|
||||
);
|
||||
let balance = rpc.get_token_account_balance(&ata).await?;
|
||||
let balance_u64 =
|
||||
|
||||
+215
-115
@@ -1,15 +1,26 @@
|
||||
//! Parallel executor for multi-SWQOS submit.
|
||||
//!
|
||||
//! - **Pool**: Pre-spawned workers; hot path only enqueues jobs (no per-call tokio::spawn).
|
||||
//! - **Arc**: Shared data is behind `Arc` so "clone" is just a refcount increment (no data copy).
|
||||
//! - **Refs**: `build_transaction` takes `&Arc<..>`, `Option<&DurableNonceInfo>`, `Option<&AddressLookupTableAccount>` so the worker passes refs only (zero clone on worker path).
|
||||
|
||||
use anyhow::{anyhow, Result};
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use once_cell::sync::OnceCell;
|
||||
use solana_hash::Hash;
|
||||
use solana_sdk::message::AddressLookupTableAccount;
|
||||
use solana_sdk::{
|
||||
instruction::Instruction, pubkey::Pubkey, signature::Keypair, signature::Signature,
|
||||
};
|
||||
use std::collections::HashMap;
|
||||
use std::hash::BuildHasherDefault;
|
||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||
use std::{str::FromStr, sync::Arc, time::Instant};
|
||||
|
||||
use fnv::FnvHasher;
|
||||
|
||||
type FnvHashMap<K, V> = HashMap<K, V, BuildHasherDefault<FnvHasher>>;
|
||||
|
||||
use crate::{
|
||||
common::nonce_cache::DurableNonceInfo,
|
||||
common::{GasFeeStrategy, SolanaRpcClient},
|
||||
@@ -17,14 +28,142 @@ use crate::{
|
||||
trading::{common::build_transaction, MiddlewareManager},
|
||||
};
|
||||
|
||||
const SWQOS_POOL_WORKERS: usize = 32;
|
||||
const SWQOS_QUEUE_CAP: usize = 128;
|
||||
|
||||
/// Shared across all jobs in one batch; built once, cloned as single Arc per job (minimal hot-path clone).
|
||||
struct SwqosSharedContext {
|
||||
payer: Arc<Keypair>,
|
||||
instructions: Arc<Vec<Instruction>>,
|
||||
rpc: Option<Arc<SolanaRpcClient>>,
|
||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
recent_blockhash: Option<Hash>,
|
||||
durable_nonce: Option<DurableNonceInfo>,
|
||||
middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
protocol_name: &'static str,
|
||||
is_buy: bool,
|
||||
wait_transaction_confirmed: bool,
|
||||
with_tip: bool,
|
||||
collector: Arc<ResultCollector>,
|
||||
}
|
||||
|
||||
/// One SWQOS submit task; only per-task data + one Arc to shared (reduces hot-path clones).
|
||||
struct SwqosJob {
|
||||
shared: Arc<SwqosSharedContext>,
|
||||
tip: f64,
|
||||
unit_limit: u32,
|
||||
unit_price: u64,
|
||||
tip_account: Arc<Pubkey>,
|
||||
swqos_client: Arc<SwqosClient>,
|
||||
swqos_type: SwqosType,
|
||||
core_id: Option<core_affinity::CoreId>,
|
||||
use_affinity: bool,
|
||||
}
|
||||
|
||||
async fn run_one_swqos_job(job: SwqosJob) {
|
||||
let s = &job.shared;
|
||||
if job.use_affinity {
|
||||
if let Some(cid) = job.core_id {
|
||||
core_affinity::set_for_current(cid);
|
||||
}
|
||||
}
|
||||
|
||||
let tip_amount = if s.with_tip { job.tip } else { 0.0 };
|
||||
|
||||
let transaction = match build_transaction(
|
||||
&s.payer,
|
||||
s.rpc.as_ref(),
|
||||
job.unit_limit,
|
||||
job.unit_price,
|
||||
s.instructions.as_ref(),
|
||||
s.address_lookup_table_account.as_ref(),
|
||||
s.recent_blockhash,
|
||||
s.middleware_manager.as_ref(),
|
||||
s.protocol_name,
|
||||
s.is_buy,
|
||||
job.swqos_type != SwqosType::Default,
|
||||
&job.tip_account,
|
||||
tip_amount,
|
||||
s.durable_nonce.as_ref(),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(tx) => tx,
|
||||
Err(e) => {
|
||||
s.collector.submit(TaskResult {
|
||||
success: false,
|
||||
signature: Signature::default(),
|
||||
error: Some(e),
|
||||
swqos_type: job.swqos_type,
|
||||
landed_on_chain: false,
|
||||
submit_done_us: crate::common::clock::now_micros(),
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let (success, err, landed_on_chain) = match job
|
||||
.swqos_client
|
||||
.send_transaction(
|
||||
if s.is_buy {
|
||||
TradeType::Buy
|
||||
} else {
|
||||
TradeType::Sell
|
||||
},
|
||||
&transaction,
|
||||
s.wait_transaction_confirmed,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => (true, None, true),
|
||||
Err(e) => {
|
||||
let landed = is_landed_error(&e);
|
||||
(false, Some(e), landed)
|
||||
}
|
||||
};
|
||||
|
||||
let sig = transaction.signatures.first().copied().unwrap_or_default();
|
||||
s.collector.submit(TaskResult {
|
||||
success,
|
||||
signature: sig,
|
||||
error: err,
|
||||
swqos_type: job.swqos_type,
|
||||
landed_on_chain,
|
||||
submit_done_us: crate::common::clock::now_micros(),
|
||||
});
|
||||
}
|
||||
|
||||
async fn swqos_worker_loop(queue: Arc<ArrayQueue<SwqosJob>>) {
|
||||
loop {
|
||||
if let Some(job) = queue.pop() {
|
||||
run_one_swqos_job(job).await;
|
||||
} else {
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static SWQOS_QUEUE: OnceCell<Arc<ArrayQueue<SwqosJob>>> = OnceCell::new();
|
||||
static SWQOS_WORKERS_STARTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
fn ensure_swqos_pool(queue: Arc<ArrayQueue<SwqosJob>>) {
|
||||
if SWQOS_WORKERS_STARTED.swap(true, Ordering::AcqRel) {
|
||||
return;
|
||||
}
|
||||
for _ in 0..SWQOS_POOL_WORKERS {
|
||||
tokio::spawn(swqos_worker_loop(queue.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
#[repr(align(64))]
|
||||
struct TaskResult {
|
||||
success: bool,
|
||||
signature: Signature,
|
||||
error: Option<anyhow::Error>,
|
||||
#[allow(dead_code)]
|
||||
swqos_type: SwqosType,
|
||||
landed_on_chain: bool,
|
||||
/// Microsecond timestamp when this task finished (SWQOS returned); for per-SWQOS event→submit timing.
|
||||
submit_done_us: i64,
|
||||
}
|
||||
|
||||
/// Check if an error indicates the transaction landed on-chain (vs network/timeout error)
|
||||
@@ -87,7 +226,7 @@ impl ResultCollector {
|
||||
self.completed_count.fetch_add(1, Ordering::Release);
|
||||
}
|
||||
|
||||
async fn wait_for_success(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
||||
async fn wait_for_success(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||
let start = Instant::now();
|
||||
let timeout = std::time::Duration::from_secs(5);
|
||||
let poll_interval = std::time::Duration::from_millis(1000);
|
||||
@@ -96,14 +235,16 @@ impl ResultCollector {
|
||||
if self.success_flag.load(Ordering::Acquire) {
|
||||
let mut signatures = Vec::new();
|
||||
let mut has_success = false;
|
||||
let mut submit_timings = Vec::new();
|
||||
while let Some(result) = self.results.pop() {
|
||||
signatures.push(result.signature);
|
||||
submit_timings.push((result.swqos_type, result.submit_done_us));
|
||||
if result.success {
|
||||
has_success = true;
|
||||
}
|
||||
}
|
||||
if has_success && !signatures.is_empty() {
|
||||
return Some((true, signatures, None));
|
||||
return Some((true, signatures, None, submit_timings));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -112,15 +253,17 @@ impl ResultCollector {
|
||||
if self.landed_failed_flag.load(Ordering::Acquire) {
|
||||
let mut signatures = Vec::new();
|
||||
let mut landed_error = None;
|
||||
let mut submit_timings = Vec::new();
|
||||
while let Some(result) = self.results.pop() {
|
||||
signatures.push(result.signature);
|
||||
submit_timings.push((result.swqos_type, result.submit_done_us));
|
||||
// Prefer the error from the tx that actually landed
|
||||
if result.landed_on_chain && result.error.is_some() {
|
||||
landed_error = result.error;
|
||||
}
|
||||
}
|
||||
if !signatures.is_empty() {
|
||||
return Some((false, signatures, landed_error));
|
||||
return Some((false, signatures, landed_error, submit_timings));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -129,8 +272,10 @@ impl ResultCollector {
|
||||
let mut signatures = Vec::new();
|
||||
let mut last_error = None;
|
||||
let mut any_success = false;
|
||||
let mut submit_timings = Vec::new();
|
||||
while let Some(result) = self.results.pop() {
|
||||
signatures.push(result.signature);
|
||||
submit_timings.push((result.swqos_type, result.submit_done_us));
|
||||
if result.success {
|
||||
any_success = true;
|
||||
}
|
||||
@@ -139,7 +284,7 @@ impl ResultCollector {
|
||||
}
|
||||
}
|
||||
if !signatures.is_empty() {
|
||||
return Some((any_success, signatures, last_error));
|
||||
return Some((any_success, signatures, last_error, submit_timings));
|
||||
}
|
||||
return None;
|
||||
}
|
||||
@@ -151,13 +296,15 @@ impl ResultCollector {
|
||||
}
|
||||
}
|
||||
|
||||
fn get_first(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
||||
fn get_first(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||
let mut signatures = Vec::new();
|
||||
let mut has_success = false;
|
||||
let mut last_error = None;
|
||||
|
||||
let mut submit_timings = Vec::new();
|
||||
|
||||
while let Some(result) = self.results.pop() {
|
||||
signatures.push(result.signature);
|
||||
submit_timings.push((result.swqos_type, result.submit_done_us));
|
||||
if result.success {
|
||||
has_success = true;
|
||||
}
|
||||
@@ -165,19 +312,20 @@ impl ResultCollector {
|
||||
last_error = result.error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if !signatures.is_empty() {
|
||||
Some((has_success, signatures, last_error))
|
||||
Some((has_success, signatures, last_error, submit_timings))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// 等待全部任务完成(不等待链上确认),然后收集并返回所有签名。用于「多路提交」时返回多笔签名。
|
||||
async fn wait_for_all_submitted(&self, timeout_secs: u64) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
||||
/// 轮询间隔 2ms,避免 50ms 间隔在最后一笔返回时多等几十 ms 拉高 submit 耗时。
|
||||
async fn wait_for_all_submitted(&self, timeout_secs: u64) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||
let start = Instant::now();
|
||||
let timeout = std::time::Duration::from_secs(timeout_secs);
|
||||
let poll_interval = std::time::Duration::from_millis(50);
|
||||
let poll_interval = std::time::Duration::from_millis(2);
|
||||
while self.completed_count.load(Ordering::Acquire) < self.total_tasks {
|
||||
if start.elapsed() > timeout {
|
||||
break;
|
||||
@@ -205,7 +353,7 @@ pub async fn execute_parallel(
|
||||
gas_fee_strategy: GasFeeStrategy,
|
||||
use_core_affinity: bool,
|
||||
check_min_tip: bool,
|
||||
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
||||
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||
let _exec_start = Instant::now();
|
||||
|
||||
if swqos_clients.is_empty() {
|
||||
@@ -272,126 +420,78 @@ pub async fn execute_parallel(
|
||||
return Err(anyhow!("Multiple swqos transactions require durable_nonce to be set.",));
|
||||
}
|
||||
|
||||
// Task preparation completed
|
||||
|
||||
// Task preparation completed: one shared context (clone once per batch), then minimal per-task data.
|
||||
let collector = Arc::new(ResultCollector::new(task_configs.len()));
|
||||
let _spawn_start = Instant::now();
|
||||
let shared = Arc::new(SwqosSharedContext {
|
||||
payer,
|
||||
instructions,
|
||||
rpc,
|
||||
address_lookup_table_account,
|
||||
recent_blockhash,
|
||||
durable_nonce,
|
||||
middleware_manager,
|
||||
protocol_name,
|
||||
is_buy,
|
||||
wait_transaction_confirmed,
|
||||
with_tip,
|
||||
collector: collector.clone(),
|
||||
});
|
||||
|
||||
for (i, swqos_client, gas_fee_strategy_config) in task_configs {
|
||||
let core_id = cores.get(i % cores.len().max(1)).copied();
|
||||
let use_affinity = use_core_affinity;
|
||||
let payer = payer.clone();
|
||||
let instructions = instructions.clone();
|
||||
let middleware_manager = middleware_manager.clone();
|
||||
let swqos_type = swqos_client.get_swqos_type();
|
||||
let tip_account_str = swqos_client.get_tip_account()?;
|
||||
let tip_account = Arc::new(Pubkey::from_str(&tip_account_str).unwrap_or_default());
|
||||
let collector = collector.clone();
|
||||
let queue = SWQOS_QUEUE.get_or_init(|| Arc::new(ArrayQueue::new(SWQOS_QUEUE_CAP)));
|
||||
ensure_swqos_pool(queue.clone());
|
||||
|
||||
let tip = gas_fee_strategy_config.2.tip;
|
||||
let unit_limit = gas_fee_strategy_config.2.cu_limit;
|
||||
let unit_price = gas_fee_strategy_config.2.cu_price;
|
||||
let rpc = rpc.clone();
|
||||
let durable_nonce = durable_nonce.clone();
|
||||
let address_lookup_table_account = address_lookup_table_account.clone();
|
||||
let recent_blockhash_task = recent_blockhash.clone();
|
||||
|
||||
tokio::spawn(async move {
|
||||
let _task_start = Instant::now();
|
||||
if use_affinity {
|
||||
if let Some(cid) = core_id {
|
||||
core_affinity::set_for_current(cid);
|
||||
{
|
||||
// Cache tip_account per client (one get_tip_account/from_str per unique client per batch). Dropped before await so future stays Send.
|
||||
let mut tip_cache: FnvHashMap<*const (), Arc<Pubkey>> =
|
||||
FnvHashMap::with_capacity_and_hasher(task_configs.len(), BuildHasherDefault::default());
|
||||
for (i, swqos_client, gas_fee_strategy_config) in task_configs {
|
||||
let core_id = cores.get(i % cores.len().max(1)).copied();
|
||||
let swqos_type = swqos_client.get_swqos_type();
|
||||
let key = Arc::as_ptr(&swqos_client) as *const ();
|
||||
let tip_account = match tip_cache.get(&key) {
|
||||
Some(tip) => tip.clone(),
|
||||
None => {
|
||||
let s = swqos_client.get_tip_account()?;
|
||||
let tip = Arc::new(Pubkey::from_str(&s).unwrap_or_default());
|
||||
tip_cache.insert(key, tip.clone());
|
||||
tip
|
||||
}
|
||||
}
|
||||
|
||||
let tip_amount = if with_tip { tip } else { 0.0 };
|
||||
|
||||
let _build_start = Instant::now();
|
||||
let transaction = match build_transaction(
|
||||
payer,
|
||||
rpc,
|
||||
};
|
||||
let (tip, unit_limit, unit_price) = (
|
||||
gas_fee_strategy_config.2.tip,
|
||||
gas_fee_strategy_config.2.cu_limit,
|
||||
gas_fee_strategy_config.2.cu_price,
|
||||
);
|
||||
let job = SwqosJob {
|
||||
shared: shared.clone(),
|
||||
tip,
|
||||
unit_limit,
|
||||
unit_price,
|
||||
instructions.as_ref(),
|
||||
address_lookup_table_account,
|
||||
recent_blockhash_task,
|
||||
middleware_manager,
|
||||
protocol_name,
|
||||
is_buy,
|
||||
swqos_type != SwqosType::Default,
|
||||
&tip_account,
|
||||
tip_amount,
|
||||
durable_nonce,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(tx) => tx,
|
||||
Err(e) => {
|
||||
// Build transaction failed
|
||||
collector.submit(TaskResult {
|
||||
success: false,
|
||||
signature: Signature::default(),
|
||||
error: Some(e),
|
||||
swqos_type,
|
||||
landed_on_chain: false,
|
||||
});
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
// Transaction built
|
||||
|
||||
let _send_start = Instant::now();
|
||||
let mut err: Option<anyhow::Error> = None;
|
||||
#[allow(unused_assignments)]
|
||||
let mut landed_on_chain = false;
|
||||
let success = match swqos_client
|
||||
.send_transaction(
|
||||
if is_buy { TradeType::Buy } else { TradeType::Sell },
|
||||
&transaction,
|
||||
wait_transaction_confirmed,
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(()) => {
|
||||
landed_on_chain = true; // Success means tx confirmed on-chain
|
||||
true
|
||||
}
|
||||
Err(e) => {
|
||||
// Check if this error indicates the tx landed but failed (e.g., ExceededSlippage)
|
||||
landed_on_chain = is_landed_error(&e);
|
||||
err = Some(e);
|
||||
// Send transaction failed
|
||||
false
|
||||
}
|
||||
};
|
||||
|
||||
// Transaction sent: always submit a result so collector never has "no result" for this task.
|
||||
// If transaction has no signatures (malformed), submit with default signature and success=false.
|
||||
let sig = transaction.signatures.first().copied().unwrap_or_default();
|
||||
collector.submit(TaskResult {
|
||||
success,
|
||||
signature: sig,
|
||||
error: err,
|
||||
tip_account,
|
||||
swqos_client,
|
||||
swqos_type,
|
||||
landed_on_chain,
|
||||
});
|
||||
});
|
||||
core_id,
|
||||
use_affinity: use_core_affinity,
|
||||
};
|
||||
let _ = queue.push(job);
|
||||
}
|
||||
}
|
||||
|
||||
// All tasks spawned
|
||||
// All jobs enqueued (no spawn on hot path)
|
||||
|
||||
if !wait_transaction_confirmed {
|
||||
const SUBMIT_TIMEOUT_SECS: u64 = 30;
|
||||
let (success, signatures, last_error) = collector
|
||||
let ret = collector
|
||||
.wait_for_all_submitted(SUBMIT_TIMEOUT_SECS)
|
||||
.await
|
||||
.unwrap_or((false, vec![], Some(anyhow!("No SWQOS result within {}s", SUBMIT_TIMEOUT_SECS))));
|
||||
return Ok((success, signatures, last_error));
|
||||
.unwrap_or((false, vec![], Some(anyhow!("No SWQOS result within {}s", SUBMIT_TIMEOUT_SECS)), vec![]));
|
||||
let (success, signatures, last_error, submit_timings) = ret;
|
||||
return Ok((success, signatures, last_error, submit_timings));
|
||||
}
|
||||
|
||||
if let Some(result) = collector.wait_for_success().await {
|
||||
Ok(result)
|
||||
let (success, signatures, last_error, submit_timings) = result;
|
||||
Ok((success, signatures, last_error, submit_timings))
|
||||
} else {
|
||||
Err(anyhow!("All transactions failed"))
|
||||
}
|
||||
|
||||
+121
-54
@@ -69,7 +69,7 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
} else {
|
||||
self.instruction_builder.build_sell_instructions(¶ms).await?
|
||||
};
|
||||
let build_elapsed = build_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
let _build_elapsed = build_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
|
||||
InstructionProcessor::preprocess(&instructions)?;
|
||||
|
||||
@@ -77,13 +77,17 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
Some(middleware_manager) => middleware_manager
|
||||
.apply_middlewares_process_protocol_instructions(
|
||||
instructions,
|
||||
self.protocol_name.to_string(),
|
||||
self.protocol_name,
|
||||
is_buy,
|
||||
)?,
|
||||
None => instructions,
|
||||
};
|
||||
|
||||
let before_submit_elapsed = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
let build_end_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
||||
.then(crate::common::clock::now_micros);
|
||||
let _before_submit_elapsed = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
let before_submit_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
||||
.then(crate::common::clock::now_micros);
|
||||
|
||||
if params.simulate {
|
||||
let send_start = crate::common::sdk_log::sdk_log_enabled().then(Instant::now);
|
||||
@@ -106,14 +110,20 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||
println!(" [SDK] {} timing(sim) build_instructions: {:.2}ms before_submit: {:.2}ms simulate: {:.2}ms total: {:.2}ms", dir, build_elapsed.as_secs_f64() * 1000.0, before_submit_elapsed.as_secs_f64() * 1000.0, send_elapsed.as_secs_f64() * 1000.0, total_elapsed.as_secs_f64() * 1000.0);
|
||||
if let (Some(start_us), Some(end_us)) = (timing_start_us, build_end_us) {
|
||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
if let (Some(start_us), Some(end_us)) = (timing_start_us, before_submit_us) {
|
||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
println!(" [SDK] {} simulate (dry-run): {:.4} ms", dir, send_elapsed.as_secs_f64() * 1000.0);
|
||||
println!(" [SDK] {} total: {:.4} ms", dir, total_elapsed.as_secs_f64() * 1000.0);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
let need_confirm = params.wait_transaction_confirmed;
|
||||
let send_start = params.log_enabled.then(Instant::now);
|
||||
let result = execute_parallel(
|
||||
¶ms.swqos_clients,
|
||||
params.payer,
|
||||
@@ -132,60 +142,72 @@ impl TradeExecutor for GenericTradeExecutor {
|
||||
params.check_min_tip,
|
||||
)
|
||||
.await;
|
||||
let send_elapsed = send_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
|
||||
if params.log_enabled && crate::common::sdk_log::sdk_log_enabled() {
|
||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||
let build_ms = build_elapsed.as_secs_f64() * 1000.0;
|
||||
let before_ms = before_submit_elapsed.as_secs_f64() * 1000.0;
|
||||
let send_ms = send_elapsed.as_secs_f64() * 1000.0;
|
||||
if let Some(start_us) = timing_start_us {
|
||||
let now_us = crate::common::clock::now_micros();
|
||||
let start_to_submit_us = (now_us - start_us).max(0);
|
||||
println!(" [SDK] {} timing(after_submit) build_instructions: {:.2}ms before_submit: {:.2}ms submit: {:.2}ms start_to_submit: {} μs", dir, build_ms, before_ms, send_ms, start_to_submit_us);
|
||||
} else {
|
||||
println!(" [SDK] {} timing(after_submit) build_instructions: {:.2}ms before_submit: {:.2}ms submit: {:.2}ms", dir, build_ms, before_ms, send_ms);
|
||||
}
|
||||
}
|
||||
let log_enabled = params.log_enabled && crate::common::sdk_log::sdk_log_enabled();
|
||||
|
||||
let (ok, signatures, err, submit_timings) = match result {
|
||||
Ok((success, sigs, last_error, timings)) => (
|
||||
success,
|
||||
sigs,
|
||||
last_error.map(|e| anyhow::anyhow!("{}", e)),
|
||||
timings,
|
||||
),
|
||||
Err(e) => (false, vec![], Some(anyhow::anyhow!("{}", e)), vec![]),
|
||||
};
|
||||
let submit_timings_ref: &[(crate::swqos::SwqosType, i64)] = submit_timings.as_slice();
|
||||
|
||||
let result = if need_confirm {
|
||||
let (ok, sigs, err) = match &result {
|
||||
Ok((success, signatures, last_error)) => (
|
||||
*success,
|
||||
signatures.clone(),
|
||||
last_error.as_ref().map(|e| anyhow::anyhow!("{}", e)),
|
||||
),
|
||||
Err(e) => (false, vec![], Some(anyhow::anyhow!("{}", e))),
|
||||
};
|
||||
let confirm_result = if let Some(rpc) = params.rpc.as_ref() {
|
||||
if sigs.is_empty() {
|
||||
(ok, sigs, err)
|
||||
if signatures.is_empty() {
|
||||
(ok, signatures, err)
|
||||
} else {
|
||||
let confirm_start = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled()).then(Instant::now);
|
||||
let poll_res = poll_any_transaction_confirmation(rpc, &sigs, true).await;
|
||||
let confirm_elapsed = confirm_start.map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||
if params.log_enabled && crate::common::sdk_log::sdk_log_enabled() {
|
||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||
let confirm_ms = confirm_elapsed.as_secs_f64() * 1000.0;
|
||||
let total_ms = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO).as_secs_f64() * 1000.0;
|
||||
println!(" [SDK] {} timing(after_confirm) confirm: {:.2}ms total: {:.2}ms", dir, confirm_ms, total_ms);
|
||||
}
|
||||
match poll_res {
|
||||
Ok(_) => (true, sigs, None),
|
||||
Err(e) => (false, sigs, Some(e)),
|
||||
}
|
||||
let poll_res = poll_any_transaction_confirmation(rpc, &signatures, true).await;
|
||||
let confirm_done_us = log_enabled.then(crate::common::clock::now_micros);
|
||||
if log_enabled {
|
||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||
if let Some(start_us) = timing_start_us {
|
||||
if let Some(end_us) = build_end_us {
|
||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
if let Some(end_us) = before_submit_us {
|
||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
if let Some(confirm_us) = confirm_done_us {
|
||||
let total_ms = (confirm_us - start_us) as f64 / 1000.0;
|
||||
for (swqos_type, submit_done_us) in submit_timings_ref {
|
||||
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||
let confirmed_ms = (confirm_us - *submit_done_us).max(0) as f64 / 1000.0;
|
||||
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms", dir, swqos_type, submit_ms, confirmed_ms, total_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
match poll_res {
|
||||
Ok(_) => (true, signatures, None),
|
||||
Err(e) => (false, signatures, Some(e)),
|
||||
}
|
||||
}
|
||||
} else {
|
||||
(ok, sigs, err)
|
||||
(ok, signatures, err)
|
||||
};
|
||||
Ok(confirm_result)
|
||||
} else {
|
||||
if params.log_enabled && crate::common::sdk_log::sdk_log_enabled() {
|
||||
let total_ms = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO).as_secs_f64() * 1000.0;
|
||||
if log_enabled {
|
||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||
println!(" [SDK] {} timing total: {:.2}ms", dir, total_ms);
|
||||
if let Some(start_us) = timing_start_us {
|
||||
if let Some(end_us) = build_end_us {
|
||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
if let Some(end_us) = before_submit_us {
|
||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
||||
}
|
||||
for (swqos_type, submit_done_us) in submit_timings_ref {
|
||||
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms", dir, swqos_type, submit_ms, submit_ms);
|
||||
}
|
||||
}
|
||||
}
|
||||
result
|
||||
Ok((ok, signatures, err))
|
||||
};
|
||||
|
||||
result
|
||||
@@ -232,22 +254,21 @@ async fn simulate_transaction(
|
||||
let unit_limit = default_config.2.cu_limit;
|
||||
let unit_price = default_config.2.cu_price;
|
||||
|
||||
// Build transaction for simulation
|
||||
let transaction = build_transaction(
|
||||
payer.clone(),
|
||||
Some(rpc.clone()),
|
||||
&payer,
|
||||
Some(&rpc),
|
||||
unit_limit,
|
||||
unit_price,
|
||||
&instructions,
|
||||
address_lookup_table_account,
|
||||
address_lookup_table_account.as_ref(),
|
||||
recent_blockhash,
|
||||
middleware_manager,
|
||||
middleware_manager.as_ref(),
|
||||
protocol_name,
|
||||
is_buy,
|
||||
false, // simulate doesn't need tip instruction
|
||||
false,
|
||||
&Pubkey::default(),
|
||||
tip,
|
||||
durable_nonce,
|
||||
durable_nonce.as_ref(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
@@ -304,3 +325,49 @@ async fn simulate_transaction(
|
||||
|
||||
Ok((true, vec![signature], None))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use crate::swqos::SwqosType;
|
||||
|
||||
/// 运行 `cargo test -p sol-trade-sdk log_timing_preview -- --nocapture` 查看日志打印效果
|
||||
#[test]
|
||||
fn log_timing_preview() {
|
||||
let dir = "Buy";
|
||||
let build_ms = 12.34;
|
||||
let before_submit_ms = 15.67;
|
||||
println!("\n--- 1. 构建指令耗时 / 提交前耗时(各打印一次,统一 ms,保留 4 位小数)---\n");
|
||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, build_ms);
|
||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, before_submit_ms);
|
||||
|
||||
println!("\n--- 2. 每个 SWQOS 独立耗时:submit=起点→该通道返回, confirmed=该通道提交→链上确认, total=起点→链上确认 ---\n");
|
||||
for (swqos_type, submit_ms, confirmed_ms, total_ms) in [
|
||||
(SwqosType::Jito, 45.12, 83.38, 128.50),
|
||||
(SwqosType::Helius, 52.30, 76.20, 128.50),
|
||||
(SwqosType::ZeroSlot, 48.90, 79.60, 128.50),
|
||||
] {
|
||||
println!(
|
||||
" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms",
|
||||
dir, swqos_type, submit_ms, confirmed_ms, total_ms
|
||||
);
|
||||
}
|
||||
|
||||
println!("\n--- 3. 不等待链上确认时:每行 total = 该通道 submit 耗时(独立)---\n");
|
||||
for (swqos_type, submit_ms, total_ms) in [
|
||||
(SwqosType::Jito, 44.20, 44.20),
|
||||
(SwqosType::Helius, 51.80, 51.80),
|
||||
] {
|
||||
println!(
|
||||
" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms",
|
||||
dir, swqos_type, submit_ms, total_ms
|
||||
);
|
||||
}
|
||||
|
||||
println!("\n--- 4. Simulate 模式(build/before_submit 仍从 grpc_recv_us 起算)---\n");
|
||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, build_ms);
|
||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, before_submit_ms);
|
||||
println!(" [SDK] {} simulate (dry-run): {:.4} ms", dir, 8.50);
|
||||
println!(" [SDK] {} total: {:.4} ms", dir, 36.51);
|
||||
println!();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -89,11 +89,18 @@ impl std::fmt::Debug for SwapParams {
|
||||
}
|
||||
|
||||
/// PumpFun protocol specific parameters
|
||||
/// Configuration parameters specific to PumpFun trading protocol
|
||||
/// Configuration parameters specific to PumpFun trading protocol.
|
||||
///
|
||||
/// **Creator Rewards Sharing**: Some coins use a dynamic `creator_vault` (fee-sharing config).
|
||||
/// Always use the latest on-chain creator/vault when building params for **sell**; do not reuse
|
||||
/// cached params from buy. Either fetch fresh data via RPC, or pass `creator_vault` from gRPC
|
||||
/// using [`from_trade`](PumpFunParams::from_trade) / [`from_dev_trade`](PumpFunParams::from_dev_trade),
|
||||
/// or override with [`with_creator_vault`](PumpFunParams::with_creator_vault).
|
||||
#[derive(Clone)]
|
||||
pub struct PumpFunParams {
|
||||
pub bonding_curve: Arc<BondingCurveAccount>,
|
||||
pub associated_bonding_curve: Pubkey,
|
||||
/// Creator vault PDA. For Creator Rewards Sharing coins this can change; pass latest from gRPC when selling.
|
||||
pub creator_vault: Pubkey,
|
||||
pub token_program: Pubkey,
|
||||
/// Whether to close token account when selling, only effective during sell operations
|
||||
@@ -222,6 +229,14 @@ impl PumpFunParams {
|
||||
token_program: mint_account.owner,
|
||||
})
|
||||
}
|
||||
|
||||
/// Override `creator_vault` with a value from gRPC/event (e.g. for Creator Rewards Sharing).
|
||||
/// Use when selling so the instruction uses the latest on-chain vault and avoids "seeds constraint violated" (2006).
|
||||
#[inline]
|
||||
pub fn with_creator_vault(mut self, creator_vault: Pubkey) -> Self {
|
||||
self.creator_vault = creator_vault;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// PumpSwap Protocol Specific Parameters
|
||||
@@ -383,7 +398,7 @@ impl PumpSwapParams {
|
||||
);
|
||||
|
||||
Ok(Self {
|
||||
pool: pool_address.clone(),
|
||||
pool: *pool_address,
|
||||
base_mint: pool_data.base_mint,
|
||||
quote_mint: pool_data.quote_mint,
|
||||
pool_base_token_account: pool_data.pool_base_token_account,
|
||||
@@ -656,7 +671,7 @@ impl RaydiumCpmmParams {
|
||||
)
|
||||
.await?;
|
||||
Ok(Self {
|
||||
pool_state: pool_address.clone(),
|
||||
pool_state: *pool_address,
|
||||
amm_config: pool.amm_config,
|
||||
base_mint: pool.token0_mint,
|
||||
quote_mint: pool.token1_mint,
|
||||
@@ -763,7 +778,7 @@ impl MeteoraDammV2Params {
|
||||
let pool_data =
|
||||
crate::instruction::utils::meteora_damm_v2::fetch_pool(rpc, pool_address).await?;
|
||||
Ok(Self {
|
||||
pool: pool_address.clone(),
|
||||
pool: *pool_address,
|
||||
token_a_vault: pool_data.token_a_vault,
|
||||
token_b_vault: pool_data.token_b_vault,
|
||||
token_a_mint: pool_data.token_a_mint,
|
||||
|
||||
@@ -6,6 +6,15 @@
|
||||
//! - 零拷贝 I/O
|
||||
//! - 内存预热
|
||||
|
||||
/// 预分配指令容量(单笔交易常见指令数)
|
||||
const TX_BUILDER_INSTRUCTION_CAP: usize = 32;
|
||||
/// 预分配地址查找表数量
|
||||
const TX_BUILDER_LOOKUP_TABLE_CAP: usize = 8;
|
||||
/// 对象池最大容量
|
||||
const TX_BUILDER_POOL_CAP: usize = 1000;
|
||||
/// 启动时预填充对象池数量
|
||||
const TX_BUILDER_POOL_PREFILL: usize = 100;
|
||||
|
||||
use crossbeam_queue::ArrayQueue;
|
||||
use once_cell::sync::Lazy;
|
||||
use solana_sdk::{
|
||||
@@ -23,8 +32,8 @@ pub struct PreallocatedTxBuilder {
|
||||
impl PreallocatedTxBuilder {
|
||||
fn new() -> Self {
|
||||
Self {
|
||||
instructions: Vec::with_capacity(32), // 预分配32条指令空间
|
||||
lookup_tables: Vec::with_capacity(8), // 预分配8个查找表空间
|
||||
instructions: Vec::with_capacity(TX_BUILDER_INSTRUCTION_CAP),
|
||||
lookup_tables: Vec::with_capacity(TX_BUILDER_LOOKUP_TABLE_CAP),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -65,23 +74,20 @@ impl PreallocatedTxBuilder {
|
||||
&mut self,
|
||||
payer: &Pubkey,
|
||||
instructions: &[Instruction],
|
||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
address_lookup_table_account: Option<&AddressLookupTableAccount>,
|
||||
recent_blockhash: Hash,
|
||||
) -> VersionedMessage {
|
||||
// 重用已分配的 vector
|
||||
self.reset();
|
||||
self.instructions.extend_from_slice(instructions);
|
||||
|
||||
// ✅ 如果有查找表,使用 V0 消息
|
||||
if let Some(address_lookup_table_account) = address_lookup_table_account {
|
||||
let message = v0::Message::try_compile(
|
||||
if let Some(alt) = address_lookup_table_account {
|
||||
let message = v0::Message::try_compile(
|
||||
payer,
|
||||
&self.instructions,
|
||||
&[address_lookup_table_account],
|
||||
std::slice::from_ref(alt),
|
||||
recent_blockhash,
|
||||
).expect("v0 message compile failed");
|
||||
|
||||
|
||||
)
|
||||
.expect("v0 message compile failed");
|
||||
VersionedMessage::V0(message)
|
||||
} else {
|
||||
// ✅ 没有查找表,使用 Legacy 消息(兼容所有 RPC)
|
||||
@@ -97,10 +103,9 @@ impl PreallocatedTxBuilder {
|
||||
|
||||
/// 🚀 全局交易构建器对象池
|
||||
static TX_BUILDER_POOL: Lazy<Arc<ArrayQueue<PreallocatedTxBuilder>>> = Lazy::new(|| {
|
||||
let pool = ArrayQueue::new(1000); // 1000个预分配构建器
|
||||
let pool = ArrayQueue::new(TX_BUILDER_POOL_CAP);
|
||||
|
||||
// 预填充池
|
||||
for _ in 0..100 {
|
||||
for _ in 0..TX_BUILDER_POOL_PREFILL {
|
||||
let _ = pool.push(PreallocatedTxBuilder::new());
|
||||
}
|
||||
|
||||
|
||||
@@ -14,7 +14,7 @@ impl InstructionMiddleware for LoggingMiddleware {
|
||||
fn process_protocol_instructions(
|
||||
&self,
|
||||
protocol_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
println!("-------------------[{}]-------------------", self.name());
|
||||
@@ -32,7 +32,7 @@ impl InstructionMiddleware for LoggingMiddleware {
|
||||
fn process_full_instructions(
|
||||
&self,
|
||||
full_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
println!("-------------------[{}]-------------------", self.name());
|
||||
|
||||
@@ -20,7 +20,7 @@ pub trait InstructionMiddleware: Send + Sync {
|
||||
fn process_protocol_instructions(
|
||||
&self,
|
||||
protocol_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>>;
|
||||
|
||||
@@ -36,7 +36,7 @@ pub trait InstructionMiddleware: Send + Sync {
|
||||
fn process_full_instructions(
|
||||
&self,
|
||||
full_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>>;
|
||||
|
||||
@@ -72,13 +72,13 @@ impl MiddlewareManager {
|
||||
pub fn apply_middlewares_process_full_instructions(
|
||||
&self,
|
||||
mut full_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
for middleware in &self.middlewares {
|
||||
full_instructions = middleware.process_full_instructions(
|
||||
full_instructions,
|
||||
protocol_name.clone(),
|
||||
protocol_name,
|
||||
is_buy,
|
||||
)?;
|
||||
if full_instructions.is_empty() {
|
||||
@@ -92,13 +92,13 @@ impl MiddlewareManager {
|
||||
pub fn apply_middlewares_process_protocol_instructions(
|
||||
&self,
|
||||
mut protocol_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
protocol_name: &str,
|
||||
is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
for middleware in &self.middlewares {
|
||||
protocol_instructions = middleware.process_protocol_instructions(
|
||||
protocol_instructions,
|
||||
protocol_name.clone(),
|
||||
protocol_name,
|
||||
is_buy,
|
||||
)?;
|
||||
if protocol_instructions.is_empty() {
|
||||
|
||||
@@ -31,6 +31,23 @@ impl TradingClient {
|
||||
trading::common::utils::get_token_balance(&self.infrastructure.rpc, &self.payer.pubkey(), mint).await
|
||||
}
|
||||
|
||||
/// 使用与交易一致的 ATA 推导(含 seed 优化)查询 payer 某 mint 的余额;卖出前查余额应使用此接口并传入池的 base_token_program,否则若使用 seed ATA 会查错账户。
|
||||
#[inline]
|
||||
pub async fn get_payer_token_balance_with_program(
|
||||
&self,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
) -> Result<u64, anyhow::Error> {
|
||||
trading::common::utils::get_token_balance_with_options(
|
||||
&self.infrastructure.rpc,
|
||||
&self.payer.pubkey(),
|
||||
mint,
|
||||
token_program,
|
||||
self.use_seed_optimize,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_payer_pubkey(&self) -> Pubkey {
|
||||
self.payer.pubkey()
|
||||
|
||||
Reference in New Issue
Block a user