Compare commits

...

18 Commits

Author SHA1 Message Date
0xfnzero f6db55c874 release: update Pump program metadata for v4.0.8 2026-05-15 01:08:33 +08:00
0xfnzero 69b4f9bb9f docs: add donation wallet address to README_CN 2026-05-14 19:26:31 +08:00
0xfnzero 532bc1195d docs: add donation wallet address to README 2026-05-14 19:24:53 +08:00
0xfnzero 8944c5455c Refine crate description wording 2026-05-14 00:25:44 +08:00
0xfnzero 0d846930ad fix(pumpswap): use live global fee recipients 2026-05-13 21:16:17 +08:00
0xfnzero 703ae5e4db fix(pumpfun): preserve observed fee recipient 2026-05-12 05:55:45 +08:00
0xfnzero 8e0210af97 fix(swqos): replace non-portable try_from_base58_string with bs58 decode + TryFrom
The patched solana-keypair in the main workspace adds try_from_base58_string,
but sol-safekey and other consumers use the standard crates.io version which
only provides from_base58_string (panics) and TryFrom<&[u8]> (fallible).

Use bs58::decode + Keypair::try_from to keep proper error handling while
remaining compatible with the standard solana-keypair crate.
2026-05-09 15:02:25 +08:00
0xfnzero e605485ecf fix(bonding-curve): tolerate extra trailing bytes in account data
BondingCurveAccount::try_from_slice requires the entire input slice to
be consumed, which fails with "Not all bytes read" when the on-chain
bonding curve account has been extended with new fields (e.g. after a
protocol upgrade). Switch to BorshDeserialize::deserialize which reads
the known fields and silently ignores any trailing bytes.
2026-05-09 14:46:52 +08:00
0xfnzero 8dec2f8d8c fix(sell): trust observed creator_vault directly to prevent Anchor 2006
In build_sell_v1/v2, the creator_vault was previously derived via
effective_creator_for_trade() passed to resolve_creator_vault_for_ix_with_fee_sharing.
When observed_trade_creator differs from bonding_curve.creator (e.g. creator
updated post-deployment), the derived vault PDA mismatches the on-chain
seeds constraint, causing Anchor error 2006 (ConstraintSeeds) on sell.

The pump.fun sell instruction validates creator_vault seeds as
PDA("creator-vault", bonding_curve.creator), but buy does not check seeds,
so buy succeeds while sell fails with 2006.

Fix: when protocol_params.creator_vault is a valid non-default/non-phantom
value (observed from gRPC / update_fee_shares), use it directly without
re-derivation. Only fall back to resolve via bonding_curve.creator when
creator_vault is missing. This ensures the authoritative observed vault
is never overridden by a stale or mismatched creator.
2026-05-09 14:41:22 +08:00
0xfnzero b505bebdac fix(pumpfun): use is_cashback_coin instead of is_mayhem_mode for sell user_volume_accumulator
The Pump.fun IDL explicitly states that user_volume_accumulator is
passed as remaining_accounts[0] for cashback coins during sell.
Using is_mayhem_mode incorrectly omitted the account for cashback
tokens, causing the program to misread bonding_curve_v2 as
user_volume_accumulator and resulting in Custom(6024) Overflow.
2026-05-09 08:18:58 +08:00
0xfnzero 1cc051a874 feat(pumpfun): runtime V2 flag, buyback fee pool fix, legacy ix encoding
- Replace compile-time `pumpfun-v2` feature flag with runtime
  `TradeConfig::use_pumpfun_v2(bool)` for flexible V1/V2 switching
- Fix BUYBACK_FEE_RECIPIENTS pool: replace wrong addresses (was reusing
  standard pool + FEE_CONFIG) with official buyback pool from
  FEE_RECIPIENTS.md
- Fix legacy buy/buy_exact_sol_in ix data encoding: use 2-byte
  Option<bool> (option tag + value) matching official Pump SDK, 26 bytes
  total instead of broken 25
- Add `SwapParams.use_pumpfun_v2` field and wire through TradingClient
  buy/sell paths
- V2 instructions read `quote_mint` from `PumpFunParams` (not
  BondingCurveAccount which lacks the field)
- Fix `fetch_bonding_curve_account` to use BorshDeserialize instead of
  non-existent `decode_from_chain_account_data`
- Update all examples with `use_pumpfun_v2: false` field
- Update README with unified V1/V2 section showing both enabling methods
2026-05-09 07:15:07 +08:00
0xfnzero 0311a0b876 docs(readme): update SWQoS partner list to Jito, Temporal, FlashBlock, BlockRazor, Astralane, SpeedLanding
Remove non-partner services (Nextblock, ZeroSlot, Bloxroute, Node1).
Update code examples to use partner service configs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-09 00:05:53 +08:00
0xfnzero b49c1c803e fix(pump): restore 26-byte legacy buy instruction data encoding
The refactored ix data encoder was producing 25-byte buy instructions
(1-byte track_volume), but the on-chain Pump program expects Anchor's
2-byte Option<bool> encoding (option tag + value), totaling 26 bytes.
The 1-byte shortfall caused instruction data under-read that manifested
as error 0xbbf (ConstraintOwner) for all legacy buy/buy_exact_sol_in.

Restore the 2-byte encoding: option tag (1u8) followed by the cashback
flag as the bool value, matching the pre-refactoring inline encoder.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 23:37:07 +08:00
0xfnzero ce8fb99626 Revert "fix(pump): default token program to legacy SPL Token instead of Token-2022"
This reverts commit 49843d8a20.
2026-05-08 23:28:21 +08:00
0xfnzero 49843d8a20 fix(pump): default token program to legacy SPL Token instead of Token-2022
The `effective_pump_mint_token_program` helper was defaulting to
TOKEN_PROGRAM_2022 when `token_program` was Pubkey::default(), causing
Anchor error 0xbbf (account owned by wrong program) for all legacy
PumpFun coins whose ATAs are owned by the original Token Program.

Fall back to TOKEN_PROGRAM (legacy) when no explicit token program is
provided. Token-2022 must be set explicitly for create_v2 coins.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 23:23:39 +08:00
0xfnzero 60d1db4755 feat(pump): add buy_v2, sell_v2, buy_exact_quote_in_v2 instruction builders
Support Pump.fun Bonding Curve v2 unified trading interface with quote_mint
parameter for SOL-paired (WSOL) and USDC-paired coins.

