Compare commits
122 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 47cef59d15 | |||
| 9af86c8397 | |||
| 30df893c30 | |||
| 22c1a149e7 | |||
| 8657273ba6 | |||
| 99fb4ee604 | |||
| 3719d4a9f4 | |||
| d7326b55f4 | |||
| 7471bcba09 | |||
| b8325b2b52 | |||
| e459f175f5 | |||
| e5e58bef89 | |||
| 9874cd5358 | |||
| 1d3c0ff5da | |||
| 34f400e89d | |||
| bd1772bed2 | |||
| 5449d51591 | |||
| b973061f92 | |||
| 57e4c5d221 | |||
| 8ed2aef931 | |||
| 0cf0064e80 | |||
| 4968c48a2e | |||
| 5908c84798 | |||
| 6dab47f8f9 | |||
| a076e0f8cd | |||
| 05ac079d6d | |||
| f6db55c874 | |||
| 69b4f9bb9f | |||
| 532bc1195d | |||
| 8944c5455c | |||
| 0d846930ad | |||
| 703ae5e4db | |||
| 8e0210af97 | |||
| e605485ecf | |||
| 8dec2f8d8c | |||
| b505bebdac | |||
| 1cc051a874 | |||
| 0311a0b876 | |||
| b49c1c803e | |||
| ce8fb99626 | |||
| 49843d8a20 | |||
| 60d1db4755 | |||
| 7a8d2a9c17 | |||
| 75bfbf6d54 | |||
| 184f1cc583 | |||
| 55c13e2f25 | |||
| fda211ea87 | |||
| 85d2c602f3 | |||
| 02d939b3cf | |||
| e8ec9103ab | |||
| 0fe54f0e94 | |||
| 7ac07247a3 | |||
| 06ed710869 | |||
| d711346c55 | |||
| 06ef2fed84 | |||
| a391539000 | |||
| c75ca4b034 | |||
| b13b4fda0a | |||
| 4dec087ea6 | |||
| 9c9ecf3e5b | |||
| 4b451af5ff | |||
| 8f2f99f3d9 | |||
| 971ef41fad | |||
| 35bfa93516 | |||
| c8f9f9f6aa | |||
| 99846a21c2 | |||
| 062c5415c3 | |||
| eaa3214e4d | |||
| ae890ad976 | |||
| e10ee0de3b | |||
| 5e1fb1a66b | |||
| a5ea26afaf | |||
| ee4a8f685b | |||
| 322acf8baf | |||
| 378b8fc324 | |||
| 19f11aa620 | |||
| 61cea7546c | |||
| d52503b8de | |||
| 9e53b7694c | |||
| 07e45d136f | |||
| 20d053bab3 | |||
| 5d921f23ff | |||
| a187126554 | |||
| 6ea8c27824 | |||
| 8c4e3ee0c5 | |||
| 624b1843a2 | |||
| 7d2ecd57e9 | |||
| 667d6d2c5b | |||
| e957bc4bee | |||
| 274636abc5 | |||
| 2abcf3839e | |||
| 0ec826fcbd | |||
| 6607d276db | |||
| d7b0985844 | |||
| 2e39649ebc | |||
| 0201d3443a | |||
| 9872b1b4a7 | |||
| e16cd6620f | |||
| 9f79e865ab | |||
| e32e7ee6ab | |||
| 30c91a74af | |||
| 6c41e1cfe6 | |||
| a003fd4d2f | |||
| fd5af3ab61 | |||
| 7e2860d8de | |||
| 07487c06cb | |||
| 1142829394 | |||
| f19f8a5d1c | |||
| d2ce193e2c | |||
| 46564f1bb5 | |||
| 63afac7aea | |||
| d9b9ddc53f | |||
| d610745c7e | |||
| 460395e5b2 | |||
| 5335a4f5ff | |||
| 23a45e611c | |||
| 48b9b17ab1 | |||
| 0cd276d6cb | |||
| 82438479d3 | |||
| 3d062279d9 | |||
| 15e07e9130 | |||
| 6eaafde4fd |
+9
-27
@@ -1,30 +1,12 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
# Proto 生成工具和生成的代码(用户不需要)
|
||||
/proto/gen/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
# 预生成的 proto Rust 代码(提交到仓库,但用户不应修改)
|
||||
# /src/swqos/pb/serverpb.rs <- 这个文件已经提交,用户不应修改
|
||||
|
||||
# Build artifacts
|
||||
/target/
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
# RustRover
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
.cargo/
|
||||
|
||||
tmp_*.rs
|
||||
tmp_*.log
|
||||
|
||||
|
||||
.claude/
|
||||
.serena/
|
||||
# Proto sources
|
||||
/proto/
|
||||
|
||||
+34
-22
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sol-trade-sdk"
|
||||
version = "3.5.3"
|
||||
version = "4.0.22"
|
||||
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"
|
||||
@@ -20,6 +20,8 @@ members = [
|
||||
"examples/shared_infrastructure",
|
||||
"examples/middleware_system",
|
||||
"examples/pumpswap_trading",
|
||||
"examples/pumpfun_copy_trading",
|
||||
"examples/pumpfun_sniper_trading",
|
||||
"examples/bonk_sniper_trading",
|
||||
"examples/bonk_copy_trading",
|
||||
"examples/raydium_cpmm_trading",
|
||||
@@ -32,10 +34,11 @@ members = [
|
||||
"examples/cli_trading",
|
||||
"examples/gas_fee_strategy",
|
||||
"examples/meteora_damm_v2_direct_trading",
|
||||
"examples/simple_trading",
|
||||
]
|
||||
|
||||
[lib]
|
||||
crate-type = ["cdylib", "rlib"]
|
||||
crate-type = ["rlib"]
|
||||
|
||||
[features]
|
||||
default = []
|
||||
@@ -43,23 +46,26 @@ perf-trace = [] # 性能追踪特性,生产环境应禁用以获得最佳性
|
||||
|
||||
[dependencies]
|
||||
solana-sdk = "3.0.0"
|
||||
solana-client = "3.0.8"
|
||||
solana-client = "3.1.12"
|
||||
solana-program = "3.0.0"
|
||||
solana-rpc-client = "3.0.8"
|
||||
solana-rpc-client-api = "3.0.8"
|
||||
solana-transaction-status = "3.0.8"
|
||||
solana-account-decoder = "3.0.8"
|
||||
solana-rpc-client = "3.1.12"
|
||||
solana-rpc-client-api = "3.1.12"
|
||||
solana-transaction-status = "3.1.12"
|
||||
solana-account-decoder = "3.1.12"
|
||||
solana-hash = "3.0.0"
|
||||
solana-entry = "3.0.8"
|
||||
solana-rpc-client-nonce-utils = "3.0.8"
|
||||
solana-perf = "3.0.8"
|
||||
solana-metrics = "3.0.8"
|
||||
solana-nonce = "3.0.0"
|
||||
solana-entry = "3.0.0"
|
||||
solana-rpc-client-nonce-utils = "3.1.12"
|
||||
solana-perf = "3.1.12"
|
||||
solana-metrics = "3.1.12"
|
||||
solana-tls-utils = "3.1.12"
|
||||
solana-nonce = "3.2.0"
|
||||
|
||||
solana-address-lookup-table-interface = "3.0.0"
|
||||
solana-message = "3.1.0"
|
||||
solana-compute-budget-interface = "3.0.0"
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
solana-transaction-status-client-types = "3.0.0"
|
||||
solana-tls-utils = "3.0.8"
|
||||
solana-commitment-config = { version = "3.1.1", features = ["serde"] }
|
||||
solana-transaction-status-client-types = "3.1.12"
|
||||
solana-system-interface = { version = "3.0.0", features = ["bincode"] }
|
||||
|
||||
borsh = { version = "1.5.3", features = ["derive"] }
|
||||
isahc = "1.7.2"
|
||||
@@ -74,7 +80,7 @@ bincode = "1.3.3"
|
||||
anyhow = "1.0.90"
|
||||
reqwest = { version = "0.12.12", features = ["json", "multipart"] }
|
||||
tokio = { version = "1.42.0" , features = ["full", "rt-multi-thread"]}
|
||||
tonic = { version = "0.14.2", features = ["transport"] }
|
||||
tonic = { version = "0.12", features = ["transport"] }
|
||||
rustls = { version = "0.23.23", features = ["ring"] }
|
||||
rustls-native-certs = "0.8.1"
|
||||
tokio-rustls = "0.26.1"
|
||||
@@ -84,10 +90,9 @@ regex = "1"
|
||||
tracing = "0.1.41"
|
||||
thiserror = "2.0.11"
|
||||
async-trait = "0.1.86"
|
||||
lazy_static = "1.5.0"
|
||||
once_cell = "1.20.3"
|
||||
prost = "0.14.1"
|
||||
prost-types = "0.14.1"
|
||||
prost = "0.13"
|
||||
prost-types = "0.13"
|
||||
num_enum = "0.7.3"
|
||||
num-derive = "0.4.2"
|
||||
num-traits = "0.2.19"
|
||||
@@ -96,7 +101,7 @@ bytemuck = { version = "1.4.0" }
|
||||
arrayref = "0.3.6"
|
||||
borsh-derive = "1.5.5"
|
||||
indicatif = "0.18.0"
|
||||
solana-system-interface = { version = "2.0.0", features = ["bincode"] }
|
||||
|
||||
fnv = "1.0.7"
|
||||
dashmap = "6.1.0"
|
||||
clru = "0.6"
|
||||
@@ -105,7 +110,10 @@ parking_lot = "0.12"
|
||||
arc-swap = "1.7"
|
||||
sha2 = "0.10"
|
||||
tonic-prost = "0.14.2"
|
||||
quinn = {version = "0.11", default-features = false, features = ["rustls"]}
|
||||
# 须含 runtime-tokio,否则 quinn::Endpoint::client 报 no async runtime found,QUIC(Speedlanding/Soyas)无法初始化
|
||||
quinn = { version = "0.11", default-features = false, features = ["rustls", "runtime-tokio"] }
|
||||
rcgen = "0.13"
|
||||
uuid = "1.11"
|
||||
|
||||
# Performance optimization dependencies
|
||||
crossbeam-queue = "0.3"
|
||||
@@ -131,6 +139,10 @@ incremental = true # 增量编译 - 大幅加速重新编译
|
||||
opt-level = 1 # 开发时适度优化
|
||||
overflow-checks = true # 开发时启用溢出检查
|
||||
|
||||
# 🚀 构建依赖
|
||||
# 注意:proto 代码已预生成在 src/swqos/pb/serverpb.rs
|
||||
# 开发者如需重新生成代码,请运行 gen_proto 目录下的工具
|
||||
|
||||
# 🚀 性能关键依赖的特殊优化
|
||||
[profile.release.package.solana-sdk]
|
||||
opt-level = 3
|
||||
|
||||
@@ -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)
|
||||
@@ -48,10 +54,12 @@
|
||||
- [⚡ Trading Parameters](#-trading-parameters)
|
||||
- [📊 Usage Examples Summary Table](#-usage-examples-summary-table)
|
||||
- [⚙️ SWQoS Service Configuration](#️-swqos-service-configuration)
|
||||
- [Astralane (Binary / Plain / QUIC)](#astralane-binary--plain--quic)
|
||||
- [🔧 Middleware System](#-middleware-system)
|
||||
- [🔍 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)
|
||||
@@ -60,44 +68,48 @@
|
||||
|
||||
---
|
||||
|
||||
## 🆕 What's new in 3.5.3
|
||||
## 📦 SDK Versions
|
||||
|
||||
- **Full release**: Includes all updates (3.5.2 SWQoS perf + IDL/instruction changes). Use this version.
|
||||
- **SWQoS submit latency**: Sync serialize + buffer-pool hot path; `format!` body for single/batch submit (Bloxroute); avoid status clone in confirmation polling.
|
||||
- **First-submit & 5-min idle**: Immediate first ping + 30s keepalive; `pool_max_idle_per_host=4` and `pool_idle_timeout=300s` (BlockRazor, Temporal, Node1, Astralane, Stellium); ping consumes response body for connection reuse.
|
||||
- **PumpFun / PumpSwap**: IDL updates (pump.json, pump_amm.json); instruction and utils updates for pumpfun and pumpswap; fast_fn and release notes.
|
||||
This SDK is available in multiple languages:
|
||||
|
||||
## 🆕 What's new in 3.5.2
|
||||
| Language | Repository | Description |
|
||||
|----------|------------|-------------|
|
||||
| **Rust** | [sol-trade-sdk](https://github.com/0xfnzero/sol-trade-sdk) | Ultra-low latency with zero-copy optimization |
|
||||
| **Node.js** | [sol-trade-sdk-nodejs](https://github.com/0xfnzero/sol-trade-sdk-nodejs) | TypeScript/JavaScript for Node.js |
|
||||
| **Python** | [sol-trade-sdk-python](https://github.com/0xfnzero/sol-trade-sdk-python) | Async/await native support |
|
||||
| **Go** | [sol-trade-sdk-golang](https://github.com/0xfnzero/sol-trade-sdk-golang) | Concurrent-safe with goroutine support |
|
||||
|
||||
- **SWQoS submit latency**: Sync serialize + buffer-pool hot path; `format!` body for single/batch submit (Bloxroute); avoid status clone in confirmation polling.
|
||||
- **First-submit & 5-min idle**: Immediate first ping + 30s keepalive; `pool_max_idle_per_host=4` and `pool_idle_timeout=300s` (BlockRazor, Temporal, Node1, Astralane, Stellium) so submit reuses the same connection; ping consumes response body for connection reuse.
|
||||
- **Docs**: All SWQoS comments translated to English.
|
||||
## What This SDK Is For
|
||||
|
||||
## 🆕 What's new in 3.5.1
|
||||
`sol-trade-sdk` is the Rust implementation of the FnZero Solana trading SDK family. It focuses on low-latency transaction construction and submission for Solana DEX trading bots, copy-trading systems, sniper bots, arbitrage strategies, and private trading infrastructure.
|
||||
|
||||
- **SWQoS / executor**: Updates to common SWQoS logic and trading executor.
|
||||
| Area | Coverage |
|
||||
|------|----------|
|
||||
| DEX protocols | PumpFun, PumpSwap, Bonk, Meteora DAMM v2, Raydium AMM v4, Raydium CPMM |
|
||||
| Submit lanes | Default Solana RPC plus Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Node1, Astralane, SpeedLanding, and other SWQoS providers |
|
||||
| Trading workflows | Buy/sell, exact input/output, copy trading, sniper trading, address lookup tables, durable nonce, middleware, shared infrastructure |
|
||||
| Hot-path design | Caller supplies recent blockhash or durable nonce; trade execution avoids RPC reads for blockhash, account, or balance data |
|
||||
|
||||
## 🆕 What's new in 3.5.0
|
||||
## 🔖 Current Release
|
||||
|
||||
- **Performance**: Hot-path timing only when logging; reduced clones (`execute_parallel` takes `&[Arc<SwqosClient>]`); shared HTTP client constants for SWQoS.
|
||||
- **Code quality**: Extracted `validate_protocol_params` for buy/sell; constants for instruction/account sizes and HTTP timeouts; prefetch and branch-hint comments.
|
||||
- **Documentation**: Bilingual (English + 中文) doc comments across execution, executor, perf, and swqos modules.
|
||||
**Rust crate:** `sol-trade-sdk = "4.0.21"`
|
||||
|
||||
---
|
||||
This release refreshes PumpFun native-SOL quote handling so SOL/WSOL sentinels prefer the smaller V1 hot path, keeps the default RPC submit lane active alongside SWQoS lanes, restores the fast-submit result window to 5 seconds, and aligns Raydium CPMM fixed-output swaps with the on-chain `swap_base_out` instruction. Trade execution requires a caller-supplied `recent_blockhash` or durable nonce; hot-path execution does not query RPC for blockhash, account, or balance data.
|
||||
|
||||
## ✨ Features
|
||||
|
||||
1. **PumpFun Trading**: Support for `buy` and `sell` operations
|
||||
1. **PumpFun Trading**: Unified SDK-side `buy`, `sell`, and `buy_exact_quote_in` flow, preferring V1 for native SOL and selecting V2 for USDC/non-native quote mints or explicit WSOL settlement
|
||||
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
|
||||
5. **Raydium AMM V4 Trading**: Support for Raydium AMM V4 (Automated Market Maker) trading operations
|
||||
6. **Meteora DAMM V2 Trading**: Support for Meteora DAMM V2 (Dynamic AMM) trading operations
|
||||
7. **Multiple MEV Protection**: Support for Jito, Nextblock, ZeroSlot, Temporal, Bloxroute, FlashBlock, BlockRazor, Node1, Astralane and other services
|
||||
8. **Concurrent Trading**: Send transactions using multiple MEV services simultaneously; the fastest succeeds while others fail
|
||||
8. **Concurrent Trading**: Submit through every configured SWQoS provider plus the default RPC lane; the first accepted result can return early while slower routes continue submitting
|
||||
9. **Unified Trading Interface**: Use unified trading protocol enums for trading operations
|
||||
10. **Middleware System**: Support for custom instruction middleware to modify, add, or remove instructions before transaction execution
|
||||
11. **Shared Infrastructure**: Share expensive RPC and SWQoS clients across multiple wallets for reduced resource usage
|
||||
12. **Hot-Path RPC Boundary**: Trade execution uses caller-supplied blockhash or durable nonce and never queries RPC for blockhash, account, or balance data
|
||||
|
||||
## 📦 Installation
|
||||
|
||||
@@ -114,14 +126,14 @@ Add the dependency to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.5.3" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.21" }
|
||||
```
|
||||
|
||||
### Use crates.io
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = "3.5.3"
|
||||
sol-trade-sdk = "4.0.21"
|
||||
```
|
||||
|
||||
## 🛠️ Usage Examples
|
||||
@@ -143,14 +155,22 @@ 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::SpeedLanding("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
];
|
||||
// Create TradeConfig instance
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
|
||||
// Optional: customize WSOL ATA and seed optimization
|
||||
// let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
||||
// .with_wsol_ata_config(true, true); // create_wsol_ata_on_startup, use_seed_optimize
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true - check & create WSOL ATA on init
|
||||
// .use_seed_optimize(true) // default: true - seed optimization for ATA ops
|
||||
// .log_enabled(true) // default: true - SDK timing / SWQOS logs
|
||||
// .check_min_tip(false) // default: false - filter SWQOS below min tip
|
||||
// .swqos_cores_from_end(false) // default: false - bind SWQOS to last N CPU cores
|
||||
// .mev_protection(false) // default: false - MEV (Astralane QUIC :9000 or HTTP mev-protect / BlockRazor)
|
||||
.build();
|
||||
|
||||
// Create TradingClient
|
||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||
@@ -187,40 +207,74 @@ gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001,
|
||||
For detailed information about all trading parameters, see the [Trading Parameters Reference](docs/TRADING_PARAMETERS.md).
|
||||
|
||||
```rust
|
||||
// Import DexParamEnum for protocol-specific parameters
|
||||
use sol_trade_sdk::trading::core::params::DexParamEnum;
|
||||
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
dex_type: DexType::PumpSwap,
|
||||
input_token_type: TradeTokenType::WSOL,
|
||||
mint: mint_pubkey,
|
||||
input_token_amount: buy_sol_amount,
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
// Use DexParamEnum for type-safe protocol parameters (zero-overhead abstraction)
|
||||
extension_params: DexParamEnum::PumpSwap(params.clone()),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
durable_nonce: None,
|
||||
fixed_output_token_amount: None, // Optional: specify exact output amount
|
||||
gas_fee_strategy: gas_fee_strategy.clone(), // Gas fee strategy configuration
|
||||
simulate: false, // Set to true for simulation only
|
||||
use_exact_sol_amount: None, // Use exact SOL input for PumpFun/PumpSwap (defaults to true)
|
||||
use sol_trade_sdk::{
|
||||
AccountPolicy, BuyAmount, DexType, SimpleBuyParams, TradeTokenType,
|
||||
trading::core::params::DexParamEnum,
|
||||
};
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
// Token used to pay. For PumpFun V2 SOL/WSOL quote pools, keep this as SOL
|
||||
// when you want to spend native SOL; the SDK will still use V2 accounts.
|
||||
TradeTokenType::SOL,
|
||||
// Mint of the meme/token you want to buy.
|
||||
mint_pubkey,
|
||||
// Regular PumpFun/PumpSwap buy. The SDK estimates token output and applies
|
||||
// slippage to the maximum quote cost.
|
||||
BuyAmount::WithMaxInput { quote_amount: buy_sol_amount },
|
||||
// Protocol state from parser/RPC cache, for example PumpFunParams::from_trade(...).
|
||||
DexParamEnum::PumpFun(pumpfun_params),
|
||||
// Pass a cached recent blockhash; the SDK does not fetch it on the hot path.
|
||||
recent_blockhash,
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
// 300 = 3%.
|
||||
.slippage_basis_points(300)
|
||||
// For bots/sniping: assume ATAs are already prepared and keep the tx small.
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
```
|
||||
|
||||
#### 4. Execute Trading
|
||||
|
||||
```rust
|
||||
client.buy(buy_params).await?;
|
||||
client.buy_simple(buy_params).await?;
|
||||
```
|
||||
|
||||
### ⚡ Trading Parameters
|
||||
|
||||
For comprehensive information about all trading parameters including `TradeBuyParams` and `TradeSellParams`, see the dedicated [Trading Parameters Reference](docs/TRADING_PARAMETERS.md).
|
||||
Use `SimpleBuyParams` / `SimpleSellParams` for new integrations. They describe trading intent and hide low-level ATA flags. Most users only choose:
|
||||
|
||||
- `pay_with` / `receive_as`: quote token direction. Use `SOL` when the wallet spends or receives native SOL. For PumpFun V2 SOL-paired pools whose quote mint is WSOL, still use `SOL` if you want native SOL settlement.
|
||||
- `amount`: trade sizing intent. Pick one enum variant instead of combining `input_token_amount`, `fixed_output_token_amount`, and `use_exact_sol_amount`.
|
||||
- `account_policy`: account creation behavior. Bots usually use `HotPathMinimal`; normal apps can keep the default `Auto`.
|
||||
|
||||
| Parameter | Meaning | Recommendation |
|
||||
|---|---|---|
|
||||
| `BuyAmount::ExactInput(amount)` | Spend exactly this quote amount; slippage protects minimum output. | Normal swaps |
|
||||
| `BuyAmount::WithMaxInput { quote_amount }` | Regular PumpFun/PumpSwap buy with slippage applied to max quote cost. | Sniping/arbitrage |
|
||||
| `BuyAmount::ExactOutput { output_amount, max_input_amount }` | Buy an exact token amount with a max quote budget. | Exact-output workflows |
|
||||
| `SellAmount::ExactInput(amount)` | Sell exactly this token amount. | Normal sells |
|
||||
| `SellAmount::ExactOutput { output_amount, max_input_amount }` | Receive an exact quote amount while limiting token input, where the DEX supports it. | Exact-output sells |
|
||||
| `AccountPolicy::Auto` | SDK creates practical ATAs when needed. | General usage |
|
||||
| `AccountPolicy::HotPathMinimal` | Avoid ATA create/close instructions in the trade tx. | Bots, sniping, latency-sensitive flows |
|
||||
| `AccountPolicy::CreateMissing` | Include ATA creation instructions where possible. | Convenience over transaction size |
|
||||
| `AccountPolicy::AssumePrepared` | Caller prepared every required ATA. | Deterministic advanced flows |
|
||||
|
||||
Optional builder methods:
|
||||
|
||||
| Method | Meaning |
|
||||
|---|---|
|
||||
| `.slippage_basis_points(300)` | Set slippage. `300` means 3%. |
|
||||
| `.address_lookup_table_account(alt)` | Attach an ALT to reduce transaction size. Useful for large PumpFun V2 transactions. |
|
||||
| `.wait_tx_confirmed(true)` | Return only after confirmation. Usually disabled for fastest submit paths. |
|
||||
| `.wait_for_all_submits(true)` | Wait for all SWQoS lane responses and return submitted signatures. Recent-blockhash route variants are not mutually exclusive; durable nonce variants are. |
|
||||
| `.simulate(true)` | Build and simulate the transaction instead of sending it. |
|
||||
| `.grpc_recv_us(ts)` | Attach upstream receive timestamp for latency tracing. |
|
||||
| `.durable_nonce(nonce_info)` | Use durable nonce and clear `recent_blockhash`. Recommended when you start from `SimpleBuyParams::new(...)` / `SimpleSellParams::new(...)`. |
|
||||
| `SimpleBuyParams::with_durable_nonce(...)` / `SimpleSellParams::with_durable_nonce(...)` | Construct params directly with durable nonce instead of `recent_blockhash`. |
|
||||
| `SimpleSellParams::with_tip(false)` | Disable relay tips for sells. Buys use the gas fee strategy/tip settings. |
|
||||
|
||||
`TradeBuyParams` and `TradeSellParams` remain available as advanced low-level APIs. See the dedicated [Trading Parameters Reference](docs/TRADING_PARAMETERS.md).
|
||||
|
||||
#### About ShredStream
|
||||
|
||||
@@ -231,6 +285,7 @@ Please ensure that the parameters your trading logic depends on are available in
|
||||
|
||||
| Description | Run Command | Source Code |
|
||||
|-------------|-------------|-------------|
|
||||
| Simple buy/sell parameter API | `cargo run --package simple_trading` | [examples/simple_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/simple_trading/src/main.rs) |
|
||||
| Create and configure TradingClient instance | `cargo run --package trading_client` | [examples/trading_client](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/trading_client/src/main.rs) |
|
||||
| Share infrastructure across multiple wallets | `cargo run --package shared_infrastructure` | [examples/shared_infrastructure](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/shared_infrastructure/src/main.rs) |
|
||||
| PumpFun token sniping trading | `cargo run --package pumpfun_sniper_trading` | [examples/pumpfun_sniper_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_sniper_trading/src/main.rs) |
|
||||
@@ -268,7 +323,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
|
||||
@@ -280,7 +335,52 @@ let bloxroute_config = SwqosConfig::Bloxroute(
|
||||
- If no custom URL is provided (`None`), the system will use the default endpoint for the specified `SwqosRegion`
|
||||
- This allows for maximum flexibility while maintaining backward compatibility
|
||||
|
||||
When using multiple MEV services, you need to use `Durable Nonce`. You need to use the `fetch_nonce_info` function to get the latest `nonce` value, and use it as the `durable_nonce` when trading.
|
||||
When using multiple MEV services, you need to use `Durable Nonce`. Fetch the latest nonce value and attach it to the high-level buy/sell params:
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{fetch_nonce_info, AccountPolicy, BuyAmount, SimpleBuyParams};
|
||||
|
||||
let nonce_info = fetch_nonce_info(&client.infrastructure.rpc, nonce_account)
|
||||
.await
|
||||
.expect("nonce account must be initialized");
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint_pubkey,
|
||||
BuyAmount::WithMaxInput { quote_amount: buy_sol_amount },
|
||||
DexParamEnum::PumpFun(pumpfun_params),
|
||||
recent_blockhash, // will be cleared by `.durable_nonce(...)`
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
.durable_nonce(nonce_info)
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
|
||||
client.buy_simple(buy_params).await?;
|
||||
```
|
||||
|
||||
#### Astralane (Binary / Plain HTTP / QUIC)
|
||||
|
||||
Astralane supports **Binary** HTTP (`/irisb`), **Plain** HTTP (`/iris`), and **QUIC** (`host:7000`, or `:9000` when global `mev_protection` is true). Pass `Some(AstralaneTransport::Plain)`, `Some(AstralaneTransport::Quic)`, or use `None` / omit for **Binary** (default). Global `mev_protection` adds `mev-protect=true` on HTTP or selects QUIC port 9000.
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{SwqosConfig, SwqosRegion, AstralaneTransport};
|
||||
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt,
|
||||
None,
|
||||
Some(AstralaneTransport::Quic),
|
||||
),
|
||||
];
|
||||
// Then create TradeConfig / TradingClient as usual with swqos_configs
|
||||
```
|
||||
|
||||
- **Binary** (default): `None` or `Some(AstralaneTransport::Binary)` — `/irisb`, bincode body.
|
||||
- **Plain**: `Some(AstralaneTransport::Plain)` — `/iris`.
|
||||
- **QUIC**: `Some(AstralaneTransport::Quic)` — regional `host:7000` / `:9000` (MEV); same API key.
|
||||
|
||||
---
|
||||
|
||||
@@ -309,23 +409,99 @@ PumpFun and PumpSwap support **cashback** for eligible tokens: part of the tradi
|
||||
|
||||
- **When params come from RPC**: If you use `PumpFunParams::from_mint_by_rpc` or `PumpSwapParams::from_pool_address_by_rpc` / `from_mint_by_rpc`, the SDK reads `is_cashback_coin` from chain—no extra step.
|
||||
- **When params come from event/parser**: If you build params from trade events (e.g. [sol-parser-sdk](https://github.com/0xfnzero/sol-parser-sdk)), you **must** pass the cashback flag into the SDK:
|
||||
- **PumpFun**: `PumpFunParams::from_trade(..., is_cashback_coin)` and `PumpFunParams::from_dev_trade(..., is_cashback_coin)` take an `is_cashback_coin` parameter. Set it from the parsed event (e.g. CreateEvent’s `is_cashback_enabled` or BondingCurve’s `is_cashback_coin`).
|
||||
- **PumpFun**: `PumpFunParams::from_trade(..., mint, quote_mint, creator, ..., is_cashback_coin, mayhem_mode)` and `PumpFunParams::from_dev_trade(..., is_cashback_coin)` take an `is_cashback_coin` parameter. Set it from the parsed event (e.g. CreateEvent’s `is_cashback_enabled` or BondingCurve’s `is_cashback_coin`).
|
||||
- **PumpSwap**: `PumpSwapParams` has a field `is_cashback_coin`. When constructing params manually (e.g. from pool/trade events), set it from the parsed pool or event data.
|
||||
- The **pumpfun_copy_trading** and **pumpfun_sniper_trading** examples use sol-parser-sdk for gRPC subscription and pass `e.is_cashback_coin` when building params.
|
||||
- **Claim**: Use `client.claim_cashback_pumpfun()` and `client.claim_cashback_pumpswap(...)` to claim accumulated cashback.
|
||||
|
||||
#### PumpFun: 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:
|
||||
|
||||
- **From gRPC/events (no RPC needed)**: You can get both `creator` and `creator_vault` from parsed transaction events:
|
||||
- **sol-parser-sdk**: Before pushing events, the pipeline calls `fill_trade_accounts`, which fills `creator_vault` from the buy/sell instruction accounts (buy index 9, sell index 8). `creator` comes from the TradeEvent log. Use `PumpFunParams::from_trade(..., e.creator, e.creator_vault, ...)` or `from_dev_trade(..., e.creator, e.creator_vault, ...)` with the event `e`.
|
||||
- **solana-streamer**: Instruction parsers set `creator_vault` from accounts[9] (buy) or accounts[8] (sell); `creator` comes from the merged CPI TradeEvent log. Use the same `from_trade` / `from_dev_trade` with `e.creator` and `e.creator_vault`.
|
||||
- **Override after RPC**: If you get params via `PumpFunParams::from_mint_by_rpc` but later receive a newer `creator_vault` from gRPC, call `.with_creator_vault(latest_creator_vault)` on the params before selling.
|
||||
|
||||
The SDK does not fetch creator_vault from RPC on every sell (to avoid latency); pass the up-to-date vault from gRPC/events when available.
|
||||
|
||||
#### PumpFun Unified Buy/Sell With V1/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 | Native SOL (`default`, Solscan SOL sentinel, or WSOL sentinel) | Non-native quote mint, or explicit WSOL settlement |
|
||||
| Transaction size | Smaller (preferred hot path) | Larger (may require LUT for nonce/tip/ATA-heavy transactions) |
|
||||
|
||||
The SDK-side builder is version-neutral: callers use the normal buy/sell flow, and `quote_mint` plus the requested settlement token (`pay_with` / `receive_as`) select the correct on-chain discriminator and account layout internally. There is no user-facing V2 switch required.
|
||||
|
||||
**Default: V1**. When `quote_mint` is `Pubkey::default()`, the Solscan SOL sentinel (`So11111111111111111111111111111111111111111`), or `WSOL_TOKEN_ACCOUNT` (`So11111111111111111111111111111111111111112`), the SDK treats the curve as native SOL-paired and uses V1 instructions when `pay_with` / `receive_as` is `SOL`. This is the preferred hot path because it avoids the 27-account V2 layout. Passing USDC or another real quote mint selects V2. Passing `WSOL` as the buy input or sell output selects V2 only when you intentionally want to settle through an existing WSOL ATA.
|
||||
|
||||
**Key changes in v2 instructions:**
|
||||
- `quote_mint` parameter — native SOL-paired curves may appear as default, Solscan SOL, or WSOL; USDC/non-native quote mints select V2
|
||||
- 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
|
||||
- USDC-paired coins must be bought with USDC and sell back to USDC. The SDK rejects SOL input for USDC quote pools before transaction submission.
|
||||
|
||||
**Pass `quote_mint` into `PumpFunParams::from_trade`**:
|
||||
|
||||
When using event/parser data, pass the event's `quote_mint` right after `mint`. `Pubkey::default()`, Solscan SOL (`So11111111111111111111111111111111111111111`), and `WSOL_TOKEN_ACCOUNT` all mean a native SOL-paired curve and default to V1 for normal SOL settlement. USDC means USDC V2.
|
||||
|
||||
```rust
|
||||
// quote_mint is not a PDA. It is the quote SPL mint carried by parser/gRPC events:
|
||||
// - Native SOL pool: Pubkey::default(), Solscan SOL, or WSOL sentinel from parser data
|
||||
// - USDC/non-native pool: actual quote SPL mint
|
||||
let quote_mint = e.quote_mint;
|
||||
let params = PumpFunParams::from_trade(
|
||||
e.bonding_curve,
|
||||
e.associated_bonding_curve,
|
||||
e.mint,
|
||||
quote_mint,
|
||||
e.creator,
|
||||
e.creator_vault,
|
||||
e.virtual_token_reserves,
|
||||
e.virtual_quote_reserves,
|
||||
e.real_token_reserves,
|
||||
e.real_quote_reserves,
|
||||
close_token_account_when_sell,
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
);
|
||||
```
|
||||
|
||||
For USDC-paired coins, pass `USDC_TOKEN_ACCOUNT` as the buy `input_mint` and sell `output_mint`; SOL/WSOL is only valid for SOL-paired PumpFun curves. For SOL-paired curves, use `SOL` for the normal fast path; use `WSOL` only if you intentionally want V2 settlement through an existing WSOL ATA.
|
||||
When consuming parser events, map `quoteMint`, `virtualQuoteReserves`, and `realQuoteReserves` into `PumpFunParams::from_trade(...)`; USDC pools use `4_292_000_000` as the initial virtual quote reserve.
|
||||
For legacy SOL events where `quote_mint` is `Pubkey::default()` or Solscan SOL, use `virtual_sol_reserves` / `real_sol_reserves` when the quote-reserve fields are absent or zero.
|
||||
|
||||
> **Note**: V2 transactions with ATA creation + durable nonce/tip may exceed `PACKET_DATA_SIZE`. The SDK reports this locally and does not remove compute-budget or tip instructions because that changes priority semantics. Use V1 when the curve is native SOL-paired, pre-create ATAs, or 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 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 - [Official Documentation](https://doc.flashblock.trade/)
|
||||
- **BlockRazor**: High-speed transaction execution with API key authentication - [Official Documentation](https://blockrazor.gitbook.io/blockrazor/)
|
||||
- **Node1**: High-speed transaction execution with API key authentication - [Official Documentation](https://node1.me/docs.html)
|
||||
- **Astralane**: Blockchain network acceleration
|
||||
- **FlashBlock**: High-speed transaction execution with API key authentication
|
||||
- **BlockRazor**: High-speed transaction execution with API key authentication
|
||||
- **Astralane**: Blockchain network acceleration (Binary/Plain HTTP and QUIC)
|
||||
- **SpeedLanding**: High-speed transaction execution with API key authentication
|
||||
|
||||
## 📁 Project Structure
|
||||
|
||||
@@ -358,6 +534,10 @@ MIT License
|
||||
- Telegram Group: https://t.me/fnzero_group
|
||||
- Discord: https://discord.gg/vuazbGkqQE
|
||||
|
||||
## ⏱️ Timing metrics (v3.5.0+)
|
||||
|
||||
When `log_enabled` and SDK log are on, the executor prints `[SDK] Buy/Sell timing(...)`. **Semantics changed in v3.5.0**: `submit` is now only the send to SWQOS/RPC; `confirm` is separate; `start_to_submit` (when `grpc_recv_us` is set) is **end-to-end from gRPC event to submit**, so it is larger than in-process timings. See [docs/TIMING_METRICS.md](docs/TIMING_METRICS.md) for definitions and how to compare with older versions.
|
||||
|
||||
## ⚠️ Important Notes
|
||||
|
||||
1. Test thoroughly before using on mainnet
|
||||
|
||||
+240
-50
@@ -39,6 +39,12 @@
|
||||
<a href="https://discord.gg/vuazbGkqQE">Discord</a>
|
||||
</p>
|
||||
|
||||
> ☕ **支持本项目**
|
||||
>
|
||||
> 本 SDK 完全免费且开源。但维护和持续更新需要消耗大量 AI 算力与 Token。如果这个 SDK 对您的开发有帮助,欢迎每月捐赠任意数量的 SOL,您的支持将帮助这个项目持续运行!
|
||||
>
|
||||
> **捐赠钱包:** `6oW7AXz1yRb57pYSxysuXnMs2aR1ha5rzGzReZ1MjPV8`
|
||||
|
||||
## 📋 目录
|
||||
|
||||
- [✨ 项目特性](#-项目特性)
|
||||
@@ -48,10 +54,12 @@
|
||||
- [⚡ 交易参数](#-交易参数)
|
||||
- [📊 使用示例汇总表格](#-使用示例汇总表格)
|
||||
- [⚙️ SWQoS 服务配置说明](#️-swqos-服务配置说明)
|
||||
- [Astralane(Binary / Plain / QUIC)](#astralanebinary--plain--quic)
|
||||
- [🔧 中间件系统说明](#-中间件系统说明)
|
||||
- [🔍 地址查找表](#-地址查找表)
|
||||
- [🔍 Nonce 缓存](#-nonce-缓存)
|
||||
- [💰 Cashback 支持(PumpFun / PumpSwap)](#-cashback-支持pumpfun--pumpswap)
|
||||
- [Pump.fun 常见链上错误与排错(文档)](docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md)
|
||||
- [🛡️ MEV 保护服务](#️-mev-保护服务)
|
||||
- [📁 项目结构](#-项目结构)
|
||||
- [📄 许可证](#-许可证)
|
||||
@@ -60,27 +68,48 @@
|
||||
|
||||
---
|
||||
|
||||
## 🆕 3.5.0 更新说明
|
||||
## 📦 SDK 版本
|
||||
|
||||
- **性能**:仅在打日志时做热路径计时;减少 clone(`execute_parallel` 改为接收 `&[Arc<SwqosClient>]`);SWQoS 共用 HTTP 客户端常量。
|
||||
- **代码质量**:抽取 buy/sell 共用的 `validate_protocol_params`;指令/账户大小与 HTTP 超时常量化;预取与分支提示注释完善。
|
||||
- **文档**:execution、executor、perf、swqos 等模块增加中英双语文档注释。
|
||||
本 SDK 提供多种语言版本:
|
||||
|
||||
---
|
||||
| 语言 | 仓库 | 描述 |
|
||||
|------|------|------|
|
||||
| **Rust** | [sol-trade-sdk](https://github.com/0xfnzero/sol-trade-sdk) | 超低延迟,零拷贝优化 |
|
||||
| **Node.js** | [sol-trade-sdk-nodejs](https://github.com/0xfnzero/sol-trade-sdk-nodejs) | TypeScript/JavaScript,Node.js 支持 |
|
||||
| **Python** | [sol-trade-sdk-python](https://github.com/0xfnzero/sol-trade-sdk-python) | 原生 async/await 支持 |
|
||||
| **Go** | [sol-trade-sdk-golang](https://github.com/0xfnzero/sol-trade-sdk-golang) | 并发安全,goroutine 支持 |
|
||||
|
||||
## 这个 SDK 适合什么场景
|
||||
|
||||
`sol-trade-sdk` 是 FnZero Solana 交易 SDK 系列的 Rust 版本,重点服务于低延迟交易构建和提交,适合 Solana DEX 交易机器人、跟单系统、狙击机器人、套利策略和私有交易基础设施。
|
||||
|
||||
| 方向 | 覆盖范围 |
|
||||
|------|----------|
|
||||
| DEX 协议 | PumpFun、PumpSwap、Bonk、Meteora DAMM v2、Raydium AMM v4、Raydium CPMM |
|
||||
| 提交通道 | 默认 Solana RPC,以及 Jito、Nextblock、ZeroSlot、Temporal、Bloxroute、FlashBlock、BlockRazor、Node1、Astralane、SpeedLanding 等 SWQoS 服务 |
|
||||
| 交易流程 | 买入/卖出、精确输入/输出、跟单交易、狙击交易、地址查找表、durable nonce、中间件、共享基础设施 |
|
||||
| 热路径设计 | 调用方传入 recent blockhash 或 durable nonce;交易执行阶段不再查询 RPC 获取 blockhash、账户或余额 |
|
||||
|
||||
## 🔖 当前版本
|
||||
|
||||
**Rust crate:** `sol-trade-sdk = "4.0.21"`
|
||||
|
||||
本版本刷新 PumpFun native SOL quote 处理逻辑,SOL/WSOL sentinel 默认优先走更小的 V1 热路径,确保默认 RPC 提交通道会和 SWQoS 通道一起发出,快速提交结果等待窗口恢复为 5 秒,并将 Raydium CPMM fixed-output 交易对齐到链上 `swap_base_out` 指令。交易执行必须由调用方传入 `recent_blockhash` 或 durable nonce;热路径不会查询 RPC 获取 blockhash、账户或余额数据。
|
||||
|
||||
## ✨ 项目特性
|
||||
|
||||
1. **PumpFun 交易**: 支持`购买`、`卖出`功能
|
||||
1. **PumpFun 交易**: SDK 侧统一为 `buy`、`sell`、`buy_exact_quote_in` 流程,native SOL 优先走 V1,USDC/非 SOL quote 或显式 WSOL 结算才走 V2
|
||||
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 等服务
|
||||
8. **并发交易**: 同时使用多个 MEV 服务发送交易,最快的成功,其他失败
|
||||
7. **多种 MEV 保护**: 支持 Jito、Temporal、FlashBlock、BlockRazor、Astralane、SpeedLanding 等服务
|
||||
8. **并发交易**: 所有已配置的 SWQoS 通道和默认 RPC 通道都会发出提交;首个成功只影响返回,较慢通道会继续提交
|
||||
9. **统一交易接口**: 使用统一的交易协议枚举进行交易操作
|
||||
10. **中间件系统**: 支持自定义指令中间件,可在交易执行前对指令进行修改、添加或移除
|
||||
11. **共享基础设施**: 多钱包可共享同一套 RPC 与 SWQoS 客户端,降低资源占用
|
||||
12. **热路径 RPC 边界**: 交易执行使用调用方传入的 blockhash 或 durable nonce,不在热路径查询 blockhash、账户或余额
|
||||
|
||||
## 📦 安装
|
||||
|
||||
@@ -97,14 +126,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.5.3" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.21" }
|
||||
```
|
||||
|
||||
### 使用 crates.io
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = "3.5.0"
|
||||
sol-trade-sdk = "4.0.21"
|
||||
```
|
||||
|
||||
## 🛠️ 使用示例
|
||||
@@ -126,14 +155,22 @@ 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::SpeedLanding("your api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
];
|
||||
// 创建 TradeConfig 实例
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
|
||||
// 可选:自定义 WSOL ATA 与 Seed 优化
|
||||
// let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
||||
// .with_wsol_ata_config(true, true); // create_wsol_ata_on_startup, use_seed_optimize
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // 默认: true - 初始化时检查并创建 WSOL ATA
|
||||
// .use_seed_optimize(true) // 默认: true - ATA 操作启用 seed 优化
|
||||
// .log_enabled(true) // 默认: true - SDK 计时 / SWQOS 日志
|
||||
// .check_min_tip(false) // 默认: false - 过滤低于最低小费的 SWQOS
|
||||
// .swqos_cores_from_end(false) // 默认: false - 将 SWQOS 绑定到末尾 N 个 CPU 核心
|
||||
// .mev_protection(false) // 默认: false - MEV(Astralane QUIC :9000 或 HTTP mev-protect / BlockRazor)
|
||||
.build();
|
||||
|
||||
// 创建 TradingClient
|
||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||
@@ -169,40 +206,74 @@ gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001,
|
||||
有关所有交易参数的详细信息,请参阅 [交易参数参考手册](docs/TRADING_PARAMETERS_CN.md)。
|
||||
|
||||
```rust
|
||||
// 导入 DexParamEnum 用于协议特定参数
|
||||
use sol_trade_sdk::trading::core::params::DexParamEnum;
|
||||
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
dex_type: DexType::PumpSwap,
|
||||
input_token_type: TradeTokenType::WSOL,
|
||||
mint: mint_pubkey,
|
||||
input_token_amount: buy_sol_amount,
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
// 使用 DexParamEnum 实现类型安全的协议参数(零开销抽象)
|
||||
extension_params: DexParamEnum::PumpSwap(params.clone()),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
durable_nonce: None,
|
||||
fixed_output_token_amount: None, // 可选:指定精确输出数量
|
||||
gas_fee_strategy: gas_fee_strategy.clone(), // Gas 费用策略配置
|
||||
simulate: false, // 设为 true 仅进行模拟
|
||||
use_exact_sol_amount: None, // 对 PumpFun/PumpSwap 使用精确 SOL 输入(默认为 true)
|
||||
use sol_trade_sdk::{
|
||||
AccountPolicy, BuyAmount, DexType, SimpleBuyParams, TradeTokenType,
|
||||
trading::core::params::DexParamEnum,
|
||||
};
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
// 支付币种。PumpFun V2 的 SOL/WSOL quote 池,如果你想花原生 SOL,
|
||||
// 这里仍然传 SOL;SDK 内部会按 V2 账户布局处理。
|
||||
TradeTokenType::SOL,
|
||||
// 要买入的 meme/token mint。
|
||||
mint_pubkey,
|
||||
// 常规 PumpFun/PumpSwap buy。SDK 先估算能买到多少 token,
|
||||
// 再把滑点应用到最大 quote 成本上。
|
||||
BuyAmount::WithMaxInput { quote_amount: buy_sol_amount },
|
||||
// 协议状态参数,通常来自 parser/RPC 缓存,例如 PumpFunParams::from_trade(...)。
|
||||
DexParamEnum::PumpFun(pumpfun_params),
|
||||
// 传入外部缓存的 recent_blockhash;SDK 不在热路径里临时获取。
|
||||
recent_blockhash,
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
// 300 = 3%。
|
||||
.slippage_basis_points(300)
|
||||
// Bot/狙击推荐:假设 ATA 已提前准备好,交易内不创建/关闭 ATA,体积更小。
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
```
|
||||
|
||||
#### 4. 执行交易
|
||||
|
||||
```rust
|
||||
client.buy(buy_params).await?;
|
||||
client.buy_simple(buy_params).await?;
|
||||
```
|
||||
|
||||
### ⚡ 交易参数
|
||||
|
||||
有关所有交易参数(包括 `TradeBuyParams` 和 `TradeSellParams`)的详细信息,请参阅专门的 [交易参数参考手册](docs/TRADING_PARAMETERS_CN.md)。
|
||||
新接入建议优先使用 `SimpleBuyParams` / `SimpleSellParams`。它们描述交易意图,SDK 内部处理底层 ATA 参数。多数用户只需要选择:
|
||||
|
||||
- `pay_with` / `receive_as`:买入时用什么 quote 支付,卖出时收什么 quote。钱包实际花/收原生 SOL 就传 `SOL`。PumpFun V2 的 SOL 配对池虽然 `quote_mint` 是 WSOL,但你想用原生 SOL 结算时这里仍传 `SOL`。
|
||||
- `amount`:交易数量语义。用一个枚举表达意图,不再同时理解 `input_token_amount`、`fixed_output_token_amount`、`use_exact_sol_amount`。
|
||||
- `account_policy`:账户创建策略。Bot 通常用 `HotPathMinimal`;普通应用可以保留默认 `Auto`。
|
||||
|
||||
| 参数 | 含义 | 推荐场景 |
|
||||
|---|---|---|
|
||||
| `BuyAmount::ExactInput(amount)` | 精确花费指定 quote 数量;滑点保护最小买到数量。 | 普通买入 |
|
||||
| `BuyAmount::WithMaxInput { quote_amount }` | PumpFun/PumpSwap 常规 buy,滑点作用在最大 quote 成本上。 | 狙击、套利 |
|
||||
| `BuyAmount::ExactOutput { output_amount, max_input_amount }` | 精确买到指定 token 数量,并限制最大 quote 成本。 | 精确输出 |
|
||||
| `SellAmount::ExactInput(amount)` | 精确卖出指定 token 数量。 | 普通卖出 |
|
||||
| `SellAmount::ExactOutput { output_amount, max_input_amount }` | 精确收到指定 quote 数量,并限制最多卖出多少 token;取决于 DEX 是否支持。 | 精确输出卖出 |
|
||||
| `AccountPolicy::Auto` | SDK 按交易路径创建必要 ATA。 | 普通用户 |
|
||||
| `AccountPolicy::HotPathMinimal` | 交易内避免创建/关闭 ATA。 | Bot、狙击、低延迟 |
|
||||
| `AccountPolicy::CreateMissing` | 尽量在交易内创建缺失 ATA。 | 优先方便,不追求最小交易体积 |
|
||||
| `AccountPolicy::AssumePrepared` | 调用方保证所有 ATA 已准备好。 | 高级确定性流程 |
|
||||
|
||||
可选 builder 方法:
|
||||
|
||||
| 方法 | 含义 |
|
||||
|---|---|
|
||||
| `.slippage_basis_points(300)` | 设置滑点。`300` 表示 3%。 |
|
||||
| `.address_lookup_table_account(alt)` | 传入 ALT 以减少交易体积。PumpFun V2 交易较大时很有用。 |
|
||||
| `.wait_tx_confirmed(true)` | 等链上确认后再返回。追求最快提交时通常关闭。 |
|
||||
| `.wait_for_all_submits(true)` | 等待所有 SWQoS 通道返回,并拿到已提交签名。recent blockhash 多路交易不互斥;durable nonce 多路交易互斥。 |
|
||||
| `.simulate(true)` | 只构建并模拟交易,不真正发送。 |
|
||||
| `.grpc_recv_us(ts)` | 传入上游收到事件的微秒时间戳,用于延迟追踪。 |
|
||||
| `.durable_nonce(nonce_info)` | 使用 durable nonce,并清空 `recent_blockhash`。如果你从 `SimpleBuyParams::new(...)` / `SimpleSellParams::new(...)` 开始构造,推荐用这个。 |
|
||||
| `SimpleBuyParams::with_durable_nonce(...)` / `SimpleSellParams::with_durable_nonce(...)` | 直接用 durable nonce 构造参数,不使用 `recent_blockhash`。 |
|
||||
| `SimpleSellParams::with_tip(false)` | 关闭卖出交易 relay tip。买入的 tip 使用 gas fee strategy 控制。 |
|
||||
|
||||
`TradeBuyParams` 和 `TradeSellParams` 仍保留为高级低层接口。详细说明见 [交易参数参考手册](docs/TRADING_PARAMETERS_CN.md)。
|
||||
|
||||
#### 关于shredstream
|
||||
|
||||
@@ -213,6 +284,7 @@ client.buy(buy_params).await?;
|
||||
|
||||
| 描述 | 运行命令 | 源码路径 |
|
||||
|------|---------|----------|
|
||||
| 简化买卖参数 API | `cargo run --package simple_trading` | [examples/simple_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/simple_trading/src/main.rs) |
|
||||
| 创建和配置 TradingClient 实例 | `cargo run --package trading_client` | [examples/trading_client](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/trading_client/src/main.rs) |
|
||||
| 多钱包共享基础设施 | `cargo run --package shared_infrastructure` | [examples/shared_infrastructure](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/shared_infrastructure/src/main.rs) |
|
||||
| PumpFun 代币狙击交易 | `cargo run --package pumpfun_sniper_trading` | [examples/pumpfun_sniper_trading](https://github.com/0xfnzero/sol-trade-sdk/tree/main/examples/pumpfun_sniper_trading/src/main.rs) |
|
||||
@@ -250,7 +322,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
|
||||
@@ -262,7 +334,52 @@ let bloxroute_config = SwqosConfig::Bloxroute(
|
||||
- 如果没有提供自定义 URL(`None`),系统将使用指定 `SwqosRegion` 的默认端点
|
||||
- 这提供了最大的灵活性,同时保持向后兼容性
|
||||
|
||||
当使用多个MEV服务时,需要使用`Durable Nonce`。你需要使用`fetch_nonce_info`函数获取最新的`nonce`值,并在交易的时候将`durable_nonce`填入交易参数。
|
||||
当使用多个 MEV 服务时,需要使用 `Durable Nonce`。先获取最新 nonce,再挂到新的 buy/sell 参数上:
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{fetch_nonce_info, AccountPolicy, BuyAmount, SimpleBuyParams};
|
||||
|
||||
let nonce_info = fetch_nonce_info(&client.infrastructure.rpc, nonce_account)
|
||||
.await
|
||||
.expect("nonce account must be initialized");
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint_pubkey,
|
||||
BuyAmount::WithMaxInput { quote_amount: buy_sol_amount },
|
||||
DexParamEnum::PumpFun(pumpfun_params),
|
||||
recent_blockhash, // 会被 `.durable_nonce(...)` 清空
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
.durable_nonce(nonce_info)
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
|
||||
client.buy_simple(buy_params).await?;
|
||||
```
|
||||
|
||||
#### Astralane(Binary / Plain / QUIC)
|
||||
|
||||
Astralane 支持 **Binary** HTTP(`/irisb`)、**Plain** HTTP(`/iris`)与 **QUIC**(`host:7000`,全局 `mev_protection` 为 true 时用 `:9000`)。第四个参数:`Some(AstralaneTransport::Plain)`、`Some(AstralaneTransport::Quic)`,或 `None` 表示 **Binary**(默认)。全局 `mev_protection` 会在 HTTP 上附加 `mev-protect=true`,或为 QUIC 选择 9000 端口。
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{SwqosConfig, SwqosRegion, AstralaneTransport};
|
||||
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Astralane(
|
||||
"your_astralane_api_key".to_string(),
|
||||
SwqosRegion::Frankfurt,
|
||||
None,
|
||||
Some(AstralaneTransport::Quic),
|
||||
),
|
||||
];
|
||||
// 然后照常使用 swqos_configs 创建 TradeConfig / TradingClient
|
||||
```
|
||||
|
||||
- **Binary**(默认):`None` 或 `Some(AstralaneTransport::Binary)` — `/irisb`,bincode 正文。
|
||||
- **Plain**:`Some(AstralaneTransport::Plain)` — `/iris`。
|
||||
- **QUIC**:`Some(AstralaneTransport::Quic)` — 按区域的 `host:7000` / `:9000`(MEV);同一 API key。
|
||||
|
||||
---
|
||||
|
||||
@@ -291,23 +408,97 @@ PumpFun 与 PumpSwap 支持**返现(Cashback)**:部分手续费可返还
|
||||
|
||||
- **参数来自 RPC 时**:使用 `PumpFunParams::from_mint_by_rpc` 或 `PumpSwapParams::from_pool_address_by_rpc` / `from_mint_by_rpc` 时,SDK 会从链上读取 `is_cashback_coin`,无需额外传入。
|
||||
- **参数来自事件/解析器时**:若根据交易事件(如 [sol-parser-sdk](https://github.com/0xfnzero/sol-parser-sdk))构建参数,**必须**把返现标志传给 SDK:
|
||||
- **PumpFun**:`PumpFunParams::from_trade(..., is_cashback_coin)` 与 `PumpFunParams::from_dev_trade(..., is_cashback_coin)` 最后一个参数为 `is_cashback_coin`。从解析出的事件传入(如 sol-parser-sdk 的 `PumpFunTradeEvent.is_cashback_coin`)。
|
||||
- **PumpFun**:`PumpFunParams::from_trade(..., mint, quote_mint, creator, ..., is_cashback_coin, mayhem_mode)` 与 `PumpFunParams::from_dev_trade(..., is_cashback_coin)` 都需要传入 `is_cashback_coin`。从解析出的事件传入(如 sol-parser-sdk 的 `PumpFunTradeEvent.is_cashback_coin`)。
|
||||
- **PumpSwap**:`PumpSwapParams` 有字段 `is_cashback_coin`。手动构造参数(如从池/交易事件)时,从解析到的池或事件数据中设置该字段。
|
||||
- **pumpfun_copy_trading**、**pumpfun_sniper_trading** 示例使用 sol-parser-sdk 订阅 gRPC 事件,并在构造参数时传入 `e.is_cashback_coin`。
|
||||
- **领取返现**:使用 `client.claim_cashback_pumpfun()` 和 `client.claim_cashback_pumpswap(...)` 领取累计的返现。
|
||||
|
||||
#### PumpFun:常见错误与排错思路
|
||||
|
||||
实盘集成时若遇 **Anchor 2006、`NotAuthorized`(6000)、Token program 不匹配、6020/6042** 等,请参阅专门文档:**[Pump.fun 常见链上错误与处理思路(中文)](docs/PUMP_ERRORS_AND_TROUBLESHOOTING_CN.md)**。
|
||||
|
||||
#### PumpFun:Creator Rewards Sharing(creator_vault)
|
||||
|
||||
部分 PumpFun 代币启用了 **Creator Rewards Sharing**,链上 `creator_vault` 可能与默认推导结果不同。若在**卖出**时复用**买入**时缓存的 params,可能触发程序错误 **2006(seeds constraint violated)**。建议:
|
||||
|
||||
- **来自 gRPC/事件(无需 RPC)**:`creator` 与 `creator_vault` 均可从解析后的事件中直接拿到:
|
||||
- **sol-parser-sdk**:推送前会调用 `fill_trade_accounts`,从 buy/sell 指令账户补全 `creator_vault`(buy 索引 9,sell 索引 8);`creator` 来自 TradeEvent 日志。用 `PumpFunParams::from_trade(..., e.creator, e.creator_vault, ...)` 或 `from_dev_trade(..., e.creator, e.creator_vault, ...)` 即可。
|
||||
- **solana-streamer**:指令解析时从 accounts[9](buy)/ accounts[8](sell)写入 `creator_vault`;`creator` 来自合并后的 CPI TradeEvent 日志。同样用事件的 `e.creator`、`e.creator_vault` 调用 `from_trade` / `from_dev_trade`。
|
||||
- **RPC 后覆盖**:若通过 `PumpFunParams::from_mint_by_rpc` 得到 params,之后又从 gRPC 拿到更新的 `creator_vault`,在卖出前对 params 调用 `.with_creator_vault(latest_creator_vault)`。
|
||||
|
||||
SDK 不会在每次卖出时通过 RPC 拉取 creator_vault(以避免延迟);请从 gRPC/事件中传入最新 vault。
|
||||
|
||||
#### PumpSwap:从事件拿 coin_creator_vault(无需 RPC)
|
||||
|
||||
**PumpSwap**(Pump AMM)的 buy/sell 指令需要 `coin_creator_vault_ata` 与 `coin_creator_vault_authority`,二者均可从解析事件中拿到,无需 RPC:
|
||||
|
||||
- **sol-parser-sdk**:指令解析从账户 17、18 写入;若事件来自日志,账户填充器也会从指令补全。用 `PumpSwapParams::from_trade(..., e.coin_creator_vault_ata, e.coin_creator_vault_authority, ...)` 即可。
|
||||
- **solana-streamer**:指令解析从 `accounts.get(17)`、`accounts.get(18)` 写入。同样用事件的 `coin_creator_vault_ata`、`coin_creator_vault_authority` 调用 `from_trade`。
|
||||
|
||||
### Pump.fun Bonding Curve 统一买卖入口与 v2 指令
|
||||
|
||||
Pump.fun 已升级 Bonding Curve 合约,推出**统一化 v2 指令**,通过固定账户布局同时支持 SOL 和 USDC 配对币。旧版 `buy`/`sell`/`buy_exact_sol_in` 仍可用于 SOL 配对币,且保持为默认选项。
|
||||
|
||||
SDK 侧调用入口保持统一:正常使用 `buy` / `sell` 流程即可,SDK 会根据 `quote_mint` 和买/卖的结算 mint 自动选择正确的链上 discriminator 和账户布局。能用 V1 的 native SOL 池会优先用 V1。
|
||||
|
||||
**v2 指令关键变化:**
|
||||
- 新增 `quote_mint` 参数 — native SOL 配对可能表现为默认值、Solscan SOL sentinel(`So11111111111111111111111111111111111111111`)或 WSOL sentinel(`So11111111111111111111111111111111111111112`);USDC/其他真实 quote mint 才选择 V2
|
||||
- 27 个固定账户(buy)/ 26 个固定账户(sell)— **无可选账户**
|
||||
- `buyback_fee_recipient`、`sharing_config` 和 6 个 `associated_quote_*` ATA 变为强制账户
|
||||
- SOL 配对币的报价和成本与旧版一致,无额外开销
|
||||
|
||||
**使用方式:**
|
||||
|
||||
把事件里的 `quote_mint` 传给 `PumpFunParams::from_trade`。`quote_mint` 不是 PDA,它就是 quote SPL mint 或 native SOL sentinel;`Pubkey::default()`、Solscan SOL(`So11111111111111111111111111111111111111111`)和 `WSOL_TOKEN_ACCOUNT` 都表示 native SOL 配对,正常用 SOL 结算时默认走旧版 V1;USDC 表示 USDC V2:
|
||||
|
||||
```rust
|
||||
// native SOL 池:可能是 Pubkey::default()、Solscan SOL sentinel 或 WSOL sentinel
|
||||
// USDC / 非 SOL 池:就是实际 quote SPL mint
|
||||
let quote_mint = e.quote_mint;
|
||||
|
||||
let params = PumpFunParams::from_trade(
|
||||
e.bonding_curve,
|
||||
e.associated_bonding_curve,
|
||||
e.mint,
|
||||
quote_mint,
|
||||
e.creator,
|
||||
e.creator_vault,
|
||||
e.virtual_token_reserves,
|
||||
e.virtual_quote_reserves,
|
||||
e.real_token_reserves,
|
||||
e.real_quote_reserves,
|
||||
close_token_account_when_sell,
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
);
|
||||
|
||||
// 之后正常交易
|
||||
client.buy(buy_params).await?;
|
||||
client.sell(sell_params).await?;
|
||||
```
|
||||
|
||||
USDC 配对币必须用 USDC 买入、卖出也结算为 USDC;SOL/WSOL 只适用于 SOL 配对的 PumpFun 曲线。SOL 配对的普通热路径请传 `SOL`,SDK 会用 V1;只有你明确传 `WSOL` 作为买入输入或卖出输出、希望通过已有 WSOL ATA 结算时,才会选择 V2。
|
||||
SDK 会在提交前拒绝 USDC quote 池的 SOL 输入,避免链上 6063 失败。
|
||||
消费 parser 事件时,需要把 `quoteMint`、`virtualQuoteReserves`、`realQuoteReserves` 传进 `PumpFunParams::from_trade(...)`;USDC 池初始虚拟 quote reserve 是 `4_292_000_000`。
|
||||
legacy SOL 事件里如果 `quote_mint` 是默认值或 Solscan SOL,并且 quote reserve 字段缺失/为 0,应回退使用 `virtual_sol_reserves` / `real_sol_reserves`。
|
||||
|
||||
| quote_mint | 实际使用的指令 | 说明 |
|
||||
|-----------|---------|------|
|
||||
| 未设置(默认)/ `SOL_TOKEN_ACCOUNT` (`So111...11111`) / `WSOL_TOKEN_ACCOUNT` (`So111...11112`) | 优先旧版 `buy`/`sell`/`buy_exact_sol_in` | native SOL 配对;普通 SOL 结算走 V1,显式 WSOL 结算才走 V2 |
|
||||
| `USDC_TOKEN_ACCOUNT` | `buy_v2`/`sell_v2`/`buy_exact_quote_in_v2` | USDC 配对(必须使用 v2) |
|
||||
|
||||
## 🛡️ MEV 保护服务
|
||||
|
||||
可以通过官网申请密钥:[社区官网](https://fnzero.dev/swqos)
|
||||
|
||||
- **Jito**: 高性能区块空间
|
||||
- **ZeroSlot**: 零延迟交易
|
||||
- **Temporal**: 时间敏感交易
|
||||
- **Bloxroute**: 区块链网络加速
|
||||
- **FlashBlock**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://doc.flashblock.trade/)
|
||||
- **BlockRazor**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://blockrazor.gitbook.io/blockrazor/)
|
||||
- **Node1**: 高速交易执行,支持 API 密钥认证 - [官方文档](https://node1.me/docs.html)
|
||||
- **Astralane**: 高速交易执行,支持 API 密钥认证
|
||||
- **FlashBlock**: 高速交易执行,支持 API 密钥认证
|
||||
- **BlockRazor**: 高速交易执行,支持 API 密钥认证
|
||||
- **Astralane**: 区块链网络加速(Binary/Plain HTTP 与 QUIC)
|
||||
- **SpeedLanding**: 高速交易执行,支持 API 密钥认证
|
||||
|
||||
## 📁 项目结构
|
||||
|
||||
@@ -347,4 +538,3 @@ MIT 许可证
|
||||
3. 注意滑点设置避免交易失败
|
||||
4. 监控余额和交易费用
|
||||
5. 遵循相关法律法规
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
## sol-trade-sdk v4.0.2
|
||||
|
||||
This release focuses on QUIC reliability and low-latency submission stability for Astralane.
|
||||
|
||||
### Highlights
|
||||
|
||||
- Fixed Astralane QUIC address-family mismatch that could produce `invalid remote address` when DNS returned IPv6 first and local endpoint was IPv4-only.
|
||||
- Added remote-family-aware local QUIC bind selection:
|
||||
- IPv4 remote -> bind `0.0.0.0:0`
|
||||
- IPv6 remote -> bind `[::]:0`
|
||||
- Added Astralane direct-IP candidate support (official region IPs), with IPv4-first selection for better QUIC stability.
|
||||
- Added automatic endpoint failover and reconnect rotation across candidate addresses, reducing single-endpoint/DNS variance impact.
|
||||
- Kept existing SDK interfaces compatible while improving submit-path resiliency.
|
||||
|
||||
### Also included from recent updates
|
||||
|
||||
- BlockRazor gRPC endpoint fixes and gRPC default transport behavior improvements (v4.0.1).
|
||||
- SWQOS transport path hardening and Binary-Tx response handling improvements (v4.0.0).
|
||||
|
||||
@@ -19,7 +19,7 @@ Include lookup tables in your trade parameters:
|
||||
|
||||
```rust
|
||||
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
||||
let address_lookup_table_account = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key).await.ok();
|
||||
let alt = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key).await?;
|
||||
|
||||
// Include lookup table in trade parameters
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
@@ -29,7 +29,7 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
slippage_basis_points: Some(100),
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: Box::new(PumpFunParams::from_trade(&trade_info, None)),
|
||||
address_lookup_table_account: address_lookup_table_account, // Include lookup table
|
||||
address_lookup_table_accounts: vec![alt], // One ALT
|
||||
wait_transaction_confirmed: true,
|
||||
create_wsol_ata: false,
|
||||
close_wsol_ata: false,
|
||||
@@ -41,6 +41,26 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
client.buy(buy_params).await?;
|
||||
```
|
||||
|
||||
Multiple lookup tables are also supported:
|
||||
|
||||
```rust
|
||||
let alt1 = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key_1).await?;
|
||||
let alt2 = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key_2).await?;
|
||||
|
||||
let params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint_pubkey,
|
||||
BuyAmount::ExactInput(buy_lamports),
|
||||
extension_params,
|
||||
recent_blockhash,
|
||||
gas_fee_strategy,
|
||||
)
|
||||
.address_lookup_table_accounts(vec![alt1, alt2]);
|
||||
```
|
||||
|
||||
Use the same `address_lookup_table_accounts` field for one or many ALTs: `vec![alt]` for a single ALT, `vec![alt1, alt2]` for multiple ALTs.
|
||||
|
||||
## 📊 Performance Comparison
|
||||
|
||||
| Aspect | Without ALT | With ALT | Improvement |
|
||||
@@ -64,4 +84,4 @@ client.buy(buy_params).await?;
|
||||
|
||||
## 📚 External Resources
|
||||
|
||||
- [Solana Address Lookup Tables Documentation](https://docs.solana.com/developing/lookup-tables)
|
||||
- [Solana Address Lookup Tables Documentation](https://docs.solana.com/developing/lookup-tables)
|
||||
|
||||
@@ -19,7 +19,7 @@
|
||||
|
||||
```rust
|
||||
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
||||
let address_lookup_table_account = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key).await.ok();
|
||||
let alt = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key).await?;
|
||||
|
||||
// 在交易参数中包含查找表
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
@@ -29,7 +29,7 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
slippage_basis_points: Some(100),
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: Box::new(PumpFunParams::from_trade(&trade_info, None)),
|
||||
address_lookup_table_account: address_lookup_table_account, // 包含查找表
|
||||
address_lookup_table_accounts: vec![alt], // 1 个 ALT
|
||||
wait_transaction_confirmed: true,
|
||||
create_wsol_ata: false,
|
||||
close_wsol_ata: false,
|
||||
@@ -41,6 +41,26 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
client.buy(buy_params).await?;
|
||||
```
|
||||
|
||||
也支持同时传入多个查找表:
|
||||
|
||||
```rust
|
||||
let alt1 = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key_1).await?;
|
||||
let alt2 = fetch_address_lookup_table_account(&client.rpc, &lookup_table_key_2).await?;
|
||||
|
||||
let params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint_pubkey,
|
||||
BuyAmount::ExactInput(buy_lamports),
|
||||
extension_params,
|
||||
recent_blockhash,
|
||||
gas_fee_strategy,
|
||||
)
|
||||
.address_lookup_table_accounts(vec![alt1, alt2]);
|
||||
```
|
||||
|
||||
单 ALT 和多 ALT 都使用同一个 `address_lookup_table_accounts` 字段:单 ALT 传 `vec![alt]`,多 ALT 传 `vec![alt1, alt2]`。
|
||||
|
||||
## 📊 性能对比
|
||||
|
||||
| 方面 | 不使用 ALT | 使用 ALT | 改进幅度 |
|
||||
@@ -64,4 +84,4 @@ client.buy(buy_params).await?;
|
||||
|
||||
## 📚 外部资源
|
||||
|
||||
- [Solana 地址查找表文档](https://docs.solana.com/developing/lookup-tables)
|
||||
- [Solana 地址查找表文档](https://docs.solana.com/developing/lookup-tables)
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# sol-trade-sdk 代码审查报告
|
||||
|
||||
审查维度:**逻辑准确性**、**可读性**、**模块化**、**超低延迟**、**代码质量**、**安全性**。
|
||||
|
||||
---
|
||||
|
||||
## 1. 代码逻辑准确性
|
||||
|
||||
### 1.1 Instruction 与 IDL / 官方行为
|
||||
|
||||
| 模块 | 结论 | 说明 |
|
||||
|------|------|------|
|
||||
| PumpFun buy/sell | ✅ 一致 | 账户顺序、discriminator、track_volume 与 `idl/pump.json` 一致;cashback 时 remainingAccounts 顺序正确 |
|
||||
| PumpSwap buy/sell | ✅ 一致 | 与 `idl/pump_amm.json` 一致;sell cashback 使用 quote_mint ATA |
|
||||
| PDA 推导 | ✅ 一致 | bonding_curve_v2、pool_v2、user_volume_accumulator、creator_vault 等 seeds 与官方一致 |
|
||||
|
||||
### 1.2 需修正的逻辑/风格
|
||||
|
||||
- **`src/instruction/utils/pumpswap.rs` 约 258、291 行**:`let program_id: &Pubkey = &&accounts::AMM_PROGRAM` 为双重引用,易误导且多余。建议改为 `&accounts::AMM_PROGRAM`。
|
||||
|
||||
---
|
||||
|
||||
## 2. 代码可读性
|
||||
|
||||
### 2.1 命名与注释
|
||||
|
||||
- 多数模块有中英文注释,instruction 与 IDL 的对应关系有标注。
|
||||
- **建议**:`src/instruction/pumpfun.rs` 约 259 行 sell 的 discriminator 使用魔法数组 `[51, 230, 133, ...]`,建议改为 `SELL_DISCRIMINATOR` 常量(与 buy 路径一致)。
|
||||
|
||||
### 2.2 错误信息与文案
|
||||
|
||||
- **建议**:`src/lib.rs` 中 “Current version only support” 应为 “only supports”;类似拼写/语法可统一检查。
|
||||
|
||||
### 2.3 过长函数
|
||||
|
||||
- **建议**:`src/lib.rs` 的 `ensure_wsol_ata` 可拆为「入口 + 重试循环」与「单次尝试 + 结果判断」,便于单测和阅读。
|
||||
|
||||
---
|
||||
|
||||
## 3. 模块化
|
||||
|
||||
### 3.1 职责与分层
|
||||
|
||||
- **instruction**:按协议分(pumpfun / pumpswap / bonk / raydium_* 等),实现 `InstructionBuilder`,边界清晰。
|
||||
- **instruction/utils**:PDA、常量、类型、池子解析与上层「组指令」分工明确。
|
||||
- **swqos**:按提供商分模块,common 放序列化、确认轮询、HTTP 客户端,无循环依赖。
|
||||
- **结论**:分层合理,模块化良好。
|
||||
|
||||
---
|
||||
|
||||
## 4. 超低延迟
|
||||
|
||||
### 4.1 必须改:避免多余 clone
|
||||
|
||||
| 位置 | 问题 | 建议 |
|
||||
|------|------|------|
|
||||
| `src/instruction/pumpswap.rs` 约 232、429 行 | `Instruction { accounts: accounts.clone(), data }` 对已拥有的 `Vec<AccountMeta>` 做完整 clone | 改为直接移动:`Instruction { program_id, accounts, data }`,不再 clone |
|
||||
|
||||
### 4.2 建议
|
||||
|
||||
- 若多路 SWQOS 并发发**同一笔**交易,可在调用方序列化一次,再传 `&[u8]` 给各 client,减少重复 bincode 序列化。
|
||||
- 热点路径未见不必要的 `Mutex`/`RwLock` 竞争,当前设计可接受。
|
||||
|
||||
---
|
||||
|
||||
## 5. 代码质量
|
||||
|
||||
### 5.1 必须改:避免 panic 的 unwrap
|
||||
|
||||
以下 PDA 或关键 `Option` 使用 `.unwrap()`,在异常输入下会直接 panic,建议改为 `Result` 并向上传播错误:
|
||||
|
||||
| 文件 | 行号(约) | 说明 |
|
||||
|------|------------|------|
|
||||
| `src/instruction/pumpfun.rs` | 67, 101, 149, 221, 291, 295 | `get_bonding_curve_pda`、`get_user_volume_accumulator_pda`、`get_bonding_curve_v2_pda` |
|
||||
| `src/instruction/pumpswap.rs` | 184, 198, 385, 407 | `get_user_volume_accumulator_pda`、`get_pool_v2_pda` |
|
||||
| `src/instruction/utils/pumpfun.rs` | 229 | `DEFAULT_CREATOR_VAULT.unwrap()`(LazyLock 未初始化时可能 panic) |
|
||||
| `src/instruction/bonk.rs` | 多处 | `get_pool_pda`、`get_vault_pda`、`params.rpc.as_ref().unwrap()` |
|
||||
| `src/instruction/utils/bonk.rs` | 110–116, 148–152 | `checked_*` 链后 `.unwrap()`,数学假设不成立会 panic |
|
||||
| `src/instruction/raydium_cpmm.rs` | 46, 106, 189, 250 | PDA / 状态相关 unwrap |
|
||||
| `src/instruction/utils/raydium_cpmm.rs` | 83, 85, 141 | `get_vault_pda(...).unwrap()` |
|
||||
|
||||
**建议**:统一改为 `.ok_or_else(|| anyhow!("..."))?` 或返回 `Result`,在调用链顶层处理错误,避免进程退出。
|
||||
|
||||
### 5.2 建议
|
||||
|
||||
- **测试**:为 instruction 构建(或至少 PDA + discriminator/data 布局)增加单元测试,固定输入与预期 bytes/accounts 比对,便于 IDL 升级时回归。
|
||||
- **错误类型**:`claim_cashback_*` 等返回 `Option<Instruction>`;可考虑统一为 `Result<Instruction>` 并带“无法构建”原因,或在文档中明确 None 的语义。
|
||||
|
||||
---
|
||||
|
||||
## 6. 安全性
|
||||
|
||||
### 6.1 必须改:API key 不得写入日志
|
||||
|
||||
| 位置 | 问题 | 建议 |
|
||||
|------|------|------|
|
||||
| `src/swqos/astralane_quic.rs` 约 61 行 | `info!(..., "api_key as CN: {}", api_key)` | 移除 api_key 或改为占位(如 `***` / 仅长度) |
|
||||
| `src/swqos/astralane_quic.rs` 约 74 行 | `info!(..., "Connected at {} (api_key: {})", addr, api_key)` | 同上 |
|
||||
|
||||
### 6.2 必须改:SkipServerVerification 风险
|
||||
|
||||
| 位置 | 问题 | 建议 |
|
||||
|------|------|------|
|
||||
| `src/swqos/astralane_quic.rs` 约 179–181 行 | `with_custom_certificate_verifier(SkipServerVerification)` 完全跳过服务端证书校验 | 1)若服务端提供证书:用 `RootCertStore` 或固定证书做校验;2)若仅 dev/内网:用 feature 或配置限制,并在文档/日志中明确“仅受控环境使用”;3)默认/生产构建建议不跳过校验 |
|
||||
|
||||
### 6.3 建议
|
||||
|
||||
- **敏感配置**:确保生产环境从环境变量或安全配置读取 API key,并在文档中说明。
|
||||
- **依赖**:定期执行 `cargo audit` 与依赖升级。
|
||||
- **unsafe**:`perf/hardware_optimizations.rs`、`realtime_tuning.rs` 中的 `unsafe` 使用范围可控,需保持注释中的安全约定。
|
||||
|
||||
---
|
||||
|
||||
## 7. 三库联动与超低延迟检查(sol-trade-sdk / sol-parser-sdk / solana-streamer)
|
||||
|
||||
### 7.1 逻辑一致性(已确认)
|
||||
|
||||
| 检查项 | sol-parser-sdk | solana-streamer | 说明 |
|
||||
|--------|----------------|-----------------|------|
|
||||
| Pump buy 账户数 | 16(fill 用 get(9) 填 creator_vault) | 16,accounts[9]=creator_vault | 与 idl/pumpfun.json 一致 |
|
||||
| Pump sell 账户数 | 14(get(8)=creator_vault) | 14,accounts[8]=creator_vault | 一致 |
|
||||
| PumpSwap buy 17/18 | 指令解析 + fill_buy_accounts get(17)/get(18) | 指令解析 accounts.get(17)/get(18) | coin_creator_vault_ata/authority 正确 |
|
||||
| PumpSwap sell 17/18 | fill_sell_accounts 同左 | 同左 | 一致 |
|
||||
| 填充顺序 | 先 parse(log 或 instruction)→ fill_accounts → push | 指令解析直接写 17/18;无单独 fill 步骤 | 两者均保证事件带齐 creator_vault / coin_creator_vault |
|
||||
| find_instruction_invoke | 选「账户数最多」的 invoke,保证取到 outer buy/sell | N/A(按当前 instruction 解析) | 正确 |
|
||||
|
||||
### 7.2 版本化交易账户解析
|
||||
|
||||
- **sol-parser-sdk**:`get_instruction_account_getter` 正确支持 versioned tx:先 `account_keys`,再 `loaded_writable_addresses`,再 `loaded_readonly_addresses`,与 Solana 约定一致。
|
||||
- **solana-streamer**:指令的 `accounts` 为索引,通过 `accounts.get(idx as usize).copied()` 从完整 `accounts: &[Pubkey]` 解析;调用方需传入已包含 loaded 的完整账户列表,否则高索引会得到 `default()`。
|
||||
|
||||
### 7.3 超低延迟相关
|
||||
|
||||
| 项目 | 状态 / 建议 |
|
||||
|------|-------------|
|
||||
| solana-streamer 热路径 | 已改为**顺序执行** inner 解析与 swap_data 提取,去掉 `thread::scope` + 双 spawn/join,减少 μs 级开销。 |
|
||||
| sol-parser-sdk | log 与 instruction 并行(rayon::join);fill 仅在有 invoke 时做;`find_instruction_invoke` 为 O(invokes),单程序单 tx 下可接受。 |
|
||||
| sol-trade-sdk | 见上文第 4 节;PumpSwap instruction 构建避免 `accounts.clone()` 已列为必须改。 |
|
||||
|
||||
### 7.4 建议
|
||||
|
||||
- **solana-streamer**:若 gRPC 上游已提供完整 `accounts`(含 loaded),可避免对每笔 tx 做 `accounts.to_vec()`,仅在需要 resize 时克隆,进一步降低分配。
|
||||
- **三库**:保持 IDL 与账户索引注释同步(pumpfun.json / pump_amm.json),避免后续扩展时索引错位。
|
||||
|
||||
---
|
||||
|
||||
## 8. 汇总:必须改 vs 建议改
|
||||
|
||||
### 必须改(优先处理)
|
||||
|
||||
| 序号 | 项 | 位置 |
|
||||
|------|----|------|
|
||||
| 1 | 移除 astralane_quic 中 API key 的日志输出 | `src/swqos/astralane_quic.rs` 61、74 行 |
|
||||
| 2 | SkipServerVerification:改为证书校验或仅限 dev 并文档化 | `src/swqos/astralane_quic.rs` 179–181 行 |
|
||||
| 3 | instruction 中 PDA 等 `.unwrap()` 改为 `Result` 并传播错误 | pumpfun.rs、pumpswap.rs、pumpfun/utils、bonk、raydium_cpmm 等 |
|
||||
| 4 | PumpSwap 构建 instruction 时避免 `accounts.clone()`,改为移动 | `src/instruction/pumpswap.rs` 232、429 行 |
|
||||
|
||||
### 建议改(可分批)
|
||||
|
||||
| 序号 | 项 | 位置 |
|
||||
|------|----|------|
|
||||
| 5 | PDA 的 `program_id` 从 `&&AMM_PROGRAM` 改为 `&AMM_PROGRAM` | `src/instruction/utils/pumpswap.rs` 258、291 行 |
|
||||
| 6 | PumpFun sell discriminator 改为命名常量 | `src/instruction/pumpfun.rs` 约 259 行 |
|
||||
| 7 | `ensure_wsol_ata` 拆分;修正 “only support” 等文案 | `src/lib.rs` |
|
||||
| 8 | 为 instruction 构建与 PDA 增加单元测试 | 新建 tests 或模块下 |
|
||||
| 9 | 生产日志用 tracing 替代 println!/eprintln! | `src/swqos/astralane.rs` 等 |
|
||||
|
||||
---
|
||||
|
||||
*报告基于当前仓库与 IDL 的静态阅读;若官方 SDK 或链上程序有未公开变更,建议再与官方实现或链上行为做一次对照验证。*
|
||||
@@ -49,7 +49,6 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
slippage_basis_points: Some(100),
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: Box::new(PumpFunParams::from_trade(&trade_info, None)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
create_wsol_ata: false,
|
||||
close_wsol_ata: false,
|
||||
|
||||
@@ -49,7 +49,6 @@ let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
slippage_basis_points: Some(100),
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: Box::new(PumpFunParams::from_trade(&trade_info, None)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
create_wsol_ata: false,
|
||||
close_wsol_ata: false,
|
||||
|
||||
@@ -0,0 +1,208 @@
|
||||
# Pump.fun(Bonding 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. SPL:Token **`initializeAccount3`**——`incorrect program id for instruction`
|
||||
|
||||
### 现象
|
||||
|
||||
- 内联指令里 **`Token Program: initializeAccount3`**(或 Token-2022 等价指令)报错 **`incorrect program id for instruction`**。
|
||||
|
||||
### 含义
|
||||
|
||||
为 **Mint** 创建用户 ATA 时,使用的 **token program(Legacy 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/` 下按相同结构扩展。
|
||||
+98
-10
@@ -4,14 +4,104 @@ This document provides a comprehensive reference for all trading parameters used
|
||||
|
||||
## 📋 Table of Contents
|
||||
|
||||
- [SimpleBuyParams / SimpleSellParams](#simplebuyparams--simplesellparams)
|
||||
- [TradeBuyParams](#tradebuyparams)
|
||||
- [TradeSellParams](#tradesellparams)
|
||||
- [Parameter Categories](#parameter-categories)
|
||||
- [Important Notes](#important-notes)
|
||||
|
||||
## SimpleBuyParams / SimpleSellParams
|
||||
|
||||
Use `SimpleBuyParams` and `SimpleSellParams` for new integrations. They keep the public API focused on trading intent and map to the lower-level `TradeBuyParams` / `TradeSellParams` internally.
|
||||
|
||||
### SimpleBuyParams
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `dex_type` | `DexType` | ✅ | Protocol to trade through, for example `DexType::PumpFun`. |
|
||||
| `pay_with` | `TradeTokenType` | ✅ | Quote token used to pay for the buy. Use `SOL` when the wallet spends native SOL. For PumpFun V2 SOL/WSOL quote pools, still use `SOL` if you want native SOL settlement. |
|
||||
| `mint` | `Pubkey` | ✅ | Mint of the token being bought. |
|
||||
| `amount` | `BuyAmount` | ✅ | Buy sizing intent. Choose one enum variant instead of combining low-level amount flags. |
|
||||
| `extension_params` | `DexParamEnum` | ✅ | Protocol state from parser/RPC cache, such as `DexParamEnum::PumpFun(PumpFunParams::from_trade(...))`. |
|
||||
| `recent_blockhash` | `Hash` | ✅ for `new` | Cached recent blockhash for non-nonce transactions. The SDK does not fetch this on the hot path. |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Compute unit price/limit and relay tip configuration. |
|
||||
| `slippage_basis_points` | `Option<u64>` | ❌ | Optional slippage override. `100` means 1%. |
|
||||
| `account_policy` | `AccountPolicy` | ❌ | ATA creation/close behavior. Default is `Auto`. |
|
||||
| `address_lookup_table_accounts` | `Vec<AddressLookupTableAccount>` | ❌ | Optional ALT list. Pass one element for a single ALT or multiple elements for multi-ALT to reduce transaction size. |
|
||||
| `wait_tx_confirmed` | `bool` | ❌ | Whether to wait for chain confirmation before returning. Default is `false`. |
|
||||
| `wait_for_all_submits` | `bool` | ❌ | Wait for every SWQoS lane response and return submitted signatures; useful for poll-any confirmation or external monitoring. Recent-blockhash route variants are not mutually exclusive; durable nonce variants are. |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce info. Use `.durable_nonce(nonce_info)` or `SimpleBuyParams::with_durable_nonce(...)`; do not combine with `recent_blockhash`. |
|
||||
| `simulate` | `bool` | ❌ | Build and simulate instead of submitting. Default is `false`. |
|
||||
| `grpc_recv_us` | `Option<i64>` | ❌ | Upstream receive timestamp in microseconds for latency tracing. |
|
||||
|
||||
### SimpleSellParams
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `dex_type` | `DexType` | ✅ | Protocol to trade through, for example `DexType::PumpFun`. |
|
||||
| `receive_as` | `TradeTokenType` | ✅ | Quote token to receive from the sell. Use `SOL` when you want native SOL output. |
|
||||
| `mint` | `Pubkey` | ✅ | Mint of the token being sold. |
|
||||
| `amount` | `SellAmount` | ✅ | Sell sizing intent. |
|
||||
| `extension_params` | `DexParamEnum` | ✅ | Protocol state from parser/RPC cache. |
|
||||
| `recent_blockhash` | `Hash` | ✅ for `new` | Cached recent blockhash for non-nonce transactions. |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Compute unit price/limit and relay tip configuration. |
|
||||
| `slippage_basis_points` | `Option<u64>` | ❌ | Optional slippage override. `100` means 1%. |
|
||||
| `account_policy` | `AccountPolicy` | ❌ | ATA creation/close behavior. Default is `Auto`. |
|
||||
| `address_lookup_table_accounts` | `Vec<AddressLookupTableAccount>` | ❌ | Optional ALT list. Pass one element for a single ALT or multiple elements for multi-ALT to reduce transaction size. |
|
||||
| `wait_tx_confirmed` | `bool` | ❌ | Whether to wait for chain confirmation before returning. Default is `false`. |
|
||||
| `wait_for_all_submits` | `bool` | ❌ | Wait for every SWQoS lane response and return submitted signatures; useful for poll-any confirmation or external monitoring. Recent-blockhash route variants are not mutually exclusive; durable nonce variants are. |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce info. Use `.durable_nonce(nonce_info)` or `SimpleSellParams::with_durable_nonce(...)`; do not combine with `recent_blockhash`. |
|
||||
| `simulate` | `bool` | ❌ | Build and simulate instead of submitting. Default is `false`. |
|
||||
| `with_tip` | `bool` | ❌ | Whether sells include relay tips. Default is `true`; set with `.with_tip(false)`. |
|
||||
| `grpc_recv_us` | `Option<i64>` | ❌ | Upstream receive timestamp in microseconds for latency tracing. |
|
||||
|
||||
### Amount Selection
|
||||
|
||||
| Variant | Meaning | Low-level mapping |
|
||||
|---------|---------|-------------------|
|
||||
| `BuyAmount::ExactInput(amount)` | Spend exactly this quote amount; slippage protects minimum token output. | `input_token_amount = amount`, `use_exact_sol_amount = Some(true)` |
|
||||
| `BuyAmount::WithMaxInput { quote_amount }` | Regular PumpFun/PumpSwap buy. The SDK estimates output and applies slippage to max quote cost. | `input_token_amount = quote_amount`, `use_exact_sol_amount = Some(false)` |
|
||||
| `BuyAmount::ExactOutput { output_amount, max_input_amount }` | Buy an exact token amount while limiting max quote input. | `fixed_output_token_amount = Some(output_amount)`, `input_token_amount = max_input_amount` |
|
||||
| `SellAmount::ExactInput(amount)` | Sell exactly this token amount; slippage protects minimum quote output. | `input_token_amount = amount` |
|
||||
| `SellAmount::ExactOutput { output_amount, max_input_amount }` | Receive an exact quote amount while limiting token input, where supported. | `fixed_output_token_amount = Some(output_amount)`, `input_token_amount = max_input_amount` |
|
||||
|
||||
### AccountPolicy
|
||||
|
||||
| Variant | Behavior | Use when |
|
||||
|---------|----------|----------|
|
||||
| `Auto` | SDK creates practical ATAs when needed. Buy creates the target mint ATA; sell creates the output ATA for non-SOL outputs. | Normal apps and manual trading tools. |
|
||||
| `HotPathMinimal` | No ATA create/close instructions in the trade transaction. | Bots, sniping, arbitrage, and any path sensitive to transaction size. |
|
||||
| `CreateMissing` | Include ATA creation where possible. | Convenience matters more than smallest transaction size. |
|
||||
| `AssumePrepared` | Do not create or close token accounts; caller prepared everything. | Advanced deterministic flows. |
|
||||
|
||||
### Durable Nonce With Simple Params
|
||||
|
||||
`fetch_nonce_info` and `DurableNonceInfo` are re-exported from the crate root:
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{fetch_nonce_info, SimpleBuyParams};
|
||||
|
||||
let nonce_info = fetch_nonce_info(&client.infrastructure.rpc, nonce_account)
|
||||
.await
|
||||
.expect("nonce account must be initialized");
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
dex_type,
|
||||
pay_with,
|
||||
mint,
|
||||
amount,
|
||||
extension_params,
|
||||
recent_blockhash,
|
||||
gas_fee_strategy,
|
||||
)
|
||||
.durable_nonce(nonce_info);
|
||||
```
|
||||
|
||||
Calling `.durable_nonce(...)` clears `recent_blockhash`; nonce transactions use the nonce value as the transaction blockhash.
|
||||
|
||||
## TradeBuyParams
|
||||
|
||||
The `TradeBuyParams` struct contains all parameters required for executing buy orders across different DEX protocols.
|
||||
`TradeBuyParams` is the advanced low-level buy API. New integrations should prefer `SimpleBuyParams` unless they need direct control over individual ATA flags.
|
||||
|
||||
### Basic Trading Parameters
|
||||
|
||||
@@ -29,13 +119,12 @@ The `TradeBuyParams` struct contains all parameters required for executing buy o
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | Address lookup table for transaction optimization |
|
||||
| `wait_transaction_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||
| `wait_tx_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||
| `create_input_token_ata` | `bool` | ✅ | Whether to create input token Associated Token Account |
|
||||
| `close_input_token_ata` | `bool` | ✅ | Whether to close input token ATA after transaction |
|
||||
| `create_mint_ata` | `bool` | ✅ | Whether to create token mint ATA |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce information containing nonce account and current nonce value |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | Optional fixed output token amount. If set, this value will be directly assigned to the output amount instead of being calculated (required for Meteora DAMM V2) |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | Optional fixed output token amount. On exact-out capable DEXes, this uses the exact-out instruction and treats input_token_amount as the max input budget (required for Meteora DAMM V2) |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Gas fee strategy instance for controlling transaction fees and priorities |
|
||||
| `simulate` | `bool` | ✅ | Whether to simulate the transaction instead of executing it. When true, the transaction will be simulated via RPC to validate and show detailed logs, compute units consumed, and potential errors without actually submitting to the blockchain |
|
||||
|
||||
@@ -61,13 +150,12 @@ The `TradeSellParams` struct contains all parameters required for executing sell
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
|-----------|------|----------|-------------|
|
||||
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | Address lookup table for transaction optimization |
|
||||
| `wait_transaction_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||
| `wait_tx_confirmed` | `bool` | ✅ | Whether to wait for transaction confirmation |
|
||||
| `create_output_token_ata` | `bool` | ✅ | Whether to create output token Associated Token Account |
|
||||
| `close_output_token_ata` | `bool` | ✅ | Whether to close output token ATA after transaction |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | Durable nonce information containing nonce account and current nonce value |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Gas fee strategy instance for controlling transaction fees and priorities |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | Optional fixed output token amount. If set, this value will be directly assigned to the output amount instead of being calculated (required for Meteora DAMM V2) |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | Optional fixed output token amount. On exact-out capable DEXes, this uses the exact-out instruction and treats input_token_amount as the max input budget (required for Meteora DAMM V2) |
|
||||
| `simulate` | `bool` | ✅ | Whether to simulate the transaction instead of executing it. When true, the transaction will be simulated via RPC to validate and show detailed logs, compute units consumed, and potential errors without actually submitting to the blockchain |
|
||||
|
||||
|
||||
@@ -88,7 +176,7 @@ These parameters are essential for defining the basic trading operation:
|
||||
These parameters control how the transaction is processed:
|
||||
|
||||
- **slippage_basis_points**: Controls acceptable price slippage
|
||||
- **wait_transaction_confirmed**: Controls whether to wait for confirmation
|
||||
- **wait_tx_confirmed**: Controls whether to wait for confirmation
|
||||
|
||||
### 🔧 Account Management Parameters
|
||||
|
||||
@@ -102,7 +190,7 @@ These parameters control automatic account creation and management:
|
||||
|
||||
These parameters enable advanced optimizations:
|
||||
|
||||
- **address_lookup_table_account**: Use address lookup tables for reduced transaction size
|
||||
- **address_lookup_table_accounts**: Use one or more address lookup tables for reduced transaction size
|
||||
|
||||
### 🔄 Token Type Parameters
|
||||
|
||||
@@ -146,7 +234,7 @@ The account management parameters provide granular control:
|
||||
|
||||
### 🔍 Address Lookup Tables
|
||||
|
||||
Before using `address_lookup_table_account`:
|
||||
Before using `address_lookup_table_accounts`:
|
||||
- Lookup tables reduce transaction size and improve success rates
|
||||
- Particularly beneficial for complex transactions with many account references
|
||||
|
||||
|
||||
@@ -4,14 +4,104 @@
|
||||
|
||||
## 📋 目录
|
||||
|
||||
- [SimpleBuyParams / SimpleSellParams](#simplebuyparams--simplesellparams)
|
||||
- [TradeBuyParams](#tradebuyparams)
|
||||
- [TradeSellParams](#tradesellparams)
|
||||
- [参数分类](#参数分类)
|
||||
- [重要说明](#重要说明)
|
||||
|
||||
## SimpleBuyParams / SimpleSellParams
|
||||
|
||||
新接入优先使用 `SimpleBuyParams` 和 `SimpleSellParams`。这两个结构体描述交易意图,SDK 内部会转换成低层 `TradeBuyParams` / `TradeSellParams`。
|
||||
|
||||
### SimpleBuyParams
|
||||
|
||||
| 参数 | 类型 | 必需 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `dex_type` | `DexType` | ✅ | 使用哪个协议交易,例如 `DexType::PumpFun`。 |
|
||||
| `pay_with` | `TradeTokenType` | ✅ | 买入时用什么 quote 支付。钱包实际花原生 SOL 就传 `SOL`。PumpFun V2 的 SOL/WSOL quote 池,如果你想用原生 SOL 结算,也仍然传 `SOL`。 |
|
||||
| `mint` | `Pubkey` | ✅ | 要买入的 token mint。 |
|
||||
| `amount` | `BuyAmount` | ✅ | 买入数量语义。选择一个枚举,不再组合多个低层数量字段。 |
|
||||
| `extension_params` | `DexParamEnum` | ✅ | 协议状态参数,来自 parser/RPC 缓存,例如 `DexParamEnum::PumpFun(PumpFunParams::from_trade(...))`。 |
|
||||
| `recent_blockhash` | `Hash` | ✅,使用 `new` 时 | 非 nonce 交易使用的 recent blockhash。SDK 不会在热路径临时获取。 |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | CU price/limit 和 relay tip 配置。 |
|
||||
| `slippage_basis_points` | `Option<u64>` | ❌ | 可选滑点覆盖。`100` 表示 1%。 |
|
||||
| `account_policy` | `AccountPolicy` | ❌ | ATA 创建/关闭策略。默认 `Auto`。 |
|
||||
| `address_lookup_table_accounts` | `Vec<AddressLookupTableAccount>` | ❌ | 可选 ALT 列表。传 1 个元素表示单 ALT,传多个元素表示多 ALT,用于减少交易体积。 |
|
||||
| `wait_tx_confirmed` | `bool` | ❌ | 是否等链上确认后再返回。默认 `false`。 |
|
||||
| `wait_for_all_submits` | `bool` | ❌ | 是否等待所有 SWQoS 通道返回并拿到已提交签名;适合 poll-any 确认或外部监控。recent blockhash 多路交易不互斥;durable nonce 多路交易互斥。 |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | durable nonce 信息。使用 `.durable_nonce(nonce_info)` 或 `SimpleBuyParams::with_durable_nonce(...)` 设置,不要和 `recent_blockhash` 混用。 |
|
||||
| `simulate` | `bool` | ❌ | 只构建并模拟交易,不提交。默认 `false`。 |
|
||||
| `grpc_recv_us` | `Option<i64>` | ❌ | 上游收到事件的微秒时间戳,用于延迟追踪。 |
|
||||
|
||||
### SimpleSellParams
|
||||
|
||||
| 参数 | 类型 | 必需 | 说明 |
|
||||
|------|------|------|------|
|
||||
| `dex_type` | `DexType` | ✅ | 使用哪个协议交易,例如 `DexType::PumpFun`。 |
|
||||
| `receive_as` | `TradeTokenType` | ✅ | 卖出后接收什么 quote。想收原生 SOL 就传 `SOL`。 |
|
||||
| `mint` | `Pubkey` | ✅ | 要卖出的 token mint。 |
|
||||
| `amount` | `SellAmount` | ✅ | 卖出数量语义。 |
|
||||
| `extension_params` | `DexParamEnum` | ✅ | 协议状态参数,来自 parser/RPC 缓存。 |
|
||||
| `recent_blockhash` | `Hash` | ✅,使用 `new` 时 | 非 nonce 交易使用的 recent blockhash。 |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | CU price/limit 和 relay tip 配置。 |
|
||||
| `slippage_basis_points` | `Option<u64>` | ❌ | 可选滑点覆盖。`100` 表示 1%。 |
|
||||
| `account_policy` | `AccountPolicy` | ❌ | ATA 创建/关闭策略。默认 `Auto`。 |
|
||||
| `address_lookup_table_accounts` | `Vec<AddressLookupTableAccount>` | ❌ | 可选 ALT 列表。传 1 个元素表示单 ALT,传多个元素表示多 ALT,用于减少交易体积。 |
|
||||
| `wait_tx_confirmed` | `bool` | ❌ | 是否等链上确认后再返回。默认 `false`。 |
|
||||
| `wait_for_all_submits` | `bool` | ❌ | 是否等待所有 SWQoS 通道返回并拿到已提交签名;适合 poll-any 确认或外部监控。recent blockhash 多路交易不互斥;durable nonce 多路交易互斥。 |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | durable nonce 信息。使用 `.durable_nonce(nonce_info)` 或 `SimpleSellParams::with_durable_nonce(...)` 设置,不要和 `recent_blockhash` 混用。 |
|
||||
| `simulate` | `bool` | ❌ | 只构建并模拟交易,不提交。默认 `false`。 |
|
||||
| `with_tip` | `bool` | ❌ | 卖出交易是否带 relay tip。默认 `true`,可通过 `.with_tip(false)` 关闭。 |
|
||||
| `grpc_recv_us` | `Option<i64>` | ❌ | 上游收到事件的微秒时间戳,用于延迟追踪。 |
|
||||
|
||||
### 数量如何选择
|
||||
|
||||
| 枚举 | 含义 | 底层映射 |
|
||||
|------|------|----------|
|
||||
| `BuyAmount::ExactInput(amount)` | 精确花费指定 quote 数量,滑点保护最小买到 token 数量。 | `input_token_amount = amount`,`use_exact_sol_amount = Some(true)` |
|
||||
| `BuyAmount::WithMaxInput { quote_amount }` | 常规 PumpFun/PumpSwap buy。SDK 估算输出,并把滑点作用在最大 quote 成本上。 | `input_token_amount = quote_amount`,`use_exact_sol_amount = Some(false)` |
|
||||
| `BuyAmount::ExactOutput { output_amount, max_input_amount }` | 精确买到指定 token 数量,并限制最多花多少 quote。 | `fixed_output_token_amount = Some(output_amount)`,`input_token_amount = max_input_amount` |
|
||||
| `SellAmount::ExactInput(amount)` | 精确卖出指定 token 数量,滑点保护最少收到 quote 数量。 | `input_token_amount = amount` |
|
||||
| `SellAmount::ExactOutput { output_amount, max_input_amount }` | 精确收到指定 quote 数量,并限制最多卖出多少 token;取决于 DEX 是否支持。 | `fixed_output_token_amount = Some(output_amount)`,`input_token_amount = max_input_amount` |
|
||||
|
||||
### AccountPolicy
|
||||
|
||||
| 枚举 | 行为 | 适用场景 |
|
||||
|------|------|----------|
|
||||
| `Auto` | SDK 按实际路径创建必要 ATA。买入会创建目标 token ATA;卖出接收非 SOL 时会创建输出 ATA。 | 普通应用、手动交易工具。 |
|
||||
| `HotPathMinimal` | 交易内不创建/关闭 ATA。 | Bot、狙击、套利、对交易体积敏感的路径。 |
|
||||
| `CreateMissing` | 尽量在交易内创建缺失 ATA。 | 更重视方便,不追求最小交易体积。 |
|
||||
| `AssumePrepared` | 不创建也不关闭 token account,调用方保证都已准备好。 | 高级确定性流程。 |
|
||||
|
||||
### Simple 参数使用 Durable Nonce
|
||||
|
||||
`fetch_nonce_info` 和 `DurableNonceInfo` 已从 crate root 重新导出:
|
||||
|
||||
```rust
|
||||
use sol_trade_sdk::{fetch_nonce_info, SimpleBuyParams};
|
||||
|
||||
let nonce_info = fetch_nonce_info(&client.infrastructure.rpc, nonce_account)
|
||||
.await
|
||||
.expect("nonce account must be initialized");
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
dex_type,
|
||||
pay_with,
|
||||
mint,
|
||||
amount,
|
||||
extension_params,
|
||||
recent_blockhash,
|
||||
gas_fee_strategy,
|
||||
)
|
||||
.durable_nonce(nonce_info);
|
||||
```
|
||||
|
||||
调用 `.durable_nonce(...)` 会清空 `recent_blockhash`;nonce 交易会使用 nonce value 作为 transaction blockhash。
|
||||
|
||||
## TradeBuyParams
|
||||
|
||||
`TradeBuyParams` 结构体包含在不同 DEX 协议上执行买入订单所需的所有参数。
|
||||
`TradeBuyParams` 是高级低层买入 API。新接入建议优先使用 `SimpleBuyParams`,只有需要直接控制单个 ATA flag 时再使用它。
|
||||
|
||||
### 基础交易参数
|
||||
|
||||
@@ -29,13 +119,12 @@
|
||||
|
||||
| 参数 | 类型 | 必需 | 描述 |
|
||||
|------|------|------|------|
|
||||
| `address_lookup_table_account` | `Option<Pubkey>` | ❌ | 用于交易优化的地址查找表 |
|
||||
| `wait_transaction_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||
| `wait_tx_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||
| `create_input_token_ata` | `bool` | ✅ | 是否创建输入代币关联代币账户 |
|
||||
| `close_input_token_ata` | `bool` | ✅ | 交易后是否关闭输入代币 ATA |
|
||||
| `create_mint_ata` | `bool` | ✅ | 是否创建代币 mint ATA |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | 持久 nonce 信息,包含 nonce 账户和当前 nonce 值 |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | 可选的固定输出代币数量。如果设置,此值将直接分配给输出数量而不是通过计算得出(Meteora DAMM V2 必需) |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | 可选的固定输出代币数量。对于支持 exact-out 的 DEX,会使用 exact-out 指令,并将 input_token_amount 作为最大输入预算(Meteora DAMM V2 必需) |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Gas fee 策略实例,用于控制交易费用和优先级 |
|
||||
| `simulate` | `bool` | ✅ | 是否模拟交易而不实际执行。当为 true 时,将通过 RPC 模拟交易以验证并显示详细日志、计算单元消耗和潜在错误,而不会实际提交到区块链 |
|
||||
|
||||
@@ -61,13 +150,12 @@
|
||||
|
||||
| 参数 | 类型 | 必需 | 描述 |
|
||||
|------|------|------|------|
|
||||
| `address_lookup_table_account` | `Option<AddressLookupTableAccount>` | ❌ | 用于交易优化的地址查找表 |
|
||||
| `wait_transaction_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||
| `wait_tx_confirmed` | `bool` | ✅ | 是否等待交易确认 |
|
||||
| `create_output_token_ata` | `bool` | ✅ | 是否创建输出代币关联代币账户 |
|
||||
| `close_output_token_ata` | `bool` | ✅ | 交易后是否关闭输出代币 ATA |
|
||||
| `durable_nonce` | `Option<DurableNonceInfo>` | ❌ | 持久 nonce 信息,包含 nonce 账户和当前 nonce 值 |
|
||||
| `gas_fee_strategy` | `GasFeeStrategy` | ✅ | Gas fee 策略实例,用于控制交易费用和优先级 |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | 可选的固定输出代币数量。如果设置,此值将直接分配给输出数量而不是通过计算得出(Meteora DAMM V2 必需) |
|
||||
| `fixed_output_token_amount` | `Option<u64>` | ❌ | 可选的固定输出代币数量。对于支持 exact-out 的 DEX,会使用 exact-out 指令,并将 input_token_amount 作为最大输入预算(Meteora DAMM V2 必需) |
|
||||
| `simulate` | `bool` | ✅ | 是否模拟交易而不实际执行。当为 true 时,将通过 RPC 模拟交易以验证并显示详细日志、计算单元消耗和潜在错误,而不会实际提交到区块链 |
|
||||
|
||||
|
||||
@@ -88,7 +176,7 @@
|
||||
这些参数控制交易的处理方式:
|
||||
|
||||
- **slippage_basis_points**: 控制可接受的价格滑点
|
||||
- **wait_transaction_confirmed**: 控制是否等待确认
|
||||
- **wait_tx_confirmed**: 控制是否等待确认
|
||||
|
||||
### 🔧 账户管理参数
|
||||
|
||||
@@ -102,7 +190,7 @@
|
||||
|
||||
这些参数启用高级优化:
|
||||
|
||||
- **address_lookup_table_account**: 使用地址查找表减少交易大小
|
||||
- **address_lookup_table_accounts**: 使用一个或多个地址查找表减少交易大小
|
||||
|
||||
### 🔄 代币类型参数
|
||||
|
||||
@@ -146,7 +234,7 @@ let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
||||
|
||||
### 🔍 地址查找表
|
||||
|
||||
使用 `address_lookup_table_account` 之前:
|
||||
使用 `address_lookup_table_accounts` 之前:
|
||||
- 查找表减少交易大小并提高成功率
|
||||
- 对于有许多账户引用的复杂交易特别有益
|
||||
|
||||
|
||||
@@ -5,9 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
sol-trade-sdk = { path = "../.." }
|
||||
solana-streamer-sdk = "0.5.0"
|
||||
sol-parser-sdk = "0.4.14"
|
||||
solana-sdk = "3.0.0"
|
||||
solana-address-lookup-table-interface = "3.0.0"
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
anyhow = "1.0.94"
|
||||
|
||||
@@ -1,22 +1,3 @@
|
||||
use sol_trade_sdk::common::address_lookup::fetch_address_lookup_table_account;
|
||||
use sol_trade_sdk::common::{gas_fee_strategy, GasFeeStrategy, TradeConfig};
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use solana_sdk::signature::Keypair;
|
||||
use solana_streamer_sdk::match_event;
|
||||
use solana_streamer_sdk::streaming::event_parser::common::filter::EventTypeFilter;
|
||||
use solana_streamer_sdk::streaming::event_parser::common::EventType;
|
||||
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::parser::PUMPFUN_PROGRAM_ID;
|
||||
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::PumpFunTradeEvent;
|
||||
use solana_streamer_sdk::streaming::event_parser::{Protocol, UnifiedEvent};
|
||||
use solana_streamer_sdk::streaming::yellowstone_grpc::{AccountFilter, TransactionFilter};
|
||||
use solana_streamer_sdk::streaming::YellowstoneGrpc;
|
||||
use std::{
|
||||
str::FromStr,
|
||||
sync::{
|
||||
@@ -25,146 +6,190 @@ use std::{
|
||||
},
|
||||
};
|
||||
|
||||
// Global static flag to ensure transaction is executed only once
|
||||
use sol_parser_sdk::grpc::{
|
||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||
TransactionFilter, YellowstoneGrpc,
|
||||
};
|
||||
use sol_parser_sdk::DexEvent;
|
||||
use sol_trade_sdk::common::address_lookup::fetch_address_lookup_table_account;
|
||||
use sol_trade_sdk::common::{GasFeeStrategy, TradeConfig};
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpFunParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use solana_sdk::signature::Keypair;
|
||||
|
||||
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("Subscribing to GRPC events...");
|
||||
println!("Subscribing to GRPC events (sol-parser-sdk, is_cashback_coin from event)...");
|
||||
|
||||
let grpc = YellowstoneGrpc::new(
|
||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
||||
None,
|
||||
)?;
|
||||
|
||||
let callback = create_event_callback();
|
||||
let protocols = vec![Protocol::PumpFun];
|
||||
// Filter accounts
|
||||
let account_include = vec![
|
||||
PUMPFUN_PROGRAM_ID.to_string(), // Listen to pumpfun program ID
|
||||
];
|
||||
let account_exclude = vec![];
|
||||
let account_required = vec![];
|
||||
|
||||
// Listen to transaction data
|
||||
let transaction_filter = TransactionFilter {
|
||||
account_include: account_include.clone(),
|
||||
account_exclude,
|
||||
account_required,
|
||||
let config = ClientConfig {
|
||||
enable_metrics: false,
|
||||
connection_timeout_ms: 10000,
|
||||
request_timeout_ms: 30000,
|
||||
enable_tls: true,
|
||||
order_mode: OrderMode::Unordered,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Listen to account data belonging to owner programs -> account event monitoring
|
||||
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
|
||||
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
|
||||
.unwrap_or_else(|_| "https://solana-yellowstone-grpc.publicnode.com:443".to_string());
|
||||
let grpc = YellowstoneGrpc::new_with_config(
|
||||
grpc_endpoint,
|
||||
std::env::var("GRPC_AUTH_TOKEN").ok(),
|
||||
config,
|
||||
)?;
|
||||
|
||||
// listen to specific event type
|
||||
let event_type_filter =
|
||||
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
|
||||
let protocols = vec![Protocol::PumpFun];
|
||||
let transaction_filter = TransactionFilter::for_protocols(&protocols);
|
||||
let account_filter = AccountFilter::for_protocols(&protocols);
|
||||
let event_filter = EventTypeFilter::include_only(vec![
|
||||
EventType::PumpFunBuy,
|
||||
EventType::PumpFunSell,
|
||||
EventType::PumpFunBuyExactSolIn,
|
||||
EventType::PumpFunTrade,
|
||||
]);
|
||||
|
||||
grpc.subscribe_events_immediate(
|
||||
protocols,
|
||||
None,
|
||||
vec![transaction_filter],
|
||||
vec![account_filter],
|
||||
Some(event_type_filter),
|
||||
None,
|
||||
callback,
|
||||
)
|
||||
.await?;
|
||||
let queue = grpc
|
||||
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
if let Some(event) = queue.pop() {
|
||||
let run = match &event {
|
||||
DexEvent::PumpFunBuy(e)
|
||||
| DexEvent::PumpFunSell(e)
|
||||
| DexEvent::PumpFunBuyExactSolIn(e) => {
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
Some(e.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
DexEvent::PumpFunTrade(e) => {
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
Some(e.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(e) = run {
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = pumpfun_copy_trade_with_grpc(e).await {
|
||||
eprintln!("Error in copy trade: {:?}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::exit(0);
|
||||
});
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::signal::ctrl_c().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create an event callback function that handles different types of events
|
||||
fn create_event_callback() -> impl Fn(Box<dyn UnifiedEvent>) {
|
||||
|event: Box<dyn UnifiedEvent>| {
|
||||
match_event!(event, {
|
||||
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
|
||||
// Test code, only test one transaction
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
let event_clone = e.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = pumpfun_copy_trade_with_grpc(event_clone).await {
|
||||
eprintln!("Error in copy trade: {:?}", err);
|
||||
std::process::exit(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Create SolanaTrade client
|
||||
/// Initializes a new SolanaTrade client with configuration
|
||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
println!("🚀 Initializing SolanaTrade client...");
|
||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
}
|
||||
|
||||
/// PumpFun sniper trade
|
||||
/// This function demonstrates how to snipe a new token from a PumpFun trade event
|
||||
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
|
||||
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
|
||||
async fn pumpfun_copy_trade_with_grpc(
|
||||
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||
) -> AnyResult<()> {
|
||||
println!("Testing PumpFun trading...");
|
||||
|
||||
let client = create_solana_trade_client().await?;
|
||||
let mint_pubkey = trade_info.mint;
|
||||
let virtual_quote_reserves = if trade_info.virtual_quote_reserves != 0 {
|
||||
trade_info.virtual_quote_reserves
|
||||
} else {
|
||||
trade_info.virtual_sol_reserves
|
||||
};
|
||||
let real_quote_reserves = if trade_info.virtual_quote_reserves != 0 {
|
||||
trade_info.real_quote_reserves
|
||||
} else {
|
||||
trade_info.real_sol_reserves
|
||||
};
|
||||
let slippage_basis_points = Some(100);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
||||
let address_lookup_table_account =
|
||||
fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key).await.ok();
|
||||
let alt = fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key)
|
||||
.await
|
||||
.ok();
|
||||
|
||||
let gas_fee_strategy = GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
// Buy tokens
|
||||
println!("Buying tokens from PumpFun...");
|
||||
let buy_sol_amount = 100_000;
|
||||
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
dex_type: DexType::PumpFun,
|
||||
input_token_type: sol_trade_sdk::TradeTokenType::SOL,
|
||||
mint: mint_pubkey,
|
||||
input_token_amount: buy_sol_amount,
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
input_token_amount: 100_000,
|
||||
slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||
trade_info.bonding_curve,
|
||||
trade_info.associated_bonding_curve,
|
||||
trade_info.mint,
|
||||
trade_info.quote_mint,
|
||||
trade_info.creator,
|
||||
trade_info.creator_vault,
|
||||
trade_info.virtual_token_reserves,
|
||||
trade_info.virtual_sol_reserves,
|
||||
virtual_quote_reserves,
|
||||
trade_info.real_token_reserves,
|
||||
trade_info.real_sol_reserves,
|
||||
real_quote_reserves,
|
||||
None,
|
||||
trade_info.fee_recipient,
|
||||
trade_info.token_program,
|
||||
false, // is_cashback_coin: set from event/parser when available
|
||||
trade_info.is_cashback_coin,
|
||||
Some(trade_info.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: address_lookup_table_account,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: alt.into_iter().collect(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: false,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: true,
|
||||
durable_nonce: None,
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
// Exit program
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
@@ -10,7 +10,10 @@ use sol_trade_sdk::common::{
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{BonkParams, DexParamEnum},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -110,7 +113,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
@@ -127,14 +137,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let gas_fee_strategy = GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(
|
||||
150000,
|
||||
150000,
|
||||
500000,
|
||||
500000,
|
||||
0.001,
|
||||
0.001,
|
||||
);
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
// Buy tokens
|
||||
println!("Buying tokens from Bonk...");
|
||||
@@ -166,8 +169,9 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
||||
trade_info.creator_associated_account,
|
||||
trade_info.global_config,
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: true,
|
||||
@@ -176,6 +180,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -216,8 +221,9 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
||||
trade_info.creator_associated_account,
|
||||
trade_info.global_config,
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
with_tip: false,
|
||||
durable_nonce: None,
|
||||
create_output_token_ata: false,
|
||||
@@ -226,6 +232,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::common::TradeConfig;
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{BonkParams, DexParamEnum},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -78,7 +81,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
@@ -95,14 +105,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(
|
||||
150000,
|
||||
150000,
|
||||
500000,
|
||||
500000,
|
||||
0.001,
|
||||
0.001,
|
||||
);
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
let token_type = if trade_info.quote_token_mint == sol_trade_sdk::constants::USD1_TOKEN_ACCOUNT
|
||||
{
|
||||
@@ -134,8 +137,9 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
||||
trade_info.creator_associated_account,
|
||||
trade_info.global_config,
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
@@ -144,6 +148,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -177,8 +182,9 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
||||
trade_info.creator_associated_account,
|
||||
trade_info.global_config,
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: true,
|
||||
close_mint_token_ata: false,
|
||||
@@ -187,6 +193,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -12,7 +12,8 @@ use sol_trade_sdk::{
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{
|
||||
BonkParams, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params, RaydiumCpmmParams, DexParamEnum,
|
||||
BonkParams, DexParamEnum, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params,
|
||||
RaydiumCpmmParams,
|
||||
},
|
||||
factory::DexType,
|
||||
},
|
||||
@@ -531,7 +532,7 @@ async fn handle_buy(
|
||||
|
||||
let client = initialize_real_client().await?;
|
||||
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
|
||||
match dex {
|
||||
@@ -565,7 +566,7 @@ async fn handle_buy_rv4(
|
||||
slippage: Option<u64>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
handle_buy_raydium_v4(mint, amm, sol_amount, slippage, create_mint_ata, use_seed, owner_pubkey)
|
||||
.await?;
|
||||
@@ -579,7 +580,7 @@ async fn handle_buy_rcpmm(
|
||||
slippage: Option<u64>,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
let (create_mint_ata, use_seed, owner_pubkey, amount_f64, decimals) =
|
||||
let (create_mint_ata, use_seed, owner_pubkey, _amount_f64, _decimals) =
|
||||
check_mint_ata(&client, mint).await?;
|
||||
handle_buy_raydium_cpmm(
|
||||
mint,
|
||||
@@ -599,8 +600,8 @@ async fn handle_buy_pumpfun(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("🔥 BUY PUMPFUN COMMAND");
|
||||
println!(" Token Mint: {}", mint);
|
||||
@@ -625,8 +626,9 @@ async fn handle_buy_pumpfun(
|
||||
slippage_basis_points: slippage,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpFun(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: false,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: create_mint_ata,
|
||||
@@ -635,9 +637,10 @@ async fn handle_buy_pumpfun(
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.buy(buy_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully bought tokens from PumpFun!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -654,7 +657,7 @@ async fn handle_buy_pumpswap(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
@@ -680,8 +683,9 @@ async fn handle_buy_pumpswap(
|
||||
slippage_basis_points: slippage,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpSwap(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: create_mint_ata,
|
||||
@@ -690,9 +694,10 @@ async fn handle_buy_pumpswap(
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.buy(buy_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully bought tokens from PumpSwap!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -708,8 +713,8 @@ async fn handle_buy_bonk(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY BONK COMMAND");
|
||||
@@ -719,7 +724,8 @@ async fn handle_buy_bonk(
|
||||
println!(" Slippage: {}%", slippage.unwrap());
|
||||
}
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||
let param =
|
||||
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||
|
||||
@@ -734,8 +740,9 @@ async fn handle_buy_bonk(
|
||||
slippage_basis_points: slippage,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::Bonk(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: create_mint_ata,
|
||||
@@ -744,9 +751,10 @@ async fn handle_buy_bonk(
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.buy(buy_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully bought tokens from Bonk!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -763,8 +771,8 @@ async fn handle_buy_raydium_v4(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY RAYDIUM V4 COMMAND");
|
||||
@@ -777,7 +785,8 @@ async fn handle_buy_raydium_v4(
|
||||
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||
let param =
|
||||
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||
|
||||
@@ -792,8 +801,9 @@ async fn handle_buy_raydium_v4(
|
||||
slippage_basis_points: slippage,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::RaydiumAmmV4(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: create_mint_ata,
|
||||
@@ -802,9 +812,10 @@ async fn handle_buy_raydium_v4(
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.buy(buy_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully bought tokens from Raydium V4!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -821,8 +832,8 @@ async fn handle_buy_raydium_cpmm(
|
||||
sol_amount: f64,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let client = initialize_real_client().await?;
|
||||
println!("🔥 BUY RAYDIUM CPMM COMMAND");
|
||||
@@ -835,7 +846,9 @@ async fn handle_buy_raydium_cpmm(
|
||||
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
||||
let param =
|
||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||
.await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||
|
||||
@@ -850,8 +863,9 @@ async fn handle_buy_raydium_cpmm(
|
||||
slippage_basis_points: slippage,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::RaydiumCpmm(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: create_mint_ata,
|
||||
@@ -860,9 +874,10 @@ async fn handle_buy_raydium_cpmm(
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.buy(buy_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully bought tokens from Raydium CPMM!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -987,11 +1002,11 @@ async fn handle_sell_pumpfun(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
|
||||
@@ -1019,8 +1034,9 @@ async fn handle_sell_pumpfun(
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::PumpFun(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -1028,10 +1044,11 @@ async fn handle_sell_pumpfun(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
|
||||
match client.sell(sell_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully sold tokens from PumpFun!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -1047,11 +1064,11 @@ async fn handle_sell_pumpswap(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||
@@ -1077,8 +1094,9 @@ async fn handle_sell_pumpswap(
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::PumpSwap(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -1086,11 +1104,12 @@ async fn handle_sell_pumpswap(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.sell(sell_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully sold tokens from PumpSwap!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
Err(e) => {
|
||||
println!(" ❌ Failed to sell tokens from PumpSwap: {}", e);
|
||||
@@ -1104,11 +1123,11 @@ async fn handle_sell_bonk(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL PUMPSWAP COMMAND");
|
||||
@@ -1119,7 +1138,8 @@ async fn handle_sell_bonk(
|
||||
}
|
||||
let client = initialize_real_client().await?;
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||
let param =
|
||||
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
@@ -1134,8 +1154,9 @@ async fn handle_sell_bonk(
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::Bonk(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -1143,9 +1164,10 @@ async fn handle_sell_bonk(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.sell(sell_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully sold tokens from Bonk!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -1162,11 +1184,11 @@ async fn handle_sell_raydium_v4(
|
||||
mint: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL RAYDIUM V4 COMMAND");
|
||||
@@ -1179,7 +1201,8 @@ async fn handle_sell_raydium_v4(
|
||||
let client = initialize_real_client().await?;
|
||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||
let param =
|
||||
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
@@ -1194,8 +1217,9 @@ async fn handle_sell_raydium_v4(
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::RaydiumAmmV4(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -1203,9 +1227,10 @@ async fn handle_sell_raydium_v4(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.sell(sell_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully sold tokens from Raydium V4!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -1222,11 +1247,11 @@ async fn handle_sell_raydium_cpmm(
|
||||
pool_address: &str,
|
||||
token_amount: Option<f64>,
|
||||
slippage: Option<u64>,
|
||||
create_mint_ata: bool,
|
||||
use_seed: bool,
|
||||
owner_pubkey: Pubkey,
|
||||
_create_mint_ata: bool,
|
||||
_use_seed: bool,
|
||||
_owner_pubkey: Pubkey,
|
||||
amount_f64: f64,
|
||||
decimals: u8,
|
||||
_decimals: u8,
|
||||
) -> Result<(), Box<dyn std::error::Error>> {
|
||||
let amount = if token_amount.is_some() { token_amount.unwrap() } else { amount_f64 };
|
||||
println!("🔥 SELL RAYDIUM CPMM COMMAND");
|
||||
@@ -1239,7 +1264,9 @@ async fn handle_sell_raydium_cpmm(
|
||||
let client = initialize_real_client().await?;
|
||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
||||
let param =
|
||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||
.await?;
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
@@ -1254,8 +1281,9 @@ async fn handle_sell_raydium_cpmm(
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::RaydiumCpmm(param),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -1263,9 +1291,10 @@ async fn handle_sell_raydium_cpmm(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
match client.sell(sell_params).await {
|
||||
Ok((_, signature, _)) => {
|
||||
Ok((_, signature, _, _)) => {
|
||||
println!(" ✅ Successfully sold tokens from Raydium CPMM!");
|
||||
println!(" ✅ Transaction Signature: {:?}", signature);
|
||||
}
|
||||
@@ -1373,7 +1402,14 @@ async fn initialize_real_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = RPC_URL.to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(payer, trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
use sol_trade_sdk::{
|
||||
SolanaTrade, TradeTokenType, common::{
|
||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
||||
}, swqos::SwqosConfig, trading::{core::params::{MeteoraDammV2Params, DexParamEnum}, factory::DexType}
|
||||
common::{
|
||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||
},
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{DexParamEnum, MeteoraDammV2Params},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade, TradeTokenType,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::signature::Keypair;
|
||||
@@ -32,10 +38,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::MeteoraDammV2(
|
||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||
.await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: false, //if input token is SOL/WSOL,set to true,if input token is USDC,set to false.
|
||||
close_input_token_ata: false, //if input token is SOL/WSOL,set to true,if input token is USDC,set to false.
|
||||
create_mint_ata: true,
|
||||
@@ -44,6 +52,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -53,7 +62,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let rpc = client.infrastructure.rpc.clone();
|
||||
let payer = client.payer.pubkey();
|
||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM;
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
&payer,
|
||||
&mint_pubkey,
|
||||
&program_id,
|
||||
client.use_seed_optimize,
|
||||
);
|
||||
let balance = rpc.get_token_account_balance(&account).await?;
|
||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||
println!("Token balance: {}", amount_token);
|
||||
@@ -66,10 +80,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::MeteoraDammV2(
|
||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||
.await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: false, //if output token is SOL/WSOL,set to true,if output token is USDC,set to false.
|
||||
close_output_token_ata: false, //if output token is SOL/WSOL,set to true,if output token is USDC,set to false.
|
||||
close_mint_token_ata: false,
|
||||
@@ -77,6 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
fixed_output_token_amount: Some(1),
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
@@ -92,7 +109,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
|
||||
@@ -1,9 +1,10 @@
|
||||
use anyhow::Result;
|
||||
use sol_trade_sdk::{
|
||||
common::{AnyResult, TradeConfig},
|
||||
swqos::{SwqosConfig, SwqosRegion},
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{PumpSwapParams, DexParamEnum}, factory::DexType, middleware::builtin::LoggingMiddleware,
|
||||
core::params::{DexParamEnum, PumpSwapParams},
|
||||
factory::DexType,
|
||||
InstructionMiddleware, MiddlewareManager,
|
||||
},
|
||||
SolanaTrade, TradeTokenType,
|
||||
@@ -30,8 +31,8 @@ impl InstructionMiddleware for CustomMiddleware {
|
||||
fn process_protocol_instructions(
|
||||
&self,
|
||||
protocol_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
is_buy: bool,
|
||||
_protocol_name: &str,
|
||||
_is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
// do anything you want here
|
||||
// you can modify the instructions here
|
||||
@@ -41,8 +42,8 @@ impl InstructionMiddleware for CustomMiddleware {
|
||||
fn process_full_instructions(
|
||||
&self,
|
||||
full_instructions: Vec<Instruction>,
|
||||
protocol_name: String,
|
||||
is_buy: bool,
|
||||
_protocol_name: &str,
|
||||
_is_buy: bool,
|
||||
) -> Result<Vec<Instruction>> {
|
||||
// do anything you want here
|
||||
// you can modify the instructions here
|
||||
@@ -62,7 +63,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
@@ -91,10 +99,12 @@ async fn test_middleware() -> AnyResult<()> {
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpSwap(
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address).await?,
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address)
|
||||
.await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
@@ -103,6 +113,7 @@ async fn test_middleware() -> AnyResult<()> {
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
println!("tip: This transaction will not succeed because we're using a test account. You can modify the code to initialize the payer with your own private key");
|
||||
|
||||
@@ -5,7 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
sol-trade-sdk = { path = "../.." }
|
||||
solana-streamer-sdk = "0.5.0"
|
||||
sol-parser-sdk = "0.4.14"
|
||||
solana-sdk = "3.0.0"
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
spl-associated-token-account = "7.0.0"
|
||||
|
||||
@@ -6,165 +6,187 @@ use std::{
|
||||
},
|
||||
};
|
||||
|
||||
use sol_parser_sdk::grpc::{
|
||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||
TransactionFilter, YellowstoneGrpc,
|
||||
};
|
||||
use sol_parser_sdk::DexEvent;
|
||||
use sol_trade_sdk::common::{nonce_cache::fetch_nonce_info, TradeConfig};
|
||||
use sol_trade_sdk::TradeTokenType;
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpFunParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use solana_streamer_sdk::match_event;
|
||||
use solana_streamer_sdk::streaming::event_parser::common::filter::EventTypeFilter;
|
||||
use solana_streamer_sdk::streaming::event_parser::common::EventType;
|
||||
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::parser::PUMPFUN_PROGRAM_ID;
|
||||
use solana_streamer_sdk::streaming::event_parser::protocols::pumpfun::PumpFunTradeEvent;
|
||||
use solana_streamer_sdk::streaming::event_parser::{Protocol, UnifiedEvent};
|
||||
use solana_streamer_sdk::streaming::yellowstone_grpc::{AccountFilter, TransactionFilter};
|
||||
use solana_streamer_sdk::streaming::YellowstoneGrpc;
|
||||
|
||||
// Global static flag to ensure transaction is executed only once
|
||||
static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
println!("Subscribing to GRPC events...");
|
||||
println!("Subscribing to GRPC events (sol-parser-sdk, is_cashback_coin from event)...");
|
||||
|
||||
let grpc = YellowstoneGrpc::new(
|
||||
"https://solana-yellowstone-grpc.publicnode.com:443".to_string(),
|
||||
None,
|
||||
)?;
|
||||
|
||||
let callback = create_event_callback();
|
||||
let protocols = vec![Protocol::PumpFun];
|
||||
// Filter accounts
|
||||
let account_include = vec![
|
||||
PUMPFUN_PROGRAM_ID.to_string(), // Listen to pumpfun program ID
|
||||
];
|
||||
let account_exclude = vec![];
|
||||
let account_required = vec![];
|
||||
|
||||
// Listen to transaction data
|
||||
let transaction_filter = TransactionFilter {
|
||||
account_include: account_include.clone(),
|
||||
account_exclude,
|
||||
account_required,
|
||||
let config = ClientConfig {
|
||||
enable_metrics: false,
|
||||
connection_timeout_ms: 10000,
|
||||
request_timeout_ms: 30000,
|
||||
enable_tls: true,
|
||||
order_mode: OrderMode::Unordered,
|
||||
..Default::default()
|
||||
};
|
||||
|
||||
// Listen to account data belonging to owner programs -> account event monitoring
|
||||
let account_filter = AccountFilter { account: vec![], owner: vec![], filters: vec![] };
|
||||
let grpc_endpoint = std::env::var("GRPC_ENDPOINT")
|
||||
.unwrap_or_else(|_| "https://solana-yellowstone-grpc.publicnode.com:443".to_string());
|
||||
let grpc = YellowstoneGrpc::new_with_config(
|
||||
grpc_endpoint,
|
||||
std::env::var("GRPC_AUTH_TOKEN").ok(),
|
||||
config,
|
||||
)?;
|
||||
|
||||
// listen to specific event type
|
||||
let event_type_filter =
|
||||
EventTypeFilter { include: vec![EventType::PumpFunBuy, EventType::PumpFunSell] };
|
||||
let protocols = vec![Protocol::PumpFun];
|
||||
let transaction_filter = TransactionFilter::for_protocols(&protocols);
|
||||
let account_filter = AccountFilter::for_protocols(&protocols);
|
||||
let event_filter = EventTypeFilter::include_only(vec![
|
||||
EventType::PumpFunBuy,
|
||||
EventType::PumpFunSell,
|
||||
EventType::PumpFunBuyExactSolIn,
|
||||
EventType::PumpFunTrade,
|
||||
]);
|
||||
|
||||
grpc.subscribe_events_immediate(
|
||||
protocols,
|
||||
None,
|
||||
vec![transaction_filter],
|
||||
vec![account_filter],
|
||||
Some(event_type_filter),
|
||||
None,
|
||||
callback,
|
||||
)
|
||||
.await?;
|
||||
let queue = grpc
|
||||
.subscribe_dex_events(vec![transaction_filter], vec![account_filter], Some(event_filter))
|
||||
.await?;
|
||||
|
||||
loop {
|
||||
if let Some(event) = queue.pop() {
|
||||
let run = match &event {
|
||||
DexEvent::PumpFunBuy(e)
|
||||
| DexEvent::PumpFunSell(e)
|
||||
| DexEvent::PumpFunBuyExactSolIn(e) => {
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
Some(e.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
DexEvent::PumpFunTrade(e) => {
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
Some(e.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(e) = run {
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = pumpfun_copy_trade_with_grpc(e).await {
|
||||
eprintln!("Error in copy trade: {:?}", err);
|
||||
std::process::exit(1);
|
||||
}
|
||||
std::process::exit(0);
|
||||
});
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
tokio::time::sleep(tokio::time::Duration::from_millis(5)).await;
|
||||
}
|
||||
}
|
||||
|
||||
tokio::signal::ctrl_c().await?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Create an event callback function that handles different types of events
|
||||
fn create_event_callback() -> impl Fn(Box<dyn UnifiedEvent>) {
|
||||
|event: Box<dyn UnifiedEvent>| {
|
||||
match_event!(event, {
|
||||
PumpFunTradeEvent => |e: PumpFunTradeEvent| {
|
||||
// Test code, only test one transaction
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
let event_clone = e.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(err) = pumpfun_copy_trade_with_grpc(event_clone).await {
|
||||
eprintln!("Error in copy trade: {:?}", err);
|
||||
std::process::exit(0);
|
||||
}
|
||||
});
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Create SolanaTrade client
|
||||
/// Initializes a new SolanaTrade client with configuration
|
||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
println!("🚀 Initializing SolanaTrade client...");
|
||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
}
|
||||
|
||||
/// PumpFun sniper trade
|
||||
/// This function demonstrates how to snipe a new token from a PumpFun trade event
|
||||
async fn pumpfun_copy_trade_with_grpc(trade_info: PumpFunTradeEvent) -> AnyResult<()> {
|
||||
/// PumpFun copy trade: use is_cashback_coin from gRPC event (sol-parser-sdk)
|
||||
async fn pumpfun_copy_trade_with_grpc(
|
||||
trade_info: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||
) -> AnyResult<()> {
|
||||
println!("Testing PumpFun trading...");
|
||||
|
||||
let client = create_solana_trade_client().await?;
|
||||
let mint_pubkey = trade_info.mint;
|
||||
let virtual_quote_reserves = if trade_info.virtual_quote_reserves != 0 {
|
||||
trade_info.virtual_quote_reserves
|
||||
} else {
|
||||
trade_info.virtual_sol_reserves
|
||||
};
|
||||
let real_quote_reserves = if trade_info.virtual_quote_reserves != 0 {
|
||||
trade_info.real_quote_reserves
|
||||
} else {
|
||||
trade_info.real_sol_reserves
|
||||
};
|
||||
let slippage_basis_points = Some(100);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
// Setup nonce cache
|
||||
let nonce_account_str = Pubkey::from_str("use_your_nonce_account_here")?;
|
||||
let durable_nonce = fetch_nonce_info(&client.infrastructure.rpc, nonce_account_str).await;
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
// Buy tokens
|
||||
println!("Buying tokens from PumpFun...");
|
||||
let buy_sol_amount = 100_000;
|
||||
// is_cashback_coin from gRPC event (sol-parser-sdk parses it from trade event)
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
dex_type: DexType::PumpFun,
|
||||
input_token_type: TradeTokenType::SOL,
|
||||
mint: mint_pubkey,
|
||||
input_token_amount: buy_sol_amount,
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
input_token_amount: 100_000,
|
||||
slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||
trade_info.bonding_curve,
|
||||
trade_info.associated_bonding_curve,
|
||||
trade_info.mint,
|
||||
trade_info.quote_mint,
|
||||
trade_info.creator,
|
||||
trade_info.creator_vault,
|
||||
trade_info.virtual_token_reserves,
|
||||
trade_info.virtual_sol_reserves,
|
||||
virtual_quote_reserves,
|
||||
trade_info.real_token_reserves,
|
||||
trade_info.real_sol_reserves,
|
||||
real_quote_reserves,
|
||||
None,
|
||||
trade_info.fee_recipient,
|
||||
trade_info.token_program,
|
||||
false, // is_cashback_coin: set from event/parser when available
|
||||
trade_info.is_cashback_coin,
|
||||
Some(trade_info.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: false,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: true,
|
||||
durable_nonce: durable_nonce,
|
||||
durable_nonce,
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
// Exit program
|
||||
std::process::exit(0);
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
sol-trade-sdk = { path = "../.." }
|
||||
sol-parser-sdk = { path = "../../../sol-parser-sdk" }
|
||||
sol-parser-sdk = "0.4.14"
|
||||
solana-sdk = "3.0.0"
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
@@ -2,7 +2,10 @@
|
||||
//!
|
||||
//! 收到 PumpFun 买卖事件后,用事件中的参数(含 is_cashback_coin)构造交易并执行一次买+卖。
|
||||
|
||||
use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use sol_parser_sdk::grpc::{
|
||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||
@@ -16,7 +19,10 @@ use sol_trade_sdk::TradeTokenType;
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpFunParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -27,7 +33,6 @@ static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
println!("PumpFun 跟单示例(sol-parser-sdk gRPC)...");
|
||||
|
||||
let config = ClientConfig {
|
||||
@@ -66,7 +71,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
loop {
|
||||
if let Some(event) = queue.pop() {
|
||||
let run = match &event {
|
||||
DexEvent::PumpFunBuy(e) | DexEvent::PumpFunSell(e) | DexEvent::PumpFunBuyExactSolIn(e) => {
|
||||
DexEvent::PumpFunBuy(e)
|
||||
| DexEvent::PumpFunSell(e)
|
||||
| DexEvent::PumpFunBuyExactSolIn(e) => {
|
||||
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||
Some(e.clone())
|
||||
} else {
|
||||
@@ -103,18 +110,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||
let rpc_url = std::env::var("RPC_URL").unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||
let rpc_url = std::env::var("RPC_URL")
|
||||
.unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||
}
|
||||
|
||||
async fn pumpfun_copy_trade(
|
||||
e: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||
) -> AnyResult<()> {
|
||||
async fn pumpfun_copy_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||
let client = create_solana_trade_client().await?;
|
||||
let mint_pubkey = e.mint;
|
||||
let virtual_quote_reserves = if e.virtual_quote_reserves != 0 {
|
||||
e.virtual_quote_reserves
|
||||
} else {
|
||||
e.virtual_sol_reserves
|
||||
};
|
||||
let real_quote_reserves =
|
||||
if e.virtual_quote_reserves != 0 { e.real_quote_reserves } else { e.real_sol_reserves };
|
||||
let slippage_basis_points = Some(100u64);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
@@ -134,19 +154,22 @@ async fn pumpfun_copy_trade(
|
||||
e.bonding_curve,
|
||||
e.associated_bonding_curve,
|
||||
e.mint,
|
||||
e.quote_mint,
|
||||
e.creator,
|
||||
e.creator_vault,
|
||||
e.virtual_token_reserves,
|
||||
e.virtual_sol_reserves,
|
||||
virtual_quote_reserves,
|
||||
e.real_token_reserves,
|
||||
e.real_sol_reserves,
|
||||
real_quote_reserves,
|
||||
None,
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: false,
|
||||
close_input_token_ata: false,
|
||||
create_mint_ata: true,
|
||||
@@ -155,6 +178,7 @@ async fn pumpfun_copy_trade(
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -182,19 +206,22 @@ async fn pumpfun_copy_trade(
|
||||
e.bonding_curve,
|
||||
e.associated_bonding_curve,
|
||||
e.mint,
|
||||
e.quote_mint,
|
||||
e.creator,
|
||||
e.creator_vault,
|
||||
e.virtual_token_reserves,
|
||||
e.virtual_sol_reserves,
|
||||
virtual_quote_reserves,
|
||||
e.real_token_reserves,
|
||||
e.real_sol_reserves,
|
||||
real_quote_reserves,
|
||||
Some(true),
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: false,
|
||||
close_output_token_ata: false,
|
||||
close_mint_token_ata: false,
|
||||
@@ -202,6 +229,7 @@ async fn pumpfun_copy_trade(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -5,7 +5,7 @@ edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
sol-trade-sdk = { path = "../.." }
|
||||
sol-parser-sdk = { path = "../../../sol-parser-sdk" }
|
||||
sol-parser-sdk = "0.4.14"
|
||||
solana-sdk = "3.0.0"
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
|
||||
@@ -3,7 +3,10 @@
|
||||
//! 监听创建者首次买入(Create 后同笔/首笔 Buy,is_created_buy == true),
|
||||
//! 用事件参数(含 is_cashback_coin)构造 from_dev_trade 并执行一次买+卖。
|
||||
|
||||
use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
Arc,
|
||||
};
|
||||
|
||||
use sol_parser_sdk::grpc::{
|
||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||
@@ -16,7 +19,10 @@ use sol_trade_sdk::TradeTokenType;
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpFunParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -27,7 +33,6 @@ static ALREADY_EXECUTED: AtomicBool = AtomicBool::new(false);
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||
println!("PumpFun 狙击示例(sol-parser-sdk gRPC)...");
|
||||
|
||||
let config = ClientConfig {
|
||||
@@ -95,18 +100,31 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
|
||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||
let rpc_url = std::env::var("RPC_URL").unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||
let rpc_url = std::env::var("RPC_URL")
|
||||
.unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||
}
|
||||
|
||||
async fn pumpfun_sniper_trade(
|
||||
e: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
||||
) -> AnyResult<()> {
|
||||
async fn pumpfun_sniper_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||
let client = create_solana_trade_client().await?;
|
||||
let mint_pubkey = e.mint;
|
||||
let virtual_quote_reserves = if e.virtual_quote_reserves != 0 {
|
||||
e.virtual_quote_reserves
|
||||
} else {
|
||||
e.virtual_sol_reserves
|
||||
};
|
||||
let real_quote_reserves =
|
||||
if e.virtual_quote_reserves != 0 { e.real_quote_reserves } else { e.real_sol_reserves };
|
||||
let slippage_basis_points = Some(300u64);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
@@ -136,9 +154,11 @@ async fn pumpfun_sniper_trade(
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
@@ -147,6 +167,7 @@ async fn pumpfun_sniper_trade(
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -168,19 +189,22 @@ async fn pumpfun_sniper_trade(
|
||||
e.bonding_curve,
|
||||
e.associated_bonding_curve,
|
||||
e.mint,
|
||||
e.quote_mint,
|
||||
e.creator,
|
||||
e.creator_vault,
|
||||
e.virtual_token_reserves,
|
||||
e.virtual_sol_reserves,
|
||||
virtual_quote_reserves,
|
||||
e.real_token_reserves,
|
||||
e.real_sol_reserves,
|
||||
real_quote_reserves,
|
||||
Some(true),
|
||||
e.fee_recipient,
|
||||
e.token_program,
|
||||
e.is_cashback_coin,
|
||||
Some(e.mayhem_mode),
|
||||
)),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: true,
|
||||
close_mint_token_ata: false,
|
||||
@@ -188,6 +212,7 @@ async fn pumpfun_sniper_trade(
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -1,7 +1,13 @@
|
||||
use sol_trade_sdk::{
|
||||
SolanaTrade, TradeTokenType, common::{
|
||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
||||
}, swqos::SwqosConfig, trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType}
|
||||
common::{
|
||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||
},
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpSwapParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade, TradeTokenType,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::signature::Keypair;
|
||||
@@ -34,8 +40,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
extension_params: DexParamEnum::PumpSwap(
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
@@ -44,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,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -53,7 +61,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let rpc = client.infrastructure.rpc.clone();
|
||||
let payer = client.payer.pubkey();
|
||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM_2022;
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
&payer,
|
||||
&mint_pubkey,
|
||||
&program_id,
|
||||
client.use_seed_optimize,
|
||||
);
|
||||
let balance = rpc.get_token_account_balance(&account).await?;
|
||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||
@@ -67,11 +80,13 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
extension_params: DexParamEnum::PumpSwap(
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: true,
|
||||
close_mint_token_ata: false,
|
||||
grpc_recv_us: None,
|
||||
durable_nonce: None,
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
@@ -91,7 +106,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
|
||||
@@ -4,7 +4,10 @@ use sol_trade_sdk::TradeTokenType;
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpSwapParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -129,14 +132,22 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
}
|
||||
|
||||
async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> AnyResult<()> {
|
||||
let params = PumpSwapParams::new(
|
||||
let client = create_solana_trade_client().await?;
|
||||
let params = PumpSwapParams::from_trade_with_fee_basis_points(
|
||||
trade_info.pool,
|
||||
trade_info.base_mint,
|
||||
trade_info.quote_mint,
|
||||
@@ -149,6 +160,13 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
|
||||
trade_info.base_token_program,
|
||||
trade_info.quote_token_program,
|
||||
trade_info.protocol_fee_recipient,
|
||||
Pubkey::default(),
|
||||
trade_info.coin_creator,
|
||||
false,
|
||||
0,
|
||||
trade_info.lp_fee_basis_points,
|
||||
trade_info.protocol_fee_basis_points,
|
||||
trade_info.coin_creator_fee_basis_points,
|
||||
);
|
||||
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
@@ -157,12 +175,13 @@ async fn pumpswap_trade_with_grpc_buy_event(trade_info: PumpSwapBuyEvent) -> Any
|
||||
} else {
|
||||
trade_info.base_mint
|
||||
};
|
||||
pumpswap_trade_with_grpc(mint, params).await?;
|
||||
pumpswap_trade_with_grpc(&client, mint, params).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> AnyResult<()> {
|
||||
let params = PumpSwapParams::new(
|
||||
let client = create_solana_trade_client().await?;
|
||||
let params = PumpSwapParams::from_trade_with_fee_basis_points(
|
||||
trade_info.pool,
|
||||
trade_info.base_mint,
|
||||
trade_info.quote_mint,
|
||||
@@ -175,6 +194,13 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
|
||||
trade_info.base_token_program,
|
||||
trade_info.quote_token_program,
|
||||
trade_info.protocol_fee_recipient,
|
||||
Pubkey::default(),
|
||||
trade_info.coin_creator,
|
||||
false,
|
||||
0,
|
||||
trade_info.lp_fee_basis_points,
|
||||
trade_info.protocol_fee_basis_points,
|
||||
trade_info.coin_creator_fee_basis_points,
|
||||
);
|
||||
let mint = if trade_info.base_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||
|| trade_info.base_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
@@ -183,14 +209,16 @@ async fn pumpswap_trade_with_grpc_sell_event(trade_info: PumpSwapSellEvent) -> A
|
||||
} else {
|
||||
trade_info.base_mint
|
||||
};
|
||||
pumpswap_trade_with_grpc(mint, params).await?;
|
||||
pumpswap_trade_with_grpc(&client, mint, params).await?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -> AnyResult<()> {
|
||||
async fn pumpswap_trade_with_grpc(
|
||||
client: &SolanaTrade,
|
||||
mint_pubkey: Pubkey,
|
||||
params: PumpSwapParams,
|
||||
) -> AnyResult<()> {
|
||||
println!("Testing PumpSwap trading...");
|
||||
|
||||
let client = create_solana_trade_client().await?;
|
||||
let slippage_basis_points = Some(500);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
@@ -211,8 +239,9 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::PumpSwap(params.clone()),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: is_sol,
|
||||
close_input_token_ata: is_sol,
|
||||
create_mint_ata: true,
|
||||
@@ -221,6 +250,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -234,7 +264,12 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
||||
} else {
|
||||
params.quote_token_program
|
||||
};
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
||||
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
&payer,
|
||||
&mint_pubkey,
|
||||
&program_id,
|
||||
client.use_seed_optimize,
|
||||
);
|
||||
let balance = rpc.get_token_account_balance(&account).await?;
|
||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||
@@ -246,8 +281,9 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::PumpSwap(params.clone()),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: is_sol,
|
||||
close_output_token_ata: is_sol,
|
||||
close_mint_token_ata: false,
|
||||
@@ -255,6 +291,7 @@ async fn pumpswap_trade_with_grpc(mint_pubkey: Pubkey, params: PumpSwapParams) -
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -2,13 +2,13 @@ use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id
|
||||
use sol_trade_sdk::{
|
||||
common::AnyResult,
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{RaydiumAmmV4Params, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, RaydiumAmmV4Params},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade,
|
||||
};
|
||||
use sol_trade_sdk::{
|
||||
common::TradeConfig, instruction::utils::raydium_amm_v4::fetch_amm_info,
|
||||
trading::common::get_multi_token_balances, TradeTokenType,
|
||||
};
|
||||
use sol_trade_sdk::{common::TradeConfig, TradeTokenType};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::signature::Keypair;
|
||||
use solana_sdk::signer::Signer;
|
||||
@@ -106,7 +106,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
@@ -121,41 +128,25 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
let slippage_basis_points = Some(100);
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
|
||||
let amm_info = fetch_amm_info(&client.infrastructure.rpc, trade_info.amm).await?;
|
||||
let (coin_reserve, pc_reserve) =
|
||||
get_multi_token_balances(&client.infrastructure.rpc, &amm_info.token_coin, &amm_info.token_pc).await?;
|
||||
let mint_pubkey = if amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| amm_info.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||
let params =
|
||||
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm)
|
||||
.await?;
|
||||
let mint_pubkey = if params.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| params.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||
{
|
||||
amm_info.coin_mint
|
||||
params.coin_mint
|
||||
} else {
|
||||
amm_info.pc_mint
|
||||
params.pc_mint
|
||||
};
|
||||
let params = RaydiumAmmV4Params::new(
|
||||
trade_info.amm,
|
||||
amm_info.coin_mint,
|
||||
amm_info.pc_mint,
|
||||
amm_info.token_coin,
|
||||
amm_info.token_pc,
|
||||
coin_reserve,
|
||||
pc_reserve,
|
||||
);
|
||||
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(
|
||||
150000,
|
||||
150000,
|
||||
500000,
|
||||
500000,
|
||||
0.001,
|
||||
0.001,
|
||||
);
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
// Buy tokens
|
||||
println!("Buying tokens from Raydium_amm_v4...");
|
||||
let input_token_amount = 100_000;
|
||||
let is_wsol = amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| amm_info.coin_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_wsol = params.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| params.coin_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let buy_params = sol_trade_sdk::TradeBuyParams {
|
||||
dex_type: DexType::RaydiumAmmV4,
|
||||
input_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
||||
@@ -164,8 +155,9 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::RaydiumAmmV4(params),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: is_wsol,
|
||||
close_input_token_ata: is_wsol,
|
||||
create_mint_ata: true,
|
||||
@@ -174,6 +166,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -193,7 +186,9 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||
|
||||
println!("Selling {} tokens", amount_token);
|
||||
let params = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm).await?;
|
||||
let params =
|
||||
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm)
|
||||
.await?;
|
||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||
dex_type: DexType::RaydiumAmmV4,
|
||||
output_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
||||
@@ -203,8 +198,9 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::RaydiumAmmV4(params),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: is_wsol,
|
||||
close_output_token_ata: is_wsol,
|
||||
close_mint_token_ata: false,
|
||||
@@ -212,6 +208,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
||||
use sol_trade_sdk::common::TradeConfig;
|
||||
use sol_trade_sdk::constants::{WSOL_TOKEN_ACCOUNT, USDC_TOKEN_ACCOUNT};
|
||||
use sol_trade_sdk::trading::core::params::{RaydiumCpmmParams, DexParamEnum};
|
||||
use sol_trade_sdk::constants::{USDC_TOKEN_ACCOUNT, WSOL_TOKEN_ACCOUNT};
|
||||
use sol_trade_sdk::trading::core::params::{DexParamEnum, RaydiumCpmmParams};
|
||||
use sol_trade_sdk::trading::factory::DexType;
|
||||
use sol_trade_sdk::TradeTokenType;
|
||||
use sol_trade_sdk::{common::AnyResult, swqos::SwqosConfig, SolanaTrade};
|
||||
@@ -107,7 +107,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
@@ -132,9 +139,12 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||
|
||||
let buy_params =
|
||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
||||
|
||||
let buy_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||
&client.infrastructure.rpc,
|
||||
&trade_info.pool_state,
|
||||
)
|
||||
.await?;
|
||||
|
||||
let is_wsol = trade_info.input_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| trade_info.output_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||
|
||||
@@ -149,8 +159,9 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
slippage_basis_points: slippage_basis_points,
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
extension_params: DexParamEnum::RaydiumCpmm(buy_params),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: is_wsol,
|
||||
close_input_token_ata: is_wsol,
|
||||
create_mint_ata: true,
|
||||
@@ -159,6 +170,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
gas_fee_strategy: gas_fee_strategy.clone(),
|
||||
simulate: false,
|
||||
use_exact_sol_amount: None,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -172,8 +184,11 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
println!("Balance: {:?}", balance);
|
||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||
|
||||
let sell_params =
|
||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
||||
let sell_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||
&client.infrastructure.rpc,
|
||||
&trade_info.pool_state,
|
||||
)
|
||||
.await?;
|
||||
|
||||
println!("Selling {} tokens", amount_token);
|
||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||
@@ -185,8 +200,9 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
recent_blockhash: Some(recent_blockhash),
|
||||
with_tip: false,
|
||||
extension_params: DexParamEnum::RaydiumCpmm(sell_params),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: is_wsol,
|
||||
close_output_token_ata: is_wsol,
|
||||
close_mint_token_ata: false,
|
||||
@@ -194,6 +210,7 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
|
||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::{
|
||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||
},
|
||||
swqos::SwqosConfig,
|
||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpSwapParams},
|
||||
factory::DexType,
|
||||
},
|
||||
SolanaTrade, TradeTokenType,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
@@ -37,8 +40,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
extension_params: DexParamEnum::PumpSwap(
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_input_token_ata: true,
|
||||
close_input_token_ata: true,
|
||||
create_mint_ata: true,
|
||||
@@ -47,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,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.buy(buy_params).await?;
|
||||
|
||||
@@ -78,8 +83,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
extension_params: DexParamEnum::PumpSwap(
|
||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
||||
),
|
||||
address_lookup_table_account: None,
|
||||
wait_transaction_confirmed: true,
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
wait_tx_confirmed: true,
|
||||
wait_for_all_submits: false,
|
||||
create_output_token_ata: true,
|
||||
close_output_token_ata: true,
|
||||
close_mint_token_ata: false,
|
||||
@@ -87,6 +93,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
fixed_output_token_amount: None,
|
||||
gas_fee_strategy: gas_fee_strategy,
|
||||
simulate: false,
|
||||
grpc_recv_us: None,
|
||||
};
|
||||
client.sell(sell_params).await?;
|
||||
|
||||
@@ -102,7 +109,14 @@ async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
|
||||
@@ -31,6 +31,7 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
SwqosConfig::Default(rpc_url.clone()),
|
||||
SwqosConfig::Jito("your_uuid".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Bloxroute("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
|
||||
];
|
||||
|
||||
// Step 1: Create shared infrastructure (expensive, do once)
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
[package]
|
||||
name = "simple_trading"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
[dependencies]
|
||||
sol-trade-sdk = { path = "../.." }
|
||||
solana-commitment-config = { version = "3.0.0", features = ["serde"] }
|
||||
solana-sdk = "3.0.0"
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
@@ -0,0 +1,138 @@
|
||||
//! Simple high-level trading API example.
|
||||
//!
|
||||
//! This example focuses on parameter construction. Replace the placeholder
|
||||
//! PumpFun params with real params from your parser/RPC cache before sending.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use sol_trade_sdk::{
|
||||
common::{GasFeeStrategy, TradeConfig},
|
||||
constants::{TOKEN_PROGRAM_2022, WSOL_TOKEN_ACCOUNT},
|
||||
instruction::utils::pumpfun::global_constants,
|
||||
swqos::SwqosConfig,
|
||||
trading::{
|
||||
core::params::{DexParamEnum, PumpFunParams},
|
||||
factory::DexType,
|
||||
},
|
||||
AccountPolicy, BuyAmount, DurableNonceInfo, SellAmount, SimpleBuyParams, SimpleSellParams,
|
||||
SolanaTrade, TradeTokenType,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::{hash::Hash, pubkey::Pubkey, signature::Keypair, signer::Signer};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||
let rpc_url = std::env::var("RPC_URL")
|
||||
.unwrap_or_else(|_| "https://api.mainnet-beta.solana.com".to_string());
|
||||
let commitment = CommitmentConfig::processed();
|
||||
let swqos_configs = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// Default is true. WSOL ATA is prepared on startup, not in the hot trade tx.
|
||||
.create_wsol_ata_on_startup(true)
|
||||
.build();
|
||||
let client = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
|
||||
let mint = Pubkey::new_unique();
|
||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let gas_fee_strategy = GasFeeStrategy::new();
|
||||
gas_fee_strategy.set_global_fee_strategy(150_000, 150_000, 500_000, 500_000, 0.001, 0.001);
|
||||
|
||||
// In production, fill these fields from your parser/RPC cache. They are
|
||||
// protocol state, not user preferences.
|
||||
let pumpfun_params = DexParamEnum::PumpFun(PumpFunParams::from_trade(
|
||||
Pubkey::new_unique(), // bonding_curve
|
||||
Pubkey::new_unique(), // associated_bonding_curve
|
||||
mint,
|
||||
// WSOL quote_mint selects PumpFun V2 SOL layout. Users still pay with
|
||||
// native SOL below by setting `TradeTokenType::SOL`.
|
||||
WSOL_TOKEN_ACCOUNT,
|
||||
Pubkey::new_unique(), // creator from event/cache
|
||||
Pubkey::default(), // creator_vault; SDK derives it if unavailable
|
||||
1_073_000_000_000_000, // virtual_token_reserves
|
||||
30_000_000_000, // virtual_quote_reserves
|
||||
793_100_000_000_000, // real_token_reserves
|
||||
0, // real_quote_reserves
|
||||
None, // close_token_account_when_sell
|
||||
global_constants::FEE_RECIPIENT,
|
||||
// If parser/cache does not know the mint owner, PumpFun now defaults to
|
||||
// Token-2022. Passing it explicitly makes the example easier to read.
|
||||
TOKEN_PROGRAM_2022,
|
||||
false, // is_cashback_coin
|
||||
Some(false), // mayhem_mode
|
||||
));
|
||||
|
||||
let buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
// For PumpFun V2 SOL-paired coins, keep this as SOL even though V2
|
||||
// account metas use the WSOL mint as quote_mint.
|
||||
TradeTokenType::SOL,
|
||||
mint,
|
||||
// Regular PumpFun/PumpSwap buy. The SDK estimates expected output and
|
||||
// applies slippage to the maximum quote cost.
|
||||
BuyAmount::WithMaxInput { quote_amount: 100_000 },
|
||||
pumpfun_params.clone(),
|
||||
recent_blockhash,
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
.slippage_basis_points(300)
|
||||
// Best for bots: do not create/close ATAs in the hot transaction.
|
||||
// Use AccountPolicy::Auto for normal integrations.
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
|
||||
// client.buy_simple(buy_params).await?;
|
||||
let _ = buy_params;
|
||||
|
||||
// Durable nonce is supported by the same high-level params. In production,
|
||||
// fetch it with `sol_trade_sdk::fetch_nonce_info(...)` immediately before
|
||||
// building the transaction.
|
||||
let nonce_buy_params = SimpleBuyParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint,
|
||||
BuyAmount::WithMaxInput { quote_amount: 100_000 },
|
||||
pumpfun_params.clone(),
|
||||
recent_blockhash,
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
.durable_nonce(DurableNonceInfo {
|
||||
nonce_account: Some(Pubkey::new_unique()),
|
||||
current_nonce: Some(Hash::new_unique()),
|
||||
})
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
let _ = nonce_buy_params;
|
||||
|
||||
let sell_params = SimpleSellParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint,
|
||||
SellAmount::ExactInput(1_000_000),
|
||||
pumpfun_params.clone(),
|
||||
client.infrastructure.rpc.get_latest_blockhash().await?,
|
||||
gas_fee_strategy.clone(),
|
||||
)
|
||||
.slippage_basis_points(300)
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
|
||||
// client.sell_simple(sell_params).await?;
|
||||
let _ = sell_params;
|
||||
|
||||
let nonce_sell_params = SimpleSellParams::new(
|
||||
DexType::PumpFun,
|
||||
TradeTokenType::SOL,
|
||||
mint,
|
||||
SellAmount::ExactInput(1_000_000),
|
||||
pumpfun_params,
|
||||
client.infrastructure.rpc.get_latest_blockhash().await?,
|
||||
gas_fee_strategy,
|
||||
)
|
||||
.durable_nonce(DurableNonceInfo {
|
||||
nonce_account: Some(Pubkey::new_unique()),
|
||||
current_nonce: Some(Hash::new_unique()),
|
||||
})
|
||||
.account_policy(AccountPolicy::HotPathMinimal);
|
||||
let _ = nonce_sell_params;
|
||||
|
||||
println!("Built simple buy/sell params for payer {}", client.payer.pubkey());
|
||||
Ok(())
|
||||
}
|
||||
@@ -10,7 +10,7 @@
|
||||
use sol_trade_sdk::{
|
||||
common::{AnyResult, InfrastructureConfig, TradeConfig},
|
||||
swqos::{SwqosConfig, SwqosRegion},
|
||||
TradingClient, TradingInfrastructure,
|
||||
AstralaneTransport, TradingClient, TradingInfrastructure,
|
||||
};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use solana_sdk::signature::Keypair;
|
||||
@@ -46,17 +46,22 @@ async fn create_trading_client_simple() -> AnyResult<TradingClient> {
|
||||
SwqosConfig::ZeroSlot("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Temporal("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::BlockRazor("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None, None),
|
||||
SwqosConfig::BlockRazor("your_api_token".to_string(), SwqosRegion::Frankfurt, None, None),
|
||||
SwqosConfig::Astralane(
|
||||
"your_api_token".to_string(),
|
||||
SwqosRegion::Frankfurt,
|
||||
None,
|
||||
Some(AstralaneTransport::Quic),
|
||||
), // QUIC;None / Some(Binary) / Some(Plain) 为 HTTP
|
||||
// Helius Sender: 4th param swqos_only Some(true) => min tip 0.000005 SOL; None => 0.0002 SOL
|
||||
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
|
||||
];
|
||||
|
||||
// Optional: Customize WSOL ATA and Seed optimization settings
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
||||
.with_wsol_ata_config(
|
||||
true, // create_wsol_ata_on_startup: Check and create WSOL ATA on startup
|
||||
true, // use_seed_optimize: Enable seed optimization for all ATA operations
|
||||
);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
.create_wsol_ata_on_startup(true)
|
||||
.use_seed_optimize(true)
|
||||
.build();
|
||||
|
||||
// Creates new infrastructure internally
|
||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||
|
||||
@@ -38,7 +38,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
// Example 2: Unwrap half of the WSOL back to SOL using seed account
|
||||
println!("\n🔄 Example 2: Unwrapping half of WSOL back to SOL using seed account");
|
||||
let unwrap_amount = wrap_amount / 2; // Half of the wrapped amount
|
||||
println!("Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...", unwrap_amount);
|
||||
println!(
|
||||
"Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...",
|
||||
unwrap_amount
|
||||
);
|
||||
|
||||
match solana_trade.wrap_wsol_to_sol(unwrap_amount).await {
|
||||
Ok(signature) => {
|
||||
@@ -81,7 +84,14 @@ async fn create_solana_trade_client() -> Result<SolanaTrade, Box<dyn std::error:
|
||||
let rpc_url = "https://api.mainnet-beta.solana.com".to_string();
|
||||
let commitment = CommitmentConfig::confirmed();
|
||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||
let trade_config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
// .create_wsol_ata_on_startup(true) // default: true
|
||||
// .use_seed_optimize(true) // default: true
|
||||
// .log_enabled(true) // default: true
|
||||
// .check_min_tip(false) // default: false
|
||||
// .swqos_cores_from_end(false) // default: false
|
||||
// .mev_protection(false) // default: false
|
||||
.build();
|
||||
let solana_trade = SolanaTrade::new(Arc::new(payer), trade_config).await;
|
||||
println!("✅ SolanaTrade client initialized successfully!");
|
||||
Ok(solana_trade)
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
# IDL files
|
||||
|
||||
Supported DEX IDLs are stored directly in this directory. The files below were
|
||||
synced from `bitquery/solana-idl-lib` commit `f804b17` and written to the SDK's
|
||||
canonical local filenames.
|
||||
|
||||
| SDK protocol | Local IDL | Source path |
|
||||
| --- | --- | --- |
|
||||
| Bonk / Raydium Launchpad | `bonk.json` | `raydium/launchpad.json` |
|
||||
| Raydium CPMM | `raydium_cpmm.json` | `raydium/raydium_cp.json` |
|
||||
| Raydium AMM v4 | `raydium_amm_v4.json` | `raydium/raydium_amm.json` |
|
||||
| Meteora DAMM v2 | `meteora_damm_v2.json` | `meteora/cp_amm_016.json` |
|
||||
| PumpFun | `pump.json` | `pumpfun/pump.json` |
|
||||
| PumpSwap | `pump_amm.json` | `pumpswap/amm.json` |
|
||||
|
||||
No separate source snapshot tree is kept in the repository.
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
+2602
-2932
File diff suppressed because it is too large
Load Diff
+380
-45
@@ -688,21 +688,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -1134,21 +1119,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -3192,21 +3162,6 @@
|
||||
{
|
||||
"name": "fee_program",
|
||||
"address": "pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ"
|
||||
},
|
||||
{
|
||||
"name": "pool_v2",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [112, 111, 111, 108, 45, 118, 50]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "base_mint"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
@@ -4010,6 +3965,254 @@
|
||||
],
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "transfer_creator_fees_to_pump_v2",
|
||||
"discriminator": [
|
||||
1,
|
||||
33,
|
||||
78,
|
||||
185,
|
||||
33,
|
||||
67,
|
||||
44,
|
||||
92
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"name": "payer",
|
||||
"writable": true,
|
||||
"signer": true
|
||||
},
|
||||
{
|
||||
"name": "quote_mint"
|
||||
},
|
||||
{
|
||||
"name": "token_program"
|
||||
},
|
||||
{
|
||||
"name": "system_program",
|
||||
"address": "11111111111111111111111111111111"
|
||||
},
|
||||
{
|
||||
"name": "associated_token_program",
|
||||
"address": "ATokenGPvbdGVxr1b2hvZbsiqW5xWH25efTNsLJA8knL"
|
||||
},
|
||||
{
|
||||
"name": "coin_creator"
|
||||
},
|
||||
{
|
||||
"name": "coin_creator_vault_authority",
|
||||
"writable": true,
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [
|
||||
99,
|
||||
114,
|
||||
101,
|
||||
97,
|
||||
116,
|
||||
111,
|
||||
114,
|
||||
95,
|
||||
118,
|
||||
97,
|
||||
117,
|
||||
108,
|
||||
116
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "coin_creator"
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "coin_creator_vault_ata",
|
||||
"writable": true,
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "coin_creator_vault_authority"
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "token_program"
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "quote_mint"
|
||||
}
|
||||
],
|
||||
"program": {
|
||||
"kind": "const",
|
||||
"value": [
|
||||
140,
|
||||
151,
|
||||
37,
|
||||
143,
|
||||
78,
|
||||
36,
|
||||
137,
|
||||
241,
|
||||
187,
|
||||
61,
|
||||
16,
|
||||
41,
|
||||
20,
|
||||
142,
|
||||
13,
|
||||
131,
|
||||
11,
|
||||
90,
|
||||
19,
|
||||
153,
|
||||
218,
|
||||
255,
|
||||
16,
|
||||
132,
|
||||
4,
|
||||
142,
|
||||
123,
|
||||
216,
|
||||
219,
|
||||
233,
|
||||
248,
|
||||
89
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "pump_creator_vault",
|
||||
"writable": true,
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [
|
||||
99,
|
||||
114,
|
||||
101,
|
||||
97,
|
||||
116,
|
||||
111,
|
||||
114,
|
||||
45,
|
||||
118,
|
||||
97,
|
||||
117,
|
||||
108,
|
||||
116
|
||||
]
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "coin_creator"
|
||||
}
|
||||
],
|
||||
"program": {
|
||||
"kind": "const",
|
||||
"value": [
|
||||
1,
|
||||
86,
|
||||
224,
|
||||
246,
|
||||
147,
|
||||
102,
|
||||
90,
|
||||
207,
|
||||
68,
|
||||
219,
|
||||
21,
|
||||
104,
|
||||
191,
|
||||
23,
|
||||
91,
|
||||
170,
|
||||
81,
|
||||
137,
|
||||
203,
|
||||
151,
|
||||
245,
|
||||
210,
|
||||
255,
|
||||
59,
|
||||
101,
|
||||
93,
|
||||
43,
|
||||
182,
|
||||
253,
|
||||
109,
|
||||
24,
|
||||
176
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "pump_creator_vault_ata",
|
||||
"writable": true,
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "pump_creator_vault"
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "token_program"
|
||||
},
|
||||
{
|
||||
"kind": "account",
|
||||
"path": "quote_mint"
|
||||
}
|
||||
],
|
||||
"program": {
|
||||
"kind": "account",
|
||||
"path": "associated_token_program"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "event_authority",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [
|
||||
95,
|
||||
95,
|
||||
101,
|
||||
118,
|
||||
101,
|
||||
110,
|
||||
116,
|
||||
95,
|
||||
97,
|
||||
117,
|
||||
116,
|
||||
104,
|
||||
111,
|
||||
114,
|
||||
105,
|
||||
116,
|
||||
121
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "program"
|
||||
}
|
||||
],
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "update_admin",
|
||||
"discriminator": [
|
||||
@@ -4072,6 +4275,72 @@
|
||||
],
|
||||
"args": []
|
||||
},
|
||||
{
|
||||
"name": "update_buyback_config",
|
||||
"discriminator": [
|
||||
251,
|
||||
224,
|
||||
171,
|
||||
146,
|
||||
160,
|
||||
26,
|
||||
113,
|
||||
233
|
||||
],
|
||||
"accounts": [
|
||||
{
|
||||
"name": "admin",
|
||||
"signer": true,
|
||||
"relations": [
|
||||
"global_config"
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "global_config",
|
||||
"writable": true
|
||||
},
|
||||
{
|
||||
"name": "event_authority",
|
||||
"pda": {
|
||||
"seeds": [
|
||||
{
|
||||
"kind": "const",
|
||||
"value": [
|
||||
95,
|
||||
95,
|
||||
101,
|
||||
118,
|
||||
101,
|
||||
110,
|
||||
116,
|
||||
95,
|
||||
97,
|
||||
117,
|
||||
116,
|
||||
104,
|
||||
111,
|
||||
114,
|
||||
105,
|
||||
116,
|
||||
121
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "program"
|
||||
}
|
||||
],
|
||||
"args": [
|
||||
{
|
||||
"name": "buyback_basis_points",
|
||||
"type": {
|
||||
"option": "u64"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"name": "update_fee_config",
|
||||
"discriminator": [
|
||||
@@ -4881,6 +5150,33 @@
|
||||
{
|
||||
"code": 6052,
|
||||
"name": "TokensInVaultLessThanCashbackEarned"
|
||||
},
|
||||
{
|
||||
"code": 6053,
|
||||
"name": "BuybackFeeRecipientNotAuthorized",
|
||||
"msg": "Buyback fee recipient not authorized"
|
||||
},
|
||||
{
|
||||
"code": 6054,
|
||||
"name": "AllBuybackFeeRecipientsShouldBeNonZero"
|
||||
},
|
||||
{
|
||||
"code": 6055,
|
||||
"name": "NotUniqueBuybackFeeRecipients"
|
||||
},
|
||||
{
|
||||
"code": 6056,
|
||||
"name": "BuybackBasisPointsOutOfRange",
|
||||
"msg": "buyback_basis_points must be <= 10_000"
|
||||
},
|
||||
{
|
||||
"code": 6057,
|
||||
"name": "WrongBuybackFeeRecipientsCount",
|
||||
"msg": "buyback fee recipients require exactly 8 remaining accounts (or none)"
|
||||
},
|
||||
{
|
||||
"code": 6058,
|
||||
"name": "BuybackFeeRecipientMissing"
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
@@ -5131,6 +5427,14 @@
|
||||
{
|
||||
"name": "cashback",
|
||||
"type": "u64"
|
||||
},
|
||||
{
|
||||
"name": "buyback_fee_basis_points",
|
||||
"type": "u64"
|
||||
},
|
||||
{
|
||||
"name": "buyback_fee",
|
||||
"type": "u64"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5568,6 +5872,16 @@
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "stable_fee_tiers",
|
||||
"type": {
|
||||
"vec": {
|
||||
"defined": {
|
||||
"name": "FeeTier"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5691,6 +6005,19 @@
|
||||
{
|
||||
"name": "is_cashback_enabled",
|
||||
"type": "bool"
|
||||
},
|
||||
{
|
||||
"name": "buyback_fee_recipients",
|
||||
"type": {
|
||||
"array": [
|
||||
"pubkey",
|
||||
8
|
||||
]
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "buyback_basis_points",
|
||||
"type": "u64"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5986,6 +6313,14 @@
|
||||
{
|
||||
"name": "cashback",
|
||||
"type": "u64"
|
||||
},
|
||||
{
|
||||
"name": "buyback_fee_basis_points",
|
||||
"type": "u64"
|
||||
},
|
||||
{
|
||||
"name": "buyback_fee",
|
||||
"type": "u64"
|
||||
}
|
||||
]
|
||||
}
|
||||
|
||||
+4612
-249
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,40 +0,0 @@
|
||||
# sol-trade-sdk v3.4.1
|
||||
|
||||
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
|
||||
|
||||
## What's Changed
|
||||
|
||||
### New Features
|
||||
|
||||
- **PumpFun & PumpSwap Cashback** (#77): Support for cashback in PumpFun and PumpSwap trading flows. See [Cashback documentation](docs/PUMP_CASHBACK_README.md).
|
||||
- **Events**: `is_cashback_coin` is now passed from events; PumpFun examples use `sol-parser-sdk` only for event parsing.
|
||||
|
||||
### Performance
|
||||
|
||||
- **SWQoS**: Reduced submit latency; fixed high latency after ~5 minutes idle.
|
||||
|
||||
### Bug Fixes
|
||||
|
||||
- **WSOL ATA**: WSOL Associated Token Account creation now runs in background with retry and timeout for more reliable setup.
|
||||
- Silenced unused and deprecated compiler warnings.
|
||||
|
||||
### Documentation
|
||||
|
||||
- README (EN/中文): Added Cashback section, outline, examples and tables.
|
||||
- Updated crates.io / docs references in README.
|
||||
|
||||
---
|
||||
|
||||
## Cargo
|
||||
|
||||
**From Git (this release):**
|
||||
```toml
|
||||
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.4.1" }
|
||||
```
|
||||
|
||||
**From crates.io** (when published):
|
||||
```toml
|
||||
sol-trade-sdk = "3.4.1"
|
||||
```
|
||||
|
||||
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.0...v3.4.1
|
||||
@@ -1,37 +0,0 @@
|
||||
# sol-trade-sdk v3.5.0
|
||||
|
||||
Rust SDK for Solana DEX trading (Pump.fun, PumpSwap, Raydium, Bonk, Meteora, etc.).
|
||||
|
||||
## What's Changed
|
||||
|
||||
### Performance
|
||||
|
||||
- **Executor hot path**: Sample `Instant::now()` only when `log_enabled` or `simulate` (total, build, submit, confirm) to reduce cold-path syscalls.
|
||||
- **SWQOS**: `execute_parallel` now takes `&[Arc<SwqosClient>]` to avoid cloning the client list on each swap.
|
||||
- **Constants**: Named constants for instruction/account sizes and HTTP client timeouts; no magic numbers in hot paths.
|
||||
|
||||
### Code Quality
|
||||
|
||||
- **Protocol params**: Single `validate_protocol_params()` used for both buy and sell; removed duplicate match blocks in `lib.rs`.
|
||||
- **Comments**: Bilingual (English + 中文) doc and inline comments across execution, executor, perf (hardware_optimizations, syscall_bypass), and swqos/common.
|
||||
- **Prefetch/safety**: Clearer docs for cache prefetch and `unsafe` usage (valid read-only ref, no concurrent write).
|
||||
|
||||
### Documentation
|
||||
|
||||
- README (EN/CN): Version references updated to 3.5.0 for path and crates.io usage.
|
||||
|
||||
---
|
||||
|
||||
## Cargo
|
||||
|
||||
**From Git (this release):**
|
||||
```toml
|
||||
sol-trade-sdk = { git = "https://github.com/0xfnzero/sol-trade-sdk", tag = "v3.5.0" }
|
||||
```
|
||||
|
||||
**From crates.io:**
|
||||
```toml
|
||||
sol-trade-sdk = "3.5.0"
|
||||
```
|
||||
|
||||
**Full Changelog**: https://github.com/0xfnzero/sol-trade-sdk/compare/v3.4.1...v3.5.0
|
||||
+2058
File diff suppressed because it is too large
Load Diff
@@ -1,17 +1,37 @@
|
||||
use crate::common::SolanaRpcClient;
|
||||
use anyhow::Result;
|
||||
use solana_address_lookup_table_interface::state::AddressLookupTable;
|
||||
use solana_sdk::{message::AddressLookupTableAccount, pubkey::Pubkey};
|
||||
use solana_message::AddressLookupTableAccount;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
pub async fn fetch_address_lookup_table_account(
|
||||
rpc: &SolanaRpcClient,
|
||||
lookup_table_address: &Pubkey,
|
||||
) -> Result<AddressLookupTableAccount, anyhow::Error> {
|
||||
let account = rpc.get_account(lookup_table_address).await?;
|
||||
let lookup_table = AddressLookupTable::deserialize(&account.data)?;
|
||||
let address_lookup_table_account = AddressLookupTableAccount {
|
||||
key: *lookup_table_address,
|
||||
addresses: lookup_table.addresses.to_vec(),
|
||||
};
|
||||
|
||||
// Parse address lookup table manually
|
||||
// Layout: 4 bytes (type) + 4 bytes (deactivation_slot) + 4 bytes (last_extended_slot) + 1 byte (last_extended_slot_start_index) + 1 byte (authority) + padding
|
||||
// Then addresses start at offset 56, each address is 32 bytes
|
||||
// First 4 bytes indicate if initialized (should be 1 or 2)
|
||||
|
||||
if account.data.len() < 56 {
|
||||
return Err(anyhow::anyhow!("Address lookup table account data too short"));
|
||||
}
|
||||
|
||||
// Read number of addresses (stored at offset 20 as u32, but we need to scan the bitmap)
|
||||
// Actually simpler: addresses start at offset 56, count from bitmap at offset 8-20
|
||||
let mut addresses = Vec::new();
|
||||
let mut offset = 56;
|
||||
while offset + 32 <= account.data.len() {
|
||||
let addr_bytes: [u8; 32] = account.data[offset..offset + 32].try_into()?;
|
||||
// Skip zero addresses (unused slots)
|
||||
if addr_bytes != [0u8; 32] {
|
||||
addresses.push(Pubkey::from(addr_bytes));
|
||||
}
|
||||
offset += 32;
|
||||
}
|
||||
|
||||
let address_lookup_table_account =
|
||||
AddressLookupTableAccount { key: *lookup_table_address, addresses };
|
||||
Ok(address_lookup_table_account)
|
||||
}
|
||||
|
||||
+108
-5
@@ -31,7 +31,7 @@ use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
use crate::instruction::utils::pumpfun::global_constants::{
|
||||
INITIAL_REAL_TOKEN_RESERVES, INITIAL_VIRTUAL_SOL_RESERVES, INITIAL_VIRTUAL_TOKEN_RESERVES,
|
||||
TOKEN_TOTAL_SUPPLY,
|
||||
INITIAL_VIRTUAL_USDC_RESERVES, TOKEN_TOTAL_SUPPLY,
|
||||
};
|
||||
use crate::instruction::utils::pumpfun::{get_bonding_curve_pda, get_creator_vault_pda};
|
||||
|
||||
@@ -62,9 +62,57 @@ pub struct BondingCurveAccount {
|
||||
pub is_mayhem_mode: bool,
|
||||
/// Whether this coin has cashback enabled (creator fee redirected to users)
|
||||
pub is_cashback_coin: bool,
|
||||
/// Quote mint for V2 curves. Defaults to WSOL for legacy/event payloads that do not expose it.
|
||||
pub quote_mint: Pubkey,
|
||||
}
|
||||
|
||||
impl BondingCurveAccount {
|
||||
#[inline]
|
||||
pub fn normalize_quote_mint(quote_mint: Pubkey) -> Pubkey {
|
||||
if quote_mint == Pubkey::default() || quote_mint == crate::constants::SOL_TOKEN_ACCOUNT {
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
} else {
|
||||
quote_mint
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn effective_quote_mint(&self) -> Pubkey {
|
||||
Self::normalize_quote_mint(self.quote_mint)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn initial_virtual_quote_reserves_for_quote_mint(quote_mint: &Pubkey) -> u64 {
|
||||
if *quote_mint == crate::constants::USDC_TOKEN_ACCOUNT {
|
||||
INITIAL_VIRTUAL_USDC_RESERVES
|
||||
} else {
|
||||
INITIAL_VIRTUAL_SOL_RESERVES
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn virtual_quote_reserves(&self) -> u64 {
|
||||
self.virtual_sol_reserves
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn real_quote_reserves(&self) -> u64 {
|
||||
self.real_sol_reserves
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn with_quote_mint(mut self, quote_mint: Pubkey) -> Self {
|
||||
let quote_mint = Self::normalize_quote_mint(quote_mint);
|
||||
let old_initial =
|
||||
Self::initial_virtual_quote_reserves_for_quote_mint(&self.effective_quote_mint());
|
||||
let new_initial = Self::initial_virtual_quote_reserves_for_quote_mint("e_mint);
|
||||
if self.virtual_sol_reserves == old_initial.saturating_add(self.real_sol_reserves) {
|
||||
self.virtual_sol_reserves = new_initial.saturating_add(self.real_sol_reserves);
|
||||
}
|
||||
self.quote_mint = quote_mint;
|
||||
self
|
||||
}
|
||||
|
||||
/// When building from event/parser data (e.g. sol-parser-sdk), pass the token's cashback flag
|
||||
/// so that sell instructions include the correct remaining accounts. From RPC use `from_mint_by_rpc` instead.
|
||||
pub fn from_dev_trade(
|
||||
@@ -75,24 +123,50 @@ impl BondingCurveAccount {
|
||||
creator: Pubkey,
|
||||
is_mayhem_mode: bool,
|
||||
is_cashback_coin: bool,
|
||||
) -> Self {
|
||||
Self::from_dev_trade_with_quote_mint(
|
||||
bonding_curve,
|
||||
mint,
|
||||
dev_token_amount,
|
||||
dev_sol_amount,
|
||||
creator,
|
||||
is_mayhem_mode,
|
||||
is_cashback_coin,
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
)
|
||||
}
|
||||
|
||||
/// Same as [`Self::from_dev_trade`], but quote-aware for V2 pools such as USDC.
|
||||
pub fn from_dev_trade_with_quote_mint(
|
||||
bonding_curve: Pubkey,
|
||||
mint: &Pubkey,
|
||||
dev_token_amount: u64,
|
||||
dev_quote_amount: u64,
|
||||
creator: Pubkey,
|
||||
is_mayhem_mode: bool,
|
||||
is_cashback_coin: bool,
|
||||
quote_mint: Pubkey,
|
||||
) -> Self {
|
||||
let account = if bonding_curve != Pubkey::default() {
|
||||
bonding_curve
|
||||
} else {
|
||||
get_bonding_curve_pda(&mint).unwrap()
|
||||
};
|
||||
let quote_mint = Self::normalize_quote_mint(quote_mint);
|
||||
Self {
|
||||
discriminator: 0,
|
||||
account: account,
|
||||
virtual_token_reserves: INITIAL_VIRTUAL_TOKEN_RESERVES - dev_token_amount,
|
||||
virtual_sol_reserves: INITIAL_VIRTUAL_SOL_RESERVES + dev_sol_amount,
|
||||
virtual_sol_reserves: Self::initial_virtual_quote_reserves_for_quote_mint("e_mint)
|
||||
+ dev_quote_amount,
|
||||
real_token_reserves: INITIAL_REAL_TOKEN_RESERVES - dev_token_amount,
|
||||
real_sol_reserves: dev_sol_amount,
|
||||
real_sol_reserves: dev_quote_amount,
|
||||
token_total_supply: TOKEN_TOTAL_SUPPLY,
|
||||
complete: false,
|
||||
creator: creator,
|
||||
is_mayhem_mode: is_mayhem_mode,
|
||||
is_cashback_coin,
|
||||
quote_mint,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,24 +182,53 @@ impl BondingCurveAccount {
|
||||
real_sol_reserves: u64,
|
||||
is_mayhem_mode: bool,
|
||||
is_cashback_coin: bool,
|
||||
) -> Self {
|
||||
Self::from_trade_with_quote_mint(
|
||||
bonding_curve,
|
||||
mint,
|
||||
creator,
|
||||
virtual_token_reserves,
|
||||
virtual_sol_reserves,
|
||||
real_token_reserves,
|
||||
real_sol_reserves,
|
||||
is_mayhem_mode,
|
||||
is_cashback_coin,
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
)
|
||||
}
|
||||
|
||||
/// Same as [`Self::from_trade`], but carries the V2 quote mint alongside quote reserves.
|
||||
pub fn from_trade_with_quote_mint(
|
||||
bonding_curve: Pubkey,
|
||||
mint: Pubkey,
|
||||
creator: Pubkey,
|
||||
virtual_token_reserves: u64,
|
||||
virtual_quote_reserves: u64,
|
||||
real_token_reserves: u64,
|
||||
real_quote_reserves: u64,
|
||||
is_mayhem_mode: bool,
|
||||
is_cashback_coin: bool,
|
||||
quote_mint: Pubkey,
|
||||
) -> Self {
|
||||
let account = if bonding_curve != Pubkey::default() {
|
||||
bonding_curve
|
||||
} else {
|
||||
get_bonding_curve_pda(&mint).unwrap()
|
||||
};
|
||||
let quote_mint = Self::normalize_quote_mint(quote_mint);
|
||||
Self {
|
||||
discriminator: 0,
|
||||
account: account,
|
||||
virtual_token_reserves: virtual_token_reserves,
|
||||
virtual_sol_reserves: virtual_sol_reserves,
|
||||
virtual_sol_reserves: virtual_quote_reserves,
|
||||
real_token_reserves: real_token_reserves,
|
||||
real_sol_reserves: real_sol_reserves,
|
||||
real_sol_reserves: real_quote_reserves,
|
||||
token_total_supply: TOKEN_TOTAL_SUPPLY,
|
||||
complete: false,
|
||||
creator: creator,
|
||||
is_mayhem_mode: is_mayhem_mode,
|
||||
is_cashback_coin,
|
||||
quote_mint,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+71
-30
@@ -4,7 +4,7 @@ use solana_sdk::{
|
||||
instruction::{AccountMeta, Instruction},
|
||||
pubkey::Pubkey,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
use std::{hash::Hash, sync::Arc};
|
||||
|
||||
use crate::common::{
|
||||
spl_associated_token_account::get_associated_token_address_with_program_id,
|
||||
@@ -21,6 +21,22 @@ const MAX_PDA_CACHE_SIZE: usize = 100_000;
|
||||
const MAX_ATA_CACHE_SIZE: usize = 100_000;
|
||||
const MAX_INSTRUCTION_CACHE_SIZE: usize = 100_000;
|
||||
|
||||
#[inline]
|
||||
fn prune_cache<K, V>(cache: &DashMap<K, V>, max_size: usize)
|
||||
where
|
||||
K: Eq + Hash + Clone,
|
||||
{
|
||||
let len = cache.len();
|
||||
if len <= max_size {
|
||||
return;
|
||||
}
|
||||
let remove_count = (len - max_size).max(max_size / 16).min(len);
|
||||
let keys: Vec<K> = cache.iter().take(remove_count).map(|entry| entry.key().clone()).collect();
|
||||
for key in keys {
|
||||
cache.remove(&key);
|
||||
}
|
||||
}
|
||||
|
||||
// --------------------- Instruction Cache ---------------------
|
||||
|
||||
/// Instruction cache key for uniquely identifying instruction types and parameters
|
||||
@@ -46,7 +62,10 @@ static INSTRUCTION_CACHE: Lazy<DashMap<InstructionCacheKey, Arc<Vec<Instruction>
|
||||
/// Get cached instruction, compute and cache if not exists (lock-free)
|
||||
/// 🚀 返回 Arc 避免每次调用克隆整个 Vec
|
||||
#[inline]
|
||||
pub fn get_cached_instructions<F>(cache_key: InstructionCacheKey, compute_fn: F) -> Arc<Vec<Instruction>>
|
||||
pub fn get_cached_instructions<F>(
|
||||
cache_key: InstructionCacheKey,
|
||||
compute_fn: F,
|
||||
) -> Arc<Vec<Instruction>>
|
||||
where
|
||||
F: FnOnce() -> Vec<Instruction>,
|
||||
{
|
||||
@@ -63,10 +82,10 @@ where
|
||||
};
|
||||
|
||||
// Lock-free cache lookup with entry API
|
||||
INSTRUCTION_CACHE
|
||||
.entry(cache_key)
|
||||
.or_insert_with(|| Arc::new(compute_fn()))
|
||||
.clone()
|
||||
let instructions =
|
||||
INSTRUCTION_CACHE.entry(cache_key).or_insert_with(|| Arc::new(compute_fn())).clone();
|
||||
prune_cache(&INSTRUCTION_CACHE, MAX_INSTRUCTION_CACHE_SIZE);
|
||||
instructions
|
||||
}
|
||||
|
||||
// --------------------- Associated Token Account ---------------------
|
||||
@@ -106,8 +125,26 @@ pub fn _create_associated_token_account_idempotent_fast(
|
||||
use_seed,
|
||||
};
|
||||
|
||||
// Only use seed if the mint address is not wSOL or SOL
|
||||
// 🔧 修复:Token-2022 也支持 seed 方式(白名单方式更安全)
|
||||
let build_standard_create = || {
|
||||
let associated_token_address =
|
||||
get_associated_token_address_with_program_id_fast(owner, mint, token_program);
|
||||
vec![Instruction {
|
||||
program_id: crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID,
|
||||
accounts: vec![
|
||||
AccountMeta::new(*payer, true), // Payer (signer, writable)
|
||||
AccountMeta::new(associated_token_address, false), // ATA address (writable, non-signer)
|
||||
AccountMeta::new_readonly(*owner, false), // Token account owner (readonly, non-signer)
|
||||
AccountMeta::new_readonly(*mint, false), // Token mint address (readonly, non-signer)
|
||||
crate::constants::SYSTEM_PROGRAM_META,
|
||||
AccountMeta::new_readonly(*token_program, false), // Token program (readonly, non-signer)
|
||||
],
|
||||
data: vec![1],
|
||||
}]
|
||||
};
|
||||
|
||||
// Only use seed if the mint address is not wSOL or SOL.
|
||||
// Seed accounts are deterministic token accounts, not ATAs; callers must ensure they are not
|
||||
// recreating an existing seeded account. Fall back to idempotent ATA if seed assembly fails.
|
||||
let arc_instructions = if use_seed
|
||||
&& !mint.eq(&crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
&& !mint.eq(&crate::constants::SOL_TOKEN_ACCOUNT)
|
||||
@@ -117,31 +154,20 @@ pub fn _create_associated_token_account_idempotent_fast(
|
||||
// Use cache to get instruction
|
||||
get_cached_instructions(cache_key, || {
|
||||
super::seed::create_associated_token_account_use_seed(payer, owner, mint, token_program)
|
||||
.unwrap()
|
||||
.unwrap_or_else(|err| {
|
||||
tracing::warn!(
|
||||
"seed token account setup failed for mint {}: {}; fallback to idempotent ATA",
|
||||
mint,
|
||||
err
|
||||
);
|
||||
build_standard_create()
|
||||
})
|
||||
})
|
||||
} else {
|
||||
// Use cache to get instruction
|
||||
get_cached_instructions(cache_key, || {
|
||||
// Get Associated Token Address using cache
|
||||
let associated_token_address =
|
||||
get_associated_token_address_with_program_id_fast(owner, mint, token_program);
|
||||
// Create Associated Token Account instruction
|
||||
// Reference implementation of spl_associated_token_account::instruction::create_associated_token_account
|
||||
vec![Instruction {
|
||||
program_id: crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID,
|
||||
accounts: vec![
|
||||
AccountMeta::new(*payer, true), // Payer (signer, writable)
|
||||
AccountMeta::new(associated_token_address, false), // ATA address (writable, non-signer)
|
||||
AccountMeta::new_readonly(*owner, false), // Token account owner (readonly, non-signer)
|
||||
AccountMeta::new_readonly(*mint, false), // Token mint address (readonly, non-signer)
|
||||
crate::constants::SYSTEM_PROGRAM_META,
|
||||
AccountMeta::new_readonly(*token_program, false), // Token program (readonly, non-signer)
|
||||
],
|
||||
data: vec![1],
|
||||
}]
|
||||
})
|
||||
get_cached_instructions(cache_key, build_standard_create)
|
||||
};
|
||||
|
||||
|
||||
// 🚀 性能优化:尝试零开销解包 Arc,如果引用计数=1则直接移出,否则克隆
|
||||
Arc::try_unwrap(arc_instructions).unwrap_or_else(|arc| (*arc).clone())
|
||||
}
|
||||
@@ -154,6 +180,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),
|
||||
@@ -181,6 +209,7 @@ where
|
||||
|
||||
if let Some(pda) = pda_result {
|
||||
PDA_CACHE.insert(cache_key, pda);
|
||||
prune_cache(&PDA_CACHE, MAX_PDA_CACHE_SIZE);
|
||||
}
|
||||
|
||||
pda_result
|
||||
@@ -263,7 +292,18 @@ fn _get_associated_token_address_with_program_id_fast(
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
)
|
||||
.unwrap()
|
||||
.unwrap_or_else(|err| {
|
||||
tracing::warn!(
|
||||
"seed token account address failed for mint {}: {}; fallback to ATA",
|
||||
token_mint_address,
|
||||
err
|
||||
);
|
||||
get_associated_token_address_with_program_id(
|
||||
wallet_address,
|
||||
token_mint_address,
|
||||
token_program_id,
|
||||
)
|
||||
})
|
||||
} else {
|
||||
get_associated_token_address_with_program_id(
|
||||
wallet_address,
|
||||
@@ -274,6 +314,7 @@ fn _get_associated_token_address_with_program_id_fast(
|
||||
|
||||
// Store computation result in cache (lock-free)
|
||||
ATA_CACHE.insert(cache_key, ata);
|
||||
prune_cache(&ATA_CACHE, MAX_ATA_CACHE_SIZE);
|
||||
|
||||
ata
|
||||
}
|
||||
|
||||
+16
-18
@@ -2,9 +2,9 @@
|
||||
//!
|
||||
//! 使用 syscall_bypass 提供的快速时间戳避免频繁的系统调用
|
||||
|
||||
use std::time::{Duration, Instant};
|
||||
use once_cell::sync::Lazy;
|
||||
use crate::perf::syscall_bypass::SystemCallBypassManager;
|
||||
use once_cell::sync::Lazy;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
/// 全局快速时间提供器
|
||||
static FAST_TIMER: Lazy<FastTimer> = Lazy::new(|| FastTimer::new());
|
||||
@@ -26,11 +26,7 @@ impl FastTimer {
|
||||
let base_instant = Instant::now();
|
||||
let base_nanos = bypass_manager.fast_timestamp_nanos();
|
||||
|
||||
Self {
|
||||
bypass_manager,
|
||||
_base_instant: base_instant,
|
||||
_base_nanos: base_nanos,
|
||||
}
|
||||
Self { bypass_manager, _base_instant: base_instant, _base_nanos: base_nanos }
|
||||
}
|
||||
|
||||
/// 🚀 获取当前时间戳(纳秒) - 使用快速系统调用绕过
|
||||
@@ -107,10 +103,7 @@ impl FastStopwatch {
|
||||
/// 创建并启动计时器
|
||||
#[inline(always)]
|
||||
pub fn start(label: &'static str) -> Self {
|
||||
Self {
|
||||
start_nanos: fast_now_nanos(),
|
||||
label,
|
||||
}
|
||||
Self { start_nanos: fast_now_nanos(), label }
|
||||
}
|
||||
|
||||
/// 获取已耗时(纳秒)
|
||||
@@ -148,8 +141,8 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
let elapsed = fast_elapsed_nanos(start);
|
||||
|
||||
// 应该大约是 10ms = 10,000,000 纳秒
|
||||
assert!(elapsed >= 9_000_000 && elapsed <= 12_000_000);
|
||||
// Scheduler jitter can exceed the sleep duration; the fast timer must not under-report.
|
||||
assert!(elapsed >= 9_000_000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -158,13 +151,18 @@ mod tests {
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
let elapsed_ms = sw.elapsed_millis();
|
||||
|
||||
assert!(elapsed_ms >= 9 && elapsed_ms <= 12);
|
||||
assert!(elapsed_ms >= 9);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_fast_now_overhead() {
|
||||
// 测试调用开销
|
||||
let iterations = 10_000;
|
||||
// This is a coarse regression guard, not a benchmark. On non-Linux targets
|
||||
// the fast timer uses `Instant::elapsed()`, and CI/desktop scheduler jitter can
|
||||
// move a single run above 100ns even when the code path is still sub-microsecond.
|
||||
let iterations = 100_000;
|
||||
for _ in 0..1_000 {
|
||||
let _ = fast_now_nanos();
|
||||
}
|
||||
let start = Instant::now();
|
||||
|
||||
for _ in 0..iterations {
|
||||
@@ -178,8 +176,8 @@ mod tests {
|
||||
println!("Average fast_now_nanos() call: {}ns", avg_per_call);
|
||||
}
|
||||
|
||||
// 快速时间戳应该非常快(< 100ns per call)
|
||||
assert!(avg_per_call < 100);
|
||||
// Keep the hot-path timer safely sub-microsecond without making the test flaky.
|
||||
assert!(avg_per_call < 500);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
+179
-10
@@ -1,6 +1,6 @@
|
||||
use crate::swqos::{SwqosType, TradeType};
|
||||
use arc_swap::ArcSwap;
|
||||
use std::collections::HashMap;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
@@ -14,6 +14,15 @@ impl GasFeeStrategyType {
|
||||
pub fn values() -> Vec<Self> {
|
||||
vec![Self::Normal, Self::LowTipHighCuPrice, Self::HighTipLowCuPrice]
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn as_str(&self) -> &'static str {
|
||||
match self {
|
||||
Self::Normal => "Normal",
|
||||
Self::LowTipHighCuPrice => "LowTipHighCuPrice",
|
||||
Self::HighTipLowCuPrice => "HighTipLowCuPrice",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
@@ -84,6 +93,33 @@ impl GasFeeStrategy {
|
||||
);
|
||||
}
|
||||
|
||||
/// 设置 Default/RPC 的优先费-only 策略。Default 没有 relay tip account,
|
||||
/// 但仍应携带 ComputeBudget 优先费。
|
||||
pub fn set_default_rpc_fee_strategy(
|
||||
&self,
|
||||
buy_cu_limit: u32,
|
||||
sell_cu_limit: u32,
|
||||
buy_cu_price: u64,
|
||||
sell_cu_price: u64,
|
||||
) {
|
||||
self.set(
|
||||
SwqosType::Default,
|
||||
TradeType::Buy,
|
||||
GasFeeStrategyType::Normal,
|
||||
buy_cu_limit,
|
||||
buy_cu_price,
|
||||
0.0,
|
||||
);
|
||||
self.set(
|
||||
SwqosType::Default,
|
||||
TradeType::Sell,
|
||||
GasFeeStrategyType::Normal,
|
||||
sell_cu_limit,
|
||||
sell_cu_price,
|
||||
0.0,
|
||||
);
|
||||
}
|
||||
|
||||
/// 为多个服务类型添加高低费率策略,会移除(SwqosType,TradeType)的默认策略。
|
||||
/// Add high-low fee strategies for multiple service types, Will remove the default strategy of (SwqosType,TradeType)
|
||||
pub fn set_high_low_fee_strategies(
|
||||
@@ -271,7 +307,7 @@ impl GasFeeStrategy {
|
||||
) -> Vec<(SwqosType, GasFeeStrategyType, GasFeeStrategyValue)> {
|
||||
let strategies = self.strategies.load();
|
||||
let mut result = Vec::new();
|
||||
let mut swqos_types = std::collections::HashSet::new();
|
||||
let mut swqos_types = HashSet::new();
|
||||
for (swqos_type, t_type, _) in strategies.keys() {
|
||||
if *t_type == trade_type {
|
||||
swqos_types.insert(*swqos_type);
|
||||
@@ -298,10 +334,17 @@ impl GasFeeStrategy {
|
||||
/// 动态更新买入小费(保持其他参数不变)
|
||||
/// Dynamically update buy tip (keep other parameters unchanged)
|
||||
pub fn update_buy_tip(&self, buy_tip: f64) {
|
||||
self.update_buy_tip_for_strategy(GasFeeStrategyType::Normal, buy_tip);
|
||||
}
|
||||
|
||||
/// 动态更新指定买入策略的小费(保持其他参数不变)。
|
||||
/// Dynamic updates should generally target Normal only; updating all strategies would
|
||||
/// collapse the low-tip/high-tip dual-lane spread into the same tip.
|
||||
pub fn update_buy_tip_for_strategy(&self, strategy_type: GasFeeStrategyType, buy_tip: f64) {
|
||||
self.strategies.rcu(|current_map| {
|
||||
let mut new_map = (**current_map).clone();
|
||||
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Buy {
|
||||
for ((_swqos_type, trade_type, s_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Buy && *s_type == strategy_type {
|
||||
value.tip = buy_tip;
|
||||
}
|
||||
}
|
||||
@@ -312,10 +355,15 @@ impl GasFeeStrategy {
|
||||
/// 动态更新卖出小费(保持其他参数不变)
|
||||
/// Dynamically update sell tip (keep other parameters unchanged)
|
||||
pub fn update_sell_tip(&self, sell_tip: f64) {
|
||||
self.update_sell_tip_for_strategy(GasFeeStrategyType::Normal, sell_tip);
|
||||
}
|
||||
|
||||
/// 动态更新指定卖出策略的小费(保持其他参数不变)。
|
||||
pub fn update_sell_tip_for_strategy(&self, strategy_type: GasFeeStrategyType, sell_tip: f64) {
|
||||
self.strategies.rcu(|current_map| {
|
||||
let mut new_map = (**current_map).clone();
|
||||
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Sell {
|
||||
for ((_swqos_type, trade_type, s_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Sell && *s_type == strategy_type {
|
||||
value.tip = sell_tip;
|
||||
}
|
||||
}
|
||||
@@ -326,10 +374,19 @@ impl GasFeeStrategy {
|
||||
/// 动态更新买入优先费(保持其他参数不变)
|
||||
/// Dynamically update buy compute unit price (keep other parameters unchanged)
|
||||
pub fn update_buy_cu_price(&self, buy_cu_price: u64) {
|
||||
self.update_buy_cu_price_for_strategy(GasFeeStrategyType::Normal, buy_cu_price);
|
||||
}
|
||||
|
||||
/// 动态更新指定买入策略的优先费(保持其他参数不变)。
|
||||
pub fn update_buy_cu_price_for_strategy(
|
||||
&self,
|
||||
strategy_type: GasFeeStrategyType,
|
||||
buy_cu_price: u64,
|
||||
) {
|
||||
self.strategies.rcu(|current_map| {
|
||||
let mut new_map = (**current_map).clone();
|
||||
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Buy {
|
||||
for ((_swqos_type, trade_type, s_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Buy && *s_type == strategy_type {
|
||||
value.cu_price = buy_cu_price;
|
||||
}
|
||||
}
|
||||
@@ -340,10 +397,19 @@ impl GasFeeStrategy {
|
||||
/// 动态更新卖出优先费(保持其他参数不变)
|
||||
/// Dynamically update sell compute unit price (keep other parameters unchanged)
|
||||
pub fn update_sell_cu_price(&self, sell_cu_price: u64) {
|
||||
self.update_sell_cu_price_for_strategy(GasFeeStrategyType::Normal, sell_cu_price);
|
||||
}
|
||||
|
||||
/// 动态更新指定卖出策略的优先费(保持其他参数不变)。
|
||||
pub fn update_sell_cu_price_for_strategy(
|
||||
&self,
|
||||
strategy_type: GasFeeStrategyType,
|
||||
sell_cu_price: u64,
|
||||
) {
|
||||
self.strategies.rcu(|current_map| {
|
||||
let mut new_map = (**current_map).clone();
|
||||
for ((_swqos_type, trade_type, _strategy_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Sell {
|
||||
for ((_swqos_type, trade_type, s_type), value) in new_map.iter_mut() {
|
||||
if *trade_type == TradeType::Sell && *s_type == strategy_type {
|
||||
value.cu_price = sell_cu_price;
|
||||
}
|
||||
}
|
||||
@@ -365,3 +431,106 @@ impl GasFeeStrategy {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn find_strategy(
|
||||
strategies: &[(SwqosType, GasFeeStrategyType, GasFeeStrategyValue)],
|
||||
swqos_type: SwqosType,
|
||||
strategy_type: GasFeeStrategyType,
|
||||
) -> GasFeeStrategyValue {
|
||||
strategies
|
||||
.iter()
|
||||
.find(|(s, t, _)| *s == swqos_type && *t == strategy_type)
|
||||
.map(|(_, _, v)| *v)
|
||||
.expect("strategy exists")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn high_low_fee_strategy_expands_two_lanes_per_swqos() {
|
||||
let strategy = GasFeeStrategy::new();
|
||||
|
||||
strategy.set_high_low_fee_strategies(
|
||||
&[SwqosType::Jito, SwqosType::Helius],
|
||||
TradeType::Buy,
|
||||
100_000,
|
||||
180_000,
|
||||
400_000,
|
||||
0.002,
|
||||
0.005,
|
||||
);
|
||||
|
||||
let strategies = strategy.get_strategies(TradeType::Buy);
|
||||
assert_eq!(strategies.len(), 4);
|
||||
|
||||
for swqos_type in [SwqosType::Jito, SwqosType::Helius] {
|
||||
let low_tip_high_cu =
|
||||
find_strategy(&strategies, swqos_type, GasFeeStrategyType::LowTipHighCuPrice);
|
||||
assert_eq!(low_tip_high_cu.cu_limit, 100_000);
|
||||
assert_eq!(low_tip_high_cu.cu_price, 400_000);
|
||||
assert_eq!(low_tip_high_cu.tip, 0.002);
|
||||
|
||||
let high_tip_low_cu =
|
||||
find_strategy(&strategies, swqos_type, GasFeeStrategyType::HighTipLowCuPrice);
|
||||
assert_eq!(high_tip_low_cu.cu_limit, 100_000);
|
||||
assert_eq!(high_tip_low_cu.cu_price, 180_000);
|
||||
assert_eq!(high_tip_low_cu.tip, 0.005);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_updates_do_not_collapse_dual_lane_fees() {
|
||||
let strategy = GasFeeStrategy::new();
|
||||
|
||||
strategy.set_high_low_fee_strategy(
|
||||
SwqosType::Jito,
|
||||
TradeType::Buy,
|
||||
100_000,
|
||||
180_000,
|
||||
400_000,
|
||||
0.002,
|
||||
0.005,
|
||||
);
|
||||
|
||||
strategy.update_buy_tip(0.009);
|
||||
strategy.update_buy_cu_price(999_999);
|
||||
|
||||
let strategies = strategy.get_strategies(TradeType::Buy);
|
||||
let low_tip_high_cu =
|
||||
find_strategy(&strategies, SwqosType::Jito, GasFeeStrategyType::LowTipHighCuPrice);
|
||||
let high_tip_low_cu =
|
||||
find_strategy(&strategies, SwqosType::Jito, GasFeeStrategyType::HighTipLowCuPrice);
|
||||
|
||||
assert_eq!(low_tip_high_cu.cu_price, 400_000);
|
||||
assert_eq!(low_tip_high_cu.tip, 0.002);
|
||||
assert_eq!(high_tip_low_cu.cu_price, 180_000);
|
||||
assert_eq!(high_tip_low_cu.tip, 0.005);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_rpc_strategy_uses_priority_fee_without_tip() {
|
||||
let strategy = GasFeeStrategy::new();
|
||||
|
||||
strategy.set_default_rpc_fee_strategy(100_000, 90_000, 700_000, 800_000);
|
||||
|
||||
let buy = find_strategy(
|
||||
&strategy.get_strategies(TradeType::Buy),
|
||||
SwqosType::Default,
|
||||
GasFeeStrategyType::Normal,
|
||||
);
|
||||
assert_eq!(buy.cu_limit, 100_000);
|
||||
assert_eq!(buy.cu_price, 700_000);
|
||||
assert_eq!(buy.tip, 0.0);
|
||||
|
||||
let sell = find_strategy(
|
||||
&strategy.get_strategies(TradeType::Sell),
|
||||
SwqosType::Default,
|
||||
GasFeeStrategyType::Normal,
|
||||
);
|
||||
assert_eq!(sell.cu_limit, 90_000);
|
||||
assert_eq!(sell.cu_price, 800_000);
|
||||
assert_eq!(sell.tip, 0.0);
|
||||
}
|
||||
}
|
||||
|
||||
+1
-1
@@ -2,11 +2,11 @@ pub mod address_lookup;
|
||||
pub mod bonding_curve;
|
||||
pub mod clock;
|
||||
pub mod fast_fn;
|
||||
pub mod sdk_log;
|
||||
pub mod fast_timing;
|
||||
pub mod gas_fee_strategy;
|
||||
pub mod global;
|
||||
pub mod nonce_cache;
|
||||
pub mod sdk_log;
|
||||
pub mod seed;
|
||||
pub mod spl_associated_token_account;
|
||||
pub mod spl_token;
|
||||
|
||||
+14
-14
@@ -1,8 +1,5 @@
|
||||
use crate::common::SolanaRpcClient;
|
||||
use solana_hash::Hash;
|
||||
use solana_nonce::state::State;
|
||||
use solana_nonce::versions::Versions;
|
||||
use solana_sdk::account_utils::StateMut;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use tracing::error;
|
||||
|
||||
@@ -21,18 +18,21 @@ pub async fn fetch_nonce_info(
|
||||
nonce_account: Pubkey,
|
||||
) -> Option<DurableNonceInfo> {
|
||||
match rpc.get_account(&nonce_account).await {
|
||||
Ok(account) => match account.state() {
|
||||
Ok(Versions::Current(state)) => {
|
||||
if let State::Initialized(data) = *state {
|
||||
let blockhash = data.durable_nonce.as_hash();
|
||||
return Some(DurableNonceInfo {
|
||||
nonce_account: Some(nonce_account),
|
||||
current_nonce: Some(*blockhash),
|
||||
});
|
||||
}
|
||||
Ok(account) => {
|
||||
// Parse nonce account manually: first 4 bytes is version, then 4 bytes authority type
|
||||
// For initialized nonce: version=0, authority_type=0, then authority (32 bytes), then blockhash (32 bytes), then fee_calculator
|
||||
if account.data.len() >= 80 {
|
||||
// Skip version (4) + authority_type (4) + authority (32) = 40 bytes
|
||||
// Then blockhash is at offset 40
|
||||
let blockhash_bytes: [u8; 32] = account.data[40..72].try_into().ok()?;
|
||||
return Some(DurableNonceInfo {
|
||||
nonce_account: Some(nonce_account),
|
||||
current_nonce: Some(Hash::from(blockhash_bytes)),
|
||||
});
|
||||
} else {
|
||||
error!("Nonce account data too short");
|
||||
}
|
||||
_ => (),
|
||||
},
|
||||
}
|
||||
Err(e) => {
|
||||
error!("Failed to get nonce account information: {:?}", e);
|
||||
}
|
||||
|
||||
@@ -3,10 +3,56 @@
|
||||
//! Controlled by `TradeConfig::log_enabled`, set in `TradingClient::new`.
|
||||
//! All SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.) should check this before output.
|
||||
|
||||
use std::fmt;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use std::time::Duration;
|
||||
|
||||
/// Format duration for log: "97.9396 ms" or "13.936 µs", 4 decimal places, space before unit.
|
||||
fn format_elapsed(d: Duration) -> String {
|
||||
let secs = d.as_secs_f64();
|
||||
if secs < 0.001 {
|
||||
format!("{:.4} µs", secs * 1_000_000.0)
|
||||
} else {
|
||||
format!("{:.4} ms", secs * 1000.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Extract a short error message for SWQOS submission failed log.
|
||||
/// Tries JSON "message"/"data" and quoted string; on any parse failure returns original (no panic).
|
||||
fn extract_swqos_error_message(s: &str) -> String {
|
||||
let s = s.trim();
|
||||
if s.is_empty() {
|
||||
return String::new();
|
||||
}
|
||||
// Plain double-quoted string (no inner JSON): unquote
|
||||
if s.starts_with('"') && s.ends_with('"') && s.len() >= 2 {
|
||||
let inner = &s[1..s.len() - 1];
|
||||
if !inner.contains('{') {
|
||||
return inner.replace("\\\"", "\"");
|
||||
}
|
||||
}
|
||||
// Try parse as JSON only when input looks like JSON (avoid parsing long non-JSON strings)
|
||||
if s.starts_with('{') {
|
||||
if let Ok(v) = serde_json::from_str::<serde_json::Value>(s) {
|
||||
let obj = v.get("error").and_then(|e| e.as_object()).or_else(|| v.as_object());
|
||||
if let Some(o) = obj {
|
||||
if let Some(m) = o.get("message").and_then(|x| x.as_str()) {
|
||||
return m.to_string();
|
||||
}
|
||||
if let Some(d) = o.get("data").and_then(|x| x.as_str()) {
|
||||
return d.to_string();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
s.to_string()
|
||||
}
|
||||
|
||||
static SDK_LOG_ENABLED: AtomicBool = AtomicBool::new(true);
|
||||
|
||||
/// Width of [provider] label so SWQOS submit/confirm lines align (longest: Speedlanding).
|
||||
pub const SWQOS_LABEL_WIDTH: usize = 12;
|
||||
|
||||
/// Whether SDK logging is enabled (set from TradeConfig.log_enabled in TradingClient::new).
|
||||
#[inline(always)]
|
||||
pub fn sdk_log_enabled() -> bool {
|
||||
@@ -17,3 +63,101 @@ pub fn sdk_log_enabled() -> bool {
|
||||
pub fn set_sdk_log_enabled(enabled: bool) {
|
||||
SDK_LOG_ENABLED.store(enabled, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Aligned log: ` [Soyas ] Buy submitted: 13.936 µs`. Call only when sdk_log_enabled().
|
||||
#[inline]
|
||||
pub fn log_swqos_submitted(provider: &str, trade_type: impl fmt::Display, elapsed: Duration) {
|
||||
println!(
|
||||
" [{:width$}] {} submitted: {}",
|
||||
provider,
|
||||
trade_type,
|
||||
format_elapsed(elapsed),
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
|
||||
/// Prints one SDK timing block (build_instructions, before_submit, per-channel submit_done).
|
||||
/// When confirm_us is Some, prints confirmed + total; when None, prints "confirmed: -, total: submit_ms".
|
||||
/// Call only when sdk_log_enabled().
|
||||
pub fn print_sdk_timing_block(
|
||||
dir: &str,
|
||||
start_us: Option<i64>,
|
||||
build_end_us: Option<i64>,
|
||||
before_submit_us: Option<i64>,
|
||||
submit_timings: &[crate::common::SwqosSubmitTiming],
|
||||
confirm_us: Option<i64>,
|
||||
) {
|
||||
println!();
|
||||
let start_us = match start_us {
|
||||
Some(u) => u,
|
||||
None => return,
|
||||
};
|
||||
if let Some(end_us) = build_end_us {
|
||||
println!(
|
||||
" [SDK][{:width$}] {} build_instructions: {:.4} ms",
|
||||
"-",
|
||||
dir,
|
||||
(end_us - start_us) as f64 / 1000.0,
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
if let Some(end_us) = before_submit_us {
|
||||
println!(
|
||||
" [SDK][{:width$}] {} before_submit: {:.4} ms",
|
||||
"-",
|
||||
dir,
|
||||
(end_us - start_us) as f64 / 1000.0,
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
if let Some(confirm_done_us) = confirm_us {
|
||||
let total_ms = (confirm_done_us - start_us) as f64 / 1000.0;
|
||||
for timing in submit_timings {
|
||||
let submit_ms = (timing.submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||
let confirmed_ms = (confirm_done_us - timing.submit_done_us).max(0) as f64 / 1000.0;
|
||||
println!(
|
||||
" [SDK][{:width$}] {} {} submit_done: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms",
|
||||
timing.swqos_type.as_str(),
|
||||
dir,
|
||||
timing.strategy_type.as_str(),
|
||||
submit_ms,
|
||||
confirmed_ms,
|
||||
total_ms,
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
} else {
|
||||
for timing in submit_timings {
|
||||
let submit_ms = (timing.submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||
println!(
|
||||
" [SDK][{:width$}] {} {} submit_done: {:.4} ms, confirmed: -, total: {:.4} ms",
|
||||
timing.swqos_type.as_str(),
|
||||
dir,
|
||||
timing.strategy_type.as_str(),
|
||||
submit_ms,
|
||||
submit_ms,
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Aligned log: ` [Stellium ] Buy submission failed after 97.9396 ms: ...`. Call only when sdk_log_enabled().
|
||||
/// Error is normalized: JSON "message"/"data" or quoted string is shown; raw JSON is not.
|
||||
#[inline]
|
||||
pub fn log_swqos_submission_failed(
|
||||
provider: &str,
|
||||
trade_type: impl fmt::Display,
|
||||
elapsed: Duration,
|
||||
err: impl fmt::Display,
|
||||
) {
|
||||
let msg = extract_swqos_error_message(&format!("{}", err));
|
||||
eprintln!(
|
||||
" [{:width$}] {} submission failed after {}, error: {}",
|
||||
provider,
|
||||
trade_type,
|
||||
format_elapsed(elapsed),
|
||||
msg,
|
||||
width = SWQOS_LABEL_WIDTH
|
||||
);
|
||||
}
|
||||
|
||||
+61
-43
@@ -1,13 +1,12 @@
|
||||
use crate::common::SolanaRpcClient;
|
||||
use anyhow::anyhow;
|
||||
use fnv::FnvHasher;
|
||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
||||
use solana_system_interface::instruction::create_account_with_seed;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::Arc;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use tokio::time::{sleep, Duration};
|
||||
use once_cell::sync::Lazy;
|
||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
||||
use solana_system_interface::instruction as system_instruction;
|
||||
use std::hash::Hasher;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::Arc;
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
// 🚀 优化:使用 AtomicU64 替代 RwLock,性能提升 5-10x
|
||||
// u64::MAX 表示未初始化状态
|
||||
@@ -17,7 +16,7 @@ static SPL_TOKEN_2022_RENT: Lazy<AtomicU64> = Lazy::new(|| AtomicU64::new(u64::M
|
||||
/// 更新租金缓存(后台任务调用)
|
||||
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
||||
let rent = fetch_rent_for_token_account(client, false).await?;
|
||||
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
||||
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
||||
|
||||
let rent = fetch_rent_for_token_account(client, true).await?;
|
||||
SPL_TOKEN_2022_RENT.store(rent, Ordering::Release);
|
||||
@@ -25,6 +24,15 @@ pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error>
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// 165 字节 Token 账户的典型租金(lamports),RPC 超时时用作回退
|
||||
const DEFAULT_TOKEN_ACCOUNT_RENT: u64 = 2_039_280;
|
||||
|
||||
/// 当 RPC 超时或不可用时设置默认租金,避免客户端创建卡死
|
||||
pub fn set_default_rents() {
|
||||
SPL_TOKEN_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
|
||||
SPL_TOKEN_2022_RENT.store(DEFAULT_TOKEN_ACCOUNT_RENT, Ordering::Release);
|
||||
}
|
||||
|
||||
pub fn start_rent_updater(client: Arc<SolanaRpcClient>) {
|
||||
tokio::spawn(async move {
|
||||
loop {
|
||||
@@ -41,6 +49,26 @@ async fn fetch_rent_for_token_account(
|
||||
Ok(client.get_minimum_balance_for_rent_exemption(165).await?)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn derive_seed_from_mint(mint: &Pubkey) -> String {
|
||||
// Keep the legacy 8-hex seed stable. Changing this derivation changes the token account
|
||||
// address and can strand balances created by earlier buys.
|
||||
let mut hasher = FnvHasher::default();
|
||||
hasher.write(mint.as_ref());
|
||||
let hash = hasher.finish();
|
||||
let v = (hash & 0xFFFF_FFFF) as u32;
|
||||
let mut seed = String::with_capacity(8);
|
||||
for i in 0..8 {
|
||||
let nibble = ((v >> (28 - i * 4)) & 0xF) as u8;
|
||||
let byte = match nibble {
|
||||
0..=9 => b'0' + nibble,
|
||||
_ => b'a' + (nibble - 10),
|
||||
};
|
||||
seed.push(byte as char);
|
||||
}
|
||||
seed
|
||||
}
|
||||
|
||||
pub fn create_associated_token_account_use_seed(
|
||||
payer: &Pubkey,
|
||||
owner: &Pubkey,
|
||||
@@ -53,35 +81,37 @@ pub fn create_associated_token_account_use_seed(
|
||||
// Relaxed: 租金值不变,无需同步;Release/Acquire 在 update_rents 保证初始化可见性
|
||||
let rent = if is_2022_token {
|
||||
let v = SPL_TOKEN_2022_RENT.load(Ordering::Relaxed);
|
||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
||||
v
|
||||
if v == u64::MAX {
|
||||
DEFAULT_TOKEN_ACCOUNT_RENT
|
||||
} else {
|
||||
v
|
||||
}
|
||||
} else {
|
||||
let v = SPL_TOKEN_RENT.load(Ordering::Relaxed);
|
||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
||||
v
|
||||
if v == u64::MAX {
|
||||
DEFAULT_TOKEN_ACCOUNT_RENT
|
||||
} else {
|
||||
v
|
||||
}
|
||||
};
|
||||
|
||||
let mut buf = [0u8; 8];
|
||||
let mut hasher = FnvHasher::default();
|
||||
hasher.write(mint.as_ref());
|
||||
let hash = hasher.finish();
|
||||
let v = (hash & 0xFFFF_FFFF) as u32;
|
||||
for i in 0..8 {
|
||||
let nibble = ((v >> (28 - i * 4)) & 0xF) as u8;
|
||||
buf[i] = match nibble {
|
||||
0..=9 => b'0' + nibble,
|
||||
_ => b'a' + (nibble - 10),
|
||||
};
|
||||
}
|
||||
let seed = unsafe { std::str::from_utf8_unchecked(&buf) };
|
||||
let seed = derive_seed_from_mint(mint);
|
||||
// 🔧 修复:使用传入的 token_program 生成地址(支持 Token 和 Token-2022)
|
||||
// 买入和卖出只要都使用事件中的 token_program,地址自然一致
|
||||
let ata_like = Pubkey::create_with_seed(payer, seed, token_program)?;
|
||||
let ata_like = Pubkey::create_with_seed(payer, &seed, token_program)?;
|
||||
|
||||
let len = 165;
|
||||
// 但账户的 owner 仍然使用正确的 token_program(Token 或 Token-2022)
|
||||
let create_acc =
|
||||
create_account_with_seed(payer, &ata_like, owner, seed, rent, len, token_program);
|
||||
// 🔧 修复: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 init_acc = if is_2022_token {
|
||||
crate::common::spl_token_2022::initialize_account3(&token_program, &ata_like, mint, owner)?
|
||||
@@ -97,21 +127,9 @@ pub fn get_associated_token_address_with_program_id_use_seed(
|
||||
token_mint_address: &Pubkey,
|
||||
token_program_id: &Pubkey,
|
||||
) -> Result<Pubkey, anyhow::Error> {
|
||||
let mut buf = [0u8; 8];
|
||||
let mut hasher = FnvHasher::default();
|
||||
hasher.write(token_mint_address.as_ref());
|
||||
let hash = hasher.finish();
|
||||
let v = (hash & 0xFFFF_FFFF) as u32;
|
||||
for i in 0..8 {
|
||||
let nibble = ((v >> (28 - i * 4)) & 0xF) as u8;
|
||||
buf[i] = match nibble {
|
||||
0..=9 => b'0' + nibble,
|
||||
_ => b'a' + (nibble - 10),
|
||||
};
|
||||
}
|
||||
let seed = unsafe { std::str::from_utf8_unchecked(&buf) };
|
||||
let seed = derive_seed_from_mint(token_mint_address);
|
||||
// 🔧 修复:使用传入的 token_program_id 生成地址(支持 Token 和 Token-2022)
|
||||
// 买入和卖出只要都使用事件中的 token_program_id,地址自然一致
|
||||
let ata_like = Pubkey::create_with_seed(wallet_address, seed, token_program_id)?;
|
||||
let ata_like = Pubkey::create_with_seed(wallet_address, &seed, token_program_id)?;
|
||||
Ok(ata_like)
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use solana_sdk::{
|
||||
message::{AccountMeta, Instruction},
|
||||
instruction::{AccountMeta, Instruction},
|
||||
pubkey::Pubkey,
|
||||
};
|
||||
|
||||
|
||||
+6
-13
@@ -1,6 +1,6 @@
|
||||
use solana_program::pubkey;
|
||||
use solana_sdk::{
|
||||
message::{AccountMeta, Instruction},
|
||||
instruction::{AccountMeta, Instruction},
|
||||
program_error::ProgramError,
|
||||
pubkey::Pubkey,
|
||||
};
|
||||
@@ -18,14 +18,11 @@ pub fn close_account(
|
||||
let mut data = Vec::with_capacity(1);
|
||||
data.push(9);
|
||||
let mut accounts = Vec::with_capacity(3 + signer_pubkeys.len());
|
||||
accounts.push(solana_sdk::message::AccountMeta::new(*account_pubkey, false));
|
||||
accounts.push(solana_sdk::message::AccountMeta::new(*destination_pubkey, false));
|
||||
accounts.push(solana_sdk::message::AccountMeta::new_readonly(
|
||||
*owner_pubkey,
|
||||
signer_pubkeys.is_empty(),
|
||||
));
|
||||
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()));
|
||||
for signer_pubkey in signer_pubkeys.iter() {
|
||||
accounts.push(solana_sdk::message::AccountMeta::new_readonly(**signer_pubkey, true));
|
||||
accounts.push(AccountMeta::new_readonly(**signer_pubkey, true));
|
||||
}
|
||||
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
||||
}
|
||||
@@ -52,11 +49,7 @@ pub fn transfer(
|
||||
accounts.push(AccountMeta::new_readonly(**signer, true));
|
||||
}
|
||||
|
||||
Ok(Instruction {
|
||||
program_id: *token_program_id,
|
||||
accounts,
|
||||
data,
|
||||
})
|
||||
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
||||
}
|
||||
|
||||
pub fn initialize_account3(
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use solana_program::pubkey;
|
||||
use solana_sdk::{
|
||||
message::{AccountMeta, Instruction},
|
||||
instruction::{AccountMeta, Instruction},
|
||||
program_error::ProgramError,
|
||||
pubkey::Pubkey,
|
||||
};
|
||||
|
||||
+141
-20
@@ -1,4 +1,5 @@
|
||||
use crate::swqos::SwqosConfig;
|
||||
use crate::common::GasFeeStrategyType;
|
||||
use crate::swqos::{SwqosConfig, SwqosType};
|
||||
use solana_commitment_config::CommitmentConfig;
|
||||
use std::hash::{Hash, Hasher};
|
||||
|
||||
@@ -9,6 +10,12 @@ pub struct InfrastructureConfig {
|
||||
pub rpc_url: String,
|
||||
pub swqos_configs: Vec<SwqosConfig>,
|
||||
pub commitment: CommitmentConfig,
|
||||
/// When true, SWQOS sender threads use the *last* N cores instead of the first N. Reduces contention with main thread / default tokio workers that often use low-numbered cores. Default false.
|
||||
pub swqos_cores_from_end: bool,
|
||||
/// Global MEV protection flag. When true, SWQOS providers that support MEV protection
|
||||
/// (Astralane QUIC `:9000` or HTTP `mev-protect=true`, BlockRazor) use MEV-protected
|
||||
/// endpoints/modes. Default false.
|
||||
pub mev_protection: bool,
|
||||
}
|
||||
|
||||
impl InfrastructureConfig {
|
||||
@@ -21,6 +28,8 @@ impl InfrastructureConfig {
|
||||
rpc_url,
|
||||
swqos_configs,
|
||||
commitment,
|
||||
swqos_cores_from_end: false,
|
||||
mev_protection: false,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,6 +39,8 @@ impl InfrastructureConfig {
|
||||
rpc_url: config.rpc_url.clone(),
|
||||
swqos_configs: config.swqos_configs.clone(),
|
||||
commitment: config.commitment.clone(),
|
||||
swqos_cores_from_end: config.swqos_cores_from_end,
|
||||
mev_protection: config.mev_protection,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,8 +58,9 @@ impl Hash for InfrastructureConfig {
|
||||
fn hash<H: Hasher>(&self, state: &mut H) {
|
||||
self.rpc_url.hash(state);
|
||||
self.swqos_configs.hash(state);
|
||||
// Hash commitment level as string since CommitmentConfig doesn't impl Hash
|
||||
format!("{:?}", self.commitment).hash(state);
|
||||
self.swqos_cores_from_end.hash(state);
|
||||
self.mev_protection.hash(state);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -57,11 +69,20 @@ impl PartialEq for InfrastructureConfig {
|
||||
self.rpc_url == other.rpc_url
|
||||
&& self.swqos_configs == other.swqos_configs
|
||||
&& self.commitment == other.commitment
|
||||
&& self.swqos_cores_from_end == other.swqos_cores_from_end
|
||||
&& self.mev_protection == other.mev_protection
|
||||
}
|
||||
}
|
||||
|
||||
impl Eq for InfrastructureConfig {}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct SwqosSubmitTiming {
|
||||
pub swqos_type: SwqosType,
|
||||
pub strategy_type: GasFeeStrategyType,
|
||||
pub submit_done_us: i64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TradeConfig {
|
||||
pub rpc_url: String,
|
||||
@@ -72,43 +93,143 @@ pub struct TradeConfig {
|
||||
pub create_wsol_ata_on_startup: bool,
|
||||
/// Whether to use seed optimization for all ATA operations (default: true)
|
||||
pub use_seed_optimize: bool,
|
||||
/// Whether to pin parallel submit tasks to CPU cores (can reduce latency; set false in containers). Default true.
|
||||
pub use_core_affinity: bool,
|
||||
/// Whether to output all SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default true.
|
||||
pub log_enabled: bool,
|
||||
/// Whether to check minimum tip per SWQOS provider (filter out configs below min). Default false to save latency.
|
||||
pub check_min_tip: bool,
|
||||
/// When true, SWQOS uses the *last* N cores (instead of the first N). Use when main thread / tokio use low-numbered cores to reduce CPU contention. Default false.
|
||||
pub swqos_cores_from_end: bool,
|
||||
/// Global MEV protection flag. When true, SWQOS providers that support MEV protection
|
||||
/// (Astralane QUIC `:9000` or Plain/Binary HTTP `mev-protect=true`, BlockRazor sandwichMitigation)
|
||||
/// use their MEV-protected endpoints/modes. Default false (no MEV protection, lower latency).
|
||||
pub mev_protection: bool,
|
||||
}
|
||||
|
||||
impl TradeConfig {
|
||||
/// Create a new TradeConfig using the builder pattern.
|
||||
///
|
||||
/// # Available builder methods
|
||||
/// - `.create_wsol_ata_on_startup(bool)` — check & create WSOL ATA on init (default: true)
|
||||
/// - `.use_seed_optimize(bool)` — seed optimization for ATA ops (default: true)
|
||||
/// - `.log_enabled(bool)` — SDK timing/SWQOS logs (default: true)
|
||||
/// - `.check_min_tip(bool)` — filter SWQOS below min tip (default: false)
|
||||
/// - `.swqos_cores_from_end(bool)` — bind SWQOS to last N cores (default: false)
|
||||
/// - `.mev_protection(bool)` — MEV protection for Astralane/BlockRazor (default: false)
|
||||
///
|
||||
/// # Example
|
||||
/// ```rust,ignore
|
||||
/// let config = TradeConfig::builder(rpc_url, swqos_configs, commitment)
|
||||
/// .mev_protection(true)
|
||||
/// .check_min_tip(true)
|
||||
/// .log_enabled(false)
|
||||
/// .build();
|
||||
/// ```
|
||||
pub fn builder(
|
||||
rpc_url: String,
|
||||
swqos_configs: Vec<SwqosConfig>,
|
||||
commitment: CommitmentConfig,
|
||||
) -> TradeConfigBuilder {
|
||||
TradeConfigBuilder::new(rpc_url, swqos_configs, commitment)
|
||||
}
|
||||
|
||||
/// Shortcut: create a TradeConfig with all defaults. Equivalent to `builder(...).build()`.
|
||||
pub fn new(
|
||||
rpc_url: String,
|
||||
swqos_configs: Vec<SwqosConfig>,
|
||||
commitment: CommitmentConfig,
|
||||
) -> Self {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
println!("🔧 TradeConfig create_wsol_ata_on_startup default: true");
|
||||
println!("🔧 TradeConfig use_seed_optimize default: true");
|
||||
}
|
||||
Self::builder(rpc_url, swqos_configs, commitment).build()
|
||||
}
|
||||
}
|
||||
|
||||
/// Builder for [`TradeConfig`]. Created via [`TradeConfig::builder`].
|
||||
///
|
||||
/// All fields are optional and pre-filled with sensible defaults.
|
||||
/// Call `.build()` to produce the final [`TradeConfig`].
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TradeConfigBuilder {
|
||||
rpc_url: String,
|
||||
swqos_configs: Vec<SwqosConfig>,
|
||||
commitment: CommitmentConfig,
|
||||
create_wsol_ata_on_startup: bool,
|
||||
use_seed_optimize: bool,
|
||||
log_enabled: bool,
|
||||
check_min_tip: bool,
|
||||
swqos_cores_from_end: bool,
|
||||
mev_protection: bool,
|
||||
}
|
||||
|
||||
impl TradeConfigBuilder {
|
||||
fn new(rpc_url: String, swqos_configs: Vec<SwqosConfig>, commitment: CommitmentConfig) -> Self {
|
||||
Self {
|
||||
rpc_url,
|
||||
swqos_configs,
|
||||
commitment,
|
||||
create_wsol_ata_on_startup: true, // default: check and create on startup
|
||||
use_seed_optimize: true, // default: use seed optimization
|
||||
use_core_affinity: true, // default: pin parallel submit tasks to cores
|
||||
log_enabled: true, // default: enable all SDK logs
|
||||
create_wsol_ata_on_startup: true,
|
||||
use_seed_optimize: true,
|
||||
log_enabled: true,
|
||||
check_min_tip: false,
|
||||
swqos_cores_from_end: false,
|
||||
mev_protection: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a TradeConfig with custom WSOL ATA settings
|
||||
pub fn with_wsol_ata_config(
|
||||
mut self,
|
||||
create_wsol_ata_on_startup: bool,
|
||||
use_seed_optimize: bool,
|
||||
) -> Self {
|
||||
self.create_wsol_ata_on_startup = create_wsol_ata_on_startup;
|
||||
self.use_seed_optimize = use_seed_optimize;
|
||||
/// Check and create WSOL ATA on SDK initialization. Default: `true`.
|
||||
pub fn create_wsol_ata_on_startup(mut self, v: bool) -> Self {
|
||||
self.create_wsol_ata_on_startup = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable seed optimization for all ATA operations. Default: `true`.
|
||||
pub fn use_seed_optimize(mut self, v: bool) -> Self {
|
||||
self.use_seed_optimize = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default: `true`.
|
||||
pub fn log_enabled(mut self, v: bool) -> Self {
|
||||
self.log_enabled = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Filter out SWQOS providers whose tip is below their minimum requirement.
|
||||
/// Adds a small check on the hot path; disable for lowest latency. Default: `false`.
|
||||
pub fn check_min_tip(mut self, v: bool) -> Self {
|
||||
self.check_min_tip = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Bind SWQOS sender threads to the *last* N CPU cores instead of the first N.
|
||||
/// Useful when main thread / tokio workers occupy low-numbered cores. Default: `false`.
|
||||
pub fn swqos_cores_from_end(mut self, v: bool) -> Self {
|
||||
self.swqos_cores_from_end = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Enable global MEV protection. When `true`:
|
||||
/// - **Astralane QUIC** uses port `9000`; **Astralane HTTP** adds `mev-protect=true`
|
||||
/// - **BlockRazor** uses `mode=sandwichMitigation` (skips blacklisted Leader slots)
|
||||
///
|
||||
/// May reduce landing speed. Default: `false`.
|
||||
pub fn mev_protection(mut self, v: bool) -> Self {
|
||||
self.mev_protection = v;
|
||||
self
|
||||
}
|
||||
|
||||
/// Consume the builder and produce a [`TradeConfig`].
|
||||
pub fn build(self) -> TradeConfig {
|
||||
TradeConfig {
|
||||
rpc_url: self.rpc_url,
|
||||
swqos_configs: self.swqos_configs,
|
||||
commitment: self.commitment,
|
||||
create_wsol_ata_on_startup: self.create_wsol_ata_on_startup,
|
||||
use_seed_optimize: self.use_seed_optimize,
|
||||
log_enabled: self.log_enabled,
|
||||
check_min_tip: self.check_min_tip,
|
||||
swqos_cores_from_end: self.swqos_cores_from_end,
|
||||
mev_protection: self.mev_protection,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub type SolanaRpcClient = solana_client::nonblocking::rpc_client::RpcClient;
|
||||
|
||||
@@ -43,8 +43,7 @@ pub const USD1_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
||||
};
|
||||
|
||||
// USDC (mainnet) mint and meta
|
||||
pub const USDC_TOKEN_ACCOUNT: Pubkey =
|
||||
pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
||||
pub const USDC_TOKEN_ACCOUNT: Pubkey = pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
||||
pub const USDC_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
||||
solana_sdk::instruction::AccountMeta {
|
||||
pubkey: USDC_TOKEN_ACCOUNT,
|
||||
@@ -58,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,
|
||||
};
|
||||
|
||||
+317
-65
@@ -1,7 +1,6 @@
|
||||
use solana_program::pubkey;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
|
||||
pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"),
|
||||
pubkey!("HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe"),
|
||||
@@ -13,6 +12,20 @@ pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("3AVi9Tg9Uo68tJfuvoKvqKNWKkC5wPdSSdeBnizKZ6jT"),
|
||||
];
|
||||
|
||||
/// Helius Sender tip accounts (fee recipient addresses).
|
||||
pub const HELIUS_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("4ACfpUFoaSD9bfPdeu6DBt89gB6ENTeHBXCAi87NhDEE"),
|
||||
pubkey!("D2L6yPZ2FmmmTKPgzaMKdhu6EWZcTpLy1Vhx8uvZe7NZ"),
|
||||
pubkey!("9bnz4RShgq1hAnLnZbP8kbgBg1kEmcJBYQq3gQbmnSta"),
|
||||
pubkey!("5VY91ws6B2hMmBFRsXkoAAdsPHBJwRfBht4DXox3xkwn"),
|
||||
pubkey!("2nyhqdwKcJZR2vcqCyrYsaPVdAnFoJjiksCXJ7hfEYgD"),
|
||||
pubkey!("2q5pghRs6arqVjRvT5gfgWfWcHWmw1ZuCzphgd5KfWGJ"),
|
||||
pubkey!("wyvPkWjVZz1M8fHQnMMCDTQDbkManefNNhweYk5WkcF"),
|
||||
pubkey!("3KCKozbAaF75qEU33jtzozcJ29yJuaLJTy2jFdzUY8bT"),
|
||||
pubkey!("4vieeGHPYPG2MmyPRcYjdiDmmhN3ww7hsFNap8pVN3Ey"),
|
||||
pubkey!("4TQLFNWK8AovT1gFvda5jfw2oJeRMKEmw7aH6MGBJ3or"),
|
||||
];
|
||||
|
||||
pub const NEXTBLOCK_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("NextbLoCkVtMGcV47JzewQdvBpLqT9TxQFozQkN98pE"),
|
||||
pubkey!("NexTbLoCkWykbLuB1NkjXgFWkX9oAtcoagQegygXXA2"),
|
||||
@@ -98,6 +111,7 @@ pub const BLOCKRAZOR_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("AP6qExwrbRgBAVaehg4b5xHENX815sMabtBzUzVB4v8S"),
|
||||
];
|
||||
|
||||
/// Astralane tip wallets. Extended with new addresses for improved routing and reduced write-lock contention (see portal.astralane.io/blockline).
|
||||
pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("astrazznxsGUhWShqgNtAdfrzP2G83DzcWVJDxwV9bF"),
|
||||
pubkey!("astra4uejePWneqNaJKuFFA8oonqCE1sqF6b45kDMZm"),
|
||||
@@ -107,6 +121,16 @@ pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("astraubkDw81n4LuutzSQ8uzHCv4BhPVhfvTcYv8SKC"),
|
||||
pubkey!("astraZW5GLFefxNPAatceHhYjfA1ciq9gvfEg2S47xk"),
|
||||
pubkey!("astrawVNP4xDBKT7rAdxrLYiTSTdqtUr63fSMduivXK"),
|
||||
// New tip wallets (2025) for improved performance and reduced write-lock delays
|
||||
pubkey!("AstrA1ejL4UeXC2SBP4cpeEmtcFPZVLxx3XGKXyCW6to"),
|
||||
pubkey!("AsTra79FET4aCKWspPqeSFvjJNyp96SvAnrmyAxqg5b7"),
|
||||
pubkey!("AstrABAu8CBTyuPXpV4eSCJ5fePEPnxN8NqBaPKQ9fHR"),
|
||||
pubkey!("AsTRADtvb6tTmrsqULQ9Wji9PigDMjhfEMza6zkynEvV"),
|
||||
pubkey!("AsTRAEoyMofR3vUPpf9k68Gsfb6ymTZttEtsAbv8Bk4d"),
|
||||
pubkey!("AStrAJv2RN2hKCHxwUMtqmSxgdcNZbihCwc1mCSnG83W"),
|
||||
pubkey!("Astran35aiQUF57XZsmkWMtNCtXGLzs8upfiqXxth2bz"),
|
||||
pubkey!("AStRAnpi6kFrKypragExgeRoJ1QnKH7pbSjLAKQVWUum"),
|
||||
pubkey!("ASTRaoF93eYt73TYvwtsv6fMWHWbGmMUZfVZPo3CRU9C"),
|
||||
];
|
||||
|
||||
pub const STELLIUM_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
@@ -128,6 +152,12 @@ pub const SOYAS_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("soyascXFW5wEEYiwfEmHy2pNwomqzvggJosGVD6TJdY"),
|
||||
pubkey!("soyasDBdKjADwPz3xk82U3TNPRDKEWJj7wWLajNHZ1L"),
|
||||
pubkey!("soyasE2abjBAynmHbGWgEwk4ctBy7JMTUCNrMbjcnyH"),
|
||||
pubkey!("soyasi59njacMUPvo3TM5paHjeK8pYSdovXgFi32gRt"),
|
||||
pubkey!("soyasQYhJxv8uZgWDxhg72td6piAf7XTkoyWHtSATEz"),
|
||||
pubkey!("soyastP66xyYC8XADXZjdMM5BAVGD2YRvz8dwtLsqb8"),
|
||||
pubkey!("soyasvdgUJWYcUCzDxpmjUnNjH7KamXLXTzLwFvdVPE"),
|
||||
pubkey!("soyasvxAunisNxaoRxkKGjNir7KmbwYnr37JmefkX9G"),
|
||||
pubkey!("soyas5doVFUwH8s5zK8gEvCL5KR5ogDmf52LsrJEZ9h"),
|
||||
];
|
||||
|
||||
pub const SPEEDLANDING_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
@@ -141,145 +171,293 @@ pub const SPEEDLANDING_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("speede8xCcUq2Tiv1efXeTuE3k9TDNq8TnGKaKSc6J4"),
|
||||
];
|
||||
|
||||
// NewYork,
|
||||
// Frankfurt,
|
||||
// Amsterdam,
|
||||
// SLC,
|
||||
// Tokyo,
|
||||
// London,
|
||||
// LosAngeles,
|
||||
// Default,
|
||||
pub const SOLAMI_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("15qWd4huAkoxvhDsHMfpUn27TW1YBYMMJJ2jkAkbeam"),
|
||||
pubkey!("9XuGciSwr5wb7dLTQm91JhuBTvj3GG8WjuRDc3obeam"),
|
||||
pubkey!("kiQioJNyFG7pU36ELLsRKXkeT48kFbk3b6rSgrWbeam"),
|
||||
pubkey!("kjmVhW1UzJrW2sU5bY5NtZ79jpvjSStsj37Pzmabeam"),
|
||||
pubkey!("kREnjPWFpt4AHeY5pijPmyXaCrMnbatUQJo7d3Xbeam"),
|
||||
pubkey!("praRZG6N6MdbsT4EFpKgZJWReZGXQhAMFcH68oCbeam"),
|
||||
pubkey!("SqoKQKU5uwBxovq3R7yEBxFwptc4z7vwoghU3M9beam"),
|
||||
pubkey!("sV72TY66T1RfmDSeHPPbwX6wwJ3bBv5hd4ehJ8tbeam"),
|
||||
pubkey!("swf8MyEeLo7gtRUo27UuJj6naCASUrypU7dbteSbeam"),
|
||||
pubkey!("uiuaQsxA47JybQAVN4FTfYuoEDkMiXV1r591Aewbeam"),
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_JITO: [&str; 8] = [
|
||||
"https://ny.mainnet.block-engine.jito.wtf",
|
||||
// `SwqosRegion` 与下列各 `SWQOS_ENDPOINTS_*` 下标严格对应(共 10 项):
|
||||
// 0 NewYork, 1 Frankfurt, 2 Amsterdam, 3 Dublin, 4 SLC, 5 Tokyo, 6 Singapore, 7 London, 8 LosAngeles, 9 Default。
|
||||
//
|
||||
// **地理就近(用户语义)**:当某枚举区域没有该服务商**独立公布**的 PoP 时,在**该服务商已出现的端点集合内**,按真实地理位置选**大圆距离最近**的一项作为填充;行尾注释说明依据。
|
||||
// **例外**:`SwqosRegion::Default`(下标 9)不表示地球上的点,表中为全局 URL 或文档默认枢纽,**不适用**地理就近,仅表示「未指定区域时的回退」。
|
||||
// 若某区域仅有一种「大区」级入口(例如全美只有一个美东 PoP),则地理上非最优但只能复用,注释会标明「受服务商可用区限制」。
|
||||
|
||||
/// Jito mainnet block engines (`https://<region>.mainnet.block-engine.jito.wtf`).
|
||||
/// There is no Los Angeles engine → use Salt Lake City for `LosAngeles`; `SwqosRegion::Default` uses the global mainnet URL.
|
||||
pub const SWQOS_ENDPOINTS_JITO: [&str; 10] = [
|
||||
"https://ny.mainnet.block-engine.jito.wtf",
|
||||
"https://frankfurt.mainnet.block-engine.jito.wtf",
|
||||
"https://amsterdam.mainnet.block-engine.jito.wtf",
|
||||
"https://dublin.mainnet.block-engine.jito.wtf",
|
||||
"https://slc.mainnet.block-engine.jito.wtf",
|
||||
"https://tokyo.mainnet.block-engine.jito.wtf",
|
||||
"https://singapore.mainnet.block-engine.jito.wtf",
|
||||
"https://london.mainnet.block-engine.jito.wtf",
|
||||
"https://ny.mainnet.block-engine.jito.wtf",
|
||||
"https://slc.mainnet.block-engine.jito.wtf", // LosAngeles: no LA PoP; nearest US-West is SLC
|
||||
"https://mainnet.block-engine.jito.wtf",
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_NEXTBLOCK: [&str; 8] = [
|
||||
/// NextBlock regional HTTP hosts (see provider docs). `SwqosRegion` order; no dedicated LA PoP → SLC as US-West fallback.
|
||||
pub const SWQOS_ENDPOINTS_NEXTBLOCK: [&str; 10] = [
|
||||
"http://ny.nextblock.io",
|
||||
"http://frankfurt.nextblock.io",
|
||||
"http://amsterdam.nextblock.io",
|
||||
"http://fra.nextblock.io",
|
||||
"http://ams.nextblock.io",
|
||||
"http://dublin.nextblock.io",
|
||||
"http://slc.nextblock.io",
|
||||
"http://tokyo.nextblock.io",
|
||||
"http://london.nextblock.io",
|
||||
"http://singapore.nextblock.io",
|
||||
"http://frankfurt.nextblock.io",
|
||||
"http://tokyo.nextblock.io",
|
||||
"http://sgp.nextblock.io",
|
||||
"http://london.nextblock.io",
|
||||
"http://slc.nextblock.io",
|
||||
"http://fra.nextblock.io", // Default: 非地理区域;服务商无「全局」主机名时用 EU 枢纽作未选区回退
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_ZERO_SLOT: [&str; 8] = [
|
||||
pub const SWQOS_ENDPOINTS_ZERO_SLOT: [&str; 10] = [
|
||||
"http://ny.0slot.trade",
|
||||
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
|
||||
"http://ams.0slot.trade",
|
||||
"http://ny.0slot.trade",
|
||||
"http://ams.0slot.trade", // Dublin: 无 IE 专用;在已公布 EU 点中选距爱尔兰最近的 ams(相对 de2 等)
|
||||
"http://la.0slot.trade", // SLC: no UT PoP; nearest US-West published host
|
||||
"http://jp.0slot.trade",
|
||||
"http://ams.0slot.trade",
|
||||
"http://jp.0slot.trade", // SG: 无本地 PoP;已公布 APAC 仅 jp,为表中离新加坡最近的大圆距离
|
||||
"http://ams.0slot.trade", // London: 无 UK 专用;已公布 EU 点中 ams 距伦敦最近之一
|
||||
"http://la.0slot.trade",
|
||||
"http://de2.0slot.trade", // Use de2 for TSW, and de1 for OVH
|
||||
"http://de2.0slot.trade", // Default: 非地理区域;EU 枢纽 de2 作未选区回退
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_TEMPORAL: [&str; 8] = [
|
||||
"http://ewr1.nozomi.temporal.xyz",
|
||||
/// Nozomi Direct regions: ewr1, fra2, ams1, lon1, lax1, tyo1, sgp1, …
|
||||
pub const SWQOS_ENDPOINTS_TEMPORAL: [&str; 10] = [
|
||||
"http://ewr1.nozomi.temporal.xyz", // NewYork → Newark
|
||||
"http://fra2.nozomi.temporal.xyz",
|
||||
"http://ams1.nozomi.temporal.xyz",
|
||||
"http://ewr1.nozomi.temporal.xyz",
|
||||
"http://lon1.nozomi.temporal.xyz", // Dublin: no IE host; UK nearest Direct PoP
|
||||
"http://lax1.nozomi.temporal.xyz", // SLC: US-West
|
||||
"http://tyo1.nozomi.temporal.xyz",
|
||||
"http://sgp1.nozomi.temporal.xyz",
|
||||
"http://pit1.nozomi.temporal.xyz",
|
||||
"http://fra2.nozomi.temporal.xyz",
|
||||
"http://lon1.nozomi.temporal.xyz",
|
||||
"http://lax1.nozomi.temporal.xyz",
|
||||
"http://fra2.nozomi.temporal.xyz", // Default: 非地理区域;EU Direct 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_BLOX: [&str; 8] = [
|
||||
pub const SWQOS_ENDPOINTS_BLOX: [&str; 10] = [
|
||||
"https://ny.solana.dex.blxrbdn.com",
|
||||
"https://germany.solana.dex.blxrbdn.com",
|
||||
"https://amsterdam.solana.dex.blxrbdn.com",
|
||||
"https://ny.solana.dex.blxrbdn.com",
|
||||
"https://uk.solana.dex.blxrbdn.com", // Dublin: IE/UK edge
|
||||
"https://la.solana.dex.blxrbdn.com", // SLC: no Mountain PoP; US-West LA
|
||||
"https://tokyo.solana.dex.blxrbdn.com",
|
||||
"https://tokyo.solana.dex.blxrbdn.com", // SG: 文档无 SGP 区域;已公布 APAC 仅 Tokyo,为距 SG 最近选项
|
||||
"https://uk.solana.dex.blxrbdn.com",
|
||||
"https://la.solana.dex.blxrbdn.com",
|
||||
"https://global.solana.dex.blxrbdn.com",
|
||||
"https://global.solana.dex.blxrbdn.com", // Default: 非地理区域;全球任播
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_NODE1: [&str; 8] = [
|
||||
pub const SWQOS_ENDPOINTS_NODE1: [&str; 10] = [
|
||||
"http://ny.node1.me",
|
||||
"http://fra.node1.me",
|
||||
"http://ams.node1.me",
|
||||
"http://ny.node1.me",
|
||||
"http://lon.node1.me", // Dublin: 已公布中英爱区域用 lon(地理上近爱尔兰)
|
||||
"http://ny.node1.me", // SLC: 已公布美国仅 ny;美西无 PoP,受可用区限制复用美东
|
||||
"http://tk.node1.me",
|
||||
"http://tk.node1.me", // SG: 已公布 APAC 仅 tk;地理上为表中离 SG 最近
|
||||
"http://lon.node1.me",
|
||||
"http://ny.node1.me",
|
||||
"http://fra.node1.me",
|
||||
"http://ny.node1.me", // LosAngeles: 同上,美国仅 ny 入口
|
||||
"http://fra.node1.me", // Default: 非地理区域;与 QUIC 对齐为 EU 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
||||
/// Node1 QUIC: port 16666. Region order matches [`SwqosRegion`].
|
||||
/// server_name = host part (e.g. ny.node1.me). Auth: first bi stream = 16-byte UUID; each tx = new bi stream, bincode body.
|
||||
pub const SWQOS_ENDPOINTS_NODE1_QUIC: [&str; 10] = [
|
||||
"ny.node1.me:16666",
|
||||
"fra.node1.me:16666",
|
||||
"ams.node1.me:16666",
|
||||
"lon.node1.me:16666",
|
||||
"ny.node1.me:16666",
|
||||
"tk.node1.me:16666",
|
||||
"tk.node1.me:16666",
|
||||
"lon.node1.me:16666",
|
||||
"ny.node1.me:16666",
|
||||
"fra.node1.me:16666", // Default: 非地理区域;与 HTTP 对齐为 EU 枢纽
|
||||
];
|
||||
|
||||
/// Published: ny, slc, ams, fra, singapore, london, tokyo (no IE/UK split → london for Dublin).
|
||||
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 10] = [
|
||||
"http://ny.flashblock.trade",
|
||||
"http://fra.flashblock.trade",
|
||||
"http://ams.flashblock.trade",
|
||||
"http://london.flashblock.trade", // Dublin: no IE host; UK nearest
|
||||
"http://slc.flashblock.trade",
|
||||
"http://tokyo.flashblock.trade",
|
||||
"http://singapore.flashblock.trade",
|
||||
"http://london.flashblock.trade",
|
||||
"http://ny.flashblock.trade",
|
||||
"http://ny.flashblock.trade",
|
||||
"http://slc.flashblock.trade",
|
||||
"http://fra.flashblock.trade", // Default: 非地理区域;EU 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 8] = [
|
||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://amsterdam.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://tokyo.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://newyork.solana.blockrazor.xyz:443/sendTransaction",
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/sendTransaction",
|
||||
/// BlockRazor Send Transaction v2: plain-text Base64 body, auth in URI, Content-Type: text/plain. Keep-alive: POST /v2/health.
|
||||
/// 若 HTTP 返回 500,可尝试 HTTPS:https://<region>.solana.blockrazor.io/v2/sendTransaction(Frankfurt/NewYork/Tokyo),通过 custom_url 覆盖。
|
||||
pub const SWQOS_ENDPOINTS_BLOCKRAZOR: [&str; 10] = [
|
||||
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://amsterdam.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://london.solana.blockrazor.xyz:443/v2/sendTransaction", // Dublin: UK nearest published
|
||||
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction", // SLC: 文档无美西;美国仅 NY,受可用区限制
|
||||
"http://tokyo.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://tokyo.solana.blockrazor.xyz:443/v2/sendTransaction", // SG: 已公布 APAC 仅 Tokyo,为距 SG 最近
|
||||
"http://london.solana.blockrazor.xyz:443/v2/sendTransaction",
|
||||
"http://newyork.solana.blockrazor.xyz:443/v2/sendTransaction", // LosAngeles: 无美西入口;美国仅 NY
|
||||
"http://frankfurt.solana.blockrazor.xyz:443/v2/sendTransaction", // Default: 非地理区域;EU 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE: [&str; 8] = [
|
||||
/// BlockRazor gRPC endpoints. Region order matches [`SwqosRegion`].
|
||||
/// Port 80 for gRPC protocol. Auth: apikey metadata in gRPC headers.
|
||||
pub const SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC: [&str; 10] = [
|
||||
"http://newyork.solana-grpc.blockrazor.xyz:80",
|
||||
"http://frankfurt.solana-grpc.blockrazor.xyz:80",
|
||||
"http://amsterdam.solana-grpc.blockrazor.xyz:80",
|
||||
"http://london.solana-grpc.blockrazor.xyz:80",
|
||||
"http://newyork.solana-grpc.blockrazor.xyz:80", // SLC: 与 HTTP 一致;美国仅 NY
|
||||
"http://tokyo.solana-grpc.blockrazor.xyz:80",
|
||||
"http://tokyo.solana-grpc.blockrazor.xyz:80",
|
||||
"http://london.solana-grpc.blockrazor.xyz:80",
|
||||
"http://newyork.solana-grpc.blockrazor.xyz:80", // LosAngeles: 与 HTTP 一致
|
||||
"http://frankfurt.solana-grpc.blockrazor.xyz:80", // Default: 非地理区域
|
||||
];
|
||||
|
||||
/// Plain HTTP API path (`/iris?api-key=…&method=…`).
|
||||
pub const ASTRALANE_PATH_IRIS: &str = "iris";
|
||||
/// Binary HTTP API path (`/irisb?api-key=…&method=sendTransaction`, raw bincode body).
|
||||
pub const ASTRALANE_PATH_IRISB: &str = "irisb";
|
||||
|
||||
/// Astralane **Plain** HTTP gateways (`/iris`). Pair with [`ASTRALANE_PATH_IRIS`].
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE_PLAIN: [&str; 10] = [
|
||||
"http://ny.gateway.astralane.io/iris",
|
||||
"http://fr.gateway.astralane.io/iris",
|
||||
"http://ams.gateway.astralane.io/iris",
|
||||
"http://ny.gateway.astralane.io/iris",
|
||||
"http://ams.gateway.astralane.io/iris", // Dublin: 无 IE 专用;在已公布 EU 点中选距爱尔兰最近的 ams
|
||||
"http://la.gateway.astralane.io/iris",
|
||||
"http://jp.gateway.astralane.io/iris",
|
||||
"http://ny.gateway.astralane.io/iris",
|
||||
"http://lax.gateway.astralane.io/iris",
|
||||
"http://lim.gateway.astralane.io/iris",
|
||||
"http://sg.gateway.astralane.io/iris",
|
||||
"http://ams.gateway.astralane.io/iris", // London: 无 UK 专用;在已公布 EU 点中选距英国最近的 ams
|
||||
"http://la.gateway.astralane.io/iris",
|
||||
"https://edge.astralane.io/iris", // Default: 非地理区域;全局任播边缘
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
|
||||
/// Astralane **Binary** HTTP gateways (`/irisb`). Pair with [`ASTRALANE_PATH_IRISB`].
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE_BINARY: [&str; 10] = [
|
||||
"http://ny.gateway.astralane.io/irisb",
|
||||
"http://fr.gateway.astralane.io/irisb",
|
||||
"http://ams.gateway.astralane.io/irisb",
|
||||
"http://ams.gateway.astralane.io/irisb", // Dublin: 同 Plain
|
||||
"http://la.gateway.astralane.io/irisb",
|
||||
"http://jp.gateway.astralane.io/irisb",
|
||||
"http://sg.gateway.astralane.io/irisb",
|
||||
"http://ams.gateway.astralane.io/irisb", // London: 同 Plain
|
||||
"http://la.gateway.astralane.io/irisb",
|
||||
"https://edge.astralane.io/irisb", // Default: 同 Plain
|
||||
];
|
||||
|
||||
/// Astralane QUIC endpoints (port 7000). Region order matches [`SwqosRegion`].
|
||||
/// See: https://github.com/Astralane/astralane-quic-client.
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 10] = [
|
||||
"ny.gateway.astralane.io:7000",
|
||||
"fr.gateway.astralane.io:7000",
|
||||
"ams.gateway.astralane.io:7000",
|
||||
"ams.gateway.astralane.io:7000", // Dublin: 同 HTTP
|
||||
"la.gateway.astralane.io:7000", // SLC: 美西 la 为最近已公布美区入口
|
||||
"jp.gateway.astralane.io:7000",
|
||||
"sg.gateway.astralane.io:7000",
|
||||
"ams.gateway.astralane.io:7000", // London: 同 HTTP
|
||||
"la.gateway.astralane.io:7000",
|
||||
"lim.gateway.astralane.io:7000", // Default: 非地理区域;全局边缘
|
||||
];
|
||||
|
||||
/// Astralane QUIC MEV-protected endpoints (port 9000). Same region order as SWQOS_ENDPOINTS_ASTRALANE_QUIC.
|
||||
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV: [&str; 10] = [
|
||||
"ny.gateway.astralane.io:9000",
|
||||
"fr.gateway.astralane.io:9000",
|
||||
"ams.gateway.astralane.io:9000",
|
||||
"ams.gateway.astralane.io:9000",
|
||||
"la.gateway.astralane.io:9000",
|
||||
"jp.gateway.astralane.io:9000",
|
||||
"sg.gateway.astralane.io:9000",
|
||||
"ams.gateway.astralane.io:9000",
|
||||
"la.gateway.astralane.io:9000",
|
||||
"lim.gateway.astralane.io:9000",
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 10] = [
|
||||
"http://ewr1.flashrpc.com",
|
||||
"http://fra1.flashrpc.com",
|
||||
"http://ams1.flashrpc.com",
|
||||
"http://ewr1.flashrpc.com",
|
||||
"http://lhr1.flashrpc.com", // Dublin: 已公布 UK 用 lhr;地理上近爱尔兰
|
||||
"http://ewr1.flashrpc.com", // SLC: 已公布美国仅 ewr;无美西 PoP,受可用区限制
|
||||
"http://tyo1.flashrpc.com",
|
||||
"http://tyo1.flashrpc.com", // SG: 表中无 SGP;APAC 仅 tyo,为距 SG 最近
|
||||
"http://lhr1.flashrpc.com",
|
||||
"http://ewr1.flashrpc.com",
|
||||
"http://fra1.flashrpc.com",
|
||||
"http://ewr1.flashrpc.com", // LosAngeles: 同上,美国仅 ewr
|
||||
"http://fra1.flashrpc.com", // Default: 非地理区域;EU 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_SOYAS: [&str; 8] = [
|
||||
pub const SWQOS_ENDPOINTS_SOYAS: [&str; 10] = [
|
||||
"nyc.landing.soyas.xyz:9000",
|
||||
"fra.landing.soyas.xyz:9000",
|
||||
"ams.landing.soyas.xyz:9000",
|
||||
"nyc.landing.soyas.xyz:9000",
|
||||
"lon.landing.soyas.xyz:9000", // Dublin: 已公布用 lon;地理近爱尔兰
|
||||
"nyc.landing.soyas.xyz:9000", // SLC: 已公布美国仅 nyc;无美西
|
||||
"tyo.landing.soyas.xyz:9000",
|
||||
"tyo.landing.soyas.xyz:9000", // SG: 表中 APAC 仅 tyo
|
||||
"lon.landing.soyas.xyz:9000",
|
||||
"nyc.landing.soyas.xyz:9000",
|
||||
"fra.landing.soyas.xyz:9000",
|
||||
"nyc.landing.soyas.xyz:9000", // LosAngeles: 同上
|
||||
"fra.landing.soyas.xyz:9000", // Default: 非地理区域;EU 枢纽
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_SPEEDLANDING: [&str; 8] = [
|
||||
pub const SWQOS_ENDPOINTS_SPEEDLANDING: [&str; 10] = [
|
||||
"nyc.speedlanding.trade:17778",
|
||||
"fra.speedlanding.trade:17778",
|
||||
"ams.speedlanding.trade:17778",
|
||||
"nyc.speedlanding.trade:17778",
|
||||
"ams.speedlanding.trade:17778", // Dublin: 已公布 EU 点中 ams 地理近爱尔兰
|
||||
"nyc.speedlanding.trade:17778", // SLC: 表中美国仅 nyc;无美西 PoP,受可用区限制
|
||||
"tyo.speedlanding.trade:17778",
|
||||
"fra.speedlanding.trade:17778",
|
||||
"nyc.speedlanding.trade:17778",
|
||||
"fra.speedlanding.trade:17778",
|
||||
"sgp.speedlanding.trade:17778",
|
||||
"ams.speedlanding.trade:17778", // London: 已公布 EU 中 ams 距英国最近之一
|
||||
"nyc.speedlanding.trade:17778", // LosAngeles: 同上,美国仅 nyc
|
||||
"fra.speedlanding.trade:17778", // Default: 非地理区域;EU 枢纽
|
||||
];
|
||||
|
||||
/// Helius Sender: POST /fast, dual routing to validators and Jito. API key optional (custom TPS only).
|
||||
pub const SWQOS_ENDPOINTS_HELIUS: [&str; 10] = [
|
||||
"http://ewr-sender.helius-rpc.com/fast",
|
||||
"http://fra-sender.helius-rpc.com/fast",
|
||||
"http://ams-sender.helius-rpc.com/fast",
|
||||
"http://lon-sender.helius-rpc.com/fast", // Dublin: IE → UK/EU routing
|
||||
"http://slc-sender.helius-rpc.com/fast",
|
||||
"http://tyo-sender.helius-rpc.com/fast",
|
||||
"http://sg-sender.helius-rpc.com/fast",
|
||||
"http://lon-sender.helius-rpc.com/fast",
|
||||
"http://slc-sender.helius-rpc.com/fast",
|
||||
"https://sender.helius-rpc.com/fast", // Default: 非地理区域;全局 Sender
|
||||
];
|
||||
|
||||
pub const SWQOS_ENDPOINTS_SOLAMI: [&str; 10] = [
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
"beam.solami.dev:11000",
|
||||
];
|
||||
|
||||
pub const SWQOS_MIN_TIP_DEFAULT: f64 = 0.00001; // 其它SWQOS默认最低小费
|
||||
@@ -296,3 +474,77 @@ pub const SWQOS_MIN_TIP_STELLIUM: f64 = 0.0001; // Stellium requires minimum 0.0
|
||||
pub const SWQOS_MIN_TIP_LIGHTSPEED: f64 = 0.0001; // Lightspeed requires minimum 0.001 SOL tip
|
||||
pub const SWQOS_MIN_TIP_SOYAS: f64 = 0.001; // Soyas requires minimum 0.001 SOL tip
|
||||
pub const SWQOS_MIN_TIP_SPEEDLANDING: f64 = 0.001; // Speedlanding requires minimum 0.001 SOL tip
|
||||
/// Helius Sender: 0.0002 SOL when not swqos_only; use SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY when swqos_only=true.
|
||||
pub const SWQOS_MIN_TIP_HELIUS: f64 = 0.0002;
|
||||
pub const SWQOS_MIN_TIP_SOLAMI: f64 = 0.0001;
|
||||
/// Helius Sender with swqos_only: minimum 0.000005 SOL (much lower tip allowed).
|
||||
pub const SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY: f64 = 0.000005;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const SWQOS_REGION_ENDPOINT_TABLES: &[&[&str]] = &[
|
||||
&SWQOS_ENDPOINTS_JITO,
|
||||
&SWQOS_ENDPOINTS_NEXTBLOCK,
|
||||
&SWQOS_ENDPOINTS_ZERO_SLOT,
|
||||
&SWQOS_ENDPOINTS_TEMPORAL,
|
||||
&SWQOS_ENDPOINTS_BLOX,
|
||||
&SWQOS_ENDPOINTS_NODE1,
|
||||
&SWQOS_ENDPOINTS_NODE1_QUIC,
|
||||
&SWQOS_ENDPOINTS_FLASHBLOCK,
|
||||
&SWQOS_ENDPOINTS_BLOCKRAZOR,
|
||||
&SWQOS_ENDPOINTS_BLOCKRAZOR_GRPC,
|
||||
&SWQOS_ENDPOINTS_ASTRALANE_PLAIN,
|
||||
&SWQOS_ENDPOINTS_ASTRALANE_BINARY,
|
||||
&SWQOS_ENDPOINTS_ASTRALANE_QUIC,
|
||||
&SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV,
|
||||
&SWQOS_ENDPOINTS_STELLIUM,
|
||||
&SWQOS_ENDPOINTS_SOYAS,
|
||||
&SWQOS_ENDPOINTS_SPEEDLANDING,
|
||||
&SWQOS_ENDPOINTS_HELIUS,
|
||||
&SWQOS_ENDPOINTS_SOLAMI,
|
||||
];
|
||||
|
||||
#[test]
|
||||
fn all_swqos_endpoint_tables_align_with_swqos_region() {
|
||||
const EXPECT: usize = 10;
|
||||
for (idx, table) in SWQOS_REGION_ENDPOINT_TABLES.iter().enumerate() {
|
||||
assert_eq!(
|
||||
table.len(),
|
||||
EXPECT,
|
||||
"SWQOS endpoint table index {} length must match SwqosRegion (10 variants)",
|
||||
idx
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astralane_quic_hosts_match_mev_row_by_row() {
|
||||
for i in 0..10 {
|
||||
let base = SWQOS_ENDPOINTS_ASTRALANE_QUIC[i].trim_end_matches(":7000");
|
||||
let mev = SWQOS_ENDPOINTS_ASTRALANE_QUIC_MEV[i].trim_end_matches(":9000");
|
||||
assert_eq!(base, mev, "Astralane QUIC vs MEV host mismatch at index {}", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn node1_http_host_matches_quic_without_port() {
|
||||
for i in 0..10 {
|
||||
let http_host =
|
||||
SWQOS_ENDPOINTS_NODE1[i].strip_prefix("http://").expect("NODE1 HTTP URL");
|
||||
let quic_host =
|
||||
SWQOS_ENDPOINTS_NODE1_QUIC[i].strip_suffix(":16666").expect("NODE1 QUIC endpoint");
|
||||
assert_eq!(http_host, quic_host, "Node1 HTTP vs QUIC host mismatch at index {}", i);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn astralane_plain_and_binary_same_origin_per_region() {
|
||||
for i in 0..10 {
|
||||
let plain = SWQOS_ENDPOINTS_ASTRALANE_PLAIN[i].trim_end_matches("/iris");
|
||||
let binary = SWQOS_ENDPOINTS_ASTRALANE_BINARY[i].trim_end_matches("/irisb");
|
||||
assert_eq!(plain, binary, "Astralane Plain vs Binary base URL mismatch at index {}", i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,4 +6,4 @@ pub mod trade {
|
||||
pub const DEFAULT_SELL_TIP_FEE: f64 = 0.0001;
|
||||
pub const DEFAULT_RPC_UNIT_LIMIT: u32 = 150000;
|
||||
pub const DEFAULT_RPC_UNIT_PRICE: u64 = 500000;
|
||||
}
|
||||
}
|
||||
|
||||
+178
-68
@@ -1,15 +1,18 @@
|
||||
use crate::{
|
||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||
instruction::utils::bonk::{
|
||||
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
|
||||
SELL_EXECT_IN_DISCRIMINATOR,
|
||||
},
|
||||
trading::{
|
||||
common::utils::get_token_balance,
|
||||
core::{
|
||||
params::{BonkParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
instruction::{
|
||||
token_account_setup::{
|
||||
push_close_wsol_if_needed, push_create_or_wrap_user_token_account,
|
||||
push_create_user_token_account,
|
||||
},
|
||||
utils::bonk::{
|
||||
accounts, get_pool_pda, get_vault_pda, BUY_EXECT_IN_DISCRIMINATOR,
|
||||
BUY_EXECT_OUT_DISCRIMINATOR, SELL_EXECT_IN_DISCRIMINATOR, SELL_EXECT_OUT_DISCRIMINATOR,
|
||||
},
|
||||
},
|
||||
trading::core::{
|
||||
params::{BonkParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
},
|
||||
utils::calc::bonk::{
|
||||
get_buy_token_amount_from_sol_amount, get_sell_sol_amount_from_token_amount,
|
||||
@@ -58,6 +61,11 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
accounts::GLOBAL_CONFIG_META
|
||||
};
|
||||
|
||||
let quote_mint = if usd1_pool {
|
||||
crate::constants::USD1_TOKEN_ACCOUNT
|
||||
} else {
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
};
|
||||
let quote_token_mint = if usd1_pool {
|
||||
crate::constants::USD1_TOKEN_ACCOUNT_META
|
||||
} else {
|
||||
@@ -91,11 +99,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
let user_quote_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if usd1_pool {
|
||||
&crate::constants::USD1_TOKEN_ACCOUNT
|
||||
} else {
|
||||
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
},
|
||||
"e_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
@@ -106,11 +110,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
protocol_params.base_vault
|
||||
};
|
||||
let quote_vault_account = if protocol_params.quote_vault == Pubkey::default() {
|
||||
if usd1_pool {
|
||||
get_vault_pda(&pool_state, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
||||
} else {
|
||||
get_vault_pda(&pool_state, &crate::constants::WSOL_TOKEN_ACCOUNT).unwrap()
|
||||
}
|
||||
get_vault_pda(&pool_state, "e_mint).unwrap()
|
||||
} else {
|
||||
protocol_params.quote_vault
|
||||
};
|
||||
@@ -120,9 +120,15 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(6);
|
||||
|
||||
if params.create_input_mint_ata && !usd1_pool {
|
||||
instructions
|
||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), amount_in));
|
||||
if params.create_input_mint_ata {
|
||||
push_create_or_wrap_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
"e_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
amount_in,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
@@ -138,12 +144,18 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
}
|
||||
|
||||
let mut data = [0u8; 32];
|
||||
data[..8].copy_from_slice(&BUY_EXECT_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..8].copy_from_slice(&BUY_EXECT_OUT_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_out.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount_in.to_le_bytes());
|
||||
} else {
|
||||
data[..8].copy_from_slice(&BUY_EXECT_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
data[24..32].copy_from_slice(&share_fee_rate.to_le_bytes());
|
||||
|
||||
let accounts: [AccountMeta; 18] = [
|
||||
let accounts: [AccountMeta; 15] = [
|
||||
AccountMeta::new(params.payer.pubkey(), true), // Payer (signer)
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
global_config, // Global Config (readonly)
|
||||
@@ -159,15 +171,12 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
crate::constants::TOKEN_PROGRAM_META, // Quote Token Program (readonly)
|
||||
accounts::EVENT_AUTHORITY_META, // Event Authority (readonly)
|
||||
accounts::BONK_META, // Program (readonly)
|
||||
crate::constants::SYSTEM_PROGRAM_META, // System Program (readonly)
|
||||
AccountMeta::new(protocol_params.platform_associated_account, false), // Platform Associated Account
|
||||
AccountMeta::new(protocol_params.creator_associated_account, false), // Creator Associated Account
|
||||
];
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(accounts::BONK, &data, accounts.to_vec()));
|
||||
|
||||
if params.close_input_mint_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), "e_mint);
|
||||
}
|
||||
|
||||
Ok(instructions)
|
||||
@@ -177,9 +186,10 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
// ========================================
|
||||
// Parameter validation and basic data preparation
|
||||
// ========================================
|
||||
if params.rpc.is_none() {
|
||||
return Err(anyhow!("RPC is not set"));
|
||||
}
|
||||
let amount = params
|
||||
.input_amount
|
||||
.filter(|&a| a > 0)
|
||||
.ok_or_else(|| anyhow!("Bonk sell requires input_amount (token amount to sell); fetch balance via RPC before calling build_sell"))?;
|
||||
|
||||
let protocol_params = params
|
||||
.protocol_params
|
||||
@@ -189,20 +199,6 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
|
||||
let usd1_pool = protocol_params.global_config == accounts::USD1_GLOBAL_CONFIG;
|
||||
|
||||
let rpc = params.rpc.as_ref().unwrap().clone();
|
||||
|
||||
let mut amount = params.input_amount;
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
let balance_u64 =
|
||||
get_token_balance(rpc.as_ref(), ¶ms.payer.pubkey(), ¶ms.input_mint).await?;
|
||||
amount = Some(balance_u64);
|
||||
}
|
||||
let amount = amount.unwrap_or(0);
|
||||
|
||||
if amount == 0 {
|
||||
return Err(anyhow!("Amount cannot be zero"));
|
||||
}
|
||||
|
||||
let pool_state = if protocol_params.pool_state == Pubkey::default() {
|
||||
if usd1_pool {
|
||||
get_pool_pda(¶ms.input_mint, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
||||
@@ -219,6 +215,11 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
accounts::GLOBAL_CONFIG_META
|
||||
};
|
||||
|
||||
let quote_mint = if usd1_pool {
|
||||
crate::constants::USD1_TOKEN_ACCOUNT
|
||||
} else {
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
};
|
||||
let quote_token_mint = if usd1_pool {
|
||||
crate::constants::USD1_TOKEN_ACCOUNT_META
|
||||
} else {
|
||||
@@ -251,11 +252,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
let user_quote_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if usd1_pool {
|
||||
&crate::constants::USD1_TOKEN_ACCOUNT
|
||||
} else {
|
||||
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
},
|
||||
"e_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
@@ -266,11 +263,7 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
protocol_params.base_vault
|
||||
};
|
||||
let quote_vault_account = if protocol_params.quote_vault == Pubkey::default() {
|
||||
if usd1_pool {
|
||||
get_vault_pda(&pool_state, &crate::constants::USD1_TOKEN_ACCOUNT).unwrap()
|
||||
} else {
|
||||
get_vault_pda(&pool_state, &crate::constants::WSOL_TOKEN_ACCOUNT).unwrap()
|
||||
}
|
||||
get_vault_pda(&pool_state, "e_mint).unwrap()
|
||||
} else {
|
||||
protocol_params.quote_vault
|
||||
};
|
||||
@@ -278,19 +271,31 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
// ========================================
|
||||
// Build instructions
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(3);
|
||||
let mut instructions = Vec::with_capacity(4);
|
||||
|
||||
if params.close_output_mint_ata && !usd1_pool {
|
||||
instructions.extend(crate::trading::common::create_wsol_ata(¶ms.payer.pubkey()));
|
||||
if params.create_output_mint_ata {
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
"e_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
let mut data = [0u8; 32];
|
||||
data[..8].copy_from_slice(&SELL_EXECT_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..8].copy_from_slice(&SELL_EXECT_OUT_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_out.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount.to_le_bytes());
|
||||
} else {
|
||||
data[..8].copy_from_slice(&SELL_EXECT_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
data[24..32].copy_from_slice(&share_fee_rate.to_le_bytes());
|
||||
|
||||
let accounts: [AccountMeta; 18] = [
|
||||
let accounts: [AccountMeta; 15] = [
|
||||
AccountMeta::new(params.payer.pubkey(), true), // Payer (signer)
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
global_config, // Global Config (readonly)
|
||||
@@ -306,15 +311,12 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
crate::constants::TOKEN_PROGRAM_META, // Quote Token Program (readonly)
|
||||
accounts::EVENT_AUTHORITY_META, // Event Authority (readonly)
|
||||
accounts::BONK_META, // Program (readonly)
|
||||
crate::constants::SYSTEM_PROGRAM_META, // System Program (readonly)
|
||||
AccountMeta::new(protocol_params.platform_associated_account, false), // Platform Associated Account
|
||||
AccountMeta::new(protocol_params.creator_associated_account, false), // Creator Associated Account
|
||||
];
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(accounts::BONK, &data, accounts.to_vec()));
|
||||
|
||||
if params.close_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), "e_mint);
|
||||
}
|
||||
if params.close_input_mint_ata {
|
||||
instructions.push(crate::common::spl_token::close_account(
|
||||
@@ -329,3 +331,111 @@ impl InstructionBuilder for BonkInstructionBuilder {
|
||||
Ok(instructions)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{common::GasFeeStrategy, swqos::TradeType, trading::core::params::DexParamEnum};
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn pk(seed: u8) -> Pubkey {
|
||||
Pubkey::new_from_array([seed; 32])
|
||||
}
|
||||
|
||||
fn bonk_params() -> BonkParams {
|
||||
BonkParams {
|
||||
mint_token_program: crate::constants::TOKEN_PROGRAM,
|
||||
platform_config: pk(8),
|
||||
platform_associated_account: pk(9),
|
||||
creator_associated_account: pk(10),
|
||||
global_config: accounts::GLOBAL_CONFIG,
|
||||
..Default::default()
|
||||
}
|
||||
}
|
||||
|
||||
fn swap_params(trade_type: TradeType) -> SwapParams {
|
||||
SwapParams {
|
||||
rpc: None,
|
||||
payer: Arc::new(Keypair::new()),
|
||||
trade_type,
|
||||
input_mint: pk(3),
|
||||
input_token_program: None,
|
||||
output_mint: pk(3),
|
||||
output_token_program: None,
|
||||
input_amount: Some(100_000),
|
||||
slippage_basis_points: Some(100),
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
recent_blockhash: None,
|
||||
wait_tx_confirmed: false,
|
||||
protocol_params: DexParamEnum::Bonk(bonk_params()),
|
||||
open_seed_optimize: true,
|
||||
swqos_clients: Arc::new(Vec::new()),
|
||||
middleware_manager: None,
|
||||
durable_nonce: None,
|
||||
with_tip: false,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: false,
|
||||
create_output_mint_ata: false,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount: Some(42),
|
||||
gas_fee_strategy: GasFeeStrategy::new(),
|
||||
simulate: true,
|
||||
log_enabled: false,
|
||||
wait_for_all_submits: false,
|
||||
use_dedicated_sender_threads: false,
|
||||
sender_thread_cores: None,
|
||||
max_sender_concurrency: 0,
|
||||
effective_core_ids: Arc::new(Vec::new()),
|
||||
check_min_tip: false,
|
||||
grpc_recv_us: None,
|
||||
use_exact_sol_amount: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bonk_buy_uses_exact_out_when_fixed_output_is_set() {
|
||||
let instructions = BonkInstructionBuilder
|
||||
.build_buy_instructions(&swap_params(TradeType::Buy))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 15);
|
||||
assert_eq!(ix.accounts[14].pubkey, accounts::BONK);
|
||||
assert_eq!(&ix.data[..8], BUY_EXECT_OUT_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 42);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 100_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bonk_sell_uses_exact_out_when_fixed_output_is_set() {
|
||||
let instructions = BonkInstructionBuilder
|
||||
.build_sell_instructions(&swap_params(TradeType::Sell))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 15);
|
||||
assert_eq!(ix.accounts[14].pubkey, accounts::BONK);
|
||||
assert_eq!(&ix.data[..8], SELL_EXECT_OUT_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 42);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 100_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bonk_usd1_buy_create_input_builds_usd1_ata_not_wsol_wrap() {
|
||||
let mut params = swap_params(TradeType::Buy);
|
||||
if let DexParamEnum::Bonk(protocol_params) = &mut params.protocol_params {
|
||||
protocol_params.global_config = accounts::USD1_GLOBAL_CONFIG;
|
||||
}
|
||||
params.create_input_mint_ata = true;
|
||||
params.open_seed_optimize = false;
|
||||
|
||||
let instructions = BonkInstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let create_ix = instructions.first().unwrap();
|
||||
|
||||
assert_eq!(create_ix.program_id, crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID);
|
||||
assert_eq!(create_ix.accounts[3].pubkey, crate::constants::USD1_TOKEN_ACCOUNT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,14 @@
|
||||
use crate::{
|
||||
instruction::utils::meteora_damm_v2::{accounts, get_event_authority_pda, SWAP_DISCRIMINATOR},
|
||||
instruction::{
|
||||
token_account_setup::{
|
||||
push_close_wsol_if_needed, push_create_or_wrap_user_token_account,
|
||||
push_create_user_token_account,
|
||||
},
|
||||
utils::meteora_damm_v2::{
|
||||
accounts, get_event_authority_pda, SWAP2_DISCRIMINATOR, SWAP_MODE_EXACT_IN,
|
||||
SWAP_MODE_EXACT_OUT, SWAP_MODE_PARTIAL_FILL,
|
||||
},
|
||||
},
|
||||
trading::core::{
|
||||
params::{MeteoraDammV2Params, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
@@ -27,10 +36,12 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<MeteoraDammV2Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
||||
|
||||
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
if !is_wsol && !is_usdc {
|
||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||
}
|
||||
@@ -38,33 +49,45 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
// ========================================
|
||||
// Trade calculation and account address preparation
|
||||
// ========================================
|
||||
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let input_mint =
|
||||
if is_a_in { protocol_params.token_a_mint } else { protocol_params.token_b_mint };
|
||||
let input_token_program =
|
||||
if is_a_in { protocol_params.token_a_program } else { protocol_params.token_b_program };
|
||||
let output_mint =
|
||||
if is_a_in { protocol_params.token_b_mint } else { protocol_params.token_a_mint };
|
||||
let output_token_program =
|
||||
if is_a_in { protocol_params.token_b_program } else { protocol_params.token_a_program };
|
||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
||||
let (amount_0, amount_1) = match protocol_params.swap_mode {
|
||||
SWAP_MODE_EXACT_OUT => {
|
||||
let amount_out = params.fixed_output_amount.ok_or_else(|| {
|
||||
anyhow!("fixed_output_amount must be set for MeteoraDammV2 exact-out swap2")
|
||||
})?;
|
||||
(amount_out, amount_in)
|
||||
}
|
||||
SWAP_MODE_EXACT_IN | SWAP_MODE_PARTIAL_FILL => {
|
||||
let minimum_amount_out = params.fixed_output_amount.ok_or_else(|| {
|
||||
anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap2 min output")
|
||||
})?;
|
||||
(amount_in, minimum_amount_out)
|
||||
}
|
||||
mode => return Err(anyhow!("Unsupported MeteoraDammV2 swap_mode {}", mode)),
|
||||
};
|
||||
|
||||
let input_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.input_mint,
|
||||
if is_a_in {
|
||||
&protocol_params.token_a_program
|
||||
} else {
|
||||
&protocol_params.token_b_program
|
||||
},
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let output_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
if is_a_in {
|
||||
&protocol_params.token_b_program
|
||||
} else {
|
||||
&protocol_params.token_a_program
|
||||
},
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
@@ -74,24 +97,32 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
let mut instructions = Vec::with_capacity(6);
|
||||
|
||||
if params.create_input_mint_ata {
|
||||
instructions
|
||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), amount_in));
|
||||
push_create_or_wrap_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
amount_in,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(
|
||||
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
),
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create buy instruction
|
||||
let accounts: [AccountMeta; 14] = [
|
||||
let mut account_metas = Vec::with_capacity(
|
||||
13 + usize::from(protocol_params.referral_token_account.is_some())
|
||||
+ usize::from(protocol_params.include_rate_limiter_sysvar),
|
||||
);
|
||||
account_metas.extend([
|
||||
accounts::AUTHORITY_META, // Pool Authority (readonly)
|
||||
AccountMeta::new(protocol_params.pool, false), // Pool
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
@@ -103,25 +134,32 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
AccountMeta::new(params.payer.pubkey(), true), // User Transfer Authority
|
||||
AccountMeta::new_readonly(protocol_params.token_a_program, false), // Token Program (readonly)
|
||||
AccountMeta::new_readonly(protocol_params.token_b_program, false), // Token Program (readonly)
|
||||
accounts::METEORA_DAMM_V2_META, // Referral Token Account (readonly)
|
||||
]);
|
||||
if let Some(referral_token_account) = protocol_params.referral_token_account {
|
||||
account_metas.push(AccountMeta::new(referral_token_account, false));
|
||||
}
|
||||
account_metas.extend([
|
||||
AccountMeta::new_readonly(get_event_authority_pda(), false), // Event Authority (readonly)
|
||||
accounts::METEORA_DAMM_V2_META, // Program (readonly)
|
||||
];
|
||||
]);
|
||||
if protocol_params.include_rate_limiter_sysvar {
|
||||
account_metas.push(accounts::SYSVAR_INSTRUCTIONS_META);
|
||||
}
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
data[..8].copy_from_slice(&SWAP_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
let mut data = [0u8; 25];
|
||||
data[..8].copy_from_slice(&SWAP2_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_0.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount_1.to_le_bytes());
|
||||
data[24] = protocol_params.swap_mode;
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::METEORA_DAMM_V2,
|
||||
&data,
|
||||
accounts.to_vec(),
|
||||
account_metas,
|
||||
));
|
||||
|
||||
if params.close_input_mint_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &input_mint);
|
||||
}
|
||||
|
||||
Ok(instructions)
|
||||
@@ -135,14 +173,16 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<MeteoraDammV2Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
||||
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
return Err(anyhow!("Token amount is not set"));
|
||||
}
|
||||
|
||||
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
if !is_wsol && !is_usdc {
|
||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||
}
|
||||
@@ -150,46 +190,69 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
// ========================================
|
||||
// Trade calculation and account address preparation
|
||||
// ========================================
|
||||
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
||||
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let input_mint =
|
||||
if is_a_in { protocol_params.token_a_mint } else { protocol_params.token_b_mint };
|
||||
let input_token_program =
|
||||
if is_a_in { protocol_params.token_a_program } else { protocol_params.token_b_program };
|
||||
let output_mint =
|
||||
if is_a_in { protocol_params.token_b_mint } else { protocol_params.token_a_mint };
|
||||
let output_token_program =
|
||||
if is_a_in { protocol_params.token_b_program } else { protocol_params.token_a_program };
|
||||
let amount_in = params.input_amount.unwrap_or(0);
|
||||
let (amount_0, amount_1) = match protocol_params.swap_mode {
|
||||
SWAP_MODE_EXACT_OUT => {
|
||||
let amount_out = params.fixed_output_amount.ok_or_else(|| {
|
||||
anyhow!("fixed_output_amount must be set for MeteoraDammV2 exact-out swap2")
|
||||
})?;
|
||||
(amount_out, amount_in)
|
||||
}
|
||||
SWAP_MODE_EXACT_IN | SWAP_MODE_PARTIAL_FILL => {
|
||||
let minimum_amount_out = params.fixed_output_amount.ok_or_else(|| {
|
||||
anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap2 min output")
|
||||
})?;
|
||||
(amount_in, minimum_amount_out)
|
||||
}
|
||||
mode => return Err(anyhow!("Unsupported MeteoraDammV2 swap_mode {}", mode)),
|
||||
};
|
||||
|
||||
let input_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.input_mint,
|
||||
if is_a_in {
|
||||
&protocol_params.token_a_program
|
||||
} else {
|
||||
&protocol_params.token_b_program
|
||||
},
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let output_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
if is_a_in {
|
||||
&protocol_params.token_b_program
|
||||
} else {
|
||||
&protocol_params.token_a_program
|
||||
},
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
// ========================================
|
||||
// Build instructions
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(3);
|
||||
let mut instructions = Vec::with_capacity(4);
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::create_wsol_ata(¶ms.payer.pubkey()));
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create buy instruction
|
||||
let accounts: [AccountMeta; 14] = [
|
||||
let mut account_metas = Vec::with_capacity(
|
||||
13 + usize::from(protocol_params.referral_token_account.is_some())
|
||||
+ usize::from(protocol_params.include_rate_limiter_sysvar),
|
||||
);
|
||||
account_metas.extend([
|
||||
accounts::AUTHORITY_META, // Pool Authority (readonly)
|
||||
AccountMeta::new(protocol_params.pool, false), // Pool
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
@@ -201,32 +264,36 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
AccountMeta::new(params.payer.pubkey(), true), // User Transfer Authority
|
||||
AccountMeta::new_readonly(protocol_params.token_a_program, false), // Token Program (readonly)
|
||||
AccountMeta::new_readonly(protocol_params.token_b_program, false), // Token Program (readonly)
|
||||
accounts::METEORA_DAMM_V2_META, // Referral Token Account (readonly)
|
||||
]);
|
||||
if let Some(referral_token_account) = protocol_params.referral_token_account {
|
||||
account_metas.push(AccountMeta::new(referral_token_account, false));
|
||||
}
|
||||
account_metas.extend([
|
||||
AccountMeta::new_readonly(get_event_authority_pda(), false), // Event Authority (readonly)
|
||||
accounts::METEORA_DAMM_V2_META, // Program (readonly)
|
||||
];
|
||||
]);
|
||||
if protocol_params.include_rate_limiter_sysvar {
|
||||
account_metas.push(accounts::SYSVAR_INSTRUCTIONS_META);
|
||||
}
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
data[..8].copy_from_slice(&SWAP_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or_default().to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
let mut data = [0u8; 25];
|
||||
data[..8].copy_from_slice(&SWAP2_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_0.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount_1.to_le_bytes());
|
||||
data[24] = protocol_params.swap_mode;
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::METEORA_DAMM_V2,
|
||||
&data,
|
||||
accounts.to_vec(),
|
||||
account_metas,
|
||||
));
|
||||
|
||||
if params.close_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &output_mint);
|
||||
}
|
||||
if params.close_input_mint_ata {
|
||||
instructions.push(crate::common::spl_token::close_account(
|
||||
if is_a_in {
|
||||
&protocol_params.token_a_program
|
||||
} else {
|
||||
&protocol_params.token_b_program
|
||||
},
|
||||
&input_token_program,
|
||||
&input_token_account,
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
@@ -237,3 +304,162 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
||||
Ok(instructions)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
common::GasFeeStrategy,
|
||||
swqos::TradeType,
|
||||
trading::core::params::{DexParamEnum, SwapParams},
|
||||
};
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn pk(seed: u8) -> Pubkey {
|
||||
Pubkey::new_from_array([seed; 32])
|
||||
}
|
||||
|
||||
fn meteora_params(referral: Option<Pubkey>) -> MeteoraDammV2Params {
|
||||
let params = MeteoraDammV2Params::new(
|
||||
pk(1),
|
||||
pk(2),
|
||||
pk(3),
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
pk(4),
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
);
|
||||
match referral {
|
||||
Some(account) => params.with_referral_token_account(account),
|
||||
None => params,
|
||||
}
|
||||
}
|
||||
|
||||
fn swap_params(protocol_params: MeteoraDammV2Params) -> SwapParams {
|
||||
SwapParams {
|
||||
rpc: None,
|
||||
payer: Arc::new(Keypair::new()),
|
||||
trade_type: TradeType::Buy,
|
||||
input_mint: crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
input_token_program: None,
|
||||
output_mint: pk(4),
|
||||
output_token_program: None,
|
||||
input_amount: Some(100_000),
|
||||
slippage_basis_points: Some(100),
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
recent_blockhash: None,
|
||||
wait_tx_confirmed: false,
|
||||
protocol_params: DexParamEnum::MeteoraDammV2(protocol_params),
|
||||
open_seed_optimize: true,
|
||||
swqos_clients: Arc::new(Vec::new()),
|
||||
middleware_manager: None,
|
||||
durable_nonce: None,
|
||||
with_tip: false,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: false,
|
||||
create_output_mint_ata: false,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount: Some(1),
|
||||
gas_fee_strategy: GasFeeStrategy::new(),
|
||||
simulate: true,
|
||||
log_enabled: false,
|
||||
wait_for_all_submits: false,
|
||||
use_dedicated_sender_threads: false,
|
||||
sender_thread_cores: None,
|
||||
max_sender_concurrency: 0,
|
||||
effective_core_ids: Arc::new(Vec::new()),
|
||||
check_min_tip: false,
|
||||
grpc_recv_us: None,
|
||||
use_exact_sol_amount: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meteora_omits_optional_referral_account() {
|
||||
let instructions = MeteoraDammV2InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(meteora_params(None)))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 13);
|
||||
assert_eq!(ix.accounts[11].pubkey, get_event_authority_pda());
|
||||
assert_eq!(ix.accounts[12].pubkey, accounts::METEORA_DAMM_V2);
|
||||
assert_eq!(&ix.data[..8], SWAP2_DISCRIMINATOR);
|
||||
assert_eq!(ix.data[24], SWAP_MODE_PARTIAL_FILL);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meteora_includes_writable_referral_account_when_set() {
|
||||
let referral = pk(9);
|
||||
let instructions = MeteoraDammV2InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(meteora_params(Some(referral))))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 14);
|
||||
assert_eq!(ix.accounts[11].pubkey, referral);
|
||||
assert!(ix.accounts[11].is_writable);
|
||||
assert_eq!(ix.accounts[12].pubkey, get_event_authority_pda());
|
||||
assert_eq!(ix.accounts[13].pubkey, accounts::METEORA_DAMM_V2);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meteora_includes_sysvar_only_when_rate_limiter_is_set() {
|
||||
let protocol_params = meteora_params(None).with_rate_limiter_sysvar(true);
|
||||
let instructions = MeteoraDammV2InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(protocol_params))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 14);
|
||||
assert_eq!(ix.accounts[11].pubkey, get_event_authority_pda());
|
||||
assert_eq!(ix.accounts[12].pubkey, accounts::METEORA_DAMM_V2);
|
||||
assert_eq!(ix.accounts[13].pubkey, accounts::SYSVAR_INSTRUCTIONS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meteora_swap2_exact_out_uses_amount_out_then_max_input() {
|
||||
let protocol_params = meteora_params(None).with_swap_mode(SWAP_MODE_EXACT_OUT);
|
||||
let instructions = MeteoraDammV2InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(protocol_params))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], SWAP2_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 1);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 100_000);
|
||||
assert_eq!(ix.data[24], SWAP_MODE_EXACT_OUT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn meteora_sol_buy_uses_pool_wsol_mint_for_user_input_account() {
|
||||
let mut params = swap_params(meteora_params(None));
|
||||
params.input_mint = crate::constants::SOL_TOKEN_ACCOUNT;
|
||||
|
||||
let instructions =
|
||||
MeteoraDammV2InstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
let expected_wsol_ata =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
&crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let wrong_sol_ata =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
&crate::constants::SOL_TOKEN_ACCOUNT,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
assert_eq!(ix.accounts[2].pubkey, expected_wsol_ata);
|
||||
assert_ne!(ix.accounts[2].pubkey, wrong_sol_ata);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
pub mod pumpfun;
|
||||
pub mod pumpswap;
|
||||
pub mod bonk;
|
||||
pub mod raydium_cpmm;
|
||||
pub mod raydium_amm_v4;
|
||||
pub mod meteora_damm_v2;
|
||||
pub mod utils;
|
||||
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(crate) mod token_account_setup;
|
||||
pub mod utils;
|
||||
|
||||
Executable → Regular
+1492
-271
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,100 @@
|
||||
//! Pump.fun bonding-curve `buy` / `buy_exact_quote_in` / `sell`
|
||||
//! instruction data stack encoding. The public helper names are version-neutral;
|
||||
//! [`PumpFunIxVersion`] selects the legacy or V2 on-chain discriminator.
|
||||
//!
|
||||
//! Legacy `buy` / `buy_exact_sol_in` 与 `@pump-fun/pump-sdk` 对齐:`OptionBool` 是单字段
|
||||
//! struct(TypeScript 传 `[true]`),在 ix 参数中为 1 字节 bool,共 25 字节 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_QUOTE_IN_V2_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR,
|
||||
BUY_V2_DISCRIMINATOR, SELL_DISCRIMINATOR, SELL_V2_DISCRIMINATOR,
|
||||
};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum PumpFunIxVersion {
|
||||
Legacy { track_volume: u8 },
|
||||
V2,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
|
||||
pub(crate) enum PumpFunIxData {
|
||||
Bytes25([u8; 25]),
|
||||
Bytes24([u8; 24]),
|
||||
}
|
||||
|
||||
impl PumpFunIxData {
|
||||
#[inline(always)]
|
||||
pub(crate) fn as_slice(&self) -> &[u8] {
|
||||
match self {
|
||||
Self::Bytes25(data) => data,
|
||||
Self::Bytes24(data) => data,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn encode_pumpfun_buy_ix_data(
|
||||
token_amount: u64,
|
||||
max_quote_cost: u64,
|
||||
version: PumpFunIxVersion,
|
||||
) -> PumpFunIxData {
|
||||
match version {
|
||||
PumpFunIxVersion::Legacy { track_volume } => {
|
||||
let mut d = [0u8; 25];
|
||||
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_quote_cost.to_le_bytes());
|
||||
d[24] = track_volume;
|
||||
PumpFunIxData::Bytes25(d)
|
||||
}
|
||||
PumpFunIxVersion::V2 => {
|
||||
let mut d = [0u8; 24];
|
||||
d[..8].copy_from_slice(&BUY_V2_DISCRIMINATOR);
|
||||
d[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&max_quote_cost.to_le_bytes());
|
||||
PumpFunIxData::Bytes24(d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn encode_pumpfun_buy_exact_quote_in_ix_data(
|
||||
spendable_quote_in: u64,
|
||||
min_tokens_out: u64,
|
||||
version: PumpFunIxVersion,
|
||||
) -> PumpFunIxData {
|
||||
match version {
|
||||
PumpFunIxVersion::Legacy { track_volume } => {
|
||||
let mut d = [0u8; 25];
|
||||
d[..8].copy_from_slice(&BUY_EXACT_SOL_IN_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[24] = track_volume;
|
||||
PumpFunIxData::Bytes25(d)
|
||||
}
|
||||
PumpFunIxVersion::V2 => {
|
||||
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());
|
||||
PumpFunIxData::Bytes24(d)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub(crate) fn encode_pumpfun_sell_ix_data(
|
||||
token_amount: u64,
|
||||
min_quote_output: u64,
|
||||
version: PumpFunIxVersion,
|
||||
) -> PumpFunIxData {
|
||||
let mut d = [0u8; 24];
|
||||
d[..8].copy_from_slice(match version {
|
||||
PumpFunIxVersion::Legacy { .. } => &SELL_DISCRIMINATOR,
|
||||
PumpFunIxVersion::V2 => &SELL_V2_DISCRIMINATOR,
|
||||
});
|
||||
d[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&min_quote_output.to_le_bytes());
|
||||
PumpFunIxData::Bytes24(d)
|
||||
}
|
||||
+335
-142
@@ -1,18 +1,28 @@
|
||||
use crate::{
|
||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||
instruction::utils::pumpswap::{
|
||||
accounts, fee_recipient_ata, get_pool_v2_pda, get_user_volume_accumulator_pda,
|
||||
get_user_volume_accumulator_wsol_ata, BUY_DISCRIMINATOR,
|
||||
BUY_EXACT_QUOTE_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||
instruction::pumpswap_ix_data::{
|
||||
encode_pumpswap_buy_exact_quote_in_ix_data, encode_pumpswap_buy_ix_data,
|
||||
encode_pumpswap_buy_two_args, encode_pumpswap_sell_ix_data,
|
||||
},
|
||||
trading::{
|
||||
common::wsol_manager,
|
||||
core::{
|
||||
params::{PumpSwapParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
instruction::{
|
||||
token_account_setup::{
|
||||
push_close_wsol_if_needed, push_create_or_wrap_user_token_account,
|
||||
push_create_user_token_account,
|
||||
},
|
||||
utils::pumpswap::{
|
||||
accounts, fee_recipient_ata, get_mayhem_fee_recipient_random, get_pool_v2_pda,
|
||||
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,
|
||||
},
|
||||
},
|
||||
utils::calc::pumpswap::{buy_quote_input_internal, sell_base_input_internal},
|
||||
trading::core::{
|
||||
params::{PumpSwapParams, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
},
|
||||
utils::calc::pumpswap::{
|
||||
buy_quote_input_internal_with_fees, sell_base_input_internal_with_fees,
|
||||
},
|
||||
};
|
||||
use anyhow::{anyhow, Result};
|
||||
use solana_sdk::{
|
||||
@@ -47,7 +57,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
let pool_quote_token_reserves = protocol_params.pool_quote_token_reserves;
|
||||
let params_coin_creator_vault_ata = protocol_params.coin_creator_vault_ata;
|
||||
let params_coin_creator_vault_authority = protocol_params.coin_creator_vault_authority;
|
||||
let create_wsol_ata = params.create_input_mint_ata;
|
||||
let create_input_ata = params.create_input_mint_ata;
|
||||
let close_wsol_ata = params.close_input_mint_ata;
|
||||
let base_token_program = protocol_params.base_token_program;
|
||||
let quote_token_program = protocol_params.quote_token_program;
|
||||
@@ -71,39 +81,40 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
// ========================================
|
||||
let quote_is_wsol_or_usdc = quote_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let mut creator = Pubkey::default();
|
||||
if params_coin_creator_vault_authority != accounts::DEFAULT_COIN_CREATOR_VAULT_AUTHORITY {
|
||||
creator = params_coin_creator_vault_authority;
|
||||
}
|
||||
let input_stable_mint = if quote_is_wsol_or_usdc { quote_mint } else { base_mint };
|
||||
let input_stable_token_program =
|
||||
if quote_is_wsol_or_usdc { quote_token_program } else { base_token_program };
|
||||
let output_trade_mint = if quote_is_wsol_or_usdc { base_mint } else { quote_mint };
|
||||
let output_trade_token_program =
|
||||
if quote_is_wsol_or_usdc { base_token_program } else { quote_token_program };
|
||||
let fee_basis_points = protocol_params.fee_basis_points;
|
||||
|
||||
let (mut token_amount, sol_amount) = if quote_is_wsol_or_usdc {
|
||||
let result = buy_quote_input_internal(
|
||||
let (token_amount, sol_amount) = if let Some(output_amount) = params.fixed_output_amount {
|
||||
(output_amount, params.input_amount.unwrap_or(0))
|
||||
} else if quote_is_wsol_or_usdc {
|
||||
let result = buy_quote_input_internal_with_fees(
|
||||
params.input_amount.unwrap_or(0),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
pool_base_token_reserves,
|
||||
pool_quote_token_reserves,
|
||||
&creator,
|
||||
&fee_basis_points,
|
||||
)
|
||||
.unwrap();
|
||||
// base_amount_out, max_quote_amount_in
|
||||
(result.base, result.max_quote)
|
||||
} else {
|
||||
let result = sell_base_input_internal(
|
||||
let result = sell_base_input_internal_with_fees(
|
||||
params.input_amount.unwrap_or(0),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
pool_base_token_reserves,
|
||||
pool_quote_token_reserves,
|
||||
&creator,
|
||||
&fee_basis_points,
|
||||
)
|
||||
.unwrap();
|
||||
// min_quote_amount_out, base_amount_in
|
||||
(result.min_quote, params.input_amount.unwrap_or(0))
|
||||
};
|
||||
|
||||
if params.fixed_output_amount.is_some() {
|
||||
token_amount = params.fixed_output_amount.unwrap();
|
||||
}
|
||||
|
||||
let user_base_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
@@ -119,14 +130,13 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
|
||||
let is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||
let fee_recipient =
|
||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
||||
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||
get_mayhem_fee_recipient_random()
|
||||
} else {
|
||||
accounts::FEE_RECIPIENT_META
|
||||
let recipient = get_protocol_fee_recipient_random();
|
||||
(recipient, AccountMeta::new_readonly(recipient, false))
|
||||
};
|
||||
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
|
||||
|
||||
@@ -135,25 +145,38 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(6);
|
||||
|
||||
if create_wsol_ata {
|
||||
instructions
|
||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), sol_amount));
|
||||
if create_input_ata {
|
||||
// Determine wrap amount based on instruction type:
|
||||
// - buy_exact_quote_in: program spends exactly input_amount, wrap input_amount
|
||||
// - buy: program may spend up to max_quote, wrap max_quote
|
||||
let wrap_amount =
|
||||
if quote_is_wsol_or_usdc && params.use_exact_sol_amount.unwrap_or(true) {
|
||||
params.input_amount.unwrap_or(0)
|
||||
} else {
|
||||
sol_amount
|
||||
};
|
||||
push_create_or_wrap_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&input_stable_mint,
|
||||
&input_stable_token_program,
|
||||
wrap_amount,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(
|
||||
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
if quote_is_wsol_or_usdc { &base_mint } else { "e_mint },
|
||||
if quote_is_wsol_or_usdc { &base_token_program } else { "e_token_program },
|
||||
params.open_seed_optimize,
|
||||
),
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_trade_mint,
|
||||
&output_trade_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create buy instruction
|
||||
let mut accounts = Vec::with_capacity(23);
|
||||
let mut accounts = Vec::with_capacity(28);
|
||||
accounts.extend([
|
||||
AccountMeta::new(pool, false), // pool_id
|
||||
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
||||
@@ -177,10 +200,9 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
]);
|
||||
if quote_is_wsol_or_usdc {
|
||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||
accounts.push(AccountMeta::new(
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
||||
false,
|
||||
));
|
||||
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||
accounts.push(AccountMeta::new(uva, false));
|
||||
}
|
||||
accounts.push(accounts::FEE_CONFIG_META);
|
||||
accounts.push(accounts::FEE_PROGRAM_META);
|
||||
@@ -190,54 +212,59 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
accounts.push(AccountMeta::new(wsol_ata, false));
|
||||
}
|
||||
}
|
||||
// Program upgrade: pool_v2 (readonly) at end of account list
|
||||
accounts.push(AccountMeta::new_readonly(
|
||||
get_pool_v2_pda(&base_mint).unwrap(),
|
||||
// `pool-v2` only when coin_creator ≠ default (@pump-fun/pump-swap-sdk remainingAccounts);
|
||||
// 否则多出的一格会把 buyback pubkey 错位,触发 BuybackFeeRecipientNotAuthorized(6053)。
|
||||
if protocol_params.coin_creator != Pubkey::default() {
|
||||
let pool_v2 = get_pool_v2_pda(&base_mint).ok_or_else(|| {
|
||||
anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint)
|
||||
})?;
|
||||
accounts.push(AccountMeta::new_readonly(pool_v2, false));
|
||||
}
|
||||
// Trailing accounts: GlobalConfig.buyback_fee_recipients 中任 pubkey + quote ATA(与 pump-swap-sdk 静态池对齐;轮换时需查链上)。
|
||||
let protocol_extra = get_protocol_extra_fee_recipient_random();
|
||||
accounts.push(AccountMeta::new_readonly(protocol_extra, false));
|
||||
accounts.push(AccountMeta::new(
|
||||
crate::instruction::utils::pumpswap::fee_recipient_ata(protocol_extra, quote_mint),
|
||||
false,
|
||||
));
|
||||
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
// buy / buy_exact_quote_in:栈上 `[u8;25]` + `new_with_bytes`,避免每笔 `Vec` 堆分配。
|
||||
let track_volume: u8 = if protocol_params.is_cashback_coin { 1 } else { 0 };
|
||||
if quote_is_wsol_or_usdc {
|
||||
if params.use_exact_sol_amount.unwrap_or(true) {
|
||||
// buy_exact_quote_in(spendable_quote_in: u64, min_base_amount_out: u64)
|
||||
// Spend exactly the input SOL/quote amount, get at least min_base_amount_out
|
||||
let ix_data = if params.fixed_output_amount.is_some() {
|
||||
encode_pumpswap_buy_ix_data(token_amount, sol_amount, track_volume)
|
||||
} else if params.use_exact_sol_amount.unwrap_or(true) {
|
||||
let min_base_amount_out = crate::utils::calc::common::calculate_with_slippage_sell(
|
||||
token_amount,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
);
|
||||
data[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
||||
// spendable_quote_in (exact SOL amount to spend)
|
||||
data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||
// min_base_amount_out (minimum tokens to receive)
|
||||
data[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
||||
encode_pumpswap_buy_exact_quote_in_ix_data(
|
||||
params.input_amount.unwrap_or(0),
|
||||
min_base_amount_out,
|
||||
track_volume,
|
||||
)
|
||||
} else {
|
||||
// buy(base_amount_out: u64, max_quote_amount_in: u64)
|
||||
// Buy exactly base_amount_out tokens, pay up to max_quote_amount_in
|
||||
data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
// base_amount_out
|
||||
data[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
// max_quote_amount_in
|
||||
data[16..24].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
}
|
||||
encode_pumpswap_buy_ix_data(token_amount, sol_amount, track_volume)
|
||||
};
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::AMM_PROGRAM,
|
||||
&ix_data,
|
||||
accounts,
|
||||
));
|
||||
} else {
|
||||
data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
// base_amount_in
|
||||
data[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
// min_quote_amount_out
|
||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||
let ix_data = encode_pumpswap_sell_ix_data(sol_amount, token_amount);
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::AMM_PROGRAM,
|
||||
&ix_data,
|
||||
accounts,
|
||||
));
|
||||
}
|
||||
|
||||
let buy_instruction = Instruction {
|
||||
program_id: accounts::AMM_PROGRAM,
|
||||
accounts: accounts.clone(),
|
||||
data: data.to_vec(),
|
||||
};
|
||||
|
||||
instructions.push(buy_instruction);
|
||||
if close_wsol_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&input_stable_mint,
|
||||
);
|
||||
}
|
||||
Ok(instructions)
|
||||
}
|
||||
@@ -261,7 +288,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
let pool_quote_token_account = protocol_params.pool_quote_token_account;
|
||||
let params_coin_creator_vault_ata = protocol_params.coin_creator_vault_ata;
|
||||
let params_coin_creator_vault_authority = protocol_params.coin_creator_vault_authority;
|
||||
let create_wsol_ata = params.create_output_mint_ata;
|
||||
let create_output_ata = params.create_output_mint_ata;
|
||||
let close_wsol_ata = params.close_output_mint_ata;
|
||||
let base_token_program = protocol_params.base_token_program;
|
||||
let quote_token_program = protocol_params.quote_token_program;
|
||||
@@ -287,47 +314,44 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
// ========================================
|
||||
let quote_is_wsol_or_usdc = quote_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let mut creator = Pubkey::default();
|
||||
if params_coin_creator_vault_authority != accounts::DEFAULT_COIN_CREATOR_VAULT_AUTHORITY {
|
||||
creator = params_coin_creator_vault_authority;
|
||||
}
|
||||
let output_stable_mint = if quote_is_wsol_or_usdc { quote_mint } else { base_mint };
|
||||
let output_stable_token_program =
|
||||
if quote_is_wsol_or_usdc { quote_token_program } else { base_token_program };
|
||||
let fee_basis_points = protocol_params.fee_basis_points;
|
||||
|
||||
let (token_amount, mut sol_amount) = if quote_is_wsol_or_usdc {
|
||||
let result = sell_base_input_internal(
|
||||
let (token_amount, sol_amount) = if let Some(output_amount) = params.fixed_output_amount {
|
||||
(params.input_amount.unwrap(), output_amount)
|
||||
} else if quote_is_wsol_or_usdc {
|
||||
let result = sell_base_input_internal_with_fees(
|
||||
params.input_amount.unwrap(),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
pool_base_token_reserves,
|
||||
pool_quote_token_reserves,
|
||||
&creator,
|
||||
&fee_basis_points,
|
||||
)
|
||||
.unwrap();
|
||||
// base_amount_in, min_quote_amount_out
|
||||
(params.input_amount.unwrap(), result.min_quote)
|
||||
} else {
|
||||
let result = buy_quote_input_internal(
|
||||
let result = buy_quote_input_internal_with_fees(
|
||||
params.input_amount.unwrap(),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
pool_base_token_reserves,
|
||||
pool_quote_token_reserves,
|
||||
&creator,
|
||||
&fee_basis_points,
|
||||
)
|
||||
.unwrap();
|
||||
// max_quote_amount_in, base_amount_out
|
||||
(result.max_quote, result.base)
|
||||
};
|
||||
|
||||
if params.fixed_output_amount.is_some() {
|
||||
sol_amount = params.fixed_output_amount.unwrap();
|
||||
}
|
||||
|
||||
// Determine fee recipient based on mayhem mode
|
||||
// Determine fee recipient based on mayhem mode (pump-public-docs: 10th = Mayhem fee recipient, 11th = WSOL ATA of Mayhem; use any one randomly)
|
||||
let is_mayhem_mode = protocol_params.is_mayhem_mode;
|
||||
let fee_recipient =
|
||||
if is_mayhem_mode { accounts::MAYHEM_FEE_RECIPIENT } else { accounts::FEE_RECIPIENT };
|
||||
let fee_recipient_meta = if is_mayhem_mode {
|
||||
accounts::MAYHEM_FEE_RECIPIENT_META
|
||||
let (fee_recipient, fee_recipient_meta) = if is_mayhem_mode {
|
||||
get_mayhem_fee_recipient_random()
|
||||
} else {
|
||||
accounts::FEE_RECIPIENT_META
|
||||
let recipient = get_protocol_fee_recipient_random();
|
||||
(recipient, AccountMeta::new_readonly(recipient, false))
|
||||
};
|
||||
let fee_recipient_ata = fee_recipient_ata(fee_recipient, quote_mint);
|
||||
|
||||
@@ -349,14 +373,20 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
// ========================================
|
||||
// Build instructions
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(3);
|
||||
let mut instructions = Vec::with_capacity(4);
|
||||
|
||||
if create_wsol_ata {
|
||||
instructions.extend(wsol_manager::create_wsol_ata(¶ms.payer.pubkey()));
|
||||
if create_output_ata {
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_stable_mint,
|
||||
&output_stable_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create sell instruction
|
||||
let mut accounts = Vec::with_capacity(23);
|
||||
let mut accounts = Vec::with_capacity(28);
|
||||
accounts.extend([
|
||||
AccountMeta::new(pool, false), // pool_id
|
||||
AccountMeta::new(params.payer.pubkey(), true), // user (signer)
|
||||
@@ -380,55 +410,54 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
||||
]);
|
||||
if !quote_is_wsol_or_usdc {
|
||||
accounts.push(accounts::GLOBAL_VOLUME_ACCUMULATOR_META);
|
||||
accounts.push(AccountMeta::new(
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()).unwrap(),
|
||||
false,
|
||||
));
|
||||
let uva = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||
accounts.push(AccountMeta::new(uva, false));
|
||||
}
|
||||
accounts.push(accounts::FEE_CONFIG_META);
|
||||
accounts.push(accounts::FEE_PROGRAM_META);
|
||||
// Cashback: remaining_accounts[0] = WSOL ATA of UserVolumeAccumulator, remaining_accounts[1] = UserVolumeAccumulator PDA
|
||||
// Cashback sell: 官方 remainingAccounts = [accumulator 的 quote_mint ATA, accumulator PDA, poolV2](用 quote_mint 非固定 WSOL)
|
||||
if protocol_params.is_cashback_coin {
|
||||
if let (Some(wsol_ata), Some(accumulator)) = (
|
||||
get_user_volume_accumulator_wsol_ata(¶ms.payer.pubkey()),
|
||||
if let (Some(quote_ata), Some(accumulator)) = (
|
||||
get_user_volume_accumulator_quote_ata(
|
||||
¶ms.payer.pubkey(),
|
||||
"e_mint,
|
||||
"e_token_program,
|
||||
),
|
||||
get_user_volume_accumulator_pda(¶ms.payer.pubkey()),
|
||||
) {
|
||||
accounts.push(AccountMeta::new(wsol_ata, false));
|
||||
accounts.push(AccountMeta::new(quote_ata, false));
|
||||
accounts.push(AccountMeta::new(accumulator, false));
|
||||
}
|
||||
}
|
||||
// Program upgrade: pool_v2 (readonly) at end of account list
|
||||
accounts.push(AccountMeta::new_readonly(
|
||||
get_pool_v2_pda(&base_mint).unwrap(),
|
||||
if protocol_params.coin_creator != Pubkey::default() {
|
||||
let pool_v2 = get_pool_v2_pda(&base_mint).ok_or_else(|| {
|
||||
anyhow!("pool_v2 PDA derivation failed for base_mint {}", base_mint)
|
||||
})?;
|
||||
accounts.push(AccountMeta::new_readonly(pool_v2, false));
|
||||
}
|
||||
let protocol_extra = get_protocol_extra_fee_recipient_random();
|
||||
accounts.push(AccountMeta::new_readonly(protocol_extra, false));
|
||||
accounts.push(AccountMeta::new(
|
||||
crate::instruction::utils::pumpswap::fee_recipient_ata(protocol_extra, quote_mint),
|
||||
false,
|
||||
));
|
||||
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
if quote_is_wsol_or_usdc {
|
||||
data[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
// base_amount_in
|
||||
data[8..16].copy_from_slice(&token_amount.to_le_bytes());
|
||||
// min_quote_amount_out
|
||||
data[16..24].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
// 栈数组 + `new_with_bytes`,避免 `data.to_vec()`。
|
||||
let ix_data = if quote_is_wsol_or_usdc {
|
||||
encode_pumpswap_sell_ix_data(token_amount, sol_amount)
|
||||
} else {
|
||||
data[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
// base_amount_out
|
||||
data[8..16].copy_from_slice(&sol_amount.to_le_bytes());
|
||||
// max_quote_amount_in
|
||||
data[16..24].copy_from_slice(&token_amount.to_le_bytes());
|
||||
}
|
||||
|
||||
let sell_instruction = Instruction {
|
||||
program_id: accounts::AMM_PROGRAM,
|
||||
accounts: accounts.clone(),
|
||||
data: data.to_vec(),
|
||||
encode_pumpswap_buy_two_args(sol_amount, token_amount)
|
||||
};
|
||||
|
||||
instructions.push(sell_instruction);
|
||||
instructions.push(Instruction::new_with_bytes(accounts::AMM_PROGRAM, &ix_data, accounts));
|
||||
|
||||
if close_wsol_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_stable_mint,
|
||||
);
|
||||
}
|
||||
if params.close_input_mint_ata {
|
||||
instructions.push(crate::common::spl_token::close_account(
|
||||
@@ -465,12 +494,12 @@ pub fn claim_cashback_pumpswap_instruction(
|
||||
// IDL order: user, user_volume_accumulator, quote_mint, quote_token_program,
|
||||
// user_volume_accumulator_wsol_token_account, user_wsol_token_account, system_program, event_authority, program
|
||||
let accounts = vec![
|
||||
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable)
|
||||
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable)
|
||||
AccountMeta::new_readonly(quote_mint, false),
|
||||
AccountMeta::new_readonly(quote_token_program, false),
|
||||
AccountMeta::new(user_volume_accumulator_wsol_ata, false), // writable
|
||||
AccountMeta::new(user_wsol_ata, false), // writable
|
||||
AccountMeta::new(user_volume_accumulator_wsol_ata, false), // writable
|
||||
AccountMeta::new(user_wsol_ata, false), // writable
|
||||
crate::constants::SYSTEM_PROGRAM_META,
|
||||
accounts::EVENT_AUTHORITY_META,
|
||||
accounts::AMM_PROGRAM_META,
|
||||
@@ -481,3 +510,167 @@ pub fn claim_cashback_pumpswap_instruction(
|
||||
accounts,
|
||||
))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
common::GasFeeStrategy,
|
||||
swqos::TradeType,
|
||||
trading::core::params::{DexParamEnum, PumpSwapParams, SwapParams},
|
||||
};
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn pk(seed: u8) -> Pubkey {
|
||||
Pubkey::new_from_array([seed; 32])
|
||||
}
|
||||
|
||||
fn pumpswap_params() -> PumpSwapParams {
|
||||
PumpSwapParams::new(
|
||||
pk(1),
|
||||
pk(2),
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
pk(3),
|
||||
pk(4),
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
pk(5),
|
||||
accounts::DEFAULT_COIN_CREATOR_VAULT_AUTHORITY,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
accounts::PROTOCOL_FEE_RECIPIENT,
|
||||
Pubkey::default(),
|
||||
false,
|
||||
0,
|
||||
)
|
||||
}
|
||||
|
||||
fn swap_params(trade_type: TradeType, fixed_output_amount: Option<u64>) -> SwapParams {
|
||||
let (input_mint, output_mint) = if trade_type == TradeType::Sell {
|
||||
(pk(2), crate::constants::WSOL_TOKEN_ACCOUNT)
|
||||
} else {
|
||||
(crate::constants::WSOL_TOKEN_ACCOUNT, pk(2))
|
||||
};
|
||||
SwapParams {
|
||||
rpc: None,
|
||||
payer: Arc::new(Keypair::new()),
|
||||
trade_type,
|
||||
input_mint,
|
||||
input_token_program: None,
|
||||
output_mint,
|
||||
output_token_program: None,
|
||||
input_amount: Some(100_000),
|
||||
slippage_basis_points: Some(100),
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
recent_blockhash: None,
|
||||
wait_tx_confirmed: false,
|
||||
protocol_params: DexParamEnum::PumpSwap(pumpswap_params()),
|
||||
open_seed_optimize: true,
|
||||
swqos_clients: Arc::new(Vec::new()),
|
||||
middleware_manager: None,
|
||||
durable_nonce: None,
|
||||
with_tip: false,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: false,
|
||||
create_output_mint_ata: false,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount,
|
||||
gas_fee_strategy: GasFeeStrategy::new(),
|
||||
simulate: true,
|
||||
log_enabled: false,
|
||||
wait_for_all_submits: false,
|
||||
use_dedicated_sender_threads: false,
|
||||
sender_thread_cores: None,
|
||||
max_sender_concurrency: 0,
|
||||
effective_core_ids: Arc::new(Vec::new()),
|
||||
check_min_tip: false,
|
||||
grpc_recv_us: None,
|
||||
use_exact_sol_amount: Some(true),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pumpswap_fixed_output_uses_buy_with_max_input_budget() {
|
||||
let instructions = PumpSwapInstructionBuilder
|
||||
.build_buy_instructions(&swap_params(TradeType::Buy, Some(42)))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], crate::instruction::utils::pumpswap::BUY_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 42);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 100_000);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pumpswap_sell_fixed_output_uses_min_quote_directly() {
|
||||
let instructions = PumpSwapInstructionBuilder
|
||||
.build_sell_instructions(&swap_params(TradeType::Sell, Some(42)))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], crate::instruction::utils::pumpswap::SELL_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 100_000);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pumpswap_usdc_buy_create_input_builds_usdc_ata() {
|
||||
let mut params = swap_params(TradeType::Buy, Some(42));
|
||||
params.protocol_params = DexParamEnum::PumpSwap(PumpSwapParams::new(
|
||||
pk(1),
|
||||
pk(2),
|
||||
crate::constants::USDC_TOKEN_ACCOUNT,
|
||||
pk(3),
|
||||
pk(4),
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
pk(5),
|
||||
accounts::DEFAULT_COIN_CREATOR_VAULT_AUTHORITY,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
accounts::PROTOCOL_FEE_RECIPIENT,
|
||||
Pubkey::default(),
|
||||
false,
|
||||
0,
|
||||
));
|
||||
params.input_mint = crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
params.create_input_mint_ata = true;
|
||||
params.open_seed_optimize = false;
|
||||
|
||||
let instructions =
|
||||
PumpSwapInstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let create_ix = instructions.first().unwrap();
|
||||
|
||||
assert_eq!(create_ix.program_id, crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID);
|
||||
assert_eq!(create_ix.accounts[3].pubkey, crate::constants::USDC_TOKEN_ACCOUNT);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn pumpswap_buy_uses_fee_basis_points_from_params_without_rpc() {
|
||||
let mut params = swap_params(TradeType::Buy, None);
|
||||
params.input_amount = Some(1_000_000);
|
||||
params.use_exact_sol_amount = Some(false);
|
||||
params.protocol_params =
|
||||
DexParamEnum::PumpSwap(pumpswap_params().with_fee_basis_points(20, 5, 75));
|
||||
|
||||
let instructions =
|
||||
PumpSwapInstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], crate::instruction::utils::pumpswap::BUY_DISCRIMINATOR);
|
||||
let base_amount_out = u64::from_le_bytes(ix.data[8..16].try_into().unwrap());
|
||||
|
||||
let expected = crate::utils::calc::pumpswap::buy_quote_input_internal_with_fees(
|
||||
1_000_000,
|
||||
100,
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
&crate::instruction::utils::pumpswap::PumpSwapFeeBasisPoints::new(20, 5, 0),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(base_amount_out, expected.base);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
//! PumpSwap AMM `buy` / `buy_exact_quote_in` / `sell` instruction **data**(栈数组、无 `Vec` 分配)。
|
||||
|
||||
use crate::instruction::utils::pumpswap::{
|
||||
BUY_DISCRIMINATOR, BUY_EXACT_QUOTE_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||
};
|
||||
|
||||
#[inline(always)]
|
||||
pub fn encode_pumpswap_buy_two_args(base_amount_out: u64, max_quote_amount_in: u64) -> [u8; 24] {
|
||||
let mut d = [0u8; 24];
|
||||
d[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
d[8..16].copy_from_slice(&base_amount_out.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&max_quote_amount_in.to_le_bytes());
|
||||
d
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn encode_pumpswap_buy_ix_data(
|
||||
base_amount_out: u64,
|
||||
max_quote_amount_in: u64,
|
||||
track_volume: u8,
|
||||
) -> [u8; 25] {
|
||||
let mut d = [0u8; 25];
|
||||
d[..8].copy_from_slice(&BUY_DISCRIMINATOR);
|
||||
d[8..16].copy_from_slice(&base_amount_out.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&max_quote_amount_in.to_le_bytes());
|
||||
d[24] = track_volume;
|
||||
d
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn encode_pumpswap_buy_exact_quote_in_ix_data(
|
||||
spendable_quote_in: u64,
|
||||
min_base_amount_out: u64,
|
||||
track_volume: u8,
|
||||
) -> [u8; 25] {
|
||||
let mut d = [0u8; 25];
|
||||
d[..8].copy_from_slice(&BUY_EXACT_QUOTE_IN_DISCRIMINATOR);
|
||||
d[8..16].copy_from_slice(&spendable_quote_in.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&min_base_amount_out.to_le_bytes());
|
||||
d[24] = track_volume;
|
||||
d
|
||||
}
|
||||
|
||||
#[inline(always)]
|
||||
pub fn encode_pumpswap_sell_ix_data(base_amount_in: u64, min_quote_amount_out: u64) -> [u8; 24] {
|
||||
let mut d = [0u8; 24];
|
||||
d[..8].copy_from_slice(&SELL_DISCRIMINATOR);
|
||||
d[8..16].copy_from_slice(&base_amount_in.to_le_bytes());
|
||||
d[16..24].copy_from_slice(&min_quote_amount_out.to_le_bytes());
|
||||
d
|
||||
}
|
||||
@@ -1,6 +1,14 @@
|
||||
use crate::{
|
||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||
instruction::utils::raydium_amm_v4::{accounts, SWAP_BASE_IN_DISCRIMINATOR},
|
||||
instruction::{
|
||||
token_account_setup::{
|
||||
push_close_wsol_if_needed, push_create_or_wrap_user_token_account,
|
||||
push_create_user_token_account,
|
||||
},
|
||||
utils::raydium_amm_v4::{
|
||||
accounts, SWAP_BASE_IN_DISCRIMINATOR, SWAP_BASE_OUT_DISCRIMINATOR,
|
||||
},
|
||||
},
|
||||
trading::core::{
|
||||
params::{RaydiumAmmV4Params, SwapParams},
|
||||
traits::InstructionBuilder,
|
||||
@@ -10,12 +18,38 @@ use crate::{
|
||||
use anyhow::{anyhow, Result};
|
||||
use solana_sdk::{
|
||||
instruction::{AccountMeta, Instruction},
|
||||
pubkey::Pubkey,
|
||||
signer::Signer,
|
||||
};
|
||||
|
||||
/// Instruction builder for RaydiumCpmm protocol
|
||||
pub struct RaydiumAmmV4InstructionBuilder;
|
||||
|
||||
fn ensure_market_accounts(params: &RaydiumAmmV4Params) -> Result<()> {
|
||||
let required = [
|
||||
("amm_open_orders", params.amm_open_orders),
|
||||
("amm_target_orders", params.amm_target_orders),
|
||||
("serum_program", params.serum_program),
|
||||
("serum_market", params.serum_market),
|
||||
("serum_bids", params.serum_bids),
|
||||
("serum_asks", params.serum_asks),
|
||||
("serum_event_queue", params.serum_event_queue),
|
||||
("serum_coin_vault_account", params.serum_coin_vault_account),
|
||||
("serum_pc_vault_account", params.serum_pc_vault_account),
|
||||
("serum_vault_signer", params.serum_vault_signer),
|
||||
];
|
||||
|
||||
for (name, account) in required {
|
||||
if account == Pubkey::default() {
|
||||
return Err(anyhow!(
|
||||
"Raydium AMM v4 requires {}; use RaydiumAmmV4Params::from_amm_address_by_rpc or with_market_accounts",
|
||||
name
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
async fn build_buy_instructions(&self, params: &SwapParams) -> Result<Vec<Instruction>> {
|
||||
@@ -29,7 +63,8 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<RaydiumAmmV4Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
|
||||
ensure_market_accounts(protocol_params)?;
|
||||
|
||||
let is_wsol = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
@@ -44,32 +79,25 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
// ========================================
|
||||
// Trade calculation and account address preparation
|
||||
// ========================================
|
||||
let is_base_in = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
let is_base_in = protocol_params.coin_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.coin_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||
let swap_result = compute_swap_amount(
|
||||
protocol_params.coin_reserve,
|
||||
protocol_params.pc_reserve,
|
||||
is_base_in,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
);
|
||||
let minimum_amount_out = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => swap_result.min_amount_out,
|
||||
};
|
||||
let input_mint =
|
||||
if is_base_in { protocol_params.coin_mint } else { protocol_params.pc_mint };
|
||||
let output_mint =
|
||||
if is_base_in { protocol_params.pc_mint } else { protocol_params.coin_mint };
|
||||
|
||||
let user_source_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
&input_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let user_destination_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
&output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
@@ -80,47 +108,66 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
let mut instructions = Vec::with_capacity(6);
|
||||
|
||||
if params.create_input_mint_ata {
|
||||
instructions
|
||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), amount_in));
|
||||
push_create_or_wrap_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&input_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
amount_in,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(
|
||||
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
),
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create buy instruction
|
||||
let accounts: [AccountMeta; 17] = [
|
||||
let accounts: [AccountMeta; 18] = [
|
||||
crate::constants::TOKEN_PROGRAM_META, // Token Program (readonly)
|
||||
AccountMeta::new(protocol_params.amm, false), // Amm
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
AccountMeta::new(protocol_params.amm, false), // Amm Open Orders
|
||||
AccountMeta::new(protocol_params.amm_open_orders, false), // Amm Open Orders
|
||||
AccountMeta::new(protocol_params.amm_target_orders, false), // Amm Target Orders
|
||||
AccountMeta::new(protocol_params.token_coin, false), // Pool Coin Token Account
|
||||
AccountMeta::new(protocol_params.token_pc, false), // Pool Pc Token Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Program
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Market
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Bids
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Asks
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Event Queue
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Coin Vault Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Pc Vault Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Vault Signer
|
||||
AccountMeta::new_readonly(protocol_params.serum_program, false), // Serum Program
|
||||
AccountMeta::new(protocol_params.serum_market, false), // Serum Market
|
||||
AccountMeta::new(protocol_params.serum_bids, false), // Serum Bids
|
||||
AccountMeta::new(protocol_params.serum_asks, false), // Serum Asks
|
||||
AccountMeta::new(protocol_params.serum_event_queue, false), // Serum Event Queue
|
||||
AccountMeta::new(protocol_params.serum_coin_vault_account, false), // Serum Coin Vault Account
|
||||
AccountMeta::new(protocol_params.serum_pc_vault_account, false), // Serum Pc Vault Account
|
||||
AccountMeta::new_readonly(protocol_params.serum_vault_signer, false), // Serum Vault Signer
|
||||
AccountMeta::new(user_source_token_account, false), // User Source Token Account
|
||||
AccountMeta::new(user_destination_token_account, false), // User Destination Token Account
|
||||
AccountMeta::new(params.payer.pubkey(), true), // User Source Owner
|
||||
];
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 17];
|
||||
data[..1].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[9..17].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..1].copy_from_slice(&SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[9..17].copy_from_slice(&amount_out.to_le_bytes());
|
||||
} else {
|
||||
let minimum_amount_out = compute_swap_amount(
|
||||
protocol_params.coin_reserve,
|
||||
protocol_params.pc_reserve,
|
||||
is_base_in,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
)
|
||||
.min_amount_out;
|
||||
data[..1].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[9..17].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::RAYDIUM_AMM_V4,
|
||||
@@ -129,8 +176,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
));
|
||||
|
||||
if params.close_input_mint_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &input_mint);
|
||||
}
|
||||
|
||||
Ok(instructions)
|
||||
@@ -144,7 +190,8 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
.protocol_params
|
||||
.as_any()
|
||||
.downcast_ref::<RaydiumAmmV4Params>()
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumCpmm"))?;
|
||||
.ok_or_else(|| anyhow!("Invalid protocol params for RaydiumAmmV4"))?;
|
||||
ensure_market_accounts(protocol_params)?;
|
||||
|
||||
if params.input_amount.is_none() || params.input_amount.unwrap_or(0) == 0 {
|
||||
return Err(anyhow!("Token amount is not set"));
|
||||
@@ -165,29 +212,22 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
// ========================================
|
||||
let is_base_in = protocol_params.pc_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.pc_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let swap_result = compute_swap_amount(
|
||||
protocol_params.coin_reserve,
|
||||
protocol_params.pc_reserve,
|
||||
is_base_in,
|
||||
params.input_amount.unwrap_or(0),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
);
|
||||
let minimum_amount_out = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => swap_result.min_amount_out,
|
||||
};
|
||||
let input_mint =
|
||||
if is_base_in { protocol_params.coin_mint } else { protocol_params.pc_mint };
|
||||
let output_mint =
|
||||
if is_base_in { protocol_params.pc_mint } else { protocol_params.coin_mint };
|
||||
|
||||
let user_source_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.input_mint,
|
||||
&input_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let user_destination_token_account =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
&output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
@@ -195,37 +235,59 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
// ========================================
|
||||
// Build instructions
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(3);
|
||||
let mut instructions = Vec::with_capacity(4);
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::create_wsol_ata(¶ms.payer.pubkey()));
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create buy instruction
|
||||
let accounts: [AccountMeta; 17] = [
|
||||
let accounts: [AccountMeta; 18] = [
|
||||
crate::constants::TOKEN_PROGRAM_META, // Token Program (readonly)
|
||||
AccountMeta::new(protocol_params.amm, false), // Amm
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
AccountMeta::new(protocol_params.amm, false), // Amm Open Orders
|
||||
AccountMeta::new(protocol_params.amm_open_orders, false), // Amm Open Orders
|
||||
AccountMeta::new(protocol_params.amm_target_orders, false), // Amm Target Orders
|
||||
AccountMeta::new(protocol_params.token_coin, false), // Pool Coin Token Account
|
||||
AccountMeta::new(protocol_params.token_pc, false), // Pool Pc Token Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Program
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Market
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Bids
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Asks
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Event Queue
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Coin Vault Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Pc Vault Account
|
||||
AccountMeta::new(protocol_params.amm, false), // Serum Vault Signer
|
||||
AccountMeta::new_readonly(protocol_params.serum_program, false), // Serum Program
|
||||
AccountMeta::new(protocol_params.serum_market, false), // Serum Market
|
||||
AccountMeta::new(protocol_params.serum_bids, false), // Serum Bids
|
||||
AccountMeta::new(protocol_params.serum_asks, false), // Serum Asks
|
||||
AccountMeta::new(protocol_params.serum_event_queue, false), // Serum Event Queue
|
||||
AccountMeta::new(protocol_params.serum_coin_vault_account, false), // Serum Coin Vault Account
|
||||
AccountMeta::new(protocol_params.serum_pc_vault_account, false), // Serum Pc Vault Account
|
||||
AccountMeta::new_readonly(protocol_params.serum_vault_signer, false), // Serum Vault Signer
|
||||
AccountMeta::new(user_source_token_account, false), // User Source Token Account
|
||||
AccountMeta::new(user_destination_token_account, false), // User Destination Token Account
|
||||
AccountMeta::new(params.payer.pubkey(), true), // User Source Owner
|
||||
];
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 17];
|
||||
data[..1].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||
data[9..17].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
let amount_in = params.input_amount.unwrap_or(0);
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..1].copy_from_slice(&SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[9..17].copy_from_slice(&amount_out.to_le_bytes());
|
||||
} else {
|
||||
let minimum_amount_out = compute_swap_amount(
|
||||
protocol_params.coin_reserve,
|
||||
protocol_params.pc_reserve,
|
||||
is_base_in,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
)
|
||||
.min_amount_out;
|
||||
data[..1].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[1..9].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[9..17].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::RAYDIUM_AMM_V4,
|
||||
@@ -234,7 +296,7 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
));
|
||||
|
||||
if params.close_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &output_mint);
|
||||
}
|
||||
if params.close_input_mint_ata {
|
||||
instructions.push(crate::common::spl_token::close_account(
|
||||
@@ -249,3 +311,160 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
||||
Ok(instructions)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
common::GasFeeStrategy,
|
||||
swqos::TradeType,
|
||||
trading::core::params::{DexParamEnum, SwapParams},
|
||||
};
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn pk(seed: u8) -> Pubkey {
|
||||
Pubkey::new_from_array([seed; 32])
|
||||
}
|
||||
|
||||
fn market_params() -> RaydiumAmmV4Params {
|
||||
RaydiumAmmV4Params::new(
|
||||
pk(1),
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
pk(2),
|
||||
pk(3),
|
||||
pk(4),
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
)
|
||||
.with_market_accounts(
|
||||
pk(5),
|
||||
pk(6),
|
||||
pk(7),
|
||||
pk(8),
|
||||
pk(9),
|
||||
pk(10),
|
||||
pk(11),
|
||||
pk(12),
|
||||
pk(13),
|
||||
pk(14),
|
||||
)
|
||||
}
|
||||
|
||||
fn swap_params(
|
||||
protocol_params: RaydiumAmmV4Params,
|
||||
fixed_output_amount: Option<u64>,
|
||||
) -> SwapParams {
|
||||
SwapParams {
|
||||
rpc: None,
|
||||
payer: Arc::new(Keypair::new()),
|
||||
trade_type: TradeType::Buy,
|
||||
input_mint: crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
input_token_program: None,
|
||||
output_mint: pk(2),
|
||||
output_token_program: None,
|
||||
input_amount: Some(100_000),
|
||||
slippage_basis_points: Some(100),
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
recent_blockhash: None,
|
||||
wait_tx_confirmed: false,
|
||||
protocol_params: DexParamEnum::RaydiumAmmV4(protocol_params),
|
||||
open_seed_optimize: true,
|
||||
swqos_clients: Arc::new(Vec::new()),
|
||||
middleware_manager: None,
|
||||
durable_nonce: None,
|
||||
with_tip: false,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: false,
|
||||
create_output_mint_ata: false,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount,
|
||||
gas_fee_strategy: GasFeeStrategy::new(),
|
||||
simulate: true,
|
||||
log_enabled: false,
|
||||
wait_for_all_submits: false,
|
||||
use_dedicated_sender_threads: false,
|
||||
sender_thread_cores: None,
|
||||
max_sender_concurrency: 0,
|
||||
effective_core_ids: Arc::new(Vec::new()),
|
||||
check_min_tip: false,
|
||||
grpc_recv_us: None,
|
||||
use_exact_sol_amount: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_amm_v4_uses_idl_market_account_order() {
|
||||
let instructions = RaydiumAmmV4InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(market_params(), None))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(ix.accounts.len(), 18);
|
||||
assert_eq!(&ix.data[..1], SWAP_BASE_IN_DISCRIMINATOR);
|
||||
assert_eq!(ix.accounts[3].pubkey, pk(5));
|
||||
assert_eq!(ix.accounts[4].pubkey, pk(6));
|
||||
assert_eq!(ix.accounts[7].pubkey, pk(7));
|
||||
assert_eq!(ix.accounts[8].pubkey, pk(8));
|
||||
assert_eq!(ix.accounts[9].pubkey, pk(9));
|
||||
assert_eq!(ix.accounts[10].pubkey, pk(10));
|
||||
assert_eq!(ix.accounts[11].pubkey, pk(11));
|
||||
assert_eq!(ix.accounts[12].pubkey, pk(12));
|
||||
assert_eq!(ix.accounts[13].pubkey, pk(13));
|
||||
assert_eq!(ix.accounts[14].pubkey, pk(14));
|
||||
assert!(!ix.accounts[7].is_writable);
|
||||
assert!(!ix.accounts[14].is_writable);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_amm_v4_uses_base_out_when_fixed_output_is_set() {
|
||||
let instructions = RaydiumAmmV4InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(market_params(), Some(42)))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..1], SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[1..9].try_into().unwrap()), 100_000);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[9..17].try_into().unwrap()), 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_amm_v4_rejects_placeholder_market_accounts() {
|
||||
let err = RaydiumAmmV4InstructionBuilder
|
||||
.build_buy_instructions(&swap_params(
|
||||
RaydiumAmmV4Params::new(
|
||||
pk(1),
|
||||
crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
pk(2),
|
||||
pk(3),
|
||||
pk(4),
|
||||
1_000_000_000,
|
||||
2_000_000_000,
|
||||
),
|
||||
None,
|
||||
))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(err.to_string().contains("amm_open_orders"));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_amm_v4_usdc_buy_create_input_builds_usdc_ata() {
|
||||
let mut protocol_params = market_params();
|
||||
protocol_params.coin_mint = crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
|
||||
let mut params = swap_params(protocol_params, Some(42));
|
||||
params.input_mint = crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
params.create_input_mint_ata = true;
|
||||
params.open_seed_optimize = false;
|
||||
|
||||
let instructions =
|
||||
RaydiumAmmV4InstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let create_ix = instructions.first().unwrap();
|
||||
|
||||
assert_eq!(create_ix.program_id, crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID);
|
||||
assert_eq!(create_ix.accounts[3].pubkey, crate::constants::USDC_TOKEN_ACCOUNT);
|
||||
}
|
||||
}
|
||||
|
||||
+239
-94
@@ -1,9 +1,15 @@
|
||||
use crate::{
|
||||
common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed,
|
||||
constants::trade::trade::DEFAULT_SLIPPAGE,
|
||||
instruction::utils::raydium_cpmm::{
|
||||
accounts, get_observation_state_pda, get_pool_pda, get_vault_account,
|
||||
SWAP_BASE_IN_DISCRIMINATOR,
|
||||
instruction::{
|
||||
token_account_setup::{
|
||||
push_close_wsol_if_needed, push_create_or_wrap_user_token_account,
|
||||
push_create_user_token_account,
|
||||
},
|
||||
utils::raydium_cpmm::{
|
||||
accounts, get_observation_state_pda, get_pool_pda, get_vault_account,
|
||||
SWAP_BASE_IN_DISCRIMINATOR, SWAP_BASE_OUT_DISCRIMINATOR,
|
||||
},
|
||||
},
|
||||
trading::core::{
|
||||
params::{RaydiumCpmmParams, SwapParams},
|
||||
@@ -61,46 +67,40 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
// ========================================
|
||||
// Trade calculation and account address preparation
|
||||
// ========================================
|
||||
let is_base_in = protocol_params.base_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
let is_base_in = protocol_params.base_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let mint_token_program = if is_base_in {
|
||||
let input_mint =
|
||||
if is_base_in { protocol_params.base_mint } else { protocol_params.quote_mint };
|
||||
let input_token_program = if is_base_in {
|
||||
protocol_params.base_token_program
|
||||
} else {
|
||||
protocol_params.quote_token_program
|
||||
};
|
||||
let output_mint =
|
||||
if is_base_in { protocol_params.quote_mint } else { protocol_params.base_mint };
|
||||
let output_token_program = if is_base_in {
|
||||
protocol_params.quote_token_program
|
||||
} else {
|
||||
protocol_params.base_token_program
|
||||
};
|
||||
|
||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||
let result = compute_swap_amount(
|
||||
protocol_params.base_reserve,
|
||||
protocol_params.quote_reserve,
|
||||
is_base_in,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
);
|
||||
let minimum_amount_out = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => result.min_amount_out,
|
||||
};
|
||||
|
||||
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
&mint_token_program,
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
let input_vault_account = get_vault_account(
|
||||
&pool_state,
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
protocol_params,
|
||||
);
|
||||
let output_vault_account = get_vault_account(&pool_state, ¶ms.output_mint, protocol_params);
|
||||
let input_vault_account = get_vault_account(&pool_state, &input_mint, protocol_params);
|
||||
let output_vault_account = get_vault_account(&pool_state, &output_mint, protocol_params);
|
||||
|
||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||
get_observation_state_pda(&pool_state).unwrap()
|
||||
@@ -114,19 +114,23 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
let mut instructions = Vec::with_capacity(6);
|
||||
|
||||
if params.create_input_mint_ata {
|
||||
instructions
|
||||
.extend(crate::trading::common::handle_wsol(¶ms.payer.pubkey(), amount_in));
|
||||
push_create_or_wrap_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
amount_in,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(
|
||||
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.output_mint,
|
||||
&mint_token_program,
|
||||
params.open_seed_optimize,
|
||||
),
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -134,23 +138,37 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
let accounts: [AccountMeta; 13] = [
|
||||
AccountMeta::new(params.payer.pubkey(), true), // Payer (signer)
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||
AccountMeta::new_readonly(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||
AccountMeta::new(pool_state, false), // Pool State
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||
crate::constants::TOKEN_PROGRAM_META, // Input Token Program (readonly)
|
||||
AccountMeta::new_readonly(mint_token_program, false), // Output Token Program (readonly)
|
||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Input token mint (readonly)
|
||||
AccountMeta::new_readonly(params.output_mint, false), // Output token mint (readonly)
|
||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||
AccountMeta::new_readonly(input_token_program, false), // Input Token Program (readonly)
|
||||
AccountMeta::new_readonly(output_token_program, false), // Output Token Program (readonly)
|
||||
AccountMeta::new_readonly(input_mint, false), // Input token mint (readonly)
|
||||
AccountMeta::new_readonly(output_mint, false), // Output token mint (readonly)
|
||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||
];
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
data[..8].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..8].copy_from_slice(&SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount_out.to_le_bytes());
|
||||
} else {
|
||||
let minimum_amount_out = compute_swap_amount(
|
||||
protocol_params.base_reserve,
|
||||
protocol_params.quote_reserve,
|
||||
is_base_in,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
)
|
||||
.min_amount_out;
|
||||
data[..8].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::RAYDIUM_CPMM,
|
||||
@@ -159,8 +177,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
));
|
||||
|
||||
if params.close_input_mint_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &input_mint);
|
||||
}
|
||||
|
||||
Ok(instructions)
|
||||
@@ -196,7 +213,7 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
|
||||
let is_usdc = protocol_params.base_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||
|| protocol_params.quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
|
||||
|
||||
if !is_wsol && !is_usdc {
|
||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||
}
|
||||
@@ -206,45 +223,36 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
// ========================================
|
||||
let is_quote_out = protocol_params.quote_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||
|| protocol_params.quote_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
let mint_token_program = if is_quote_out {
|
||||
let input_mint =
|
||||
if is_quote_out { protocol_params.base_mint } else { protocol_params.quote_mint };
|
||||
let input_token_program = if is_quote_out {
|
||||
protocol_params.base_token_program
|
||||
} else {
|
||||
protocol_params.quote_token_program
|
||||
};
|
||||
|
||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||
Some(fixed) => fixed,
|
||||
None => {
|
||||
compute_swap_amount(
|
||||
protocol_params.base_reserve,
|
||||
protocol_params.quote_reserve,
|
||||
is_quote_out,
|
||||
params.input_amount.unwrap_or(0),
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
)
|
||||
.min_amount_out
|
||||
}
|
||||
let output_mint =
|
||||
if is_quote_out { protocol_params.quote_mint } else { protocol_params.base_mint };
|
||||
let output_token_program = if is_quote_out {
|
||||
protocol_params.quote_token_program
|
||||
} else {
|
||||
protocol_params.base_token_program
|
||||
};
|
||||
|
||||
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.input_mint,
|
||||
&mint_token_program,
|
||||
&input_mint,
|
||||
&input_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
|
||||
let output_vault_account = get_vault_account(
|
||||
&pool_state,
|
||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
||||
protocol_params,
|
||||
);
|
||||
let input_vault_account = get_vault_account(&pool_state, ¶ms.input_mint, protocol_params);
|
||||
let output_vault_account = get_vault_account(&pool_state, &output_mint, protocol_params);
|
||||
let input_vault_account = get_vault_account(&pool_state, &input_mint, protocol_params);
|
||||
|
||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||
get_observation_state_pda(&pool_state).unwrap()
|
||||
@@ -255,33 +263,54 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
// ========================================
|
||||
// Build instructions
|
||||
// ========================================
|
||||
let mut instructions = Vec::with_capacity(3);
|
||||
let mut instructions = Vec::with_capacity(4);
|
||||
|
||||
if params.create_output_mint_ata {
|
||||
instructions.extend(crate::trading::common::create_wsol_ata(¶ms.payer.pubkey()));
|
||||
push_create_user_token_account(
|
||||
&mut instructions,
|
||||
¶ms.payer.pubkey(),
|
||||
&output_mint,
|
||||
&output_token_program,
|
||||
params.open_seed_optimize,
|
||||
);
|
||||
}
|
||||
|
||||
// Create sell instruction
|
||||
let accounts: [AccountMeta; 13] = [
|
||||
AccountMeta::new(params.payer.pubkey(), true), // Payer (signer)
|
||||
accounts::AUTHORITY_META, // Authority (readonly)
|
||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||
AccountMeta::new_readonly(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||
AccountMeta::new(pool_state, false), // Pool State
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||
AccountMeta::new_readonly(mint_token_program, false), // Input Token Program (readonly)
|
||||
crate::constants::TOKEN_PROGRAM_META, // Output Token Program (readonly)
|
||||
AccountMeta::new_readonly(params.input_mint, false), // Input token mint (readonly)
|
||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Output token mint (readonly)
|
||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||
AccountMeta::new_readonly(input_token_program, false), // Input Token Program (readonly)
|
||||
AccountMeta::new_readonly(output_token_program, false), // Output Token Program (readonly)
|
||||
AccountMeta::new_readonly(input_mint, false), // Input token mint (readonly)
|
||||
AccountMeta::new_readonly(output_mint, false), // Output token mint (readonly)
|
||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||
];
|
||||
// Create instruction data
|
||||
let mut data = [0u8; 24];
|
||||
data[..8].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(¶ms.input_amount.unwrap_or(0).to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
let amount_in = params.input_amount.unwrap_or(0);
|
||||
if let Some(amount_out) = params.fixed_output_amount {
|
||||
data[..8].copy_from_slice(&SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&amount_out.to_le_bytes());
|
||||
} else {
|
||||
let minimum_amount_out = compute_swap_amount(
|
||||
protocol_params.base_reserve,
|
||||
protocol_params.quote_reserve,
|
||||
is_quote_out,
|
||||
amount_in,
|
||||
params.slippage_basis_points.unwrap_or(DEFAULT_SLIPPAGE),
|
||||
)
|
||||
.min_amount_out;
|
||||
data[..8].copy_from_slice(&SWAP_BASE_IN_DISCRIMINATOR);
|
||||
data[8..16].copy_from_slice(&amount_in.to_le_bytes());
|
||||
data[16..24].copy_from_slice(&minimum_amount_out.to_le_bytes());
|
||||
}
|
||||
|
||||
instructions.push(Instruction::new_with_bytes(
|
||||
accounts::RAYDIUM_CPMM,
|
||||
@@ -290,12 +319,11 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
));
|
||||
|
||||
if params.close_output_mint_ata {
|
||||
// Close wSOL ATA account, reclaim rent
|
||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||
push_close_wsol_if_needed(&mut instructions, ¶ms.payer.pubkey(), &output_mint);
|
||||
}
|
||||
if params.close_input_mint_ata {
|
||||
instructions.push(crate::common::spl_token::close_account(
|
||||
&mint_token_program,
|
||||
&input_token_program,
|
||||
&input_token_account,
|
||||
¶ms.payer.pubkey(),
|
||||
¶ms.payer.pubkey(),
|
||||
@@ -306,3 +334,120 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
||||
Ok(instructions)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::{
|
||||
common::GasFeeStrategy,
|
||||
swqos::TradeType,
|
||||
trading::core::params::{DexParamEnum, SwapParams},
|
||||
};
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair};
|
||||
use std::sync::Arc;
|
||||
|
||||
fn pk(seed: u8) -> Pubkey {
|
||||
Pubkey::new_from_array([seed; 32])
|
||||
}
|
||||
|
||||
fn cpmm_params() -> RaydiumCpmmParams {
|
||||
RaydiumCpmmParams {
|
||||
pool_state: pk(1),
|
||||
amm_config: pk(2),
|
||||
base_mint: crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
quote_mint: pk(3),
|
||||
base_reserve: 1_000_000_000,
|
||||
quote_reserve: 2_000_000_000,
|
||||
base_vault: pk(4),
|
||||
quote_vault: pk(5),
|
||||
base_token_program: crate::constants::TOKEN_PROGRAM,
|
||||
quote_token_program: crate::constants::TOKEN_PROGRAM,
|
||||
observation_state: pk(6),
|
||||
}
|
||||
}
|
||||
|
||||
fn swap_params(fixed_output_amount: Option<u64>) -> SwapParams {
|
||||
SwapParams {
|
||||
rpc: None,
|
||||
payer: Arc::new(Keypair::new()),
|
||||
trade_type: TradeType::Buy,
|
||||
input_mint: crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
input_token_program: None,
|
||||
output_mint: pk(3),
|
||||
output_token_program: None,
|
||||
input_amount: Some(100_000),
|
||||
slippage_basis_points: Some(100),
|
||||
address_lookup_table_accounts: Vec::new(),
|
||||
recent_blockhash: None,
|
||||
wait_tx_confirmed: false,
|
||||
protocol_params: DexParamEnum::RaydiumCpmm(cpmm_params()),
|
||||
open_seed_optimize: true,
|
||||
swqos_clients: Arc::new(Vec::new()),
|
||||
middleware_manager: None,
|
||||
durable_nonce: None,
|
||||
with_tip: false,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: false,
|
||||
create_output_mint_ata: false,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount,
|
||||
gas_fee_strategy: GasFeeStrategy::new(),
|
||||
simulate: true,
|
||||
log_enabled: false,
|
||||
wait_for_all_submits: false,
|
||||
use_dedicated_sender_threads: false,
|
||||
sender_thread_cores: None,
|
||||
max_sender_concurrency: 0,
|
||||
effective_core_ids: Arc::new(Vec::new()),
|
||||
check_min_tip: false,
|
||||
grpc_recv_us: None,
|
||||
use_exact_sol_amount: None,
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_cpmm_uses_base_in_and_readonly_amm_config_by_default() {
|
||||
let instructions =
|
||||
RaydiumCpmmInstructionBuilder.build_buy_instructions(&swap_params(None)).await.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], SWAP_BASE_IN_DISCRIMINATOR);
|
||||
assert_eq!(ix.accounts[2].pubkey, pk(2));
|
||||
assert!(!ix.accounts[2].is_writable);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_cpmm_uses_base_output_when_fixed_output_is_set() {
|
||||
let instructions = RaydiumCpmmInstructionBuilder
|
||||
.build_buy_instructions(&swap_params(Some(42)))
|
||||
.await
|
||||
.unwrap();
|
||||
let ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(&ix.data[..8], SWAP_BASE_OUT_DISCRIMINATOR);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[8..16].try_into().unwrap()), 100_000);
|
||||
assert_eq!(u64::from_le_bytes(ix.data[16..24].try_into().unwrap()), 42);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn raydium_cpmm_usdc_buy_create_input_uses_usdc_accounts() {
|
||||
let mut protocol_params = cpmm_params();
|
||||
protocol_params.base_mint = crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
protocol_params.quote_mint = pk(3);
|
||||
|
||||
let mut params = swap_params(Some(42));
|
||||
params.protocol_params = DexParamEnum::RaydiumCpmm(protocol_params);
|
||||
params.input_mint = crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
params.create_input_mint_ata = true;
|
||||
params.open_seed_optimize = false;
|
||||
|
||||
let instructions =
|
||||
RaydiumCpmmInstructionBuilder.build_buy_instructions(¶ms).await.unwrap();
|
||||
let create_ix = instructions.first().unwrap();
|
||||
let swap_ix = instructions.last().unwrap();
|
||||
|
||||
assert_eq!(create_ix.program_id, crate::constants::ASSOCIATED_TOKEN_PROGRAM_ID);
|
||||
assert_eq!(create_ix.accounts[3].pubkey, crate::constants::USDC_TOKEN_ACCOUNT);
|
||||
assert_eq!(swap_ix.accounts[10].pubkey, crate::constants::USDC_TOKEN_ACCOUNT);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn push_create_user_token_account(
|
||||
instructions: &mut Vec<Instruction>,
|
||||
payer: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
use_seed: bool,
|
||||
) {
|
||||
instructions.extend(
|
||||
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
payer,
|
||||
payer,
|
||||
mint,
|
||||
token_program,
|
||||
use_seed,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn push_create_or_wrap_user_token_account(
|
||||
instructions: &mut Vec<Instruction>,
|
||||
payer: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
token_program: &Pubkey,
|
||||
amount: u64,
|
||||
use_seed: bool,
|
||||
) {
|
||||
if *mint == crate::constants::WSOL_TOKEN_ACCOUNT {
|
||||
instructions.extend(crate::trading::common::handle_wsol(payer, amount));
|
||||
} else {
|
||||
push_create_user_token_account(instructions, payer, mint, token_program, use_seed);
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub(crate) fn push_close_wsol_if_needed(
|
||||
instructions: &mut Vec<Instruction>,
|
||||
payer: &Pubkey,
|
||||
mint: &Pubkey,
|
||||
) {
|
||||
if *mint == crate::constants::WSOL_TOKEN_ACCOUNT {
|
||||
instructions.extend(crate::trading::common::close_wsol(payer));
|
||||
}
|
||||
}
|
||||
@@ -57,7 +57,9 @@ pub mod accounts {
|
||||
}
|
||||
|
||||
pub const BUY_EXECT_IN_DISCRIMINATOR: [u8; 8] = [250, 234, 13, 123, 213, 156, 19, 236];
|
||||
pub const BUY_EXECT_OUT_DISCRIMINATOR: [u8; 8] = [24, 211, 116, 40, 105, 3, 153, 56];
|
||||
pub const SELL_EXECT_IN_DISCRIMINATOR: [u8; 8] = [149, 39, 222, 155, 211, 124, 152, 26];
|
||||
pub const SELL_EXECT_OUT_DISCRIMINATOR: [u8; 8] = [95, 200, 71, 34, 8, 9, 11, 166];
|
||||
|
||||
pub async fn fetch_pool_state(
|
||||
rpc: &SolanaRpcClient,
|
||||
|
||||
@@ -16,6 +16,7 @@ pub mod accounts {
|
||||
|
||||
pub const AUTHORITY: Pubkey = pubkey!("HLnpSz9h2S4hiLQ43rnSD9XkcUThA7B8hQMKmDaiTLcC");
|
||||
pub const METEORA_DAMM_V2: Pubkey = pubkey!("cpamdpZCGKUy5JxQXB4dcpGPiikHawvSWAd6mEn1sGG");
|
||||
pub const SYSVAR_INSTRUCTIONS: Pubkey = pubkey!("Sysvar1nstructions1111111111111111111111111");
|
||||
|
||||
// META
|
||||
|
||||
@@ -32,9 +33,20 @@ pub mod accounts {
|
||||
is_signer: false,
|
||||
is_writable: false,
|
||||
};
|
||||
|
||||
pub const SYSVAR_INSTRUCTIONS_META: solana_sdk::instruction::AccountMeta =
|
||||
solana_sdk::instruction::AccountMeta {
|
||||
pubkey: SYSVAR_INSTRUCTIONS,
|
||||
is_signer: false,
|
||||
is_writable: false,
|
||||
};
|
||||
}
|
||||
|
||||
pub const SWAP_DISCRIMINATOR: &[u8] = &[248, 198, 158, 145, 225, 117, 135, 200];
|
||||
pub const SWAP2_DISCRIMINATOR: &[u8] = &[65, 75, 63, 76, 235, 91, 91, 136];
|
||||
pub const SWAP_MODE_EXACT_IN: u8 = 0;
|
||||
pub const SWAP_MODE_PARTIAL_FILL: u8 = 1;
|
||||
pub const SWAP_MODE_EXACT_OUT: u8 = 2;
|
||||
|
||||
pub async fn fetch_pool(
|
||||
rpc: &SolanaRpcClient,
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
pub mod bonk;
|
||||
pub mod meteora_damm_v2;
|
||||
pub mod pumpfun;
|
||||
pub mod pumpswap;
|
||||
pub mod raydium_amm_v4;
|
||||
pub mod raydium_cpmm;
|
||||
pub mod meteora_damm_v2;
|
||||
|
||||
// types
|
||||
pub mod bonk_types;
|
||||
pub mod meteora_damm_v2_types;
|
||||
pub mod pumpswap_types;
|
||||
pub mod raydium_amm_v4_types;
|
||||
pub mod raydium_cpmm_types;
|
||||
pub mod meteora_damm_v2_types;
|
||||
@@ -1,56 +1,55 @@
|
||||
//! 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 solana_sdk::pubkey::Pubkey;
|
||||
use borsh::BorshDeserialize;
|
||||
use rand::seq::IndexedRandom;
|
||||
use solana_sdk::{
|
||||
instruction::{AccountMeta, Instruction},
|
||||
pubkey::Pubkey,
|
||||
};
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||
// --- seeds -------------------------------------------------------------
|
||||
|
||||
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 (`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_VIRTUAL_USDC_RESERVES: u64 = 4_292_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 {
|
||||
@@ -59,8 +58,17 @@ pub mod global_constants {
|
||||
is_writable: true,
|
||||
};
|
||||
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
||||
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
|
||||
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
|
||||
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
|
||||
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
|
||||
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
|
||||
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
|
||||
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
|
||||
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
|
||||
];
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
|
||||
pub const MAYHEM_FEE_RECIPIENT_META: solana_sdk::instruction::AccountMeta =
|
||||
solana_sdk::instruction::AccountMeta {
|
||||
pubkey: MAYHEM_FEE_RECIPIENT,
|
||||
@@ -68,7 +76,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 {
|
||||
@@ -77,49 +84,57 @@ 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
|
||||
|
||||
pub const PROTOCOL_EXTRA_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
|
||||
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
|
||||
pubkey!("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
|
||||
pubkey!("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
|
||||
pubkey!("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
|
||||
pubkey!("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
|
||||
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,
|
||||
@@ -156,17 +171,156 @@ 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];
|
||||
|
||||
pub struct Symbol;
|
||||
/// `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];
|
||||
|
||||
impl Symbol {
|
||||
pub const SOLANA: &'static str = "solana";
|
||||
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];
|
||||
|
||||
pub(crate) const SHARING_CONFIG_STATUS_ACTIVE: u8 = 1;
|
||||
|
||||
// --- Fee recipient pools -----------------------------------------------
|
||||
|
||||
#[inline]
|
||||
pub fn is_mayhem_fee_recipient(pubkey: &Pubkey) -> bool {
|
||||
global_constants::MAYHEM_FEE_RECIPIENTS.contains(pubkey)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_amm_fee_recipient(pubkey: &Pubkey) -> bool {
|
||||
pubkey == &global_constants::PUMPFUN_AMM_FEE_1
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_2
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_3
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_4
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_5
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_6
|
||||
|| pubkey == &global_constants::PUMPFUN_AMM_FEE_7
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_standard_bonding_fee_recipient(pubkey: &Pubkey) -> bool {
|
||||
*pubkey == global_constants::FEE_RECIPIENT
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn reconcile_mayhem_mode_for_trade(
|
||||
mayhem_from_event: Option<bool>,
|
||||
fee_recipient: &Pubkey,
|
||||
) -> bool {
|
||||
if *fee_recipient == Pubkey::default() {
|
||||
return mayhem_from_event.unwrap_or(false);
|
||||
}
|
||||
let fee_m = is_mayhem_fee_recipient(fee_recipient);
|
||||
let fee_s = is_standard_bonding_fee_recipient(fee_recipient);
|
||||
match mayhem_from_event {
|
||||
Some(log_m) => {
|
||||
if fee_m && !log_m {
|
||||
true
|
||||
} else if fee_s && log_m && !fee_m {
|
||||
false
|
||||
} else {
|
||||
log_m
|
||||
}
|
||||
}
|
||||
None => fee_m,
|
||||
}
|
||||
}
|
||||
|
||||
#[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);
|
||||
let is_amm = is_amm_fee_recipient(pk);
|
||||
let is_s = is_standard_bonding_fee_recipient(pk);
|
||||
if is_mayhem_mode {
|
||||
is_m || (!is_s && !is_amm && *pk != Pubkey::default())
|
||||
} else {
|
||||
is_s || (!is_m && !is_amm && *pk != Pubkey::default())
|
||||
}
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
|
||||
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
|
||||
.choose(&mut rand::rng())
|
||||
.unwrap_or(&global_constants::MAYHEM_FEE_RECIPIENTS[0]);
|
||||
AccountMeta { pubkey: recipient, is_signer: false, is_writable: true }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_standard_fee_recipient_meta_random() -> AccountMeta {
|
||||
// Historical name kept for API compatibility. Do not randomize across static AMM fee
|
||||
// recipients for bonding-curve buy/sell; stale AMM protocol fee accounts can fail
|
||||
// Pump.fun authorization with error 6000 when Global has rotated.
|
||||
AccountMeta { pubkey: global_constants::FEE_RECIPIENT, is_signer: false, is_writable: true }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_protocol_extra_fee_recipient_random() -> Pubkey {
|
||||
*global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS
|
||||
.choose(&mut rand::rng())
|
||||
.unwrap_or(&global_constants::PROTOCOL_EXTRA_FEE_RECIPIENTS[0])
|
||||
}
|
||||
|
||||
/// Buyback fee recipient (#9 in buy_v2/sell_v2) — dedicated pool, distinct from protocol extra fee recipients.
|
||||
#[inline]
|
||||
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 {
|
||||
get_standard_fee_recipient_meta_random()
|
||||
}
|
||||
}
|
||||
|
||||
// --- Extend bonding curve (cold path) --------------------------------
|
||||
|
||||
#[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(
|
||||
@@ -174,13 +328,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(
|
||||
@@ -188,8 +340,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)
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -199,13 +350,11 @@ 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()));
|
||||
if creator_vault_pda.eq(&DEFAULT_CREATOR_VAULT.unwrap()) {
|
||||
Pubkey::default()
|
||||
} else {
|
||||
*creator_vault_pda
|
||||
match DEFAULT_CREATOR_VAULT.as_ref() {
|
||||
Some(default) if creator_vault_pda.eq(default) => Pubkey::default(),
|
||||
_ => *creator_vault_pda,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -217,45 +366,90 @@ 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)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_fee_sharing_config_pda(mint: &Pubkey) -> Option<Pubkey> {
|
||||
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)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn phantom_default_creator_vault() -> Pubkey {
|
||||
solana_sdk::pubkey!("2DR3iqRPVThyRLVJnwjPW1qiGWrp8RUFfHVjMbZyhdNc")
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_phantom_default_creator_vault(pk: &Pubkey) -> bool {
|
||||
*pk == phantom_default_creator_vault()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn resolve_creator_vault_for_ix(
|
||||
creator: &Pubkey,
|
||||
creator_vault_from_event: Pubkey,
|
||||
mint: &Pubkey,
|
||||
) -> Option<Pubkey> {
|
||||
resolve_creator_vault_for_ix_with_fee_sharing(creator, creator_vault_from_event, mint, None)
|
||||
}
|
||||
|
||||
/// 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,
|
||||
fee_sharing_creator_vault_if_active: Option<Pubkey>,
|
||||
) -> Option<Pubkey> {
|
||||
let phantom = phantom_default_creator_vault();
|
||||
|
||||
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() {
|
||||
return None;
|
||||
}
|
||||
|
||||
get_creator_vault_pda(creator)
|
||||
}
|
||||
|
||||
#[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 seed: &[&[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)
|
||||
Pubkey::try_find_program_address(seed, program_id).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"))?;
|
||||
|
||||
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))?;
|
||||
|
||||
Ok((Arc::new(bonding_curve), bonding_curve_pda))
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn get_buy_price(
|
||||
amount: u64,
|
||||
@@ -275,3 +469,276 @@ pub fn get_buy_price(
|
||||
|
||||
s_u64.min(real_token_reserves)
|
||||
}
|
||||
|
||||
// --- RPC -------------------------------------------------------------
|
||||
|
||||
#[inline]
|
||||
pub async fn fetch_fee_sharing_creator_vault_if_active(
|
||||
rpc: &SolanaRpcClient,
|
||||
mint: &Pubkey,
|
||||
) -> Result<Option<Pubkey>, anyhow::Error> {
|
||||
let Some(config_pda) = get_fee_sharing_config_pda(mint) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let acc = match rpc.get_account(&config_pda).await {
|
||||
Ok(a) => a,
|
||||
Err(_) => return Ok(None),
|
||||
};
|
||||
if acc.owner != accounts::FEE_PROGRAM {
|
||||
return Ok(None);
|
||||
}
|
||||
let d = acc.data.as_slice();
|
||||
if d.len() < 43 || d[..8] != SHARING_CONFIG_ACCOUNT_DISCRIMINATOR {
|
||||
return Ok(None);
|
||||
}
|
||||
if d[10] != SHARING_CONFIG_STATUS_ACTIVE {
|
||||
return Ok(None);
|
||||
}
|
||||
let mint_on_chain = Pubkey::new_from_array(
|
||||
d[11..43].try_into().map_err(|_| anyhow!("SharingConfig mint slice"))?,
|
||||
);
|
||||
if mint_on_chain != *mint {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(get_creator_vault_pda(&config_pda))
|
||||
}
|
||||
|
||||
#[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_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"));
|
||||
}
|
||||
|
||||
// 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))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
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]
|
||||
fn pumpfun_discriminators_are_8_bytes() {
|
||||
assert_eq!(BUY_DISCRIMINATOR.len(), 8);
|
||||
assert_eq!(BUY_EXACT_SOL_IN_DISCRIMINATOR.len(), 8);
|
||||
assert_eq!(SELL_DISCRIMINATOR.len(), 8);
|
||||
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]
|
||||
fn pumpfun_bonding_curve_and_v2_pda_differ_for_same_mint() {
|
||||
let mint = Pubkey::new_unique();
|
||||
let pda = get_bonding_curve_pda(&mint).unwrap();
|
||||
let pda_v2 = get_bonding_curve_v2_pda(&mint).unwrap();
|
||||
assert_ne!(pda, pda_v2, "bonding_curve and bonding_curve_v2 PDAs must differ");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpfun_creator_vault_pda_deterministic() {
|
||||
let creator = Pubkey::new_unique();
|
||||
let a = get_creator_vault_pda(&creator).unwrap();
|
||||
let b = get_creator_vault_pda(&creator).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fee_sharing_config_pda_deterministic() {
|
||||
let mint = Pubkey::new_unique();
|
||||
let a = get_fee_sharing_config_pda(&mint).unwrap();
|
||||
let b = get_fee_sharing_config_pda(&mint).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn default_creator_yields_fixed_creator_vault() {
|
||||
let v = get_creator_vault_pda(&Pubkey::default()).unwrap();
|
||||
assert_eq!(
|
||||
v,
|
||||
phantom_default_creator_vault(),
|
||||
"phantom vault constant must match PDA(default creator)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_uses_ix_vault_when_creator_borsh_is_default() {
|
||||
let mint = Pubkey::new_unique();
|
||||
let ix_vault = Pubkey::new_unique();
|
||||
let resolved = resolve_creator_vault_for_ix(&Pubkey::default(), ix_vault, &mint);
|
||||
assert_eq!(resolved, Some(ix_vault));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_returns_none_when_creator_and_vault_missing() {
|
||||
let mint = Pubkey::new_unique();
|
||||
assert_eq!(
|
||||
resolve_creator_vault_for_ix(&Pubkey::default(), Pubkey::default(), &mint),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_rejects_phantom_vault_when_creator_borsh_is_default() {
|
||||
let mint = Pubkey::new_unique();
|
||||
assert_eq!(
|
||||
resolve_creator_vault_for_ix(
|
||||
&Pubkey::default(),
|
||||
phantom_default_creator_vault(),
|
||||
&mint,
|
||||
),
|
||||
None
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_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));
|
||||
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)"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolve_remaps_phantom_vault_when_creator_known() {
|
||||
let creator = Pubkey::new_unique();
|
||||
let mint = Pubkey::new_unique();
|
||||
let expected = get_creator_vault_pda(&creator).unwrap();
|
||||
assert_eq!(
|
||||
resolve_creator_vault_for_ix(&creator, phantom_default_creator_vault(), &mint),
|
||||
Some(expected)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
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();
|
||||
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, vs, &mint, None);
|
||||
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]
|
||||
fn reconcile_mayhem_prefers_fee_when_log_says_false_but_fee_is_mayhem_pool() {
|
||||
let fee = global_constants::MAYHEM_FEE_RECIPIENTS[0];
|
||||
assert!(reconcile_mayhem_mode_for_trade(Some(false), &fee));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reconcile_mayhem_prefers_fee_when_log_says_true_but_fee_is_standard_pool() {
|
||||
let fee = global_constants::FEE_RECIPIENT;
|
||||
assert!(!reconcile_mayhem_mode_for_trade(Some(true), &fee));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pump_fee_meta_rejects_amm_fee_when_building_mayhem_ix() {
|
||||
let fee = global_constants::PUMPFUN_AMM_FEE_4;
|
||||
let m = pump_fun_fee_recipient_meta(fee, true);
|
||||
assert!(
|
||||
global_constants::MAYHEM_FEE_RECIPIENTS.contains(&m.pubkey),
|
||||
"expected fallback to mayhem pool, got {}",
|
||||
m.pubkey
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pump_fee_meta_uses_observed_non_amm_fee_for_standard_ix() {
|
||||
let fee = Pubkey::new_unique();
|
||||
let m = pump_fun_fee_recipient_meta(fee, false);
|
||||
assert_eq!(m.pubkey, fee);
|
||||
assert!(m.is_writable);
|
||||
assert!(!m.is_signer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pump_fee_meta_rejects_amm_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, global_constants::FEE_RECIPIENT);
|
||||
assert!(m.is_writable);
|
||||
assert!(!m.is_signer);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pump_fee_meta_default_standard_uses_main_fee_recipient() {
|
||||
let m = pump_fun_fee_recipient_meta(Pubkey::default(), false);
|
||||
assert_eq!(m.pubkey, global_constants::FEE_RECIPIENT);
|
||||
assert!(m.is_writable);
|
||||
assert!(!m.is_signer);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,12 +2,23 @@ use crate::{
|
||||
common::{
|
||||
spl_associated_token_account::get_associated_token_address_with_program_id, SolanaRpcClient,
|
||||
},
|
||||
constants::TOKEN_PROGRAM,
|
||||
constants::{TOKEN_PROGRAM, WSOL_TOKEN_ACCOUNT},
|
||||
instruction::utils::pumpswap_types::{pool_decode, Pool},
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use once_cell::sync::Lazy;
|
||||
use parking_lot::RwLock;
|
||||
use rand::seq::IndexedRandom;
|
||||
use solana_account_decoder::UiAccountEncoding;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
use solana_sdk::{instruction::AccountMeta, pubkey::Pubkey};
|
||||
use std::sync::{
|
||||
atomic::{AtomicBool, Ordering},
|
||||
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)
|
||||
|
||||
/// Constants used as seeds for deriving PDAs (Program Derived Addresses)
|
||||
pub mod seeds {
|
||||
@@ -29,6 +40,10 @@ pub mod seeds {
|
||||
|
||||
/// Seed for pool v2 PDA (required by program upgrade, readonly at end of account list)
|
||||
pub const POOL_V2_SEED: &[u8] = b"pool-v2";
|
||||
/// Legacy pool PDA seed (used with index, creator, base_mint, quote_mint)
|
||||
pub const POOL_SEED: &[u8] = b"pool";
|
||||
/// Pump program: pool-authority PDA seed (creator for canonical pool)
|
||||
pub const POOL_AUTHORITY_SEED: &[u8] = b"pool-authority";
|
||||
}
|
||||
|
||||
/// Constants related to program accounts and authorities
|
||||
@@ -53,6 +68,8 @@ pub mod accounts {
|
||||
pubkey!("62qc2CNXwrYqQScmEdiZFFAnJR262PxWEuNQtxfafNgV");
|
||||
|
||||
pub const AMM_PROGRAM: Pubkey = pubkey!("pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA");
|
||||
/// Pump Bonding Curve program(canonical pool 的 creator 来自此程序的 pool-authority PDA)
|
||||
pub const PUMP_PROGRAM_ID: Pubkey = pubkey!("6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P");
|
||||
|
||||
pub const LP_FEE_BASIS_POINTS: u64 = 25;
|
||||
pub const PROTOCOL_FEE_BASIS_POINTS: u64 = 5;
|
||||
@@ -68,9 +85,33 @@ pub mod accounts {
|
||||
pub const DEFAULT_COIN_CREATOR_VAULT_AUTHORITY: Pubkey =
|
||||
pubkey!("8N3GDaZ2iwN65oxVatKTLPNooAVUJTbfiVJ1ahyqwjSk");
|
||||
|
||||
/// Mayhem fee recipient (for mayhem mode coins)
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey =
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS");
|
||||
/// Mayhem fee recipients (pump-public-docs: use any one randomly for throughput)
|
||||
pub const MAYHEM_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("GesfTA3X2arioaHp8bbKdjG9vJtskViWACZoYvxp4twS"),
|
||||
pubkey!("4budycTjhs9fD6xw62VBducVTNgMgJJ5BgtKq7mAZwn6"),
|
||||
pubkey!("8SBKzEQU4nLSzcwF4a74F2iaUDQyTfjGndn6qUWBnrpR"),
|
||||
pubkey!("4UQeTP1T39KZ9Sfxzo3WR5skgsaP6NZa87BAkuazLEKH"),
|
||||
pubkey!("8sNeir4QsLsJdYpc9RZacohhK1Y5FLU3nC5LXgYB4aa6"),
|
||||
pubkey!("Fh9HmeLNUMVCvejxCtCL2DbYaRyBFVJ5xrWkLnMH6fdk"),
|
||||
pubkey!("463MEnMeGyJekNZFQSTUABBEbLnvMTALbT6ZmsxAbAdq"),
|
||||
pubkey!("6AUH3WEHucYZyC61hqpqYUWVto5qA5hjHuNQ32GNnNxA"),
|
||||
];
|
||||
/// Default Mayhem fee recipient (first of MAYHEM_FEE_RECIPIENTS)
|
||||
pub const MAYHEM_FEE_RECIPIENT: Pubkey = MAYHEM_FEE_RECIPIENTS[0];
|
||||
|
||||
/// Buyback trailing fee recipients (`GlobalConfig.buyback_fee_recipients` on Pump AMM).
|
||||
/// Must match one of these for the pubkey passed after optional `pool-v2` (`@pump-fun/pump-swap-sdk` `getBuybackFeeRecipient`).
|
||||
/// Static mirror of pump-public-docs; if protocol rotates configs, decode global_config from RPC.
|
||||
pub const PROTOCOL_EXTRA_FEE_RECIPIENTS: [Pubkey; 8] = [
|
||||
pubkey!("5YxQFdt3Tr9zJLvkFccqXVUwhdTWJQc1fFg2YPbxvxeD"),
|
||||
pubkey!("9M4giFFMxmFGXtc3feFzRai56WbBqehoSeRE5GK7gf7"),
|
||||
pubkey!("GXPFM2caqTtQYC2cJ5yJRi9VDkpsYZXzYdwYpGnLmtDL"),
|
||||
pubkey!("3BpXnfJaUTiwXnJNe7Ej1rcbzqTTQUvLShZaWazebsVR"),
|
||||
pubkey!("5cjcW9wExnJJiqgLjq7DEG75Pm6JBgE1hNv4B2vHXUW6"),
|
||||
pubkey!("EHAAiTxcdDwQ3U4bU6YcMsQGaekdzLS3B5SmYo46kJtL"),
|
||||
pubkey!("5eHhjP8JaYkz83CWwvGU2uMUXefd3AazWGx4gpcuEEYD"),
|
||||
pubkey!("A7hAgCzFw14fejgCp387JUJRMNyz4j89JKnhtKU8piqW"),
|
||||
];
|
||||
|
||||
// META
|
||||
|
||||
@@ -138,10 +179,439 @@ pub mod accounts {
|
||||
};
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct PumpSwapFeeBasisPoints {
|
||||
pub lp_fee_basis_points: u64,
|
||||
pub protocol_fee_basis_points: u64,
|
||||
pub coin_creator_fee_basis_points: u64,
|
||||
}
|
||||
|
||||
impl PumpSwapFeeBasisPoints {
|
||||
#[inline]
|
||||
pub const fn new(
|
||||
lp_fee_basis_points: u64,
|
||||
protocol_fee_basis_points: u64,
|
||||
coin_creator_fee_basis_points: u64,
|
||||
) -> Self {
|
||||
Self { lp_fee_basis_points, protocol_fee_basis_points, coin_creator_fee_basis_points }
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub const fn legacy_default() -> Self {
|
||||
Self::new(
|
||||
accounts::LP_FEE_BASIS_POINTS,
|
||||
accounts::PROTOCOL_FEE_BASIS_POINTS,
|
||||
accounts::COIN_CREATOR_FEE_BASIS_POINTS,
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for PumpSwapFeeBasisPoints {
|
||||
#[inline]
|
||||
fn default() -> Self {
|
||||
Self::legacy_default()
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PumpSwapFeeTier {
|
||||
pub market_cap_lamports_threshold: u128,
|
||||
pub fees: PumpSwapFeeBasisPoints,
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub struct PumpSwapFeeConfig {
|
||||
pub flat_fees: PumpSwapFeeBasisPoints,
|
||||
pub fee_tiers: Vec<PumpSwapFeeTier>,
|
||||
pub stable_fee_tiers: Vec<PumpSwapFeeTier>,
|
||||
}
|
||||
|
||||
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 PUMPSWAP_FEE_CONFIG_TTL: Duration = Duration::from_secs(300);
|
||||
const PUMPSWAP_FEE_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;
|
||||
const FEE_CONFIG_DISCRIMINATOR_LEN: usize = 8;
|
||||
const FEE_CONFIG_BUMP_LEN: usize = 1;
|
||||
const FEE_TIER_LEN: usize = 16 + U64_LEN * 3;
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct GlobalConfig {
|
||||
pub lp_fee_basis_points: u64,
|
||||
pub protocol_fee_basis_points: u64,
|
||||
pub coin_creator_fee_basis_points: u64,
|
||||
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,
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
struct CachedFeeConfig {
|
||||
fetched_at: Instant,
|
||||
config: PumpSwapFeeConfig,
|
||||
}
|
||||
|
||||
static GLOBAL_CONFIG_CACHE: Lazy<RwLock<Option<CachedGlobalConfig>>> =
|
||||
Lazy::new(|| RwLock::new(None));
|
||||
static GLOBAL_CONFIG_REFRESH_IN_FLIGHT: AtomicBool = AtomicBool::new(false);
|
||||
static FEE_CONFIG_CACHE: Lazy<RwLock<Option<CachedFeeConfig>>> = 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 read_u64(data: &[u8], offset: usize) -> Option<u64> {
|
||||
let bytes = data.get(offset..offset + U64_LEN)?;
|
||||
Some(u64::from_le_bytes(bytes.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn read_u128(data: &[u8], offset: usize) -> Option<u128> {
|
||||
let bytes = data.get(offset..offset + 16)?;
|
||||
Some(u128::from_le_bytes(bytes.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn read_u32(data: &[u8], offset: usize) -> Option<u32> {
|
||||
let bytes = data.get(offset..offset + 4)?;
|
||||
Some(u32::from_le_bytes(bytes.try_into().ok()?))
|
||||
}
|
||||
|
||||
fn decode_global_config(data: &[u8]) -> Option<GlobalConfig> {
|
||||
let mut offset = GLOBAL_CONFIG_DISCRIMINATOR_LEN;
|
||||
offset += PUBKEY_LEN; // admin
|
||||
let lp_fee_basis_points = read_u64(data, offset)?;
|
||||
offset += U64_LEN;
|
||||
let protocol_fee_basis_points = read_u64(data, offset)?;
|
||||
offset += U64_LEN;
|
||||
offset += U8_LEN; // disable_flags
|
||||
|
||||
let protocol_fee_recipients = read_pubkey_array::<8>(data, offset)?;
|
||||
offset += PUBKEY_LEN * 8;
|
||||
let coin_creator_fee_basis_points = read_u64(data, offset)?;
|
||||
offset += U64_LEN;
|
||||
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 {
|
||||
lp_fee_basis_points,
|
||||
protocol_fee_basis_points,
|
||||
coin_creator_fee_basis_points,
|
||||
protocol_fee_recipients,
|
||||
reserved_fee_recipient,
|
||||
reserved_fee_recipients,
|
||||
buyback_fee_recipients,
|
||||
})
|
||||
}
|
||||
|
||||
fn decode_fees(data: &[u8], offset: usize) -> Option<PumpSwapFeeBasisPoints> {
|
||||
Some(PumpSwapFeeBasisPoints::new(
|
||||
read_u64(data, offset)?,
|
||||
read_u64(data, offset + U64_LEN)?,
|
||||
read_u64(data, offset + U64_LEN * 2)?,
|
||||
))
|
||||
}
|
||||
|
||||
fn decode_fee_tiers(data: &[u8], offset: &mut usize) -> Option<Vec<PumpSwapFeeTier>> {
|
||||
let len = read_u32(data, *offset)? as usize;
|
||||
*offset += 4;
|
||||
let byte_len = len.checked_mul(FEE_TIER_LEN)?;
|
||||
let end = (*offset).checked_add(byte_len)?;
|
||||
data.get(*offset..end)?;
|
||||
|
||||
let mut tiers = Vec::with_capacity(len);
|
||||
for _ in 0..len {
|
||||
let market_cap_lamports_threshold = read_u128(data, *offset)?;
|
||||
*offset += 16;
|
||||
let fees = decode_fees(data, *offset)?;
|
||||
*offset += U64_LEN * 3;
|
||||
tiers.push(PumpSwapFeeTier { market_cap_lamports_threshold, fees });
|
||||
}
|
||||
Some(tiers)
|
||||
}
|
||||
|
||||
pub fn decode_fee_config(data: &[u8]) -> Option<PumpSwapFeeConfig> {
|
||||
let mut offset = FEE_CONFIG_DISCRIMINATOR_LEN;
|
||||
offset += FEE_CONFIG_BUMP_LEN;
|
||||
offset += PUBKEY_LEN; // admin
|
||||
|
||||
let flat_fees = decode_fees(data, offset)?;
|
||||
offset += U64_LEN * 3;
|
||||
|
||||
let fee_tiers = decode_fee_tiers(data, &mut offset)?;
|
||||
let stable_fee_tiers = decode_fee_tiers(data, &mut offset)?;
|
||||
|
||||
Some(PumpSwapFeeConfig { flat_fees, fee_tiers, stable_fee_tiers })
|
||||
}
|
||||
|
||||
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)
|
||||
}
|
||||
|
||||
async fn refresh_fee_config_once(rpc: &SolanaRpcClient) -> Option<PumpSwapFeeConfig> {
|
||||
let account = match tokio::time::timeout(
|
||||
PUMPSWAP_FEE_CONFIG_RPC_TIMEOUT,
|
||||
rpc.get_account(&accounts::FEE_CONFIG),
|
||||
)
|
||||
.await
|
||||
{
|
||||
Ok(Ok(account)) => account,
|
||||
Ok(Err(e)) => {
|
||||
warn!(target: "pumpswap_fee_config", "PumpSwap FeeConfig 读取失败: {}", e);
|
||||
return None;
|
||||
}
|
||||
Err(_) => {
|
||||
warn!(
|
||||
target: "pumpswap_fee_config",
|
||||
timeout_ms = PUMPSWAP_FEE_CONFIG_RPC_TIMEOUT.as_millis(),
|
||||
"PumpSwap FeeConfig 读取超时"
|
||||
);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
|
||||
let Some(config) = decode_fee_config(&account.data) else {
|
||||
warn!(
|
||||
target: "pumpswap_fee_config",
|
||||
data_len = account.data.len(),
|
||||
"PumpSwap FeeConfig 解析失败"
|
||||
);
|
||||
return None;
|
||||
};
|
||||
|
||||
*FEE_CONFIG_CACHE.write() =
|
||||
Some(CachedFeeConfig { 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 && !GLOBAL_CONFIG_REFRESH_IN_FLIGHT.swap(true, Ordering::AcqRel) {
|
||||
let rpc = Arc::clone(rpc);
|
||||
tokio::spawn(async move {
|
||||
let _ = refresh_global_config_once(rpc.as_ref()).await;
|
||||
let _ = refresh_fee_config_once(rpc.as_ref()).await;
|
||||
GLOBAL_CONFIG_REFRESH_IN_FLIGHT.store(false, Ordering::Release);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
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 cached_fee_config() -> Option<PumpSwapFeeConfig> {
|
||||
let guard = FEE_CONFIG_CACHE.read();
|
||||
let cached = guard.as_ref()?;
|
||||
(cached.fetched_at.elapsed() <= PUMPSWAP_FEE_CONFIG_TTL).then(|| cached.config.clone())
|
||||
}
|
||||
|
||||
pub async fn fetch_fee_config(rpc: &SolanaRpcClient) -> Option<PumpSwapFeeConfig> {
|
||||
if let Some(config) = cached_fee_config() {
|
||||
return Some(config);
|
||||
}
|
||||
refresh_fee_config_once(rpc).await
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn global_fee_basis_points() -> PumpSwapFeeBasisPoints {
|
||||
cached_global_config()
|
||||
.map(|config| {
|
||||
PumpSwapFeeBasisPoints::new(
|
||||
config.lp_fee_basis_points,
|
||||
config.protocol_fee_basis_points,
|
||||
config.coin_creator_fee_basis_points,
|
||||
)
|
||||
})
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn is_canonical_pump_pool(base_mint: &Pubkey, pool_creator: &Pubkey) -> bool {
|
||||
get_pump_pool_authority_pda(base_mint) == *pool_creator
|
||||
}
|
||||
|
||||
#[inline]
|
||||
pub fn pool_market_cap_lamports(
|
||||
base_mint_supply: u64,
|
||||
base_reserve: u64,
|
||||
quote_reserve: u64,
|
||||
) -> Option<u128> {
|
||||
if base_reserve == 0 {
|
||||
return None;
|
||||
}
|
||||
Some((quote_reserve as u128) * (base_mint_supply as u128) / (base_reserve as u128))
|
||||
}
|
||||
|
||||
pub fn calculate_fee_tier(
|
||||
fee_tiers: &[PumpSwapFeeTier],
|
||||
market_cap_lamports: u128,
|
||||
) -> Option<PumpSwapFeeBasisPoints> {
|
||||
let first = fee_tiers.first()?;
|
||||
if market_cap_lamports < first.market_cap_lamports_threshold {
|
||||
return Some(first.fees);
|
||||
}
|
||||
fee_tiers
|
||||
.iter()
|
||||
.rev()
|
||||
.find(|tier| market_cap_lamports >= tier.market_cap_lamports_threshold)
|
||||
.map(|tier| tier.fees)
|
||||
.or(Some(first.fees))
|
||||
}
|
||||
|
||||
pub fn compute_fee_basis_points(
|
||||
fee_config: Option<&PumpSwapFeeConfig>,
|
||||
pool_creator: Pubkey,
|
||||
base_mint: Pubkey,
|
||||
base_mint_supply: Option<u64>,
|
||||
base_reserve: u64,
|
||||
quote_reserve: u64,
|
||||
) -> PumpSwapFeeBasisPoints {
|
||||
let Some(fee_config) = fee_config else {
|
||||
return global_fee_basis_points();
|
||||
};
|
||||
|
||||
if !is_canonical_pump_pool(&base_mint, &pool_creator) {
|
||||
return fee_config.flat_fees;
|
||||
}
|
||||
|
||||
let Some(base_mint_supply) = base_mint_supply else {
|
||||
return global_fee_basis_points();
|
||||
};
|
||||
let Some(market_cap_lamports) =
|
||||
pool_market_cap_lamports(base_mint_supply, base_reserve, quote_reserve)
|
||||
else {
|
||||
return global_fee_basis_points();
|
||||
};
|
||||
|
||||
calculate_fee_tier(&fee_config.fee_tiers, market_cap_lamports).unwrap_or(fee_config.flat_fees)
|
||||
}
|
||||
|
||||
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 = 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 {
|
||||
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.
|
||||
#[inline]
|
||||
pub fn get_pool_v2_pda(base_mint: &Pubkey) -> Option<Pubkey> {
|
||||
@@ -152,6 +622,35 @@ pub fn get_pool_v2_pda(base_mint: &Pubkey) -> Option<Pubkey> {
|
||||
Some(pda)
|
||||
}
|
||||
|
||||
/// Pump 程序上的 pool-authority PDA(canonical pool 的 creator),与 @pump-fun/pump-swap-sdk 一致。
|
||||
#[inline]
|
||||
pub fn get_pump_pool_authority_pda(mint: &Pubkey) -> Pubkey {
|
||||
Pubkey::find_program_address(
|
||||
&[seeds::POOL_AUTHORITY_SEED, mint.as_ref()],
|
||||
&accounts::PUMP_PROGRAM_ID,
|
||||
)
|
||||
.0
|
||||
}
|
||||
|
||||
/// Canonical Pump 池 PDA:index=0,creator=pumpPoolAuthorityPda(mint),base_mint=mint,quote_mint=WSOL。
|
||||
/// 与 @pump-fun/pump-swap-sdk 的 canonicalPumpPoolPda(mint) 一致,用于从 bonding curve 迁移后的标准池查找。
|
||||
#[inline]
|
||||
pub fn get_canonical_pool_pda(mint: &Pubkey) -> Pubkey {
|
||||
const CANONICAL_POOL_INDEX: u16 = 0;
|
||||
let authority = get_pump_pool_authority_pda(mint);
|
||||
let (pda, _) = Pubkey::find_program_address(
|
||||
&[
|
||||
seeds::POOL_SEED,
|
||||
&CANONICAL_POOL_INDEX.to_le_bytes(),
|
||||
authority.as_ref(),
|
||||
mint.as_ref(),
|
||||
WSOL_TOKEN_ACCOUNT.as_ref(),
|
||||
],
|
||||
&accounts::AMM_PROGRAM,
|
||||
);
|
||||
pda
|
||||
}
|
||||
|
||||
// Find a pool for a specific mint
|
||||
pub async fn find_pool(rpc: &SolanaRpcClient, mint: &Pubkey) -> Result<Pubkey, anyhow::Error> {
|
||||
let (pool_address, _) = find_by_mint(rpc, mint).await?;
|
||||
@@ -191,14 +690,14 @@ pub fn get_user_volume_accumulator_pda(user: &Pubkey) -> Option<Pubkey> {
|
||||
crate::common::fast_fn::PdaCacheKey::PumpSwapUserVolume(*user),
|
||||
|| {
|
||||
let seeds: &[&[u8]; 2] = &[&seeds::USER_VOLUME_ACCUMULATOR_SEED, user.as_ref()];
|
||||
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
|
||||
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
},
|
||||
)
|
||||
}
|
||||
|
||||
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (used for cashback remaining accounts).
|
||||
/// WSOL ATA of UserVolumeAccumulator for Pump AMM (buy cashback: remaining_accounts[0] 官方用 NATIVE_MINT).
|
||||
pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
|
||||
let accumulator = get_user_volume_accumulator_pda(user)?;
|
||||
Some(crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
@@ -208,9 +707,23 @@ pub fn get_user_volume_accumulator_wsol_ata(user: &Pubkey) -> Option<Pubkey> {
|
||||
))
|
||||
}
|
||||
|
||||
/// Quote-mint ATA of UserVolumeAccumulator(sell cashback 时官方用 quoteMint,非固定 WSOL).
|
||||
pub fn get_user_volume_accumulator_quote_ata(
|
||||
user: &Pubkey,
|
||||
quote_mint: &Pubkey,
|
||||
quote_token_program: &Pubkey,
|
||||
) -> Option<Pubkey> {
|
||||
let accumulator = get_user_volume_accumulator_pda(user)?;
|
||||
Some(crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
&accumulator,
|
||||
quote_mint,
|
||||
quote_token_program,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn get_global_volume_accumulator_pda() -> Option<Pubkey> {
|
||||
let seeds: &[&[u8]; 1] = &[&seeds::GLOBAL_VOLUME_ACCUMULATOR_SEED];
|
||||
let program_id: &Pubkey = &&accounts::AMM_PROGRAM;
|
||||
let program_id: &Pubkey = &accounts::AMM_PROGRAM;
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
}
|
||||
@@ -227,19 +740,23 @@ pub async fn fetch_pool(
|
||||
Ok(pool)
|
||||
}
|
||||
|
||||
pub async fn find_by_base_mint(
|
||||
/// Known pool account sizes: 252 (SPL Token) and 643 (Token2022)
|
||||
const POOL_DATA_LEN_SPL: u64 = 8 + 244;
|
||||
const POOL_DATA_LEN_T22: u64 = 643;
|
||||
|
||||
/// Run getProgramAccounts with a Memcmp filter, querying both pool sizes in parallel.
|
||||
async fn get_program_accounts_both_sizes(
|
||||
rpc: &SolanaRpcClient,
|
||||
base_mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
// Use getProgramAccounts to find pools for the given mint
|
||||
let filters = vec![
|
||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(43, &base_mint.to_bytes()),
|
||||
),
|
||||
];
|
||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
||||
filters: Some(filters),
|
||||
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,
|
||||
@@ -251,95 +768,114 @@ pub async fn find_by_base_mint(
|
||||
};
|
||||
let program_id = accounts::AMM_PROGRAM;
|
||||
#[allow(deprecated)]
|
||||
let accounts = rpc.get_program_accounts_with_config(&program_id, config).await?;
|
||||
if accounts.is_empty() {
|
||||
return Err(anyhow!("No pool found for mint {}", base_mint));
|
||||
}
|
||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
||||
let mut pools: Vec<_> = accounts
|
||||
let (spl_result, t22_result) = tokio::join!(
|
||||
rpc.get_program_accounts_with_config(&program_id, make_config(POOL_DATA_LEN_SPL)),
|
||||
rpc.get_program_accounts_with_config(&program_id, make_config(POOL_DATA_LEN_T22)),
|
||||
);
|
||||
let mut all = spl_result.unwrap_or_default();
|
||||
all.extend(t22_result.unwrap_or_default());
|
||||
Ok(all)
|
||||
}
|
||||
|
||||
fn decode_pool_accounts(
|
||||
accounts: Vec<(Pubkey, solana_sdk::account::Account)>,
|
||||
) -> Vec<(Pubkey, Pool)> {
|
||||
accounts
|
||||
.into_iter()
|
||||
.filter_map(|(addr, acc)| {
|
||||
// 🔧 修复:跳过8字节的discriminator
|
||||
if acc.data.len() > 8 {
|
||||
pool_decode(&acc.data[8..]).map(|pool| (addr, pool))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
.collect()
|
||||
}
|
||||
|
||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
||||
if pools.is_empty() {
|
||||
return Err(anyhow!("No valid pool decoded for mint {} (found {} accounts but all decode failed)", base_mint, accounts_count));
|
||||
pub async fn find_by_base_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
base_mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
// base_mint offset: 8(discriminator) + 1(bump) + 2(index) + 32(creator) = 43
|
||||
let accounts = get_program_accounts_both_sizes(rpc, 43, base_mint).await?;
|
||||
if accounts.is_empty() {
|
||||
return Err(anyhow!("No pool found for mint {}", base_mint));
|
||||
}
|
||||
let mut pools = decode_pool_accounts(accounts);
|
||||
if pools.is_empty() {
|
||||
return Err(anyhow!("No valid pool decoded for mint {}", base_mint));
|
||||
}
|
||||
|
||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||
let (address, pool) = pools[0].clone();
|
||||
Ok((address, pool))
|
||||
Ok((pools[0].0, pools[0].1.clone()))
|
||||
}
|
||||
|
||||
pub async fn find_by_quote_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
quote_mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
// Use getProgramAccounts to find pools for the given mint
|
||||
let filters = vec![
|
||||
// solana_rpc_client_api::filter::RpcFilterType::DataSize(211), // Pool account size
|
||||
solana_rpc_client_api::filter::RpcFilterType::Memcmp(
|
||||
solana_client::rpc_filter::Memcmp::new_base58_encoded(75, "e_mint.to_bytes()),
|
||||
),
|
||||
];
|
||||
let config = solana_rpc_client_api::config::RpcProgramAccountsConfig {
|
||||
filters: Some(filters),
|
||||
account_config: solana_rpc_client_api::config::RpcAccountInfoConfig {
|
||||
encoding: Some(UiAccountEncoding::Base64),
|
||||
data_slice: None,
|
||||
commitment: None,
|
||||
min_context_slot: None,
|
||||
},
|
||||
with_context: None,
|
||||
sort_results: None,
|
||||
};
|
||||
let program_id = accounts::AMM_PROGRAM;
|
||||
#[allow(deprecated)]
|
||||
let accounts = rpc.get_program_accounts_with_config(&program_id, config).await?;
|
||||
// quote_mint offset: 8 + 1 + 2 + 32 + 32 = 75
|
||||
let accounts = get_program_accounts_both_sizes(rpc, 75, quote_mint).await?;
|
||||
if accounts.is_empty() {
|
||||
return Err(anyhow!("No pool found for mint {}", quote_mint));
|
||||
}
|
||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
||||
let mut pools: Vec<_> = accounts
|
||||
.into_iter()
|
||||
.filter_map(|(addr, acc)| {
|
||||
// 🔧 修复:跳过8字节的discriminator
|
||||
if acc.data.len() > 8 {
|
||||
pool_decode(&acc.data[8..]).map(|pool| (addr, pool))
|
||||
} else {
|
||||
None
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
|
||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
||||
let mut pools = decode_pool_accounts(accounts);
|
||||
if pools.is_empty() {
|
||||
return Err(anyhow!("No valid pool decoded for quote_mint {} (found {} accounts but all decode failed)", quote_mint, accounts_count));
|
||||
return Err(anyhow!("No valid pool decoded for quote_mint {}", quote_mint));
|
||||
}
|
||||
|
||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||
let (address, pool) = pools[0].clone();
|
||||
Ok((address, pool))
|
||||
Ok((pools[0].0, pools[0].1.clone()))
|
||||
}
|
||||
|
||||
/// 按 mint 查找 PumpSwap 池(本函数仅用于 PumpSwap,其他 DEX 勿用)。
|
||||
///
|
||||
/// 查找顺序(与 @pump-fun/pump-swap-sdk 一致):
|
||||
/// 1. Pool v2 PDA ["pool-v2", base_mint] — 一次 getAccount
|
||||
/// 2. Canonical pool PDA ["pool", 0, pumpPoolAuthority(mint), mint, WSOL] — 迁移后的标准池
|
||||
/// 3. getProgramAccounts 按 base_mint / quote_mint 过滤
|
||||
pub async fn find_by_mint(
|
||||
rpc: &SolanaRpcClient,
|
||||
mint: &Pubkey,
|
||||
) -> Result<(Pubkey, Pool), anyhow::Error> {
|
||||
if let Ok((address, pool)) = find_by_base_mint(rpc, mint).await {
|
||||
return Ok((address, pool));
|
||||
let mut diag = Vec::<String>::new();
|
||||
|
||||
// 1. PumpSwap v2 PDA(seeds: ["pool-v2", base_mint])
|
||||
if let Some(pool_address) = get_pool_v2_pda(mint) {
|
||||
diag.push(format!("PDA(v2)={}", pool_address));
|
||||
match fetch_pool(rpc, &pool_address).await {
|
||||
Ok(pool) if pool.base_mint == *mint => return Ok((pool_address, pool)),
|
||||
Ok(_) => diag.push("PDA(v2) 账户存在但 base_mint 不匹配".into()),
|
||||
Err(e) => diag.push(format!("PDA(v2) get_account/decode 失败: {}", e)),
|
||||
}
|
||||
}
|
||||
if let Ok((address, pool)) = find_by_quote_mint(rpc, mint).await {
|
||||
return Ok((address, pool));
|
||||
|
||||
// 2. Canonical pool PDA(与 pump-swap-sdk canonicalPumpPoolPda(mint) 一致)
|
||||
let canonical_address = get_canonical_pool_pda(mint);
|
||||
diag.push(format!("canonical={}", canonical_address));
|
||||
match fetch_pool(rpc, &canonical_address).await {
|
||||
Ok(pool) if pool.base_mint == *mint => return Ok((canonical_address, pool)),
|
||||
Ok(_) => diag.push("canonical 账户存在但 base_mint 不匹配".into()),
|
||||
Err(e) => diag.push(format!("canonical get_account/decode 失败: {}", e)),
|
||||
}
|
||||
Err(anyhow!("No pool found for mint {}", mint))
|
||||
|
||||
// 3. Fallback: getProgramAccounts by base_mint / quote_mint (with 3s timeout to avoid blocking)
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_base_mint(rpc, mint))
|
||||
.await
|
||||
{
|
||||
Ok(Ok((address, pool))) => return Ok((address, pool)),
|
||||
Ok(Err(e)) => diag.push(format!("getProgramAccounts(base_mint): {}", e)),
|
||||
Err(_) => diag.push("getProgramAccounts(base_mint): timed out (3s)".into()),
|
||||
}
|
||||
match tokio::time::timeout(std::time::Duration::from_secs(3), find_by_quote_mint(rpc, mint))
|
||||
.await
|
||||
{
|
||||
Ok(Ok((address, pool))) => return Ok((address, pool)),
|
||||
Ok(Err(e)) => diag.push(format!("getProgramAccounts(quote_mint): {}", e)),
|
||||
Err(_) => diag.push("getProgramAccounts(quote_mint): timed out (3s)".into()),
|
||||
}
|
||||
|
||||
let diag_str = diag.join("; ");
|
||||
eprintln!("[find_by_mint] {} failed: {}", mint, diag_str);
|
||||
Err(anyhow!("No pool found for mint {}. diag: {}", mint, diag_str))
|
||||
}
|
||||
|
||||
pub async fn get_token_balances(
|
||||
@@ -362,3 +898,92 @@ pub fn get_fee_config_pda() -> Option<Pubkey> {
|
||||
let pda: Option<(Pubkey, u8)> = Pubkey::try_find_program_address(seeds, program_id);
|
||||
pda.map(|pubkey| pubkey.0)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
|
||||
fn fee_config_fixture() -> PumpSwapFeeConfig {
|
||||
PumpSwapFeeConfig {
|
||||
flat_fees: PumpSwapFeeBasisPoints::new(25, 5, 0),
|
||||
fee_tiers: vec![
|
||||
PumpSwapFeeTier {
|
||||
market_cap_lamports_threshold: 0,
|
||||
fees: PumpSwapFeeBasisPoints::new(2, 93, 30),
|
||||
},
|
||||
PumpSwapFeeTier {
|
||||
market_cap_lamports_threshold: 420_000_000_000,
|
||||
fees: PumpSwapFeeBasisPoints::new(20, 5, 95),
|
||||
},
|
||||
PumpSwapFeeTier {
|
||||
market_cap_lamports_threshold: 4_420_000_000_000,
|
||||
fees: PumpSwapFeeBasisPoints::new(20, 5, 75),
|
||||
},
|
||||
PumpSwapFeeTier {
|
||||
market_cap_lamports_threshold: 9_820_000_000_000,
|
||||
fees: PumpSwapFeeBasisPoints::new(20, 5, 70),
|
||||
},
|
||||
],
|
||||
stable_fee_tiers: Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_user_volume_accumulator_pda_deterministic() {
|
||||
let user = Pubkey::new_unique();
|
||||
let a = get_user_volume_accumulator_pda(&user).unwrap();
|
||||
let b = get_user_volume_accumulator_pda(&user).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_global_volume_accumulator_matches_constant() {
|
||||
let pda = get_global_volume_accumulator_pda().unwrap();
|
||||
assert_eq!(pda, accounts::GLOBAL_VOLUME_ACCUMULATOR);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_pool_v2_pda_deterministic() {
|
||||
let base_mint = Pubkey::new_unique();
|
||||
let a = get_pool_v2_pda(&base_mint).unwrap();
|
||||
let b = get_pool_v2_pda(&base_mint).unwrap();
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_fee_tier_selects_issue_106_fee_bucket() {
|
||||
let selected = calculate_fee_tier(&fee_config_fixture().fee_tiers, 4_500_000_000_000);
|
||||
assert_eq!(selected, Some(PumpSwapFeeBasisPoints::new(20, 5, 75)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_compute_fees_uses_flat_fee_for_non_canonical_pool() {
|
||||
let base_mint = Pubkey::new_unique();
|
||||
let non_canonical_creator = Pubkey::new_unique();
|
||||
let fees = compute_fee_basis_points(
|
||||
Some(&fee_config_fixture()),
|
||||
non_canonical_creator,
|
||||
base_mint,
|
||||
Some(1_000_000_000_000_000),
|
||||
1_000_000_000_000_000,
|
||||
4_500_000_000_000,
|
||||
);
|
||||
assert_eq!(fees, PumpSwapFeeBasisPoints::new(25, 5, 0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pumpswap_compute_fees_uses_tier_for_canonical_pool() {
|
||||
let base_mint = Pubkey::new_unique();
|
||||
let canonical_creator = get_pump_pool_authority_pda(&base_mint);
|
||||
let fees = compute_fee_basis_points(
|
||||
Some(&fee_config_fixture()),
|
||||
canonical_creator,
|
||||
base_mint,
|
||||
Some(1_000_000_000_000_000),
|
||||
1_000_000_000_000_000,
|
||||
4_500_000_000_000,
|
||||
);
|
||||
assert_eq!(fees, PumpSwapFeeBasisPoints::new(20, 5, 75));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -17,9 +17,12 @@ pub struct Pool {
|
||||
pub is_mayhem_mode: bool,
|
||||
/// Whether this pool's coin has cashback enabled
|
||||
pub is_cashback_coin: bool,
|
||||
/// Reserved for future fields (pump-public-docs: pool structure = 244 bytes total)
|
||||
pub _reserved: [u8; 7],
|
||||
}
|
||||
|
||||
pub const POOL_SIZE: usize = 1 + 2 + 32 * 6 + 8 + 32 + 1 + 1;
|
||||
/// Borsh 解码用的 Pool 长度。链上池为 244 字节(pump-public-docs Breaking Change),与 POOL_SIZE 一致。
|
||||
pub const POOL_SIZE: usize = 244;
|
||||
|
||||
pub fn pool_decode(data: &[u8]) -> Option<Pool> {
|
||||
if data.len() < POOL_SIZE {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::{
|
||||
common::SolanaRpcClient,
|
||||
instruction::utils::raydium_amm_v4_types::{amm_info_decode, AmmInfo},
|
||||
instruction::utils::raydium_amm_v4_types::{
|
||||
amm_info_decode, market_state_decode, AmmInfo, MarketState,
|
||||
},
|
||||
};
|
||||
use anyhow::anyhow;
|
||||
use solana_sdk::pubkey::Pubkey;
|
||||
@@ -40,3 +42,25 @@ pub async fn fetch_amm_info(rpc: &SolanaRpcClient, amm: Pubkey) -> Result<AmmInf
|
||||
amm_info_decode(&amm_info).ok_or_else(|| anyhow!("Failed to decode amm info"))?;
|
||||
Ok(amm_info)
|
||||
}
|
||||
|
||||
pub async fn fetch_market_state(
|
||||
rpc: &SolanaRpcClient,
|
||||
market: Pubkey,
|
||||
) -> Result<MarketState, anyhow::Error> {
|
||||
let market_data = rpc.get_account_data(&market).await?;
|
||||
market_state_decode(&market_data).ok_or_else(|| anyhow!("Failed to decode market state"))
|
||||
}
|
||||
|
||||
pub fn derive_serum_vault_signer(
|
||||
serum_program: &Pubkey,
|
||||
serum_market: &Pubkey,
|
||||
vault_signer_nonce: u64,
|
||||
) -> Result<Pubkey, anyhow::Error> {
|
||||
let nonce = vault_signer_nonce.to_le_bytes();
|
||||
Pubkey::create_program_address(&[serum_market.as_ref(), &nonce], serum_program)
|
||||
.or_else(|_| {
|
||||
let legacy_nonce = [vault_signer_nonce as u8];
|
||||
Pubkey::create_program_address(&[serum_market.as_ref(), &legacy_nonce], serum_program)
|
||||
})
|
||||
.map_err(|err| anyhow!("Failed to derive Serum vault signer: {}", err))
|
||||
}
|
||||
|
||||
@@ -77,3 +77,38 @@ pub fn amm_info_decode(data: &[u8]) -> Option<AmmInfo> {
|
||||
}
|
||||
borsh::from_slice::<AmmInfo>(&data[..AMM_INFO_SIZE]).ok()
|
||||
}
|
||||
|
||||
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, BorshDeserialize)]
|
||||
pub struct MarketState {
|
||||
pub padding: [u8; 5],
|
||||
pub account_flags: u64,
|
||||
pub own_address: Pubkey,
|
||||
pub vault_signer_nonce: u64,
|
||||
pub coin_mint: Pubkey,
|
||||
pub pc_mint: Pubkey,
|
||||
pub serum_coin_vault_account: Pubkey,
|
||||
pub coin_deposits_total: u64,
|
||||
pub coin_fees_accrued: u64,
|
||||
pub serum_pc_vault_account: Pubkey,
|
||||
pub pc_deposits_total: u64,
|
||||
pub pc_fees_accrued: u64,
|
||||
pub pc_dust_threshold: u64,
|
||||
pub request_queue: Pubkey,
|
||||
pub serum_event_queue: Pubkey,
|
||||
pub serum_bids: Pubkey,
|
||||
pub serum_asks: Pubkey,
|
||||
pub coin_lot_size: u64,
|
||||
pub pc_lot_size: u64,
|
||||
pub fee_rate_bps: u64,
|
||||
pub referrer_rebate_accrued: u64,
|
||||
pub padding2: [u8; 7],
|
||||
}
|
||||
|
||||
pub const MARKET_STATE_SIZE: usize = 388;
|
||||
|
||||
pub fn market_state_decode(data: &[u8]) -> Option<MarketState> {
|
||||
if data.len() < MARKET_STATE_SIZE {
|
||||
return None;
|
||||
}
|
||||
borsh::from_slice::<MarketState>(&data[..MARKET_STATE_SIZE]).ok()
|
||||
}
|
||||
|
||||
@@ -135,9 +135,11 @@ pub fn get_vault_account(
|
||||
) -> Pubkey {
|
||||
if protocol_params.base_mint == *token_mint && protocol_params.base_vault != Pubkey::default() {
|
||||
protocol_params.base_vault
|
||||
} else if protocol_params.quote_mint == *token_mint && protocol_params.quote_vault != Pubkey::default() {
|
||||
} else if protocol_params.quote_mint == *token_mint
|
||||
&& protocol_params.quote_vault != Pubkey::default()
|
||||
{
|
||||
protocol_params.quote_vault
|
||||
} else {
|
||||
get_vault_pda(pool_state, token_mint).unwrap()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+9
-977
@@ -1,3 +1,4 @@
|
||||
pub mod client;
|
||||
pub mod common;
|
||||
pub mod constants;
|
||||
pub mod instruction;
|
||||
@@ -5,981 +6,12 @@ pub mod perf;
|
||||
pub mod swqos;
|
||||
pub mod trading;
|
||||
pub mod utils;
|
||||
use crate::common::nonce_cache::DurableNonceInfo;
|
||||
use crate::common::sdk_log;
|
||||
use crate::common::GasFeeStrategy;
|
||||
use crate::common::{TradeConfig, InfrastructureConfig};
|
||||
#[cfg(feature = "perf-trace")]
|
||||
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
|
||||
use crate::constants::SOL_TOKEN_ACCOUNT;
|
||||
use crate::constants::USD1_TOKEN_ACCOUNT;
|
||||
use crate::constants::USDC_TOKEN_ACCOUNT;
|
||||
use crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||
use crate::swqos::common::TradeError;
|
||||
use crate::swqos::SwqosClient;
|
||||
use crate::swqos::SwqosConfig;
|
||||
use crate::swqos::TradeType;
|
||||
use crate::trading::core::params::BonkParams;
|
||||
use crate::trading::core::params::MeteoraDammV2Params;
|
||||
use crate::trading::core::params::PumpFunParams;
|
||||
use crate::trading::core::params::PumpSwapParams;
|
||||
use crate::trading::core::params::RaydiumAmmV4Params;
|
||||
use crate::trading::core::params::RaydiumCpmmParams;
|
||||
use crate::trading::core::params::DexParamEnum;
|
||||
use crate::trading::factory::DexType;
|
||||
use crate::trading::MiddlewareManager;
|
||||
use crate::trading::SwapParams;
|
||||
use crate::trading::TradeFactory;
|
||||
use common::SolanaRpcClient;
|
||||
use parking_lot::Mutex;
|
||||
use rustls::crypto::{ring::default_provider, CryptoProvider};
|
||||
use solana_sdk::hash::Hash;
|
||||
use solana_sdk::message::AddressLookupTableAccount;
|
||||
use solana_sdk::signer::Signer;
|
||||
use solana_sdk::{pubkey::Pubkey, signature::Keypair, signature::Signature};
|
||||
use std::sync::Arc;
|
||||
#[allow(unused_imports)]
|
||||
use tracing::{debug, error, info, warn};
|
||||
|
||||
/// Single place to validate that protocol params match the given DEX type (avoids duplicate match in buy/sell).
|
||||
#[inline(always)]
|
||||
fn validate_protocol_params(dex_type: DexType, params: &DexParamEnum) -> bool {
|
||||
match dex_type {
|
||||
DexType::PumpFun => params.as_any().downcast_ref::<PumpFunParams>().is_some(),
|
||||
DexType::PumpSwap => params.as_any().downcast_ref::<PumpSwapParams>().is_some(),
|
||||
DexType::Bonk => params.as_any().downcast_ref::<BonkParams>().is_some(),
|
||||
DexType::RaydiumCpmm => params.as_any().downcast_ref::<RaydiumCpmmParams>().is_some(),
|
||||
DexType::RaydiumAmmV4 => params.as_any().downcast_ref::<RaydiumAmmV4Params>().is_some(),
|
||||
DexType::MeteoraDammV2 => params.as_any().downcast_ref::<MeteoraDammV2Params>().is_some(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Type of the token to buy
|
||||
#[derive(Clone, PartialEq)]
|
||||
pub enum TradeTokenType {
|
||||
SOL,
|
||||
WSOL,
|
||||
USD1,
|
||||
USDC,
|
||||
}
|
||||
|
||||
/// Shared infrastructure components that can be reused across multiple wallets
|
||||
///
|
||||
/// This struct holds the expensive-to-initialize components (RPC client, SWQOS clients)
|
||||
/// that are wallet-independent and can be shared when only the trading wallet changes.
|
||||
pub struct TradingInfrastructure {
|
||||
/// Shared RPC client for blockchain interactions
|
||||
pub rpc: Arc<SolanaRpcClient>,
|
||||
/// Shared SWQOS clients for transaction priority and routing
|
||||
pub swqos_clients: Vec<Arc<SwqosClient>>,
|
||||
/// Configuration used to create this infrastructure
|
||||
pub config: InfrastructureConfig,
|
||||
}
|
||||
|
||||
impl TradingInfrastructure {
|
||||
/// Create new shared infrastructure from configuration
|
||||
///
|
||||
/// This performs the expensive initialization:
|
||||
/// - Creates RPC client with connection pool
|
||||
/// - Creates SWQOS clients (each with their own HTTP client)
|
||||
/// - Initializes rent cache and starts background updater
|
||||
pub async fn new(config: InfrastructureConfig) -> Self {
|
||||
// Install crypto provider (idempotent)
|
||||
if CryptoProvider::get_default().is_none() {
|
||||
let _ = default_provider()
|
||||
.install_default()
|
||||
.map_err(|e| anyhow::anyhow!("Failed to install crypto provider: {:?}", e));
|
||||
}
|
||||
|
||||
// Create RPC client
|
||||
let rpc = Arc::new(SolanaRpcClient::new_with_commitment(
|
||||
config.rpc_url.clone(),
|
||||
config.commitment.clone(),
|
||||
));
|
||||
|
||||
// Initialize rent cache and start background updater
|
||||
common::seed::update_rents(&rpc).await.unwrap();
|
||||
common::seed::start_rent_updater(rpc.clone());
|
||||
|
||||
// Create SWQOS clients with blacklist checking
|
||||
let mut swqos_clients: Vec<Arc<SwqosClient>> = vec![];
|
||||
for swqos in &config.swqos_configs {
|
||||
// Check blacklist, skip disabled providers
|
||||
if swqos.is_blacklisted() {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ SWQOS {:?} is blacklisted, skipping", swqos.swqos_type());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
match SwqosConfig::get_swqos_client(
|
||||
config.rpc_url.clone(),
|
||||
config.commitment.clone(),
|
||||
swqos.clone(),
|
||||
).await {
|
||||
Ok(swqos_client) => swqos_clients.push(swqos_client),
|
||||
Err(err) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(
|
||||
target: "sol_trade_sdk",
|
||||
"failed to create {:?} swqos client: {err}. Excluding from swqos list",
|
||||
swqos.swqos_type()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
rpc,
|
||||
swqos_clients,
|
||||
config,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Main trading client for Solana DeFi protocols
|
||||
///
|
||||
/// `SolTradingSDK` provides a unified interface for trading across multiple Solana DEXs
|
||||
/// including PumpFun, PumpSwap, Bonk, Raydium AMM V4, and Raydium CPMM.
|
||||
/// It manages RPC connections, transaction signing, and SWQOS (Solana Web Quality of Service) settings.
|
||||
pub struct TradingClient {
|
||||
/// The keypair used for signing all transactions
|
||||
pub payer: Arc<Keypair>,
|
||||
/// Shared infrastructure (RPC client, SWQOS clients)
|
||||
/// Can be shared across multiple TradingClient instances with different wallets
|
||||
pub infrastructure: Arc<TradingInfrastructure>,
|
||||
/// Optional middleware manager for custom transaction processing
|
||||
pub middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||
/// Whether to use seed optimization for all ATA operations (default: true)
|
||||
/// Applies to all token account creations across buy and sell operations
|
||||
pub use_seed_optimize: bool,
|
||||
/// Whether to pin parallel submit tasks to CPU cores (from TradeConfig.use_core_affinity). Default true.
|
||||
pub use_core_affinity: bool,
|
||||
/// Whether to output all SDK logs (from TradeConfig.log_enabled).
|
||||
pub log_enabled: bool,
|
||||
}
|
||||
|
||||
static INSTANCE: Mutex<Option<Arc<TradingClient>>> = Mutex::new(None);
|
||||
|
||||
/// 🔄 向后兼容:SolanaTrade 别名
|
||||
pub type SolanaTrade = TradingClient;
|
||||
|
||||
impl Clone for TradingClient {
|
||||
fn clone(&self) -> Self {
|
||||
Self {
|
||||
payer: self.payer.clone(),
|
||||
infrastructure: self.infrastructure.clone(),
|
||||
middleware_manager: self.middleware_manager.clone(),
|
||||
use_seed_optimize: self.use_seed_optimize,
|
||||
use_core_affinity: self.use_core_affinity,
|
||||
log_enabled: self.log_enabled,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Parameters for executing buy orders across different DEX protocols
|
||||
///
|
||||
/// Contains all necessary configuration for purchasing tokens, including
|
||||
/// protocol-specific settings, account management options, and transaction preferences.
|
||||
#[derive(Clone)]
|
||||
pub struct TradeBuyParams {
|
||||
// Trading configuration
|
||||
/// The DEX protocol to use for the trade
|
||||
pub dex_type: DexType,
|
||||
/// Type of the token to buy
|
||||
pub input_token_type: TradeTokenType,
|
||||
/// Public key of the token to purchase
|
||||
pub mint: Pubkey,
|
||||
/// Amount of tokens to buy (in smallest token units)
|
||||
pub input_token_amount: u64,
|
||||
/// Optional slippage tolerance in basis points (e.g., 100 = 1%)
|
||||
pub slippage_basis_points: Option<u64>,
|
||||
/// Recent blockhash for transaction validity
|
||||
pub recent_blockhash: Option<Hash>,
|
||||
/// Protocol-specific parameters (PumpFun, Raydium, etc.)
|
||||
pub extension_params: DexParamEnum,
|
||||
// Extended configuration
|
||||
/// Optional address lookup table for transaction size optimization
|
||||
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
/// Whether to wait for transaction confirmation before returning
|
||||
pub wait_transaction_confirmed: bool,
|
||||
/// Whether to create input token associated token account
|
||||
pub create_input_token_ata: bool,
|
||||
/// Whether to close input token associated token account after trade
|
||||
pub close_input_token_ata: bool,
|
||||
/// Whether to create token mint associated token account
|
||||
pub create_mint_ata: bool,
|
||||
/// Durable nonce information
|
||||
pub durable_nonce: Option<DurableNonceInfo>,
|
||||
/// Optional fixed output token amount (If this value is set, it will be directly assigned to the output amount instead of being calculated)
|
||||
pub fixed_output_token_amount: Option<u64>,
|
||||
/// Gas fee strategy
|
||||
pub gas_fee_strategy: GasFeeStrategy,
|
||||
/// Whether to simulate the transaction instead of executing it
|
||||
pub simulate: bool,
|
||||
/// Use exact SOL amount instructions (buy_exact_sol_in for PumpFun, buy_exact_quote_in for PumpSwap).
|
||||
/// When Some(true) or None (default), the exact SOL/quote amount is spent and slippage is applied to output tokens.
|
||||
/// When Some(false), uses regular buy instruction where slippage is applied to SOL/quote input.
|
||||
/// This option only applies to PumpFun and PumpSwap DEXes; it is ignored for other DEXes.
|
||||
pub use_exact_sol_amount: Option<bool>,
|
||||
/// 可选:事件收到时间(微秒,与 sol-parser-sdk 的 metadata.grpc_recv_us / clock::now_micros 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点,打印起点→提交耗时。
|
||||
pub grpc_recv_us: Option<i64>,
|
||||
}
|
||||
|
||||
/// Parameters for executing sell orders across different DEX protocols
|
||||
///
|
||||
/// Contains all necessary configuration for selling tokens, including
|
||||
/// protocol-specific settings, tip preferences, account management options, and transaction preferences.
|
||||
#[derive(Clone)]
|
||||
pub struct TradeSellParams {
|
||||
// Trading configuration
|
||||
/// The DEX protocol to use for the trade
|
||||
pub dex_type: DexType,
|
||||
/// Type of the token to sell
|
||||
pub output_token_type: TradeTokenType,
|
||||
/// Public key of the token to sell
|
||||
pub mint: Pubkey,
|
||||
/// Amount of tokens to sell (in smallest token units)
|
||||
pub input_token_amount: u64,
|
||||
/// Optional slippage tolerance in basis points (e.g., 100 = 1%)
|
||||
pub slippage_basis_points: Option<u64>,
|
||||
/// Recent blockhash for transaction validity
|
||||
pub recent_blockhash: Option<Hash>,
|
||||
/// Whether to include tip for transaction priority
|
||||
pub with_tip: bool,
|
||||
/// Protocol-specific parameters (PumpFun, Raydium, etc.)
|
||||
pub extension_params: DexParamEnum,
|
||||
// Extended configuration
|
||||
/// Optional address lookup table for transaction size optimization
|
||||
pub address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||
/// Whether to wait for transaction confirmation before returning
|
||||
pub wait_transaction_confirmed: bool,
|
||||
/// Whether to create output token associated token account
|
||||
pub create_output_token_ata: bool,
|
||||
/// Whether to close output token associated token account after trade
|
||||
pub close_output_token_ata: bool,
|
||||
/// Whether to close mint token associated token account after trade
|
||||
pub close_mint_token_ata: bool,
|
||||
/// Durable nonce information
|
||||
pub durable_nonce: Option<DurableNonceInfo>,
|
||||
/// Optional fixed output token amount (If this value is set, it will be directly assigned to the output amount instead of being calculated)
|
||||
pub fixed_output_token_amount: Option<u64>,
|
||||
/// Gas fee strategy
|
||||
pub gas_fee_strategy: GasFeeStrategy,
|
||||
/// Whether to simulate the transaction instead of executing it
|
||||
pub simulate: bool,
|
||||
/// 可选:事件收到时间(微秒,与 sol-parser-sdk clock 同源)。不传且开启 log_enabled 时 SDK 用 now_micros() 作为起点。
|
||||
pub grpc_recv_us: Option<i64>,
|
||||
}
|
||||
|
||||
impl TradingClient {
|
||||
/// Create a TradingClient from shared infrastructure (fast path)
|
||||
///
|
||||
/// This is the preferred method when multiple wallets share the same infrastructure.
|
||||
/// It only performs wallet-specific initialization (fast_init) without the expensive
|
||||
/// RPC/SWQOS client creation.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `payer` - The keypair used for signing transactions
|
||||
/// * `infrastructure` - Shared infrastructure (RPC client, SWQOS clients)
|
||||
/// * `use_seed_optimize` - Whether to use seed optimization for ATA operations
|
||||
///
|
||||
/// # Returns
|
||||
/// Returns a configured `TradingClient` instance ready for trading operations
|
||||
pub fn from_infrastructure(
|
||||
payer: Arc<Keypair>,
|
||||
infrastructure: Arc<TradingInfrastructure>,
|
||||
use_seed_optimize: bool,
|
||||
) -> Self {
|
||||
// Initialize wallet-specific caches (fast, synchronous)
|
||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||
|
||||
Self {
|
||||
payer,
|
||||
infrastructure,
|
||||
middleware_manager: None,
|
||||
use_seed_optimize,
|
||||
use_core_affinity: true,
|
||||
log_enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Create a TradingClient from shared infrastructure with optional WSOL ATA setup
|
||||
///
|
||||
/// Same as `from_infrastructure` but also handles WSOL ATA creation if requested.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `payer` - The keypair used for signing transactions
|
||||
/// * `infrastructure` - Shared infrastructure (RPC client, SWQOS clients)
|
||||
/// * `use_seed_optimize` - Whether to use seed optimization for ATA operations
|
||||
/// * `create_wsol_ata` - Whether to check/create WSOL ATA
|
||||
pub async fn from_infrastructure_with_wsol_setup(
|
||||
payer: Arc<Keypair>,
|
||||
infrastructure: Arc<TradingInfrastructure>,
|
||||
use_seed_optimize: bool,
|
||||
create_wsol_ata: bool,
|
||||
) -> Self {
|
||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||
|
||||
if create_wsol_ata {
|
||||
// 在后台异步创建 WSOL ATA,不阻塞启动
|
||||
let payer_clone = payer.clone();
|
||||
let rpc_clone = infrastructure.rpc.clone();
|
||||
tokio::spawn(async move {
|
||||
Self::ensure_wsol_ata(&payer_clone, &rpc_clone).await;
|
||||
});
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA creation started in background, does not block bot startup");
|
||||
}
|
||||
}
|
||||
|
||||
Self {
|
||||
payer,
|
||||
infrastructure,
|
||||
middleware_manager: None,
|
||||
use_seed_optimize,
|
||||
use_core_affinity: true,
|
||||
log_enabled: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to ensure WSOL ATA exists for a wallet
|
||||
async fn ensure_wsol_ata(payer: &Arc<Keypair>, rpc: &Arc<SolanaRpcClient>) {
|
||||
let wsol_ata =
|
||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||
&payer.pubkey(),
|
||||
&WSOL_TOKEN_ACCOUNT,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
);
|
||||
|
||||
match rpc.get_account(&wsol_ata).await {
|
||||
Ok(_) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists: {}", wsol_ata);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Err(_) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "🔨 Creating WSOL ATA: {}", wsol_ata);
|
||||
}
|
||||
let create_ata_ixs =
|
||||
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
||||
|
||||
if !create_ata_ixs.is_empty() {
|
||||
use solana_sdk::transaction::Transaction;
|
||||
|
||||
// 重试逻辑:最多尝试3次,每次超时10秒
|
||||
const MAX_RETRIES: usize = 3;
|
||||
const TIMEOUT_SECS: u64 = 10;
|
||||
let mut last_error = None;
|
||||
|
||||
for attempt in 1..=MAX_RETRIES {
|
||||
if attempt > 1 {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "🔄 Retrying WSOL ATA creation (attempt {}/{})...", attempt, MAX_RETRIES);
|
||||
}
|
||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
||||
}
|
||||
|
||||
let recent_blockhash = match rpc.get_latest_blockhash().await {
|
||||
Ok(hash) => hash,
|
||||
Err(e) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Failed to get latest blockhash: {}", e);
|
||||
}
|
||||
last_error = Some(format!("Failed to get blockhash: {}", e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
|
||||
let tx = Transaction::new_signed_with_payer(
|
||||
&create_ata_ixs,
|
||||
Some(&payer.pubkey()),
|
||||
&[payer.as_ref()],
|
||||
recent_blockhash,
|
||||
);
|
||||
|
||||
// 使用超时包装 send_and_confirm_transaction
|
||||
let send_result = tokio::time::timeout(
|
||||
tokio::time::Duration::from_secs(TIMEOUT_SECS),
|
||||
rpc.send_and_confirm_transaction(&tx)
|
||||
).await;
|
||||
|
||||
match send_result {
|
||||
Ok(Ok(signature)) => {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA created successfully: {}", signature);
|
||||
}
|
||||
return;
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
last_error = Some(format!("{}", e));
|
||||
|
||||
// 检查账户是否实际已存在
|
||||
if let Ok(_) = rpc.get_account(&wsol_ata).await {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA already exists (tx failed but account exists): {}", wsol_ata);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if attempt < MAX_RETRIES && sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Attempt {} failed: {}", attempt, e);
|
||||
}
|
||||
}
|
||||
Err(_) => {
|
||||
last_error = Some(format!("Transaction confirmation timeout ({}s)", TIMEOUT_SECS));
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
warn!(target: "sol_trade_sdk", "⚠️ Attempt {} timed out", attempt);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 所有重试都失败了
|
||||
if let Some(err) = last_error {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
error!(target: "sol_trade_sdk", "❌ WSOL ATA creation failed after {} retries: {}", MAX_RETRIES, wsol_ata);
|
||||
error!(target: "sol_trade_sdk", " Error: {}", err);
|
||||
error!(target: "sol_trade_sdk", " 💡 Possible causes:");
|
||||
error!(target: "sol_trade_sdk", " 1. Insufficient SOL balance (need ~0.002 SOL for rent exemption)");
|
||||
error!(target: "sol_trade_sdk", " 2. RPC timeout or network congestion");
|
||||
error!(target: "sol_trade_sdk", " 3. Insufficient transaction fee");
|
||||
error!(target: "sol_trade_sdk", " 🔧 Solutions:");
|
||||
error!(target: "sol_trade_sdk", " 1. Fund wallet with at least 0.1 SOL");
|
||||
error!(target: "sol_trade_sdk", " 2. Retry after a few seconds");
|
||||
error!(target: "sol_trade_sdk", " 3. Check RPC connection");
|
||||
error!(target: "sol_trade_sdk", " ⚠️ Process will exit in 5 seconds, restart after fixing the above");
|
||||
}
|
||||
std::thread::sleep(std::time::Duration::from_secs(5));
|
||||
panic!(
|
||||
"❌ WSOL ATA creation failed and account does not exist: {}. Error: {}",
|
||||
wsol_ata, err
|
||||
);
|
||||
}
|
||||
} else {
|
||||
if sdk_log::sdk_log_enabled() {
|
||||
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA already exists (no need to create)");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Creates a new SolTradingSDK instance with the specified configuration
|
||||
///
|
||||
/// This function initializes the trading system with RPC connection, SWQOS settings,
|
||||
/// and sets up necessary components for trading operations.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `payer` - The keypair used for signing transactions
|
||||
/// * `trade_config` - Trading configuration including RPC URL, SWQOS settings, etc.
|
||||
///
|
||||
/// # Returns
|
||||
/// Returns a configured `SolTradingSDK` instance ready for trading operations
|
||||
#[inline]
|
||||
pub async fn new(payer: Arc<Keypair>, trade_config: TradeConfig) -> Self {
|
||||
// 设置 SDK 全局日志开关,后续所有 SDK 内日志(SWQOS/WSOL/耗时等)均受此控制
|
||||
sdk_log::set_sdk_log_enabled(trade_config.log_enabled);
|
||||
// 预热高性能时钟,避免首笔交易时触发 3 次 Utc::now() 校准
|
||||
let _ = crate::common::clock::now_micros();
|
||||
// Create infrastructure from trade config
|
||||
let infra_config = InfrastructureConfig::from_trade_config(&trade_config);
|
||||
let infrastructure = Arc::new(TradingInfrastructure::new(infra_config).await);
|
||||
|
||||
// Initialize wallet-specific caches
|
||||
crate::common::fast_fn::fast_init(&payer.pubkey());
|
||||
|
||||
// Handle WSOL ATA creation if configured
|
||||
if trade_config.create_wsol_ata_on_startup {
|
||||
Self::ensure_wsol_ata(&payer, &infrastructure.rpc).await;
|
||||
}
|
||||
|
||||
let instance = Self {
|
||||
payer,
|
||||
infrastructure,
|
||||
middleware_manager: None,
|
||||
use_seed_optimize: trade_config.use_seed_optimize,
|
||||
use_core_affinity: trade_config.use_core_affinity,
|
||||
log_enabled: trade_config.log_enabled,
|
||||
};
|
||||
|
||||
let mut current = INSTANCE.lock();
|
||||
*current = Some(Arc::new(instance.clone()));
|
||||
|
||||
instance
|
||||
}
|
||||
|
||||
/// Adds a middleware manager to the SolanaTrade instance
|
||||
///
|
||||
/// Middleware managers can be used to implement custom logic that runs before or after trading operations,
|
||||
/// such as logging, monitoring, or custom validation.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `middleware_manager` - The middleware manager to attach
|
||||
///
|
||||
/// # Returns
|
||||
/// Returns the modified SolanaTrade instance with middleware manager attached
|
||||
pub fn with_middleware_manager(mut self, middleware_manager: MiddlewareManager) -> Self {
|
||||
self.middleware_manager = Some(Arc::new(middleware_manager));
|
||||
self
|
||||
}
|
||||
|
||||
/// Gets the RPC client instance for direct Solana blockchain interactions
|
||||
///
|
||||
/// This provides access to the underlying Solana RPC client that can be used
|
||||
/// for custom blockchain operations outside of the trading framework.
|
||||
///
|
||||
/// # Returns
|
||||
/// Returns a reference to the Arc-wrapped SolanaRpcClient instance
|
||||
pub fn get_rpc(&self) -> &Arc<SolanaRpcClient> {
|
||||
&self.infrastructure.rpc
|
||||
}
|
||||
|
||||
/// Gets the current globally shared SolanaTrade instance
|
||||
///
|
||||
/// This provides access to the singleton instance that was created with `new()`.
|
||||
/// Useful for accessing the trading instance from different parts of the application.
|
||||
///
|
||||
/// # Returns
|
||||
/// Returns the Arc-wrapped SolanaTrade instance
|
||||
///
|
||||
/// # Panics
|
||||
/// Panics if no instance has been initialized yet. Make sure to call `new()` first.
|
||||
pub fn get_instance() -> Arc<Self> {
|
||||
let instance = INSTANCE.lock();
|
||||
instance
|
||||
.as_ref()
|
||||
.expect("SolanaTrade instance not initialized. Please call new() first.")
|
||||
.clone()
|
||||
}
|
||||
|
||||
/// Execute a buy order for a specified token
|
||||
///
|
||||
/// 🔧 修复:返回Vec<Signature>支持多SWQOS并发交易
|
||||
/// - bool: 是否至少有一个交易成功
|
||||
/// - Vec<Signature>: 所有提交的交易签名(按SWQOS顺序)
|
||||
/// - Option<TradeError>: 最后一个错误(如果全部失败)
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `params` - Buy trade parameters containing all necessary trading configuration
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok((bool, Vec<Signature>, Option<TradeError>))` with success flag and all transaction signatures,
|
||||
/// or an error if the transaction fails.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - Invalid protocol parameters are provided for the specified DEX type
|
||||
/// - The transaction fails to execute
|
||||
/// - Network or RPC errors occur
|
||||
/// - Insufficient SOL balance for the purchase
|
||||
/// - Required accounts cannot be created or accessed
|
||||
#[inline]
|
||||
pub async fn buy(
|
||||
&self,
|
||||
params: TradeBuyParams,
|
||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
||||
#[cfg(feature = "perf-trace")]
|
||||
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
|
||||
debug!(
|
||||
target: "sol_trade_sdk",
|
||||
"slippage_basis_points is none, use default slippage basis points: {}",
|
||||
DEFAULT_SLIPPAGE
|
||||
);
|
||||
}
|
||||
if params.input_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||
return Err(anyhow::anyhow!(
|
||||
" Current version only support USD1 trading on Bonk protocols"
|
||||
));
|
||||
}
|
||||
let input_token_mint = if params.input_token_type == TradeTokenType::SOL {
|
||||
SOL_TOKEN_ACCOUNT
|
||||
} else if params.input_token_type == TradeTokenType::WSOL {
|
||||
WSOL_TOKEN_ACCOUNT
|
||||
} else if params.input_token_type == TradeTokenType::USDC {
|
||||
USDC_TOKEN_ACCOUNT
|
||||
} else {
|
||||
USD1_TOKEN_ACCOUNT
|
||||
};
|
||||
let executor = TradeFactory::create_executor(params.dex_type.clone());
|
||||
let protocol_params = params.extension_params;
|
||||
let buy_params = SwapParams {
|
||||
rpc: Some(self.infrastructure.rpc.clone()),
|
||||
payer: self.payer.clone(),
|
||||
trade_type: TradeType::Buy,
|
||||
input_mint: input_token_mint,
|
||||
output_mint: params.mint,
|
||||
input_token_program: None,
|
||||
output_token_program: None,
|
||||
input_amount: Some(params.input_token_amount),
|
||||
slippage_basis_points: params.slippage_basis_points,
|
||||
address_lookup_table_account: params.address_lookup_table_account,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: protocol_params.clone(),
|
||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||
middleware_manager: self.middleware_manager.clone(),
|
||||
durable_nonce: params.durable_nonce,
|
||||
with_tip: true,
|
||||
create_input_mint_ata: params.create_input_token_ata,
|
||||
close_input_mint_ata: params.close_input_token_ata,
|
||||
create_output_mint_ata: params.create_mint_ata,
|
||||
close_output_mint_ata: false,
|
||||
fixed_output_amount: params.fixed_output_token_amount,
|
||||
gas_fee_strategy: params.gas_fee_strategy,
|
||||
simulate: params.simulate,
|
||||
log_enabled: self.log_enabled,
|
||||
use_core_affinity: self.use_core_affinity,
|
||||
grpc_recv_us: params.grpc_recv_us,
|
||||
use_exact_sol_amount: params.use_exact_sol_amount,
|
||||
};
|
||||
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
|
||||
}
|
||||
|
||||
let swap_result = executor.swap(buy_params).await;
|
||||
let result =
|
||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Execute a sell order for a specified token
|
||||
///
|
||||
/// 🔧 修复:返回Vec<Signature>支持多SWQOS并发交易
|
||||
/// - bool: 是否至少有一个交易成功
|
||||
/// - Vec<Signature>: 所有提交的交易签名(按SWQOS顺序)
|
||||
/// - Option<TradeError>: 最后一个错误(如果全部失败)
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `params` - Sell trade parameters containing all necessary trading configuration
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok((bool, Vec<Signature>, Option<TradeError>))` with success flag and all transaction signatures,
|
||||
/// or an error if the transaction fails.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - Invalid protocol parameters are provided for the specified DEX type
|
||||
/// - The transaction fails to execute
|
||||
/// - Network or RPC errors occur
|
||||
/// - Insufficient token balance for the sale
|
||||
/// - Token account doesn't exist or is not properly initialized
|
||||
/// - Required accounts cannot be created or accessed
|
||||
#[inline]
|
||||
pub async fn sell(
|
||||
&self,
|
||||
params: TradeSellParams,
|
||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
||||
#[cfg(feature = "perf-trace")]
|
||||
if sdk_log::sdk_log_enabled() && params.slippage_basis_points.is_none() {
|
||||
debug!(
|
||||
target: "sol_trade_sdk",
|
||||
"slippage_basis_points is none, use default slippage basis points: {}",
|
||||
DEFAULT_SLIPPAGE
|
||||
);
|
||||
}
|
||||
if params.output_token_type == TradeTokenType::USD1 && params.dex_type != DexType::Bonk {
|
||||
return Err(anyhow::anyhow!(
|
||||
" Current version only support USD1 trading on Bonk protocols"
|
||||
));
|
||||
}
|
||||
let executor = TradeFactory::create_executor(params.dex_type.clone());
|
||||
let protocol_params = params.extension_params;
|
||||
let output_token_mint = if params.output_token_type == TradeTokenType::SOL {
|
||||
SOL_TOKEN_ACCOUNT
|
||||
} else if params.output_token_type == TradeTokenType::WSOL {
|
||||
WSOL_TOKEN_ACCOUNT
|
||||
} else if params.output_token_type == TradeTokenType::USDC {
|
||||
USDC_TOKEN_ACCOUNT
|
||||
} else {
|
||||
USD1_TOKEN_ACCOUNT
|
||||
};
|
||||
let sell_params = SwapParams {
|
||||
rpc: Some(self.infrastructure.rpc.clone()),
|
||||
payer: self.payer.clone(),
|
||||
trade_type: TradeType::Sell,
|
||||
input_mint: params.mint,
|
||||
output_mint: output_token_mint,
|
||||
input_token_program: None,
|
||||
output_token_program: None,
|
||||
input_amount: Some(params.input_token_amount),
|
||||
slippage_basis_points: params.slippage_basis_points,
|
||||
address_lookup_table_account: params.address_lookup_table_account,
|
||||
recent_blockhash: params.recent_blockhash,
|
||||
wait_transaction_confirmed: params.wait_transaction_confirmed,
|
||||
protocol_params: protocol_params.clone(),
|
||||
with_tip: params.with_tip,
|
||||
open_seed_optimize: self.use_seed_optimize, // 使用全局seed优化配置
|
||||
swqos_clients: self.infrastructure.swqos_clients.clone(),
|
||||
middleware_manager: self.middleware_manager.clone(),
|
||||
durable_nonce: params.durable_nonce,
|
||||
create_input_mint_ata: false,
|
||||
close_input_mint_ata: params.close_mint_token_ata,
|
||||
create_output_mint_ata: params.create_output_token_ata,
|
||||
close_output_mint_ata: params.close_output_token_ata,
|
||||
fixed_output_amount: params.fixed_output_token_amount,
|
||||
gas_fee_strategy: params.gas_fee_strategy,
|
||||
simulate: params.simulate,
|
||||
log_enabled: self.log_enabled,
|
||||
use_core_affinity: self.use_core_affinity,
|
||||
grpc_recv_us: params.grpc_recv_us,
|
||||
use_exact_sol_amount: None,
|
||||
};
|
||||
|
||||
if !validate_protocol_params(params.dex_type, &protocol_params) {
|
||||
return Err(anyhow::anyhow!("Invalid protocol params for Trade"));
|
||||
}
|
||||
|
||||
let swap_result = executor.swap(sell_params).await;
|
||||
let result =
|
||||
swap_result.map(|(success, sigs, err)| (success, sigs, err.map(TradeError::from)));
|
||||
return result;
|
||||
}
|
||||
|
||||
/// Execute a sell order for a percentage of the specified token amount
|
||||
///
|
||||
/// This is a convenience function that calculates the exact amount to sell based on
|
||||
/// a percentage of the total token amount and then calls the `sell` function.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// * `params` - Sell trade parameters (will be modified with calculated token amount)
|
||||
/// * `amount_token` - Total amount of tokens available (in smallest token units)
|
||||
/// * `percent` - Percentage of tokens to sell (1-100, where 100 = 100%)
|
||||
///
|
||||
/// # Returns
|
||||
///
|
||||
/// Returns `Ok(Signature)` with the transaction signature if the sell order is successfully executed,
|
||||
/// or an error if the transaction fails.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - `percent` is 0 or greater than 100
|
||||
/// - Invalid protocol parameters are provided for the specified DEX type
|
||||
/// - The transaction fails to execute
|
||||
/// - Network or RPC errors occur
|
||||
/// - Insufficient token balance for the calculated sale amount
|
||||
/// - Token account doesn't exist or is not properly initialized
|
||||
/// - Required accounts cannot be created or accessed
|
||||
pub async fn sell_by_percent(
|
||||
&self,
|
||||
mut params: TradeSellParams,
|
||||
amount_token: u64,
|
||||
percent: u64,
|
||||
) -> Result<(bool, Vec<Signature>, Option<TradeError>), anyhow::Error> {
|
||||
if percent == 0 || percent > 100 {
|
||||
return Err(anyhow::anyhow!("Percentage must be between 1 and 100"));
|
||||
}
|
||||
let amount = amount_token * percent / 100;
|
||||
params.input_token_amount = amount;
|
||||
self.sell(params).await
|
||||
}
|
||||
|
||||
/// Wraps native SOL into wSOL (Wrapped SOL) for use in SPL token operations
|
||||
///
|
||||
/// This function creates a wSOL associated token account (if it doesn't exist),
|
||||
/// transfers the specified amount of SOL to that account, and then syncs the native
|
||||
/// token balance to make SOL usable as an SPL token in trading operations.
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `amount` - The amount of SOL to wrap (in lamports)
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - Transaction signature if successful
|
||||
/// * `Err(anyhow::Error)` - If the transaction fails to execute
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - Insufficient SOL balance for the wrap operation
|
||||
/// - wSOL associated token account creation fails
|
||||
/// - Transaction fails to execute or confirm
|
||||
/// - Network or RPC errors occur
|
||||
pub async fn wrap_sol_to_wsol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
||||
use crate::trading::common::wsol_manager::handle_wsol;
|
||||
use solana_sdk::transaction::Transaction;
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let instructions = handle_wsol(&self.payer.pubkey(), amount);
|
||||
let mut transaction =
|
||||
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
/// Closes the wSOL associated token account and unwraps remaining balance to native SOL
|
||||
///
|
||||
/// This function closes the wSOL associated token account, which automatically
|
||||
/// transfers any remaining wSOL balance back to the account owner as native SOL.
|
||||
/// This is useful for cleaning up wSOL accounts and recovering wrapped SOL after trading operations.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - Transaction signature if successful
|
||||
/// * `Err(anyhow::Error)` - If the transaction fails to execute
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - wSOL associated token account doesn't exist
|
||||
/// - Account closure fails due to insufficient permissions
|
||||
/// - Transaction fails to execute or confirm
|
||||
/// - Network or RPC errors occur
|
||||
pub async fn close_wsol(&self) -> Result<String, anyhow::Error> {
|
||||
use crate::trading::common::wsol_manager::close_wsol;
|
||||
use solana_sdk::transaction::Transaction;
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let instructions = close_wsol(&self.payer.pubkey());
|
||||
let mut transaction =
|
||||
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
|
||||
/// Creates a wSOL associated token account (ATA) without wrapping any SOL
|
||||
///
|
||||
/// This function only creates the wSOL associated token account for the payer
|
||||
/// without transferring any SOL into it. This is useful when you want to set up
|
||||
/// the account infrastructure in advance without committing funds yet.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - Transaction signature if successful
|
||||
/// * `Err(anyhow::Error)` - If the transaction fails to execute
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// This function will return an error if:
|
||||
/// - wSOL ATA account already exists (idempotent, will succeed silently)
|
||||
/// - Transaction fails to execute or confirm
|
||||
/// - Network or RPC errors occur
|
||||
/// - Insufficient SOL for transaction fees
|
||||
pub async fn create_wsol_ata(&self) -> Result<String, anyhow::Error> {
|
||||
use crate::trading::common::wsol_manager::create_wsol_ata;
|
||||
use solana_sdk::transaction::Transaction;
|
||||
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let instructions = create_wsol_ata(&self.payer.pubkey());
|
||||
|
||||
// If instructions are empty, ATA already exists
|
||||
if instructions.is_empty() {
|
||||
return Err(anyhow::anyhow!("wSOL ATA already exists or no instructions needed"));
|
||||
}
|
||||
|
||||
let mut transaction =
|
||||
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
|
||||
/// 将 WSOL 转换为 SOL,使用 seed 账户
|
||||
///
|
||||
/// 这个函数实现以下步骤:
|
||||
/// 1. 使用 super::seed::create_associated_token_account_use_seed 创建 WSOL seed 账号
|
||||
/// 2. 使用 get_associated_token_address_with_program_id_use_seed 获取该账号的 ATA 地址
|
||||
/// 3. 添加从用户 WSOL ATA 转账到该 seed ATA 账号的指令
|
||||
/// 4. 添加关闭 WSOL seed 账号的指令
|
||||
///
|
||||
/// # Arguments
|
||||
/// * `amount` - 要转换的 WSOL 数量(以 lamports 为单位)
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - 交易签名
|
||||
/// * `Err(anyhow::Error)` - 如果交易执行失败
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// 此函数在以下情况下会返回错误:
|
||||
/// - 用户 WSOL ATA 中余额不足
|
||||
/// - seed 账户创建失败
|
||||
/// - 转账指令执行失败
|
||||
/// - 交易执行或确认失败
|
||||
/// - 网络或 RPC 错误
|
||||
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
||||
use crate::trading::common::wsol_manager::{wrap_wsol_to_sol as wrap_wsol_to_sol_internal, wrap_wsol_to_sol_without_create};
|
||||
use crate::common::seed::get_associated_token_address_with_program_id_use_seed;
|
||||
use solana_sdk::transaction::Transaction;
|
||||
|
||||
// 检查临时seed账户是否已存在
|
||||
let seed_ata_address = get_associated_token_address_with_program_id_use_seed(
|
||||
&self.payer.pubkey(),
|
||||
&crate::constants::WSOL_TOKEN_ACCOUNT,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
)?;
|
||||
|
||||
let account_exists = self.infrastructure.rpc.get_account(&seed_ata_address).await.is_ok();
|
||||
|
||||
let instructions = if account_exists {
|
||||
// 如果账户已存在,使用不创建账户的版本
|
||||
wrap_wsol_to_sol_without_create(&self.payer.pubkey(), amount)?
|
||||
} else {
|
||||
// 如果账户不存在,使用创建账户的版本
|
||||
wrap_wsol_to_sol_internal(&self.payer.pubkey(), amount)?
|
||||
};
|
||||
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let mut transaction = Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
|
||||
/// Claim Bonding Curve (Pump) cashback.
|
||||
///
|
||||
/// Transfers native SOL from the user's UserVolumeAccumulator to the wallet.
|
||||
/// If there is nothing to claim, the transaction may still succeed with no SOL transferred.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - Transaction signature
|
||||
/// * `Err(anyhow::Error)` - Build or send failure (e.g. invalid PDA)
|
||||
pub async fn claim_cashback_pumpfun(&self) -> Result<String, anyhow::Error> {
|
||||
use solana_sdk::transaction::Transaction;
|
||||
let ix = crate::instruction::pumpfun::claim_cashback_pumpfun_instruction(&self.payer.pubkey())
|
||||
.ok_or_else(|| anyhow::anyhow!("Failed to build PumpFun claim_cashback instruction"))?;
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let mut transaction = Transaction::new_with_payer(&[ix], Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
|
||||
/// Claim PumpSwap (AMM) cashback.
|
||||
///
|
||||
/// Transfers WSOL from the UserVolumeAccumulator to the user's WSOL ATA.
|
||||
/// Creates the user's WSOL ATA idempotently if it does not exist, then claims.
|
||||
///
|
||||
/// # Returns
|
||||
/// * `Ok(String)` - Transaction signature
|
||||
/// * `Err(anyhow::Error)` - Build or send failure
|
||||
pub async fn claim_cashback_pumpswap(&self) -> Result<String, anyhow::Error> {
|
||||
use solana_sdk::transaction::Transaction;
|
||||
let mut instructions = crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||
&self.payer.pubkey(),
|
||||
&self.payer.pubkey(),
|
||||
&WSOL_TOKEN_ACCOUNT,
|
||||
&crate::constants::TOKEN_PROGRAM,
|
||||
self.use_seed_optimize,
|
||||
);
|
||||
let ix = crate::instruction::pumpswap::claim_cashback_pumpswap_instruction(
|
||||
&self.payer.pubkey(),
|
||||
WSOL_TOKEN_ACCOUNT,
|
||||
crate::constants::TOKEN_PROGRAM,
|
||||
).ok_or_else(|| anyhow::anyhow!("Failed to build PumpSwap claim_cashback instruction"))?;
|
||||
instructions.push(ix);
|
||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||
let mut transaction = Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||
Ok(signature.to_string())
|
||||
}
|
||||
}
|
||||
pub use crate::common::nonce_cache::{fetch_nonce_info, DurableNonceInfo};
|
||||
// Re-export for SwqosConfig (Node1/BlockRazor transport; Astralane submission mode)
|
||||
pub use crate::swqos::{AstralaneTransport, SwqosTransport};
|
||||
pub use client::{
|
||||
find_pool_by_mint, recommended_sender_thread_core_indices, AccountPolicy, BuyAmount,
|
||||
SellAmount, SimpleBuyParams, SimpleSellParams, SolanaTrade, TradeBuyParams, TradeSellParams,
|
||||
TradeTokenType, TradingClient, TradingInfrastructure,
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! 🚀 编译器级性能优化 - 极致编译时优化
|
||||
//!
|
||||
//!
|
||||
//! 实现编译时的极致性能优化,包括:
|
||||
//! - 编译器标志优化配置
|
||||
//! - 编译时代码生成
|
||||
@@ -137,100 +137,110 @@ impl CompilerOptimizer {
|
||||
stats: CompilerOptimizationStats::default(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 🚀 生成超高性能编译配置
|
||||
pub fn generate_ultra_performance_config(&self) -> Result<CompilerConfig> {
|
||||
tracing::info!(target: "sol_trade_sdk","🚀 Generating ultra-performance compiler configuration...");
|
||||
|
||||
|
||||
let mut rustflags = Vec::new();
|
||||
|
||||
|
||||
// 基础优化标志
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push("opt-level=3".to_string()); // 最高优化级别
|
||||
|
||||
|
||||
// 链接时优化
|
||||
if self.optimization_flags.enable_lto {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push("lto=fat".to_string()); // 胖LTO获得最佳优化
|
||||
}
|
||||
|
||||
|
||||
// 目标CPU优化
|
||||
if !self.optimization_flags.target_cpu.is_empty() {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push(format!("target-cpu={}", self.optimization_flags.target_cpu));
|
||||
}
|
||||
|
||||
|
||||
// 目标特性
|
||||
if !self.optimization_flags.target_features.is_empty() {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push(format!("target-feature={}", self.optimization_flags.target_features.join(",")));
|
||||
rustflags.push(format!(
|
||||
"target-feature={}",
|
||||
self.optimization_flags.target_features.join(",")
|
||||
));
|
||||
}
|
||||
|
||||
|
||||
// 代码模型
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
||||
|
||||
rustflags
|
||||
.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
||||
|
||||
// 恐慌处理
|
||||
if self.codegen_config.panic_abort {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push("panic=abort".to_string());
|
||||
}
|
||||
|
||||
|
||||
// 溢出检查
|
||||
if !self.codegen_config.overflow_checks {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push("overflow-checks=no".to_string());
|
||||
}
|
||||
|
||||
|
||||
// 代码生成单元
|
||||
if let Some(units) = self.optimization_flags.codegen_units {
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push(format!("codegen-units={}", units));
|
||||
}
|
||||
|
||||
|
||||
// 内联阈值
|
||||
rustflags.push("-C".to_string());
|
||||
rustflags.push(format!("inline-threshold={}", self.inline_strategy.inline_threshold));
|
||||
|
||||
|
||||
// 额外的性能优化标志
|
||||
rustflags.extend([
|
||||
"-C".to_string(), "embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
||||
"-C".to_string(), "debuginfo=0".to_string(), // 禁用调试信息
|
||||
"-C".to_string(), "rpath=no".to_string(), // 禁用rpath
|
||||
"-C".to_string(), "force-frame-pointers=no".to_string(), // 禁用帧指针
|
||||
"-C".to_string(),
|
||||
"embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
||||
"-C".to_string(),
|
||||
"debuginfo=0".to_string(), // 禁用调试信息
|
||||
"-C".to_string(),
|
||||
"rpath=no".to_string(), // 禁用rpath
|
||||
"-C".to_string(),
|
||||
"force-frame-pointers=no".to_string(), // 禁用帧指针
|
||||
]);
|
||||
|
||||
|
||||
let config = CompilerConfig {
|
||||
rustflags,
|
||||
env_vars: self.generate_env_vars(),
|
||||
cargo_config: self.generate_cargo_config(),
|
||||
};
|
||||
|
||||
|
||||
tracing::info!(target: "sol_trade_sdk","✅ Ultra-performance compiler configuration generated");
|
||||
Ok(config)
|
||||
}
|
||||
|
||||
|
||||
/// 生成环境变量配置
|
||||
fn generate_env_vars(&self) -> HashMap<String, String> {
|
||||
let mut env_vars = HashMap::new();
|
||||
|
||||
|
||||
// CPU特定优化
|
||||
env_vars.insert("CARGO_CFG_TARGET_FEATURE".to_string(),
|
||||
self.optimization_flags.target_features.join(","));
|
||||
|
||||
env_vars.insert(
|
||||
"CARGO_CFG_TARGET_FEATURE".to_string(),
|
||||
self.optimization_flags.target_features.join(","),
|
||||
);
|
||||
|
||||
// 启用不稳定特性
|
||||
env_vars.insert("RUSTC_BOOTSTRAP".to_string(), "1".to_string());
|
||||
|
||||
|
||||
// 编译缓存设置
|
||||
if self.optimization_flags.incremental {
|
||||
env_vars.insert("CARGO_INCREMENTAL".to_string(), "1".to_string());
|
||||
} else {
|
||||
env_vars.insert("CARGO_INCREMENTAL".to_string(), "0".to_string());
|
||||
}
|
||||
|
||||
|
||||
env_vars
|
||||
}
|
||||
|
||||
|
||||
/// 生成Cargo配置
|
||||
fn generate_cargo_config(&self) -> CargoConfig {
|
||||
CargoConfig {
|
||||
@@ -244,17 +254,21 @@ impl CompilerOptimizer {
|
||||
debug_assertions: false,
|
||||
rpath: false,
|
||||
strip: true, // 去除符号表
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 获取统计信息
|
||||
pub fn get_stats(&self) -> CompilerOptimizationStats {
|
||||
CompilerOptimizationStats {
|
||||
inlined_functions: AtomicU64::new(self.stats.inlined_functions.load(Ordering::Relaxed)),
|
||||
constant_folding: AtomicU64::new(self.stats.constant_folding.load(Ordering::Relaxed)),
|
||||
dead_code_elimination: AtomicU64::new(self.stats.dead_code_elimination.load(Ordering::Relaxed)),
|
||||
loop_optimizations: AtomicU64::new(self.stats.loop_optimizations.load(Ordering::Relaxed)),
|
||||
dead_code_elimination: AtomicU64::new(
|
||||
self.stats.dead_code_elimination.load(Ordering::Relaxed),
|
||||
),
|
||||
loop_optimizations: AtomicU64::new(
|
||||
self.stats.loop_optimizations.load(Ordering::Relaxed),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -274,17 +288,20 @@ impl OptimizationFlags {
|
||||
"+popcnt".to_string(),
|
||||
];
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
#[cfg(target_arch = "aarch64")]
|
||||
let target_features = vec!["+neon".to_string()];
|
||||
|
||||
#[cfg(not(any(target_arch = "x86_64", target_arch = "aarch64")))]
|
||||
let target_features = vec![];
|
||||
Self {
|
||||
opt_level: OptLevel::Aggressive,
|
||||
enable_lto: true,
|
||||
enable_pgo: false, // PGO需要多阶段构建
|
||||
enable_pgo: false, // PGO需要多阶段构建
|
||||
target_cpu: "native".to_string(), // 使用本机CPU特性
|
||||
target_features,
|
||||
code_model: CodeModel::Small,
|
||||
debug_info: false,
|
||||
incremental: false, // 发布版本禁用增量编译
|
||||
incremental: false, // 发布版本禁用增量编译
|
||||
codegen_units: Some(1), // 单个代码生成单元获得最佳优化
|
||||
}
|
||||
}
|
||||
@@ -294,7 +311,7 @@ impl CodegenConfig {
|
||||
/// 超高性能配置
|
||||
pub fn ultra_performance() -> Self {
|
||||
Self {
|
||||
panic_abort: true, // 恐慌即中止,避免展开开销
|
||||
panic_abort: true, // 恐慌即中止,避免展开开销
|
||||
overflow_checks: false, // 生产环境禁用溢出检查
|
||||
fat_lto: true,
|
||||
enable_simd: true,
|
||||
@@ -353,14 +370,14 @@ macro_rules! compile_time_optimize {
|
||||
(const $expr:expr) => {
|
||||
const { $expr }
|
||||
};
|
||||
|
||||
|
||||
// 强制内联热路径
|
||||
(inline_hot $fn_name:ident) => {
|
||||
#[inline(always)]
|
||||
#[hot]
|
||||
$fn_name
|
||||
};
|
||||
|
||||
|
||||
// 标记冷路径
|
||||
(cold $fn_name:ident) => {
|
||||
#[inline(never)]
|
||||
@@ -372,10 +389,10 @@ macro_rules! compile_time_optimize {
|
||||
/// 🚀 零成本抽象特征
|
||||
pub trait ZeroCostAbstraction {
|
||||
type Output;
|
||||
|
||||
|
||||
/// 编译时计算
|
||||
fn compute_at_compile_time(&self) -> Self::Output;
|
||||
|
||||
|
||||
/// 内联操作
|
||||
#[inline(always)]
|
||||
fn inline_operation(&self) -> Self::Output {
|
||||
@@ -399,35 +416,35 @@ impl CompileTimeOptimizedEventProcessor {
|
||||
route_table: Self::precompute_route_table(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// 编译时预计算哈希表
|
||||
const fn precompute_hash_table() -> [u64; 256] {
|
||||
let mut table = [0u64; 256];
|
||||
let mut i = 0;
|
||||
|
||||
|
||||
while i < 256 {
|
||||
// 使用编译时常量计算哈希值
|
||||
table[i] = Self::const_hash(i as u8);
|
||||
i += 1;
|
||||
}
|
||||
|
||||
|
||||
table
|
||||
}
|
||||
|
||||
|
||||
/// 编译时预计算路由表
|
||||
const fn precompute_route_table() -> [u32; 1024] {
|
||||
let mut table = [0u32; 1024];
|
||||
let mut i = 0;
|
||||
|
||||
|
||||
while i < 1024 {
|
||||
// 预计算路由信息
|
||||
table[i] = (i as u32) % 16; // 16个工作线程
|
||||
i += 1;
|
||||
}
|
||||
|
||||
|
||||
table
|
||||
}
|
||||
|
||||
|
||||
/// 编译时常量哈希函数
|
||||
const fn const_hash(input: u8) -> u64 {
|
||||
// 使用简单的编译时常量哈希
|
||||
@@ -437,16 +454,14 @@ impl CompileTimeOptimizedEventProcessor {
|
||||
hash ^= hash << 17;
|
||||
hash
|
||||
}
|
||||
|
||||
|
||||
/// 🚀 零开销事件路由
|
||||
#[inline(always)]
|
||||
pub fn route_event_zero_cost(&self, event_id: u8) -> u32 {
|
||||
// 编译时优化:直接数组访问,无边界检查
|
||||
unsafe {
|
||||
*self.route_table.get_unchecked((event_id as usize) & 1023)
|
||||
}
|
||||
unsafe { *self.route_table.get_unchecked((event_id as usize) & 1023) }
|
||||
}
|
||||
|
||||
|
||||
/// 🚀 编译时优化的哈希查找
|
||||
#[inline(always)]
|
||||
pub fn hash_lookup_optimized(&self, key: u8) -> u64 {
|
||||
@@ -464,28 +479,28 @@ impl SIMDCompileTimeOptimizer {
|
||||
#[target_feature(enable = "avx2")]
|
||||
pub unsafe fn vectorized_sum_compile_time(data: &[u64]) -> u64 {
|
||||
use std::arch::x86_64::*;
|
||||
|
||||
|
||||
if data.len() < 4 {
|
||||
return data.iter().sum();
|
||||
}
|
||||
|
||||
|
||||
let chunks = data.len() / 4;
|
||||
let mut sum_vec = _mm256_setzero_si256();
|
||||
|
||||
|
||||
for i in 0..chunks {
|
||||
let ptr = data.as_ptr().add(i * 4) as *const __m256i;
|
||||
let vec = _mm256_loadu_si256(ptr);
|
||||
sum_vec = _mm256_add_epi64(sum_vec, vec);
|
||||
}
|
||||
|
||||
|
||||
// 水平求和
|
||||
let mut result = [0u64; 4];
|
||||
_mm256_storeu_si256(result.as_mut_ptr() as *mut __m256i, sum_vec);
|
||||
let partial_sum: u64 = result.iter().sum();
|
||||
|
||||
|
||||
// 处理剩余元素
|
||||
let remaining: u64 = data[chunks * 4..].iter().sum();
|
||||
|
||||
|
||||
partial_sum + remaining
|
||||
}
|
||||
|
||||
@@ -523,7 +538,8 @@ fn main() {
|
||||
println!("cargo:rustc-link-arg=-fprofile-use");
|
||||
}
|
||||
}
|
||||
"#.to_string()
|
||||
"#
|
||||
.to_string()
|
||||
}
|
||||
|
||||
/// 🚀 生成.cargo/config.toml
|
||||
@@ -576,56 +592,58 @@ rustflags = [
|
||||
rustflags = [
|
||||
"-C", "target-feature=+sse4.2,+avx,+avx2,+fma,+bmi1,+bmi2,+lzcnt,+popcnt",
|
||||
]
|
||||
"#.to_string()
|
||||
"#
|
||||
.to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_compiler_optimizer_creation() {
|
||||
let optimizer = CompilerOptimizer::new();
|
||||
assert!(optimizer.optimization_flags.enable_lto);
|
||||
assert_eq!(optimizer.optimization_flags.opt_level as u8, OptLevel::Aggressive as u8);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_compile_time_processor() {
|
||||
const PROCESSOR: CompileTimeOptimizedEventProcessor = CompileTimeOptimizedEventProcessor::new();
|
||||
|
||||
const PROCESSOR: CompileTimeOptimizedEventProcessor =
|
||||
CompileTimeOptimizedEventProcessor::new();
|
||||
|
||||
let route = PROCESSOR.route_event_zero_cost(42);
|
||||
assert!(route < 16); // 应该路由到16个工作线程之一
|
||||
|
||||
|
||||
let hash = PROCESSOR.hash_lookup_optimized(100);
|
||||
assert!(hash > 0); // 哈希值应该非零
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_ultra_performance_config() {
|
||||
let flags = OptimizationFlags::ultra_performance();
|
||||
assert!(flags.enable_lto);
|
||||
assert_eq!(flags.target_cpu, "native");
|
||||
assert!(!flags.target_features.is_empty());
|
||||
|
||||
|
||||
let codegen = CodegenConfig::ultra_performance();
|
||||
assert!(codegen.panic_abort);
|
||||
assert!(!codegen.overflow_checks);
|
||||
assert!(codegen.enable_simd);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
#[test]
|
||||
fn test_compiler_config_generation() {
|
||||
let optimizer = CompilerOptimizer::new();
|
||||
let config = optimizer.generate_ultra_performance_config().unwrap();
|
||||
|
||||
|
||||
assert!(!config.rustflags.is_empty());
|
||||
assert!(config.rustflags.contains(&"-C".to_string()));
|
||||
assert!(config.rustflags.contains(&"opt-level=3".to_string()));
|
||||
|
||||
|
||||
assert!(config.env_vars.contains_key("CARGO_INCREMENTAL"));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_simd_compile_time_optimization() {
|
||||
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
|
||||
@@ -642,7 +660,7 @@ mod tests {
|
||||
assert_eq!(sum, 36); // 1+2+3+4+5+6+7+8 = 36
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_build_script_generation() {
|
||||
let build_script = generate_build_script();
|
||||
@@ -650,7 +668,7 @@ mod tests {
|
||||
assert!(build_script.contains("TARGET_FEATURE"));
|
||||
assert!(build_script.contains("lld"));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_cargo_config_generation() {
|
||||
let config = generate_cargo_config_toml();
|
||||
@@ -659,4 +677,4 @@ mod tests {
|
||||
assert!(config.contains("target-cpu=native"));
|
||||
assert!(config.contains("panic = \"abort\""));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Hardware-oriented optimizations: cache-line alignment, prefetch, SIMD, branch hints, memory barriers.
|
||||
//! 硬件级优化:缓存行对齐与预取、SIMD、分支提示、内存屏障。
|
||||
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use anyhow::Result;
|
||||
use crossbeam_utils::CachePadded;
|
||||
use std::mem::size_of;
|
||||
use std::ptr;
|
||||
use crossbeam_utils::CachePadded;
|
||||
use anyhow::Result;
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
|
||||
/// Typical CPU cache line size in bytes. 典型 CPU 缓存行大小(字节)。
|
||||
pub const CACHE_LINE_SIZE: usize = 64;
|
||||
@@ -32,7 +32,7 @@ impl SIMDMemoryOps {
|
||||
_ => Self::memcpy_avx512_or_fallback(dst, src, len),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Copy 1–8 bytes (scalar / small word). 小数据拷贝(1–8 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcpy_small(dst: *mut u8, src: *const u8, len: usize) {
|
||||
@@ -53,52 +53,52 @@ impl SIMDMemoryOps {
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Copy 9–16 bytes using SSE (128-bit). SSE 拷贝(9–16 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcpy_sse(dst: *mut u8, src: *const u8, len: usize) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_storeu_si128};
|
||||
|
||||
|
||||
if len <= 16 {
|
||||
let chunk = _mm_loadu_si128(src as *const __m128i);
|
||||
_mm_storeu_si128(dst as *mut __m128i, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
ptr::copy_nonoverlapping(src, dst, len);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Copy 17–32 bytes using AVX (256-bit). AVX 拷贝(17–32 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcpy_avx(dst: *mut u8, src: *const u8, len: usize) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
||||
|
||||
|
||||
if len <= 32 {
|
||||
let chunk = _mm256_loadu_si256(src as *const __m256i);
|
||||
_mm256_storeu_si256(dst as *mut __m256i, chunk);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
ptr::copy_nonoverlapping(src, dst, len);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Copy 33–64 bytes using AVX2 (256-bit, two chunks). AVX2 拷贝(33–64 字节,两段)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcpy_avx2(dst: *mut u8, src: *const u8, len: usize) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_storeu_si256};
|
||||
|
||||
|
||||
let chunk1 = _mm256_loadu_si256(src as *const __m256i);
|
||||
_mm256_storeu_si256(dst as *mut __m256i, chunk1);
|
||||
if len > 32 {
|
||||
@@ -109,52 +109,52 @@ impl SIMDMemoryOps {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
ptr::copy_nonoverlapping(src, dst, len);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Copy >64 bytes: AVX-512 64-byte chunks when available, else AVX2 32-byte chunks. >64 字节:有 AVX512 用 64 字节块,否则 AVX2 32 字节块。
|
||||
#[inline(always)]
|
||||
unsafe fn memcpy_avx512_or_fallback(dst: *mut u8, src: *const u8, len: usize) {
|
||||
#[cfg(all(target_arch = "x86_64", target_feature = "avx512f"))]
|
||||
{
|
||||
use std::arch::x86_64::{__m512i, _mm512_loadu_si512, _mm512_storeu_si512};
|
||||
|
||||
|
||||
let chunks = len / 64;
|
||||
let mut offset = 0;
|
||||
|
||||
|
||||
for _ in 0..chunks {
|
||||
let chunk = _mm512_loadu_si512(src.add(offset) as *const __m512i);
|
||||
_mm512_storeu_si512(dst.add(offset) as *mut __m512i, chunk);
|
||||
offset += 64;
|
||||
}
|
||||
|
||||
|
||||
let remaining = len % 64;
|
||||
if remaining > 0 {
|
||||
Self::memcpy_avx2(dst.add(offset), src.add(offset), remaining);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(all(target_arch = "x86_64", target_feature = "avx512f")))]
|
||||
{
|
||||
let chunks = len / 32;
|
||||
let mut offset = 0;
|
||||
|
||||
|
||||
for _ in 0..chunks {
|
||||
Self::memcpy_avx2(dst.add(offset), src.add(offset), 32);
|
||||
offset += 32;
|
||||
}
|
||||
|
||||
|
||||
let remaining = len % 32;
|
||||
if remaining > 0 {
|
||||
Self::memcpy_avx(dst.add(offset), src.add(offset), remaining);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// SIMD-optimized byte equality; dispatches by length (small / SSE / AVX2 / large). SIMD 加速的内存比较,按长度分派。
|
||||
#[inline(always)]
|
||||
pub unsafe fn memcmp_simd_optimized(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||
@@ -166,109 +166,115 @@ impl SIMDMemoryOps {
|
||||
_ => Self::memcmp_large(a, b, len),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Compare 1–8 bytes (scalar). 小数据比较(1–8 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcmp_small(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||
match len {
|
||||
1 => *a == *b,
|
||||
2 => *(a as *const u16) == *(b as *const u16),
|
||||
2 => ptr::read_unaligned(a as *const u16) == ptr::read_unaligned(b as *const u16),
|
||||
3 => {
|
||||
*(a as *const u16) == *(b as *const u16) &&
|
||||
*a.add(2) == *b.add(2)
|
||||
ptr::read_unaligned(a as *const u16) == ptr::read_unaligned(b as *const u16)
|
||||
&& *a.add(2) == *b.add(2)
|
||||
}
|
||||
4 => *(a as *const u32) == *(b as *const u32),
|
||||
5..=8 => *(a as *const u64) == *(b as *const u64),
|
||||
4 => ptr::read_unaligned(a as *const u32) == ptr::read_unaligned(b as *const u32),
|
||||
5..=7 => {
|
||||
ptr::read_unaligned(a as *const u32) == ptr::read_unaligned(b as *const u32)
|
||||
&& (4..len).all(|i| *a.add(i) == *b.add(i))
|
||||
}
|
||||
8 => ptr::read_unaligned(a as *const u64) == ptr::read_unaligned(b as *const u64),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Compare 9–16 bytes using SSE. SSE 比较(9–16 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_cmpeq_epi8, _mm_movemask_epi8};
|
||||
|
||||
use std::arch::x86_64::{__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8};
|
||||
|
||||
let chunk_a = _mm_loadu_si128(a as *const __m128i);
|
||||
let chunk_b = _mm_loadu_si128(b as *const __m128i);
|
||||
let cmp_result = _mm_cmpeq_epi8(chunk_a, chunk_b);
|
||||
let mask = _mm_movemask_epi8(cmp_result) as u32;
|
||||
|
||||
|
||||
let valid_mask = if len >= 16 { 0xFFFF } else { (1u32 << len) - 1 };
|
||||
(mask & valid_mask) == valid_mask
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
(0..len).all(|i| *a.add(i) == *b.add(i))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Compare 17–32 bytes using AVX2. AVX2 比较(17–32 字节)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_cmpeq_epi8, _mm256_movemask_epi8};
|
||||
|
||||
use std::arch::x86_64::{
|
||||
__m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8,
|
||||
};
|
||||
|
||||
let chunk_a = _mm256_loadu_si256(a as *const __m256i);
|
||||
let chunk_b = _mm256_loadu_si256(b as *const __m256i);
|
||||
let cmp_result = _mm256_cmpeq_epi8(chunk_a, chunk_b);
|
||||
let mask = _mm256_movemask_epi8(cmp_result) as u32;
|
||||
|
||||
|
||||
let valid_mask = if len >= 32 { 0xFFFFFFFF } else { (1u32 << len) - 1 };
|
||||
(mask & valid_mask) == valid_mask
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
(0..len).all(|i| *a.add(i) == *b.add(i))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// Compare >32 bytes in 32-byte AVX2 chunks. 大数据比较(32 字节 AVX2 分块)。
|
||||
#[inline(always)]
|
||||
unsafe fn memcmp_large(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||
let chunks = len / 32;
|
||||
|
||||
|
||||
for i in 0..chunks {
|
||||
let offset = i * 32;
|
||||
if !Self::memcmp_avx2(a.add(offset), b.add(offset), 32) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
let remaining = len % 32;
|
||||
if remaining > 0 {
|
||||
return Self::memcmp_avx2(a.add(chunks * 32), b.add(chunks * 32), remaining);
|
||||
}
|
||||
|
||||
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
/// SIMD-optimized zero memory. SIMD 加速的内存清零。
|
||||
#[inline(always)]
|
||||
pub unsafe fn memzero_simd_optimized(ptr: *mut u8, len: usize) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
{
|
||||
use std::arch::x86_64::{__m256i, _mm256_setzero_si256, _mm256_storeu_si256};
|
||||
|
||||
|
||||
let zero = _mm256_setzero_si256();
|
||||
let chunks = len / 32;
|
||||
let mut offset = 0;
|
||||
|
||||
|
||||
for _ in 0..chunks {
|
||||
_mm256_storeu_si256(ptr.add(offset) as *mut __m256i, zero);
|
||||
offset += 32;
|
||||
}
|
||||
|
||||
|
||||
let remaining = len % 32;
|
||||
for i in 0..remaining {
|
||||
*ptr.add(offset + i) = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(not(target_arch = "x86_64"))]
|
||||
{
|
||||
ptr::write_bytes(ptr, 0, len);
|
||||
@@ -291,17 +297,17 @@ impl CacheAlignedCounter {
|
||||
_padding: [0; CACHE_LINE_SIZE - size_of::<AtomicU64>()],
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[inline(always)]
|
||||
pub fn increment(&self) -> u64 {
|
||||
self.value.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
|
||||
|
||||
#[inline(always)]
|
||||
pub fn load(&self) -> u64 {
|
||||
self.value.load(Ordering::Relaxed)
|
||||
}
|
||||
|
||||
|
||||
#[inline(always)]
|
||||
pub fn store(&self, val: u64) {
|
||||
self.value.store(val, Ordering::Relaxed)
|
||||
@@ -312,7 +318,7 @@ impl CacheLineAligned for CacheAlignedCounter {
|
||||
fn ensure_cache_aligned(&self) -> bool {
|
||||
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
||||
}
|
||||
|
||||
|
||||
fn prefetch_data(&self) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
unsafe {
|
||||
@@ -339,10 +345,10 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||
if !capacity.is_power_of_two() {
|
||||
return Err(anyhow::anyhow!("Capacity must be a power of 2"));
|
||||
}
|
||||
|
||||
|
||||
let mut buffer = Vec::with_capacity(capacity);
|
||||
buffer.resize_with(capacity, Default::default);
|
||||
|
||||
|
||||
Ok(Self {
|
||||
buffer,
|
||||
producer_head: CachePadded::new(AtomicU64::new(0)),
|
||||
@@ -351,7 +357,7 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||
mask: capacity - 1,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
/// Lock-free push; returns false if full. 无锁写入,满则返回 false。
|
||||
#[inline(always)]
|
||||
pub fn try_push(&self, item: T) -> bool {
|
||||
@@ -368,7 +374,7 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||
self.producer_head.store(current_head + 1, Ordering::Release);
|
||||
true
|
||||
}
|
||||
|
||||
|
||||
/// Lock-free pop; returns None if empty. 无锁读取,空则返回 None。
|
||||
#[inline(always)]
|
||||
pub fn try_pop(&self) -> Option<T> {
|
||||
@@ -385,7 +391,7 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||
self.consumer_tail.store(current_tail + 1, Ordering::Release);
|
||||
Some(item)
|
||||
}
|
||||
|
||||
|
||||
/// Current number of elements. 当前元素个数。
|
||||
#[inline(always)]
|
||||
pub fn len(&self) -> usize {
|
||||
@@ -393,12 +399,11 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
||||
let tail = self.consumer_tail.load(Ordering::Relaxed);
|
||||
((head + self.capacity as u64 - tail) & self.mask as u64) as usize
|
||||
}
|
||||
|
||||
|
||||
/// True if no elements. 是否为空。
|
||||
#[inline(always)]
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.producer_head.load(Ordering::Relaxed) ==
|
||||
self.consumer_tail.load(Ordering::Relaxed)
|
||||
self.producer_head.load(Ordering::Relaxed) == self.consumer_tail.load(Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -406,7 +411,7 @@ impl<T> CacheLineAligned for CacheOptimizedRingBuffer<T> {
|
||||
fn ensure_cache_aligned(&self) -> bool {
|
||||
(self as *const Self as usize) % CACHE_LINE_SIZE == 0
|
||||
}
|
||||
|
||||
|
||||
fn prefetch_data(&self) {
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
unsafe {
|
||||
@@ -428,44 +433,44 @@ impl BranchOptimizer {
|
||||
pub fn likely(condition: bool) -> bool {
|
||||
#[cold]
|
||||
fn cold() {}
|
||||
|
||||
|
||||
if !condition {
|
||||
cold();
|
||||
}
|
||||
condition
|
||||
}
|
||||
|
||||
|
||||
/// Hint: condition is usually false. 提示编译器条件大概率为假。
|
||||
#[inline(always)]
|
||||
pub fn unlikely(condition: bool) -> bool {
|
||||
#[cold]
|
||||
fn cold() {}
|
||||
|
||||
|
||||
if condition {
|
||||
cold();
|
||||
}
|
||||
condition
|
||||
}
|
||||
|
||||
|
||||
/// Prefetch: load cache line at ptr into L1. Caller must ensure ptr is valid, read-only, no concurrent write. 预取:将 ptr 所在缓存行加载到 L1;调用方需保证有效、只读、无并发写。
|
||||
#[inline(always)]
|
||||
pub unsafe fn prefetch_read_data<T>(ptr: *const T) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -479,25 +484,25 @@ impl MemoryBarriers {
|
||||
pub fn compiler_barrier() {
|
||||
std::sync::atomic::compiler_fence(Ordering::SeqCst);
|
||||
}
|
||||
|
||||
|
||||
/// Light barrier (Acquire). 轻量级屏障(Acquire)。
|
||||
#[inline(always)]
|
||||
pub fn memory_barrier_light() {
|
||||
std::sync::atomic::fence(Ordering::Acquire);
|
||||
}
|
||||
|
||||
|
||||
/// Full sequential consistency barrier. 全序一致性屏障。
|
||||
#[inline(always)]
|
||||
pub fn memory_barrier_heavy() {
|
||||
std::sync::atomic::fence(Ordering::SeqCst);
|
||||
}
|
||||
|
||||
|
||||
/// Store/release barrier. 存储屏障,保证写入可见性。
|
||||
#[inline(always)]
|
||||
pub fn store_barrier() {
|
||||
std::sync::atomic::fence(Ordering::Release);
|
||||
}
|
||||
|
||||
|
||||
/// Load/acquire barrier. 加载屏障,保证读取顺序。
|
||||
#[inline(always)]
|
||||
pub fn load_barrier() {
|
||||
@@ -508,63 +513,54 @@ impl MemoryBarriers {
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_cache_aligned_counter() {
|
||||
let counter = CacheAlignedCounter::new(0);
|
||||
assert!(counter.ensure_cache_aligned());
|
||||
|
||||
|
||||
assert_eq!(counter.load(), 0);
|
||||
counter.increment();
|
||||
assert_eq!(counter.load(), 1);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_simd_memcpy() {
|
||||
let src = [1u8, 2, 3, 4, 5, 6, 7, 8, 9, 10];
|
||||
let mut dst = [0u8; 10];
|
||||
|
||||
|
||||
unsafe {
|
||||
SIMDMemoryOps::memcpy_simd_optimized(
|
||||
dst.as_mut_ptr(),
|
||||
src.as_ptr(),
|
||||
src.len()
|
||||
);
|
||||
SIMDMemoryOps::memcpy_simd_optimized(dst.as_mut_ptr(), src.as_ptr(), src.len());
|
||||
}
|
||||
|
||||
|
||||
assert_eq!(src, dst);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_cache_optimized_ring_buffer() {
|
||||
let buffer: CacheOptimizedRingBuffer<u64> =
|
||||
CacheOptimizedRingBuffer::new(16).unwrap();
|
||||
|
||||
let buffer: CacheOptimizedRingBuffer<u64> = CacheOptimizedRingBuffer::new(16).unwrap();
|
||||
|
||||
assert!(buffer.is_empty());
|
||||
|
||||
|
||||
// 测试推入
|
||||
assert!(buffer.try_push(42));
|
||||
assert_eq!(buffer.len(), 1);
|
||||
|
||||
|
||||
// 测试弹出
|
||||
assert_eq!(buffer.try_pop(), Some(42));
|
||||
assert!(buffer.is_empty());
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_simd_memcmp() {
|
||||
let a = [1u8, 2, 3, 4, 5];
|
||||
let b = [1u8, 2, 3, 4, 5];
|
||||
let c = [1u8, 2, 3, 4, 6];
|
||||
|
||||
|
||||
unsafe {
|
||||
assert!(SIMDMemoryOps::memcmp_simd_optimized(
|
||||
a.as_ptr(), b.as_ptr(), a.len()
|
||||
));
|
||||
|
||||
assert!(!SIMDMemoryOps::memcmp_simd_optimized(
|
||||
a.as_ptr(), c.as_ptr(), a.len()
|
||||
));
|
||||
assert!(SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), b.as_ptr(), a.len()));
|
||||
|
||||
assert!(!SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), c.as_ptr(), a.len()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+8
-8
@@ -1,14 +1,14 @@
|
||||
//! Performance: SIMD, cache prefetch, branch hints, zero-copy I/O, syscall bypass, compiler hints.
|
||||
//! 性能优化:SIMD、缓存预取、分支提示、零拷贝 I/O、系统调用绕过、编译器提示。
|
||||
|
||||
pub mod simd;
|
||||
pub mod hardware_optimizations;
|
||||
pub mod zero_copy_io;
|
||||
pub mod syscall_bypass;
|
||||
pub mod compiler_optimization;
|
||||
pub mod hardware_optimizations;
|
||||
pub mod simd;
|
||||
pub mod syscall_bypass;
|
||||
pub mod zero_copy_io;
|
||||
|
||||
pub use simd::*;
|
||||
pub use hardware_optimizations::*;
|
||||
pub use zero_copy_io::*;
|
||||
pub use syscall_bypass::*;
|
||||
pub use compiler_optimization::*;
|
||||
pub use hardware_optimizations::*;
|
||||
pub use simd::*;
|
||||
pub use syscall_bypass::*;
|
||||
pub use zero_copy_io::*;
|
||||
|
||||
+1
-1
@@ -235,7 +235,7 @@ impl SIMDHash {
|
||||
/// 批量计算 SHA256 哈希
|
||||
#[inline(always)]
|
||||
pub fn hash_batch_sha256(data: &[&[u8]]) -> Vec<[u8; 32]> {
|
||||
use sha2::{Sha256, Digest};
|
||||
use sha2::{Digest, Sha256};
|
||||
|
||||
data.iter()
|
||||
.map(|item| {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user