- Add BUY_V2, SELL_V2, BUY_EXACT_QUOTE_IN_V2 discriminators
- Implement 27/26-account v2 instruction layouts matching official IDL
- Add PumpFunParams::quote_mint and use_v2_ix fields (default legacy)
- Add with_quote_mint() builder, buyback fee recipient pool, and PDA helpers
- Add v2 ix data encoders in pumpfun_ix_data.rs
- Legacy instructions remain default for backward compatibility

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-08 20:48:11 +08:00
0xfnzero 7a8d2a9c17 docs(readme): bump crates.io examples to v4.0.7
Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 00:40:09 +08:00
0xfnzero 75bfbf6d54 fix(pumpfun): trust explicit ix creator_vault over creator-derived PDA
- resolve_creator_vault_for_ix_with_fee_sharing uses non-placeholder ix vault as-is.
- When ix vault missing, fall back to fee_sharing_creator_vault_if_active then PDA(creator).
- Add Pump troubleshooting CN doc; extend PumpFunParams field documentation.
- Bump to v4.0.7.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-05-06 00:25:54 +08:00
64 changed files with 6245 additions and 4087 deletions
+2 -2
View File
@@ -1,6 +1,6 @@
[package]
name = "sol-trade-sdk"
version = "4.0.6"
version = "4.0.8"
edition = "2021"
authors = [
"William <byteblock6@gmail.com>",
@@ -8,7 +8,7 @@ authors = [
"wei <1415121722@qq.com>",
]
repository = "https://github.com/0xfnzero/sol-trade-sdk"
description = "Rust SDK to interact with the dex trade Solana program."
description = "A high-performance Rust SDK for Solana DEX trading."
license = "MIT"
keywords = ["solana", "memecoins", "pumpfun", "pumpswap", "raydium"]
readme = "README.md"
+69 -16
View File
@@ -39,6 +39,12 @@
<a href="https://discord.gg/vuazbGkqQE">Discord</a>
</p>
> ☕ **Support This Project**
>
> This SDK is completely free and open source. However, maintaining and continuously updating it requires significant AI computing resources and token consumption. If this SDK helps with your trading development, consider making a monthly SOL donation — any amount is appreciated and helps keep this project alive!
>
> **Donation Wallet:** `6oW7AXz1yRb57pYSxysuXnMs2aR1ha5rzGzReZ1MjPV8`
## 📋 Table of Contents
- [✨ Features](#-features)
@@ -53,6 +59,7 @@
- [🔍 Address Lookup Tables](#-address-lookup-tables)
- [🔍 Nonce Cache](#-nonce-cache)
- [💰 Cashback Support (PumpFun / PumpSwap)](#-cashback-support-pumpfun--pumpswap)
- [🔄 PumpFun V1 vs V2 Instructions](#-pumpfun-v1-vs-v2-instructions)
- [🛡️ MEV Protection Services](#-mev-protection-services)
- [📁 Project Structure](#-project-structure)
- [📄 License](#-license)
@@ -74,7 +81,7 @@ This SDK is available in multiple languages:
## ✨ Features
1. **PumpFun Trading**: Support for `buy` and `sell` operations
1. **PumpFun Trading**: Support for `buy`, `sell`, `buy_exact_sol_in`, and the new unified `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2` instructions (SOL + USDC)
2. **PumpSwap Trading**: Support for PumpSwap pool trading operations
3. **Bonk Trading**: Support for Bonk trading operations
4. **Raydium CPMM Trading**: Support for Raydium CPMM (Concentrated Pool Market Maker) trading operations
@@ -101,14 +108,14 @@ Add the dependency to your `Cargo.toml`:
```toml
# Add to your Cargo.toml
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.3" }
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.8" }
```
### Use crates.io
```toml
# Add to your Cargo.toml
sol-trade-sdk = "4.0.3"
sol-trade-sdk = "4.0.8"
```
## 🛠️ Usage Examples
@@ -130,15 +137,12 @@ let commitment = CommitmentConfig::processed();
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),
SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::FlashBlock("your api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::BlockRazor("your api_token".to_string(), SwqosRegion::Frankfurt, None),
// Astralane: 4th param = AstralaneTransport — Binary (default), Plain (/iris), or Quic
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // Binary HTTP /irisb
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt,
None,
Some(AstralaneTransport::Quic),
), // QUIC
SwqosConfig::SpeedLanding("your api_token".to_string(), SwqosRegion::Frankfurt, None),
];
// Create TradeConfig instance
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
@@ -148,6 +152,7 @@ let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
// .check_min_tip(false) // default: false - filter SWQOS below min tip
// .swqos_cores_from_end(false) // default: false - bind SWQOS to last N CPU cores
// .mev_protection(false) // default: false - MEV (Astralane QUIC :9000 or HTTP mev-protect / BlockRazor)
// .use_pumpfun_v2(false) // default: false - V1 (18 accounts); set true for V2 (27 accounts, quote_mint) when PumpFun deploys V2
.build();
// Create TradingClient
@@ -266,7 +271,7 @@ let jito_config = SwqosConfig::Jito(
);
// Using default regional endpoint (third parameter is None)
let bloxroute_config = SwqosConfig::Bloxroute(
let temporal_config = SwqosConfig::Temporal(
"your_api_token".to_string(),
SwqosRegion::NewYork, // Will use the default endpoint for this region
None // No custom URL, uses SwqosRegion
@@ -335,6 +340,10 @@ 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: troubleshooting (on-chain errors)
For **Anchor 2006 / `NotAuthorized` (6000) / wrong token program / BuyZeroAmount (6020) / slippage (6042)** and related issues, see **[docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md](docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md)** (Chinese). An English appendix may be added later.
#### 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:
@@ -346,25 +355,69 @@ Some PumpFun coins use **Creator Rewards Sharing**, so the on-chain `creator_vau
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.
#### PumpFun V1 vs V2 Instructions
PumpFun has two instruction sets for bonding-curve trading:
| | V1 (default) | V2 (opt-in) |
|---|---|---|
| Instructions | `buy` / `buy_exact_sol_in` / `sell` | `buy_v2` / `buy_exact_quote_in_v2` / `sell_v2` |
| Account metas | 18 | 27 |
| Quote mint | SOL only (legacy) | SOL or USDC (via `quote_mint` field) |
| Transaction size | Smaller (fits `PACKET_DATA_SIZE` without LUT) | Larger (requires LUT for most transactions) |
**Default: V1** (`use_pumpfun_v2 = false`). The SDK uses V1 instructions which produce smaller transactions that fit within the 1232-byte `PACKET_DATA_SIZE` limit without requiring an Address Lookup Table.
**Key changes in v2 instructions:**
- `quote_mint` parameter — pass wrapped SOL for SOL-paired, or USDC mint for USDC-paired
- 27 fixed accounts (buy) / 26 fixed accounts (sell) — **no optional accounts**
- `buyback_fee_recipient`, `sharing_config`, and 6 `associated_quote_*` ATAs are now mandatory
- Same pricing and cost as legacy instructions for SOL-paired coins
**How to enable V2:**
**Method 1 — Global runtime flag** (recommended when PumpFun officially deploys V2 on mainnet):
```rust
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
.use_pumpfun_v2(true) // Switch all PumpFun trades to V2 instructions (27 accounts)
.build();
```
**Method 2 — Per-trade via `quote_mint`** (for USDC-paired coins or mixed V1/V2 scenarios):
```rust
use sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
use sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT;
// SOL-paired coin with v2 layout
let params = PumpFunParams::from_trade(/* ... */)
.with_quote_mint(WSOL_TOKEN_ACCOUNT);
// USDC-paired coin (requires v2)
let params = PumpFunParams::from_trade(/* ... */)
.with_quote_mint(USDC_TOKEN_ACCOUNT);
```
> **Note**: V2 transactions with ATA creation + durable nonce may exceed `PACKET_DATA_SIZE`. Enable an Address Lookup Table (`address_lookup_table_account`) when using V2.
#### PumpSwap: coin_creator_vault from events (no RPC)
For **PumpSwap** (Pump AMM), `coin_creator_vault_ata` and `coin_creator_vault_authority` are required in buy/sell instructions. Both are available from parsed events without RPC:
- **sol-parser-sdk**: Instruction parser sets them from accounts 17 and 18; the account filler also fills them when the event comes from logs. Use `PumpSwapParams::from_trade(..., e.coin_creator_vault_ata, e.coin_creator_vault_authority, ...)` with the buy/sell event `e`.
- **solana-streamer**: Instruction parser sets them from `accounts.get(17)` and `accounts.get(18)`. Use the same `from_trade` with the events `coin_creator_vault_ata` and `coin_creator_vault_authority`.
- **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)
- **Jito**: High-performance block space
- **ZeroSlot**: Zero-latency transactions
- **Temporal**: Time-sensitive transactions
- **Bloxroute**: Blockchain network acceleration
- **FlashBlock**: High-speed transaction execution with API key authentication
- **BlockRazor**: High-speed transaction execution with API key authentication
- **Node1**: High-speed transaction execution with API key authentication
- **Astralane**: Blockchain network acceleration (Binary/Plain HTTP and QUIC; see [Astralane](#astralane-binary--plain--quic) above)
- **Astralane**: Blockchain network acceleration (Binary/Plain HTTP and QUIC)
- **SpeedLanding**: High-speed transaction execution with API key authentication
## 📁 Project Structure
+59 -16
View File
@@ -39,6 +39,12 @@
<a href="https://discord.gg/vuazbGkqQE">Discord</a>
</p>
> ☕ **支持本项目**
>
> 本 SDK 完全免费且开源。但维护和持续更新需要消耗大量 AI 算力与 Token。如果这个 SDK 对您的开发有帮助,欢迎每月捐赠任意数量的 SOL,您的支持将帮助这个项目持续运行!
>
> **捐赠钱包:** `6oW7AXz1yRb57pYSxysuXnMs2aR1ha5rzGzReZ1MjPV8`
## 📋 目录
- [✨ 项目特性](#-项目特性)
@@ -53,6 +59,7 @@
- [🔍 地址查找表](#-地址查找表)
- [🔍 Nonce 缓存](#-nonce-缓存)
- [💰 Cashback 支持(PumpFun / PumpSwap](#-cashback-支持pumpfun--pumpswap)
- [Pump.fun 常见链上错误与排错(文档)](docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md)
- [🛡️ MEV 保护服务](#-mev-保护服务)
- [📁 项目结构](#-项目结构)
- [📄 许可证](#-许可证)
@@ -74,13 +81,13 @@
## ✨ 项目特性
1. **PumpFun 交易**: 支持`购买``卖出`功能
1. **PumpFun 交易**: 支持 `buy``sell``buy_exact_sol_in` 以及全新的统一化 `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2` 指令(SOL + USDC
2. **PumpSwap 交易**: 支持 PumpSwap 池的交易操作
3. **Bonk 交易**: 支持 Bonk 的交易操作
4. **Raydium CPMM 交易**: 支持 Raydium CPMM (Concentrated Pool Market Maker) 的交易操作
5. **Raydium AMM V4 交易**: 支持 Raydium AMM V4 (Automated Market Maker) 的交易操作
6. **Meteora DAMM V2 交易**: 支持 Meteora DAMM V2 (Dynamic AMM) 的交易操作
7. **多种 MEV 保护**: 支持 Jito、Nextblock、ZeroSlot、Temporal、Bloxroute、FlashBlock、BlockRazor、Node1、Astralane 等服务
7. **多种 MEV 保护**: 支持 Jito、Temporal、FlashBlock、BlockRazor、Astralane、SpeedLanding 等服务
8. **并发交易**: 同时使用多个 MEV 服务发送交易,最快的成功,其他失败
9. **统一交易接口**: 使用统一的交易协议枚举进行交易操作
10. **中间件系统**: 支持自定义指令中间件,可在交易执行前对指令进行修改、添加或移除
@@ -101,14 +108,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
```toml
# 添加到您的 Cargo.toml
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.3" }
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.8" }
```
### 使用 crates.io
```toml
# 添加到您的 Cargo.toml
sol-trade-sdk = "4.0.3"
sol-trade-sdk = "4.0.8"
```
## 🛠️ 使用示例
@@ -130,15 +137,12 @@ let commitment = CommitmentConfig::processed();
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),
SwqosConfig::Temporal("your api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::FlashBlock("your api_token".to_string(), SwqosRegion::Frankfurt, None),
SwqosConfig::BlockRazor("your api_token".to_string(), SwqosRegion::Frankfurt, None),
// Astralane:第4个参数为 AstralaneTransport — Binary(默认)、Plain/iris)或 Quic
SwqosConfig::Astralane("your_astralane_api_key".to_string(), SwqosRegion::Frankfurt, None, None), // Binary /irisb
SwqosConfig::Astralane(
"your_astralane_api_key".to_string(),
SwqosRegion::Frankfurt,
None,
Some(AstralaneTransport::Quic),
), // QUIC
SwqosConfig::SpeedLanding("your api_token".to_string(), SwqosRegion::Frankfurt, None),
];
// 创建 TradeConfig 实例
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
@@ -265,7 +269,7 @@ let jito_config = SwqosConfig::Jito(
);
// 使用默认区域端点(第三个参数为 None)
let bloxroute_config = SwqosConfig::Bloxroute(
let temporal_config = SwqosConfig::Temporal(
"your_api_token".to_string(),
SwqosRegion::NewYork, // 将使用该区域的默认端点
None // 没有自定义 URL,使用 SwqosRegion
@@ -334,6 +338,10 @@ 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:常见错误与排错思路
实盘集成时若遇 **Anchor 2006、`NotAuthorized`(6000)、Token program 不匹配、6020/6042** 等,请参阅专门文档:**[Pump.fun 常见链上错误与处理思路(中文)](docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md)**。
#### PumpFunCreator Rewards Sharingcreator_vault
部分 PumpFun 代币启用了 **Creator Rewards Sharing**,链上 `creator_vault` 可能与默认推导结果不同。若在**卖出**时复用**买入**时缓存的 params,可能触发程序错误 **2006seeds constraint violated**。建议:
@@ -352,18 +360,53 @@ SDK 不会在每次卖出时通过 RPC 拉取 creator_vault(以避免延迟)
- **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`
### Pump.fun Bonding Curve v2buy_v2 / sell_v2 / buy_exact_quote_in_v2
Pump.fun 已升级 Bonding Curve 合约,推出**统一化 v2 指令**,通过固定账户布局同时支持 SOL 和 USDC 配对币。旧版 `buy`/`sell`/`buy_exact_sol_in` 仍可用于 SOL 配对币,且保持为默认选项。
**v2 指令关键变化:**
- 新增 `quote_mint` 参数 — SOL 配对传包装 SOL(`So11111111111111111111111111111111111111112`),USDC 配对传 USDC mint
- 27 个固定账户(buy)/ 26 个固定账户(sell)— **无可选账户**
- `buyback_fee_recipient``sharing_config` 和 6 个 `associated_quote_*` ATA 变为强制账户
- SOL 配对币的报价和成本与旧版一致,无额外开销
**使用方式:**
设置 `PumpFunParams``quote_mint` 即可,SDK 会自动切换到 v2 discriminator 和新账户布局:
```rust
use sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
use sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT;
// SOL 配对币 — 传包装 SOL mint
let params = PumpFunParams::from_trade(/* ... */)
.with_quote_mint(WSOL_TOKEN_ACCOUNT);
// USDC 配对币(即将开放 — 必须使用 v2)
let params = PumpFunParams::from_trade(/* ... */)
.with_quote_mint(USDC_TOKEN_ACCOUNT);
// 之后正常交易
client.buy(buy_params).await?;
client.sell(sell_params).await?;
```
| quote_mint | use_v2_ix | 实际使用的指令 | 说明 |
|-----------|-------------|---------|------|
| 未设置(默认) | `false` | 旧版 `buy`/`sell`/`buy_exact_sol_in` | 向后兼容,仅 SOL |
| `WSOL_TOKEN_ACCOUNT` | `true` | `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2` | SOL 配对,统一布局 |
| `USDC_TOKEN_ACCOUNT` | `true` | `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2` | USDC 配对(必须使用 v2 |
## 🛡️ MEV 保护服务
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
- **Jito**: 高性能区块空间
- **ZeroSlot**: 零延迟交易
- **Temporal**: 时间敏感交易
- **Bloxroute**: 区块链网络加速
- **FlashBlock**: 高速交易执行,支持 API 密钥认证
- **BlockRazor**: 高速交易执行,支持 API 密钥认证
- **Node1**: 高速交易执行,支持 API 密钥认证
- **Astralane**: 区块链网络加速(Binary/Plain HTTP 与 QUIC,见 [Astralane](#astralanebinary--plain--quic)
- **Astralane**: 区块链网络加速(Binary/Plain HTTP 与 QUIC
- **SpeedLanding**: 高速交易执行,支持 API 密钥认证
## 📁 项目结构
+208
View File
@@ -0,0 +1,208 @@
# Pump.funBonding Curve)常见链上错误与处理思路
本文档面向使用 **sol-trade-sdk** 组装 Pump.fun Program`6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P`)买卖交易的集成方,汇总**实战中高频**的失败形态、日志特征,以及与 SDK 参数的对应关系和**推荐处理方式**。
> 自定义错误码以仓库内 `idl/pump.json`、`idl/pump_fees.json` 为准;**2006** 等部分错误来自 **Anchor 框架**,不在 Pump 自定义枚举里。
---
## 1. Anchor `2006` / `ConstraintSeeds``creator_vault`
### 现象
- Solana Explorer / `simulateTransaction`**Program Error: custom program error: 2006**,或 Anchor 文案 **A seeds constraint was violated**
- 日志里常见于账户 **`creator_vault`**:打印 **Left**(你传入的 pubkey)与 **Right**(程序按当前 curve 推导的 PDA)。
### 含义
Pump 校验 `creator_vault` 必须满足程序的 **PDAs seeds**(与 bonding curve 上记录的 **creator / fee-sharing 布局**一致)。传入地址与程序期望不一致即失败。
### 常见成因
1. **`bonding_curve.creator` 与链上不符**:事件/缓存里用的是 create 交易的 `creator` 字段、`user`,或陈旧快照,与 curve 账户内真实 creator 不一致;据此推导或缓存的 vault 会错。
2. **买单侧「旧 vault」被沿用到卖单**:买入时 ix 里的 `creator_vault` 在后续 trade 语境下已不再与程序约束一致(例如 creator / sharing 语义在链上演进),卖单仍填旧地址 → **Left ≠ Right**
3. **Creator Rewards / pump-fees 分成布局**:部分 mint 使用 `sharing-config` 相关 seeds,单靠 `PDA(["creator-vault"], bonding_curve.creator)` 不足以覆盖全部历史状态;Stale 的 offline hint 也会把 resolve 引向错误 vault。
4. **Phantom vault**:历史上若用 `Pubkey::default()` 推导出的占位 vault(SDK 常量 `phantom_default_creator_vault`),链上必定失败。
### SDK 侧处理思路
| 方向 | 做法 |
|------|------|
| **买入 / 卖出指令**(同一套解析) | 使用 `resolve_creator_vault_for_ix_with_fee_sharing``src/instruction/utils/pumpfun.rs`):有 **非 default、非 phantom** 的 ix / 解析器回填 **`creator_vault` 时原样采用****不会**再根据 `creator``get_creator_vault_pda` 覆盖费分成等非传统布局);**未传 ix vault** 时依次:`fee_sharing_creator_vault_if_active` hint → `PDA(effective_creator)``PumpFunInstructionBuilder` 买卖均走此逻辑。 |
| **权威对齐** | 低延迟路径外,可 **`PumpFunParams::from_mint_by_rpc`** 或由解析器 **`fill_trade_accounts`**(如 sol-parser-sdk)持续刷新 `creator` / `creator_vault`;必要时对 **fee-sharing** 使用 `fetch_fee_sharing_creator_vault_if_active` / `refresh_fee_sharing_creator_vault_from_rpc`。 |
| **bonding_curve 账户地址** | 指令构建时使用 **`get_bonding_curve_pda(mint)`** 作为 canonical bonding curve pubkey,避免缓存中的曲线地址错位导致读到错误 **creator**。 |
集成方若在 **bot** 侧维护持仓快照,建议在**每笔**解析到的 Pump trade 后刷新缓存/仓位中的 `creator``creator_vault`,避免「只写一次建仓快照」。
---
## 2. Pump `6000` `NotAuthorized`(常见:`feeRecipient`
### 现象
- 日志:`AnchorError thrown in programs/pump/src/fee_recipient.rs`**`Error Code: NotAuthorized`**(与 Global 授权的 fee recipient 池有关)。
### 含义
账户 **#2 fee recipient** 不是当前 Pump **Global / 协议**允许使用的收款地址之一,或与 **Mayhem / 非 Mayhem** 池不一致。
### 常见成因
1. 使用了**过期**或**错误池**的 fee recipient(静态列表落后于主网轮换)。
2. **`mayhem_mode``fee_recipient` 不匹配**:声明 Mayhem 却传普通池地址,或相反(见 `reconcile_mayhem_mode_for_trade``src/instruction/utils/pumpfun.rs`)。
### SDK 侧处理思路
| 方向 | 做法 |
|------|------|
| **优先事件** | 使用 gRPC / 解析器里的 **`tradeEvent.feeRecipient`** 或同笔 **create_v2 + buy** 观测到的 fee recipient。 |
| **纠偏** | `PumpFunParams::from_trade` 会对 `mayhem_mode``fee_recipient` 做池一致性纠偏;发单前若事件缺省,可走 `pump_fun_fee_recipient_meta`(按 `is_mayhem_mode` 从静态池选)。 |
| **提交前保留观测值** | 不要无条件把已观测的 `fee_recipient` 清成 default;否则会退回 SDK 内置静态池,静态池若落后于主网 Global 授权,仍可能触发 6000。只有缺少观测值时才让 builder 兜底。 |
---
## 3. SPLToken **`initializeAccount3`**——`incorrect program id for instruction`
### 现象
- 内联指令里 **`Token Program: initializeAccount3`**(或 Token-2022 等价指令)报错 **`incorrect program id for instruction`**。
### 含义
**Mint** 创建用户 ATA 时,使用的 **token programLegacy SPL vs Token-2022****Mint 的实际 owner`mint.owner`** 不一致。
### 常见成因
1. Pump 新发多为 **Token-2022**,但代码写死 **`Tokenkeg…`**。
2. 少数 Legacy mint`Tokenkeg…`),却被强制按 Token-2022 建账。
### SDK 侧处理思路
- **`PumpFunParams::token_program`** 必须与非 default 的 **mint owner** 一致;从 **gRPC / 解析结果** 带入,**勿**在已明确 program 时再用「仅按 `.pump` 后缀猜 Token-2022」覆盖(业务层若做后缀启发,应仅在 `token_program == default` 时生效)。
---
## 4. Pump `6020` `BuyZeroAmount`
### 现象
- `buy` / `buy_exact_sol_in`**Buy zero amount**
### 常见成因
- `min_tokens_out == 0`(或等价路径算出可买 **0 枚**),协议直接拒绝。
- 使用 **Create / Shred** 事件构造曲线时 **virtual / real 储备全 0**,本地定价算出 **0**
### SDK 侧处理思路
- 对「首买 / 无储备」场景用 **`PumpFunParams::from_dev_trade`** 或按协议初值回填虚拟储备(与 `global_constants` 一致),再算 **`min_tokens_out`**。
- 适当 **放宽买入滑点**`slippage_basis_points`),避免估算代币量略小于链上。
---
## 5. Pump `6042` `BuySlippageBelowMinTokensOut`
### 现象
- 文案:**Slippage: Would buy less tokens than expected min_tokens_out**。
### 含义
链上实际可成交代币数量 **小于** 指令参数 **`min_tokens_out`**。
### 常见成因
- 市价波动、SOL 竞价导致曲线状态与本地快照不一致。
- 本地 **`get_buy_token_amount_from_sol_amount`** 所用 **creator / 费率假设**与链上 **pfee CPI**(动态费率)不一致,**预估偏多**。
### SDK 侧处理思路
- **提高滑点容忍**(或降低 **`min_tokens_out`**)。
- 尽量用 **较新**的 **virtual/real reserves**(来自最近一次 trade 解析或简短 RPC)。
- 若运行在 **狙击手**等极端延迟场景,需接受:**保守的 min_out**(更大滑点)换成功率。
---
## 6. Pump `6024` `Overflow` 与其它算术类错误
### 现象
- `6024 Overflow``6025 Truncation``6026 DivisionByZero`(见 IDL)。
### 常见成因
- 指令参数 **`amount` / SOL / lamports** 与曲线状态组合不合法(例如极端大卖、或为 0 与后续计算冲突)。
- SDK 外传入了 **不合理的储备快照**
### SDK 侧处理思路
- 校验 **买入/卖出金额 > 0**、与余额一致。
- 使用 **`from_mint_by_rpc`** 或与链一致的储备后再算 **`min_sol_output` / `min_tokens_out`**。
---
## 7. Pump `6027` `NotEnoughRemainingAccounts`(返现等)
### 现象
- 返现代币等路径要求 **remaining accounts**(例如 `UserVolumeAccumulator`),数量不足。
### 常见成因
- **`is_cashback_coin`(或等价标志)为 true**,但组装指令时 **未追加**所需账户。
### SDK 侧处理思路
- **`PumpFunParams::from_trade` / `from_dev_trade`** 传入正确的 **`is_cashback_coin`**(来自事件)。
- README 中与 **Cashback** 章节一致:**事件路径必须带标志**,不能默认 false。
---
## 8. Pump `6022` `SellZeroAmount`
### 含义
卖出代币数量为 **0**。在业务层过滤即可。
---
## 9. 与 pump-fees / Creator 迁移相关的错误(`6049``6053` 等)
IDL 中例如:
- **`6049` `CreatorMigratedToSharingConfig`**
- **`6050` `UnableToDistributeCreatorVaultMigratedToSharingConfig`**
- **`6053` `BondingCurveAndSharingConfigCreatorMismatch`**
### 思路
这些是 **creator / fee-sharing** 生命周期中的**专用分支**,与一般买卖路径不同。若仿真或清算类指令触发:
-**Pump / pump-fees 官方文档** 为准使用 **`distribute_creator_fees`**、**reset_fee_sharing_config** 等;
- **`creator_vault` resolve** 需结合 **`fetch_fee_sharing_creator_vault_if_active`** 与链上 **`SharingConfig` 状态**,避免离线 deduce 过时。
---
## 10. 调试清单(推荐给集成方)
1. **记下失败指令索引** + **Simulation / explorer 展开的账户列表**,重点核对:**mint、bonding_curve、associated_bonding_curve、creator_vault、fee_recipient、token_program**。
2. **对比 Anchor 日志里的 Left / Right**(针对 2006)与本地 `PumpFunParams` 打印是否一致。
3. **`mint.owner`** 与 **`PumpFunParams.token_program`** 是否一致。
4. **`bonding_curve` 地址**是否与 **`get_bonding_curve_pda(mint)`** 一致。
5. **`mayhem_mode``fee_recipient`** 是否同池。
6. 低延迟不足以覆盖 **creator 演进** 时,是否在卖前引入了 **RPC 或最新 trade** 刷新。
---
## 参考代码入口(本仓库)
| 主题 | 路径 |
|------|------|
| Buy / Sell vault resolve(显式 ix `creator_vault``fee_sharing` hint → `PDA(effective_creator)` | `src/instruction/utils/pumpfun.rs``resolve_creator_vault_for_ix_with_fee_sharing``effective_creator_for_trade``src/trading/core/params/pumpfun.rs` |
| Fee recipient / Mayhem | `src/instruction/utils/pumpfun.rs``pump_fun_fee_recipient_meta`, `reconcile_mayhem_mode_for_trade` |
| 指令构建 | `src/instruction/pumpfun.rs``PumpFunInstructionBuilder` |
| Params | `src/trading/core/params/pumpfun.rs``PumpFunParams::{from_trade, from_dev_trade, from_mint_by_rpc, refresh_fee_sharing_creator_vault_from_rpc}` |
---
如需英文版或对 PumpSwap/其它 DEX 的同类文档,可在 `docs/` 下按相同结构扩展。
+1
View File
@@ -176,6 +176,7 @@ async fn pumpfun_copy_trade_with_grpc(
gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -179,6 +179,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -147,6 +147,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+5
View File
@@ -636,6 +636,7 @@ async fn handle_buy_pumpfun(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
@@ -692,6 +693,7 @@ async fn handle_buy_pumpswap(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
@@ -748,6 +750,7 @@ async fn handle_buy_bonk(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
@@ -808,6 +811,7 @@ async fn handle_buy_raydium_v4(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
@@ -869,6 +873,7 @@ async fn handle_buy_raydium_cpmm(
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
match client.buy(buy_params).await {
@@ -51,6 +51,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -112,6 +112,7 @@ async fn test_middleware() -> AnyResult<()> {
gas_fee_strategy: gas_fee_strategy,
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -172,6 +172,7 @@ async fn pumpfun_copy_trade_with_grpc(
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -169,6 +169,7 @@ async fn pumpfun_copy_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent)
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -159,6 +159,7 @@ async fn pumpfun_sniper_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -50,6 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -244,6 +244,7 @@ async fn pumpswap_trade_with_grpc(
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -181,6 +181,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
@@ -169,6 +169,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+1
View File
@@ -50,6 +50,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
gas_fee_strategy: gas_fee_strategy.clone(),
simulate: false,
use_exact_sol_amount: None,
use_pumpfun_v2: false,
grpc_recv_us: None,
};
client.buy(buy_params).await?;
+2323 -2896
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -4835,7 +4835,7 @@
},
{
"code": 6052,
"name": "TokensInVaultLessThanCashbackEarned"
"name": "CashbackEarnedDoesNotMatchTokenInVault"
}
],
"types": [
+1463 -242
View File
File diff suppressed because it is too large Load Diff
+39 -21
View File
@@ -3,6 +3,7 @@
use crate::common::nonce_cache::DurableNonceInfo;
use crate::common::sdk_log;
use crate::common::GasFeeStrategy;
use crate::common::SolanaRpcClient;
use crate::common::{InfrastructureConfig, TradeConfig};
#[cfg(feature = "perf-trace")]
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
@@ -25,7 +26,6 @@ use crate::trading::factory::DexType;
use crate::trading::MiddlewareManager;
use crate::trading::SwapParams;
use crate::trading::TradeFactory;
use crate::common::SolanaRpcClient;
use parking_lot::Mutex;
use rustls::crypto::{ring::default_provider, CryptoProvider};
use solana_sdk::hash::Hash;
@@ -112,7 +112,9 @@ impl TradingInfrastructure {
// 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, crate::common::seed::update_rents(&rpc)).await {
match tokio::time::timeout(RENT_UPDATE_TIMEOUT, crate::common::seed::update_rents(&rpc))
.await
{
Ok(Ok(())) => {}
Ok(Err(e)) => {
if sdk_log::sdk_log_enabled() {
@@ -218,15 +220,9 @@ impl TradingInfrastructure {
}
if !swqos_clients.is_empty() {
let labels: Vec<&str> = swqos_clients
.iter()
.map(|c| c.get_swqos_type().as_str())
.collect();
eprintln!(
"️ SWQOS 通道已就绪: {} 条 → [{}]",
swqos_clients.len(),
labels.join(", ")
);
let labels: Vec<&str> =
swqos_clients.iter().map(|c| c.get_swqos_type().as_str()).collect();
eprintln!("️ SWQOS 通道已就绪: {} 条 → [{}]", swqos_clients.len(), labels.join(", "));
}
let swqos_count = swqos_clients.len();
@@ -248,6 +244,8 @@ impl TradingInfrastructure {
(cap, Arc::new(ids))
};
crate::instruction::utils::pumpswap::warm_pumpswap_global_config(Some(&rpc)).await;
Self {
rpc,
swqos_clients: Arc::new(swqos_clients),
@@ -303,6 +301,8 @@ pub struct TradingClient {
pub log_enabled: bool,
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). Default false for lower latency.
pub check_min_tip: bool,
/// Use PumpFun V2 instructions (buy_v2 / sell_v2, 27-account metas). Default false.
pub use_pumpfun_v2: bool,
}
static INSTANCE: Mutex<Option<Arc<TradingClient>>> = Mutex::new(None);
@@ -323,6 +323,7 @@ impl Clone for TradingClient {
effective_core_ids: self.effective_core_ids.clone(),
log_enabled: self.log_enabled,
check_min_tip: self.check_min_tip,
use_pumpfun_v2: self.use_pumpfun_v2,
}
}
}
@@ -372,7 +373,7 @@ pub struct TradeBuyParams {
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
/// This option only applies to PumpFun and PumpSwap DEXes; it is ignored for other DEXes.
pub use_exact_sol_amount: Option<bool>,
/// 可选:事件收到时间(微秒,与 sol-parser-sdk 的 metadata.grpc_recv_us / clock::now_micros 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点,打印起点→提交耗时。
/// Optional upstream receive timestamp (e.g. gRPC recv) in microseconds for latency tracing.
pub grpc_recv_us: Option<i64>,
}
@@ -418,7 +419,7 @@ pub struct TradeSellParams {
pub gas_fee_strategy: GasFeeStrategy,
/// Whether to simulate the transaction instead of executing it
pub simulate: bool,
/// 可选:事件收到时间(微秒,与 sol-parser-sdk clock 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点。
/// Optional upstream receive timestamp (e.g. gRPC recv) in microseconds for latency tracing.
pub grpc_recv_us: Option<i64>,
}
@@ -457,6 +458,7 @@ impl TradingClient {
effective_core_ids,
log_enabled: true,
check_min_tip: false,
use_pumpfun_v2: false,
}
}
@@ -503,6 +505,7 @@ impl TradingClient {
effective_core_ids,
log_enabled: true,
check_min_tip: false,
use_pumpfun_v2: false,
}
}
@@ -682,6 +685,7 @@ impl TradingClient {
effective_core_ids: infrastructure.effective_core_ids.clone(),
log_enabled: trade_config.log_enabled,
check_min_tip: trade_config.check_min_tip,
use_pumpfun_v2: trade_config.use_pumpfun_v2,
};
let mut current = INSTANCE.lock();
@@ -727,7 +731,8 @@ impl TradingClient {
Some(v) => {
self.use_dedicated_sender_threads = true;
let cap = v.len().min(self.max_sender_concurrency);
self.sender_thread_cores = Some(Arc::new(if cap < v.len() { v[..cap].to_vec() } else { v }));
self.sender_thread_cores =
Some(Arc::new(if cap < v.len() { v[..cap].to_vec() } else { v }));
}
}
self
@@ -790,7 +795,10 @@ impl TradingClient {
pub async fn buy(
&self,
params: TradeBuyParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), anyhow::Error> {
) -> Result<
(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>),
anyhow::Error,
> {
if params.recent_blockhash.is_none() && params.durable_nonce.is_none() {
return Err(anyhow::anyhow!(
"Must provide either recent_blockhash or durable_nonce for buy (required for transaction validity)"
@@ -860,11 +868,13 @@ impl TradingClient {
check_min_tip: self.check_min_tip,
grpc_recv_us: params.grpc_recv_us,
use_exact_sol_amount: params.use_exact_sol_amount,
use_pumpfun_v2: self.use_pumpfun_v2,
};
let swap_result = executor.swap(buy_params).await;
let result =
swap_result.map(|(success, sigs, err, timings)| (success, sigs, err.map(TradeError::from), timings));
let result = swap_result.map(|(success, sigs, err, timings)| {
(success, sigs, err.map(TradeError::from), timings)
});
result
}
@@ -897,7 +907,10 @@ impl TradingClient {
pub async fn sell(
&self,
params: TradeSellParams,
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), anyhow::Error> {
) -> Result<
(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>),
anyhow::Error,
> {
#[cfg(feature = "perf-trace")]
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
debug!(
@@ -967,11 +980,13 @@ impl TradingClient {
check_min_tip: self.check_min_tip,
grpc_recv_us: params.grpc_recv_us,
use_exact_sol_amount: None,
use_pumpfun_v2: self.use_pumpfun_v2,
};
let swap_result = executor.swap(sell_params).await;
let result =
swap_result.map(|(success, sigs, err, timings)| (success, sigs, err.map(TradeError::from), timings));
let result = swap_result.map(|(success, sigs, err, timings)| {
(success, sigs, err.map(TradeError::from), timings)
});
result
}
@@ -1006,7 +1021,10 @@ impl TradingClient {
mut params: TradeSellParams,
amount_token: u64,
percent: u64,
) -> Result<(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>), anyhow::Error> {
) -> Result<
(bool, Vec<Signature>, Option<TradeError>, Vec<(crate::swqos::SwqosType, i64)>),
anyhow::Error,
> {
if percent == 0 || percent > 100 {
return Err(anyhow::anyhow!("Percentage must be between 1 and 100"));
}
+6 -8
View File
@@ -8,16 +8,16 @@ pub async fn fetch_address_lookup_table_account(
lookup_table_address: &Pubkey,
) -> Result<AddressLookupTableAccount, anyhow::Error> {
let account = rpc.get_account(lookup_table_address).await?;
// Parse address lookup table manually
// Layout: 4 bytes (type) + 4 bytes (deactivation_slot) + 4 bytes (last_extended_slot) + 1 byte (last_extended_slot_start_index) + 1 byte (authority) + padding
// Then addresses start at offset 56, each address is 32 bytes
// First 4 bytes indicate if initialized (should be 1 or 2)
if account.data.len() < 56 {
return Err(anyhow::anyhow!("Address lookup table account data too short"));
}
// Read number of addresses (stored at offset 20 as u32, but we need to scan the bitmap)
// Actually simpler: addresses start at offset 56, count from bitmap at offset 8-20
let mut addresses = Vec::new();
@@ -30,10 +30,8 @@ pub async fn fetch_address_lookup_table_account(
}
offset += 32;
}
let address_lookup_table_account = AddressLookupTableAccount {
key: *lookup_table_address,
addresses,
};
let address_lookup_table_account =
AddressLookupTableAccount { key: *lookup_table_address, addresses };
Ok(address_lookup_table_account)
}
+2
View File
@@ -154,6 +154,8 @@ pub enum PdaCacheKey {
PumpFunUserVolume(Pubkey),
PumpFunBondingCurve(Pubkey),
PumpFunBondingCurveV2(Pubkey),
/// Pump-fees program `sharing-config` PDA for a mint (`feeSharingConfigPda`).
PumpFunFeeSharingConfig(Pubkey),
PumpFunCreatorVault(Pubkey),
BonkPool(Pubkey, Pubkey),
BonkVault(Pubkey, Pubkey),
+2 -9
View File
@@ -34,10 +34,7 @@ fn extract_swqos_error_message(s: &str) -> String {
// Try parse as JSON only when input looks like JSON (avoid parsing long non-JSON strings)
if s.starts_with('{') {
if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
let obj = v
.get("error")
.and_then(|e| e.as_object())
.or_else(|| v.as_object());
let obj = v.get("error").and_then(|e| e.as_object()).or_else(|| v.as_object());
if let Some(o) = obj {
if let Some(m) = o.get("message").and_then(|x| x.as_str()) {
return m.to_string();
@@ -69,11 +66,7 @@ pub fn set_sdk_log_enabled(enabled: bool) {
/// Aligned log: ` [Soyas ] Buy submitted: 13.936 µs`. Call only when sdk_log_enabled().
#[inline]
pub fn log_swqos_submitted(
provider: &str,
trade_type: impl fmt::Display,
elapsed: Duration,
) {
pub fn log_swqos_submitted(provider: &str, trade_type: impl fmt::Display, elapsed: Duration) {
println!(
" [{:width$}] {} submitted: {}",
provider,
+9 -2
View File
@@ -94,8 +94,15 @@ pub fn create_associated_token_account_use_seed(
let len = 165;
// 🔧 修复:create_account_with_seed 的第3个参数必须是 payer(与第92行生成地址时使用的 base 一致)
// 否则创建的账户地址与 ata_like 不匹配,导致 initializeAccount3 失败
let create_acc =
system_instruction::create_account_with_seed(payer, &ata_like, payer, seed, rent, len, token_program);
let create_acc = system_instruction::create_account_with_seed(
payer,
&ata_like,
payer,
seed,
rent,
len,
token_program,
);
let init_acc = if is_2022_token {
crate::common::spl_token_2022::initialize_account3(&token_program, &ata_like, mint, owner)?
+1 -4
View File
@@ -20,10 +20,7 @@ pub fn close_account(
let mut accounts = Vec::with_capacity(3 + signer_pubkeys.len());
accounts.push(AccountMeta::new(*account_pubkey, false));
accounts.push(AccountMeta::new(*destination_pubkey, false));
accounts.push(AccountMeta::new_readonly(
*owner_pubkey,
signer_pubkeys.is_empty(),
));
accounts.push(AccountMeta::new_readonly(*owner_pubkey, signer_pubkeys.is_empty()));
for signer_pubkey in signer_pubkeys.iter() {
accounts.push(AccountMeta::new_readonly(**signer_pubkey, true));
}
+14
View File
@@ -95,6 +95,9 @@ pub struct TradeConfig {
/// (Astralane QUIC `:9000` or Plain/Binary HTTP `mev-protect=true`, BlockRazor sandwichMitigation)
/// use their MEV-protected endpoints/modes. Default false (no MEV protection, lower latency).
pub mev_protection: bool,
/// Use PumpFun V2 instructions (buy_v2 / sell_v2, 27/26-account metas, quote_mint support).
/// Default: `false` keeps legacy SOL-paired instructions for smaller transactions; V2 is the official future-proof interface.
pub use_pumpfun_v2: bool,
}
impl TradeConfig {
@@ -149,6 +152,7 @@ pub struct TradeConfigBuilder {
check_min_tip: bool,
swqos_cores_from_end: bool,
mev_protection: bool,
use_pumpfun_v2: bool,
}
impl TradeConfigBuilder {
@@ -163,6 +167,7 @@ impl TradeConfigBuilder {
check_min_tip: false,
swqos_cores_from_end: false,
mev_protection: false,
use_pumpfun_v2: false,
}
}
@@ -208,6 +213,14 @@ impl TradeConfigBuilder {
self
}
/// Use PumpFun V2 instructions (`buy_v2` / `sell_v2`, 27-account metas, `quote_mint` support).
/// Default: `false` (V1 — 18-account metas, legacy SOL-paired, smaller transaction).
/// Set to `true` when PumpFun officially deploys V2 on mainnet.
pub fn use_pumpfun_v2(mut self, v: bool) -> Self {
self.use_pumpfun_v2 = v;
self
}
/// Consume the builder and produce a [`TradeConfig`].
pub fn build(self) -> TradeConfig {
TradeConfig {
@@ -220,6 +233,7 @@ impl TradeConfigBuilder {
check_min_tip: self.check_min_tip,
swqos_cores_from_end: self.swqos_cores_from_end,
mev_protection: self.mev_protection,
use_pumpfun_v2: self.use_pumpfun_v2,
}
}
}
+6
View File
@@ -57,3 +57,9 @@ pub const RENT_META: solana_sdk::instruction::AccountMeta =
pub const ASSOCIATED_TOKEN_PROGRAM_ID: Pubkey =
pubkey!("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
pub const ASSOCIATED_TOKEN_PROGRAM_META: solana_sdk::instruction::AccountMeta =
solana_sdk::instruction::AccountMeta {
pubkey: ASSOCIATED_TOKEN_PROGRAM_ID,
is_signer: false,
is_writable: false,
};
+8 -10
View File
@@ -212,7 +212,7 @@ pub const SWQOS_ENDPOINTS_ZERO_SLOT: [&str; 10] = [
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
"http://ams.0slot.trade",
"http://ams.0slot.trade", // Dublin: 无 IE 专用;在已公布 EU 点中选距爱尔兰最近的 ams(相对 de2 等)
"http://la.0slot.trade", // SLC: no UT PoP; nearest US-West published host
"http://la.0slot.trade", // SLC: no UT PoP; nearest US-West published host
"http://jp.0slot.trade",
"http://jp.0slot.trade", // SG: 无本地 PoP;已公布 APAC 仅 jp,为表中离新加坡最近的大圆距离
"http://ams.0slot.trade", // London: 无 UK 专用;已公布 EU 点中 ams 距伦敦最近之一
@@ -252,11 +252,11 @@ pub const SWQOS_ENDPOINTS_NODE1: [&str; 10] = [
"http://fra.node1.me",
"http://ams.node1.me",
"http://lon.node1.me", // Dublin: 已公布中英爱区域用 lon(地理上近爱尔兰)
"http://ny.node1.me", // SLC: 已公布美国仅 ny;美西无 PoP,受可用区限制复用美东
"http://ny.node1.me", // SLC: 已公布美国仅 ny;美西无 PoP,受可用区限制复用美东
"http://tk.node1.me",
"http://tk.node1.me", // SG: 已公布 APAC 仅 tk;地理上为表中离 SG 最近
"http://lon.node1.me",
"http://ny.node1.me", // LosAngeles: 同上,美国仅 ny 入口
"http://ny.node1.me", // LosAngeles: 同上,美国仅 ny 入口
"http://fra.node1.me", // Default: 非地理区域;与 QUIC 对齐为 EU 枢纽
];
@@ -359,7 +359,7 @@ pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 10] = [
"fr.gateway.astralane.io:7000",
"ams.gateway.astralane.io:7000",
"ams.gateway.astralane.io:7000", // Dublin: 同 HTTP
"la.gateway.astralane.io:7000", // SLC: 美西 la 为最近已公布美区入口
"la.gateway.astralane.io:7000", // SLC: 美西 la 为最近已公布美区入口
"jp.gateway.astralane.io:7000",
"sg.gateway.astralane.io:7000",
"ams.gateway.astralane.io:7000", // London: 同 HTTP
@@ -503,12 +503,10 @@ mod tests {
#[test]
fn node1_http_host_matches_quic_without_port() {
for i in 0..10 {
let http_host = SWQOS_ENDPOINTS_NODE1[i]
.strip_prefix("http://")
.expect("NODE1 HTTP URL");
let quic_host = SWQOS_ENDPOINTS_NODE1_QUIC[i]
.strip_suffix(":16666")
.expect("NODE1 QUIC endpoint");
let http_host =
SWQOS_ENDPOINTS_NODE1[i].strip_prefix("http://").expect("NODE1 HTTP URL");
let quic_host =
SWQOS_ENDPOINTS_NODE1_QUIC[i].strip_suffix(":16666").expect("NODE1 QUIC endpoint");
assert_eq!(http_host, quic_host, "Node1 HTTP vs QUIC host mismatch at index {}", i);
}
}
+2 -2
View File
@@ -1,9 +1,9 @@
pub mod bonk;
pub mod meteora_damm_v2;
pub(crate) mod pumpfun_ix_data;
pub(crate) mod pumpswap_ix_data;
pub mod pumpfun;
pub(crate) mod pumpfun_ix_data;
pub mod pumpswap;
pub(crate) mod pumpswap_ix_data;
pub mod raydium_amm_v4;
pub mod raydium_cpmm;
pub mod utils;
Executable → Regular
+796 -274
View File
File diff suppressed because it is too large Load Diff
+52 -13
View File
@@ -1,25 +1,31 @@
//! Pump.fun 曲线 `buy` / `buy_exact_sol_in` / `sell` **instruction data** 栈上编码(热路径零堆分配)。
//! Pump.fun 曲线 **legacy** `buy` / `buy_exact_sol_in` / `sell` **`buy_v2` / `sell_v2` / `buy_exact_quote_in_v2`**
//! 的 instruction data 栈上编码(热路径零堆分配)。
//!
//! 与 `@pump-fun/pump-sdk` Anchor `coder.instruction.encode` 对齐:`OptionBool` 在 ix 参数中为 **1 字节**。
//! Legacy `buy` / `buy_exact_sol_in` 与 `@pump-fun/pump-sdk` 对齐:`OptionBool` 在 ix 参数中为
//! **1 字节 option tag + 1 字节值**Anchor `Option<bool>` = 2 字节),共 26 字节 ix data。
//! `*_v2` 指令无 `track_volume` 字节(见 [pump-public-docs](https://github.com/pump-fun/pump-public-docs))。
use crate::instruction::utils::pumpfun::{
BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
BUY_DISCRIMINATOR, BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR,
BUY_V2_DISCRIMINATOR, SELL_DISCRIMINATOR, SELL_V2_DISCRIMINATOR,
};
/// 与官方 `getBuyInstructionInternal` 一致:`track_volume = true`
pub const TRACK_VOLUME_TRUE: u8 = 1;
/// 与官方 `getBuyInstructionInternal` 对齐:`OptionBool` 在 ix 中为 1 字节 option tag + 1 字节值
/// `track_volume` 在调用侧组合为 `(1u8, cashback as u8)`Option tag + value),共 26 字节 ix data。
pub const TRACK_VOLUME_OPTION_TAG: u8 = 1;
#[inline(always)]
pub fn encode_pumpfun_buy_ix_data(
token_amount: u64,
max_sol_cost: u64,
track_volume: u8,
) -> [u8; 25] {
let mut d = [0u8; 25];
track_volume_val: u8,
) -> [u8; 26] {
let mut d = [0u8; 26];
d[..8].copy_from_slice(&BUY_DISCRIMINATOR);
d[8..16].copy_from_slice(&token_amount.to_le_bytes());
d[16..24].copy_from_slice(&max_sol_cost.to_le_bytes());
d[24] = track_volume;
d[24] = TRACK_VOLUME_OPTION_TAG;
d[25] = track_volume_val;
d
}
@@ -27,13 +33,14 @@ pub fn encode_pumpfun_buy_ix_data(
pub fn encode_pumpfun_buy_exact_sol_in_ix_data(
spendable_sol_in: u64,
min_tokens_out: u64,
track_volume: u8,
) -> [u8; 25] {
let mut d = [0u8; 25];
track_volume_val: u8,
) -> [u8; 26] {
let mut d = [0u8; 26];
d[..8].copy_from_slice(&BUY_EXACT_SOL_IN_DISCRIMINATOR);
d[8..16].copy_from_slice(&spendable_sol_in.to_le_bytes());
d[16..24].copy_from_slice(&min_tokens_out.to_le_bytes());
d[24] = track_volume;
d[24] = TRACK_VOLUME_OPTION_TAG;
d[25] = track_volume_val;
d
}
@@ -45,3 +52,35 @@ pub fn encode_pumpfun_sell_ix_data(token_amount: u64, min_sol_output: u64) -> [u
d[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
d
}
// --- v2 instruction data encoders (no track_volume arg — 2 args each, 24 bytes total) ---
#[inline(always)]
pub fn encode_pumpfun_buy_v2_ix_data(amount: u64, max_sol_cost: u64) -> [u8; 24] {
let mut d = [0u8; 24];
d[..8].copy_from_slice(&BUY_V2_DISCRIMINATOR);
d[8..16].copy_from_slice(&amount.to_le_bytes());
d[16..24].copy_from_slice(&max_sol_cost.to_le_bytes());
d
}
#[inline(always)]
pub fn encode_pumpfun_buy_exact_quote_in_v2_ix_data(
spendable_quote_in: u64,
min_tokens_out: u64,
) -> [u8; 24] {
let mut d = [0u8; 24];
d[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR);
d[8..16].copy_from_slice(&spendable_quote_in.to_le_bytes());
d[16..24].copy_from_slice(&min_tokens_out.to_le_bytes());
d
}
#[inline(always)]
pub fn encode_pumpfun_sell_v2_ix_data(token_amount: u64, min_sol_output: u64) -> [u8; 24] {
let mut d = [0u8; 24];
d[..8].copy_from_slice(&SELL_V2_DISCRIMINATOR);
d[8..16].copy_from_slice(&token_amount.to_le_bytes());
d[16..24].copy_from_slice(&min_sol_output.to_le_bytes());
d
}
+17 -21
View File
@@ -6,8 +6,9 @@ use crate::{
},
instruction::utils::pumpswap::{
accounts, fee_recipient_ata, get_mayhem_fee_recipient_random, get_pool_v2_pda,
get_protocol_extra_fee_recipient_random, get_user_volume_accumulator_pda,
get_user_volume_accumulator_quote_ata, get_user_volume_accumulator_wsol_ata,
get_protocol_extra_fee_recipient_random, get_protocol_fee_recipient_random,
get_user_volume_accumulator_pda, get_user_volume_accumulator_quote_ata,
get_user_volume_accumulator_wsol_ata, warm_pumpswap_global_config,
},
trading::{
common::wsol_manager,
@@ -31,6 +32,7 @@ pub struct PumpSwapInstructionBuilder;
#[async_trait::async_trait]
impl InstructionBuilder for PumpSwapInstructionBuilder {
async fn build_buy_instructions(&self, params: &SwapParams) -> Result<Vec<Instruction>> {
warm_pumpswap_global_config(params.rpc.as_ref()).await;
// ========================================
// Parameter validation and basic data preparation
// ========================================
@@ -131,13 +133,10 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
get_mayhem_fee_recipient_random()
} else {
(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 recipient = get_protocol_fee_recipient_random();
(recipient, AccountMeta::new_readonly(recipient, false))
};
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
// ========================================
// Build instructions
@@ -148,13 +147,12 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
// Determine wrap amount based on instruction type:
// - buy_exact_quote_in: program spends exactly input_amount, wrap input_amount
// - buy: program may spend up to max_quote, wrap max_quote
let wrap_amount = if quote_is_wsol_or_usdc
&& params.use_exact_sol_amount.unwrap_or(true)
{
params.input_amount.unwrap_or(0)
} else {
sol_amount
};
let wrap_amount =
if quote_is_wsol_or_usdc && params.use_exact_sol_amount.unwrap_or(true) {
params.input_amount.unwrap_or(0)
} else {
sol_amount
};
instructions
.extend(crate::trading::common::handle_wsol(&params.payer.pubkey(), wrap_amount));
}
@@ -261,6 +259,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
}
async fn build_sell_instructions(&self, params: &SwapParams) -> Result<Vec<Instruction>> {
warm_pumpswap_global_config(params.rpc.as_ref()).await;
// ========================================
// Parameter validation and basic data preparation
// ========================================
@@ -346,13 +345,10 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
get_mayhem_fee_recipient_random()
} else {
(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 recipient = get_protocol_fee_recipient_random();
(recipient, AccountMeta::new_readonly(recipient, false))
};
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(
+246 -262
View File
@@ -1,5 +1,10 @@
//! Pump.fun bonding-curve utilities (flat module): PDAs, fee `#2`, pump-fees `SharingConfig`, cold RPC.
//!
//! Hot swap ix assembly stays sync; async helpers at file bottom. Layout matches `@pump-fun/pump-sdk`.
use crate::common::{bonding_curve::BondingCurveAccount, SolanaRpcClient};
use anyhow::anyhow;
use borsh::BorshDeserialize;
use rand::seq::IndexedRandom;
use solana_sdk::{
instruction::{AccountMeta, Instruction},
@@ -7,85 +12,43 @@ use solana_sdk::{
};
use std::sync::Arc;
// --- Aligned with official `@pump-fun/pump-sdk` (npm) ---
// - `src/fees.ts` `getFeeRecipient(global, mayhemMode)` — fee recipient pools
// - `src/bondingCurve.ts` `CURRENT_FEE_RECIPIENTS` / `getStaticRandomFeeRecipient`
// - `src/sdk.ts` `BONDING_CURVE_NEW_SIZE` (151) + `extendAccountInstruction` — **not** called from the
// trade hot path here (no RPC in `PumpFunInstructionBuilder`); use these helpers from a cold path if needed.
// --- seeds -------------------------------------------------------------
/// Minimum bonding curve account data length after protocol upgrades (`sdk.ts` `BONDING_CURVE_NEW_SIZE`).
pub const PUMP_BONDING_CURVE_MIN_DATA_LEN: usize = 151;
/// Anchor discriminator for `extend_account` (`pump.json`); same as `PumpSdk.extendAccountInstruction`.
pub const EXTEND_ACCOUNT_DISCRIMINATOR: [u8; 8] = [234, 102, 194, 203, 150, 72, 62, 229];
/// Build `extend_account` for bonding curve (cold path / separate tx only — do not add RPC to hot-path builds).
#[inline]
pub fn extend_bonding_curve_account_instruction(bonding_curve: &Pubkey, user: &Pubkey) -> Instruction {
Instruction {
program_id: accounts::PUMPFUN,
accounts: vec![
AccountMeta::new(*bonding_curve, false),
AccountMeta::new(*user, true),
crate::constants::SYSTEM_PROGRAM_META,
accounts::EVENT_AUTHORITY_META,
accounts::PUMPFUN_META,
],
data: EXTEND_ACCOUNT_DISCRIMINATOR.to_vec(),
}
}
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
pub mod seeds {
/// Seed for bonding curve PDAs
/// Seed for bonding curve PDAs (`["bonding-curve", mint]`).
pub const BONDING_CURVE_SEED: &[u8] = b"bonding-curve";
/// Seed for bonding curve v2 PDA (required by program upgrade, readonly at end of account list)
/// Seed for bonding curve v2 PDA (`["bonding-curve-v2", mint]`).
pub const BONDING_CURVE_V2_SEED: &[u8] = b"bonding-curve-v2";
/// Seed for creator vault PDAs
/// Creator vault PDA seeds prefix (`["creator-vault", authority]`).
pub const CREATOR_VAULT_SEED: &[u8] = b"creator-vault";
/// Seed for metadata PDAs
/// Metadata PDA seeds prefix.
pub const METADATA_SEED: &[u8] = b"metadata";
/// Seed for user volume accumulator PDAs
/// User volume accumulator for cashback / bonding-curve UX.
pub const USER_VOLUME_ACCUMULATOR_SEED: &[u8] = b"user_volume_accumulator";
/// Seed for global volume accumulator PDAs
/// Global volume accumulator.
pub const GLOBAL_VOLUME_ACCUMULATOR_SEED: &[u8] = b"global_volume_accumulator";
pub const FEE_CONFIG_SEED: &[u8] = b"fee_config";
/// `feeSharingConfig` PDA under pump-fees (`@pump-fun/pump-sdk` `feeSharingConfigPda`)
/// `feeSharingConfig` PDA under pump-fees (`feeSharingConfigPda`).
pub const SHARING_CONFIG_SEED: &[u8] = b"sharing-config";
}
pub mod global_constants {
use solana_sdk::{pubkey, pubkey::Pubkey};
pub const INITIAL_VIRTUAL_TOKEN_RESERVES: u64 = 1_073_000_000_000_000;
pub const INITIAL_VIRTUAL_SOL_RESERVES: u64 = 30_000_000_000;
pub const INITIAL_REAL_TOKEN_RESERVES: u64 = 793_100_000_000_000;
pub const TOKEN_TOTAL_SUPPLY: u64 = 1_000_000_000_000_000;
pub const FEE_BASIS_POINTS: u64 = 95;
pub const ENABLE_MIGRATE: bool = false;
pub const POOL_MIGRATION_FEE: u64 = 15_000_001;
pub const CREATOR_FEE: u64 = 30;
pub const SCALE: u64 = 1_000_000;
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000;
pub const COMPLETION_LAMPORTS: u64 = 85 * LAMPORTS_PER_SOL;
pub const SCALE: u64 = 1_000_000; // 10^6 for token decimals
pub const LAMPORTS_PER_SOL: u64 = 1_000_000_000; // 10^9 for solana lamports
pub const COMPLETION_LAMPORTS: u64 = 85 * LAMPORTS_PER_SOL; // ~ 85 SOL
/// Public key for the fee recipient
pub const FEE_RECIPIENT: Pubkey = pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
pub const FEE_RECIPIENT_META: solana_sdk::instruction::AccountMeta =
solana_sdk::instruction::AccountMeta {
@@ -94,7 +57,6 @@ pub mod global_constants {
is_writable: true,
};
/// Mayhem fee recipients (pump-public-docs: use any one randomly)
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
@@ -113,7 +75,6 @@ pub mod global_constants {
is_writable: true,
};
/// Public key for the global PDA
pub const GLOBAL_ACCOUNT: Pubkey = pubkey!("4wTV1YmiEkRvAtNtsSGPtUrqRYQMe5SKy2uB4Jjaxnjf");
pub const GLOBAL_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
solana_sdk::instruction::AccountMeta {
@@ -122,23 +83,17 @@ pub mod global_constants {
is_writable: false,
};
/// Public key for the authority
pub const AUTHORITY: Pubkey = pubkey!("FFWtrEQ4B4PKQoVuHYzZq8FabGkVatYzDpEVHsK5rrhF");
/// Public key for the withdraw authority
pub const WITHDRAW_AUTHORITY: Pubkey = pubkey!("39azUYFWPz3VHgKCf3VChUwbpURdCHRxjWVowf5jUJjg");
pub const PUMPFUN_AMM_FEE_1: Pubkey = pubkey!("7VtfL8fvgNfhz17qKRMjzQEXgbdpnHHHQRh54R9jP2RJ"); // Pump.fun AMM: Protocol Fee 1
pub const PUMPFUN_AMM_FEE_2: Pubkey = pubkey!("7hTckgnGnLQR6sdH7YkqFTAA7VwTfYFaZ6EhEsU3saCX"); // Pump.fun AMM: Protocol Fee 2
pub const PUMPFUN_AMM_FEE_3: Pubkey = pubkey!("9rPYyANsfQZw3DnDmKE3YCQF5E8oD89UXoHn9JFEhJUz"); // Pump.fun AMM: Protocol Fee 3
pub const PUMPFUN_AMM_FEE_4: Pubkey = pubkey!("AVmoTthdrX6tKt4nDjco2D775W2YK3sDhxPcMmzUAmTY"); // Pump.fun AMM: Protocol Fee 4
pub const PUMPFUN_AMM_FEE_5: Pubkey = pubkey!("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM"); // Pump.fun AMM: Protocol Fee 5
pub const PUMPFUN_AMM_FEE_6: Pubkey = pubkey!("FWsW1xNtWscwNmKv6wVsU1iTzRN6wmmk3MjxRP5tT7hz"); // Pump.fun AMM: Protocol Fee 6
pub const PUMPFUN_AMM_FEE_1: Pubkey = pubkey!("7VtfL8fvgNfhz17qKRMjzQEXgbdpnHHHQRh54R9jP2RJ");
pub const PUMPFUN_AMM_FEE_2: Pubkey = pubkey!("7hTckgnGnLQR6sdH7YkqFTAA7VwTfYFaZ6EhEsU3saCX");
pub const PUMPFUN_AMM_FEE_3: Pubkey = pubkey!("9rPYyANsfQZw3DnDmKE3YCQF5E8oD89UXoHn9JFEhJUz");
pub const PUMPFUN_AMM_FEE_4: Pubkey = pubkey!("AVmoTthdrX6tKt4nDjco2D775W2YK3sDhxPcMmzUAmTY");
pub const PUMPFUN_AMM_FEE_5: Pubkey = pubkey!("CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbicfhtW4xC9iM");
pub const PUMPFUN_AMM_FEE_6: Pubkey = pubkey!("FWsW1xNtWscwNmKv6wVsU1iTzRN6wmmk3MjxRP5tT7hz");
pub const PUMPFUN_AMM_FEE_7: Pubkey = pubkey!("G5UZAVbAf46s7cKWoyKu8kYTip9DGTpbLZ2qa9Aq69dP");
// Pump.fun AMM: Protocol Fee 7
/// Protocol extra fee recipients (Apr 2026 breaking upgrade). One is appended after `bonding-curve-v2`, **writable**.
/// See: <https://github.com/pump-fun/pump-public-docs/blob/main/docs/BREAKING_FEE_RECIPIENT.md>
pub const PROTOCOL_EXTRA_FEE_RECIPIENTS: [Pubkey; 8] = [
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
@@ -149,35 +104,36 @@ pub mod global_constants {
pubkey!("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
pubkey!("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
];
/// Buyback fee recipients (v2 account #9 in buy_v2/sell_v2).
/// 对应官方 FEE_RECIPIENTS.md "Buyback (Applies to All)" 池,与主 fee_recipient 池互斥。
pub const BUYBACK_FEE_RECIPIENTS: [Pubkey; 8] = [
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
pubkey!("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
pubkey!("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
pubkey!("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
pubkey!("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
pubkey!("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
pubkey!("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
];
}
/// Constants related to program accounts and authorities
pub mod accounts {
use solana_sdk::{pubkey, pubkey::Pubkey};
/// Public key for the Pump.fun program
pub const PUMPFUN: Pubkey = pubkey!("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P");
/// Public key for the MPL Token Metadata program
pub const MPL_TOKEN_METADATA: Pubkey = pubkey!("metaqbxxUerdq28cj1RbAWkYQm3ybzjb6a8bt518x1s");
/// Authority for program events
pub const EVENT_AUTHORITY: Pubkey = pubkey!("Ce6TQqeHC9p8KetsN6JsjHK7UTZk7nasjjnr7XxXp9F1");
/// Associated Token Program ID
pub const ASSOCIATED_TOKEN_PROGRAM: Pubkey =
pubkey!("ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL");
pub const AMM_PROGRAM: Pubkey = pubkey!("675kPX9MHTjS2zt1qfr1NYHuzeLXfQM9H24wFSUt1Mp8");
pub const FEE_PROGRAM: Pubkey = pubkey!("pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ");
pub const GLOBAL_VOLUME_ACCUMULATOR: Pubkey =
pubkey!("Hq2wp8uJ9jCPsYgNHex8RtqdvMPfVGoYwjvF1ATiwn2Y");
pub const FEE_CONFIG: Pubkey = pubkey!("8Wf5TiAheLUqBrKXeYg2JtAFFMWtKdG2BSFgqUcPVwTt");
// META
pub const PUMPFUN_META: solana_sdk::instruction::AccountMeta =
solana_sdk::instruction::AccountMeta {
pubkey: PUMPFUN,
@@ -214,24 +170,35 @@ pub mod accounts {
};
}
/// Instruction discriminators for PumpFun program
// --- Anchor / layout constants ---------------------------------------
/// Minimum bonding curve account data length (`sdk.ts` `BONDING_CURVE_NEW_SIZE`).
pub const PUMP_BONDING_CURVE_MIN_DATA_LEN: usize = 151;
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];
/// Anchor account discriminator for `SharingConfig` on `pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ` (`pump_fees.json`).
/// `buy_v2` — unified SOL/USDC quote interface ([pump-public-docs](https://github.com/pump-fun/pump-public-docs)).
pub const BUY_V2_DISCRIMINATOR: [u8; 8] = [184, 23, 238, 97, 103, 197, 211, 61];
/// `sell_v2`
pub const SELL_V2_DISCRIMINATOR: [u8; 8] = [93, 246, 130, 60, 231, 233, 64, 178];
/// `buy_exact_quote_in_v2` (native SOL spend for SOL-paired coins when `quote_mint` is WSOL)
pub const BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR: [u8; 8] = [194, 171, 28, 70, 104, 77, 91, 47];
pub const EXTEND_ACCOUNT_DISCRIMINATOR: [u8; 8] = [234, 102, 194, 203, 150, 72, 62, 229];
pub const SHARING_CONFIG_ACCOUNT_DISCRIMINATOR: [u8; 8] = [216, 74, 9, 0, 56, 140, 93, 75];
/// `ConfigStatus::Active` as serialized by Anchor (enum variant index; `Paused` = 0).
const SHARING_CONFIG_STATUS_ACTIVE: u8 = 1;
pub(crate) const SHARING_CONFIG_STATUS_ACTIVE: u8 = 1;
// --- Fee recipient pools -----------------------------------------------
/// Check if a pubkey is one of the Mayhem fee recipients
#[inline]
pub fn is_mayhem_fee_recipient(pubkey: &Pubkey) -> bool {
global_constants::MAYHEM_FEE_RECIPIENTS.iter().any(|p| p == pubkey)
global_constants::MAYHEM_FEE_RECIPIENTS.contains(pubkey)
}
/// Check if a pubkey is a Pump.fun AMM protocol fee recipient (PUMPFUN_AMM_FEE_1..7)
#[inline]
pub fn is_amm_fee_recipient(pubkey: &Pubkey) -> bool {
pubkey == &global_constants::PUMPFUN_AMM_FEE_1
@@ -243,14 +210,11 @@ pub fn is_amm_fee_recipient(pubkey: &Pubkey) -> bool {
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_7
}
/// Non-mayhem bonding-curve fee pool: primary fee recipient + AMM protocol fee slots (`getFeeRecipient` when `mayhemMode === false`).
#[inline]
pub fn is_standard_bonding_fee_recipient(pubkey: &Pubkey) -> bool {
*pubkey == global_constants::FEE_RECIPIENT || is_amm_fee_recipient(pubkey)
}
/// Bonding-curve trade: `mayhemMode` 与账户 #2 fee recipient 必须同属 Mayhem 池或同属普通池,否则会 Anchor `NotAuthorized`fee_recipient 校验)。
/// gRPC 偶尔只带对一侧的字段时,用 fee 地址与静态池对齐。
#[inline]
pub fn reconcile_mayhem_mode_for_trade(
mayhem_from_event: Option<bool>,
@@ -275,7 +239,6 @@ pub fn reconcile_mayhem_mode_for_trade(
}
}
/// Whether `pk` is allowed as account #2 for this bonding-curve mode. Unknown pubkeys (not in static pools) are accepted — chain is authoritative.
#[inline]
pub fn fee_recipient_ok_for_bonding_curve_mode(pk: &Pubkey, is_mayhem_mode: bool) -> bool {
let is_m = is_mayhem_fee_recipient(pk);
@@ -287,8 +250,6 @@ pub fn fee_recipient_ok_for_bonding_curve_mode(pk: &Pubkey, is_mayhem_mode: bool
}
}
/// Mayhem: random among `Global.reservedFeeRecipient` + `Global.reservedFeeRecipients` (`fees.ts` `getFeeRecipient` when `mayhemMode === true`).
/// Uses hardcoded `MAYHEM_FEE_RECIPIENTS`; prefer gRPC/event `PumpFunParams.fee_recipient` when set.
#[inline]
pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
@@ -297,8 +258,6 @@ pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
AccountMeta { pubkey: recipient, is_signer: false, is_writable: true }
}
/// Non-mayhem: random among `Global::fee_recipient` + `Global::fee_recipients[0..7]`.
/// Same pubkey set as `bondingCurve.ts` `CURRENT_FEE_RECIPIENTS` / `getStaticRandomFeeRecipient` and `fees.ts` `getFeeRecipient` when `mayhemMode === false`.
#[inline]
pub fn get_standard_fee_recipient_meta_random() -> AccountMeta {
const POOL: &[Pubkey] = &[
@@ -311,17 +270,10 @@ pub fn get_standard_fee_recipient_meta_random() -> AccountMeta {
global_constants::PUMPFUN_AMM_FEE_6,
global_constants::PUMPFUN_AMM_FEE_7,
];
let recipient = *POOL
.choose(&mut rand::rng())
.unwrap_or(&global_constants::FEE_RECIPIENT);
AccountMeta {
pubkey: recipient,
is_signer: false,
is_writable: true,
}
let recipient = *POOL.choose(&mut rand::rng()).unwrap_or(&global_constants::FEE_RECIPIENT);
AccountMeta { pubkey: recipient, is_signer: false, is_writable: true }
}
/// Random entry from [`global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS`] (must be last account after bonding-curve-v2, writable).
#[inline]
pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
*global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS
@@ -329,17 +281,23 @@ pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
.unwrap_or(&global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
}
/// 账户 #2 fee recipient:优先使用 gRPC/ShredStream 解析值(同笔 create_v2+buy 的 `observed_fee_recipient` 或 `tradeEvent.feeRecipient`);未提供或与 `is_mayhem_mode` 池不一致时按 mayhem 从静态池随机(避免 NotAuthorized)。
/// Buyback fee recipient (#9 in buy_v2/sell_v2) — dedicated pool, distinct from protocol extra fee recipients.
#[inline]
pub fn pump_fun_fee_recipient_meta(from_stream: Pubkey, is_mayhem_mode: bool) -> AccountMeta {
let trust_stream = from_stream != Pubkey::default()
&& fee_recipient_ok_for_bonding_curve_mode(&from_stream, is_mayhem_mode);
if trust_stream {
AccountMeta {
pubkey: from_stream,
is_signer: false,
is_writable: true,
}
pub fn get_buyback_fee_recipient_random() -> Pubkey {
*global_constants::BUYBACK_FEE_RECIPIENTS
.choose(&mut rand::rng())
.unwrap_or(&global_constants::BUYBACK_FEE_RECIPIENTS[0])
}
#[inline]
pub fn pump_fun_fee_recipient_meta(
observed_fee_recipient: Pubkey,
is_mayhem_mode: bool,
) -> AccountMeta {
let trust_observation = observed_fee_recipient != Pubkey::default()
&& fee_recipient_ok_for_bonding_curve_mode(&observed_fee_recipient, is_mayhem_mode);
if trust_observation {
AccountMeta { pubkey: observed_fee_recipient, is_signer: false, is_writable: true }
} else if is_mayhem_mode {
get_mayhem_fee_recipient_meta_random()
} else {
@@ -347,12 +305,28 @@ pub fn pump_fun_fee_recipient_meta(from_stream: Pubkey, is_mayhem_mode: bool) ->
}
}
pub struct Symbol;
// --- Extend bonding curve (cold path) --------------------------------
impl Symbol {
pub const SOLANA: &'static str = "solana";
#[inline]
pub fn extend_bonding_curve_account_instruction(
bonding_curve: &Pubkey,
user: &Pubkey,
) -> Instruction {
Instruction::new_with_bytes(
accounts::PUMPFUN,
&EXTEND_ACCOUNT_DISCRIMINATOR,
vec![
AccountMeta::new(*bonding_curve, false),
AccountMeta::new(*user, true),
crate::constants::SYSTEM_PROGRAM_META,
accounts::EVENT_AUTHORITY_META,
accounts::PUMPFUN_META,
],
)
}
// --- Cached PDAs + creator_vault resolve ------------------------------
#[inline]
pub fn get_bonding_curve_pda(mint: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::get_cached_pda(
@@ -360,13 +334,11 @@ pub fn get_bonding_curve_pda(mint: &Pubkey) -> Option<Pubkey> {
|| {
let seeds: &[&[u8]; 2] = &[seeds::BONDING_CURVE_SEED, mint.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
Pubkey::try_find_program_address(seeds, program_id).map(|pubkey| pubkey.0)
},
)
}
/// Bonding curve v2 PDA (seeds: ["bonding-curve-v2", mint]). Required at end of buy/sell/buy_exact_sol_in accounts.
#[inline]
pub fn get_bonding_curve_v2_pda(mint: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::get_cached_pda(
@@ -374,8 +346,7 @@ pub fn get_bonding_curve_v2_pda(mint: &Pubkey) -> Option<Pubkey> {
|| {
let seeds: &[&[u8]; 2] = &[seeds::BONDING_CURVE_V2_SEED, mint.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
Pubkey::try_find_program_address(seeds, program_id).map(|pubkey| pubkey.0)
},
)
}
@@ -385,7 +356,6 @@ pub fn get_creator(creator_vault_pda: &Pubkey) -> Pubkey {
if creator_vault_pda.eq(&Pubkey::default()) {
Pubkey::default()
} else {
// 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()));
match DEFAULT_CREATOR_VAULT.as_ref() {
@@ -402,24 +372,25 @@ pub fn get_creator_vault_pda(creator: &Pubkey) -> Option<Pubkey> {
|| {
let seeds: &[&[u8]; 2] = &[seeds::CREATOR_VAULT_SEED, creator.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
Pubkey::try_find_program_address(seeds, program_id).map(|pubkey| pubkey.0)
},
)
}
/// `feeSharingConfig` PDA per mint (`pump-sdk` `feeSharingConfigPda` → `pump-fees` program).
#[inline]
pub fn get_fee_sharing_config_pda(mint: &Pubkey) -> Option<Pubkey> {
Pubkey::try_find_program_address(
&[seeds::SHARING_CONFIG_SEED, mint.as_ref()],
&accounts::FEE_PROGRAM,
crate::common::fast_fn::get_cached_pda(
crate::common::fast_fn::PdaCacheKey::PumpFunFeeSharingConfig(*mint),
|| {
Pubkey::try_find_program_address(
&[seeds::SHARING_CONFIG_SEED, mint.as_ref()],
&accounts::FEE_PROGRAM,
)
.map(|(p, _)| p)
},
)
.map(|(p, _)| p)
}
/// PDA of `["creator-vault", Pubkey::default()]`. Never use as a real vault — it is only produced when
/// `creator` was missing and code incorrectly derived a vault; on-chain this fails with Anchor 2006.
#[inline]
pub fn phantom_default_creator_vault() -> Pubkey {
solana_sdk::pubkey!("2DR3iqRPVThyRLVJnwjPW1qiGWrp8RUFfHVjMbZyhdNc")
@@ -430,21 +401,6 @@ pub fn is_phantom_default_creator_vault(pk: &Pubkey) -> bool {
*pk == phantom_default_creator_vault()
}
/// Resolve `creator_vault` for Pump buy/sell account #10.
///
/// - If `creator` is **missing** in the outer trade-event borsh (`Pubkey::default()`) but
/// `creator_vault` was filled from **instruction accounts** (e.g. `fill_trade_accounts` index 9),
/// **trust that vault** — unless it equals [`phantom_default_creator_vault`] (bad derivation / cache).
/// - If event `creator_vault` is **missing** → [`get_creator_vault_pda`]`(creator)` (never `PDA(default)`).
/// - If it **matches** `PDA(creator)` → use it (fast path).
/// - If **Creator Rewards Sharing is active** (`fee_sharing_creator_vault_if_active` / RPC) and the event
/// vault matches `PDA(["creator-vault", fee_sharing_config_pda])` → use it.
/// - If `fee_sharing_creator_vault_if_active` is **None**, do **not** trust a stale event vault that merely
/// equals the theoretical sharing-layout PDA — fall back to `PDA(creator)` (sharing may have migrated off).
/// - If the event vault is some other stale value but `creator` is correct → `PDA(creator)` (fixes 2006 Left≠Right).
///
/// For **Creator Rewards Sharing** (`fee_sharing_creator_vault_if_active`), prefer
/// [`resolve_creator_vault_for_ix_with_fee_sharing`] or [`fetch_fee_sharing_creator_vault_if_active`].
#[inline]
pub fn resolve_creator_vault_for_ix(
creator: &Pubkey,
@@ -454,78 +410,74 @@ pub fn resolve_creator_vault_for_ix(
resolve_creator_vault_for_ix_with_fee_sharing(creator, creator_vault_from_event, mint, None)
}
/// Same as [`resolve_creator_vault_for_ix`], but when `fee_sharing_creator_vault_if_active` is
/// `Some(PDA(["creator-vault", fee_sharing_config_pda(mint)]))` from an RPC hint, overrides stale
/// `PDA(creator)` so sell/buy match on-chain seeds (Anchor 2006).
/// Resolves Pump.fun bonding-curve buy/sell **account `#10` (`creator_vault`)** for ix assembly.
///
/// **Priority (highest first)**
/// 1. **Explicit `creator_vault`** from ix / parser / cached observation when non-default and not the phantom
/// sentinel — **always used as-is** (no remap to [`get_creator_vault_pda`] from `creator`);
/// fee-sharing / multi-party layouts rely on upstream passing the vault the program expects (`pfee…` / `update_fee_shares`).
/// 2. If ix vault missing: optional `fee_sharing_creator_vault_if_active` hint (non-default, non-phantom).
/// 3. Else: [`get_creator_vault_pda`] from `creator` when `creator` is known.
#[inline]
pub fn resolve_creator_vault_for_ix_with_fee_sharing(
creator: &Pubkey,
creator_vault_from_event: Pubkey,
mint: &Pubkey,
_mint: &Pubkey,
fee_sharing_creator_vault_if_active: Option<Pubkey>,
) -> Option<Pubkey> {
let phantom = phantom_default_creator_vault();
let fee_sharing_vault: Option<Pubkey> = fee_sharing_creator_vault_if_active.and_then(|v| {
let sharing_pk = get_fee_sharing_config_pda(mint)?;
let expected = get_creator_vault_pda(&sharing_pk)?;
if v == expected { Some(v) } else { None }
});
if creator_vault_from_event != Pubkey::default() && creator_vault_from_event != phantom {
return Some(creator_vault_from_event);
}
if let Some(v) = fee_sharing_creator_vault_if_active {
if v != Pubkey::default() && v != phantom {
return Some(v);
}
}
if *creator == Pubkey::default() {
if creator_vault_from_event == Pubkey::default() {
return None;
}
if creator_vault_from_event == phantom {
return None;
}
return Some(creator_vault_from_event);
return None;
}
if creator_vault_from_event == phantom {
if let Some(vs) = fee_sharing_vault {
let v_derived = get_creator_vault_pda(creator)?;
if vs != v_derived {
return Some(vs);
}
}
return get_creator_vault_pda(creator);
}
let v_derived = get_creator_vault_pda(creator)?;
if let Some(vs) = fee_sharing_vault {
if vs != v_derived
&& (creator_vault_from_event == Pubkey::default()
|| creator_vault_from_event == v_derived
|| creator_vault_from_event != vs)
{
return Some(vs);
}
}
if creator_vault_from_event == Pubkey::default() {
return Some(v_derived);
}
if creator_vault_from_event == v_derived {
return Some(creator_vault_from_event);
}
// 仅当 RPC / 调用方已确认 Creator Rewards Sharing **仍 Active**hint 为 Some)时,才信任
// `creator_vault == PDA(["creator-vault", fee_sharing_config])`。hint 为 None 时可能是「已停用」或从未拉取:
// 此时旧缓存里的 fee-sharing vault 必须回退到 `PDA(creator)`,否则易与链上 seeds 不一致(2006)。
if fee_sharing_creator_vault_if_active.is_some() {
if let Some(sharing) = get_fee_sharing_config_pda(mint) {
let v_sharing = get_creator_vault_pda(&sharing)?;
if creator_vault_from_event == v_sharing {
return Some(creator_vault_from_event);
}
}
}
Some(v_derived)
get_creator_vault_pda(creator)
}
/// Read pump-fees `SharingConfig` for `mint`; if **Active** and `mint` matches, return
/// `PDA(["creator-vault", fee_sharing_config_pda])` on Pump program (same as npm `pump-sdk`).
#[inline]
pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::get_cached_pda(
crate::common::fast_fn::PdaCacheKey::PumpFunUserVolume(*user),
|| {
let seed: &[&[u8]; 2] = &[seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
Pubkey::try_find_program_address(seed, program_id).map(|pubkey| pubkey.0)
},
)
}
#[inline]
pub fn get_buy_price(
amount: u64,
virtual_sol_reserves: u64,
virtual_token_reserves: u64,
real_token_reserves: u64,
) -> u64 {
if amount == 0 {
return 0;
}
let n: u128 = (virtual_sol_reserves as u128) * (virtual_token_reserves as u128);
let i: u128 = (virtual_sol_reserves as u128) + (amount as u128);
let r: u128 = n / i + 1;
let s: u128 = (virtual_token_reserves as u128) - r;
let s_u64 = s as u64;
s_u64.min(real_token_reserves)
}
// --- RPC -------------------------------------------------------------
#[inline]
pub async fn fetch_fee_sharing_creator_vault_if_active(
rpc: &SolanaRpcClient,
@@ -549,9 +501,7 @@ pub async fn fetch_fee_sharing_creator_vault_if_active(
return Ok(None);
}
let mint_on_chain = Pubkey::new_from_array(
d[11..43]
.try_into()
.map_err(|_| anyhow::anyhow!("SharingConfig mint slice"))?,
d[11..43].try_into().map_err(|_| anyhow!("SharingConfig mint slice"))?,
);
if mint_on_chain != *mint {
return Ok(None);
@@ -559,62 +509,37 @@ pub async fn fetch_fee_sharing_creator_vault_if_active(
Ok(get_creator_vault_pda(&config_pda))
}
#[inline]
pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
crate::common::fast_fn::get_cached_pda(
crate::common::fast_fn::PdaCacheKey::PumpFunUserVolume(*user),
|| {
let seeds: &[&[u8]; 2] = &[seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
let program_id: &Pubkey = &accounts::PUMPFUN;
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
pda.map(|pubkey| pubkey.0)
},
)
}
#[inline]
pub async fn fetch_bonding_curve_account(
rpc: &SolanaRpcClient,
mint: &Pubkey,
) -> Result<(Arc<BondingCurveAccount>, Pubkey), anyhow::Error> {
let bonding_curve_pda: Pubkey =
get_bonding_curve_pda(mint).ok_or(anyhow!("Bonding curve not found"))?;
get_bonding_curve_pda(mint).ok_or_else(|| anyhow!("Bonding curve not found"))?;
let account = rpc.get_account(&bonding_curve_pda).await?;
if account.data.is_empty() {
return Err(anyhow!("Bonding curve not found"));
}
let bonding_curve =
solana_sdk::borsh1::try_from_slice_unchecked::<BondingCurveAccount>(&account.data[8..])
.map_err(|e| anyhow::anyhow!("Failed to deserialize bonding curve account: {}", e))?;
// Use `deserialize` instead of `try_from_slice` so that extra trailing bytes
// (from on-chain schema additions like new fields) are silently ignored.
// `try_from_slice` requires the entire slice to be consumed, causing
// "Not all bytes read" when the account has been extended.
let mut bonding_curve = BondingCurveAccount::deserialize(&mut &account.data[8..])
.map_err(|e| anyhow::anyhow!("Failed to decode bonding curve account: {}", e))?;
bonding_curve.account = bonding_curve_pda;
Ok((Arc::new(bonding_curve), bonding_curve_pda))
}
#[inline]
pub fn get_buy_price(
amount: u64,
virtual_sol_reserves: u64,
virtual_token_reserves: u64,
real_token_reserves: u64,
) -> u64 {
if amount == 0 {
return 0;
}
let n: u128 = (virtual_sol_reserves as u128) * (virtual_token_reserves as u128);
let i: u128 = (virtual_sol_reserves as u128) + (amount as u128);
let r: u128 = n / i + 1;
let s: u128 = (virtual_token_reserves as u128) - r;
let s_u64 = s as u64;
s_u64.min(real_token_reserves)
}
#[cfg(test)]
mod tests {
use super::*;
use super::{
global_constants, phantom_default_creator_vault, pump_fun_fee_recipient_meta,
reconcile_mayhem_mode_for_trade, resolve_creator_vault_for_ix,
resolve_creator_vault_for_ix_with_fee_sharing, *,
};
use solana_sdk::pubkey::Pubkey;
#[test]
@@ -622,6 +547,9 @@ mod tests {
assert_eq!(BUY_DISCRIMINATOR.len(), 8);
assert_eq!(BUY_EXACT_SOL_IN_DISCRIMINATOR.len(), 8);
assert_eq!(SELL_DISCRIMINATOR.len(), 8);
assert_eq!(BUY_V2_DISCRIMINATOR.len(), 8);
assert_eq!(SELL_V2_DISCRIMINATOR.len(), 8);
assert_eq!(BUY_EXACT_QUOTE_IN_V2_DISCRIMINATOR.len(), 8);
}
#[test]
@@ -651,7 +579,11 @@ mod tests {
#[test]
fn default_creator_yields_fixed_creator_vault() {
let v = get_creator_vault_pda(&Pubkey::default()).unwrap();
assert_eq!(v, phantom_default_creator_vault(), "phantom vault constant must match PDA(default creator)");
assert_eq!(
v,
phantom_default_creator_vault(),
"phantom vault constant must match PDA(default creator)"
);
}
#[test]
@@ -675,26 +607,46 @@ mod tests {
fn resolve_rejects_phantom_vault_when_creator_borsh_is_default() {
let mint = Pubkey::new_unique();
assert_eq!(
resolve_creator_vault_for_ix(&Pubkey::default(), phantom_default_creator_vault(), &mint),
resolve_creator_vault_for_ix(
&Pubkey::default(),
phantom_default_creator_vault(),
&mint,
),
None
);
}
#[test]
fn resolve_prefers_fee_sharing_vault_when_rpc_hint_and_differs_from_creator_pda() {
fn resolve_prefers_creator_pda_ix_vault_even_when_fee_sharing_hint_differs() {
let creator = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let v_derived = get_creator_vault_pda(&creator).unwrap();
let sharing_pk = get_fee_sharing_config_pda(&mint).unwrap();
let vs = get_creator_vault_pda(&sharing_pk).unwrap();
assert_ne!(v_derived, vs);
let resolved = resolve_creator_vault_for_ix_with_fee_sharing(
&creator,
v_derived,
&mint,
Some(vs),
let resolved =
resolve_creator_vault_for_ix_with_fee_sharing(&creator, v_derived, &mint, Some(vs));
assert_eq!(
resolved,
Some(v_derived),
"observed ix uses PDA(creator); stale hint must not override → wrong vault / Anchor 2006"
);
}
#[test]
fn resolve_trusts_ix_fee_sharing_vault_when_creator_known() {
let creator = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let sharing_pk = get_fee_sharing_config_pda(&mint).unwrap();
let vs = get_creator_vault_pda(&sharing_pk).unwrap();
let creator_vault = get_creator_vault_pda(&creator).unwrap();
assert_ne!(vs, creator_vault);
let resolved = resolve_creator_vault_for_ix_with_fee_sharing(&creator, vs, &mint, Some(vs));
assert_eq!(
resolved,
Some(vs),
"explicit ix creator_vault (e.g. fee-sharing #8) wins; no remap to PDA(creator)"
);
assert_eq!(resolved, Some(vs));
}
#[test]
@@ -709,7 +661,19 @@ mod tests {
}
#[test]
fn resolve_stale_fee_sharing_vault_falls_back_to_creator_pda_when_hint_inactive() {
fn resolve_ix_vault_always_wins_when_non_default_even_if_creator_pda_differs() {
let creator = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let v_derived = get_creator_vault_pda(&creator).unwrap();
let ix_other = Pubkey::new_unique();
assert_ne!(ix_other, v_derived);
let resolved =
resolve_creator_vault_for_ix_with_fee_sharing(&creator, ix_other, &mint, None);
assert_eq!(resolved, Some(ix_other));
}
#[test]
fn resolve_fee_sharing_ix_vault_used_as_is_even_without_hint() {
let creator = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let v_derived = get_creator_vault_pda(&creator).unwrap();
@@ -717,11 +681,22 @@ mod tests {
let vs = get_creator_vault_pda(&sharing_pk).unwrap();
assert_ne!(v_derived, vs);
let resolved = resolve_creator_vault_for_ix_with_fee_sharing(&creator, vs, &mint, None);
assert_eq!(
resolved,
Some(v_derived),
"hint None: stale sharing-layout vault in cache must not win over PDA(creator)"
assert_eq!(resolved, Some(vs));
}
#[test]
fn resolve_falls_back_to_fee_sharing_hint_when_ix_vault_placeholder() {
let creator = Pubkey::new_unique();
let mint = Pubkey::new_unique();
let sharing_pk = get_fee_sharing_config_pda(&mint).unwrap();
let vs = get_creator_vault_pda(&sharing_pk).unwrap();
let resolved = resolve_creator_vault_for_ix_with_fee_sharing(
&creator,
Pubkey::default(),
&mint,
Some(vs),
);
assert_eq!(resolved, Some(vs));
}
#[test]
@@ -746,4 +721,13 @@ mod tests {
m.pubkey
);
}
#[test]
fn pump_fee_meta_uses_observed_standard_fee_for_standard_ix() {
let fee = global_constants::PUMPFUN_AMM_FEE_7;
let m = pump_fun_fee_recipient_meta(fee, false);
assert_eq!(m.pubkey, fee);
assert!(m.is_writable);
assert!(!m.is_signer);
}
}
+194 -31
View File
@@ -6,9 +6,14 @@ use crate::{
instruction::utils::pumpswap_types::{pool_decode, Pool},
};
use anyhow::anyhow;
use once_cell::sync::Lazy;
use parking_lot::RwLock;
use rand::seq::IndexedRandom;
use solana_account_decoder::UiAccountEncoding;
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
use std::sync::Arc;
use std::time::{Duration, Instant};
use tracing::warn;
// Pool account sizes moved to find_by_base_mint/find_by_quote_mint (POOL_DATA_LEN_SPL, POOL_DATA_LEN_T22)
@@ -175,22 +180,180 @@ 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];
const PUMPSWAP_GLOBAL_CONFIG_TTL: Duration = Duration::from_secs(90);
const PUMPSWAP_GLOBAL_CONFIG_RPC_TIMEOUT: Duration = Duration::from_millis(180);
const PUBKEY_LEN: usize = 32;
const U64_LEN: usize = 8;
const U8_LEN: usize = 1;
const BOOL_LEN: usize = 1;
const GLOBAL_CONFIG_DISCRIMINATOR_LEN: usize = 8;
#[derive(Clone, Debug)]
pub struct GlobalConfig {
pub protocol_fee_recipients: [Pubkey; 8],
pub reserved_fee_recipient: Pubkey,
pub reserved_fee_recipients: [Pubkey; 7],
pub buyback_fee_recipients: [Pubkey; 8],
}
#[derive(Clone)]
struct CachedGlobalConfig {
fetched_at: Instant,
config: GlobalConfig,
}
static GLOBAL_CONFIG_CACHE: Lazy<RwLock<Option<CachedGlobalConfig>>> =
Lazy::new(|| RwLock::new(None));
fn read_pubkey(data: &[u8], offset: usize) -> Option<Pubkey> {
let bytes = data.get(offset..offset + PUBKEY_LEN)?;
Some(Pubkey::new_from_array(bytes.try_into().ok()?))
}
fn read_pubkey_array<const N: usize>(data: &[u8], offset: usize) -> Option<[Pubkey; N]> {
let mut keys = [Pubkey::default(); N];
for (i, key) in keys.iter_mut().enumerate() {
*key = read_pubkey(data, offset + i * PUBKEY_LEN)?;
}
Some(keys)
}
fn decode_global_config(data: &[u8]) -> Option<GlobalConfig> {
let mut offset = GLOBAL_CONFIG_DISCRIMINATOR_LEN;
offset += PUBKEY_LEN; // admin
offset += U64_LEN * 2; // lp_fee_basis_points + protocol_fee_basis_points
offset += U8_LEN; // disable_flags
let protocol_fee_recipients = read_pubkey_array::<8>(data, offset)?;
offset += PUBKEY_LEN * 8;
offset += U64_LEN; // coin_creator_fee_basis_points
offset += PUBKEY_LEN; // admin_set_coin_creator_authority
offset += PUBKEY_LEN; // whitelist_pda
let reserved_fee_recipient = read_pubkey(data, offset)?;
offset += PUBKEY_LEN;
offset += BOOL_LEN; // mayhem_mode_enabled
let reserved_fee_recipients = read_pubkey_array::<7>(data, offset)?;
offset += PUBKEY_LEN * 7;
offset += BOOL_LEN; // is_cashback_enabled
let buyback_fee_recipients = read_pubkey_array::<8>(data, offset)?;
Some(GlobalConfig {
protocol_fee_recipients,
reserved_fee_recipient,
reserved_fee_recipients,
buyback_fee_recipients,
})
}
async fn refresh_global_config_once(rpc: &SolanaRpcClient) -> Option<GlobalConfig> {
let account = match tokio::time::timeout(
PUMPSWAP_GLOBAL_CONFIG_RPC_TIMEOUT,
rpc.get_account(&accounts::GLOBAL_ACCOUNT),
)
.await
{
Ok(Ok(account)) => account,
Ok(Err(e)) => {
warn!(target: "pumpswap_global_config", "PumpSwap GlobalConfig 读取失败: {}", e);
return None;
}
Err(_) => {
warn!(
target: "pumpswap_global_config",
timeout_ms = PUMPSWAP_GLOBAL_CONFIG_RPC_TIMEOUT.as_millis(),
"PumpSwap GlobalConfig 读取超时"
);
return None;
}
};
let Some(config) = decode_global_config(&account.data) else {
warn!(
target: "pumpswap_global_config",
data_len = account.data.len(),
"PumpSwap GlobalConfig 解析失败"
);
return None;
};
*GLOBAL_CONFIG_CACHE.write() =
Some(CachedGlobalConfig { fetched_at: Instant::now(), config: config.clone() });
Some(config)
}
pub async fn warm_pumpswap_global_config(rpc: Option<&Arc<SolanaRpcClient>>) {
let Some(rpc) = rpc else {
return;
};
let stale = GLOBAL_CONFIG_CACHE
.read()
.as_ref()
.map(|c| c.fetched_at.elapsed() > PUMPSWAP_GLOBAL_CONFIG_TTL)
.unwrap_or(true);
if stale {
let _ = refresh_global_config_once(rpc.as_ref()).await;
}
}
fn cached_global_config() -> Option<GlobalConfig> {
let guard = GLOBAL_CONFIG_CACHE.read();
let cached = guard.as_ref()?;
(cached.fetched_at.elapsed() <= PUMPSWAP_GLOBAL_CONFIG_TTL).then(|| cached.config.clone())
}
fn choose_nonzero(keys: &[Pubkey]) -> Option<Pubkey> {
let mut valid = [Pubkey::default(); 8];
let mut len = 0;
for key in keys.iter().copied() {
if key == Pubkey::default() || len == valid.len() {
continue;
}
valid[len] = key;
len += 1;
}
valid[..len].choose(&mut rand::rng()).copied()
}
/// 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 recipient = cached_global_config()
.and_then(|config| {
let mut pool = [Pubkey::default(); 8];
pool[0] = config.reserved_fee_recipient;
pool[1..].copy_from_slice(&config.reserved_fee_recipients);
choose_nonzero(&pool)
})
.unwrap_or_else(|| {
*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)
}
#[inline]
pub fn get_protocol_fee_recipient_random() -> Pubkey {
cached_global_config()
.and_then(|config| choose_nonzero(&config.protocol_fee_recipients))
.unwrap_or(accounts::FEE_RECIPIENT)
}
/// Random entry from [`accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS`] (readonly; paired with [`fee_recipient_ata`] as last account).
#[inline]
pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
*accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS
.choose(&mut rand::rng())
.unwrap_or(&accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
cached_global_config()
.and_then(|config| choose_nonzero(&config.buyback_fee_recipients))
.unwrap_or_else(|| {
*accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS
.choose(&mut rand::rng())
.unwrap_or(&accounts::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
})
}
/// Pool v2 PDA (seeds: ["pool-v2", base_mint]). Required at end of buy/sell/buy_exact_quote_in accounts.
@@ -331,23 +494,21 @@ async fn get_program_accounts_both_sizes(
memcmp_offset: usize,
mint: &Pubkey,
) -> Result<Vec<(Pubkey, solana_sdk::account::Account)>, anyhow::Error> {
let make_config = |data_size: u64| {
solana_rpc_client_api::config::RpcProgramAccountsConfig {
filters: Some(vec![
solana_rpc_client_api::filter::RpcFilterType::DataSize(data_size),
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
solana_client::rpc_filter::Memcmp::new_base58_encoded(memcmp_offset, mint.as_ref()),
),
]),
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64),
data_slice: None,
commitment: None,
min_context_slot: None,
},
with_context: None,
sort_results: None,
}
let make_config = |data_size: u64| solana_rpc_client_api::config::RpcProgramAccountsConfig {
filters: Some(vec![
solana_rpc_client_api::filter::RpcFilterType::DataSize(data_size),
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
solana_client::rpc_filter::Memcmp::new_base58_encoded(memcmp_offset, mint.as_ref()),
),
]),
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
encoding: Some(UiAccountEncoding::Base64),
data_slice: None,
commitment: None,
min_context_slot: None,
},
with_context: None,
sort_results: None,
};
let program_id = accounts::AMM_PROGRAM;
#[allow(deprecated)]
@@ -360,7 +521,9 @@ async fn get_program_accounts_both_sizes(
Ok(all)
}
fn decode_pool_accounts(accounts: Vec<(Pubkey, solana_sdk::account::Account)>) -> Vec<(Pubkey, Pool)> {
fn decode_pool_accounts(
accounts: Vec<(Pubkey, solana_sdk::account::Account)>,
) -> Vec<(Pubkey, Pool)> {
accounts
.into_iter()
.filter_map(|(addr, acc)| {
@@ -439,12 +602,16 @@ pub async fn find_by_mint(
}
// 3. Fallback: getProgramAccounts by base_mint / quote_mint (with 3s timeout to avoid blocking)
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_base_mint(rpc, mint)).await {
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_base_mint(rpc, mint))
.await
{
Ok(Ok((address, pool))) => return Ok((address, pool)),
Ok(Err(e)) => diag.push(format!("getProgramAccounts(base_mint): {}", e)),
Err(_) => diag.push("getProgramAccounts(base_mint): timed out (3s)".into()),
}
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_quote_mint(rpc, mint)).await {
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_quote_mint(rpc, mint))
.await
{
Ok(Ok((address, pool))) => return Ok((address, pool)),
Ok(Err(e)) => diag.push(format!("getProgramAccounts(quote_mint): {}", e)),
Err(_) => diag.push("getProgramAccounts(quote_mint): timed out (3s)".into()),
@@ -452,11 +619,7 @@ pub async fn find_by_mint(
let diag_str = diag.join("; ");
eprintln!("[find_by_mint] {} failed: {}", mint, diag_str);
Err(anyhow!(
"No pool found for mint {}. diag: {}",
mint,
diag_str
))
Err(anyhow!("No pool found for mint {}. diag: {}", mint, diag_str))
}
pub async fn get_token_balances(
+4 -4
View File
@@ -447,23 +447,23 @@ impl BranchOptimizer {
/// Prefetch: load cache line at ptr into L1. Caller must ensure ptr is valid, read-only, no concurrent write. 预取:将 ptr 所在缓存行加载到 L1;调用方需保证有效、只读、无并发写。
#[inline(always)]
pub unsafe fn prefetch_read_data<T>(ptr: *const T) {
pub unsafe fn prefetch_read_data<T>(_ptr: *const T) {
#[cfg(target_arch = "x86_64")]
{
use std::arch::x86_64::_mm_prefetch;
use std::arch::x86_64::_MM_HINT_T0;
_mm_prefetch(ptr as *const i8, _MM_HINT_T0);
_mm_prefetch(_ptr as *const i8, _MM_HINT_T0);
}
}
/// Prefetch for write (T1 hint). 写预取(T1 提示)。
#[inline(always)]
pub unsafe fn prefetch_write_data<T>(ptr: *const T) {
pub unsafe fn prefetch_write_data<T>(_ptr: *const T) {
#[cfg(target_arch = "x86_64")]
{
use std::arch::x86_64::_mm_prefetch;
use std::arch::x86_64::_MM_HINT_T1;
_mm_prefetch(ptr as *const i8, _MM_HINT_T1);
_mm_prefetch(_ptr as *const i8, _MM_HINT_T1);
}
}
}
+36 -6
View File
@@ -202,11 +202,20 @@ impl AstralaneClient {
let _ = response.bytes().await;
if status.is_success() {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submitted("Astralane", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"Astralane",
trade_type,
start_time.elapsed(),
);
}
} else {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("Astralane", trade_type, start_time.elapsed(), format!("status {}", status));
crate::common::sdk_log::log_swqos_submission_failed(
"Astralane",
trade_type,
start_time.elapsed(),
format!("status {}", status),
);
}
return Err(anyhow::anyhow!("Astralane sendTransaction failed: {}", status));
}
@@ -214,12 +223,21 @@ impl AstralaneClient {
AstralaneBackend::Quic(quic) => {
if let Err(e) = quic.send_transaction(&body_bytes).await {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("Astralane", trade_type, start_time.elapsed(), &e);
crate::common::sdk_log::log_swqos_submission_failed(
"Astralane",
trade_type,
start_time.elapsed(),
&e,
);
}
return Err(e);
}
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submitted("Astralane", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"Astralane",
trade_type,
start_time.elapsed(),
);
}
}
}
@@ -230,14 +248,26 @@ impl AstralaneClient {
Err(e) => {
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmation failed: {:?}", "Astralane", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmation failed: {:?}",
"Astralane",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
return Err(e);
}
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "Astralane", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"Astralane",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
}
+7 -7
View File
@@ -77,9 +77,7 @@ impl AstralaneQuicClient {
"lit.gateway.astralane.io" => {
vec![SocketAddr::new(IpAddr::V4(Ipv4Addr::new(84, 32, 97, 47)), port)]
}
_ => {
Vec::new()
}
_ => Vec::new(),
}
}
@@ -132,8 +130,8 @@ impl AstralaneQuicClient {
/// Generates a self-signed TLS certificate with the API key as the Common Name (CN).
pub async fn connect(server_addr: &str, api_key: &str) -> Result<Self> {
let _ = rustls::crypto::ring::default_provider().install_default();
let candidates = Self::resolve_server_candidates(server_addr)
.context("Invalid server address")?;
let candidates =
Self::resolve_server_candidates(server_addr).context("Invalid server address")?;
let addr = candidates[0];
info!("[astralane-quic] Building TLS config (CN = api_key)");
@@ -167,7 +165,8 @@ impl AstralaneQuicClient {
}
}
let connection = connection_opt.ok_or_else(|| {
last_err.unwrap_or_else(|| anyhow::anyhow!("Failed to connect to Astralane QUIC server"))
last_err
.unwrap_or_else(|| anyhow::anyhow!("Failed to connect to Astralane QUIC server"))
})?;
info!("[astralane-quic] Connected at {}", selected_addr);
@@ -203,7 +202,8 @@ impl AstralaneQuicClient {
}
}
}
Err(last_err.unwrap_or_else(|| anyhow::anyhow!("Failed to reconnect to Astralane QUIC server")))
Err(last_err
.unwrap_or_else(|| anyhow::anyhow!("Failed to reconnect to Astralane QUIC server")))
}
/// Send a single bincode-serialized `VersionedTransaction`.
+93 -46
View File
@@ -5,9 +5,9 @@ use rand::seq::IndexedRandom;
use reqwest::Client;
use std::{sync::Arc, time::Instant};
use arc_swap::ArcSwap;
use solana_transaction_status::UiTransactionEncoding;
use std::time::Duration;
use arc_swap::ArcSwap;
use crate::swqos::SwqosClientTrait;
use crate::swqos::{SwqosType, TradeType};
@@ -18,8 +18,8 @@ use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
use std::sync::atomic::{AtomicBool, Ordering};
use tokio::task::JoinHandle;
use tonic::transport::Channel;
use tonic::metadata::AsciiMetadataValue;
use tonic::transport::Channel;
// Include pre-generated gRPC code
pub mod serverpb {
@@ -46,7 +46,9 @@ impl BlockRazorGrpcClient {
let mut request = tonic::Request::new(serverpb::HealthRequest {});
request.metadata_mut().insert("apikey", apikey);
let response = client.get_health(request).await
let response = client
.get_health(request)
.await
.map_err(|e| anyhow::anyhow!("gRPC health check failed: {}", e))?;
Ok(response.into_inner().status)
}
@@ -75,7 +77,9 @@ impl BlockRazorGrpcClient {
});
request.metadata_mut().insert("apikey", apikey);
let response = client.send_transaction(request).await
let response = client
.send_transaction(request)
.await
.map_err(|e| anyhow::anyhow!("gRPC send transaction failed: {}", e))?;
Ok(response.into_inner().signature)
}
@@ -151,7 +155,12 @@ impl BlockRazorClient {
Ok(Self::new_http(rpc_url, endpoint, auth_token, false))
}
pub async fn new_grpc(rpc_url: String, endpoint: String, auth_token: String, mev_protection: bool) -> Result<Self> {
pub async fn new_grpc(
rpc_url: String,
endpoint: String,
auth_token: String,
mev_protection: bool,
) -> Result<Self> {
let rpc_client = SolanaRpcClient::new(rpc_url);
// 配置 Channel,增加连接超时
@@ -162,10 +171,8 @@ impl BlockRazorClient {
.await
.map_err(|e| anyhow::anyhow!("Failed to connect to gRPC endpoint: {}", e))?;
let grpc_client = Arc::new(ArcSwap::from_pointee(BlockRazorGrpcClient::new(
channel,
auth_token.clone(),
)));
let grpc_client =
Arc::new(ArcSwap::from_pointee(BlockRazorGrpcClient::new(channel, auth_token.clone())));
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
let stop_ping = Arc::new(AtomicBool::new(false));
@@ -189,7 +196,12 @@ impl BlockRazorClient {
Ok(client)
}
pub fn new_http(rpc_url: String, endpoint: String, auth_token: String, mev_protection: bool) -> Self {
pub fn new_http(
rpc_url: String,
endpoint: String,
auth_token: String,
mev_protection: bool,
) -> Self {
let rpc_client = SolanaRpcClient::new(rpc_url);
let http_client = default_http_client_builder().user_agent("").build().unwrap();
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
@@ -279,7 +291,10 @@ impl BlockRazorClient {
}
Err(reconnect_err) => {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("BlockRazor gRPC reconnect failed: {}", reconnect_err);
eprintln!(
"BlockRazor gRPC reconnect failed: {}",
reconnect_err
);
}
}
}
@@ -309,7 +324,8 @@ impl BlockRazorClient {
let stop_ping = stop_ping.clone();
let handle = tokio::spawn(async move {
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await {
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await
{
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("BlockRazor HTTP ping request failed: {}", e);
}
@@ -320,7 +336,9 @@ impl BlockRazorClient {
if stop_ping.load(Ordering::Relaxed) {
break;
}
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await {
if let Err(e) =
Self::send_http_ping(&http_client, &endpoint, &auth_token).await
{
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("BlockRazor HTTP ping request failed: {}", e);
}
@@ -337,11 +355,7 @@ impl BlockRazorClient {
}
}
async fn send_http_ping(
http_client: &Client,
endpoint: &str,
auth_token: &str,
) -> Result<()> {
async fn send_http_ping(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
let ping_url = endpoint.replace("/v2/sendTransaction", "/v2/health");
let response = http_client
.post(&ping_url)
@@ -380,56 +394,73 @@ impl BlockRazorClient {
let start_time = Instant::now();
match &self.backend {
BlockRazorBackend::Grpc {
grpc_client,
mev_protection,
..
} => {
BlockRazorBackend::Grpc { grpc_client, mev_protection, .. } => {
let (content, _signature) =
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
// 使用 load() 无锁获取客户端引用
let client = grpc_client.load();
let signature = client.send_transaction(
content,
// mev_protection=true: sandwichMitigation mode skips blacklisted Leader slots (MEV protection).
// revert_protection is unrelated to MEV; keep false.
if *mev_protection { "sandwichMitigation".to_string() } else { "fast".to_string() },
None,
false,
).await;
let signature = client
.send_transaction(
content,
// mev_protection=true: sandwichMitigation mode skips blacklisted Leader slots (MEV protection).
// revert_protection is unrelated to MEV; keep false.
if *mev_protection {
"sandwichMitigation".to_string()
} else {
"fast".to_string()
},
None,
false,
)
.await;
match signature {
Ok(sig) => {
if !sig.is_empty() {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submitted("BlockRazor", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"BlockRazor",
trade_type,
start_time.elapsed(),
);
}
} else {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), "empty signature".to_string());
crate::common::sdk_log::log_swqos_submission_failed(
"BlockRazor",
trade_type,
start_time.elapsed(),
"empty signature".to_string(),
);
}
return Err(anyhow::anyhow!("BlockRazor gRPC returned empty signature"));
return Err(anyhow::anyhow!(
"BlockRazor gRPC returned empty signature"
));
}
}
Err(e) => {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), format!("gRPC error: {}", e));
crate::common::sdk_log::log_swqos_submission_failed(
"BlockRazor",
trade_type,
start_time.elapsed(),
format!("gRPC error: {}", e),
);
}
return Err(anyhow::anyhow!("BlockRazor gRPC sendTransaction failed: {}", e));
return Err(anyhow::anyhow!(
"BlockRazor gRPC sendTransaction failed: {}",
e
));
}
}
}
BlockRazorBackend::Http {
endpoint,
auth_token,
http_client,
mev_protection,
..
endpoint, auth_token, http_client, mev_protection, ..
} => {
let (content, _signature) =
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
let mut query_params: Vec<(&str, &str)> = vec![
let query_params: Vec<(&str, &str)> = vec![
("auth", auth_token.as_str()),
// mev_protection=true: sandwichMitigation mode skips blacklisted Leader slots (MEV protection).
// revertProtection is unrelated to MEV; not set.
@@ -448,12 +479,21 @@ impl BlockRazorClient {
if status.is_success() {
let _ = response.bytes().await;
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submitted("blockrazor", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"blockrazor",
trade_type,
start_time.elapsed(),
);
}
} else {
let body = response.text().await.unwrap_or_default();
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("blockrazor", trade_type, start_time.elapsed(), format!("status {} body: {}", status, body));
crate::common::sdk_log::log_swqos_submission_failed(
"blockrazor",
trade_type,
start_time.elapsed(),
format!("status {} body: {}", status, body),
);
}
return Err(anyhow::anyhow!(
"BlockRazor HTTP sendTransaction failed: status {} body: {}",
@@ -485,7 +525,13 @@ impl BlockRazorClient {
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "blockrazor", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"blockrazor",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
@@ -495,7 +541,8 @@ impl BlockRazorClient {
impl Drop for BlockRazorClient {
fn drop(&mut self) {
match &self.backend {
BlockRazorBackend::Grpc { stop_ping, ping_handle, .. } | BlockRazorBackend::Http { stop_ping, ping_handle, .. } => {
BlockRazorBackend::Grpc { stop_ping, ping_handle, .. }
| BlockRazorBackend::Http { stop_ping, ping_handle, .. } => {
stop_ping.store(true, Ordering::Relaxed);
let ping_handle = ping_handle.clone();
+30 -5
View File
@@ -100,13 +100,27 @@ impl BloxrouteClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("bloxroute", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"bloxroute",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [bloxroute] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" [bloxroute] {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
}
} else if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("bloxroute", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"bloxroute",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -128,7 +142,13 @@ impl BloxrouteClient {
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "bloxroute", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"bloxroute",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
@@ -170,7 +190,12 @@ impl BloxrouteClient {
if response_json.get("result").is_some() {
println!(" bloxroute {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" bloxroute {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" bloxroute {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
}
}
+24 -4
View File
@@ -97,12 +97,26 @@ impl FlashBlockClient {
// Parse response
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("success").is_some() || response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("FlashBlock", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"FlashBlock",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [FlashBlock] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" [FlashBlock] {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("FlashBlock", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"FlashBlock",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -122,7 +136,13 @@ impl FlashBlockClient {
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "FlashBlock", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"FlashBlock",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+28 -5
View File
@@ -107,7 +107,10 @@ impl HeliusClient {
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!(
" [helius] {} submission failed after {:?} status={} body={}",
trade_type, start_time.elapsed(), status, response_text
trade_type,
start_time.elapsed(),
status,
response_text
);
}
return Err(anyhow::anyhow!(
@@ -124,15 +127,29 @@ impl HeliusClient {
.and_then(|v| v.as_str())
.unwrap_or("unknown");
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("helius", trade_type, start_time.elapsed(), err_msg);
crate::common::sdk_log::log_swqos_submission_failed(
"helius",
trade_type,
start_time.elapsed(),
err_msg,
);
}
return Err(anyhow::anyhow!("Helius Sender error: {}", err_msg));
}
if response_json.get("result").is_some() && crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submitted("helius", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"helius",
trade_type,
start_time.elapsed(),
);
}
} else if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("helius", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"helius",
trade_type,
start_time.elapsed(),
response_text,
);
}
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
@@ -152,7 +169,13 @@ impl HeliusClient {
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "helius", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"helius",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
}
+37 -6
View File
@@ -105,12 +105,26 @@ impl JitoClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("jito", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"jito",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [jito] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" [jito] {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("jito", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"jito",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -118,13 +132,25 @@ impl JitoClient {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmation failed: {:?}", "jito", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmation failed: {:?}",
"jito",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
return Err(e);
}
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "jito", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"jito",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
@@ -171,7 +197,12 @@ impl JitoClient {
if response_json.get("result").is_some() {
println!(" jito {} submitted: {:?}", trade_type, start_time.elapsed());
} else if let Some(_error) = response_json.get("error") {
eprintln!(" jito {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" jito {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
}
+24 -4
View File
@@ -103,12 +103,26 @@ impl LightspeedClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("lightspeed", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"lightspeed",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
crate::common::sdk_log::log_swqos_submission_failed("lightspeed", trade_type, start_time.elapsed(), _error);
crate::common::sdk_log::log_swqos_submission_failed(
"lightspeed",
trade_type,
start_time.elapsed(),
_error,
);
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("lightspeed", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"lightspeed",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -128,7 +142,13 @@ impl LightspeedClient {
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "lightspeed", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"lightspeed",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+30 -16
View File
@@ -30,17 +30,16 @@ use crate::{
constants::swqos::{
SWQOS_ENDPOINTS_ASTRALANE_BINARY, SWQOS_ENDPOINTS_ASTRALANE_PLAIN,
SWQOS_ENDPOINTS_ASTRALANE_QUIC, SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV,
SWQOS_ENDPOINTS_BLOCKRAZOR,
SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC, SWQOS_ENDPOINTS_BLOX, SWQOS_ENDPOINTS_FLASHBLOCK,
SWQOS_ENDPOINTS_HELIUS, SWQOS_ENDPOINTS_JITO, SWQOS_ENDPOINTS_NEXTBLOCK,
SWQOS_ENDPOINTS_NODE1, SWQOS_ENDPOINTS_NODE1_QUIC, SWQOS_ENDPOINTS_SOYAS,
SWQOS_ENDPOINTS_SPEEDLANDING, SWQOS_ENDPOINTS_STELLIUM, SWQOS_ENDPOINTS_TEMPORAL,
SWQOS_ENDPOINTS_ZERO_SLOT, SWQOS_MIN_TIP_ASTRALANE, SWQOS_MIN_TIP_BLOCKRAZOR,
SWQOS_MIN_TIP_BLOXROUTE, SWQOS_MIN_TIP_DEFAULT, SWQOS_MIN_TIP_FLASHBLOCK,
SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_JITO, SWQOS_MIN_TIP_LIGHTSPEED,
SWQOS_MIN_TIP_NEXTBLOCK, SWQOS_MIN_TIP_NODE1, SWQOS_MIN_TIP_SOYAS,
SWQOS_MIN_TIP_SPEEDLANDING, SWQOS_MIN_TIP_STELLIUM, SWQOS_MIN_TIP_TEMPORAL,
SWQOS_MIN_TIP_ZERO_SLOT,
SWQOS_ENDPOINTS_BLOCKRAZOR, SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC, SWQOS_ENDPOINTS_BLOX,
SWQOS_ENDPOINTS_FLASHBLOCK, SWQOS_ENDPOINTS_HELIUS, SWQOS_ENDPOINTS_JITO,
SWQOS_ENDPOINTS_NEXTBLOCK, SWQOS_ENDPOINTS_NODE1, SWQOS_ENDPOINTS_NODE1_QUIC,
SWQOS_ENDPOINTS_SOYAS, SWQOS_ENDPOINTS_SPEEDLANDING, SWQOS_ENDPOINTS_STELLIUM,
SWQOS_ENDPOINTS_TEMPORAL, SWQOS_ENDPOINTS_ZERO_SLOT, SWQOS_MIN_TIP_ASTRALANE,
SWQOS_MIN_TIP_BLOCKRAZOR, SWQOS_MIN_TIP_BLOXROUTE, SWQOS_MIN_TIP_DEFAULT,
SWQOS_MIN_TIP_FLASHBLOCK, SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_JITO,
SWQOS_MIN_TIP_LIGHTSPEED, SWQOS_MIN_TIP_NEXTBLOCK, SWQOS_MIN_TIP_NODE1,
SWQOS_MIN_TIP_SOYAS, SWQOS_MIN_TIP_SPEEDLANDING, SWQOS_MIN_TIP_STELLIUM,
SWQOS_MIN_TIP_TEMPORAL, SWQOS_MIN_TIP_ZERO_SLOT,
},
swqos::{
astralane::AstralaneClient, blockrazor::BlockRazorClient, bloxroute::BloxrouteClient,
@@ -411,15 +410,30 @@ impl SwqosConfig {
SwqosConfig::BlockRazor(auth_token, region, url, transport) => {
// BlockRazor: transport=None 或 transport=Grpc 时使用 gRPCtransport=Http 时使用 HTTP
let use_http = transport.map_or(false, |t| t == SwqosTransport::Http);
let endpoint = SwqosConfig::get_endpoint_with_transport(SwqosType::BlockRazor, region, url, transport, mev_protection);
let endpoint = SwqosConfig::get_endpoint_with_transport(
SwqosType::BlockRazor,
region,
url,
transport,
mev_protection,
);
if use_http {
let blockrazor_client =
BlockRazorClient::new_http(rpc_url.clone(), endpoint.to_string(), auth_token, mev_protection);
let blockrazor_client = BlockRazorClient::new_http(
rpc_url.clone(),
endpoint.to_string(),
auth_token,
mev_protection,
);
Ok(Arc::new(blockrazor_client))
} else {
// 使用 gRPC 模式(默认或用户明确指定了 gRPC)
let blockrazor_client =
BlockRazorClient::new_grpc(rpc_url.clone(), endpoint.to_string(), auth_token, mev_protection).await?;
let blockrazor_client = BlockRazorClient::new_grpc(
rpc_url.clone(),
endpoint.to_string(),
auth_token,
mev_protection,
)
.await?;
Ok(Arc::new(blockrazor_client))
}
}
+24 -4
View File
@@ -99,12 +99,26 @@ impl NextBlockClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("nextblock", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"nextblock",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
crate::common::sdk_log::log_swqos_submission_failed("nextblock", trade_type, start_time.elapsed(), _error);
crate::common::sdk_log::log_swqos_submission_failed(
"nextblock",
trade_type,
start_time.elapsed(),
_error,
);
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("nextblock", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"nextblock",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -124,7 +138,13 @@ impl NextBlockClient {
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "nextblock", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"nextblock",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+24 -4
View File
@@ -184,13 +184,27 @@ impl Node1Client {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("node1", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"node1",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
eprintln!(" [node1] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
eprintln!(
" [node1] {} submission failed after {:?}: {:?}",
trade_type,
start_time.elapsed(),
_error
);
}
}
} else if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("node1", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"node1",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -212,7 +226,13 @@ impl Node1Client {
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "node1", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"node1",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+38 -15
View File
@@ -73,13 +73,14 @@ impl rustls::client::danger::ServerCertVerifier for SkipServerVerification {
}
/// TLS 客户端证书:ECDSA P-256 + CN=钱包公钥(与 Speedlanding / Astralane QUIC 策略一致)。
fn generate_client_tls_credentials(keypair: &Keypair) -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>)> {
fn generate_client_tls_credentials(
keypair: &Keypair,
) -> Result<(CertificateDer<'static>, PrivateKeyDer<'static>)> {
let tls_key = RcgenKeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
let mut cert_params = CertificateParams::new(vec![])?;
cert_params.distinguished_name.push(
rcgen::DnType::CommonName,
rcgen::DnValue::Utf8String(keypair.pubkey().to_string()),
);
cert_params
.distinguished_name
.push(rcgen::DnType::CommonName, rcgen::DnValue::Utf8String(keypair.pubkey().to_string()));
let cert = cert_params.self_signed(&tls_key)?;
let cert_der = CertificateDer::from(cert.der().to_vec());
let key_der = PrivateKeyDer::Pkcs8(PrivatePkcs8KeyDer::from(tls_key.serialize_der()));
@@ -103,11 +104,11 @@ pub struct SoyasClient {
impl SoyasClient {
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
let rpc_client = SolanaRpcClient::new(rpc_url);
let keypair = Keypair::try_from_base58_string(api_key.trim()).map_err(|e| {
anyhow::anyhow!(
"Soyas api_token 无法解析为 Solana keypair base58QUIC mTLS 用): {}",
e
)
let keypair_bytes = bs58::decode(api_key.trim()).into_vec().map_err(|e| {
anyhow::anyhow!("Soyas api_token base58 解码失败(QUIC mTLS 用): {}", e)
})?;
let keypair = Keypair::try_from(keypair_bytes.as_slice()).map_err(|e| {
anyhow::anyhow!("Soyas api_token 无法解析为 Solana keypairQUIC mTLS 用): {}", e)
})?;
let (cert, key) = generate_client_tls_credentials(&keypair)?;
let mut crypto = rustls::ClientConfig::builder()
@@ -176,13 +177,23 @@ impl SwqosClientTrait for SoyasClient {
let connection = self.connection.load_full();
if Self::try_send_bytes(&connection, &serialized_tx).await.is_err() {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("Soyas", trade_type, start_time.elapsed(), "reconnecting");
}
crate::common::sdk_log::log_swqos_submission_failed(
"Soyas",
trade_type,
start_time.elapsed(),
"reconnecting",
);
}
self.reconnect().await?;
let connection = self.connection.load_full();
if let Err(e) = Self::try_send_bytes(&connection, &serialized_tx).await {
if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("Soyas", trade_type, start_time.elapsed(), &e);
crate::common::sdk_log::log_swqos_submission_failed(
"Soyas",
trade_type,
start_time.elapsed(),
&e,
);
}
return Err(e.into());
}
@@ -196,14 +207,26 @@ impl SwqosClientTrait for SoyasClient {
Err(e) => {
if crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmation failed: {:?}", "Soyas", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmation failed: {:?}",
"Soyas",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
return Err(e);
}
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "Soyas", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"Soyas",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
}
+12 -11
View File
@@ -48,11 +48,11 @@ impl SpeedlandingClient {
pub async fn new(rpc_url: String, endpoint_string: String, api_key: String) -> Result<Self> {
let rpc_client = SolanaRpcClient::new(rpc_url);
// Speedlanding QUIC:与官方一致使用 `solana_tls_utils::new_dummy_x509_certificate`Ed25519 dummy cert+ SNI `speed-landing`。
let keypair = Keypair::try_from_base58_string(api_key.trim()).map_err(|e| {
anyhow::anyhow!(
"Speedlanding api_token 无法解析为 Solana keypair base58(用于 mTLS);请确认粘贴的是机器人提供的密钥而非其它字符串: {}",
e
)
let keypair_bytes = bs58::decode(api_key.trim()).into_vec().map_err(|e| {
anyhow::anyhow!("Speedlanding api_token base58 解码失败(mTLS 用): {}", e)
})?;
let keypair = Keypair::try_from(keypair_bytes.as_slice()).map_err(|e| {
anyhow::anyhow!("Speedlanding api_token 无法解析为 Solana keypairmTLS 用): {}", e)
})?;
let (cert, key) = new_dummy_x509_certificate(&keypair);
let mut crypto = rustls::ClientConfig::builder()
@@ -112,11 +112,8 @@ impl SpeedlandingClient {
let _guard = self.reconnect.lock().await;
let current = self.connection.load_full();
if current.close_reason().is_some() {
let connecting = self.endpoint.connect_with(
self.client_config.clone(),
self.addr,
SPEED_SERVER,
)?;
let connecting =
self.endpoint.connect_with(self.client_config.clone(), self.addr, SPEED_SERVER)?;
let connection = timeout(CONNECT_TIMEOUT, connecting)
.await
.context("Speedlanding QUIC reconnect timeout")?
@@ -170,7 +167,11 @@ impl SwqosClientTrait for SpeedlandingClient {
match send_result.context("Speedlanding QUIC send timeout") {
Ok(Ok(())) => {
// 提交结果与「详细耗时/SDK 开关」无关,便于确认当前通道确实在执行
crate::common::sdk_log::log_swqos_submitted("Speedlanding", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"Speedlanding",
trade_type,
start_time.elapsed(),
);
}
Ok(Err(e)) => {
crate::common::sdk_log::log_swqos_submission_failed(
+24 -4
View File
@@ -168,13 +168,27 @@ impl StelliumClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if crate::common::sdk_log::sdk_log_enabled() {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("Stellium", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"Stellium",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
crate::common::sdk_log::log_swqos_submission_failed("Stellium", trade_type, start_time.elapsed(), _error);
crate::common::sdk_log::log_swqos_submission_failed(
"Stellium",
trade_type,
start_time.elapsed(),
_error,
);
}
}
} else if crate::common::sdk_log::sdk_log_enabled() {
crate::common::sdk_log::log_swqos_submission_failed("Stellium", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"Stellium",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -196,7 +210,13 @@ impl StelliumClient {
}
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "Stellium", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"Stellium",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+24 -4
View File
@@ -209,12 +209,26 @@ impl TemporalClient {
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
if response_json.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("nozomi", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"nozomi",
trade_type,
start_time.elapsed(),
);
} else if let Some(_error) = response_json.get("error") {
crate::common::sdk_log::log_swqos_submission_failed("nozomi", trade_type, start_time.elapsed(), _error);
crate::common::sdk_log::log_swqos_submission_failed(
"nozomi",
trade_type,
start_time.elapsed(),
_error,
);
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("nozomi", trade_type, start_time.elapsed(), response_text);
crate::common::sdk_log::log_swqos_submission_failed(
"nozomi",
trade_type,
start_time.elapsed(),
response_text,
);
}
let start_time: Instant = Instant::now();
@@ -232,7 +246,13 @@ impl TemporalClient {
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "nozomi", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"nozomi",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+79 -20
View File
@@ -1,12 +1,10 @@
use crate::swqos::common::{
default_http_client_builder, poll_transaction_confirmation,
};
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation};
use bincode;
use rand::seq::IndexedRandom;
use reqwest::Client;
use std::{sync::Arc, time::Instant, time::Duration};
use std::sync::atomic::{AtomicBool, Ordering};
use std::{sync::Arc, time::Duration, time::Instant};
use tokio::task::JoinHandle;
use bincode;
use crate::swqos::SwqosClientTrait;
use crate::swqos::{SwqosType, TradeType};
@@ -101,7 +99,8 @@ impl ZeroSlotClient {
if stop_ping.load(Ordering::Relaxed) {
break;
}
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
{
if crate::common::sdk_log::sdk_log_enabled() {
eprintln!("0slot ping request failed: {}", e);
}
@@ -176,41 +175,89 @@ impl ZeroSlotClient {
200 => {
if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&response_text) {
if json_value.get("result").is_some() {
crate::common::sdk_log::log_swqos_submitted("0slot", trade_type, start_time.elapsed());
crate::common::sdk_log::log_swqos_submitted(
"0slot",
trade_type,
start_time.elapsed(),
);
} else if let Some(error) = json_value.get("error") {
let code = error.get("code")
let code = error
.get("code")
.and_then(|c| c.as_i64())
.map(|c| c.to_string())
.unwrap_or_else(|| "unknown".to_string());
let message = error.get("message")
let message = error
.get("message")
.and_then(|m| m.as_str())
.unwrap_or("unknown error");
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("code {}: {}", code, message));
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
format!("code {}: {}", code, message),
);
return Err(anyhow::anyhow!("0slot Binary-Tx error: {}", message));
} else {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("unexpected JSON: {}", response_text));
return Err(anyhow::anyhow!("0slot Binary-Tx unexpected JSON: {}", response_text));
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
format!("unexpected JSON: {}", response_text),
);
return Err(anyhow::anyhow!(
"0slot Binary-Tx unexpected JSON: {}",
response_text
));
}
} else {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("invalid JSON: {}", response_text));
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
format!("invalid JSON: {}", response_text),
);
return Err(anyhow::anyhow!("0slot Binary-Tx invalid JSON: {}", response_text));
}
}
403 => {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
response_text.clone(),
);
return Err(anyhow::anyhow!("0slot API key error: {}", response_text));
}
419 => {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
response_text.clone(),
);
return Err(anyhow::anyhow!("0slot rate limit exceeded"));
}
500 => {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), "submission failed".to_string());
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
"submission failed".to_string(),
);
return Err(anyhow::anyhow!("0slot transaction submission failed"));
}
_ => {
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("status {} body: {}", status, response_text));
return Err(anyhow::anyhow!("0slot Binary-Tx failed with status {}: {}", status, response_text));
crate::common::sdk_log::log_swqos_submission_failed(
"0slot",
trade_type,
start_time.elapsed(),
format!("status {} body: {}", status, response_text),
);
return Err(anyhow::anyhow!(
"0slot Binary-Tx failed with status {}: {}",
status,
response_text
));
}
}
@@ -222,13 +269,25 @@ impl ZeroSlotClient {
Ok(_) => (),
Err(e) => {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmation failed: {:?}", "0slot", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmation failed: {:?}",
"0slot",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
return Err(e);
}
}
if wait_confirmation {
println!(" signature: {:?}", signature);
println!(" [{:width$}] {} confirmed: {:?}", "0slot", trade_type, start_time.elapsed(), width = crate::common::sdk_log::SWQOS_LABEL_WIDTH);
println!(
" [{:width$}] {} confirmed: {:?}",
"0slot",
trade_type,
start_time.elapsed(),
width = crate::common::sdk_log::SWQOS_LABEL_WIDTH
);
}
Ok(())
+4 -4
View File
@@ -1,9 +1,9 @@
use solana_hash::Hash;
use solana_sdk::{
instruction::Instruction, pubkey::Pubkey,
signature::Keypair, signer::Signer, transaction::VersionedTransaction,
};
use solana_message::AddressLookupTableAccount;
use solana_sdk::{
instruction::Instruction, pubkey::Pubkey, signature::Keypair, signer::Signer,
transaction::VersionedTransaction,
};
use solana_system_interface::instruction as system_instruction;
use std::sync::Arc;
+2 -1
View File
@@ -88,7 +88,8 @@ pub async fn transfer_sol(
return Err(anyhow!("Insufficient balance"));
}
let transfer_instruction = system_instruction::transfer(&payer.pubkey(), receive_wallet, amount);
let transfer_instruction =
system_instruction::transfer(&payer.pubkey(), receive_wallet, amount);
let recent_blockhash = rpc.get_latest_blockhash().await?;
+1 -1
View File
@@ -7,7 +7,7 @@ use crate::common::{
spl_token::close_account,
};
use smallvec::SmallVec;
use solana_sdk::{instruction::Instruction, instruction::AccountMeta, pubkey::Pubkey};
use solana_sdk::{instruction::AccountMeta, instruction::Instruction, pubkey::Pubkey};
use solana_system_interface::instruction as system_instruction;
#[inline]
+11 -25
View File
@@ -14,6 +14,7 @@
use anyhow::{anyhow, Result};
use crossbeam_queue::ArrayQueue;
use once_cell::sync::OnceCell;
use parking_lot::Mutex;
use solana_hash::Hash;
use solana_message::AddressLookupTableAccount;
use solana_sdk::{
@@ -21,7 +22,6 @@ use solana_sdk::{
};
use std::collections::HashMap;
use std::hash::BuildHasherDefault;
use parking_lot::Mutex;
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
use std::{
str::FromStr,
@@ -187,11 +187,7 @@ fn ensure_dedicated_pool(
.map(|all_ids| {
sender_thread_cores
.map(|indices| {
indices
.iter()
.take(n)
.filter_map(|&i| all_ids.get(i).cloned())
.collect()
indices.iter().take(n).filter_map(|&i| all_ids.get(i).cloned()).collect()
})
.unwrap_or_else(|| all_ids.into_iter().take(n).collect())
})
@@ -416,8 +412,7 @@ impl ResultCollector {
}
// 「不等待链上确认」仍会等各 SWQOS 的 HTTP 回包;主循环在收齐或触达 `timeout_secs` 后结束。
// 若主窗口到时仍有未回包通道,晚到的 TaskResult 若立刻 drain 会丢签名——仅在该路径上拉长 grace。
let all_submitted =
self.completed_count.load(Ordering::Acquire) >= self.total_tasks;
let all_submitted = self.completed_count.load(Ordering::Acquire) >= self.total_tasks;
if all_submitted {
// 全数已登记:仅留极短 settle,避免极端情况下最后一笔与计数可见性竞态。
tokio::time::sleep(Duration::from_millis(35)).await;
@@ -472,11 +467,8 @@ pub async fn execute_parallel(
let instructions = Arc::new(instructions);
// One get_strategies call per batch (avoid N calls in loop).
let gas_fee_configs = gas_fee_strategy.get_strategies(if is_buy {
TradeType::Buy
} else {
TradeType::Sell
});
let gas_fee_configs =
gas_fee_strategy.get_strategies(if is_buy { TradeType::Buy } else { TradeType::Sell });
let mut task_configs = Vec::with_capacity(swqos_clients.len() * 3);
for (i, swqos_client) in swqos_clients.iter().enumerate() {
if !with_tip && !matches!(swqos_client.get_swqos_type(), SwqosType::Default) {
@@ -589,18 +581,12 @@ pub async fn execute_parallel(
if !wait_transaction_confirmed {
// submit_timeout_secs 为「等齐各 SWQOS HTTP 应答」的上限;收齐后会立刻进入短 settle,不会睡满整段秒数。
// `wait_for_all_submitted` 仅在未收齐时追加长 grace,避免过早 drain 丢晚到签名。
let ret = collector
.wait_for_all_submitted(submit_timeout_secs)
.await
.unwrap_or((
false,
vec![],
Some(anyhow!(
"No SWQOS result within grace window (primary {}s)",
submit_timeout_secs
)),
vec![],
));
let ret = collector.wait_for_all_submitted(submit_timeout_secs).await.unwrap_or((
false,
vec![],
Some(anyhow!("No SWQOS result within grace window (primary {}s)", submit_timeout_secs)),
vec![],
));
let (success, signatures, last_error, submit_timings) = ret;
return Ok((success, signatures, last_error, submit_timings));
}
+35 -13
View File
@@ -1,10 +1,9 @@
use anyhow::Result;
use solana_hash::Hash;
use solana_sdk::{
instruction::Instruction, pubkey::Pubkey,
signature::Keypair, signature::Signature,
};
use solana_message::AddressLookupTableAccount;
use solana_sdk::{
instruction::Instruction, pubkey::Pubkey, signature::Keypair, signature::Signature,
};
use std::{
sync::Arc,
time::{Duration, Instant},
@@ -13,6 +12,7 @@ use std::{
use tracing::{info, trace, warn};
use super::{params::SwapParams, traits::InstructionBuilder};
use crate::swqos::SwqosType;
use crate::swqos::TradeType;
use crate::{
common::{nonce_cache::DurableNonceInfo, GasFeeStrategy, SolanaRpcClient},
@@ -26,7 +26,6 @@ use crate::{
trading::MiddlewareManager,
};
use once_cell::sync::Lazy;
use crate::swqos::{ SwqosType};
/// Global syscall bypass manager (reserved for future time/IO optimizations).
/// 全局系统调用绕过管理器(预留,后续可接入时间/IO 等优化)。
@@ -234,10 +233,7 @@ impl TradeExecutor for GenericTradeExecutor {
);
}
Ok((ok, signatures, err, submit_timings))
};
result
@@ -368,8 +364,20 @@ mod tests {
let before_submit_ms = 15.67;
let w = 12usize; // same as crate::common::sdk_log::SWQOS_LABEL_WIDTH
println!("\n--- 1. 构建指令耗时 / 提交前耗时(各打印一次,统一 ms,保留 4 位小数)---\n");
println!(" [SDK][{:width$}] {} build_instructions: {:.4} ms", "-", dir, build_ms, width = w);
println!(" [SDK][{:width$}] {} before_submit: {:.4} ms", "-", dir, before_submit_ms, width = w);
println!(
" [SDK][{:width$}] {} build_instructions: {:.4} ms",
"-",
dir,
build_ms,
width = w
);
println!(
" [SDK][{:width$}] {} before_submit: {:.4} ms",
"-",
dir,
before_submit_ms,
width = w
);
println!("\n--- 2. 每个 SWQOS 独立耗时:submit_done=起点→该通道提交完成, confirmed=该通道提交→链上确认, total=起点→链上确认 ---\n");
for (swqos_type, submit_ms, confirmed_ms, total_ms) in [
@@ -388,7 +396,9 @@ mod tests {
);
}
println!("\n--- 3. 不等待链上确认时:每行 total = 该通道 submit_done(提交完成总耗时)---\n");
println!(
"\n--- 3. 不等待链上确认时:每行 total = 该通道 submit_done(提交完成总耗时)---\n"
);
for (swqos_type, submit_ms, total_ms) in
[(SwqosType::Jito, 44.20, 44.20), (SwqosType::Helius, 51.80, 51.80)]
{
@@ -403,8 +413,20 @@ mod tests {
}
println!("\n--- 4. Simulate 模式(build/before_submit 仍从 grpc_recv_us 起算)---\n");
println!(" [SDK][{:width$}] {} build_instructions: {:.4} ms", "-", dir, build_ms, width = w);
println!(" [SDK][{:width$}] {} before_submit: {:.4} ms", "-", dir, before_submit_ms, width = w);
println!(
" [SDK][{:width$}] {} build_instructions: {:.4} ms",
"-",
dir,
build_ms,
width = w
);
println!(
" [SDK][{:width$}] {} before_submit: {:.4} ms",
"-",
dir,
before_submit_ms,
width = w
);
println!(" [SDK][{:width$}] {} simulate (dry-run): {:.4} ms", "-", dir, 8.50, width = w);
println!(" [SDK][{:width$}] {} total: {:.4} ms", "-", dir, 36.51, width = w);
println!();
+3
View File
@@ -97,6 +97,9 @@ pub struct SwapParams {
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
/// This option only applies to PumpFun and PumpSwap DEXes; it is ignored for other DEXes.
pub use_exact_sol_amount: Option<bool>,
/// Use PumpFun V2 instructions (buy_v2 / sell_v2 / buy_exact_quote_in_v2, 27/26-account metas, quote_mint support).
/// Default: `false` keeps legacy SOL-paired instructions for smaller transactions; V2 is the official future-proof interface.
pub use_pumpfun_v2: bool,
}
impl SwapParams {
+2 -3
View File
@@ -41,9 +41,8 @@ impl MeteoraDammV2Params {
) -> Result<Self, anyhow::Error> {
let pool_data =
crate::instruction::utils::meteora_damm_v2::fetch_pool(rpc, pool_address).await?;
let mint_accounts = rpc
.get_multiple_accounts(&[pool_data.token_a_mint, pool_data.token_b_mint])
.await?;
let mint_accounts =
rpc.get_multiple_accounts(&[pool_data.token_a_mint, pool_data.token_b_mint]).await?;
let token_a_program = mint_accounts
.get(0)
.and_then(|a| a.as_ref())
+104 -37
View File
@@ -5,28 +5,46 @@ use crate::instruction::utils::pumpfun::reconcile_mayhem_mode_for_trade;
use solana_sdk::pubkey::Pubkey;
use std::sync::Arc;
/// PumpFun protocol specific parameters
/// Configuration parameters specific to PumpFun trading protocol.
///
/// **Creator vault**: Pump buy/sell pass `creator_vault` = `PDA(["creator-vault", authority])`.
/// Usually `authority` is [`BondingCurveAccount::creator`]; with **Creator Rewards Sharing** it is
/// `fee_sharing_config_pda(mint)` (see [`fetch_fee_sharing_creator_vault_if_active`](crate::instruction::utils::pumpfun::fetch_fee_sharing_creator_vault_if_active)).
/// Keep `bonding_curve.creator` in sync with chain; ix building uses [`resolve_creator_vault_for_ix_with_fee_sharing`](crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing).
/// **Buy/sell**`creator_vault` 及(若可得)**`tradeEvent` / CPI 日志中的 `creator`** 优先于陈旧的曲线快照;
/// ix 组装与链下询价见 [`Self::effective_creator_for_trade`]、[`crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing`]。
///
/// **V2 instructions**: Set `use_v2_ix = true` to use `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2`
/// with unified 27/26-account layout. Required for USDC-paired coins (`quote_mint != WSOL`).
/// For SOL-paired coins, legacy instructions still work and are the default.
#[derive(Clone)]
pub struct PumpFunParams {
pub bonding_curve: Arc<BondingCurveAccount>,
pub associated_bonding_curve: Pubkey,
/// Resolved by [`resolve_creator_vault_for_ix_with_fee_sharing`](crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing): ix vault when it matches `PDA(creator)`, fee-sharing vault, or RPC hint.
/// 最新一笔可观测 trade 的 **`tradeEvent.creator`(日志)**。当 `Some` 且非 default 时,
/// **优先于** `bonding_curve.creator` 用于链下 creator-fee 询价与 `creator_vault` 在缺省 ix 时的推导。
/// Pump 上 creator 可能随交易推进,调用方应在每次解析到带 `creator` 的 trade 后更新(如 `.with_observed_trade_creator`)。
pub observed_trade_creator: Option<Pubkey>,
/// Resolved by [`resolve_creator_vault_for_ix_with_fee_sharing`](crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing)
/// **显式 `creator_vault`(非 default、非 phantom)永远优先并按原值使用**,不会再用 `creator` 重算覆盖;
/// 未传时再按 `fee_sharing_creator_vault_if_active`、`PDA(effective_creator)`(见 [`Self::effective_creator_for_trade`])。
pub creator_vault: Pubkey,
/// `Some(PDA(["creator-vault", fee_sharing_config]))` when pump-fees `SharingConfig` is **Active**; set by `from_mint_by_rpc` / [`refresh_fee_sharing_creator_vault_from_rpc`](Self::refresh_fee_sharing_creator_vault_from_rpc).
pub fee_sharing_creator_vault_if_active: Option<Pubkey>,
/// SPL Token or Token-2022 program id owning the **mint** (from gRPC / parser / cache).
/// **`Pubkey::default()`**ix 构建时使用 SDK 默认 **Token-2022**(与多数 Pump.fun 新发一致);显式传入 Legacy 或 Token-2022 id 可覆盖该默认值。
pub token_program: Pubkey,
/// Whether to close token account when selling, only effective during sell operations
pub close_token_account_when_sell: Option<bool>,
/// Fee recipient for buy/sell account #2. Set from sol-parser-sdk (`tradeEvent.feeRecipient` / 同笔 create_v2+buy 回填的 `observed_fee_recipient`);热路径不查 RPC。
/// `Pubkey::default()` 时按 mayhem 从静态池随机(与 npm 静态池一致,可能落后于主网 Global)。
pub fee_recipient: Pubkey,
/// Quote mint for v2 instructions (default: `So11111111111111111111111111111111111111112` for SOL-paired).
/// For USDC-paired coins, set to `EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`.
pub quote_mint: Pubkey,
/// Whether to use v2 instructions (`buy_v2`/`sell_v2`/`buy_exact_quote_in_v2`).
/// Default `false` for backward compatibility. Must be `true` for USDC-paired coins.
pub use_v2_ix: bool,
}
impl PumpFunParams {
@@ -38,11 +56,14 @@ impl PumpFunParams {
Self {
bonding_curve: Arc::new(BondingCurveAccount { ..Default::default() }),
associated_bonding_curve: Pubkey::default(),
observed_trade_creator: None,
creator_vault: creator_vault,
fee_sharing_creator_vault_if_active: None,
token_program: token_program,
close_token_account_when_sell: Some(close_token_account_when_sell),
fee_recipient: Pubkey::default(),
quote_mint: Pubkey::default(),
use_v2_ix: false,
}
}
@@ -74,24 +95,30 @@ impl PumpFunParams {
is_mayhem_mode,
is_cashback_coin,
);
let creator_vault_resolved = crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve_account.creator,
creator_vault,
&mint,
None,
)
.or_else(|| {
crate::instruction::utils::pumpfun::get_creator_vault_pda(&bonding_curve_account.creator)
})
.unwrap_or_default();
let creator_vault_resolved =
crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve_account.creator,
creator_vault,
&mint,
None,
)
.or_else(|| {
crate::instruction::utils::pumpfun::get_creator_vault_pda(
&bonding_curve_account.creator,
)
})
.unwrap_or_default();
Self {
bonding_curve: Arc::new(bonding_curve_account),
associated_bonding_curve: associated_bonding_curve,
observed_trade_creator: (creator != Pubkey::default()).then_some(creator),
creator_vault: creator_vault_resolved,
fee_sharing_creator_vault_if_active: None,
close_token_account_when_sell: close_token_account_when_sell,
token_program: token_program,
fee_recipient,
quote_mint: Pubkey::default(),
use_v2_ix: false,
}
}
@@ -129,27 +156,32 @@ impl PumpFunParams {
is_mayhem_mode,
is_cashback_coin,
);
let creator_vault_resolved = crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve.creator,
creator_vault,
&mint,
None,
)
.or_else(|| {
crate::instruction::utils::pumpfun::get_creator_vault_pda(&bonding_curve.creator)
})
.unwrap_or_default();
let creator_vault_resolved =
crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve.creator,
creator_vault,
&mint,
None,
)
.or_else(|| {
crate::instruction::utils::pumpfun::get_creator_vault_pda(&bonding_curve.creator)
})
.unwrap_or_default();
Self {
bonding_curve: Arc::new(bonding_curve),
associated_bonding_curve: associated_bonding_curve,
observed_trade_creator: (creator != Pubkey::default()).then_some(creator),
creator_vault: creator_vault_resolved,
fee_sharing_creator_vault_if_active: None,
close_token_account_when_sell: close_token_account_when_sell,
token_program: token_program,
fee_recipient,
quote_mint: Pubkey::default(),
use_v2_ix: false,
}
}
/// 仅 RPC 读取曲线快照;[`Self::observed_trade_creator`] 为 `None`,便于 bot 缓存合并时用粘性的 trade 日志 creator 覆盖陈旧曲线推导。
pub async fn from_mint_by_rpc(
rpc: &SolanaRpcClient,
mint: &Pubkey,
@@ -176,27 +208,44 @@ impl PumpFunParams {
&mint_account.owner,
);
let fee_sharing_creator_vault_if_active =
crate::instruction::utils::pumpfun::fetch_fee_sharing_creator_vault_if_active(rpc, mint)
.await?;
let creator_vault = crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve.creator,
Pubkey::default(),
mint,
fee_sharing_creator_vault_if_active,
)
.or_else(|| crate::instruction::utils::pumpfun::get_creator_vault_pda(&bonding_curve.creator))
.unwrap_or_default();
crate::instruction::utils::pumpfun::fetch_fee_sharing_creator_vault_if_active(
rpc, mint,
)
.await?;
let creator_vault =
crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&bonding_curve.creator,
Pubkey::default(),
mint,
fee_sharing_creator_vault_if_active,
)
.or_else(|| {
crate::instruction::utils::pumpfun::get_creator_vault_pda(&bonding_curve.creator)
})
.unwrap_or_default();
Ok(Self {
bonding_curve: Arc::new(bonding_curve),
associated_bonding_curve: associated_bonding_curve,
observed_trade_creator: None,
creator_vault,
fee_sharing_creator_vault_if_active,
close_token_account_when_sell: None,
token_program: mint_account.owner,
fee_recipient: Pubkey::default(),
quote_mint: Pubkey::default(),
use_v2_ix: false,
})
}
/// 链下公式与 **`creator_vault` 推导回退****日志/事件 `creator`**(若已写入 `observed_trade_creator`
/// 优先,否则使用 `bonding_curve.creator`。
#[inline]
pub fn effective_creator_for_trade(&self) -> Pubkey {
self.observed_trade_creator
.filter(|c| *c != Pubkey::default())
.unwrap_or(self.bonding_curve.creator)
}
/// One `getAccount` on pump-fees `SharingConfig` + re-resolves [`Self::creator_vault`]. Call before sell
/// when params come from gRPC/cache so migrated fee-sharing mints do not hit Anchor 2006.
pub async fn refresh_fee_sharing_creator_vault_from_rpc(
@@ -205,9 +254,11 @@ impl PumpFunParams {
mint: &Pubkey,
) -> Result<Self, anyhow::Error> {
self.fee_sharing_creator_vault_if_active =
crate::instruction::utils::pumpfun::fetch_fee_sharing_creator_vault_if_active(rpc, mint)
.await?;
let c = self.bonding_curve.creator;
crate::instruction::utils::pumpfun::fetch_fee_sharing_creator_vault_if_active(
rpc, mint,
)
.await?;
let c = self.effective_creator_for_trade();
if let Some(v) =
crate::instruction::utils::pumpfun::resolve_creator_vault_for_ix_with_fee_sharing(
&c,
@@ -221,13 +272,29 @@ impl PumpFunParams {
Ok(self)
}
/// Updates the cached `creator_vault` field only. Buy/sell ix use [`BondingCurveAccount::creator`].
/// Sets `quote_mint` and enables v2 instructions. Required for USDC-paired coins.
/// For SOL-paired coins, pass `WSOL_TOKEN_ACCOUNT` or leave default.
#[inline]
pub fn with_quote_mint(mut self, quote_mint: Pubkey) -> Self {
self.quote_mint = quote_mint;
self.use_v2_ix = quote_mint != Pubkey::default();
self
}
/// Updates the cached `creator_vault` field only. Buy/sell ix use [`Self::effective_creator_for_trade`] + resolve.
#[inline]
pub fn with_creator_vault(mut self, creator_vault: Pubkey) -> Self {
self.creator_vault = creator_vault;
self
}
/// 覆盖 **最新一笔 trade 日志中的 `creator`**`tradeEvent.creator`)。`None` 或 default 会清除覆盖。
#[inline]
pub fn with_observed_trade_creator(mut self, c: Option<Pubkey>) -> Self {
self.observed_trade_creator = c.filter(|x| *x != Pubkey::default());
self
}
/// Override fee-sharing vault hint (e.g. from an off-chain indexer). `None` clears the hint.
#[inline]
pub fn with_fee_sharing_creator_vault_if_active(
+5 -2
View File
@@ -1,7 +1,7 @@
use crate::swqos::SwqosType;
use crate::trading::SwapParams;
use anyhow::Result;
use solana_sdk::{instruction::Instruction, signature::Signature};
use crate::swqos::{SwqosType};
/// 交易执行器trait - 定义了所有交易协议都需要实现的核心方法
#[async_trait::async_trait]
pub trait TradeExecutor: Send + Sync {
@@ -9,7 +9,10 @@ pub trait TradeExecutor: Send + Sync {
/// - bool: 是否至少有一个交易成功
/// - Vec<Signature>: 所有提交的交易签名(按SWQOS顺序)
/// - Option<anyhow::Error>: 最后一个错误(如果全部失败)
async fn swap(&self, params: SwapParams) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)>;
async fn swap(
&self,
params: SwapParams,
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)>;
/// 获取协议名称
fn protocol_name(&self) -> &'static str;
}
+1 -1
View File
@@ -19,13 +19,13 @@ const TX_BUILDER_POOL_PREFILL: usize = 64;
use crossbeam_queue::ArrayQueue;
use once_cell::sync::Lazy;
use solana_message::AddressLookupTableAccount;
use solana_sdk::{
hash::Hash,
instruction::Instruction,
message::{v0, Message, VersionedMessage},
pubkey::Pubkey,
};
use solana_message::AddressLookupTableAccount;
use std::sync::Arc;
/// 预分配的交易构建器
pub struct PreallocatedTxBuilder {
+2 -5
View File
@@ -13,11 +13,8 @@ pub(crate) fn creator_side_fee_basis_points(
coin_creator: &Pubkey,
cashback_fee_basis_points: u64,
) -> u64 {
let creator_bps = if *coin_creator == Pubkey::default() {
0
} else {
COIN_CREATOR_FEE_BASIS_POINTS
};
let creator_bps =
if *coin_creator == Pubkey::default() { 0 } else { COIN_CREATOR_FEE_BASIS_POINTS };
creator_bps.saturating_add(cashback_fee_basis_points)
}