Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
667d6d2c5b | ||
|
|
e957bc4bee | ||
|
|
274636abc5 | ||
|
|
2abcf3839e | ||
|
|
0ec826fcbd | ||
|
|
6607d276db |
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "sol-trade-sdk"
|
name = "sol-trade-sdk"
|
||||||
version = "3.6.2"
|
version = "3.6.3"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
authors = [
|
authors = [
|
||||||
"William <byteblock6@gmail.com>",
|
"William <byteblock6@gmail.com>",
|
||||||
|
|||||||
@@ -90,14 +90,14 @@ Add the dependency to your `Cargo.toml`:
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
# Add to your Cargo.toml
|
# Add to your Cargo.toml
|
||||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.2" }
|
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.3" }
|
||||||
```
|
```
|
||||||
|
|
||||||
### Use crates.io
|
### Use crates.io
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
# Add to your Cargo.toml
|
# Add to your Cargo.toml
|
||||||
sol-trade-sdk = "3.6.2"
|
sol-trade-sdk = "3.6.3"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ Usage Examples
|
## 🛠️ Usage Examples
|
||||||
|
|||||||
+2
-2
@@ -90,14 +90,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
# 添加到您的 Cargo.toml
|
# 添加到您的 Cargo.toml
|
||||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.2" }
|
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.3" }
|
||||||
```
|
```
|
||||||
|
|
||||||
### 使用 crates.io
|
### 使用 crates.io
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
# 添加到您的 Cargo.toml
|
# 添加到您的 Cargo.toml
|
||||||
sol-trade-sdk = "3.6.2"
|
sol-trade-sdk = "3.6.3"
|
||||||
```
|
```
|
||||||
|
|
||||||
## 🛠️ 使用示例
|
## 🛠️ 使用示例
|
||||||
|
|||||||
@@ -1,16 +0,0 @@
|
|||||||
## sol-trade-sdk v3.6.2
|
|
||||||
|
|
||||||
### Changes
|
|
||||||
|
|
||||||
- **Node1 QUIC support** — Node1 SWQOS can use QUIC transport: `SwqosConfig::Node1(api_token, region, custom_url, Some(SwqosTransport::Quic))`. Uses UUID auth on first bi stream, one bi stream per transaction, bincode-serialized `VersionedTransaction`. Region endpoints: `SWQOS_ENDPOINTS_NODE1_QUIC` (ny, fra, ams, lon, tk). New dependency: `uuid`.
|
|
||||||
- **Speedlanding QUIC reliability** — Proactive connection check before send (`ensure_connected()`); 5s connect and send timeouts; reconnect uses `lock().await` so concurrent senders wait for the new connection instead of failing on `try_lock()`; TLS SNI is derived from the endpoint host (e.g. `nyc.speedlanding.trade`) with fallback to `speed-landing` for IP or unknown host. Addresses user reports of transactions failing to send.
|
|
||||||
|
|
||||||
### Crates.io
|
|
||||||
|
|
||||||
```toml
|
|
||||||
sol-trade-sdk = "3.6.2"
|
|
||||||
```
|
|
||||||
|
|
||||||
### Repository
|
|
||||||
|
|
||||||
- **Tag:** [v3.6.2](https://github.com/0xfnzero/sol-trade-sdk/releases/tag/v3.6.2)
|
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
# Release v3.6.3
|
||||||
|
|
||||||
|
## Changes from v3.6.2
|
||||||
|
|
||||||
|
### Parallel multi-SWQoS submit
|
||||||
|
|
||||||
|
- **Transaction builder pool**: Introduced `PARALLEL_SENDER_COUNT` (18) and ensured pool prefill is at least 18, so that when using dedicated sender threads all channels can acquire a builder without waiting or allocating. Prefill is now 64 with a guaranteed minimum of 18.
|
||||||
|
- **Async executor**: Documented that builder pool prefill must match the dedicated sender thread count so multi-channel submit never serializes on `build_transaction`.
|
||||||
|
- **Executor logging**: Submit timings are no longer sorted before printing (avoids any extra work on the hot path). Log order reflects completion order (first-completed first); the last line is the slowest channel in that batch.
|
||||||
|
|
||||||
|
### Other
|
||||||
|
|
||||||
|
- Added `docs/ASYNC_EXECUTOR_REVIEW.md`.
|
||||||
|
- Minor updates in types, lib, params, and middleware example.
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# async_executor 逻辑与超低延迟 / 无锁竞争 审查
|
||||||
|
|
||||||
|
## 1. 逻辑正确性
|
||||||
|
|
||||||
|
- **execute_parallel 流程**:预计算 task_configs → 建一次 shared + collector → 选 queue/notify(专属池或 tokio 池)→ 填 tip_cache、组 SwqosJob、全部 push → notify_waiters → 根据 wait_transaction_confirmed 调 wait_for_success 或 wait_for_all_submitted。逻辑正确。
|
||||||
|
- **ResultCollector**:submit 用无锁 ArrayQueue + 原子标志;wait_for_success 先看 success_flag/landed_failed_flag 再 drain results。先成功即返回,未 drain 到的后续结果会随 collector 丢弃,符合「任一成功即返回」语义。
|
||||||
|
- **ensure_swqos_pool**:SWQOS_WORKERS_STARTED 用 swap 保证只初始化一次;队列由 execute_parallel 侧 get_or_init,再传给 ensure_swqos_pool,先起 worker 再 push,顺序正确。
|
||||||
|
- **ensure_dedicated_pool**:在 Mutex 内判空、创建 queue/notify、spawn 线程、存 JoinHandles,返回 (queue, notify)。首次调用持锁完成初始化,后续调用每次持锁取 (queue, notify) 再返回。
|
||||||
|
- **tip_cache**:用 `Arc::as_ptr(&swqos_client)` 做 key,按 client 身份去重,正确。
|
||||||
|
|
||||||
|
## 2. 锁竞争与超低延迟
|
||||||
|
|
||||||
|
- **DEDICATED_POOL 的 Mutex**:专属线程池开启时,**每次** execute_parallel 都会调 ensure_dedicated_pool,从而 **每次** 对 DEDICATED_POOL 加锁一次,仅为了读已有的 (queue, notify)。高并发下会成为争用点。
|
||||||
|
- **优化**:初始化完成后,queue/notify 存到 OnceCell,热路径只做 OnceCell::get + Arc::clone,不再碰 Mutex。
|
||||||
|
- **其余**:ArrayQueue(无锁 MPMC)、ResultCollector(ArrayQueue + 原子变量)、Notify 均无额外锁,合适。
|
||||||
|
|
||||||
|
## 3. 已实现的优化
|
||||||
|
|
||||||
|
- **专属池热路径无锁**:`DEDICATED_QUEUE` / `DEDICATED_NOTIFY` 改为 `OnceCell` 存储;`DEDICATED_INIT` 仅存 `JoinHandle` 并在初始化时持锁。热路径先读 OnceCell,命中则直接 `Arc::clone` 返回,不再加锁;未命中时再持锁做一次性初始化并 set OnceCell。
|
||||||
|
|
||||||
|
## 4. 其他说明
|
||||||
|
|
||||||
|
- **wait_for_success 与 drain**:先读 `success_flag` 再 `while let Some(...) = results.pop()` 时,若某 worker 刚 store(success) 尚未 push(result),可能本轮 drain 为空,则 `!signatures.is_empty()` 不成立,不会 return,下一轮轮询会再 drain,逻辑正确。
|
||||||
|
- **SWQOS_QUEUE / SWQOS_NOTIFY**:tokio 池侧已用 OnceCell,无每次加锁。
|
||||||
@@ -16,7 +16,10 @@ use sol_trade_sdk::common::{GasFeeStrategy, TradeConfig};
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -63,7 +66,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
loop {
|
loop {
|
||||||
if let Some(event) = queue.pop() {
|
if let Some(event) = queue.pop() {
|
||||||
let run = match &event {
|
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) {
|
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||||
Some(e.clone())
|
Some(e.clone())
|
||||||
} else {
|
} else {
|
||||||
@@ -123,7 +128,9 @@ async fn pumpfun_copy_trade_with_grpc(
|
|||||||
|
|
||||||
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
let lookup_table_key = Pubkey::from_str("use_your_lookup_table_key_here").unwrap();
|
||||||
let address_lookup_table_account =
|
let address_lookup_table_account =
|
||||||
fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key).await.ok();
|
fetch_address_lookup_table_account(&client.infrastructure.rpc, &lookup_table_key)
|
||||||
|
.await
|
||||||
|
.ok();
|
||||||
|
|
||||||
let gas_fee_strategy = GasFeeStrategy::new();
|
let gas_fee_strategy = GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|||||||
@@ -10,7 +10,10 @@ use sol_trade_sdk::common::{
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{BonkParams, DexParamEnum},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -127,14 +130,7 @@ async fn bonk_copy_trade_with_grpc(trade_info: BonkTradeEvent) -> AnyResult<()>
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = GasFeeStrategy::new();
|
let gas_fee_strategy = GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buy tokens
|
// Buy tokens
|
||||||
println!("Buying tokens from Bonk...");
|
println!("Buying tokens from Bonk...");
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::common::TradeConfig;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{BonkParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{BonkParams, DexParamEnum},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -95,14 +98,7 @@ async fn bonk_sniper_trade_with_shreds(trade_info: BonkTradeEvent) -> AnyResult<
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
let token_type = if trade_info.quote_token_mint == sol_trade_sdk::constants::USD1_TOKEN_ACCOUNT
|
let token_type = if trade_info.quote_token_mint == sol_trade_sdk::constants::USD1_TOKEN_ACCOUNT
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -12,7 +12,8 @@ use sol_trade_sdk::{
|
|||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{
|
trading::{
|
||||||
core::params::{
|
core::params::{
|
||||||
BonkParams, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params, RaydiumCpmmParams, DexParamEnum,
|
BonkParams, DexParamEnum, PumpFunParams, PumpSwapParams, RaydiumAmmV4Params,
|
||||||
|
RaydiumCpmmParams,
|
||||||
},
|
},
|
||||||
factory::DexType,
|
factory::DexType,
|
||||||
},
|
},
|
||||||
@@ -721,7 +722,8 @@ async fn handle_buy_bonk(
|
|||||||
println!(" Slippage: {}%", slippage.unwrap());
|
println!(" Slippage: {}%", slippage.unwrap());
|
||||||
}
|
}
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
let param =
|
||||||
|
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -780,7 +782,8 @@ async fn handle_buy_raydium_v4(
|
|||||||
|
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
let param =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -839,7 +842,9 @@ async fn handle_buy_raydium_cpmm(
|
|||||||
|
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
let param =
|
||||||
|
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||||
|
.await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
let sol_lamports = sol_str_to_lamports(sol_amount.to_string().as_str()).unwrap();
|
||||||
|
|
||||||
@@ -1126,7 +1131,8 @@ async fn handle_sell_bonk(
|
|||||||
}
|
}
|
||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
let param =
|
||||||
|
BonkParams::from_mint_by_rpc(&client.infrastructure.rpc, &mint_pubkey, false).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
@@ -1187,7 +1193,8 @@ async fn handle_sell_raydium_v4(
|
|||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let amm_pubkey = Pubkey::from_str(amm)?;
|
let amm_pubkey = Pubkey::from_str(amm)?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
let param =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, amm_pubkey).await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
@@ -1248,7 +1255,9 @@ async fn handle_sell_raydium_cpmm(
|
|||||||
let client = initialize_real_client().await?;
|
let client = initialize_real_client().await?;
|
||||||
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
let pool_pubkey = Pubkey::from_str(pool_address)?;
|
||||||
let mint_pubkey = Pubkey::from_str(mint)?;
|
let mint_pubkey = Pubkey::from_str(mint)?;
|
||||||
let param = RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey).await?;
|
let param =
|
||||||
|
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_pubkey)
|
||||||
|
.await?;
|
||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
SolanaTrade, TradeTokenType, common::{
|
common::{
|
||||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
}, swqos::SwqosConfig, trading::{core::params::{MeteoraDammV2Params, DexParamEnum}, factory::DexType}
|
},
|
||||||
|
swqos::SwqosConfig,
|
||||||
|
trading::{
|
||||||
|
core::params::{DexParamEnum, MeteoraDammV2Params},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
@@ -32,7 +38,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points: slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::MeteoraDammV2(
|
extension_params: DexParamEnum::MeteoraDammV2(
|
||||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
@@ -54,7 +61,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM;
|
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM;
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
println!("Token balance: {}", amount_token);
|
println!("Token balance: {}", amount_token);
|
||||||
@@ -67,7 +79,8 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
with_tip: false,
|
with_tip: false,
|
||||||
extension_params: DexParamEnum::MeteoraDammV2(
|
extension_params: DexParamEnum::MeteoraDammV2(
|
||||||
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool).await?,
|
MeteoraDammV2Params::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
|
|||||||
@@ -3,7 +3,8 @@ use sol_trade_sdk::{
|
|||||||
common::{AnyResult, TradeConfig},
|
common::{AnyResult, TradeConfig},
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{
|
trading::{
|
||||||
core::params::{PumpSwapParams, DexParamEnum}, factory::DexType,
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
InstructionMiddleware, MiddlewareManager,
|
InstructionMiddleware, MiddlewareManager,
|
||||||
},
|
},
|
||||||
SolanaTrade, TradeTokenType,
|
SolanaTrade, TradeTokenType,
|
||||||
@@ -30,7 +31,7 @@ impl InstructionMiddleware for CustomMiddleware {
|
|||||||
fn process_protocol_instructions(
|
fn process_protocol_instructions(
|
||||||
&self,
|
&self,
|
||||||
protocol_instructions: Vec<Instruction>,
|
protocol_instructions: Vec<Instruction>,
|
||||||
_protocol_name: String,
|
_protocol_name: &str,
|
||||||
_is_buy: bool,
|
_is_buy: bool,
|
||||||
) -> Result<Vec<Instruction>> {
|
) -> Result<Vec<Instruction>> {
|
||||||
// do anything you want here
|
// do anything you want here
|
||||||
@@ -41,7 +42,7 @@ impl InstructionMiddleware for CustomMiddleware {
|
|||||||
fn process_full_instructions(
|
fn process_full_instructions(
|
||||||
&self,
|
&self,
|
||||||
full_instructions: Vec<Instruction>,
|
full_instructions: Vec<Instruction>,
|
||||||
_protocol_name: String,
|
_protocol_name: &str,
|
||||||
_is_buy: bool,
|
_is_buy: bool,
|
||||||
) -> Result<Vec<Instruction>> {
|
) -> Result<Vec<Instruction>> {
|
||||||
// do anything you want here
|
// do anything you want here
|
||||||
@@ -91,7 +92,8 @@ async fn test_middleware() -> AnyResult<()> {
|
|||||||
slippage_basis_points: slippage_basis_points,
|
slippage_basis_points: slippage_basis_points,
|
||||||
recent_blockhash: Some(recent_blockhash),
|
recent_blockhash: Some(recent_blockhash),
|
||||||
extension_params: DexParamEnum::PumpSwap(
|
extension_params: DexParamEnum::PumpSwap(
|
||||||
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address).await?,
|
PumpSwapParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &pool_address)
|
||||||
|
.await?,
|
||||||
),
|
),
|
||||||
address_lookup_table_account: None,
|
address_lookup_table_account: None,
|
||||||
wait_transaction_confirmed: true,
|
wait_transaction_confirmed: true,
|
||||||
|
|||||||
@@ -16,7 +16,10 @@ use sol_trade_sdk::TradeTokenType;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -62,7 +65,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
loop {
|
loop {
|
||||||
if let Some(event) = queue.pop() {
|
if let Some(event) = queue.pop() {
|
||||||
let run = match &event {
|
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) {
|
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||||
Some(e.clone())
|
Some(e.clone())
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,7 +2,10 @@
|
|||||||
//!
|
//!
|
||||||
//! 收到 PumpFun 买卖事件后,用事件中的参数(含 is_cashback_coin)构造交易并执行一次买+卖。
|
//! 收到 PumpFun 买卖事件后,用事件中的参数(含 is_cashback_coin)构造交易并执行一次买+卖。
|
||||||
|
|
||||||
use std::sync::{atomic::{AtomicBool, Ordering}, Arc};
|
use std::sync::{
|
||||||
|
atomic::{AtomicBool, Ordering},
|
||||||
|
Arc,
|
||||||
|
};
|
||||||
|
|
||||||
use sol_parser_sdk::grpc::{
|
use sol_parser_sdk::grpc::{
|
||||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||||
@@ -16,7 +19,10 @@ use sol_trade_sdk::TradeTokenType;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -65,7 +71,9 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
loop {
|
loop {
|
||||||
if let Some(event) = queue.pop() {
|
if let Some(event) = queue.pop() {
|
||||||
let run = match &event {
|
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) {
|
if !ALREADY_EXECUTED.swap(true, Ordering::SeqCst) {
|
||||||
Some(e.clone())
|
Some(e.clone())
|
||||||
} else {
|
} else {
|
||||||
@@ -102,16 +110,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = 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 commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||||
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pumpfun_copy_trade(
|
async fn pumpfun_copy_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||||
e: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
|
||||||
) -> AnyResult<()> {
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
let mint_pubkey = e.mint;
|
let mint_pubkey = e.mint;
|
||||||
let slippage_basis_points = Some(100u64);
|
let slippage_basis_points = Some(100u64);
|
||||||
|
|||||||
@@ -3,7 +3,10 @@
|
|||||||
//! 监听创建者首次买入(Create 后同笔/首笔 Buy,is_created_buy == true),
|
//! 监听创建者首次买入(Create 后同笔/首笔 Buy,is_created_buy == true),
|
||||||
//! 用事件参数(含 is_cashback_coin)构造 from_dev_trade 并执行一次买+卖。
|
//! 用事件参数(含 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::{
|
use sol_parser_sdk::grpc::{
|
||||||
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
AccountFilter, ClientConfig, EventType, EventTypeFilter, OrderMode, Protocol,
|
||||||
@@ -16,7 +19,10 @@ use sol_trade_sdk::TradeTokenType;
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpFunParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpFunParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -94,16 +100,15 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
|
|
||||||
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
async fn create_solana_trade_client() -> AnyResult<SolanaTrade> {
|
||||||
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
let payer = Keypair::from_base58_string("use_your_payer_keypair_here");
|
||||||
let rpc_url = 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 commitment = CommitmentConfig::confirmed();
|
||||||
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
let swqos_configs: Vec<SwqosConfig> = vec![SwqosConfig::Default(rpc_url.clone())];
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment);
|
||||||
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
Ok(SolanaTrade::new(Arc::new(payer), trade_config).await)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn pumpfun_sniper_trade(
|
async fn pumpfun_sniper_trade(e: sol_parser_sdk::core::events::PumpFunTradeEvent) -> AnyResult<()> {
|
||||||
e: sol_parser_sdk::core::events::PumpFunTradeEvent,
|
|
||||||
) -> AnyResult<()> {
|
|
||||||
let client = create_solana_trade_client().await?;
|
let client = create_solana_trade_client().await?;
|
||||||
let mint_pubkey = e.mint;
|
let mint_pubkey = e.mint;
|
||||||
let slippage_basis_points = Some(300u64);
|
let slippage_basis_points = Some(300u64);
|
||||||
|
|||||||
@@ -1,7 +1,13 @@
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
SolanaTrade, TradeTokenType, common::{
|
common::{
|
||||||
AnyResult, TradeConfig, fast_fn::get_associated_token_address_with_program_id_fast_use_seed
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
}, swqos::SwqosConfig, trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType}
|
},
|
||||||
|
swqos::SwqosConfig,
|
||||||
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
use solana_sdk::signature::Keypair;
|
use solana_sdk::signature::Keypair;
|
||||||
@@ -54,7 +60,12 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
let rpc = client.infrastructure.rpc.clone();
|
let rpc = client.infrastructure.rpc.clone();
|
||||||
let payer = client.payer.pubkey();
|
let payer = client.payer.pubkey();
|
||||||
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM_2022;
|
let program_id = sol_trade_sdk::constants::TOKEN_PROGRAM_2022;
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
|
|||||||
@@ -1,11 +1,14 @@
|
|||||||
use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed;
|
use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed;
|
||||||
use sol_trade_sdk::common::TradeConfig;
|
use sol_trade_sdk::common::TradeConfig;
|
||||||
use sol_trade_sdk::TradeTokenType;
|
|
||||||
use sol_trade_sdk::instruction::utils::pumpswap::fetch_pool;
|
use sol_trade_sdk::instruction::utils::pumpswap::fetch_pool;
|
||||||
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
@@ -244,7 +247,12 @@ async fn pumpswap_trade_with_grpc(
|
|||||||
} else {
|
} else {
|
||||||
params.quote_token_program
|
params.quote_token_program
|
||||||
};
|
};
|
||||||
let account = get_associated_token_address_with_program_id_fast_use_seed(&payer, &mint_pubkey, &program_id, client.use_seed_optimize);
|
let account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
|
&payer,
|
||||||
|
&mint_pubkey,
|
||||||
|
&program_id,
|
||||||
|
client.use_seed_optimize,
|
||||||
|
);
|
||||||
let balance = rpc.get_token_account_balance(&account).await?;
|
let balance = rpc.get_token_account_balance(&account).await?;
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
|
|||||||
@@ -2,7 +2,10 @@ use sol_trade_sdk::common::fast_fn::get_associated_token_address_with_program_id
|
|||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
common::AnyResult,
|
common::AnyResult,
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{RaydiumAmmV4Params, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, RaydiumAmmV4Params},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade,
|
SolanaTrade,
|
||||||
};
|
};
|
||||||
use sol_trade_sdk::{
|
use sol_trade_sdk::{
|
||||||
@@ -122,8 +125,12 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = client.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
|
|
||||||
let amm_info = fetch_amm_info(&client.infrastructure.rpc, trade_info.amm).await?;
|
let amm_info = fetch_amm_info(&client.infrastructure.rpc, trade_info.amm).await?;
|
||||||
let (coin_reserve, pc_reserve) =
|
let (coin_reserve, pc_reserve) = get_multi_token_balances(
|
||||||
get_multi_token_balances(&client.infrastructure.rpc, &amm_info.token_coin, &amm_info.token_pc).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&amm_info.token_coin,
|
||||||
|
&amm_info.token_pc,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
let mint_pubkey = if amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
let mint_pubkey = if amm_info.pc_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| amm_info.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
|| amm_info.pc_mint == sol_trade_sdk::constants::USDC_TOKEN_ACCOUNT
|
||||||
{
|
{
|
||||||
@@ -142,14 +149,7 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
);
|
);
|
||||||
|
|
||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
150000,
|
|
||||||
150000,
|
|
||||||
500000,
|
|
||||||
500000,
|
|
||||||
0.001,
|
|
||||||
0.001,
|
|
||||||
);
|
|
||||||
|
|
||||||
// Buy tokens
|
// Buy tokens
|
||||||
println!("Buying tokens from Raydium_amm_v4...");
|
println!("Buying tokens from Raydium_amm_v4...");
|
||||||
@@ -194,7 +194,9 @@ async fn raydium_amm_v4_copy_trade_with_grpc(trade_info: RaydiumAmmV4SwapEvent)
|
|||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
println!("Selling {} tokens", amount_token);
|
||||||
let params = RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm).await?;
|
let params =
|
||||||
|
RaydiumAmmV4Params::from_amm_address_by_rpc(&client.infrastructure.rpc, trade_info.amm)
|
||||||
|
.await?;
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
dex_type: DexType::RaydiumAmmV4,
|
dex_type: DexType::RaydiumAmmV4,
|
||||||
output_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
output_token_type: if is_wsol { TradeTokenType::WSOL } else { TradeTokenType::USDC },
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
use sol_trade_sdk::common::spl_associated_token_account::get_associated_token_address;
|
||||||
use sol_trade_sdk::common::TradeConfig;
|
use sol_trade_sdk::common::TradeConfig;
|
||||||
use sol_trade_sdk::constants::{WSOL_TOKEN_ACCOUNT, USDC_TOKEN_ACCOUNT};
|
use sol_trade_sdk::constants::{USDC_TOKEN_ACCOUNT, WSOL_TOKEN_ACCOUNT};
|
||||||
use sol_trade_sdk::trading::core::params::{RaydiumCpmmParams, DexParamEnum};
|
use sol_trade_sdk::trading::core::params::{DexParamEnum, RaydiumCpmmParams};
|
||||||
use sol_trade_sdk::trading::factory::DexType;
|
use sol_trade_sdk::trading::factory::DexType;
|
||||||
use sol_trade_sdk::TradeTokenType;
|
use sol_trade_sdk::TradeTokenType;
|
||||||
use sol_trade_sdk::{common::AnyResult, swqos::SwqosConfig, SolanaTrade};
|
use sol_trade_sdk::{common::AnyResult, swqos::SwqosConfig, SolanaTrade};
|
||||||
@@ -132,8 +132,11 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
let gas_fee_strategy = sol_trade_sdk::common::GasFeeStrategy::new();
|
||||||
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
gas_fee_strategy.set_global_fee_strategy(150000, 150000, 500000, 500000, 0.001, 0.001);
|
||||||
|
|
||||||
let buy_params =
|
let buy_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&trade_info.pool_state,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
let is_wsol = trade_info.input_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
let is_wsol = trade_info.input_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|| trade_info.output_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
|| trade_info.output_token_mint == sol_trade_sdk::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
@@ -173,8 +176,11 @@ async fn raydium_cpmm_copy_trade_with_grpc(trade_info: RaydiumCpmmSwapEvent) ->
|
|||||||
println!("Balance: {:?}", balance);
|
println!("Balance: {:?}", balance);
|
||||||
let amount_token = balance.amount.parse::<u64>().unwrap();
|
let amount_token = balance.amount.parse::<u64>().unwrap();
|
||||||
|
|
||||||
let sell_params =
|
let sell_params = RaydiumCpmmParams::from_pool_address_by_rpc(
|
||||||
RaydiumCpmmParams::from_pool_address_by_rpc(&client.infrastructure.rpc, &trade_info.pool_state).await?;
|
&client.infrastructure.rpc,
|
||||||
|
&trade_info.pool_state,
|
||||||
|
)
|
||||||
|
.await?;
|
||||||
|
|
||||||
println!("Selling {} tokens", amount_token);
|
println!("Selling {} tokens", amount_token);
|
||||||
let sell_params = sol_trade_sdk::TradeSellParams {
|
let sell_params = sol_trade_sdk::TradeSellParams {
|
||||||
|
|||||||
@@ -3,7 +3,10 @@ use sol_trade_sdk::{
|
|||||||
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
fast_fn::get_associated_token_address_with_program_id_fast_use_seed, AnyResult, TradeConfig,
|
||||||
},
|
},
|
||||||
swqos::SwqosConfig,
|
swqos::SwqosConfig,
|
||||||
trading::{core::params::{PumpSwapParams, DexParamEnum}, factory::DexType},
|
trading::{
|
||||||
|
core::params::{DexParamEnum, PumpSwapParams},
|
||||||
|
factory::DexType,
|
||||||
|
},
|
||||||
SolanaTrade, TradeTokenType,
|
SolanaTrade, TradeTokenType,
|
||||||
};
|
};
|
||||||
use solana_commitment_config::CommitmentConfig;
|
use solana_commitment_config::CommitmentConfig;
|
||||||
|
|||||||
@@ -48,17 +48,21 @@ async fn create_trading_client_simple() -> AnyResult<TradingClient> {
|
|||||||
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::FlashBlock("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None, None),
|
SwqosConfig::Node1("your_api_token".to_string(), SwqosRegion::Frankfurt, None, None),
|
||||||
SwqosConfig::BlockRazor("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
SwqosConfig::BlockRazor("your_api_token".to_string(), SwqosRegion::Frankfurt, None),
|
||||||
SwqosConfig::Astralane("your_api_token".to_string(), SwqosRegion::Frankfurt, None, Some(SwqosTransport::Quic)), // QUIC; use None for HTTP
|
SwqosConfig::Astralane(
|
||||||
|
"your_api_token".to_string(),
|
||||||
|
SwqosRegion::Frankfurt,
|
||||||
|
None,
|
||||||
|
Some(SwqosTransport::Quic),
|
||||||
|
), // QUIC; use None for HTTP
|
||||||
// Helius Sender: 4th param swqos_only Some(true) => min tip 0.000005 SOL; None => 0.0002 SOL
|
// 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)),
|
SwqosConfig::Helius("".to_string(), SwqosRegion::Default, None, Some(true)),
|
||||||
];
|
];
|
||||||
|
|
||||||
// Optional: Customize WSOL ATA and Seed optimization settings
|
// Optional: Customize WSOL ATA and Seed optimization settings
|
||||||
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment)
|
let trade_config = TradeConfig::new(rpc_url, swqos_configs, commitment).with_wsol_ata_config(
|
||||||
.with_wsol_ata_config(
|
true, // create_wsol_ata_on_startup: Check and create WSOL ATA on startup
|
||||||
true, // create_wsol_ata_on_startup: Check and create WSOL ATA on startup
|
true, // use_seed_optimize: Enable seed optimization for all ATA operations
|
||||||
true, // use_seed_optimize: Enable seed optimization for all ATA operations
|
);
|
||||||
);
|
|
||||||
|
|
||||||
// Creates new infrastructure internally
|
// Creates new infrastructure internally
|
||||||
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
let client = TradingClient::new(Arc::new(payer), trade_config).await;
|
||||||
|
|||||||
@@ -38,7 +38,10 @@ async fn main() -> Result<(), Box<dyn std::error::Error>> {
|
|||||||
// Example 2: Unwrap half of the WSOL back to SOL using seed account
|
// Example 2: Unwrap half of the WSOL back to SOL using seed account
|
||||||
println!("\n🔄 Example 2: Unwrapping half of WSOL back to SOL using seed account");
|
println!("\n🔄 Example 2: Unwrapping half of WSOL back to SOL using seed account");
|
||||||
let unwrap_amount = wrap_amount / 2; // Half of the wrapped amount
|
let unwrap_amount = wrap_amount / 2; // Half of the wrapped amount
|
||||||
println!("Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...", unwrap_amount);
|
println!(
|
||||||
|
"Unwrapping {} lamports (0.0005 SOL) back to SOL using seed account...",
|
||||||
|
unwrap_amount
|
||||||
|
);
|
||||||
|
|
||||||
match solana_trade.wrap_wsol_to_sol(unwrap_amount).await {
|
match solana_trade.wrap_wsol_to_sol(unwrap_amount).await {
|
||||||
Ok(signature) => {
|
Ok(signature) => {
|
||||||
|
|||||||
@@ -46,7 +46,10 @@ static INSTRUCTION_CACHE: Lazy<DashMap<InstructionCacheKey, Arc<Vec<Instruction>
|
|||||||
/// Get cached instruction, compute and cache if not exists (lock-free)
|
/// Get cached instruction, compute and cache if not exists (lock-free)
|
||||||
/// 🚀 返回 Arc 避免每次调用克隆整个 Vec
|
/// 🚀 返回 Arc 避免每次调用克隆整个 Vec
|
||||||
#[inline]
|
#[inline]
|
||||||
pub fn get_cached_instructions<F>(cache_key: InstructionCacheKey, compute_fn: F) -> Arc<Vec<Instruction>>
|
pub fn get_cached_instructions<F>(
|
||||||
|
cache_key: InstructionCacheKey,
|
||||||
|
compute_fn: F,
|
||||||
|
) -> Arc<Vec<Instruction>>
|
||||||
where
|
where
|
||||||
F: FnOnce() -> Vec<Instruction>,
|
F: FnOnce() -> Vec<Instruction>,
|
||||||
{
|
{
|
||||||
@@ -63,10 +66,7 @@ where
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Lock-free cache lookup with entry API
|
// Lock-free cache lookup with entry API
|
||||||
INSTRUCTION_CACHE
|
INSTRUCTION_CACHE.entry(cache_key).or_insert_with(|| Arc::new(compute_fn())).clone()
|
||||||
.entry(cache_key)
|
|
||||||
.or_insert_with(|| Arc::new(compute_fn()))
|
|
||||||
.clone()
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// --------------------- Associated Token Account ---------------------
|
// --------------------- Associated Token Account ---------------------
|
||||||
|
|||||||
@@ -2,9 +2,9 @@
|
|||||||
//!
|
//!
|
||||||
//! 使用 syscall_bypass 提供的快速时间戳避免频繁的系统调用
|
//! 使用 syscall_bypass 提供的快速时间戳避免频繁的系统调用
|
||||||
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
use crate::perf::syscall_bypass::SystemCallBypassManager;
|
use crate::perf::syscall_bypass::SystemCallBypassManager;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use std::time::{Duration, Instant};
|
||||||
|
|
||||||
/// 全局快速时间提供器
|
/// 全局快速时间提供器
|
||||||
static FAST_TIMER: Lazy<FastTimer> = Lazy::new(|| FastTimer::new());
|
static FAST_TIMER: Lazy<FastTimer> = Lazy::new(|| FastTimer::new());
|
||||||
@@ -26,11 +26,7 @@ impl FastTimer {
|
|||||||
let base_instant = Instant::now();
|
let base_instant = Instant::now();
|
||||||
let base_nanos = bypass_manager.fast_timestamp_nanos();
|
let base_nanos = bypass_manager.fast_timestamp_nanos();
|
||||||
|
|
||||||
Self {
|
Self { bypass_manager, _base_instant: base_instant, _base_nanos: base_nanos }
|
||||||
bypass_manager,
|
|
||||||
_base_instant: base_instant,
|
|
||||||
_base_nanos: base_nanos,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 获取当前时间戳(纳秒) - 使用快速系统调用绕过
|
/// 🚀 获取当前时间戳(纳秒) - 使用快速系统调用绕过
|
||||||
@@ -107,10 +103,7 @@ impl FastStopwatch {
|
|||||||
/// 创建并启动计时器
|
/// 创建并启动计时器
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn start(label: &'static str) -> Self {
|
pub fn start(label: &'static str) -> Self {
|
||||||
Self {
|
Self { start_nanos: fast_now_nanos(), label }
|
||||||
start_nanos: fast_now_nanos(),
|
|
||||||
label,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 获取已耗时(纳秒)
|
/// 获取已耗时(纳秒)
|
||||||
|
|||||||
+1
-1
@@ -2,11 +2,11 @@ pub mod address_lookup;
|
|||||||
pub mod bonding_curve;
|
pub mod bonding_curve;
|
||||||
pub mod clock;
|
pub mod clock;
|
||||||
pub mod fast_fn;
|
pub mod fast_fn;
|
||||||
pub mod sdk_log;
|
|
||||||
pub mod fast_timing;
|
pub mod fast_timing;
|
||||||
pub mod gas_fee_strategy;
|
pub mod gas_fee_strategy;
|
||||||
pub mod global;
|
pub mod global;
|
||||||
pub mod nonce_cache;
|
pub mod nonce_cache;
|
||||||
|
pub mod sdk_log;
|
||||||
pub mod seed;
|
pub mod seed;
|
||||||
pub mod spl_associated_token_account;
|
pub mod spl_associated_token_account;
|
||||||
pub mod spl_token;
|
pub mod spl_token;
|
||||||
|
|||||||
+9
-5
@@ -1,13 +1,13 @@
|
|||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use anyhow::anyhow;
|
use anyhow::anyhow;
|
||||||
use fnv::FnvHasher;
|
use fnv::FnvHasher;
|
||||||
|
use once_cell::sync::Lazy;
|
||||||
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
use solana_sdk::{instruction::Instruction, pubkey::Pubkey};
|
||||||
use solana_system_interface::instruction::create_account_with_seed;
|
use solana_system_interface::instruction::create_account_with_seed;
|
||||||
use std::hash::Hasher;
|
use std::hash::Hasher;
|
||||||
use std::sync::Arc;
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
use tokio::time::{sleep, Duration};
|
use tokio::time::{sleep, Duration};
|
||||||
use once_cell::sync::Lazy;
|
|
||||||
|
|
||||||
// 🚀 优化:使用 AtomicU64 替代 RwLock,性能提升 5-10x
|
// 🚀 优化:使用 AtomicU64 替代 RwLock,性能提升 5-10x
|
||||||
// u64::MAX 表示未初始化状态
|
// u64::MAX 表示未初始化状态
|
||||||
@@ -17,7 +17,7 @@ static SPL_TOKEN_2022_RENT: Lazy<AtomicU64> = Lazy::new(|| AtomicU64::new(u64::M
|
|||||||
/// 更新租金缓存(后台任务调用)
|
/// 更新租金缓存(后台任务调用)
|
||||||
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
pub async fn update_rents(client: &SolanaRpcClient) -> Result<(), anyhow::Error> {
|
||||||
let rent = fetch_rent_for_token_account(client, false).await?;
|
let rent = fetch_rent_for_token_account(client, false).await?;
|
||||||
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
SPL_TOKEN_RENT.store(rent, Ordering::Release); // Release 确保其他线程可见
|
||||||
|
|
||||||
let rent = fetch_rent_for_token_account(client, true).await?;
|
let rent = fetch_rent_for_token_account(client, true).await?;
|
||||||
SPL_TOKEN_2022_RENT.store(rent, Ordering::Release);
|
SPL_TOKEN_2022_RENT.store(rent, Ordering::Release);
|
||||||
@@ -62,11 +62,15 @@ pub fn create_associated_token_account_use_seed(
|
|||||||
// Relaxed: 租金值不变,无需同步;Release/Acquire 在 update_rents 保证初始化可见性
|
// Relaxed: 租金值不变,无需同步;Release/Acquire 在 update_rents 保证初始化可见性
|
||||||
let rent = if is_2022_token {
|
let rent = if is_2022_token {
|
||||||
let v = SPL_TOKEN_2022_RENT.load(Ordering::Relaxed);
|
let v = SPL_TOKEN_2022_RENT.load(Ordering::Relaxed);
|
||||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
if v == u64::MAX {
|
||||||
|
return Err(anyhow!("Rent not initialized"));
|
||||||
|
}
|
||||||
v
|
v
|
||||||
} else {
|
} else {
|
||||||
let v = SPL_TOKEN_RENT.load(Ordering::Relaxed);
|
let v = SPL_TOKEN_RENT.load(Ordering::Relaxed);
|
||||||
if v == u64::MAX { return Err(anyhow!("Rent not initialized")); }
|
if v == u64::MAX {
|
||||||
|
return Err(anyhow!("Rent not initialized"));
|
||||||
|
}
|
||||||
v
|
v
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -52,11 +52,7 @@ pub fn transfer(
|
|||||||
accounts.push(AccountMeta::new_readonly(**signer, true));
|
accounts.push(AccountMeta::new_readonly(**signer, true));
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(Instruction {
|
Ok(Instruction { program_id: *token_program_id, accounts, data })
|
||||||
program_id: *token_program_id,
|
|
||||||
accounts,
|
|
||||||
data,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn initialize_account3(
|
pub fn initialize_account3(
|
||||||
|
|||||||
+12
-10
@@ -17,11 +17,7 @@ impl InfrastructureConfig {
|
|||||||
swqos_configs: Vec<SwqosConfig>,
|
swqos_configs: Vec<SwqosConfig>,
|
||||||
commitment: CommitmentConfig,
|
commitment: CommitmentConfig,
|
||||||
) -> Self {
|
) -> Self {
|
||||||
Self {
|
Self { rpc_url, swqos_configs, commitment }
|
||||||
rpc_url,
|
|
||||||
swqos_configs,
|
|
||||||
commitment,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create from TradeConfig (extract infrastructure-only settings)
|
/// Create from TradeConfig (extract infrastructure-only settings)
|
||||||
@@ -74,6 +70,10 @@ pub struct TradeConfig {
|
|||||||
pub use_seed_optimize: bool,
|
pub use_seed_optimize: bool,
|
||||||
/// Whether to pin parallel submit tasks to CPU cores (can reduce latency; set false in containers). Default true.
|
/// Whether to pin parallel submit tasks to CPU cores (can reduce latency; set false in containers). Default true.
|
||||||
pub use_core_affinity: bool,
|
pub use_core_affinity: bool,
|
||||||
|
/// Use dedicated OS threads for sender pool (opt-in). When true, N threads run only send work; default N=18. Reduces scheduling contention when sending many txs. Default false.
|
||||||
|
pub use_dedicated_sender_threads: bool,
|
||||||
|
/// When use_dedicated_sender_threads is true, core indices to pin each sender thread to. If None or empty, N=SWQOS_DEDICATED_DEFAULT_THREADS with no affinity. If Some(ids), N=ids.len() and threads are pinned to these cores. Arc avoids cloning the Vec when building params.
|
||||||
|
pub sender_thread_cores: Option<std::sync::Arc<Vec<usize>>>,
|
||||||
/// Whether to output all SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default true.
|
/// Whether to output all SDK logs (timing, SWQOS submit/confirm, WSOL, blacklist, etc.). Default true.
|
||||||
pub log_enabled: bool,
|
pub log_enabled: bool,
|
||||||
/// Whether to check minimum tip per SWQOS provider (filter out configs below min). Default false to save latency.
|
/// Whether to check minimum tip per SWQOS provider (filter out configs below min). Default false to save latency.
|
||||||
@@ -94,11 +94,13 @@ impl TradeConfig {
|
|||||||
rpc_url,
|
rpc_url,
|
||||||
swqos_configs,
|
swqos_configs,
|
||||||
commitment,
|
commitment,
|
||||||
create_wsol_ata_on_startup: true, // default: check and create on startup
|
create_wsol_ata_on_startup: true, // default: check and create on startup
|
||||||
use_seed_optimize: true, // default: use seed optimization
|
use_seed_optimize: true, // default: use seed optimization
|
||||||
use_core_affinity: true, // default: pin parallel submit tasks to cores
|
use_core_affinity: true, // default: pin parallel submit tasks to cores
|
||||||
log_enabled: true, // default: enable all SDK logs
|
use_dedicated_sender_threads: false, // default: use tokio worker pool
|
||||||
check_min_tip: false, // default: skip min tip check to reduce latency
|
sender_thread_cores: None, // when dedicated threads enabled, which cores to pin (None => default count, no affinity)
|
||||||
|
log_enabled: true, // default: enable all SDK logs
|
||||||
|
check_min_tip: false, // default: skip min tip check to reduce latency
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -43,8 +43,7 @@ pub const USD1_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
|||||||
};
|
};
|
||||||
|
|
||||||
// USDC (mainnet) mint and meta
|
// USDC (mainnet) mint and meta
|
||||||
pub const USDC_TOKEN_ACCOUNT: Pubkey =
|
pub const USDC_TOKEN_ACCOUNT: Pubkey = pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
||||||
pubkey!("EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v");
|
|
||||||
pub const USDC_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
pub const USDC_TOKEN_ACCOUNT_META: solana_sdk::instruction::AccountMeta =
|
||||||
solana_sdk::instruction::AccountMeta {
|
solana_sdk::instruction::AccountMeta {
|
||||||
pubkey: USDC_TOKEN_ACCOUNT,
|
pubkey: USDC_TOKEN_ACCOUNT,
|
||||||
|
|||||||
+11
-12
@@ -1,7 +1,6 @@
|
|||||||
use solana_program::pubkey;
|
use solana_program::pubkey;
|
||||||
use solana_sdk::pubkey::Pubkey;
|
use solana_sdk::pubkey::Pubkey;
|
||||||
|
|
||||||
|
|
||||||
pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
pub const JITO_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||||
pubkey!("96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"),
|
pubkey!("96gYZGLnJYVFmbjzopPSU6QiEV5fGqZNyN9nmNhvrZU5"),
|
||||||
pubkey!("HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe"),
|
pubkey!("HFqU5x63VTqvQss8hp11i4wVV8bD44PvwucfZ2bU7gRe"),
|
||||||
@@ -236,11 +235,11 @@ pub const SWQOS_ENDPOINTS_NODE1_QUIC: [&str; 8] = [
|
|||||||
"ny.node1.me:16666",
|
"ny.node1.me:16666",
|
||||||
"fra.node1.me:16666",
|
"fra.node1.me:16666",
|
||||||
"ams.node1.me:16666",
|
"ams.node1.me:16666",
|
||||||
"ny.node1.me:16666", // SLC → ny
|
"ny.node1.me:16666", // SLC → ny
|
||||||
"tk.node1.me:16666",
|
"tk.node1.me:16666",
|
||||||
"lon.node1.me:16666",
|
"lon.node1.me:16666",
|
||||||
"ny.node1.me:16666", // LA → ny
|
"ny.node1.me:16666", // LA → ny
|
||||||
"ny.node1.me:16666", // Default → ny
|
"ny.node1.me:16666", // Default → ny
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_FLASHBLOCK: [&str; 8] = [
|
||||||
@@ -284,14 +283,14 @@ pub const SWQOS_ENDPOINTS_ASTRALANE: [&str; 8] = [
|
|||||||
/// Astralane QUIC endpoints (port 7000). Region order: NewYork, Frankfurt, Amsterdam, SLC, Tokyo, London, LosAngeles, Default.
|
/// Astralane QUIC endpoints (port 7000). Region order: NewYork, Frankfurt, Amsterdam, SLC, Tokyo, London, LosAngeles, Default.
|
||||||
/// See: https://github.com/Astralane/astralane-quic-client. We use fr, ams, la, ny, lim, sg only (avoid ams2/fr2 for lower latency).
|
/// See: https://github.com/Astralane/astralane-quic-client. We use fr, ams, la, ny, lim, sg only (avoid ams2/fr2 for lower latency).
|
||||||
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_ASTRALANE_QUIC: [&str; 8] = [
|
||||||
"ny.gateway.astralane.io:7000", // NewYork
|
"ny.gateway.astralane.io:7000", // NewYork
|
||||||
"fr.gateway.astralane.io:7000", // Frankfurt
|
"fr.gateway.astralane.io:7000", // Frankfurt
|
||||||
"ams.gateway.astralane.io:7000", // Amsterdam
|
"ams.gateway.astralane.io:7000", // Amsterdam
|
||||||
"lim.gateway.astralane.io:7000", // SLC (no slc, use lim)
|
"lim.gateway.astralane.io:7000", // SLC (no slc, use lim)
|
||||||
"sg.gateway.astralane.io:7000", // Tokyo (Asia)
|
"sg.gateway.astralane.io:7000", // Tokyo (Asia)
|
||||||
"ams.gateway.astralane.io:7000", // London (Europe, avoid ams2)
|
"ams.gateway.astralane.io:7000", // London (Europe, avoid ams2)
|
||||||
"la.gateway.astralane.io:7000", // LosAngeles
|
"la.gateway.astralane.io:7000", // LosAngeles
|
||||||
"lim.gateway.astralane.io:7000", // Default
|
"lim.gateway.astralane.io:7000", // Default
|
||||||
];
|
];
|
||||||
|
|
||||||
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
|
pub const SWQOS_ENDPOINTS_STELLIUM: [&str; 8] = [
|
||||||
|
|||||||
@@ -29,8 +29,10 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
.downcast_ref::<MeteoraDammV2Params>()
|
.downcast_ref::<MeteoraDammV2Params>()
|
||||||
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
.ok_or_else(|| anyhow!("Invalid protocol params for MeteoraDammV2"))?;
|
||||||
|
|
||||||
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
let is_wsol = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
|
let is_usdc = protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
if !is_wsol && !is_usdc {
|
if !is_wsol && !is_usdc {
|
||||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||||
}
|
}
|
||||||
@@ -38,7 +40,8 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
let is_a_in = protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
let amount_in: u64 = params.input_amount.unwrap_or(0);
|
||||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||||
Some(fixed) => fixed,
|
Some(fixed) => fixed,
|
||||||
@@ -141,8 +144,10 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
return Err(anyhow!("Token amount is not set"));
|
return Err(anyhow!("Token amount is not set"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
let is_wsol = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT || protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
|| protocol_params.token_a_mint == crate::constants::WSOL_TOKEN_ACCOUNT;
|
||||||
|
let is_usdc = protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_a_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
if !is_wsol && !is_usdc {
|
if !is_wsol && !is_usdc {
|
||||||
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
return Err(anyhow!("Pool must contain WSOL or USDC"));
|
||||||
}
|
}
|
||||||
@@ -150,7 +155,8 @@ impl InstructionBuilder for MeteoraDammV2InstructionBuilder {
|
|||||||
// ========================================
|
// ========================================
|
||||||
// Trade calculation and account address preparation
|
// Trade calculation and account address preparation
|
||||||
// ========================================
|
// ========================================
|
||||||
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT || protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
let is_a_in = protocol_params.token_b_mint == crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
|| protocol_params.token_b_mint == crate::constants::USDC_TOKEN_ACCOUNT;
|
||||||
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
let minimum_amount_out: u64 = match params.fixed_output_amount {
|
||||||
Some(fixed) => fixed,
|
Some(fixed) => fixed,
|
||||||
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
None => return Err(anyhow!("fixed_output_amount must be set for MeteoraDammV2 swap")),
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
|
pub mod bonk;
|
||||||
|
pub mod meteora_damm_v2;
|
||||||
pub mod pumpfun;
|
pub mod pumpfun;
|
||||||
pub mod pumpswap;
|
pub mod pumpswap;
|
||||||
pub mod bonk;
|
|
||||||
pub mod raydium_cpmm;
|
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod meteora_damm_v2;
|
pub mod raydium_cpmm;
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
+21
-27
@@ -10,7 +10,8 @@ use crate::{
|
|||||||
instruction::utils::pumpfun::{
|
instruction::utils::pumpfun::{
|
||||||
accounts, get_bonding_curve_pda, get_bonding_curve_v2_pda, get_creator,
|
accounts, get_bonding_curve_pda, get_bonding_curve_v2_pda, get_creator,
|
||||||
get_mayhem_fee_recipient_meta_random, get_user_volume_accumulator_pda,
|
get_mayhem_fee_recipient_meta_random, get_user_volume_accumulator_pda,
|
||||||
global_constants::{self}, BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
global_constants::{self},
|
||||||
|
BUY_DISCRIMINATOR, BUY_EXACT_SOL_IN_DISCRIMINATOR, SELL_DISCRIMINATOR,
|
||||||
},
|
},
|
||||||
utils::calc::{
|
utils::calc::{
|
||||||
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
|
common::{calculate_with_slippage_buy, calculate_with_slippage_sell},
|
||||||
@@ -64,8 +65,9 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
||||||
get_bonding_curve_pda(¶ms.output_mint)
|
get_bonding_curve_pda(¶ms.output_mint).ok_or_else(|| {
|
||||||
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.output_mint))?
|
anyhow!("bonding_curve PDA derivation failed for mint {}", params.output_mint)
|
||||||
|
})?
|
||||||
} else {
|
} else {
|
||||||
bonding_curve.account
|
bonding_curve.account
|
||||||
};
|
};
|
||||||
@@ -147,8 +149,9 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
global_constants::FEE_RECIPIENT_META
|
global_constants::FEE_RECIPIENT_META
|
||||||
};
|
};
|
||||||
|
|
||||||
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.output_mint)
|
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.output_mint).ok_or_else(|| {
|
||||||
.ok_or_else(|| anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.output_mint))?;
|
anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.output_mint)
|
||||||
|
})?;
|
||||||
let mut accounts: Vec<AccountMeta> = vec![
|
let mut accounts: Vec<AccountMeta> = vec![
|
||||||
global_constants::GLOBAL_ACCOUNT_META,
|
global_constants::GLOBAL_ACCOUNT_META,
|
||||||
fee_recipient_meta,
|
fee_recipient_meta,
|
||||||
@@ -169,11 +172,7 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
];
|
];
|
||||||
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // remainingAccounts: @pump-fun/pump-sdk 要求末尾传 bondingCurveV2Pda(mint),勿删
|
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false)); // remainingAccounts: @pump-fun/pump-sdk 要求末尾传 bondingCurveV2Pda(mint),勿删
|
||||||
|
|
||||||
instructions.push(Instruction::new_with_bytes(
|
instructions.push(Instruction::new_with_bytes(accounts::PUMPFUN, &buy_data, accounts));
|
||||||
accounts::PUMPFUN,
|
|
||||||
&buy_data,
|
|
||||||
accounts,
|
|
||||||
));
|
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
}
|
}
|
||||||
@@ -220,8 +219,9 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
let bonding_curve_addr = if bonding_curve.account == Pubkey::default() {
|
||||||
get_bonding_curve_pda(¶ms.input_mint)
|
get_bonding_curve_pda(¶ms.input_mint).ok_or_else(|| {
|
||||||
.ok_or_else(|| anyhow!("bonding_curve PDA derivation failed for mint {}", params.input_mint))?
|
anyhow!("bonding_curve PDA derivation failed for mint {}", params.input_mint)
|
||||||
|
})?
|
||||||
} else {
|
} else {
|
||||||
bonding_curve.account
|
bonding_curve.account
|
||||||
};
|
};
|
||||||
@@ -290,20 +290,18 @@ impl InstructionBuilder for PumpFunInstructionBuilder {
|
|||||||
|
|
||||||
// Cashback: Bonding Curve Sell expects UserVolumeAccumulator PDA at 0th remaining account (writable)
|
// Cashback: Bonding Curve Sell expects UserVolumeAccumulator PDA at 0th remaining account (writable)
|
||||||
if bonding_curve.is_cashback_coin {
|
if bonding_curve.is_cashback_coin {
|
||||||
let user_volume_accumulator = get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
let user_volume_accumulator =
|
||||||
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
get_user_volume_accumulator_pda(¶ms.payer.pubkey())
|
||||||
|
.ok_or_else(|| anyhow!("user_volume_accumulator PDA derivation failed"))?;
|
||||||
accounts.push(AccountMeta::new(user_volume_accumulator, false));
|
accounts.push(AccountMeta::new(user_volume_accumulator, false));
|
||||||
}
|
}
|
||||||
// remainingAccounts: @pump-fun/pump-sdk sell 要求末尾传 bondingCurveV2Pda(mint)(cashback 时在 user_volume_accumulator 之后),勿删
|
// remainingAccounts: @pump-fun/pump-sdk sell 要求末尾传 bondingCurveV2Pda(mint)(cashback 时在 user_volume_accumulator 之后),勿删
|
||||||
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.input_mint)
|
let bonding_curve_v2 = get_bonding_curve_v2_pda(¶ms.input_mint).ok_or_else(|| {
|
||||||
.ok_or_else(|| anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.input_mint))?;
|
anyhow!("bonding_curve_v2 PDA derivation failed for mint {}", params.input_mint)
|
||||||
|
})?;
|
||||||
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false));
|
accounts.push(AccountMeta::new_readonly(bonding_curve_v2, false));
|
||||||
|
|
||||||
instructions.push(Instruction::new_with_bytes(
|
instructions.push(Instruction::new_with_bytes(accounts::PUMPFUN, &sell_data, accounts));
|
||||||
accounts::PUMPFUN,
|
|
||||||
&sell_data,
|
|
||||||
accounts,
|
|
||||||
));
|
|
||||||
|
|
||||||
// Optional: Close token account
|
// Optional: Close token account
|
||||||
if protocol_params.close_token_account_when_sell.unwrap_or(false)
|
if protocol_params.close_token_account_when_sell.unwrap_or(false)
|
||||||
@@ -327,15 +325,11 @@ pub fn claim_cashback_pumpfun_instruction(payer: &Pubkey) -> Option<Instruction>
|
|||||||
const CLAIM_CASHBACK_DISCRIMINATOR: [u8; 8] = [37, 58, 35, 126, 190, 53, 228, 197];
|
const CLAIM_CASHBACK_DISCRIMINATOR: [u8; 8] = [37, 58, 35, 126, 190, 53, 228, 197];
|
||||||
let user_volume_accumulator = get_user_volume_accumulator_pda(payer)?;
|
let user_volume_accumulator = get_user_volume_accumulator_pda(payer)?;
|
||||||
let accounts = vec![
|
let accounts = vec![
|
||||||
AccountMeta::new(*payer, true), // user (signer, writable)
|
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||||
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable, not signer)
|
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable, not signer)
|
||||||
crate::constants::SYSTEM_PROGRAM_META,
|
crate::constants::SYSTEM_PROGRAM_META,
|
||||||
accounts::EVENT_AUTHORITY_META,
|
accounts::EVENT_AUTHORITY_META,
|
||||||
accounts::PUMPFUN_META,
|
accounts::PUMPFUN_META,
|
||||||
];
|
];
|
||||||
Some(Instruction::new_with_bytes(
|
Some(Instruction::new_with_bytes(accounts::PUMPFUN, &CLAIM_CASHBACK_DISCRIMINATOR, accounts))
|
||||||
accounts::PUMPFUN,
|
|
||||||
&CLAIM_CASHBACK_DISCRIMINATOR,
|
|
||||||
accounts,
|
|
||||||
))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -225,11 +225,7 @@ impl InstructionBuilder for PumpSwapInstructionBuilder {
|
|||||||
buf.to_vec()
|
buf.to_vec()
|
||||||
};
|
};
|
||||||
|
|
||||||
instructions.push(Instruction {
|
instructions.push(Instruction { program_id: accounts::AMM_PROGRAM, accounts, data });
|
||||||
program_id: accounts::AMM_PROGRAM,
|
|
||||||
accounts,
|
|
||||||
data,
|
|
||||||
});
|
|
||||||
if close_wsol_ata {
|
if close_wsol_ata {
|
||||||
// Close wSOL ATA account, reclaim rent
|
// Close wSOL ATA account, reclaim rent
|
||||||
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
instructions.extend(crate::trading::common::close_wsol(¶ms.payer.pubkey()));
|
||||||
@@ -462,12 +458,12 @@ pub fn claim_cashback_pumpswap_instruction(
|
|||||||
// IDL order: user, user_volume_accumulator, quote_mint, quote_token_program,
|
// IDL order: user, user_volume_accumulator, quote_mint, quote_token_program,
|
||||||
// user_volume_accumulator_wsol_token_account, user_wsol_token_account, system_program, event_authority, program
|
// user_volume_accumulator_wsol_token_account, user_wsol_token_account, system_program, event_authority, program
|
||||||
let accounts = vec![
|
let accounts = vec![
|
||||||
AccountMeta::new(*payer, true), // user (signer, writable)
|
AccountMeta::new(*payer, true), // user (signer, writable)
|
||||||
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable)
|
AccountMeta::new(user_volume_accumulator, false), // user_volume_accumulator (writable)
|
||||||
AccountMeta::new_readonly(quote_mint, false),
|
AccountMeta::new_readonly(quote_mint, false),
|
||||||
AccountMeta::new_readonly(quote_token_program, false),
|
AccountMeta::new_readonly(quote_token_program, false),
|
||||||
AccountMeta::new(user_volume_accumulator_wsol_ata, false), // writable
|
AccountMeta::new(user_volume_accumulator_wsol_ata, false), // writable
|
||||||
AccountMeta::new(user_wsol_ata, false), // writable
|
AccountMeta::new(user_wsol_ata, false), // writable
|
||||||
crate::constants::SYSTEM_PROGRAM_META,
|
crate::constants::SYSTEM_PROGRAM_META,
|
||||||
accounts::EVENT_AUTHORITY_META,
|
accounts::EVENT_AUTHORITY_META,
|
||||||
accounts::AMM_PROGRAM_META,
|
accounts::AMM_PROGRAM_META,
|
||||||
|
|||||||
@@ -62,7 +62,11 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
let user_source_token_account =
|
let user_source_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -187,7 +191,11 @@ impl InstructionBuilder for RaydiumAmmV4InstructionBuilder {
|
|||||||
let user_destination_token_account =
|
let user_destination_token_account =
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
crate::common::fast_fn::get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -84,7 +84,11 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
let input_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -97,10 +101,15 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let input_vault_account = get_vault_account(
|
let input_vault_account = get_vault_account(
|
||||||
&pool_state,
|
&pool_state,
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
protocol_params,
|
protocol_params,
|
||||||
);
|
);
|
||||||
let output_vault_account = get_vault_account(&pool_state, ¶ms.output_mint, protocol_params);
|
let output_vault_account =
|
||||||
|
get_vault_account(&pool_state, ¶ms.output_mint, protocol_params);
|
||||||
|
|
||||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||||
get_observation_state_pda(&pool_state).unwrap()
|
get_observation_state_pda(&pool_state).unwrap()
|
||||||
@@ -136,13 +145,17 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
accounts::AUTHORITY_META, // Authority (readonly)
|
accounts::AUTHORITY_META, // Authority (readonly)
|
||||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||||
AccountMeta::new(pool_state, false), // Pool State
|
AccountMeta::new(pool_state, false), // Pool State
|
||||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||||
crate::constants::TOKEN_PROGRAM_META, // Input Token Program (readonly)
|
crate::constants::TOKEN_PROGRAM_META, // Input Token Program (readonly)
|
||||||
AccountMeta::new_readonly(mint_token_program, false), // Output Token Program (readonly)
|
AccountMeta::new_readonly(mint_token_program, false), // Output Token Program (readonly)
|
||||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Input token mint (readonly)
|
if is_wsol {
|
||||||
|
crate::constants::WSOL_TOKEN_ACCOUNT_META
|
||||||
|
} else {
|
||||||
|
crate::constants::USDC_TOKEN_ACCOUNT_META
|
||||||
|
}, // Input token mint (readonly)
|
||||||
AccountMeta::new_readonly(params.output_mint, false), // Output token mint (readonly)
|
AccountMeta::new_readonly(params.output_mint, false), // Output token mint (readonly)
|
||||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||||
];
|
];
|
||||||
@@ -228,7 +241,11 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
let output_token_account = get_associated_token_address_with_program_id_fast_use_seed(
|
||||||
¶ms.payer.pubkey(),
|
¶ms.payer.pubkey(),
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
params.open_seed_optimize,
|
params.open_seed_optimize,
|
||||||
);
|
);
|
||||||
@@ -241,10 +258,15 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
|
|
||||||
let output_vault_account = get_vault_account(
|
let output_vault_account = get_vault_account(
|
||||||
&pool_state,
|
&pool_state,
|
||||||
if is_wsol { &crate::constants::WSOL_TOKEN_ACCOUNT } else { &crate::constants::USDC_TOKEN_ACCOUNT },
|
if is_wsol {
|
||||||
|
&crate::constants::WSOL_TOKEN_ACCOUNT
|
||||||
|
} else {
|
||||||
|
&crate::constants::USDC_TOKEN_ACCOUNT
|
||||||
|
},
|
||||||
protocol_params,
|
protocol_params,
|
||||||
);
|
);
|
||||||
let input_vault_account = get_vault_account(&pool_state, ¶ms.input_mint, protocol_params);
|
let input_vault_account =
|
||||||
|
get_vault_account(&pool_state, ¶ms.input_mint, protocol_params);
|
||||||
|
|
||||||
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
let observation_state_account = if protocol_params.observation_state == Pubkey::default() {
|
||||||
get_observation_state_pda(&pool_state).unwrap()
|
get_observation_state_pda(&pool_state).unwrap()
|
||||||
@@ -267,14 +289,18 @@ impl InstructionBuilder for RaydiumCpmmInstructionBuilder {
|
|||||||
accounts::AUTHORITY_META, // Authority (readonly)
|
accounts::AUTHORITY_META, // Authority (readonly)
|
||||||
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
AccountMeta::new(protocol_params.amm_config, false), // Amm Config (readonly)
|
||||||
AccountMeta::new(pool_state, false), // Pool State
|
AccountMeta::new(pool_state, false), // Pool State
|
||||||
AccountMeta::new(input_token_account, false), // Input Token Account
|
AccountMeta::new(input_token_account, false), // Input Token Account
|
||||||
AccountMeta::new(output_token_account, false), // Output Token Account
|
AccountMeta::new(output_token_account, false), // Output Token Account
|
||||||
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
AccountMeta::new(input_vault_account, false), // Input Vault Account
|
||||||
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
AccountMeta::new(output_vault_account, false), // Output Vault Account
|
||||||
AccountMeta::new_readonly(mint_token_program, false), // Input Token Program (readonly)
|
AccountMeta::new_readonly(mint_token_program, false), // Input Token Program (readonly)
|
||||||
crate::constants::TOKEN_PROGRAM_META, // Output Token Program (readonly)
|
crate::constants::TOKEN_PROGRAM_META, // Output Token Program (readonly)
|
||||||
AccountMeta::new_readonly(params.input_mint, false), // Input token mint (readonly)
|
AccountMeta::new_readonly(params.input_mint, false), // Input token mint (readonly)
|
||||||
if is_wsol { crate::constants::WSOL_TOKEN_ACCOUNT_META } else { crate::constants::USDC_TOKEN_ACCOUNT_META }, // Output token mint (readonly)
|
if is_wsol {
|
||||||
|
crate::constants::WSOL_TOKEN_ACCOUNT_META
|
||||||
|
} else {
|
||||||
|
crate::constants::USDC_TOKEN_ACCOUNT_META
|
||||||
|
}, // Output token mint (readonly)
|
||||||
AccountMeta::new(observation_state_account, false), // Observation State Account
|
AccountMeta::new(observation_state_account, false), // Observation State Account
|
||||||
];
|
];
|
||||||
// Create instruction data
|
// Create instruction data
|
||||||
|
|||||||
@@ -1,13 +1,13 @@
|
|||||||
pub mod bonk;
|
pub mod bonk;
|
||||||
|
pub mod meteora_damm_v2;
|
||||||
pub mod pumpfun;
|
pub mod pumpfun;
|
||||||
pub mod pumpswap;
|
pub mod pumpswap;
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod raydium_cpmm;
|
pub mod raydium_cpmm;
|
||||||
pub mod meteora_damm_v2;
|
|
||||||
|
|
||||||
// types
|
// types
|
||||||
pub mod bonk_types;
|
pub mod bonk_types;
|
||||||
|
pub mod meteora_damm_v2_types;
|
||||||
pub mod pumpswap_types;
|
pub mod pumpswap_types;
|
||||||
pub mod raydium_amm_v4_types;
|
pub mod raydium_amm_v4_types;
|
||||||
pub mod raydium_cpmm_types;
|
pub mod raydium_cpmm_types;
|
||||||
pub mod meteora_damm_v2_types;
|
|
||||||
@@ -178,11 +178,7 @@ pub fn get_mayhem_fee_recipient_meta_random() -> AccountMeta {
|
|||||||
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
|
let recipient = *global_constants::MAYHEM_FEE_RECIPIENTS
|
||||||
.choose(&mut rand::rng())
|
.choose(&mut rand::rng())
|
||||||
.unwrap_or(&global_constants::MAYHEM_FEE_RECIPIENTS[0]);
|
.unwrap_or(&global_constants::MAYHEM_FEE_RECIPIENTS[0]);
|
||||||
AccountMeta {
|
AccountMeta { pubkey: recipient, is_signer: false, is_writable: true }
|
||||||
pubkey: recipient,
|
|
||||||
is_signer: false,
|
|
||||||
is_writable: true,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct Symbol;
|
pub struct Symbol;
|
||||||
|
|||||||
@@ -169,11 +169,7 @@ pub fn get_mayhem_fee_recipient_random() -> (Pubkey, AccountMeta) {
|
|||||||
let recipient = *accounts::MAYHEM_FEE_RECIPIENTS
|
let recipient = *accounts::MAYHEM_FEE_RECIPIENTS
|
||||||
.choose(&mut rand::rng())
|
.choose(&mut rand::rng())
|
||||||
.unwrap_or(&accounts::MAYHEM_FEE_RECIPIENTS[0]);
|
.unwrap_or(&accounts::MAYHEM_FEE_RECIPIENTS[0]);
|
||||||
let meta = AccountMeta {
|
let meta = AccountMeta { pubkey: recipient, is_signer: false, is_writable: false };
|
||||||
pubkey: recipient,
|
|
||||||
is_signer: false,
|
|
||||||
is_writable: false,
|
|
||||||
};
|
|
||||||
(recipient, meta)
|
(recipient, meta)
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -334,7 +330,7 @@ pub async fn find_by_base_mint(
|
|||||||
if accounts.is_empty() {
|
if accounts.is_empty() {
|
||||||
return Err(anyhow!("No pool found for mint {}", base_mint));
|
return Err(anyhow!("No pool found for mint {}", base_mint));
|
||||||
}
|
}
|
||||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
||||||
let mut pools: Vec<_> = accounts
|
let mut pools: Vec<_> = accounts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|(addr, acc)| {
|
.filter_map(|(addr, acc)| {
|
||||||
@@ -349,7 +345,11 @@ pub async fn find_by_base_mint(
|
|||||||
|
|
||||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
||||||
if pools.is_empty() {
|
if pools.is_empty() {
|
||||||
return Err(anyhow!("No valid pool decoded for mint {} (found {} accounts but all decode failed)", base_mint, accounts_count));
|
return Err(anyhow!(
|
||||||
|
"No valid pool decoded for mint {} (found {} accounts but all decode failed)",
|
||||||
|
base_mint,
|
||||||
|
accounts_count
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||||
@@ -386,7 +386,7 @@ pub async fn find_by_quote_mint(
|
|||||||
if accounts.is_empty() {
|
if accounts.is_empty() {
|
||||||
return Err(anyhow!("No pool found for mint {}", quote_mint));
|
return Err(anyhow!("No pool found for mint {}", quote_mint));
|
||||||
}
|
}
|
||||||
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
let accounts_count = accounts.len(); // 🔧 保存长度,因为 into_iter() 会消耗 accounts
|
||||||
let mut pools: Vec<_> = accounts
|
let mut pools: Vec<_> = accounts
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter_map(|(addr, acc)| {
|
.filter_map(|(addr, acc)| {
|
||||||
@@ -401,7 +401,11 @@ pub async fn find_by_quote_mint(
|
|||||||
|
|
||||||
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
// 🔧 修复:检查过滤后的 pools 是否为空(accounts 可能不为空但解码全部失败)
|
||||||
if pools.is_empty() {
|
if pools.is_empty() {
|
||||||
return Err(anyhow!("No valid pool decoded for quote_mint {} (found {} accounts but all decode failed)", quote_mint, accounts_count));
|
return Err(anyhow!(
|
||||||
|
"No valid pool decoded for quote_mint {} (found {} accounts but all decode failed)",
|
||||||
|
quote_mint,
|
||||||
|
accounts_count
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
pools.sort_by(|a, b| b.1.lp_supply.cmp(&a.1.lp_supply));
|
||||||
|
|||||||
@@ -135,7 +135,9 @@ pub fn get_vault_account(
|
|||||||
) -> Pubkey {
|
) -> Pubkey {
|
||||||
if protocol_params.base_mint == *token_mint && protocol_params.base_vault != Pubkey::default() {
|
if protocol_params.base_mint == *token_mint && protocol_params.base_vault != Pubkey::default() {
|
||||||
protocol_params.base_vault
|
protocol_params.base_vault
|
||||||
} else if protocol_params.quote_mint == *token_mint && protocol_params.quote_vault != Pubkey::default() {
|
} else if protocol_params.quote_mint == *token_mint
|
||||||
|
&& protocol_params.quote_vault != Pubkey::default()
|
||||||
|
{
|
||||||
protocol_params.quote_vault
|
protocol_params.quote_vault
|
||||||
} else {
|
} else {
|
||||||
get_vault_pda(pool_state, token_mint).unwrap()
|
get_vault_pda(pool_state, token_mint).unwrap()
|
||||||
|
|||||||
+64
-36
@@ -8,7 +8,7 @@ pub mod utils;
|
|||||||
use crate::common::nonce_cache::DurableNonceInfo;
|
use crate::common::nonce_cache::DurableNonceInfo;
|
||||||
use crate::common::sdk_log;
|
use crate::common::sdk_log;
|
||||||
use crate::common::GasFeeStrategy;
|
use crate::common::GasFeeStrategy;
|
||||||
use crate::common::{TradeConfig, InfrastructureConfig};
|
use crate::common::{InfrastructureConfig, TradeConfig};
|
||||||
#[cfg(feature = "perf-trace")]
|
#[cfg(feature = "perf-trace")]
|
||||||
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
|
use crate::constants::trade::trade::DEFAULT_SLIPPAGE;
|
||||||
use crate::constants::SOL_TOKEN_ACCOUNT;
|
use crate::constants::SOL_TOKEN_ACCOUNT;
|
||||||
@@ -22,12 +22,12 @@ use crate::swqos::TradeType;
|
|||||||
// Re-export for SWQOS HTTP/QUIC choice in SwqosConfig (e.g. Astralane)
|
// Re-export for SWQOS HTTP/QUIC choice in SwqosConfig (e.g. Astralane)
|
||||||
pub use crate::swqos::SwqosTransport;
|
pub use crate::swqos::SwqosTransport;
|
||||||
use crate::trading::core::params::BonkParams;
|
use crate::trading::core::params::BonkParams;
|
||||||
|
use crate::trading::core::params::DexParamEnum;
|
||||||
use crate::trading::core::params::MeteoraDammV2Params;
|
use crate::trading::core::params::MeteoraDammV2Params;
|
||||||
use crate::trading::core::params::PumpFunParams;
|
use crate::trading::core::params::PumpFunParams;
|
||||||
use crate::trading::core::params::PumpSwapParams;
|
use crate::trading::core::params::PumpSwapParams;
|
||||||
use crate::trading::core::params::RaydiumAmmV4Params;
|
use crate::trading::core::params::RaydiumAmmV4Params;
|
||||||
use crate::trading::core::params::RaydiumCpmmParams;
|
use crate::trading::core::params::RaydiumCpmmParams;
|
||||||
use crate::trading::core::params::DexParamEnum;
|
|
||||||
use crate::trading::factory::DexType;
|
use crate::trading::factory::DexType;
|
||||||
use crate::trading::MiddlewareManager;
|
use crate::trading::MiddlewareManager;
|
||||||
use crate::trading::SwapParams;
|
use crate::trading::SwapParams;
|
||||||
@@ -65,13 +65,8 @@ pub async fn find_pool_by_mint(
|
|||||||
dex_type: DexType,
|
dex_type: DexType,
|
||||||
) -> Result<Pubkey, anyhow::Error> {
|
) -> Result<Pubkey, anyhow::Error> {
|
||||||
match dex_type {
|
match dex_type {
|
||||||
DexType::PumpSwap => {
|
DexType::PumpSwap => crate::instruction::utils::pumpswap::find_pool(rpc, mint).await,
|
||||||
crate::instruction::utils::pumpswap::find_pool(rpc, mint).await
|
_ => Err(anyhow::anyhow!("find_pool_by_mint not implemented for {:?}", dex_type)),
|
||||||
}
|
|
||||||
_ => Err(anyhow::anyhow!(
|
|
||||||
"find_pool_by_mint not implemented for {:?}",
|
|
||||||
dex_type
|
|
||||||
)),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -91,8 +86,8 @@ pub enum TradeTokenType {
|
|||||||
pub struct TradingInfrastructure {
|
pub struct TradingInfrastructure {
|
||||||
/// Shared RPC client for blockchain interactions
|
/// Shared RPC client for blockchain interactions
|
||||||
pub rpc: Arc<SolanaRpcClient>,
|
pub rpc: Arc<SolanaRpcClient>,
|
||||||
/// Shared SWQOS clients for transaction priority and routing
|
/// Shared SWQOS clients for transaction priority and routing. Arc<Vec<..>> so cloning into SwapParams is a single Arc clone.
|
||||||
pub swqos_clients: Vec<Arc<SwqosClient>>,
|
pub swqos_clients: Arc<Vec<Arc<SwqosClient>>>,
|
||||||
/// Configuration used to create this infrastructure
|
/// Configuration used to create this infrastructure
|
||||||
pub config: InfrastructureConfig,
|
pub config: InfrastructureConfig,
|
||||||
}
|
}
|
||||||
@@ -182,7 +177,7 @@ impl TradingInfrastructure {
|
|||||||
|
|
||||||
Self {
|
Self {
|
||||||
rpc,
|
rpc,
|
||||||
swqos_clients,
|
swqos_clients: Arc::new(swqos_clients),
|
||||||
config,
|
config,
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -206,6 +201,10 @@ pub struct TradingClient {
|
|||||||
pub use_seed_optimize: bool,
|
pub use_seed_optimize: bool,
|
||||||
/// Whether to pin parallel submit tasks to CPU cores (from TradeConfig.use_core_affinity). Default true.
|
/// Whether to pin parallel submit tasks to CPU cores (from TradeConfig.use_core_affinity). Default true.
|
||||||
pub use_core_affinity: bool,
|
pub use_core_affinity: bool,
|
||||||
|
/// Use dedicated sender threads (from TradeConfig.use_dedicated_sender_threads). Default false.
|
||||||
|
pub use_dedicated_sender_threads: bool,
|
||||||
|
/// Core indices for dedicated sender threads (from TradeConfig.sender_thread_cores). Arc avoids cloning the Vec when building SwapParams.
|
||||||
|
pub sender_thread_cores: Option<Arc<Vec<usize>>>,
|
||||||
/// Whether to output all SDK logs (from TradeConfig.log_enabled).
|
/// Whether to output all SDK logs (from TradeConfig.log_enabled).
|
||||||
pub log_enabled: bool,
|
pub log_enabled: bool,
|
||||||
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). Default false for lower latency.
|
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). Default false for lower latency.
|
||||||
@@ -225,6 +224,8 @@ impl Clone for TradingClient {
|
|||||||
middleware_manager: self.middleware_manager.clone(),
|
middleware_manager: self.middleware_manager.clone(),
|
||||||
use_seed_optimize: self.use_seed_optimize,
|
use_seed_optimize: self.use_seed_optimize,
|
||||||
use_core_affinity: self.use_core_affinity,
|
use_core_affinity: self.use_core_affinity,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
log_enabled: self.log_enabled,
|
log_enabled: self.log_enabled,
|
||||||
check_min_tip: self.check_min_tip,
|
check_min_tip: self.check_min_tip,
|
||||||
}
|
}
|
||||||
@@ -354,6 +355,8 @@ impl TradingClient {
|
|||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize,
|
use_seed_optimize,
|
||||||
use_core_affinity: true,
|
use_core_affinity: true,
|
||||||
|
use_dedicated_sender_threads: false,
|
||||||
|
sender_thread_cores: None,
|
||||||
log_enabled: true,
|
log_enabled: true,
|
||||||
check_min_tip: false,
|
check_min_tip: false,
|
||||||
}
|
}
|
||||||
@@ -394,6 +397,8 @@ impl TradingClient {
|
|||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize,
|
use_seed_optimize,
|
||||||
use_core_affinity: true,
|
use_core_affinity: true,
|
||||||
|
use_dedicated_sender_threads: false,
|
||||||
|
sender_thread_cores: None,
|
||||||
log_enabled: true,
|
log_enabled: true,
|
||||||
check_min_tip: false,
|
check_min_tip: false,
|
||||||
}
|
}
|
||||||
@@ -408,7 +413,9 @@ impl TradingClient {
|
|||||||
timeout_secs: u64,
|
timeout_secs: u64,
|
||||||
) -> Result<(), String> {
|
) -> Result<(), String> {
|
||||||
use solana_sdk::transaction::Transaction;
|
use solana_sdk::transaction::Transaction;
|
||||||
let recent_blockhash = rpc.get_latest_blockhash().await
|
let recent_blockhash = rpc
|
||||||
|
.get_latest_blockhash()
|
||||||
|
.await
|
||||||
.map_err(|e| format!("Failed to get blockhash: {}", e))?;
|
.map_err(|e| format!("Failed to get blockhash: {}", e))?;
|
||||||
let tx = Transaction::new_signed_with_payer(
|
let tx = Transaction::new_signed_with_payer(
|
||||||
create_ata_ixs,
|
create_ata_ixs,
|
||||||
@@ -419,7 +426,8 @@ impl TradingClient {
|
|||||||
let send_result = tokio::time::timeout(
|
let send_result = tokio::time::timeout(
|
||||||
tokio::time::Duration::from_secs(timeout_secs),
|
tokio::time::Duration::from_secs(timeout_secs),
|
||||||
rpc.send_and_confirm_transaction(&tx),
|
rpc.send_and_confirm_transaction(&tx),
|
||||||
).await;
|
)
|
||||||
|
.await;
|
||||||
match send_result {
|
match send_result {
|
||||||
Ok(Ok(_signature)) => Ok(()),
|
Ok(Ok(_signature)) => Ok(()),
|
||||||
Ok(Err(e)) => {
|
Ok(Err(e)) => {
|
||||||
@@ -437,12 +445,11 @@ impl TradingClient {
|
|||||||
const MAX_RETRIES: usize = 3;
|
const MAX_RETRIES: usize = 3;
|
||||||
const TIMEOUT_SECS: u64 = 10;
|
const TIMEOUT_SECS: u64 = 10;
|
||||||
|
|
||||||
let wsol_ata =
|
let wsol_ata = crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
||||||
crate::common::fast_fn::get_associated_token_address_with_program_id_fast(
|
&payer.pubkey(),
|
||||||
&payer.pubkey(),
|
&WSOL_TOKEN_ACCOUNT,
|
||||||
&WSOL_TOKEN_ACCOUNT,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
);
|
||||||
);
|
|
||||||
|
|
||||||
if rpc.get_account(&wsol_ata).await.is_ok() {
|
if rpc.get_account(&wsol_ata).await.is_ok() {
|
||||||
if sdk_log::sdk_log_enabled() {
|
if sdk_log::sdk_log_enabled() {
|
||||||
@@ -451,8 +458,7 @@ impl TradingClient {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
let create_ata_ixs =
|
let create_ata_ixs = crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
||||||
crate::trading::common::wsol_manager::create_wsol_ata(&payer.pubkey());
|
|
||||||
if create_ata_ixs.is_empty() {
|
if create_ata_ixs.is_empty() {
|
||||||
if sdk_log::sdk_log_enabled() {
|
if sdk_log::sdk_log_enabled() {
|
||||||
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA already exists (no need to create)");
|
info!(target: "sol_trade_sdk", "ℹ️ WSOL ATA already exists (no need to create)");
|
||||||
@@ -471,7 +477,15 @@ impl TradingClient {
|
|||||||
}
|
}
|
||||||
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
tokio::time::sleep(tokio::time::Duration::from_secs(2)).await;
|
||||||
}
|
}
|
||||||
match Self::try_create_wsol_ata_once(rpc.as_ref(), payer, &wsol_ata, &create_ata_ixs, TIMEOUT_SECS).await {
|
match Self::try_create_wsol_ata_once(
|
||||||
|
rpc.as_ref(),
|
||||||
|
payer,
|
||||||
|
&wsol_ata,
|
||||||
|
&create_ata_ixs,
|
||||||
|
TIMEOUT_SECS,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
Ok(()) => {
|
Ok(()) => {
|
||||||
if sdk_log::sdk_log_enabled() {
|
if sdk_log::sdk_log_enabled() {
|
||||||
info!(target: "sol_trade_sdk", "✅ WSOL ATA created or already exists");
|
info!(target: "sol_trade_sdk", "✅ WSOL ATA created or already exists");
|
||||||
@@ -560,6 +574,8 @@ impl TradingClient {
|
|||||||
middleware_manager: None,
|
middleware_manager: None,
|
||||||
use_seed_optimize: trade_config.use_seed_optimize,
|
use_seed_optimize: trade_config.use_seed_optimize,
|
||||||
use_core_affinity: trade_config.use_core_affinity,
|
use_core_affinity: trade_config.use_core_affinity,
|
||||||
|
use_dedicated_sender_threads: trade_config.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: trade_config.sender_thread_cores.clone(),
|
||||||
log_enabled: trade_config.log_enabled,
|
log_enabled: trade_config.log_enabled,
|
||||||
check_min_tip: trade_config.check_min_tip,
|
check_min_tip: trade_config.check_min_tip,
|
||||||
};
|
};
|
||||||
@@ -706,6 +722,8 @@ impl TradingClient {
|
|||||||
simulate: params.simulate,
|
simulate: params.simulate,
|
||||||
log_enabled: self.log_enabled,
|
log_enabled: self.log_enabled,
|
||||||
use_core_affinity: self.use_core_affinity,
|
use_core_affinity: self.use_core_affinity,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
check_min_tip: self.check_min_tip,
|
check_min_tip: self.check_min_tip,
|
||||||
grpc_recv_us: params.grpc_recv_us,
|
grpc_recv_us: params.grpc_recv_us,
|
||||||
use_exact_sol_amount: params.use_exact_sol_amount,
|
use_exact_sol_amount: params.use_exact_sol_amount,
|
||||||
@@ -810,6 +828,8 @@ impl TradingClient {
|
|||||||
simulate: params.simulate,
|
simulate: params.simulate,
|
||||||
log_enabled: self.log_enabled,
|
log_enabled: self.log_enabled,
|
||||||
use_core_affinity: self.use_core_affinity,
|
use_core_affinity: self.use_core_affinity,
|
||||||
|
use_dedicated_sender_threads: self.use_dedicated_sender_threads,
|
||||||
|
sender_thread_cores: self.sender_thread_cores.clone(),
|
||||||
check_min_tip: self.check_min_tip,
|
check_min_tip: self.check_min_tip,
|
||||||
grpc_recv_us: params.grpc_recv_us,
|
grpc_recv_us: params.grpc_recv_us,
|
||||||
use_exact_sol_amount: None,
|
use_exact_sol_amount: None,
|
||||||
@@ -981,8 +1001,10 @@ impl TradingClient {
|
|||||||
/// - 交易执行或确认失败
|
/// - 交易执行或确认失败
|
||||||
/// - 网络或 RPC 错误
|
/// - 网络或 RPC 错误
|
||||||
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
pub async fn wrap_wsol_to_sol(&self, amount: u64) -> Result<String, anyhow::Error> {
|
||||||
use crate::trading::common::wsol_manager::{wrap_wsol_to_sol as wrap_wsol_to_sol_internal, wrap_wsol_to_sol_without_create};
|
|
||||||
use crate::common::seed::get_associated_token_address_with_program_id_use_seed;
|
use crate::common::seed::get_associated_token_address_with_program_id_use_seed;
|
||||||
|
use crate::trading::common::wsol_manager::{
|
||||||
|
wrap_wsol_to_sol as wrap_wsol_to_sol_internal, wrap_wsol_to_sol_without_create,
|
||||||
|
};
|
||||||
use solana_sdk::transaction::Transaction;
|
use solana_sdk::transaction::Transaction;
|
||||||
|
|
||||||
// 检查临时seed账户是否已存在
|
// 检查临时seed账户是否已存在
|
||||||
@@ -1003,7 +1025,8 @@ impl TradingClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let mut transaction = Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
let mut transaction =
|
||||||
|
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||||
Ok(signature.to_string())
|
Ok(signature.to_string())
|
||||||
@@ -1019,8 +1042,10 @@ impl TradingClient {
|
|||||||
/// * `Err(anyhow::Error)` - Build or send failure (e.g. invalid PDA)
|
/// * `Err(anyhow::Error)` - Build or send failure (e.g. invalid PDA)
|
||||||
pub async fn claim_cashback_pumpfun(&self) -> Result<String, anyhow::Error> {
|
pub async fn claim_cashback_pumpfun(&self) -> Result<String, anyhow::Error> {
|
||||||
use solana_sdk::transaction::Transaction;
|
use solana_sdk::transaction::Transaction;
|
||||||
let ix = crate::instruction::pumpfun::claim_cashback_pumpfun_instruction(&self.payer.pubkey())
|
let ix = crate::instruction::pumpfun::claim_cashback_pumpfun_instruction(
|
||||||
.ok_or_else(|| anyhow::anyhow!("Failed to build PumpFun claim_cashback 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 recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let mut transaction = Transaction::new_with_payer(&[ix], Some(&self.payer.pubkey()));
|
let mut transaction = Transaction::new_with_payer(&[ix], Some(&self.payer.pubkey()));
|
||||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
@@ -1038,21 +1063,24 @@ impl TradingClient {
|
|||||||
/// * `Err(anyhow::Error)` - Build or send failure
|
/// * `Err(anyhow::Error)` - Build or send failure
|
||||||
pub async fn claim_cashback_pumpswap(&self) -> Result<String, anyhow::Error> {
|
pub async fn claim_cashback_pumpswap(&self) -> Result<String, anyhow::Error> {
|
||||||
use solana_sdk::transaction::Transaction;
|
use solana_sdk::transaction::Transaction;
|
||||||
let mut instructions = crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
let mut instructions =
|
||||||
&self.payer.pubkey(),
|
crate::common::fast_fn::create_associated_token_account_idempotent_fast_use_seed(
|
||||||
&self.payer.pubkey(),
|
&self.payer.pubkey(),
|
||||||
&WSOL_TOKEN_ACCOUNT,
|
&self.payer.pubkey(),
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
&WSOL_TOKEN_ACCOUNT,
|
||||||
self.use_seed_optimize,
|
&crate::constants::TOKEN_PROGRAM,
|
||||||
);
|
self.use_seed_optimize,
|
||||||
|
);
|
||||||
let ix = crate::instruction::pumpswap::claim_cashback_pumpswap_instruction(
|
let ix = crate::instruction::pumpswap::claim_cashback_pumpswap_instruction(
|
||||||
&self.payer.pubkey(),
|
&self.payer.pubkey(),
|
||||||
WSOL_TOKEN_ACCOUNT,
|
WSOL_TOKEN_ACCOUNT,
|
||||||
crate::constants::TOKEN_PROGRAM,
|
crate::constants::TOKEN_PROGRAM,
|
||||||
).ok_or_else(|| anyhow::anyhow!("Failed to build PumpSwap claim_cashback instruction"))?;
|
)
|
||||||
|
.ok_or_else(|| anyhow::anyhow!("Failed to build PumpSwap claim_cashback instruction"))?;
|
||||||
instructions.push(ix);
|
instructions.push(ix);
|
||||||
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
let recent_blockhash = self.infrastructure.rpc.get_latest_blockhash().await?;
|
||||||
let mut transaction = Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
let mut transaction =
|
||||||
|
Transaction::new_with_payer(&instructions, Some(&self.payer.pubkey()));
|
||||||
transaction.sign(&[&*self.payer], recent_blockhash);
|
transaction.sign(&[&*self.payer], recent_blockhash);
|
||||||
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
let signature = self.infrastructure.rpc.send_and_confirm_transaction(&transaction).await?;
|
||||||
Ok(signature.to_string())
|
Ok(signature.to_string())
|
||||||
|
|||||||
@@ -163,12 +163,16 @@ impl CompilerOptimizer {
|
|||||||
// 目标特性
|
// 目标特性
|
||||||
if !self.optimization_flags.target_features.is_empty() {
|
if !self.optimization_flags.target_features.is_empty() {
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("target-feature={}", self.optimization_flags.target_features.join(",")));
|
rustflags.push(format!(
|
||||||
|
"target-feature={}",
|
||||||
|
self.optimization_flags.target_features.join(",")
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
// 代码模型
|
// 代码模型
|
||||||
rustflags.push("-C".to_string());
|
rustflags.push("-C".to_string());
|
||||||
rustflags.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
rustflags
|
||||||
|
.push(format!("code-model={:?}", self.optimization_flags.code_model).to_lowercase());
|
||||||
|
|
||||||
// 恐慌处理
|
// 恐慌处理
|
||||||
if self.codegen_config.panic_abort {
|
if self.codegen_config.panic_abort {
|
||||||
@@ -194,10 +198,14 @@ impl CompilerOptimizer {
|
|||||||
|
|
||||||
// 额外的性能优化标志
|
// 额外的性能优化标志
|
||||||
rustflags.extend([
|
rustflags.extend([
|
||||||
"-C".to_string(), "embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
"-C".to_string(),
|
||||||
"-C".to_string(), "debuginfo=0".to_string(), // 禁用调试信息
|
"embed-bitcode=no".to_string(), // 不嵌入位码以减少体积
|
||||||
"-C".to_string(), "rpath=no".to_string(), // 禁用rpath
|
"-C".to_string(),
|
||||||
"-C".to_string(), "force-frame-pointers=no".to_string(), // 禁用帧指针
|
"debuginfo=0".to_string(), // 禁用调试信息
|
||||||
|
"-C".to_string(),
|
||||||
|
"rpath=no".to_string(), // 禁用rpath
|
||||||
|
"-C".to_string(),
|
||||||
|
"force-frame-pointers=no".to_string(), // 禁用帧指针
|
||||||
]);
|
]);
|
||||||
|
|
||||||
let config = CompilerConfig {
|
let config = CompilerConfig {
|
||||||
@@ -215,8 +223,10 @@ impl CompilerOptimizer {
|
|||||||
let mut env_vars = HashMap::new();
|
let mut env_vars = HashMap::new();
|
||||||
|
|
||||||
// CPU特定优化
|
// CPU特定优化
|
||||||
env_vars.insert("CARGO_CFG_TARGET_FEATURE".to_string(),
|
env_vars.insert(
|
||||||
self.optimization_flags.target_features.join(","));
|
"CARGO_CFG_TARGET_FEATURE".to_string(),
|
||||||
|
self.optimization_flags.target_features.join(","),
|
||||||
|
);
|
||||||
|
|
||||||
// 启用不稳定特性
|
// 启用不稳定特性
|
||||||
env_vars.insert("RUSTC_BOOTSTRAP".to_string(), "1".to_string());
|
env_vars.insert("RUSTC_BOOTSTRAP".to_string(), "1".to_string());
|
||||||
@@ -244,7 +254,7 @@ impl CompilerOptimizer {
|
|||||||
debug_assertions: false,
|
debug_assertions: false,
|
||||||
rpath: false,
|
rpath: false,
|
||||||
strip: true, // 去除符号表
|
strip: true, // 去除符号表
|
||||||
}
|
},
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -253,8 +263,12 @@ impl CompilerOptimizer {
|
|||||||
CompilerOptimizationStats {
|
CompilerOptimizationStats {
|
||||||
inlined_functions: AtomicU64::new(self.stats.inlined_functions.load(Ordering::Relaxed)),
|
inlined_functions: AtomicU64::new(self.stats.inlined_functions.load(Ordering::Relaxed)),
|
||||||
constant_folding: AtomicU64::new(self.stats.constant_folding.load(Ordering::Relaxed)),
|
constant_folding: AtomicU64::new(self.stats.constant_folding.load(Ordering::Relaxed)),
|
||||||
dead_code_elimination: AtomicU64::new(self.stats.dead_code_elimination.load(Ordering::Relaxed)),
|
dead_code_elimination: AtomicU64::new(
|
||||||
loop_optimizations: AtomicU64::new(self.stats.loop_optimizations.load(Ordering::Relaxed)),
|
self.stats.dead_code_elimination.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
loop_optimizations: AtomicU64::new(
|
||||||
|
self.stats.loop_optimizations.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -279,12 +293,12 @@ impl OptimizationFlags {
|
|||||||
Self {
|
Self {
|
||||||
opt_level: OptLevel::Aggressive,
|
opt_level: OptLevel::Aggressive,
|
||||||
enable_lto: true,
|
enable_lto: true,
|
||||||
enable_pgo: false, // PGO需要多阶段构建
|
enable_pgo: false, // PGO需要多阶段构建
|
||||||
target_cpu: "native".to_string(), // 使用本机CPU特性
|
target_cpu: "native".to_string(), // 使用本机CPU特性
|
||||||
target_features,
|
target_features,
|
||||||
code_model: CodeModel::Small,
|
code_model: CodeModel::Small,
|
||||||
debug_info: false,
|
debug_info: false,
|
||||||
incremental: false, // 发布版本禁用增量编译
|
incremental: false, // 发布版本禁用增量编译
|
||||||
codegen_units: Some(1), // 单个代码生成单元获得最佳优化
|
codegen_units: Some(1), // 单个代码生成单元获得最佳优化
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -294,7 +308,7 @@ impl CodegenConfig {
|
|||||||
/// 超高性能配置
|
/// 超高性能配置
|
||||||
pub fn ultra_performance() -> Self {
|
pub fn ultra_performance() -> Self {
|
||||||
Self {
|
Self {
|
||||||
panic_abort: true, // 恐慌即中止,避免展开开销
|
panic_abort: true, // 恐慌即中止,避免展开开销
|
||||||
overflow_checks: false, // 生产环境禁用溢出检查
|
overflow_checks: false, // 生产环境禁用溢出检查
|
||||||
fat_lto: true,
|
fat_lto: true,
|
||||||
enable_simd: true,
|
enable_simd: true,
|
||||||
@@ -442,9 +456,7 @@ impl CompileTimeOptimizedEventProcessor {
|
|||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn route_event_zero_cost(&self, event_id: u8) -> u32 {
|
pub fn route_event_zero_cost(&self, event_id: u8) -> u32 {
|
||||||
// 编译时优化:直接数组访问,无边界检查
|
// 编译时优化:直接数组访问,无边界检查
|
||||||
unsafe {
|
unsafe { *self.route_table.get_unchecked((event_id as usize) & 1023) }
|
||||||
*self.route_table.get_unchecked((event_id as usize) & 1023)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 编译时优化的哈希查找
|
/// 🚀 编译时优化的哈希查找
|
||||||
@@ -523,7 +535,8 @@ fn main() {
|
|||||||
println!("cargo:rustc-link-arg=-fprofile-use");
|
println!("cargo:rustc-link-arg=-fprofile-use");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
"#.to_string()
|
"#
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 生成.cargo/config.toml
|
/// 🚀 生成.cargo/config.toml
|
||||||
@@ -576,7 +589,8 @@ rustflags = [
|
|||||||
rustflags = [
|
rustflags = [
|
||||||
"-C", "target-feature=+sse4.2,+avx,+avx2,+fma,+bmi1,+bmi2,+lzcnt,+popcnt",
|
"-C", "target-feature=+sse4.2,+avx,+avx2,+fma,+bmi1,+bmi2,+lzcnt,+popcnt",
|
||||||
]
|
]
|
||||||
"#.to_string()
|
"#
|
||||||
|
.to_string()
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
@@ -592,7 +606,8 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_compile_time_processor() {
|
fn test_compile_time_processor() {
|
||||||
const PROCESSOR: CompileTimeOptimizedEventProcessor = CompileTimeOptimizedEventProcessor::new();
|
const PROCESSOR: CompileTimeOptimizedEventProcessor =
|
||||||
|
CompileTimeOptimizedEventProcessor::new();
|
||||||
|
|
||||||
let route = PROCESSOR.route_event_zero_cost(42);
|
let route = PROCESSOR.route_event_zero_cost(42);
|
||||||
assert!(route < 16); // 应该路由到16个工作线程之一
|
assert!(route < 16); // 应该路由到16个工作线程之一
|
||||||
|
|||||||
@@ -1,11 +1,11 @@
|
|||||||
//! Hardware-oriented optimizations: cache-line alignment, prefetch, SIMD, branch hints, memory barriers.
|
//! Hardware-oriented optimizations: cache-line alignment, prefetch, SIMD, branch hints, memory barriers.
|
||||||
//! 硬件级优化:缓存行对齐与预取、SIMD、分支提示、内存屏障。
|
//! 硬件级优化:缓存行对齐与预取、SIMD、分支提示、内存屏障。
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
use anyhow::Result;
|
||||||
|
use crossbeam_utils::CachePadded;
|
||||||
use std::mem::size_of;
|
use std::mem::size_of;
|
||||||
use std::ptr;
|
use std::ptr;
|
||||||
use crossbeam_utils::CachePadded;
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
use anyhow::Result;
|
|
||||||
|
|
||||||
/// Typical CPU cache line size in bytes. 典型 CPU 缓存行大小(字节)。
|
/// Typical CPU cache line size in bytes. 典型 CPU 缓存行大小(字节)。
|
||||||
pub const CACHE_LINE_SIZE: usize = 64;
|
pub const CACHE_LINE_SIZE: usize = 64;
|
||||||
@@ -173,10 +173,7 @@ impl SIMDMemoryOps {
|
|||||||
match len {
|
match len {
|
||||||
1 => *a == *b,
|
1 => *a == *b,
|
||||||
2 => *(a as *const u16) == *(b as *const u16),
|
2 => *(a as *const u16) == *(b as *const u16),
|
||||||
3 => {
|
3 => *(a as *const u16) == *(b as *const u16) && *a.add(2) == *b.add(2),
|
||||||
*(a as *const u16) == *(b as *const u16) &&
|
|
||||||
*a.add(2) == *b.add(2)
|
|
||||||
}
|
|
||||||
4 => *(a as *const u32) == *(b as *const u32),
|
4 => *(a as *const u32) == *(b as *const u32),
|
||||||
5..=8 => *(a as *const u64) == *(b as *const u64),
|
5..=8 => *(a as *const u64) == *(b as *const u64),
|
||||||
_ => unreachable!(),
|
_ => unreachable!(),
|
||||||
@@ -188,7 +185,7 @@ impl SIMDMemoryOps {
|
|||||||
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_sse(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m128i, _mm_loadu_si128, _mm_cmpeq_epi8, _mm_movemask_epi8};
|
use std::arch::x86_64::{__m128i, _mm_cmpeq_epi8, _mm_loadu_si128, _mm_movemask_epi8};
|
||||||
|
|
||||||
let chunk_a = _mm_loadu_si128(a as *const __m128i);
|
let chunk_a = _mm_loadu_si128(a as *const __m128i);
|
||||||
let chunk_b = _mm_loadu_si128(b as *const __m128i);
|
let chunk_b = _mm_loadu_si128(b as *const __m128i);
|
||||||
@@ -210,7 +207,9 @@ impl SIMDMemoryOps {
|
|||||||
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
|
unsafe fn memcmp_avx2(a: *const u8, b: *const u8, len: usize) -> bool {
|
||||||
#[cfg(target_arch = "x86_64")]
|
#[cfg(target_arch = "x86_64")]
|
||||||
{
|
{
|
||||||
use std::arch::x86_64::{__m256i, _mm256_loadu_si256, _mm256_cmpeq_epi8, _mm256_movemask_epi8};
|
use std::arch::x86_64::{
|
||||||
|
__m256i, _mm256_cmpeq_epi8, _mm256_loadu_si256, _mm256_movemask_epi8,
|
||||||
|
};
|
||||||
|
|
||||||
let chunk_a = _mm256_loadu_si256(a as *const __m256i);
|
let chunk_a = _mm256_loadu_si256(a as *const __m256i);
|
||||||
let chunk_b = _mm256_loadu_si256(b as *const __m256i);
|
let chunk_b = _mm256_loadu_si256(b as *const __m256i);
|
||||||
@@ -397,8 +396,7 @@ impl<T: Copy + Default> CacheOptimizedRingBuffer<T> {
|
|||||||
/// True if no elements. 是否为空。
|
/// True if no elements. 是否为空。
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn is_empty(&self) -> bool {
|
pub fn is_empty(&self) -> bool {
|
||||||
self.producer_head.load(Ordering::Relaxed) ==
|
self.producer_head.load(Ordering::Relaxed) == self.consumer_tail.load(Ordering::Relaxed)
|
||||||
self.consumer_tail.load(Ordering::Relaxed)
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -525,11 +523,7 @@ mod tests {
|
|||||||
let mut dst = [0u8; 10];
|
let mut dst = [0u8; 10];
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
SIMDMemoryOps::memcpy_simd_optimized(
|
SIMDMemoryOps::memcpy_simd_optimized(dst.as_mut_ptr(), src.as_ptr(), src.len());
|
||||||
dst.as_mut_ptr(),
|
|
||||||
src.as_ptr(),
|
|
||||||
src.len()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
assert_eq!(src, dst);
|
assert_eq!(src, dst);
|
||||||
@@ -537,8 +531,7 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_cache_optimized_ring_buffer() {
|
fn test_cache_optimized_ring_buffer() {
|
||||||
let buffer: CacheOptimizedRingBuffer<u64> =
|
let buffer: CacheOptimizedRingBuffer<u64> = CacheOptimizedRingBuffer::new(16).unwrap();
|
||||||
CacheOptimizedRingBuffer::new(16).unwrap();
|
|
||||||
|
|
||||||
assert!(buffer.is_empty());
|
assert!(buffer.is_empty());
|
||||||
|
|
||||||
@@ -558,13 +551,9 @@ mod tests {
|
|||||||
let c = [1u8, 2, 3, 4, 6];
|
let c = [1u8, 2, 3, 4, 6];
|
||||||
|
|
||||||
unsafe {
|
unsafe {
|
||||||
assert!(SIMDMemoryOps::memcmp_simd_optimized(
|
assert!(SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), b.as_ptr(), a.len()));
|
||||||
a.as_ptr(), b.as_ptr(), a.len()
|
|
||||||
));
|
|
||||||
|
|
||||||
assert!(!SIMDMemoryOps::memcmp_simd_optimized(
|
assert!(!SIMDMemoryOps::memcmp_simd_optimized(a.as_ptr(), c.as_ptr(), a.len()));
|
||||||
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.
|
//! Performance: SIMD, cache prefetch, branch hints, zero-copy I/O, syscall bypass, compiler hints.
|
||||||
//! 性能优化:SIMD、缓存预取、分支提示、零拷贝 I/O、系统调用绕过、编译器提示。
|
//! 性能优化: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 compiler_optimization;
|
||||||
|
pub mod hardware_optimizations;
|
||||||
|
pub mod simd;
|
||||||
|
pub mod syscall_bypass;
|
||||||
|
pub mod zero_copy_io;
|
||||||
|
|
||||||
pub use simd::*;
|
|
||||||
pub use hardware_optimizations::*;
|
|
||||||
pub use zero_copy_io::*;
|
|
||||||
pub use syscall_bypass::*;
|
|
||||||
pub use compiler_optimization::*;
|
pub use compiler_optimization::*;
|
||||||
|
pub use hardware_optimizations::*;
|
||||||
|
pub use simd::*;
|
||||||
|
pub use syscall_bypass::*;
|
||||||
|
pub use zero_copy_io::*;
|
||||||
|
|||||||
+1
-1
@@ -235,7 +235,7 @@ impl SIMDHash {
|
|||||||
/// 批量计算 SHA256 哈希
|
/// 批量计算 SHA256 哈希
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn hash_batch_sha256(data: &[&[u8]]) -> Vec<[u8; 32]> {
|
pub fn hash_batch_sha256(data: &[&[u8]]) -> Vec<[u8; 32]> {
|
||||||
use sha2::{Sha256, Digest};
|
use sha2::{Digest, Sha256};
|
||||||
|
|
||||||
data.iter()
|
data.iter()
|
||||||
.map(|item| {
|
.map(|item| {
|
||||||
|
|||||||
+58
-58
@@ -1,11 +1,11 @@
|
|||||||
//! Syscall bypass: batching, vDSO fast time, io_uring, mmap, userspace impl.
|
//! Syscall bypass: batching, vDSO fast time, io_uring, mmap, userspace impl.
|
||||||
//! 系统调用绕过:批处理、vDSO 快速时间、io_uring、mmap、用户态实现。
|
//! 系统调用绕过:批处理、vDSO 快速时间、io_uring、mmap、用户态实现。
|
||||||
|
|
||||||
use std::sync::atomic::{AtomicU64, Ordering};
|
|
||||||
use std::sync::Arc;
|
|
||||||
use std::time::{SystemTime, UNIX_EPOCH, Duration, Instant};
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use std::fs::OpenOptions;
|
use std::fs::OpenOptions;
|
||||||
|
use std::sync::atomic::{AtomicU64, Ordering};
|
||||||
|
use std::sync::Arc;
|
||||||
|
use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use crossbeam_utils::CachePadded;
|
use crossbeam_utils::CachePadded;
|
||||||
@@ -55,14 +55,30 @@ pub struct SyscallBatchProcessor {
|
|||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone)]
|
||||||
pub enum SyscallRequest {
|
pub enum SyscallRequest {
|
||||||
Write { fd: i32, data: Vec<u8> },
|
Write {
|
||||||
Read { fd: i32, size: usize },
|
fd: i32,
|
||||||
Send { socket: i32, data: Vec<u8> },
|
data: Vec<u8>,
|
||||||
Recv { socket: i32, size: usize },
|
},
|
||||||
|
Read {
|
||||||
|
fd: i32,
|
||||||
|
size: usize,
|
||||||
|
},
|
||||||
|
Send {
|
||||||
|
socket: i32,
|
||||||
|
data: Vec<u8>,
|
||||||
|
},
|
||||||
|
Recv {
|
||||||
|
socket: i32,
|
||||||
|
size: usize,
|
||||||
|
},
|
||||||
GetTime,
|
GetTime,
|
||||||
MemAlloc { size: usize },
|
MemAlloc {
|
||||||
|
size: usize,
|
||||||
|
},
|
||||||
/// 内存释放
|
/// 内存释放
|
||||||
MemFree { ptr: usize },
|
MemFree {
|
||||||
|
ptr: usize,
|
||||||
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速时间提供器 - 绕过系统调用获取时间
|
/// 🚀 快速时间提供器 - 绕过系统调用获取时间
|
||||||
@@ -91,12 +107,10 @@ impl FastTimeProvider {
|
|||||||
_base_time: now,
|
_base_time: now,
|
||||||
monotonic_start: instant_now,
|
monotonic_start: instant_now,
|
||||||
time_cache: CachePadded::new(AtomicU64::new(
|
time_cache: CachePadded::new(AtomicU64::new(
|
||||||
now.duration_since(UNIX_EPOCH)?.as_nanos() as u64
|
now.duration_since(UNIX_EPOCH)?.as_nanos() as u64,
|
||||||
)),
|
)),
|
||||||
cache_update_interval_ns: 1_000_000, // 1ms
|
cache_update_interval_ns: 1_000_000, // 1ms
|
||||||
last_update: CachePadded::new(AtomicU64::new(
|
last_update: CachePadded::new(AtomicU64::new(instant_now.elapsed().as_nanos() as u64)),
|
||||||
instant_now.elapsed().as_nanos() as u64
|
|
||||||
)),
|
|
||||||
vdso_enabled: enable_vdso,
|
vdso_enabled: enable_vdso,
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -149,10 +163,8 @@ impl FastTimeProvider {
|
|||||||
if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) {
|
if let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH) {
|
||||||
let nanos = now.as_nanos() as u64;
|
let nanos = now.as_nanos() as u64;
|
||||||
self.time_cache.store(nanos, Ordering::Relaxed);
|
self.time_cache.store(nanos, Ordering::Relaxed);
|
||||||
self.last_update.store(
|
self.last_update
|
||||||
self.monotonic_start.elapsed().as_nanos() as u64,
|
.store(self.monotonic_start.elapsed().as_nanos() as u64, Ordering::Relaxed);
|
||||||
Ordering::Relaxed
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -262,7 +274,9 @@ impl IOOptimizer {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 这是一个系统调用而不是N个
|
// 这是一个系统调用而不是N个
|
||||||
self.async_io_stats.syscalls_avoided.fetch_add(requests.len() as u64 - 1, Ordering::Relaxed);
|
self.async_io_stats
|
||||||
|
.syscalls_avoided
|
||||||
|
.fetch_add(requests.len() as u64 - 1, Ordering::Relaxed);
|
||||||
|
|
||||||
Ok(results)
|
Ok(results)
|
||||||
}
|
}
|
||||||
@@ -300,11 +314,7 @@ impl IOOptimizer {
|
|||||||
};
|
};
|
||||||
|
|
||||||
#[cfg(not(target_os = "linux"))]
|
#[cfg(not(target_os = "linux"))]
|
||||||
let file = OpenOptions::new()
|
let file = OpenOptions::new().read(true).write(true).create(true).open(file_path)?;
|
||||||
.read(true)
|
|
||||||
.write(true)
|
|
||||||
.create(true)
|
|
||||||
.open(file_path)?;
|
|
||||||
|
|
||||||
let fd = file.as_raw_fd();
|
let fd = file.as_raw_fd();
|
||||||
|
|
||||||
@@ -322,11 +332,8 @@ impl IOOptimizer {
|
|||||||
return Err(anyhow::anyhow!("Memory mapping failed"));
|
return Err(anyhow::anyhow!("Memory mapping failed"));
|
||||||
}
|
}
|
||||||
|
|
||||||
let region = MemoryMappedRegion {
|
let region =
|
||||||
address: addr as usize,
|
MemoryMappedRegion { address: addr as usize, size, file_descriptor: fd };
|
||||||
size,
|
|
||||||
file_descriptor: fd,
|
|
||||||
};
|
|
||||||
|
|
||||||
self.mmap_regions.push(region);
|
self.mmap_regions.push(region);
|
||||||
|
|
||||||
@@ -344,10 +351,18 @@ impl IOOptimizer {
|
|||||||
/// 获取I/O统计
|
/// 获取I/O统计
|
||||||
pub fn get_stats(&self) -> AsyncIOStats {
|
pub fn get_stats(&self) -> AsyncIOStats {
|
||||||
AsyncIOStats {
|
AsyncIOStats {
|
||||||
operations_queued: AtomicU64::new(self.async_io_stats.operations_queued.load(Ordering::Relaxed)),
|
operations_queued: AtomicU64::new(
|
||||||
operations_completed: AtomicU64::new(self.async_io_stats.operations_completed.load(Ordering::Relaxed)),
|
self.async_io_stats.operations_queued.load(Ordering::Relaxed),
|
||||||
bytes_transferred: AtomicU64::new(self.async_io_stats.bytes_transferred.load(Ordering::Relaxed)),
|
),
|
||||||
syscalls_avoided: AtomicU64::new(self.async_io_stats.syscalls_avoided.load(Ordering::Relaxed)),
|
operations_completed: AtomicU64::new(
|
||||||
|
self.async_io_stats.operations_completed.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
bytes_transferred: AtomicU64::new(
|
||||||
|
self.async_io_stats.bytes_transferred.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
|
syscalls_avoided: AtomicU64::new(
|
||||||
|
self.async_io_stats.syscalls_avoided.load(Ordering::Relaxed),
|
||||||
|
),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -370,8 +385,7 @@ impl SyscallBatchProcessor {
|
|||||||
/// 🚀 提交系统调用请求到批处理队列
|
/// 🚀 提交系统调用请求到批处理队列
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn submit_request(&self, request: SyscallRequest) -> Result<()> {
|
pub fn submit_request(&self, request: SyscallRequest) -> Result<()> {
|
||||||
self.pending_calls.push(request)
|
self.pending_calls.push(request).map_err(|_| anyhow::anyhow!("Batch queue full"))?;
|
||||||
.map_err(|_| anyhow::anyhow!("Batch queue full"))?;
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -489,13 +503,7 @@ impl SystemCallBypassManager {
|
|||||||
tracing::info!(target: "sol_trade_sdk"," 🚀 vDSO: {}", config.enable_vdso);
|
tracing::info!(target: "sol_trade_sdk"," 🚀 vDSO: {}", config.enable_vdso);
|
||||||
tracing::info!(target: "sol_trade_sdk"," 📁 io_uring: {}", config.enable_io_uring);
|
tracing::info!(target: "sol_trade_sdk"," 📁 io_uring: {}", config.enable_io_uring);
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self { config, batch_processor, fast_time_provider, _io_optimizer: io_optimizer, stats })
|
||||||
config,
|
|
||||||
batch_processor,
|
|
||||||
fast_time_provider,
|
|
||||||
_io_optimizer: io_optimizer,
|
|
||||||
stats,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 快速获取当前时间戳 - 绕过系统调用
|
/// 🚀 快速获取当前时间戳 - 绕过系统调用
|
||||||
@@ -507,10 +515,7 @@ impl SystemCallBypassManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 回退到标准时间获取
|
// 回退到标准时间获取
|
||||||
SystemTime::now()
|
SystemTime::now().duration_since(UNIX_EPOCH).unwrap_or_default().as_nanos() as u64
|
||||||
.duration_since(UNIX_EPOCH)
|
|
||||||
.unwrap_or_default()
|
|
||||||
.as_nanos() as u64
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 提交批量I/O操作
|
/// 🚀 提交批量I/O操作
|
||||||
@@ -548,20 +553,16 @@ impl SystemCallBypassManager {
|
|||||||
|
|
||||||
/// 用户空间内存分配
|
/// 用户空间内存分配
|
||||||
fn userspace_allocate(&self, size: usize) -> Result<*mut u8> {
|
fn userspace_allocate(&self, size: usize) -> Result<*mut u8> {
|
||||||
use std::sync::Mutex;
|
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
|
use std::sync::Mutex;
|
||||||
|
|
||||||
struct MemoryPool {
|
struct MemoryPool {
|
||||||
pool: Box<[u8; 1024 * 1024]>,
|
pool: Box<[u8; 1024 * 1024]>,
|
||||||
offset: usize,
|
offset: usize,
|
||||||
}
|
}
|
||||||
|
|
||||||
static MEMORY_POOL: Lazy<Mutex<MemoryPool>> = Lazy::new(|| {
|
static MEMORY_POOL: Lazy<Mutex<MemoryPool>> =
|
||||||
Mutex::new(MemoryPool {
|
Lazy::new(|| Mutex::new(MemoryPool { pool: Box::new([0; 1024 * 1024]), offset: 0 }));
|
||||||
pool: Box::new([0; 1024 * 1024]),
|
|
||||||
offset: 0,
|
|
||||||
})
|
|
||||||
});
|
|
||||||
|
|
||||||
let mut pool = MEMORY_POOL.lock().unwrap();
|
let mut pool = MEMORY_POOL.lock().unwrap();
|
||||||
|
|
||||||
@@ -644,8 +645,10 @@ impl SyscallBypassStatsSnapshot {
|
|||||||
tracing::info!(target: "sol_trade_sdk"," 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
|
tracing::info!(target: "sol_trade_sdk"," 📁 I/O Operations Optimized: {}", self.io_operations_optimized);
|
||||||
tracing::info!(target: "sol_trade_sdk"," 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
|
tracing::info!(target: "sol_trade_sdk"," 💾 Memory Operations Avoided: {}", self.memory_operations_avoided);
|
||||||
|
|
||||||
let total_optimizations = self.syscalls_bypassed + self.time_calls_cached +
|
let total_optimizations = self.syscalls_bypassed
|
||||||
self.io_operations_optimized + self.memory_operations_avoided;
|
+ self.time_calls_cached
|
||||||
|
+ self.io_operations_optimized
|
||||||
|
+ self.memory_operations_avoided;
|
||||||
tracing::info!(target: "sol_trade_sdk"," 🏆 Total Optimizations: {}", total_optimizations);
|
tracing::info!(target: "sol_trade_sdk"," 🏆 Total Optimizations: {}", total_optimizations);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -684,10 +687,7 @@ mod tests {
|
|||||||
async fn test_syscall_batch_processor() {
|
async fn test_syscall_batch_processor() {
|
||||||
let processor = SyscallBatchProcessor::new(10).unwrap();
|
let processor = SyscallBatchProcessor::new(10).unwrap();
|
||||||
|
|
||||||
let request = SyscallRequest::Write {
|
let request = SyscallRequest::Write { fd: 1, data: vec![1, 2, 3, 4, 5] };
|
||||||
fd: 1,
|
|
||||||
data: vec![1, 2, 3, 4, 5],
|
|
||||||
};
|
|
||||||
|
|
||||||
processor.submit_request(request).unwrap();
|
processor.submit_request(request).unwrap();
|
||||||
|
|
||||||
|
|||||||
+33
-26
@@ -10,11 +10,11 @@
|
|||||||
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
// use std::mem::{size_of, MaybeUninit};
|
// use std::mem::{size_of, MaybeUninit};
|
||||||
|
use anyhow::{Context, Result};
|
||||||
|
use crossbeam_utils::CachePadded;
|
||||||
|
use memmap2::{MmapMut, MmapOptions};
|
||||||
use std::ptr::NonNull;
|
use std::ptr::NonNull;
|
||||||
use std::slice;
|
use std::slice;
|
||||||
use memmap2::{MmapMut, MmapOptions};
|
|
||||||
use anyhow::{Result, Context};
|
|
||||||
use crossbeam_utils::CachePadded;
|
|
||||||
|
|
||||||
/// 🚀 零拷贝内存管理器
|
/// 🚀 零拷贝内存管理器
|
||||||
pub struct ZeroCopyMemoryManager {
|
pub struct ZeroCopyMemoryManager {
|
||||||
@@ -109,7 +109,7 @@ impl SharedMemoryPool {
|
|||||||
current,
|
current,
|
||||||
current & !mask,
|
current & !mask,
|
||||||
Ordering::AcqRel,
|
Ordering::AcqRel,
|
||||||
Ordering::Relaxed
|
Ordering::Relaxed,
|
||||||
) {
|
) {
|
||||||
Ok(_) => {
|
Ok(_) => {
|
||||||
// 成功分配
|
// 成功分配
|
||||||
@@ -128,10 +128,7 @@ impl SharedMemoryPool {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// 更新分配器头指针
|
// 更新分配器头指针
|
||||||
self.allocator_head.store(
|
self.allocator_head.store((block_index + 1) * 64, Ordering::Relaxed);
|
||||||
(block_index + 1) * 64,
|
|
||||||
Ordering::Relaxed
|
|
||||||
);
|
|
||||||
|
|
||||||
return Some(ZeroCopyBlock {
|
return Some(ZeroCopyBlock {
|
||||||
ptr,
|
ptr,
|
||||||
@@ -171,7 +168,8 @@ impl SharedMemoryPool {
|
|||||||
|
|
||||||
/// 获取可用块数量
|
/// 获取可用块数量
|
||||||
pub fn available_blocks(&self) -> usize {
|
pub fn available_blocks(&self) -> usize {
|
||||||
self.free_blocks.iter()
|
self.free_blocks
|
||||||
|
.iter()
|
||||||
.map(|bitmap| bitmap.load(Ordering::Relaxed).count_ones() as usize)
|
.map(|bitmap| bitmap.load(Ordering::Relaxed).count_ones() as usize)
|
||||||
.sum()
|
.sum()
|
||||||
}
|
}
|
||||||
@@ -225,7 +223,7 @@ impl ZeroCopyBlock {
|
|||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
self.ptr.as_ptr(),
|
self.ptr.as_ptr(),
|
||||||
data.as_ptr(),
|
data.as_ptr(),
|
||||||
data.len()
|
data.len(),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@@ -303,7 +301,9 @@ impl MemoryMappedBuffer {
|
|||||||
if current_write + data_len <= self.size {
|
if current_write + data_len <= self.size {
|
||||||
// 数据不跨越缓冲区边界
|
// 数据不跨越缓冲区边界
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
write_ptr, data.as_ptr(), data_len
|
write_ptr,
|
||||||
|
data.as_ptr(),
|
||||||
|
data_len,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// 数据跨越缓冲区边界,分两段写入
|
// 数据跨越缓冲区边界,分两段写入
|
||||||
@@ -312,14 +312,16 @@ impl MemoryMappedBuffer {
|
|||||||
|
|
||||||
// 写入第一部分
|
// 写入第一部分
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
write_ptr, data.as_ptr(), first_part
|
write_ptr,
|
||||||
|
data.as_ptr(),
|
||||||
|
first_part,
|
||||||
);
|
);
|
||||||
|
|
||||||
// 写入第二部分(从缓冲区开头)
|
// 写入第二部分(从缓冲区开头)
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
self.mmap.as_ptr() as *mut u8,
|
self.mmap.as_ptr() as *mut u8,
|
||||||
data.as_ptr().add(first_part),
|
data.as_ptr().add(first_part),
|
||||||
second_part
|
second_part,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -358,7 +360,9 @@ impl MemoryMappedBuffer {
|
|||||||
if current_read + read_len <= self.size {
|
if current_read + read_len <= self.size {
|
||||||
// 数据不跨越缓冲区边界
|
// 数据不跨越缓冲区边界
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr(), read_ptr, read_len
|
buffer.as_mut_ptr(),
|
||||||
|
read_ptr,
|
||||||
|
read_len,
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
// 数据跨越缓冲区边界,分两段读取
|
// 数据跨越缓冲区边界,分两段读取
|
||||||
@@ -367,14 +371,16 @@ impl MemoryMappedBuffer {
|
|||||||
|
|
||||||
// 读取第一部分
|
// 读取第一部分
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr(), read_ptr, first_part
|
buffer.as_mut_ptr(),
|
||||||
|
read_ptr,
|
||||||
|
first_part,
|
||||||
);
|
);
|
||||||
|
|
||||||
// 读取第二部分(从缓冲区开头)
|
// 读取第二部分(从缓冲区开头)
|
||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
buffer.as_mut_ptr().add(first_part),
|
buffer.as_mut_ptr().add(first_part),
|
||||||
self.mmap.as_ptr(),
|
self.mmap.as_ptr(),
|
||||||
second_part
|
second_part,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -442,7 +448,8 @@ impl DirectMemoryAccessManager {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 选择DMA通道(轮询分配)
|
// 选择DMA通道(轮询分配)
|
||||||
let channel_index = self.channel_allocator.fetch_add(1, Ordering::Relaxed) % self.dma_channels.len();
|
let channel_index =
|
||||||
|
self.channel_allocator.fetch_add(1, Ordering::Relaxed) % self.dma_channels.len();
|
||||||
let channel = &self.dma_channels[channel_index];
|
let channel = &self.dma_channels[channel_index];
|
||||||
|
|
||||||
// 执行DMA传输
|
// 执行DMA传输
|
||||||
@@ -486,7 +493,7 @@ impl DMAChannel {
|
|||||||
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
super::hardware_optimizations::SIMDMemoryOps::memcpy_simd_optimized(
|
||||||
dst.as_mut_ptr(),
|
dst.as_mut_ptr(),
|
||||||
src.as_ptr(),
|
src.as_ptr(),
|
||||||
transfer_size
|
transfer_size,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -571,11 +578,16 @@ impl ZeroCopyMemoryManager {
|
|||||||
// 中块池: 1MB blocks, 4GB total
|
// 中块池: 1MB blocks, 4GB total
|
||||||
shared_pools.push(Arc::new(SharedMemoryPool::new(1, 4 * 1024 * 1024 * 1024, 1024 * 1024)?));
|
shared_pools.push(Arc::new(SharedMemoryPool::new(1, 4 * 1024 * 1024 * 1024, 1024 * 1024)?));
|
||||||
// 大块池: 16MB blocks, 8GB total
|
// 大块池: 16MB blocks, 8GB total
|
||||||
shared_pools.push(Arc::new(SharedMemoryPool::new(2, 8 * 1024 * 1024 * 1024, 16 * 1024 * 1024)?));
|
shared_pools.push(Arc::new(SharedMemoryPool::new(
|
||||||
|
2,
|
||||||
|
8 * 1024 * 1024 * 1024,
|
||||||
|
16 * 1024 * 1024,
|
||||||
|
)?));
|
||||||
|
|
||||||
// 创建内存映射缓冲区
|
// 创建内存映射缓冲区
|
||||||
for i in 0..8 {
|
for i in 0..8 {
|
||||||
mmap_buffers.push(Arc::new(MemoryMappedBuffer::new(i, 256 * 1024 * 1024)?)); // 256MB each
|
mmap_buffers.push(Arc::new(MemoryMappedBuffer::new(i, 256 * 1024 * 1024)?));
|
||||||
|
// 256MB each
|
||||||
}
|
}
|
||||||
|
|
||||||
let dma_manager = Arc::new(DirectMemoryAccessManager::new(16)?); // 16 DMA channels
|
let dma_manager = Arc::new(DirectMemoryAccessManager::new(16)?); // 16 DMA channels
|
||||||
@@ -586,12 +598,7 @@ impl ZeroCopyMemoryManager {
|
|||||||
tracing::info!(target: "sol_trade_sdk"," 💾 Mapped Buffers: {}", mmap_buffers.len());
|
tracing::info!(target: "sol_trade_sdk"," 💾 Mapped Buffers: {}", mmap_buffers.len());
|
||||||
tracing::info!(target: "sol_trade_sdk"," 🔄 DMA Channels: 16");
|
tracing::info!(target: "sol_trade_sdk"," 🔄 DMA Channels: 16");
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self { shared_pools, mmap_buffers, dma_manager, stats })
|
||||||
shared_pools,
|
|
||||||
mmap_buffers,
|
|
||||||
dma_manager,
|
|
||||||
stats,
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 分配零拷贝内存块
|
/// 🚀 分配零拷贝内存块
|
||||||
|
|||||||
+62
-31
@@ -4,18 +4,18 @@ use reqwest::Client;
|
|||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
use tracing::{error, info, warn};
|
use tracing::{error, info, warn};
|
||||||
|
|
||||||
use std::time::Duration;
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use bincode::serialize as bincode_serialize;
|
use bincode::serialize as bincode_serialize;
|
||||||
use solana_client::rpc_client::SerializableTransaction;
|
use solana_client::rpc_client::SerializableTransaction;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
use std::time::Duration;
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::ASTRALANE_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::ASTRALANE_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
/// Empty body for getHealth POST; avoid per-request allocation.
|
/// Empty body for getHealth POST; avoid per-request allocation.
|
||||||
static PING_BODY: &[u8] = &[];
|
static PING_BODY: &[u8] = &[];
|
||||||
@@ -42,11 +42,21 @@ pub struct AstralaneClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for AstralaneClient {
|
impl SwqosClientTrait for AstralaneClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
@@ -54,7 +64,10 @@ impl SwqosClientTrait for AstralaneClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *ASTRALANE_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| ASTRALANE_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *ASTRALANE_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| ASTRALANE_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -100,36 +113,48 @@ impl AstralaneClient {
|
|||||||
|
|
||||||
async fn start_ping_task(&self) {
|
async fn start_ping_task(&self) {
|
||||||
match &self.backend {
|
match &self.backend {
|
||||||
AstralaneBackend::Http { endpoint, auth_token, http_client, ping_handle, stop_ping } => {
|
AstralaneBackend::Http {
|
||||||
let endpoint = endpoint.clone();
|
endpoint,
|
||||||
let auth_token = auth_token.clone();
|
auth_token,
|
||||||
let http_client = http_client.clone();
|
http_client,
|
||||||
let ping_handle = ping_handle.clone();
|
ping_handle,
|
||||||
let stop_ping = stop_ping.clone();
|
stop_ping,
|
||||||
let handle = tokio::spawn(async move {
|
} => {
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
let endpoint = endpoint.clone();
|
||||||
loop {
|
let auth_token = auth_token.clone();
|
||||||
interval.tick().await;
|
let http_client = http_client.clone();
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
let ping_handle = ping_handle.clone();
|
||||||
break;
|
let stop_ping = stop_ping.clone();
|
||||||
}
|
let handle = tokio::spawn(async move {
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||||
warn!(target: "sol_trade_sdk", "Astralane ping request failed: {}", e);
|
loop {
|
||||||
|
interval.tick().await;
|
||||||
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if let Err(e) =
|
||||||
|
Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||||
|
{
|
||||||
|
warn!(target: "sol_trade_sdk", "Astralane ping request failed: {}", e);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
});
|
||||||
|
let mut guard = ping_handle.lock().await;
|
||||||
|
if let Some(old) = guard.as_ref() {
|
||||||
|
old.abort();
|
||||||
}
|
}
|
||||||
});
|
*guard = Some(handle);
|
||||||
let mut guard = ping_handle.lock().await;
|
|
||||||
if let Some(old) = guard.as_ref() {
|
|
||||||
old.abort();
|
|
||||||
}
|
|
||||||
*guard = Some(handle);
|
|
||||||
}
|
}
|
||||||
AstralaneBackend::Quic(_) => {}
|
AstralaneBackend::Quic(_) => {}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request: POST endpoint?api-key=...&method=getHealth
|
/// Send ping request: POST endpoint?api-key=...&method=getHealth
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
let response = http_client
|
let response = http_client
|
||||||
.post(endpoint)
|
.post(endpoint)
|
||||||
.query(&[("api-key", auth_token), ("method", "getHealth")])
|
.query(&[("api-key", auth_token), ("method", "getHealth")])
|
||||||
@@ -145,10 +170,16 @@ impl AstralaneClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transaction_impl(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let signature = transaction.get_signature();
|
let signature = transaction.get_signature();
|
||||||
let body_bytes = bincode_serialize(transaction).map_err(|e| anyhow::anyhow!("Astralane binary serialize failed: {}", e))?;
|
let body_bytes = bincode_serialize(transaction)
|
||||||
|
.map_err(|e| anyhow::anyhow!("Astralane binary serialize failed: {}", e))?;
|
||||||
|
|
||||||
match &self.backend {
|
match &self.backend {
|
||||||
AstralaneBackend::Http { endpoint, auth_token, http_client, .. } => {
|
AstralaneBackend::Http { endpoint, auth_token, http_client, .. } => {
|
||||||
|
|||||||
+18
-26
@@ -49,14 +49,16 @@ impl AstralaneQuicClient {
|
|||||||
/// Generates a self-signed TLS certificate with the API key as the Common Name (CN).
|
/// Generates a self-signed TLS certificate with the API key as the Common Name (CN).
|
||||||
pub async fn connect(server_addr: &str, api_key: &str) -> Result<Self> {
|
pub async fn connect(server_addr: &str, api_key: &str) -> Result<Self> {
|
||||||
let _ = rustls::crypto::ring::default_provider().install_default();
|
let _ = rustls::crypto::ring::default_provider().install_default();
|
||||||
let addr = SocketAddr::from_str(server_addr).or_else(|_| {
|
let addr = SocketAddr::from_str(server_addr)
|
||||||
use std::net::ToSocketAddrs;
|
.or_else(|_| {
|
||||||
server_addr
|
use std::net::ToSocketAddrs;
|
||||||
.to_socket_addrs()
|
server_addr
|
||||||
.ok()
|
.to_socket_addrs()
|
||||||
.and_then(|mut addrs| addrs.next())
|
.ok()
|
||||||
.ok_or_else(|| anyhow::anyhow!("Cannot resolve address: {}", server_addr))
|
.and_then(|mut addrs| addrs.next())
|
||||||
}).context("Invalid server address")?;
|
.ok_or_else(|| anyhow::anyhow!("Cannot resolve address: {}", server_addr))
|
||||||
|
})
|
||||||
|
.context("Invalid server address")?;
|
||||||
|
|
||||||
info!("[astralane-quic] Building TLS config (CN = api_key)");
|
info!("[astralane-quic] Building TLS config (CN = api_key)");
|
||||||
let client_config = Self::build_client_config(api_key)?;
|
let client_config = Self::build_client_config(api_key)?;
|
||||||
@@ -116,10 +118,8 @@ impl AstralaneQuicClient {
|
|||||||
guard.clone()
|
guard.clone()
|
||||||
};
|
};
|
||||||
|
|
||||||
let mut send_stream = conn
|
let mut send_stream =
|
||||||
.open_uni()
|
conn.open_uni().await.context("Failed to open unidirectional stream")?;
|
||||||
.await
|
|
||||||
.context("Failed to open unidirectional stream")?;
|
|
||||||
|
|
||||||
send_stream
|
send_stream
|
||||||
.write_all(transaction_bytes)
|
.write_all(transaction_bytes)
|
||||||
@@ -154,19 +154,15 @@ impl AstralaneQuicClient {
|
|||||||
|
|
||||||
/// Close the connection gracefully.
|
/// Close the connection gracefully.
|
||||||
pub async fn close(&self) {
|
pub async fn close(&self) {
|
||||||
self.connection
|
self.connection.lock().await.close(error_code::OK.into(), b"client closing");
|
||||||
.lock()
|
|
||||||
.await
|
|
||||||
.close(error_code::OK.into(), b"client closing");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn build_client_config(api_key: &str) -> Result<ClientConfig> {
|
fn build_client_config(api_key: &str) -> Result<ClientConfig> {
|
||||||
let key_pair = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
let key_pair = KeyPair::generate_for(&rcgen::PKCS_ECDSA_P256_SHA256)?;
|
||||||
let mut cert_params = CertificateParams::new(vec![])?;
|
let mut cert_params = CertificateParams::new(vec![])?;
|
||||||
cert_params.distinguished_name.push(
|
cert_params
|
||||||
rcgen::DnType::CommonName,
|
.distinguished_name
|
||||||
rcgen::DnValue::Utf8String(api_key.to_string()),
|
.push(rcgen::DnType::CommonName, rcgen::DnValue::Utf8String(api_key.to_string()));
|
||||||
);
|
|
||||||
let cert = cert_params.self_signed(&key_pair)?;
|
let cert = cert_params.self_signed(&key_pair)?;
|
||||||
|
|
||||||
let cert_der = CertificateDer::from(cert.der().to_vec());
|
let cert_der = CertificateDer::from(cert.der().to_vec());
|
||||||
@@ -181,9 +177,7 @@ impl AstralaneQuicClient {
|
|||||||
crypto.alpn_protocols = vec![ALPN_ASTRALANE_TPU.to_vec()];
|
crypto.alpn_protocols = vec![ALPN_ASTRALANE_TPU.to_vec()];
|
||||||
|
|
||||||
let mut transport = TransportConfig::default();
|
let mut transport = TransportConfig::default();
|
||||||
transport.max_idle_timeout(Some(
|
transport.max_idle_timeout(Some(IdleTimeout::try_from(Duration::from_secs(30)).unwrap()));
|
||||||
IdleTimeout::try_from(Duration::from_secs(30)).unwrap(),
|
|
||||||
));
|
|
||||||
transport.keep_alive_interval(Some(Duration::from_secs(25)));
|
transport.keep_alive_interval(Some(Duration::from_secs(25)));
|
||||||
|
|
||||||
let mut client_config =
|
let mut client_config =
|
||||||
@@ -196,9 +190,7 @@ impl AstralaneQuicClient {
|
|||||||
|
|
||||||
impl Drop for AstralaneQuicClient {
|
impl Drop for AstralaneQuicClient {
|
||||||
fn drop(&mut self) {
|
fn drop(&mut self) {
|
||||||
self.connection
|
self.connection.get_mut().close(error_code::OK.into(), b"client closing");
|
||||||
.get_mut()
|
|
||||||
.close(error_code::OK.into(), b"client closing");
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+58
-22
@@ -1,20 +1,22 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BlockRazorClient {
|
pub struct BlockRazorClient {
|
||||||
@@ -28,16 +30,29 @@ pub struct BlockRazorClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for BlockRazorClient {
|
impl SwqosClientTrait for BlockRazorClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *BLOCKRAZOR_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| BLOCKRAZOR_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *BLOCKRAZOR_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| BLOCKRAZOR_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,10 +65,7 @@ impl BlockRazorClient {
|
|||||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
// 官方文档:請求中唯一允許的 header 是 Content-Type: text/plain;避免默认 User-Agent 等导致 500
|
// 官方文档:請求中唯一允許的 header 是 Content-Type: text/plain;避免默认 User-Agent 等导致 500
|
||||||
let http_client = default_http_client_builder()
|
let http_client = default_http_client_builder().user_agent("").build().unwrap();
|
||||||
.user_agent("")
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let client = Self {
|
let client = Self {
|
||||||
rpc_client: Arc::new(rpc_client),
|
rpc_client: Arc::new(rpc_client),
|
||||||
@@ -87,13 +99,14 @@ impl BlockRazorClient {
|
|||||||
eprintln!("BlockRazor ping request failed: {}", e);
|
eprintln!("BlockRazor ping request failed: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive to avoid server ~5min idle close
|
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive to avoid server ~5min idle close
|
||||||
loop {
|
loop {
|
||||||
interval.tick().await;
|
interval.tick().await;
|
||||||
if stop_ping.load(Ordering::Relaxed) {
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||||
|
{
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!("BlockRazor ping request failed: {}", e);
|
eprintln!("BlockRazor ping request failed: {}", e);
|
||||||
}
|
}
|
||||||
@@ -112,7 +125,11 @@ impl BlockRazorClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request: POST /v2/health?auth=... (Keep Alive). Only required param: auth.
|
/// Send ping request: POST /v2/health?auth=... (Keep Alive). Only required param: auth.
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
let ping_url = endpoint.replace("/v2/sendTransaction", "/v2/health");
|
let ping_url = endpoint.replace("/v2/sendTransaction", "/v2/health");
|
||||||
let response = http_client
|
let response = http_client
|
||||||
.post(&ping_url)
|
.post(&ping_url)
|
||||||
@@ -132,11 +149,18 @@ impl BlockRazorClient {
|
|||||||
|
|
||||||
/// Send transaction via v2 API: plain Base64 body, Content-Type: text/plain. Only required URI param: auth.
|
/// Send transaction via v2 API: plain Base64 body, Content-Type: text/plain. Only required URI param: auth.
|
||||||
/// 文档要求:auth 以 URI 参数传入;body 为纯 Base64 编码交易;唯一允许的 header 为 Content-Type: text/plain。
|
/// 文档要求:auth 以 URI 参数传入;body 为纯 Base64 编码交易;唯一允许的 header 为 Content-Type: text/plain。
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let response = self.http_client
|
let response = self
|
||||||
|
.http_client
|
||||||
.post(&self.endpoint)
|
.post(&self.endpoint)
|
||||||
.query(&[("auth", self.auth_token.as_str())])
|
.query(&[("auth", self.auth_token.as_str())])
|
||||||
.header("Content-Type", "text/plain")
|
.header("Content-Type", "text/plain")
|
||||||
@@ -153,7 +177,10 @@ impl BlockRazorClient {
|
|||||||
} else {
|
} else {
|
||||||
let body = response.text().await.unwrap_or_default();
|
let body = response.text().await.unwrap_or_default();
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [blockrazor] {} submission failed: status {} body: {}", trade_type, status, body);
|
eprintln!(
|
||||||
|
" [blockrazor] {} submission failed: status {} body: {}",
|
||||||
|
trade_type, status, body
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(anyhow::anyhow!(
|
return Err(anyhow::anyhow!(
|
||||||
"BlockRazor sendTransaction failed: status {} body: {}",
|
"BlockRazor sendTransaction failed: status {} body: {}",
|
||||||
@@ -168,10 +195,14 @@ impl BlockRazorClient {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [blockrazor] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [blockrazor] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -181,7 +212,12 @@ impl BlockRazorClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+45
-14
@@ -6,17 +6,16 @@ use rand::seq::IndexedRandom;
|
|||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::BLOX_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::BLOX_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct BloxrouteClient {
|
pub struct BloxrouteClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -27,16 +26,29 @@ pub struct BloxrouteClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for BloxrouteClient {
|
impl SwqosClientTrait for BloxrouteClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *BLOX_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| BLOX_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *BLOX_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| BLOX_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -56,9 +68,15 @@ impl BloxrouteClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Single format! for body to avoid json! + to_string() double allocation
|
// Single format! for body to avoid json! + to_string() double allocation
|
||||||
let body = format!(
|
let body = format!(
|
||||||
@@ -67,7 +85,9 @@ impl BloxrouteClient {
|
|||||||
);
|
);
|
||||||
|
|
||||||
let endpoint = format!("{}/api/v2/submit", self.endpoint);
|
let endpoint = format!("{}/api/v2/submit", self.endpoint);
|
||||||
let response_text = self.http_client.post(&endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&endpoint)
|
||||||
.body(body)
|
.body(body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Authorization", self.auth_token.as_str())
|
.header("Authorization", self.auth_token.as_str())
|
||||||
@@ -95,10 +115,14 @@ impl BloxrouteClient {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [bloxroute] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [bloxroute] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -108,7 +132,12 @@ impl BloxrouteClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, _wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
_wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
|
|
||||||
let contents = serialization::serialize_transactions_batch_sync(
|
let contents = serialization::serialize_transactions_batch_sync(
|
||||||
@@ -123,7 +152,9 @@ impl BloxrouteClient {
|
|||||||
let body = format!(r#"{{"entries":[{}]}}"#, entries);
|
let body = format!(r#"{{"entries":[{}]}}"#, entries);
|
||||||
|
|
||||||
let endpoint = format!("{}/api/v2/submit-batch", self.endpoint);
|
let endpoint = format!("{}/api/v2/submit-batch", self.endpoint);
|
||||||
let response_text = self.http_client.post(&endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&endpoint)
|
||||||
.body(body)
|
.body(body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Authorization", self.auth_token.as_str())
|
.header("Authorization", self.auth_token.as_str())
|
||||||
|
|||||||
+19
-7
@@ -1,9 +1,9 @@
|
|||||||
use crate::common::types::SolanaRpcClient;
|
use crate::common::types::SolanaRpcClient;
|
||||||
|
use crate::swqos::serialization;
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use base64::engine::general_purpose::{self, STANDARD};
|
use base64::engine::general_purpose::{self, STANDARD};
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
use bincode::serialize;
|
use bincode::serialize;
|
||||||
use crate::swqos::serialization;
|
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json;
|
use serde_json;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -117,7 +117,11 @@ pub async fn poll_any_transaction_confirmation(
|
|||||||
|
|
||||||
loop {
|
loop {
|
||||||
if start.elapsed() >= timeout {
|
if start.elapsed() >= timeout {
|
||||||
return Err(anyhow::anyhow!("Transaction confirmation timed out after {}s ({} signatures polled)", timeout.as_secs(), signatures.len()));
|
return Err(anyhow::anyhow!(
|
||||||
|
"Transaction confirmation timed out after {}s ({} signatures polled)",
|
||||||
|
timeout.as_secs(),
|
||||||
|
signatures.len()
|
||||||
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
poll_count += 1;
|
poll_count += 1;
|
||||||
@@ -241,7 +245,12 @@ pub async fn poll_any_transaction_confirmation(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_nb_transaction(client: Client, endpoint: &str, auth_token: &str, transaction: &Transaction) -> Result<Signature, anyhow::Error> {
|
pub async fn send_nb_transaction(
|
||||||
|
client: Client,
|
||||||
|
endpoint: &str,
|
||||||
|
auth_token: &str,
|
||||||
|
transaction: &Transaction,
|
||||||
|
) -> Result<Signature, anyhow::Error> {
|
||||||
// Serialize transaction
|
// Serialize transaction
|
||||||
let serialized = bincode::serialize(transaction)
|
let serialized = bincode::serialize(transaction)
|
||||||
.map_err(|e| anyhow::anyhow!("Transaction serialization failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Transaction serialization failed: {}", e))?;
|
||||||
@@ -266,18 +275,21 @@ pub async fn send_nb_transaction(client: Client, endpoint: &str, auth_token: &st
|
|||||||
.await
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("Request failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Request failed: {}", e))?;
|
||||||
|
|
||||||
let resp = response.json::<serde_json::Value>().await
|
let resp = response
|
||||||
|
.json::<serde_json::Value>()
|
||||||
|
.await
|
||||||
.map_err(|e| anyhow::anyhow!("Response parsing failed: {}", e))?;
|
.map_err(|e| anyhow::anyhow!("Response parsing failed: {}", e))?;
|
||||||
|
|
||||||
if let Some(reason) = resp["reason"].as_str() {
|
if let Some(reason) = resp["reason"].as_str() {
|
||||||
return Err(anyhow::anyhow!(reason.to_string()));
|
return Err(anyhow::anyhow!(reason.to_string()));
|
||||||
}
|
}
|
||||||
|
|
||||||
let signature = resp["signature"].as_str()
|
let signature = resp["signature"]
|
||||||
|
.as_str()
|
||||||
.ok_or_else(|| anyhow::anyhow!("Missing signature field in response"))?;
|
.ok_or_else(|| anyhow::anyhow!("Missing signature field in response"))?;
|
||||||
|
|
||||||
let signature = Signature::from_str(signature)
|
let signature =
|
||||||
.map_err(|e| anyhow::anyhow!("Invalid signature: {}", e))?;
|
Signature::from_str(signature).map_err(|e| anyhow::anyhow!("Invalid signature: {}", e))?;
|
||||||
|
|
||||||
Ok(signature)
|
Ok(signature)
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-13
@@ -1,4 +1,6 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -6,14 +8,13 @@ use std::{sync::Arc, time::Instant};
|
|||||||
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::FLASHBLOCK_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::FLASHBLOCK_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct FlashBlockClient {
|
pub struct FlashBlockClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -24,16 +25,29 @@ pub struct FlashBlockClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for FlashBlockClient {
|
impl SwqosClientTrait for FlashBlockClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *FLASHBLOCK_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| FLASHBLOCK_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *FLASHBLOCK_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| FLASHBLOCK_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +63,15 @@ impl FlashBlockClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// FlashBlock API format
|
// FlashBlock API format
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -61,7 +81,9 @@ impl FlashBlockClient {
|
|||||||
let url = format!("{}/api/v2/submit-batch", self.endpoint);
|
let url = format!("{}/api/v2/submit-batch", self.endpoint);
|
||||||
|
|
||||||
// Send request to FlashBlock
|
// Send request to FlashBlock
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Authorization", &self.auth_token)
|
.header("Authorization", &self.auth_token)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
@@ -88,9 +110,13 @@ impl FlashBlockClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [FlashBlock] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [FlashBlock] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -100,7 +126,12 @@ impl FlashBlockClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+9
-27
@@ -20,7 +20,9 @@ use std::sync::Arc;
|
|||||||
use std::time::Instant;
|
use std::time::Instant;
|
||||||
|
|
||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
use crate::constants::swqos::{HELIUS_TIP_ACCOUNTS, SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY};
|
use crate::constants::swqos::{
|
||||||
|
HELIUS_TIP_ACCOUNTS, SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_HELIUS_SWQOS_ONLY,
|
||||||
|
};
|
||||||
use crate::swqos::{SwqosClientTrait, SwqosType, TradeType};
|
use crate::swqos::{SwqosClientTrait, SwqosType, TradeType};
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@@ -43,12 +45,7 @@ impl HeliusClient {
|
|||||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||||
let http_client = default_http_client_builder().build().unwrap();
|
let http_client = default_http_client_builder().build().unwrap();
|
||||||
let submit_url = Self::build_submit_url(&endpoint, api_key.as_deref(), swqos_only);
|
let submit_url = Self::build_submit_url(&endpoint, api_key.as_deref(), swqos_only);
|
||||||
Self {
|
Self { submit_url, rpc_client: Arc::new(rpc_client), http_client, swqos_only }
|
||||||
submit_url,
|
|
||||||
rpc_client: Arc::new(rpc_client),
|
|
||||||
http_client,
|
|
||||||
swqos_only,
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Build URL once at construction; no per-request allocation.
|
/// Build URL once at construction; no per-request allocation.
|
||||||
@@ -132,17 +129,10 @@ impl HeliusClient {
|
|||||||
return Err(anyhow::anyhow!("Helius Sender error: {}", err_msg));
|
return Err(anyhow::anyhow!("Helius Sender error: {}", err_msg));
|
||||||
}
|
}
|
||||||
if response_json.get("result").is_some() && crate::common::sdk_log::sdk_log_enabled() {
|
if response_json.get("result").is_some() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(
|
println!(" [helius] {} submitted: {:?}", trade_type, start_time.elapsed());
|
||||||
" [helius] {} submitted: {:?}",
|
|
||||||
trade_type,
|
|
||||||
start_time.elapsed()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
} else if crate::common::sdk_log::sdk_log_enabled() {
|
} else if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(
|
eprintln!(" [helius] {} submission failed: {:?}", trade_type, response_text);
|
||||||
" [helius] {} submission failed: {:?}",
|
|
||||||
trade_type, response_text
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
@@ -159,15 +149,8 @@ impl HeliusClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(
|
println!(" signature: {:?}", signature);
|
||||||
" signature: {:?}",
|
println!(" [helius] {} confirmed: {:?}", trade_type, start_time.elapsed());
|
||||||
signature
|
|
||||||
);
|
|
||||||
println!(
|
|
||||||
" [helius] {} confirmed: {:?}",
|
|
||||||
trade_type,
|
|
||||||
start_time.elapsed()
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
@@ -191,8 +174,7 @@ impl SwqosClientTrait for HeliusClient {
|
|||||||
wait_confirmation: bool,
|
wait_confirmation: bool,
|
||||||
) -> Result<()> {
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation)
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
.await?;
|
|
||||||
}
|
}
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
+37
-16
@@ -1,5 +1,7 @@
|
|||||||
|
use crate::swqos::common::{
|
||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode, FormatBase64VersionedTransaction};
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
FormatBase64VersionedTransaction,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -7,14 +9,13 @@ use std::{sync::Arc, time::Instant};
|
|||||||
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::JITO_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::JITO_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
pub struct JitoClient {
|
pub struct JitoClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
pub auth_token: String,
|
pub auth_token: String,
|
||||||
@@ -24,11 +25,21 @@ pub struct JitoClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for JitoClient {
|
impl SwqosClientTrait for JitoClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions_impl(trade_type, transactions, wait_confirmation).await
|
self.send_transactions_impl(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -52,9 +63,15 @@ impl JitoClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction_impl(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"id": 1,
|
"id": 1,
|
||||||
@@ -76,8 +93,7 @@ impl JitoClient {
|
|||||||
let response = if self.auth_token.is_empty() {
|
let response = if self.auth_token.is_empty() {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint)
|
||||||
} else {
|
} else {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint).header("x-jito-auth", &self.auth_token)
|
||||||
.header("x-jito-auth", &self.auth_token)
|
|
||||||
};
|
};
|
||||||
let response_text = response
|
let response_text = response
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
@@ -104,7 +120,7 @@ impl JitoClient {
|
|||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [jito] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" [jito] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -114,9 +130,15 @@ impl JitoClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions_impl(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, _wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions_impl(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
_wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let txs_base64 = transactions.iter().map(|tx| tx.to_base64_string()).collect::<Vec<String>>();
|
let txs_base64 =
|
||||||
|
transactions.iter().map(|tx| tx.to_base64_string()).collect::<Vec<String>>();
|
||||||
let body = serde_json::json!({
|
let body = serde_json::json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
"method": "sendBundle",
|
"method": "sendBundle",
|
||||||
@@ -135,8 +157,7 @@ impl JitoClient {
|
|||||||
let response = if self.auth_token.is_empty() {
|
let response = if self.auth_token.is_empty() {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint)
|
||||||
} else {
|
} else {
|
||||||
self.http_client.post(&endpoint)
|
self.http_client.post(&endpoint).header("x-jito-auth", &self.auth_token)
|
||||||
.header("x-jito-auth", &self.auth_token)
|
|
||||||
};
|
};
|
||||||
let response_text = response
|
let response_text = response
|
||||||
.body(body.to_string())
|
.body(body.to_string())
|
||||||
|
|||||||
+44
-12
@@ -1,4 +1,6 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -6,10 +8,10 @@ use std::{sync::Arc, time::Instant};
|
|||||||
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::LIGHTSPEED_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::LIGHTSPEED_TIP_ACCOUNTS};
|
||||||
|
|
||||||
@@ -23,16 +25,29 @@ pub struct LightspeedClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for LightspeedClient {
|
impl SwqosClientTrait for LightspeedClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *LIGHTSPEED_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| LIGHTSPEED_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *LIGHTSPEED_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| LIGHTSPEED_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -50,9 +65,15 @@ impl LightspeedClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Lightspeed uses standard Solana JSON-RPC format for sendTransaction
|
// Lightspeed uses standard Solana JSON-RPC format for sendTransaction
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -70,7 +91,9 @@ impl LightspeedClient {
|
|||||||
]
|
]
|
||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.send()
|
.send()
|
||||||
@@ -93,9 +116,13 @@ impl LightspeedClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [lightspeed] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [lightspeed] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -105,7 +132,12 @@ impl LightspeedClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+98
-161
@@ -1,22 +1,22 @@
|
|||||||
|
pub mod astralane;
|
||||||
pub mod astralane_quic;
|
pub mod astralane_quic;
|
||||||
pub mod common;
|
pub mod blockrazor;
|
||||||
pub mod serialization;
|
|
||||||
pub mod solana_rpc;
|
|
||||||
pub mod jito;
|
|
||||||
pub mod nextblock;
|
|
||||||
pub mod zeroslot;
|
|
||||||
pub mod temporal;
|
|
||||||
pub mod bloxroute;
|
pub mod bloxroute;
|
||||||
|
pub mod common;
|
||||||
|
pub mod flashblock;
|
||||||
|
pub mod helius;
|
||||||
|
pub mod jito;
|
||||||
|
pub mod lightspeed;
|
||||||
|
pub mod nextblock;
|
||||||
pub mod node1;
|
pub mod node1;
|
||||||
pub mod node1_quic;
|
pub mod node1_quic;
|
||||||
pub mod flashblock;
|
pub mod serialization;
|
||||||
pub mod blockrazor;
|
pub mod solana_rpc;
|
||||||
pub mod astralane;
|
|
||||||
pub mod stellium;
|
|
||||||
pub mod lightspeed;
|
|
||||||
pub mod soyas;
|
pub mod soyas;
|
||||||
pub mod speedlanding;
|
pub mod speedlanding;
|
||||||
pub mod helius;
|
pub mod stellium;
|
||||||
|
pub mod temporal;
|
||||||
|
pub mod zeroslot;
|
||||||
|
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
@@ -29,55 +29,25 @@ use anyhow::Result;
|
|||||||
use crate::{
|
use crate::{
|
||||||
common::SolanaRpcClient,
|
common::SolanaRpcClient,
|
||||||
constants::swqos::{
|
constants::swqos::{
|
||||||
SWQOS_ENDPOINTS_BLOX,
|
SWQOS_ENDPOINTS_ASTRALANE, SWQOS_ENDPOINTS_ASTRALANE_QUIC, SWQOS_ENDPOINTS_BLOCKRAZOR,
|
||||||
SWQOS_ENDPOINTS_JITO,
|
SWQOS_ENDPOINTS_BLOX, SWQOS_ENDPOINTS_FLASHBLOCK, SWQOS_ENDPOINTS_HELIUS,
|
||||||
SWQOS_ENDPOINTS_NEXTBLOCK,
|
SWQOS_ENDPOINTS_JITO, SWQOS_ENDPOINTS_NEXTBLOCK, SWQOS_ENDPOINTS_NODE1,
|
||||||
SWQOS_ENDPOINTS_TEMPORAL,
|
SWQOS_ENDPOINTS_NODE1_QUIC, SWQOS_ENDPOINTS_SOYAS, SWQOS_ENDPOINTS_SPEEDLANDING,
|
||||||
SWQOS_ENDPOINTS_ZERO_SLOT,
|
SWQOS_ENDPOINTS_STELLIUM, SWQOS_ENDPOINTS_TEMPORAL, SWQOS_ENDPOINTS_ZERO_SLOT,
|
||||||
SWQOS_ENDPOINTS_NODE1,
|
SWQOS_MIN_TIP_ASTRALANE, SWQOS_MIN_TIP_BLOCKRAZOR, SWQOS_MIN_TIP_BLOXROUTE,
|
||||||
SWQOS_ENDPOINTS_NODE1_QUIC,
|
SWQOS_MIN_TIP_DEFAULT, SWQOS_MIN_TIP_FLASHBLOCK, SWQOS_MIN_TIP_HELIUS, SWQOS_MIN_TIP_JITO,
|
||||||
SWQOS_ENDPOINTS_FLASHBLOCK,
|
SWQOS_MIN_TIP_LIGHTSPEED, SWQOS_MIN_TIP_NEXTBLOCK, SWQOS_MIN_TIP_NODE1,
|
||||||
SWQOS_ENDPOINTS_BLOCKRAZOR,
|
SWQOS_MIN_TIP_SOYAS, SWQOS_MIN_TIP_SPEEDLANDING, SWQOS_MIN_TIP_STELLIUM,
|
||||||
SWQOS_ENDPOINTS_ASTRALANE,
|
SWQOS_MIN_TIP_TEMPORAL, SWQOS_MIN_TIP_ZERO_SLOT,
|
||||||
SWQOS_ENDPOINTS_ASTRALANE_QUIC,
|
|
||||||
SWQOS_ENDPOINTS_STELLIUM,
|
|
||||||
SWQOS_ENDPOINTS_SOYAS,
|
|
||||||
SWQOS_ENDPOINTS_SPEEDLANDING,
|
|
||||||
SWQOS_ENDPOINTS_HELIUS,
|
|
||||||
SWQOS_MIN_TIP_DEFAULT,
|
|
||||||
SWQOS_MIN_TIP_JITO,
|
|
||||||
SWQOS_MIN_TIP_NEXTBLOCK,
|
|
||||||
SWQOS_MIN_TIP_ZERO_SLOT,
|
|
||||||
SWQOS_MIN_TIP_TEMPORAL,
|
|
||||||
SWQOS_MIN_TIP_BLOXROUTE,
|
|
||||||
SWQOS_MIN_TIP_NODE1,
|
|
||||||
SWQOS_MIN_TIP_FLASHBLOCK,
|
|
||||||
SWQOS_MIN_TIP_BLOCKRAZOR,
|
|
||||||
SWQOS_MIN_TIP_ASTRALANE,
|
|
||||||
SWQOS_MIN_TIP_STELLIUM,
|
|
||||||
SWQOS_MIN_TIP_LIGHTSPEED,
|
|
||||||
SWQOS_MIN_TIP_SOYAS,
|
|
||||||
SWQOS_MIN_TIP_SPEEDLANDING,
|
|
||||||
SWQOS_MIN_TIP_HELIUS,
|
|
||||||
},
|
},
|
||||||
swqos::{
|
swqos::{
|
||||||
bloxroute::BloxrouteClient,
|
astralane::AstralaneClient, blockrazor::BlockRazorClient, bloxroute::BloxrouteClient,
|
||||||
jito::JitoClient,
|
flashblock::FlashBlockClient, helius::HeliusClient, jito::JitoClient,
|
||||||
nextblock::NextBlockClient,
|
lightspeed::LightspeedClient, nextblock::NextBlockClient, node1::Node1Client,
|
||||||
solana_rpc::SolRpcClient,
|
node1_quic::Node1QuicClient, solana_rpc::SolRpcClient, soyas::SoyasClient,
|
||||||
temporal::TemporalClient,
|
speedlanding::SpeedlandingClient, stellium::StelliumClient, temporal::TemporalClient,
|
||||||
zeroslot::ZeroSlotClient,
|
zeroslot::ZeroSlotClient,
|
||||||
node1::Node1Client,
|
},
|
||||||
node1_quic::Node1QuicClient,
|
|
||||||
flashblock::FlashBlockClient,
|
|
||||||
blockrazor::BlockRazorClient,
|
|
||||||
astralane::AstralaneClient,
|
|
||||||
stellium::StelliumClient,
|
|
||||||
lightspeed::LightspeedClient,
|
|
||||||
soyas::SoyasClient,
|
|
||||||
speedlanding::SpeedlandingClient,
|
|
||||||
helius::HeliusClient,
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
lazy_static::lazy_static! {
|
lazy_static::lazy_static! {
|
||||||
@@ -90,7 +60,7 @@ lazy_static::lazy_static! {
|
|||||||
/// Providers added here will be disabled even if configured by user
|
/// Providers added here will be disabled even if configured by user
|
||||||
/// To enable a provider, remove it from this list
|
/// To enable a provider, remove it from this list
|
||||||
pub const SWQOS_BLACKLIST: &[SwqosType] = &[
|
pub const SWQOS_BLACKLIST: &[SwqosType] = &[
|
||||||
SwqosType::NextBlock, // NextBlock is disabled by default
|
SwqosType::NextBlock, // NextBlock is disabled by default
|
||||||
];
|
];
|
||||||
|
|
||||||
/// SWQOS 提交通道:HTTP 或 QUIC(低延迟)。部分提供商(如 Astralane)支持 QUIC。
|
/// SWQOS 提交通道:HTTP 或 QUIC(低延迟)。部分提供商(如 Astralane)支持 QUIC。
|
||||||
@@ -166,8 +136,18 @@ pub type SwqosClient = dyn SwqosClientTrait + Send + Sync + 'static;
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
pub trait SwqosClientTrait {
|
pub trait SwqosClientTrait {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()>;
|
async fn send_transaction(
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()>;
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()>;
|
||||||
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()>;
|
||||||
fn get_tip_account(&self) -> Result<String>;
|
fn get_tip_account(&self) -> Result<String>;
|
||||||
fn get_swqos_type(&self) -> SwqosType;
|
fn get_swqos_type(&self) -> SwqosType;
|
||||||
/// Minimum tip in SOL required by this provider. Helius returns lower value when swqos_only is true.
|
/// Minimum tip in SOL required by this provider. Helius returns lower value when swqos_only is true.
|
||||||
@@ -243,7 +223,7 @@ pub enum SwqosConfig {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl SwqosConfig {
|
impl SwqosConfig {
|
||||||
pub fn swqos_type(&self) -> SwqosType{
|
pub fn swqos_type(&self) -> SwqosType {
|
||||||
match self {
|
match self {
|
||||||
SwqosConfig::Default(_) => SwqosType::Default,
|
SwqosConfig::Default(_) => SwqosType::Default,
|
||||||
SwqosConfig::Jito(_, _, _) => SwqosType::Jito,
|
SwqosConfig::Jito(_, _, _) => SwqosType::Jito,
|
||||||
@@ -292,164 +272,121 @@ impl SwqosConfig {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn get_swqos_client(rpc_url: String, commitment: CommitmentConfig, swqos_config: SwqosConfig) -> Result<Arc<SwqosClient>> {
|
pub async fn get_swqos_client(
|
||||||
|
rpc_url: String,
|
||||||
|
commitment: CommitmentConfig,
|
||||||
|
swqos_config: SwqosConfig,
|
||||||
|
) -> Result<Arc<SwqosClient>> {
|
||||||
match swqos_config {
|
match swqos_config {
|
||||||
SwqosConfig::Jito(auth_token, region, url) => {
|
SwqosConfig::Jito(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Jito, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Jito, region, url);
|
||||||
let jito_client = JitoClient::new(
|
let jito_client = JitoClient::new(rpc_url.clone(), endpoint, auth_token);
|
||||||
rpc_url.clone(),
|
|
||||||
endpoint,
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(jito_client))
|
Ok(Arc::new(jito_client))
|
||||||
}
|
}
|
||||||
SwqosConfig::NextBlock(auth_token, region, url) => {
|
SwqosConfig::NextBlock(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::NextBlock, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::NextBlock, region, url);
|
||||||
let nextblock_client = NextBlockClient::new(
|
let nextblock_client =
|
||||||
rpc_url.clone(),
|
NextBlockClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(nextblock_client))
|
Ok(Arc::new(nextblock_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::ZeroSlot(auth_token, region, url) => {
|
SwqosConfig::ZeroSlot(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::ZeroSlot, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::ZeroSlot, region, url);
|
||||||
let zeroslot_client = ZeroSlotClient::new(
|
let zeroslot_client =
|
||||||
rpc_url.clone(),
|
ZeroSlotClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(zeroslot_client))
|
Ok(Arc::new(zeroslot_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Temporal(auth_token, region, url) => {
|
SwqosConfig::Temporal(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Temporal, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Temporal, region, url);
|
||||||
let temporal_client = TemporalClient::new(
|
let temporal_client =
|
||||||
rpc_url.clone(),
|
TemporalClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(temporal_client))
|
Ok(Arc::new(temporal_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Bloxroute(auth_token, region, url) => {
|
SwqosConfig::Bloxroute(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Bloxroute, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Bloxroute, region, url);
|
||||||
let bloxroute_client = BloxrouteClient::new(
|
let bloxroute_client =
|
||||||
rpc_url.clone(),
|
BloxrouteClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(bloxroute_client))
|
Ok(Arc::new(bloxroute_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Node1(auth_token, region, url, transport) => {
|
SwqosConfig::Node1(auth_token, region, url, transport) => {
|
||||||
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||||
if use_quic {
|
if use_quic {
|
||||||
let quic_endpoint = url
|
let quic_endpoint = url
|
||||||
.unwrap_or_else(|| SWQOS_ENDPOINTS_NODE1_QUIC[region as usize].to_string());
|
.unwrap_or_else(|| SWQOS_ENDPOINTS_NODE1_QUIC[region as usize].to_string());
|
||||||
let node1_quic = Node1QuicClient::connect(
|
let node1_quic =
|
||||||
&quic_endpoint,
|
Node1QuicClient::connect(&quic_endpoint, &auth_token, rpc_url.clone())
|
||||||
&auth_token,
|
.await?;
|
||||||
rpc_url.clone(),
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
Ok(Arc::new(node1_quic))
|
Ok(Arc::new(node1_quic))
|
||||||
} else {
|
} else {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Node1, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Node1, region, url);
|
||||||
let node1_client = Node1Client::new(
|
let node1_client =
|
||||||
rpc_url.clone(),
|
Node1Client::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token,
|
|
||||||
);
|
|
||||||
Ok(Arc::new(node1_client))
|
Ok(Arc::new(node1_client))
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
SwqosConfig::FlashBlock(auth_token, region, url) => {
|
SwqosConfig::FlashBlock(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::FlashBlock, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::FlashBlock, region, url);
|
||||||
let flashblock_client = FlashBlockClient::new(
|
let flashblock_client =
|
||||||
rpc_url.clone(),
|
FlashBlockClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(flashblock_client))
|
Ok(Arc::new(flashblock_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::BlockRazor(auth_token, region, url) => {
|
SwqosConfig::BlockRazor(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
||||||
let blockrazor_client = BlockRazorClient::new(
|
let blockrazor_client =
|
||||||
rpc_url.clone(),
|
BlockRazorClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(blockrazor_client))
|
Ok(Arc::new(blockrazor_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Astralane(auth_token, region, url, transport) => {
|
SwqosConfig::Astralane(auth_token, region, url, transport) => {
|
||||||
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||||
if use_quic {
|
if use_quic {
|
||||||
let quic_endpoint = url
|
let quic_endpoint = url.unwrap_or_else(|| {
|
||||||
.unwrap_or_else(|| SWQOS_ENDPOINTS_ASTRALANE_QUIC[region as usize].to_string());
|
SWQOS_ENDPOINTS_ASTRALANE_QUIC[region as usize].to_string()
|
||||||
|
});
|
||||||
let astralane_client =
|
let astralane_client =
|
||||||
AstralaneClient::new_quic(rpc_url.clone(), &quic_endpoint, auth_token).await?;
|
AstralaneClient::new_quic(rpc_url.clone(), &quic_endpoint, auth_token)
|
||||||
|
.await?;
|
||||||
Ok(Arc::new(astralane_client))
|
Ok(Arc::new(astralane_client))
|
||||||
} else {
|
} else {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Astralane, region, url);
|
||||||
let astralane_client = AstralaneClient::new(
|
let astralane_client =
|
||||||
rpc_url.clone(),
|
AstralaneClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token,
|
|
||||||
);
|
|
||||||
Ok(Arc::new(astralane_client))
|
Ok(Arc::new(astralane_client))
|
||||||
}
|
}
|
||||||
},
|
}
|
||||||
SwqosConfig::Stellium(auth_token, region, url) => {
|
SwqosConfig::Stellium(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Stellium, region, url);
|
||||||
let stellium_client = StelliumClient::new(
|
let stellium_client =
|
||||||
rpc_url.clone(),
|
StelliumClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(stellium_client))
|
Ok(Arc::new(stellium_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Lightspeed(auth_token, region, url) => {
|
SwqosConfig::Lightspeed(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Lightspeed, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Lightspeed, region, url);
|
||||||
let lightspeed_client = LightspeedClient::new(
|
let lightspeed_client =
|
||||||
rpc_url.clone(),
|
LightspeedClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
);
|
|
||||||
Ok(Arc::new(lightspeed_client))
|
Ok(Arc::new(lightspeed_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Soyas(auth_token, region, url) => {
|
SwqosConfig::Soyas(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Soyas, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Soyas, region, url);
|
||||||
let soyas_client = SoyasClient::new(
|
let soyas_client =
|
||||||
rpc_url.clone(),
|
SoyasClient::new(rpc_url.clone(), endpoint.to_string(), auth_token).await?;
|
||||||
endpoint.to_string(),
|
|
||||||
auth_token
|
|
||||||
).await?;
|
|
||||||
Ok(Arc::new(soyas_client))
|
Ok(Arc::new(soyas_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Speedlanding(auth_token, region, url) => {
|
SwqosConfig::Speedlanding(auth_token, region, url) => {
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Speedlanding, region, url);
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Speedlanding, region, url);
|
||||||
let speedlanding_client = SpeedlandingClient::new(
|
let speedlanding_client =
|
||||||
rpc_url.clone(),
|
SpeedlandingClient::new(rpc_url.clone(), endpoint.to_string(), auth_token)
|
||||||
endpoint.to_string(),
|
.await?;
|
||||||
auth_token
|
|
||||||
).await?;
|
|
||||||
Ok(Arc::new(speedlanding_client))
|
Ok(Arc::new(speedlanding_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Helius(api_key, region, url, swqos_only) => {
|
SwqosConfig::Helius(api_key, region, url, swqos_only) => {
|
||||||
let swqos_only = swqos_only.unwrap_or(false);
|
let swqos_only = swqos_only.unwrap_or(false);
|
||||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::Helius, region, url.clone());
|
let endpoint = SwqosConfig::get_endpoint(SwqosType::Helius, region, url.clone());
|
||||||
let api_key_opt = if api_key.is_empty() { None } else { Some(api_key.clone()) };
|
let api_key_opt = if api_key.is_empty() { None } else { Some(api_key.clone()) };
|
||||||
let helius_client = HeliusClient::new(
|
let helius_client =
|
||||||
rpc_url.clone(),
|
HeliusClient::new(rpc_url.clone(), endpoint, api_key_opt, swqos_only);
|
||||||
endpoint,
|
|
||||||
api_key_opt,
|
|
||||||
swqos_only,
|
|
||||||
);
|
|
||||||
Ok(Arc::new(helius_client))
|
Ok(Arc::new(helius_client))
|
||||||
},
|
}
|
||||||
SwqosConfig::Default(endpoint) => {
|
SwqosConfig::Default(endpoint) => {
|
||||||
let rpc = SolanaRpcClient::new_with_commitment(
|
let rpc = SolanaRpcClient::new_with_commitment(endpoint, commitment);
|
||||||
endpoint,
|
|
||||||
commitment
|
|
||||||
);
|
|
||||||
let rpc_client = SolRpcClient::new(Arc::new(rpc));
|
let rpc_client = SolRpcClient::new(Arc::new(rpc));
|
||||||
Ok(Arc::new(rpc_client))
|
Ok(Arc::new(rpc_client))
|
||||||
}
|
}
|
||||||
|
|||||||
+44
-12
@@ -1,4 +1,6 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -6,10 +8,10 @@ use std::{sync::Arc, time::Instant};
|
|||||||
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NEXTBLOCK_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NEXTBLOCK_TIP_ACCOUNTS};
|
||||||
|
|
||||||
@@ -23,16 +25,29 @@ pub struct NextBlockClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for NextBlockClient {
|
impl SwqosClientTrait for NextBlockClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *NEXTBLOCK_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NEXTBLOCK_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NEXTBLOCK_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NEXTBLOCK_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -54,9 +69,15 @@ impl NextBlockClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"transaction": {
|
"transaction": {
|
||||||
@@ -65,7 +86,9 @@ impl NextBlockClient {
|
|||||||
"frontRunningProtection": false
|
"frontRunningProtection": false
|
||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Authorization", &self.auth_token)
|
.header("Authorization", &self.auth_token)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
@@ -89,9 +112,13 @@ impl NextBlockClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nextblock] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [nextblock] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -101,7 +128,12 @@ impl NextBlockClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+55
-20
@@ -1,21 +1,23 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NODE1_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NODE1_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct Node1Client {
|
pub struct Node1Client {
|
||||||
@@ -29,16 +31,29 @@ pub struct Node1Client {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for Node1Client {
|
impl SwqosClientTrait for Node1Client {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *NODE1_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NODE1_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NODE1_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NODE1_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -90,7 +105,8 @@ impl Node1Client {
|
|||||||
if stop_ping.load(Ordering::Relaxed) {
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||||
|
{
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!("Node1 ping request failed: {}", e);
|
eprintln!("Node1 ping request failed: {}", e);
|
||||||
}
|
}
|
||||||
@@ -109,7 +125,11 @@ impl Node1Client {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request to /ping endpoint
|
/// Send ping request to /ping endpoint
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, _auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
_auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
// Build ping URL
|
// Build ping URL
|
||||||
let ping_url = if endpoint.ends_with('/') {
|
let ping_url = if endpoint.ends_with('/') {
|
||||||
format!("{}ping", endpoint)
|
format!("{}ping", endpoint)
|
||||||
@@ -118,10 +138,8 @@ impl Node1Client {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
||||||
let response = http_client.get(&ping_url)
|
let response =
|
||||||
.timeout(Duration::from_millis(1500))
|
http_client.get(&ping_url).timeout(Duration::from_millis(1500)).send().await?;
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
let _ = response.bytes().await;
|
let _ = response.bytes().await;
|
||||||
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
@@ -130,9 +148,15 @@ impl Node1Client {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -145,7 +169,9 @@ impl Node1Client {
|
|||||||
}))?;
|
}))?;
|
||||||
|
|
||||||
// Node1 uses api-key header instead of URL parameter
|
// Node1 uses api-key header instead of URL parameter
|
||||||
let response_text = self.http_client.post(&self.endpoint)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&self.endpoint)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("api-key", &self.auth_token)
|
.header("api-key", &self.auth_token)
|
||||||
@@ -173,10 +199,14 @@ impl Node1Client {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [node1] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [node1] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -186,7 +216,12 @@ impl Node1Client {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+28
-38
@@ -10,8 +10,8 @@ use quinn::{ClientConfig, Connection, Endpoint, IdleTimeout, RecvStream, Transpo
|
|||||||
use std::net::ToSocketAddrs;
|
use std::net::ToSocketAddrs;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
use std::time::Duration;
|
use std::time::Duration;
|
||||||
use tokio::time::timeout;
|
|
||||||
use tokio::sync::Mutex;
|
use tokio::sync::Mutex;
|
||||||
|
use tokio::time::timeout;
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
use crate::common::SolanaRpcClient;
|
use crate::common::SolanaRpcClient;
|
||||||
@@ -41,44 +41,34 @@ pub struct Node1QuicClient {
|
|||||||
|
|
||||||
impl Node1QuicClient {
|
impl Node1QuicClient {
|
||||||
/// Connect and authenticate. Reuse the returned client for all subsequent sends.
|
/// Connect and authenticate. Reuse the returned client for all subsequent sends.
|
||||||
pub async fn connect(
|
pub async fn connect(server_addr: &str, api_key: &str, rpc_url: String) -> Result<Self> {
|
||||||
server_addr: &str,
|
|
||||||
api_key: &str,
|
|
||||||
rpc_url: String,
|
|
||||||
) -> Result<Self> {
|
|
||||||
let socket_addr = server_addr
|
let socket_addr = server_addr
|
||||||
.to_socket_addrs()
|
.to_socket_addrs()
|
||||||
.context("resolve Node1 QUIC server address")?
|
.context("resolve Node1 QUIC server address")?
|
||||||
.next()
|
.next()
|
||||||
.context("no socket address for Node1 QUIC")?;
|
.context("no socket address for Node1 QUIC")?;
|
||||||
|
|
||||||
let api_key_uuid = Uuid::parse_str(api_key).context("Node1 API key must be a valid UUID")?;
|
let api_key_uuid =
|
||||||
|
Uuid::parse_str(api_key).context("Node1 API key must be a valid UUID")?;
|
||||||
let api_key_bytes: [u8; 16] = *api_key_uuid.as_bytes();
|
let api_key_bytes: [u8; 16] = *api_key_uuid.as_bytes();
|
||||||
|
|
||||||
let server_name = server_addr
|
let server_name = server_addr.split(':').next().unwrap_or(server_addr);
|
||||||
.split(':')
|
|
||||||
.next()
|
|
||||||
.unwrap_or(server_addr);
|
|
||||||
|
|
||||||
let client_config = Self::build_client_config()?;
|
let client_config = Self::build_client_config()?;
|
||||||
let mut endpoint = Endpoint::client("0.0.0.0:0".parse()?)
|
let mut endpoint =
|
||||||
.context("create QUIC endpoint")?;
|
Endpoint::client("0.0.0.0:0".parse()?).context("create QUIC endpoint")?;
|
||||||
endpoint.set_default_client_config(client_config);
|
endpoint.set_default_client_config(client_config);
|
||||||
|
|
||||||
let connecting = endpoint
|
let connecting =
|
||||||
.connect(socket_addr, server_name)
|
endpoint.connect(socket_addr, server_name).context("Node1 QUIC connect failed")?;
|
||||||
.context("Node1 QUIC connect failed")?;
|
|
||||||
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
.await
|
.await
|
||||||
.context("Node1 QUIC connect timeout")?
|
.context("Node1 QUIC connect timeout")?
|
||||||
.context("Node1 QUIC handshake failed")?;
|
.context("Node1 QUIC handshake failed")?;
|
||||||
|
|
||||||
timeout(
|
timeout(AUTH_TIMEOUT, Self::authenticate(&connection, &api_key_bytes))
|
||||||
AUTH_TIMEOUT,
|
.await
|
||||||
Self::authenticate(&connection, &api_key_bytes),
|
.context("Node1 QUIC auth timeout")??;
|
||||||
)
|
|
||||||
.await
|
|
||||||
.context("Node1 QUIC auth timeout")??;
|
|
||||||
|
|
||||||
Ok(Self {
|
Ok(Self {
|
||||||
endpoint,
|
endpoint,
|
||||||
@@ -96,8 +86,7 @@ impl Node1QuicClient {
|
|||||||
.with_custom_certificate_verifier(Arc::new(SkipServerVerification))
|
.with_custom_certificate_verifier(Arc::new(SkipServerVerification))
|
||||||
.with_no_client_auth();
|
.with_no_client_auth();
|
||||||
|
|
||||||
let client_crypto = QuicClientConfig::try_from(crypto)
|
let client_crypto = QuicClientConfig::try_from(crypto).context("build QUIC TLS config")?;
|
||||||
.context("build QUIC TLS config")?;
|
|
||||||
let mut client_config = ClientConfig::new(Arc::new(client_crypto));
|
let mut client_config = ClientConfig::new(Arc::new(client_crypto));
|
||||||
|
|
||||||
let mut transport = TransportConfig::default();
|
let mut transport = TransportConfig::default();
|
||||||
@@ -140,12 +129,9 @@ impl Node1QuicClient {
|
|||||||
.context("Node1 QUIC reconnect timeout")?
|
.context("Node1 QUIC reconnect timeout")?
|
||||||
.context("Node1 QUIC re-handshake failed")?;
|
.context("Node1 QUIC re-handshake failed")?;
|
||||||
|
|
||||||
timeout(
|
timeout(AUTH_TIMEOUT, Self::authenticate(&connection, &self.api_key_uuid))
|
||||||
AUTH_TIMEOUT,
|
.await
|
||||||
Self::authenticate(&connection, &self.api_key_uuid),
|
.context("Node1 QUIC re-auth timeout")??;
|
||||||
)
|
|
||||||
.await
|
|
||||||
.context("Node1 QUIC re-auth timeout")??;
|
|
||||||
|
|
||||||
let mut g = self.connection.lock().await;
|
let mut g = self.connection.lock().await;
|
||||||
*g = connection.clone();
|
*g = connection.clone();
|
||||||
@@ -201,16 +187,16 @@ impl SwqosClientTrait for Node1QuicClient {
|
|||||||
let signature = transaction.signatures.first().copied().unwrap_or_default();
|
let signature = transaction.signatures.first().copied().unwrap_or_default();
|
||||||
let tx_bytes = bincode::serialize(transaction).context("Node1 QUIC: bincode serialize")?;
|
let tx_bytes = bincode::serialize(transaction).context("Node1 QUIC: bincode serialize")?;
|
||||||
|
|
||||||
let (status, msg) = timeout(
|
let (status, msg) = timeout(SEND_TIMEOUT, self.send_transaction_bytes(&tx_bytes))
|
||||||
SEND_TIMEOUT,
|
.await
|
||||||
self.send_transaction_bytes(&tx_bytes),
|
.context("Node1 QUIC send timeout")??;
|
||||||
)
|
|
||||||
.await
|
|
||||||
.context("Node1 QUIC send timeout")??;
|
|
||||||
|
|
||||||
if status != 200 {
|
if status != 200 {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [node1-quic] {} submit failed: status={} msg={}", trade_type, status, msg);
|
eprintln!(
|
||||||
|
" [node1-quic] {} submit failed: status={} msg={}",
|
||||||
|
trade_type, status, msg
|
||||||
|
);
|
||||||
}
|
}
|
||||||
anyhow::bail!("Node1 QUIC submit failed: status={} msg={}", status, msg);
|
anyhow::bail!("Node1 QUIC submit failed: status={} msg={}", status, msg);
|
||||||
}
|
}
|
||||||
@@ -229,7 +215,11 @@ impl SwqosClientTrait for Node1QuicClient {
|
|||||||
}
|
}
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
eprintln!(" [node1-quic] {} confirmation failed: {:?}", trade_type, start.elapsed());
|
eprintln!(
|
||||||
|
" [node1-quic] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
Err(e)
|
Err(e)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -119,9 +119,11 @@ impl SpeedlandingClient {
|
|||||||
let _guard = self.reconnect.lock().await;
|
let _guard = self.reconnect.lock().await;
|
||||||
let current = self.connection.load_full();
|
let current = self.connection.load_full();
|
||||||
if current.close_reason().is_some() {
|
if current.close_reason().is_some() {
|
||||||
let connecting = self
|
let connecting = self.endpoint.connect_with(
|
||||||
.endpoint
|
self.client_config.clone(),
|
||||||
.connect_with(self.client_config.clone(), self.addr, self.server_name.as_str())?;
|
self.addr,
|
||||||
|
self.server_name.as_str(),
|
||||||
|
)?;
|
||||||
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
let connection = timeout(CONNECT_TIMEOUT, connecting)
|
||||||
.await
|
.await
|
||||||
.context("Speedlanding QUIC reconnect timeout")?
|
.context("Speedlanding QUIC reconnect timeout")?
|
||||||
@@ -151,7 +153,8 @@ impl SwqosClientTrait for SpeedlandingClient {
|
|||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (buf_guard, signature) = serialize_transaction_bincode_sync(transaction)?;
|
let (buf_guard, signature) = serialize_transaction_bincode_sync(transaction)?;
|
||||||
let connection = self.ensure_connected().await?;
|
let connection = self.ensure_connected().await?;
|
||||||
let mut send_result = timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
let mut send_result =
|
||||||
|
timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||||
let need_retry = match &send_result {
|
let need_retry = match &send_result {
|
||||||
Ok(Ok(())) => false,
|
Ok(Ok(())) => false,
|
||||||
Ok(Err(_)) | Err(_) => true,
|
Ok(Err(_)) | Err(_) => true,
|
||||||
@@ -161,16 +164,20 @@ impl SwqosClientTrait for SpeedlandingClient {
|
|||||||
eprintln!(" [speedlanding] {} send failed or timeout, reconnecting", trade_type);
|
eprintln!(" [speedlanding] {} send failed or timeout, reconnecting", trade_type);
|
||||||
}
|
}
|
||||||
let connection = self.ensure_connected().await?;
|
let connection = self.ensure_connected().await?;
|
||||||
send_result = timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
send_result =
|
||||||
|
timeout(SEND_TIMEOUT, Self::try_send_bytes(&connection, &*buf_guard)).await;
|
||||||
}
|
}
|
||||||
send_result
|
send_result.context("Speedlanding QUIC send timeout")??;
|
||||||
.context("Speedlanding QUIC send timeout")??;
|
|
||||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [speedlanding] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [speedlanding] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
}
|
}
|
||||||
|
|||||||
+49
-16
@@ -1,21 +1,22 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::STELLIUM_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::STELLIUM_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct StelliumClient {
|
pub struct StelliumClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -27,16 +28,29 @@ pub struct StelliumClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for StelliumClient {
|
impl SwqosClientTrait for StelliumClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *STELLIUM_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| STELLIUM_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *STELLIUM_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| STELLIUM_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -79,7 +93,9 @@ impl StelliumClient {
|
|||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
// Immediate first ping to warm connection and reduce first-submit cold start latency
|
// Immediate first ping to warm connection and reduce first-submit cold start latency
|
||||||
let url = format!("{}/{}", endpoint, auth_token);
|
let url = format!("{}/{}", endpoint, auth_token);
|
||||||
if let Ok(resp) = http_client.get(&url).timeout(Duration::from_millis(1500)).send().await {
|
if let Ok(resp) =
|
||||||
|
http_client.get(&url).timeout(Duration::from_millis(1500)).send().await
|
||||||
|
{
|
||||||
let status = resp.status();
|
let status = resp.status();
|
||||||
let _ = resp.bytes().await;
|
let _ = resp.bytes().await;
|
||||||
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
if !status.is_success() && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
@@ -111,9 +127,15 @@ impl StelliumClient {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Stellium uses standard Solana sendTransaction format
|
// Stellium uses standard Solana sendTransaction format
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -130,7 +152,9 @@ impl StelliumClient {
|
|||||||
let url = format!("{}/{}", self.endpoint, self.auth_token);
|
let url = format!("{}/{}", self.endpoint, self.auth_token);
|
||||||
|
|
||||||
// Send request to Stellium
|
// Send request to Stellium
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.header("Connection", "keep-alive")
|
.header("Connection", "keep-alive")
|
||||||
@@ -159,10 +183,14 @@ impl StelliumClient {
|
|||||||
Err(e) => {
|
Err(e) => {
|
||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [Stellium] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [Stellium] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
}
|
}
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
if wait_confirmation && crate::common::sdk_log::sdk_log_enabled() {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -172,7 +200,12 @@ impl StelliumClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+62
-26
@@ -1,27 +1,29 @@
|
|||||||
|
use crate::swqos::common::{
|
||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use std::{sync::Arc, time::Instant};
|
use sha2::{Digest, Sha256};
|
||||||
use std::time::Duration;
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
use sha2::{Sha256, Digest};
|
use std::time::Duration;
|
||||||
|
use std::{sync::Arc, time::Instant};
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::NOZOMI_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::NOZOMI_TIP_ACCOUNTS};
|
||||||
|
|
||||||
use tokio::task::JoinHandle;
|
|
||||||
use std::sync::atomic::{AtomicBool, Ordering};
|
use std::sync::atomic::{AtomicBool, Ordering};
|
||||||
|
use tokio::task::JoinHandle;
|
||||||
|
|
||||||
const SPECIAL_API_KEY_PREFIX: &str = "298b5025";
|
const SPECIAL_API_KEY_PREFIX: &str = "298b5025";
|
||||||
const SPECIAL_API_KEY_SUFFIX: &str = "a055323";
|
const SPECIAL_API_KEY_SUFFIX: &str = "a055323";
|
||||||
|
|
||||||
const SPECIAL_API_KEY_HASH: &str = "e7be933c8058aebcb4d08a6120fb4dfd2ead568d42527a3fc2b60a703f25e48d";
|
const SPECIAL_API_KEY_HASH: &str =
|
||||||
|
"e7be933c8058aebcb4d08a6120fb4dfd2ead568d42527a3fc2b60a703f25e48d";
|
||||||
const TEMPORAL_COMMUNITY_TIP_ADDRESS: &str = "mwGELGMgGGrNL1UibNCQeJHDE7qdPptWRYB6noUHmTj";
|
const TEMPORAL_COMMUNITY_TIP_ADDRESS: &str = "mwGELGMgGGrNL1UibNCQeJHDE7qdPptWRYB6noUHmTj";
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -31,7 +33,6 @@ fn fast_sha256_hex(input: &str) -> String {
|
|||||||
format!("{:x}", hasher.finalize())
|
format!("{:x}", hasher.finalize())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct TemporalClient {
|
pub struct TemporalClient {
|
||||||
pub rpc_client: Arc<SolanaRpcClient>,
|
pub rpc_client: Arc<SolanaRpcClient>,
|
||||||
@@ -44,18 +45,30 @@ pub struct TemporalClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for TemporalClient {
|
impl SwqosClientTrait for TemporalClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let api_key = &self.auth_token;
|
let api_key = &self.auth_token;
|
||||||
if api_key.len() >= SPECIAL_API_KEY_PREFIX.len() + SPECIAL_API_KEY_SUFFIX.len() {
|
if api_key.len() >= SPECIAL_API_KEY_PREFIX.len() + SPECIAL_API_KEY_SUFFIX.len() {
|
||||||
if api_key.starts_with(SPECIAL_API_KEY_PREFIX) && api_key.ends_with(SPECIAL_API_KEY_SUFFIX) {
|
if api_key.starts_with(SPECIAL_API_KEY_PREFIX)
|
||||||
|
&& api_key.ends_with(SPECIAL_API_KEY_SUFFIX)
|
||||||
|
{
|
||||||
let current_api_key_hash = fast_sha256_hex(api_key);
|
let current_api_key_hash = fast_sha256_hex(api_key);
|
||||||
|
|
||||||
if current_api_key_hash == SPECIAL_API_KEY_HASH {
|
if current_api_key_hash == SPECIAL_API_KEY_HASH {
|
||||||
@@ -64,7 +77,10 @@ impl SwqosClientTrait for TemporalClient {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
let tip_account = *NOZOMI_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| NOZOMI_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *NOZOMI_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| NOZOMI_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -114,7 +130,8 @@ impl TemporalClient {
|
|||||||
if stop_ping.load(Ordering::Relaxed) {
|
if stop_ping.load(Ordering::Relaxed) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||||
|
{
|
||||||
eprintln!("Temporal ping request failed: {}", e);
|
eprintln!("Temporal ping request failed: {}", e);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -131,7 +148,11 @@ impl TemporalClient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/// Send ping request to /ping endpoint
|
/// Send ping request to /ping endpoint
|
||||||
async fn send_ping_request(http_client: &Client, endpoint: &str, _auth_token: &str) -> Result<()> {
|
async fn send_ping_request(
|
||||||
|
http_client: &Client,
|
||||||
|
endpoint: &str,
|
||||||
|
_auth_token: &str,
|
||||||
|
) -> Result<()> {
|
||||||
// Build ping URL (no auth token required for ping endpoint)
|
// Build ping URL (no auth token required for ping endpoint)
|
||||||
let ping_url = if endpoint.ends_with('/') {
|
let ping_url = if endpoint.ends_with('/') {
|
||||||
format!("{}ping", endpoint)
|
format!("{}ping", endpoint)
|
||||||
@@ -140,10 +161,8 @@ impl TemporalClient {
|
|||||||
};
|
};
|
||||||
|
|
||||||
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
// Short timeout for ping; consume body so connection is returned to pool for reuse by submit
|
||||||
let response = http_client.get(&ping_url)
|
let response =
|
||||||
.timeout(Duration::from_millis(1500))
|
http_client.get(&ping_url).timeout(Duration::from_millis(1500)).send().await?;
|
||||||
.send()
|
|
||||||
.await?;
|
|
||||||
let status = response.status();
|
let status = response.status();
|
||||||
let _ = response.bytes().await;
|
let _ = response.bytes().await;
|
||||||
if !status.is_success() {
|
if !status.is_success() {
|
||||||
@@ -152,9 +171,15 @@ impl TemporalClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
// Build request body according to Nozomi documentation requirements
|
// Build request body according to Nozomi documentation requirements
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
@@ -172,7 +197,9 @@ impl TemporalClient {
|
|||||||
url.push_str("/?c=");
|
url.push_str("/?c=");
|
||||||
url.push_str(&self.auth_token);
|
url.push_str(&self.auth_token);
|
||||||
|
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body)
|
.body(request_body)
|
||||||
.header("Content-Type", "application/json")
|
.header("Content-Type", "application/json")
|
||||||
.send()
|
.send()
|
||||||
@@ -195,9 +222,13 @@ impl TemporalClient {
|
|||||||
Ok(_) => (),
|
Ok(_) => (),
|
||||||
Err(e) => {
|
Err(e) => {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [nozomi] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(
|
||||||
|
" [nozomi] {} confirmation failed: {:?}",
|
||||||
|
trade_type,
|
||||||
|
start_time.elapsed()
|
||||||
|
);
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -207,7 +238,12 @@ impl TemporalClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
+39
-12
@@ -1,4 +1,6 @@
|
|||||||
use crate::swqos::common::{default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode};
|
use crate::swqos::common::{
|
||||||
|
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||||
|
};
|
||||||
use rand::seq::IndexedRandom;
|
use rand::seq::IndexedRandom;
|
||||||
use reqwest::Client;
|
use reqwest::Client;
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
@@ -6,14 +8,13 @@ use std::{sync::Arc, time::Instant};
|
|||||||
|
|
||||||
use solana_transaction_status::UiTransactionEncoding;
|
use solana_transaction_status::UiTransactionEncoding;
|
||||||
|
|
||||||
|
use crate::swqos::SwqosClientTrait;
|
||||||
|
use crate::swqos::{SwqosType, TradeType};
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::transaction::VersionedTransaction;
|
use solana_sdk::transaction::VersionedTransaction;
|
||||||
use crate::swqos::{SwqosType, TradeType};
|
|
||||||
use crate::swqos::SwqosClientTrait;
|
|
||||||
|
|
||||||
use crate::{common::SolanaRpcClient, constants::swqos::ZEROSLOT_TIP_ACCOUNTS};
|
use crate::{common::SolanaRpcClient, constants::swqos::ZEROSLOT_TIP_ACCOUNTS};
|
||||||
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct ZeroSlotClient {
|
pub struct ZeroSlotClient {
|
||||||
pub endpoint: String,
|
pub endpoint: String,
|
||||||
@@ -24,16 +25,29 @@ pub struct ZeroSlotClient {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl SwqosClientTrait for ZeroSlotClient {
|
impl SwqosClientTrait for ZeroSlotClient {
|
||||||
async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_tip_account(&self) -> Result<String> {
|
fn get_tip_account(&self) -> Result<String> {
|
||||||
let tip_account = *ZEROSLOT_TIP_ACCOUNTS.choose(&mut rand::rng()).or_else(|| ZEROSLOT_TIP_ACCOUNTS.first()).unwrap();
|
let tip_account = *ZEROSLOT_TIP_ACCOUNTS
|
||||||
|
.choose(&mut rand::rng())
|
||||||
|
.or_else(|| ZEROSLOT_TIP_ACCOUNTS.first())
|
||||||
|
.unwrap();
|
||||||
Ok(tip_account.to_string())
|
Ok(tip_account.to_string())
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -49,9 +63,15 @@ impl ZeroSlotClient {
|
|||||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transaction(&self, trade_type: TradeType, transaction: &VersionedTransaction, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transaction(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transaction: &VersionedTransaction,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
let start_time = Instant::now();
|
let start_time = Instant::now();
|
||||||
let (content, signature) = serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
let (content, signature) =
|
||||||
|
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||||
|
|
||||||
let request_body = serde_json::to_string(&json!({
|
let request_body = serde_json::to_string(&json!({
|
||||||
"jsonrpc": "2.0",
|
"jsonrpc": "2.0",
|
||||||
@@ -69,7 +89,9 @@ impl ZeroSlotClient {
|
|||||||
url.push_str(&self.auth_token);
|
url.push_str(&self.auth_token);
|
||||||
|
|
||||||
// 4. Use `text().await?` directly, avoiding async JSON parsing from `json().await?`
|
// 4. Use `text().await?` directly, avoiding async JSON parsing from `json().await?`
|
||||||
let response_text = self.http_client.post(&url)
|
let response_text = self
|
||||||
|
.http_client
|
||||||
|
.post(&url)
|
||||||
.body(request_body) // Pass string directly, avoiding `json()` overhead
|
.body(request_body) // Pass string directly, avoiding `json()` overhead
|
||||||
.header("Content-Type", "application/json") // Explicitly specify JSON header
|
.header("Content-Type", "application/json") // Explicitly specify JSON header
|
||||||
.send()
|
.send()
|
||||||
@@ -95,7 +117,7 @@ impl ZeroSlotClient {
|
|||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
println!(" [0slot] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
println!(" [0slot] {} confirmation failed: {:?}", trade_type, start_time.elapsed());
|
||||||
return Err(e);
|
return Err(e);
|
||||||
},
|
}
|
||||||
}
|
}
|
||||||
if wait_confirmation {
|
if wait_confirmation {
|
||||||
println!(" signature: {:?}", signature);
|
println!(" signature: {:?}", signature);
|
||||||
@@ -105,7 +127,12 @@ impl ZeroSlotClient {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn send_transactions(&self, trade_type: TradeType, transactions: &Vec<VersionedTransaction>, wait_confirmation: bool) -> Result<()> {
|
pub async fn send_transactions(
|
||||||
|
&self,
|
||||||
|
trade_type: TradeType,
|
||||||
|
transactions: &Vec<VersionedTransaction>,
|
||||||
|
wait_confirmation: bool,
|
||||||
|
) -> Result<()> {
|
||||||
for transaction in transactions {
|
for transaction in transactions {
|
||||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,8 +1,8 @@
|
|||||||
use dashmap::DashMap;
|
use dashmap::DashMap;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use solana_sdk::instruction::Instruction;
|
|
||||||
use solana_compute_budget_interface::ComputeBudgetInstruction;
|
use solana_compute_budget_interface::ComputeBudgetInstruction;
|
||||||
|
use solana_sdk::instruction::Instruction;
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
/// Cache key containing all parameters for compute budget instructions
|
/// Cache key containing all parameters for compute budget instructions
|
||||||
|
|||||||
@@ -1,12 +1,12 @@
|
|||||||
|
pub mod compute_budget_manager;
|
||||||
pub mod nonce_manager;
|
pub mod nonce_manager;
|
||||||
pub mod transaction_builder;
|
pub mod transaction_builder;
|
||||||
pub mod compute_budget_manager;
|
|
||||||
pub mod utils;
|
pub mod utils;
|
||||||
pub mod wsol_manager;
|
pub mod wsol_manager;
|
||||||
|
|
||||||
// Re-export commonly used functions
|
// Re-export commonly used functions
|
||||||
|
pub use compute_budget_manager::*;
|
||||||
pub use nonce_manager::*;
|
pub use nonce_manager::*;
|
||||||
pub use transaction_builder::*;
|
pub use transaction_builder::*;
|
||||||
pub use compute_budget_manager::*;
|
|
||||||
pub use utils::*;
|
pub use utils::*;
|
||||||
pub use wsol_manager::*;
|
pub use wsol_manager::*;
|
||||||
@@ -15,7 +15,8 @@ pub fn add_nonce_instruction(
|
|||||||
durable_nonce: Option<&DurableNonceInfo>,
|
durable_nonce: Option<&DurableNonceInfo>,
|
||||||
) -> Result<(), anyhow::Error> {
|
) -> Result<(), anyhow::Error> {
|
||||||
if let Some(durable_nonce) = durable_nonce {
|
if let Some(durable_nonce) = durable_nonce {
|
||||||
let nonce_advance_ix = advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
|
let nonce_advance_ix =
|
||||||
|
advance_nonce_account(&durable_nonce.nonce_account.unwrap(), &payer.pubkey());
|
||||||
instructions.push(nonce_advance_ix);
|
instructions.push(nonce_advance_ix);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ use std::sync::Arc;
|
|||||||
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
|
use super::nonce_manager::{add_nonce_instruction, get_transaction_blockhash};
|
||||||
use crate::{
|
use crate::{
|
||||||
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
|
common::{nonce_cache::DurableNonceInfo, SolanaRpcClient},
|
||||||
trading::{MiddlewareManager, core::transaction_pool::{acquire_builder, release_builder}},
|
trading::{
|
||||||
|
core::transaction_pool::{acquire_builder, release_builder},
|
||||||
|
MiddlewareManager,
|
||||||
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Convert SOL amount (f64) to lamports without string allocation (hot path).
|
/// Convert SOL amount (f64) to lamports without string allocation (hot path).
|
||||||
|
|||||||
@@ -40,14 +40,7 @@ pub async fn get_token_balance(
|
|||||||
payer: &Pubkey,
|
payer: &Pubkey,
|
||||||
mint: &Pubkey,
|
mint: &Pubkey,
|
||||||
) -> Result<u64, anyhow::Error> {
|
) -> Result<u64, anyhow::Error> {
|
||||||
get_token_balance_with_options(
|
get_token_balance_with_options(rpc, payer, mint, &crate::constants::TOKEN_PROGRAM, false).await
|
||||||
rpc,
|
|
||||||
payer,
|
|
||||||
mint,
|
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
|
||||||
false,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 使用与交易指令一致的 ATA 推导(可选 seed)查询余额;卖出/余额查询应与买入使用同一 ATA 地址。
|
/// 使用与交易指令一致的 ATA 推导(可选 seed)查询余额;卖出/余额查询应与买入使用同一 ATA 地址。
|
||||||
|
|||||||
@@ -1,7 +1,10 @@
|
|||||||
use crate::common::{
|
use crate::common::{
|
||||||
fast_fn::create_associated_token_account_idempotent_fast,
|
fast_fn::create_associated_token_account_idempotent_fast,
|
||||||
|
seed::{
|
||||||
|
create_associated_token_account_use_seed,
|
||||||
|
get_associated_token_address_with_program_id_use_seed,
|
||||||
|
},
|
||||||
spl_token::close_account,
|
spl_token::close_account,
|
||||||
seed::{create_associated_token_account_use_seed, get_associated_token_address_with_program_id_use_seed},
|
|
||||||
};
|
};
|
||||||
use smallvec::SmallVec;
|
use smallvec::SmallVec;
|
||||||
use solana_sdk::{instruction::Instruction, message::AccountMeta, pubkey::Pubkey};
|
use solana_sdk::{instruction::Instruction, message::AccountMeta, pubkey::Pubkey};
|
||||||
@@ -109,10 +112,7 @@ pub fn wrap_sol_only(payer: &Pubkey, amount_in: u64) -> SmallVec<[Instruction; 2
|
|||||||
///
|
///
|
||||||
/// 注意:此函数只生成指令,不检查账户是否存在(需要调用方在发送交易前检查)
|
/// 注意:此函数只生成指令,不检查账户是否存在(需要调用方在发送交易前检查)
|
||||||
/// 如果临时账户已存在,可以安全地跳过创建步骤,直接转账并关闭
|
/// 如果临时账户已存在,可以安全地跳过创建步骤,直接转账并关闭
|
||||||
pub fn wrap_wsol_to_sol(
|
pub fn wrap_wsol_to_sol(payer: &Pubkey, amount: u64) -> Result<Vec<Instruction>, anyhow::Error> {
|
||||||
payer: &Pubkey,
|
|
||||||
amount: u64,
|
|
||||||
) -> Result<Vec<Instruction>, anyhow::Error> {
|
|
||||||
let mut instructions = Vec::new();
|
let mut instructions = Vec::new();
|
||||||
|
|
||||||
// 1. 创建 WSOL seed 账户(注意:如果账户已存在会失败)
|
// 1. 创建 WSOL seed 账户(注意:如果账户已存在会失败)
|
||||||
@@ -151,13 +151,8 @@ pub fn wrap_wsol_to_sol(
|
|||||||
instructions.push(transfer_instruction);
|
instructions.push(transfer_instruction);
|
||||||
|
|
||||||
// 5. 添加关闭 WSOL seed 账户的指令
|
// 5. 添加关闭 WSOL seed 账户的指令
|
||||||
let close_instruction = close_account(
|
let close_instruction =
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
close_account(&crate::constants::TOKEN_PROGRAM, &seed_ata_address, payer, payer, &[])?;
|
||||||
&seed_ata_address,
|
|
||||||
payer,
|
|
||||||
payer,
|
|
||||||
&[],
|
|
||||||
)?;
|
|
||||||
instructions.push(close_instruction);
|
instructions.push(close_instruction);
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
@@ -197,13 +192,8 @@ pub fn wrap_wsol_to_sol_without_create(
|
|||||||
instructions.push(transfer_instruction);
|
instructions.push(transfer_instruction);
|
||||||
|
|
||||||
// 4. 添加关闭 WSOL seed 账户的指令
|
// 4. 添加关闭 WSOL seed 账户的指令
|
||||||
let close_instruction = close_account(
|
let close_instruction =
|
||||||
&crate::constants::TOKEN_PROGRAM,
|
close_account(&crate::constants::TOKEN_PROGRAM, &seed_ata_address, payer, payer, &[])?;
|
||||||
&seed_ata_address,
|
|
||||||
payer,
|
|
||||||
payer,
|
|
||||||
&[],
|
|
||||||
)?;
|
|
||||||
instructions.push(close_instruction);
|
instructions.push(close_instruction);
|
||||||
|
|
||||||
Ok(instructions)
|
Ok(instructions)
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
//! Parallel executor for multi-SWQOS submit.
|
//! Parallel executor for multi-SWQOS submit.
|
||||||
//!
|
//!
|
||||||
//! - **Pool**: Pre-spawned workers; hot path only enqueues jobs (no per-call tokio::spawn).
|
//! - **Pool**: Pre-spawned workers (default 18); hot path only enqueues jobs (no per-call tokio::spawn).
|
||||||
|
//! - **Dedicated threads** (opt-in via TradeConfig): When `use_dedicated_sender_threads` is true, N OS threads (default 18) run sender work only, optionally pinned to cores via `sender_thread_cores`, reducing scheduling contention when sending many txs.
|
||||||
//! - **Arc**: Shared data is behind `Arc` so "clone" is just a refcount increment (no data copy).
|
//! - **Arc**: Shared data is behind `Arc` so "clone" is just a refcount increment (no data copy).
|
||||||
//! - **Refs**: `build_transaction` takes `&Arc<..>`, `Option<&DurableNonceInfo>`, `Option<&AddressLookupTableAccount>` so the worker passes refs only (zero clone on worker path).
|
//! - **Refs**: `build_transaction` takes `&Arc<..>`, `Option<&DurableNonceInfo>`, `Option<&AddressLookupTableAccount>` so the worker passes refs only (zero clone on worker path).
|
||||||
|
|
||||||
@@ -15,7 +16,9 @@ use solana_sdk::{
|
|||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
use std::hash::BuildHasherDefault;
|
use std::hash::BuildHasherDefault;
|
||||||
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering};
|
||||||
|
use std::sync::Mutex;
|
||||||
use std::{str::FromStr, sync::Arc, time::Instant};
|
use std::{str::FromStr, sync::Arc, time::Instant};
|
||||||
|
use tokio::sync::Notify;
|
||||||
|
|
||||||
use fnv::FnvHasher;
|
use fnv::FnvHasher;
|
||||||
|
|
||||||
@@ -28,8 +31,10 @@ use crate::{
|
|||||||
trading::{common::build_transaction, MiddlewareManager},
|
trading::{common::build_transaction, MiddlewareManager},
|
||||||
};
|
};
|
||||||
|
|
||||||
const SWQOS_POOL_WORKERS: usize = 32;
|
/// 与 transaction_pool::PARALLEL_SENDER_COUNT 一致,保证多路 build 不串行
|
||||||
|
const SWQOS_POOL_WORKERS: usize = 18;
|
||||||
const SWQOS_QUEUE_CAP: usize = 128;
|
const SWQOS_QUEUE_CAP: usize = 128;
|
||||||
|
const SWQOS_DEDICATED_DEFAULT_THREADS: usize = 18;
|
||||||
|
|
||||||
/// Shared across all jobs in one batch; built once, cloned as single Arc per job (minimal hot-path clone).
|
/// Shared across all jobs in one batch; built once, cloned as single Arc per job (minimal hot-path clone).
|
||||||
struct SwqosSharedContext {
|
struct SwqosSharedContext {
|
||||||
@@ -105,11 +110,7 @@ async fn run_one_swqos_job(job: SwqosJob) {
|
|||||||
let (success, err, landed_on_chain) = match job
|
let (success, err, landed_on_chain) = match job
|
||||||
.swqos_client
|
.swqos_client
|
||||||
.send_transaction(
|
.send_transaction(
|
||||||
if s.is_buy {
|
if s.is_buy { TradeType::Buy } else { TradeType::Sell },
|
||||||
TradeType::Buy
|
|
||||||
} else {
|
|
||||||
TradeType::Sell
|
|
||||||
},
|
|
||||||
&transaction,
|
&transaction,
|
||||||
s.wait_transaction_confirmed,
|
s.wait_transaction_confirmed,
|
||||||
)
|
)
|
||||||
@@ -133,25 +134,80 @@ async fn run_one_swqos_job(job: SwqosJob) {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn swqos_worker_loop(queue: Arc<ArrayQueue<SwqosJob>>) {
|
async fn swqos_worker_loop(queue: Arc<ArrayQueue<SwqosJob>>, notify: Arc<Notify>) {
|
||||||
loop {
|
loop {
|
||||||
if let Some(job) = queue.pop() {
|
if let Some(job) = queue.pop() {
|
||||||
run_one_swqos_job(job).await;
|
run_one_swqos_job(job).await;
|
||||||
} else {
|
} else {
|
||||||
tokio::task::yield_now().await;
|
notify.notified().await;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
static SWQOS_QUEUE: OnceCell<Arc<ArrayQueue<SwqosJob>>> = OnceCell::new();
|
static SWQOS_QUEUE: OnceCell<Arc<ArrayQueue<SwqosJob>>> = OnceCell::new();
|
||||||
|
static SWQOS_NOTIFY: OnceCell<Arc<Notify>> = OnceCell::new();
|
||||||
static SWQOS_WORKERS_STARTED: AtomicBool = AtomicBool::new(false);
|
static SWQOS_WORKERS_STARTED: AtomicBool = AtomicBool::new(false);
|
||||||
|
|
||||||
|
/// Dedicated OS-thread sender pool. Queue and notify are in OnceCell so hot path never takes a lock after init.
|
||||||
|
static DEDICATED_QUEUE: OnceCell<Arc<ArrayQueue<SwqosJob>>> = OnceCell::new();
|
||||||
|
static DEDICATED_NOTIFY: OnceCell<Arc<Notify>> = OnceCell::new();
|
||||||
|
/// JoinHandles kept so dedicated threads are not detached; only touched during init under lock.
|
||||||
|
static DEDICATED_INIT: Mutex<Option<Vec<std::thread::JoinHandle<()>>>> = Mutex::new(None);
|
||||||
|
|
||||||
|
fn ensure_dedicated_pool(sender_thread_cores: Option<&[usize]>) -> (Arc<ArrayQueue<SwqosJob>>, Arc<Notify>) {
|
||||||
|
if let (Some(q), Some(n)) = (DEDICATED_QUEUE.get(), DEDICATED_NOTIFY.get()) {
|
||||||
|
return (q.clone(), n.clone());
|
||||||
|
}
|
||||||
|
let mut guard = DEDICATED_INIT.lock().expect("dedicated init mutex");
|
||||||
|
if let (Some(q), Some(n)) = (DEDICATED_QUEUE.get(), DEDICATED_NOTIFY.get()) {
|
||||||
|
return (q.clone(), n.clone());
|
||||||
|
}
|
||||||
|
let n = sender_thread_cores
|
||||||
|
.map(|v| v.len())
|
||||||
|
.unwrap_or(SWQOS_DEDICATED_DEFAULT_THREADS)
|
||||||
|
.min(32);
|
||||||
|
let queue = Arc::new(ArrayQueue::new(SWQOS_QUEUE_CAP));
|
||||||
|
let notify = Arc::new(Notify::new());
|
||||||
|
let core_ids: Vec<core_affinity::CoreId> = sender_thread_cores
|
||||||
|
.and_then(|indices| {
|
||||||
|
core_affinity::get_core_ids().map(|ids| {
|
||||||
|
indices
|
||||||
|
.iter()
|
||||||
|
.filter_map(|&i| ids.get(i).cloned())
|
||||||
|
.collect()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
.unwrap_or_default();
|
||||||
|
let mut handles = Vec::with_capacity(n);
|
||||||
|
for i in 0..n {
|
||||||
|
let queue = queue.clone();
|
||||||
|
let notify = notify.clone();
|
||||||
|
let core_id = core_ids.get(i).cloned();
|
||||||
|
let handle = std::thread::spawn(move || {
|
||||||
|
if let Some(cid) = core_id {
|
||||||
|
core_affinity::set_for_current(cid);
|
||||||
|
}
|
||||||
|
let rt = tokio::runtime::Builder::new_current_thread()
|
||||||
|
.enable_all()
|
||||||
|
.build()
|
||||||
|
.expect("dedicated sender runtime");
|
||||||
|
rt.block_on(swqos_worker_loop(queue, notify));
|
||||||
|
});
|
||||||
|
handles.push(handle);
|
||||||
|
}
|
||||||
|
let _ = DEDICATED_QUEUE.set(queue.clone());
|
||||||
|
let _ = DEDICATED_NOTIFY.set(notify.clone());
|
||||||
|
*guard = Some(handles);
|
||||||
|
(queue, notify)
|
||||||
|
}
|
||||||
|
|
||||||
fn ensure_swqos_pool(queue: Arc<ArrayQueue<SwqosJob>>) {
|
fn ensure_swqos_pool(queue: Arc<ArrayQueue<SwqosJob>>) {
|
||||||
if SWQOS_WORKERS_STARTED.swap(true, Ordering::AcqRel) {
|
if SWQOS_WORKERS_STARTED.swap(true, Ordering::AcqRel) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
let notify = SWQOS_NOTIFY.get_or_init(|| Arc::new(Notify::new())).clone();
|
||||||
for _ in 0..SWQOS_POOL_WORKERS {
|
for _ in 0..SWQOS_POOL_WORKERS {
|
||||||
tokio::spawn(swqos_worker_loop(queue.clone()));
|
tokio::spawn(swqos_worker_loop(queue.clone(), notify.clone()));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -193,7 +249,7 @@ fn is_landed_error(error: &anyhow::Error) -> bool {
|
|||||||
struct ResultCollector {
|
struct ResultCollector {
|
||||||
results: Arc<ArrayQueue<TaskResult>>,
|
results: Arc<ArrayQueue<TaskResult>>,
|
||||||
success_flag: Arc<AtomicBool>,
|
success_flag: Arc<AtomicBool>,
|
||||||
landed_failed_flag: Arc<AtomicBool>, // 🔧 Tx landed on-chain but failed (nonce consumed)
|
landed_failed_flag: Arc<AtomicBool>, // 🔧 Tx landed on-chain but failed (nonce consumed)
|
||||||
completed_count: Arc<AtomicUsize>,
|
completed_count: Arc<AtomicUsize>,
|
||||||
total_tasks: usize,
|
total_tasks: usize,
|
||||||
}
|
}
|
||||||
@@ -226,7 +282,9 @@ impl ResultCollector {
|
|||||||
self.completed_count.fetch_add(1, Ordering::Release);
|
self.completed_count.fetch_add(1, Ordering::Release);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn wait_for_success(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
async fn wait_for_success(
|
||||||
|
&self,
|
||||||
|
) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let timeout = std::time::Duration::from_secs(5);
|
let timeout = std::time::Duration::from_secs(5);
|
||||||
let poll_interval = std::time::Duration::from_millis(1000);
|
let poll_interval = std::time::Duration::from_millis(1000);
|
||||||
@@ -268,7 +326,7 @@ impl ResultCollector {
|
|||||||
}
|
}
|
||||||
|
|
||||||
let completed = self.completed_count.load(Ordering::Acquire);
|
let completed = self.completed_count.load(Ordering::Acquire);
|
||||||
if completed >= self.total_tasks {
|
if completed >= self.total_tasks {
|
||||||
let mut signatures = Vec::new();
|
let mut signatures = Vec::new();
|
||||||
let mut last_error = None;
|
let mut last_error = None;
|
||||||
let mut any_success = false;
|
let mut any_success = false;
|
||||||
@@ -296,7 +354,9 @@ impl ResultCollector {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn get_first(&self) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
fn get_first(
|
||||||
|
&self,
|
||||||
|
) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||||
let mut signatures = Vec::new();
|
let mut signatures = Vec::new();
|
||||||
let mut has_success = false;
|
let mut has_success = false;
|
||||||
let mut last_error = None;
|
let mut last_error = None;
|
||||||
@@ -322,7 +382,10 @@ impl ResultCollector {
|
|||||||
|
|
||||||
/// 等待全部任务完成(不等待链上确认),然后收集并返回所有签名。用于「多路提交」时返回多笔签名。
|
/// 等待全部任务完成(不等待链上确认),然后收集并返回所有签名。用于「多路提交」时返回多笔签名。
|
||||||
/// 轮询间隔 2ms,避免 50ms 间隔在最后一笔返回时多等几十 ms 拉高 submit 耗时。
|
/// 轮询间隔 2ms,避免 50ms 间隔在最后一笔返回时多等几十 ms 拉高 submit 耗时。
|
||||||
async fn wait_for_all_submitted(&self, timeout_secs: u64) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
async fn wait_for_all_submitted(
|
||||||
|
&self,
|
||||||
|
timeout_secs: u64,
|
||||||
|
) -> Option<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||||
let start = Instant::now();
|
let start = Instant::now();
|
||||||
let timeout = std::time::Duration::from_secs(timeout_secs);
|
let timeout = std::time::Duration::from_secs(timeout_secs);
|
||||||
let poll_interval = std::time::Duration::from_millis(2);
|
let poll_interval = std::time::Duration::from_millis(2);
|
||||||
@@ -340,7 +403,7 @@ impl ResultCollector {
|
|||||||
pub async fn execute_parallel(
|
pub async fn execute_parallel(
|
||||||
swqos_clients: &[Arc<SwqosClient>],
|
swqos_clients: &[Arc<SwqosClient>],
|
||||||
payer: Arc<Keypair>,
|
payer: Arc<Keypair>,
|
||||||
rpc: Option<Arc<SolanaRpcClient>>,
|
rpc: Option<&Arc<SolanaRpcClient>>,
|
||||||
instructions: Vec<Instruction>,
|
instructions: Vec<Instruction>,
|
||||||
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
address_lookup_table_account: Option<AddressLookupTableAccount>,
|
||||||
recent_blockhash: Option<Hash>,
|
recent_blockhash: Option<Hash>,
|
||||||
@@ -352,6 +415,8 @@ pub async fn execute_parallel(
|
|||||||
with_tip: bool,
|
with_tip: bool,
|
||||||
gas_fee_strategy: GasFeeStrategy,
|
gas_fee_strategy: GasFeeStrategy,
|
||||||
use_core_affinity: bool,
|
use_core_affinity: bool,
|
||||||
|
use_dedicated_sender_threads: bool,
|
||||||
|
sender_thread_cores: Option<&[usize]>,
|
||||||
check_min_tip: bool,
|
check_min_tip: bool,
|
||||||
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>, Vec<(SwqosType, i64)>)> {
|
||||||
let _exec_start = Instant::now();
|
let _exec_start = Instant::now();
|
||||||
@@ -387,11 +452,7 @@ pub async fn execute_parallel(
|
|||||||
TradeType::Sell
|
TradeType::Sell
|
||||||
});
|
});
|
||||||
let check_tip = with_tip && !matches!(swqos_type, SwqosType::Default) && check_min_tip;
|
let check_tip = with_tip && !matches!(swqos_type, SwqosType::Default) && check_min_tip;
|
||||||
let min_tip = if check_tip {
|
let min_tip = if check_tip { swqos_client.min_tip_sol() } else { 0.0 };
|
||||||
swqos_client.min_tip_sol()
|
|
||||||
} else {
|
|
||||||
0.0
|
|
||||||
};
|
|
||||||
gas_fee_strategy_configs
|
gas_fee_strategy_configs
|
||||||
.into_iter()
|
.into_iter()
|
||||||
.filter(move |config| config.0 == swqos_type)
|
.filter(move |config| config.0 == swqos_type)
|
||||||
@@ -425,7 +486,7 @@ pub async fn execute_parallel(
|
|||||||
let shared = Arc::new(SwqosSharedContext {
|
let shared = Arc::new(SwqosSharedContext {
|
||||||
payer,
|
payer,
|
||||||
instructions,
|
instructions,
|
||||||
rpc,
|
rpc: rpc.cloned(),
|
||||||
address_lookup_table_account,
|
address_lookup_table_account,
|
||||||
recent_blockhash,
|
recent_blockhash,
|
||||||
durable_nonce,
|
durable_nonce,
|
||||||
@@ -437,8 +498,13 @@ pub async fn execute_parallel(
|
|||||||
collector: collector.clone(),
|
collector: collector.clone(),
|
||||||
});
|
});
|
||||||
|
|
||||||
let queue = SWQOS_QUEUE.get_or_init(|| Arc::new(ArrayQueue::new(SWQOS_QUEUE_CAP)));
|
let (queue, notify) = if use_dedicated_sender_threads {
|
||||||
ensure_swqos_pool(queue.clone());
|
ensure_dedicated_pool(sender_thread_cores)
|
||||||
|
} else {
|
||||||
|
let q = SWQOS_QUEUE.get_or_init(|| Arc::new(ArrayQueue::new(SWQOS_QUEUE_CAP)));
|
||||||
|
ensure_swqos_pool(q.clone());
|
||||||
|
(q.clone(), SWQOS_NOTIFY.get_or_init(|| Arc::new(Notify::new())).clone())
|
||||||
|
};
|
||||||
|
|
||||||
{
|
{
|
||||||
// Cache tip_account per client (one get_tip_account/from_str per unique client per batch). Dropped before await so future stays Send.
|
// Cache tip_account per client (one get_tip_account/from_str per unique client per batch). Dropped before await so future stays Send.
|
||||||
@@ -477,14 +543,18 @@ pub async fn execute_parallel(
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
notify.notify_waiters();
|
||||||
|
|
||||||
// All jobs enqueued (no spawn on hot path)
|
// All jobs enqueued (no spawn on hot path)
|
||||||
|
|
||||||
if !wait_transaction_confirmed {
|
if !wait_transaction_confirmed {
|
||||||
const SUBMIT_TIMEOUT_SECS: u64 = 30;
|
const SUBMIT_TIMEOUT_SECS: u64 = 30;
|
||||||
let ret = collector
|
let ret = collector.wait_for_all_submitted(SUBMIT_TIMEOUT_SECS).await.unwrap_or((
|
||||||
.wait_for_all_submitted(SUBMIT_TIMEOUT_SECS)
|
false,
|
||||||
.await
|
vec![],
|
||||||
.unwrap_or((false, vec![], Some(anyhow!("No SWQOS result within {}s", SUBMIT_TIMEOUT_SECS)), vec![]));
|
Some(anyhow!("No SWQOS result within {}s", SUBMIT_TIMEOUT_SECS)),
|
||||||
|
vec![],
|
||||||
|
));
|
||||||
let (success, signatures, last_error, submit_timings) = ret;
|
let (success, signatures, last_error, submit_timings) = ret;
|
||||||
return Ok((success, signatures, last_error, submit_timings));
|
return Ok((success, signatures, last_error, submit_timings));
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,16 +2,9 @@
|
|||||||
//! 执行模块:指令预处理、缓存预取、分支提示。
|
//! 执行模块:指令预处理、缓存预取、分支提示。
|
||||||
|
|
||||||
use anyhow::Result;
|
use anyhow::Result;
|
||||||
use solana_sdk::{
|
use solana_sdk::{instruction::Instruction, pubkey::Pubkey, signature::Keypair};
|
||||||
instruction::Instruction,
|
|
||||||
pubkey::Pubkey,
|
|
||||||
signature::Keypair,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::perf::{
|
use crate::perf::{hardware_optimizations::BranchOptimizer, simd::SIMDMemory};
|
||||||
hardware_optimizations::BranchOptimizer,
|
|
||||||
simd::SIMDMemory,
|
|
||||||
};
|
|
||||||
|
|
||||||
/// Solana account key size in bytes (Pubkey). 每个账户(Pubkey)的字节数。
|
/// Solana account key size in bytes (Pubkey). 每个账户(Pubkey)的字节数。
|
||||||
pub const BYTES_PER_ACCOUNT: usize = 32;
|
pub const BYTES_PER_ACCOUNT: usize = 32;
|
||||||
|
|||||||
@@ -4,10 +4,15 @@ use solana_sdk::{
|
|||||||
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
|
instruction::Instruction, message::AddressLookupTableAccount, pubkey::Pubkey,
|
||||||
signature::Keypair, signature::Signature,
|
signature::Keypair, signature::Signature,
|
||||||
};
|
};
|
||||||
use std::{sync::Arc, time::{Duration, Instant}};
|
use std::{
|
||||||
|
sync::Arc,
|
||||||
|
time::{Duration, Instant},
|
||||||
|
};
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
use tracing::{info, trace, warn};
|
use tracing::{info, trace, warn};
|
||||||
|
|
||||||
|
use super::{params::SwapParams, traits::InstructionBuilder};
|
||||||
|
use crate::swqos::TradeType;
|
||||||
use crate::{
|
use crate::{
|
||||||
common::{nonce_cache::DurableNonceInfo, GasFeeStrategy, SolanaRpcClient},
|
common::{nonce_cache::DurableNonceInfo, GasFeeStrategy, SolanaRpcClient},
|
||||||
perf::syscall_bypass::SystemCallBypassManager,
|
perf::syscall_bypass::SystemCallBypassManager,
|
||||||
@@ -20,8 +25,6 @@ use crate::{
|
|||||||
trading::MiddlewareManager,
|
trading::MiddlewareManager,
|
||||||
};
|
};
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use crate::swqos::TradeType;
|
|
||||||
use super::{params::SwapParams, traits::InstructionBuilder};
|
|
||||||
|
|
||||||
/// Global syscall bypass manager (reserved for future time/IO optimizations).
|
/// Global syscall bypass manager (reserved for future time/IO optimizations).
|
||||||
/// 全局系统调用绕过管理器(预留,后续可接入时间/IO 等优化)。
|
/// 全局系统调用绕过管理器(预留,后续可接入时间/IO 等优化)。
|
||||||
@@ -49,7 +52,10 @@ impl GenericTradeExecutor {
|
|||||||
|
|
||||||
#[async_trait::async_trait]
|
#[async_trait::async_trait]
|
||||||
impl TradeExecutor for GenericTradeExecutor {
|
impl TradeExecutor for GenericTradeExecutor {
|
||||||
async fn swap(&self, params: SwapParams) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
async fn swap(
|
||||||
|
&self,
|
||||||
|
params: SwapParams,
|
||||||
|
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)> {
|
||||||
// Sample total start only when logging or simulate. 仅在有日志或 simulate 时取起点。
|
// Sample total start only when logging or simulate. 仅在有日志或 simulate 时取起点。
|
||||||
let total_start = (params.log_enabled || params.simulate).then(Instant::now);
|
let total_start = (params.log_enabled || params.simulate).then(Instant::now);
|
||||||
let timing_start_us: Option<i64> = if params.log_enabled {
|
let timing_start_us: Option<i64> = if params.log_enabled {
|
||||||
@@ -58,7 +64,8 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
None
|
None
|
||||||
};
|
};
|
||||||
|
|
||||||
let is_buy = params.trade_type == TradeType::Buy || params.trade_type == TradeType::CreateAndBuy;
|
let is_buy =
|
||||||
|
params.trade_type == TradeType::Buy || params.trade_type == TradeType::CreateAndBuy;
|
||||||
|
|
||||||
Prefetch::keypair(¶ms.payer);
|
Prefetch::keypair(¶ms.payer);
|
||||||
|
|
||||||
@@ -85,7 +92,8 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
|
|
||||||
let build_end_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
let build_end_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
||||||
.then(crate::common::clock::now_micros);
|
.then(crate::common::clock::now_micros);
|
||||||
let _before_submit_elapsed = total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
let _before_submit_elapsed =
|
||||||
|
total_start.as_ref().map(|s| s.elapsed()).unwrap_or(Duration::ZERO);
|
||||||
let before_submit_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
let before_submit_us = (params.log_enabled && crate::common::sdk_log::sdk_log_enabled())
|
||||||
.then(crate::common::clock::now_micros);
|
.then(crate::common::clock::now_micros);
|
||||||
|
|
||||||
@@ -111,12 +119,24 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
if crate::common::sdk_log::sdk_log_enabled() {
|
if crate::common::sdk_log::sdk_log_enabled() {
|
||||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||||
if let (Some(start_us), Some(end_us)) = (timing_start_us, build_end_us) {
|
if let (Some(start_us), Some(end_us)) = (timing_start_us, build_end_us) {
|
||||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} build_instructions: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let (Some(start_us), Some(end_us)) = (timing_start_us, before_submit_us) {
|
if let (Some(start_us), Some(end_us)) = (timing_start_us, before_submit_us) {
|
||||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} before_submit: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
println!(" [SDK] {} simulate (dry-run): {:.4} ms", dir, send_elapsed.as_secs_f64() * 1000.0);
|
println!(
|
||||||
|
" [SDK] {} simulate (dry-run): {:.4} ms",
|
||||||
|
dir,
|
||||||
|
send_elapsed.as_secs_f64() * 1000.0
|
||||||
|
);
|
||||||
println!(" [SDK] {} total: {:.4} ms", dir, total_elapsed.as_secs_f64() * 1000.0);
|
println!(" [SDK] {} total: {:.4} ms", dir, total_elapsed.as_secs_f64() * 1000.0);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -125,9 +145,9 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
|
|
||||||
let need_confirm = params.wait_transaction_confirmed;
|
let need_confirm = params.wait_transaction_confirmed;
|
||||||
let result = execute_parallel(
|
let result = execute_parallel(
|
||||||
¶ms.swqos_clients,
|
params.swqos_clients.as_slice(),
|
||||||
params.payer,
|
params.payer,
|
||||||
params.rpc.clone(),
|
params.rpc.as_ref(),
|
||||||
final_instructions,
|
final_instructions,
|
||||||
params.address_lookup_table_account,
|
params.address_lookup_table_account,
|
||||||
params.recent_blockhash,
|
params.recent_blockhash,
|
||||||
@@ -139,6 +159,8 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
if is_buy { true } else { params.with_tip },
|
if is_buy { true } else { params.with_tip },
|
||||||
params.gas_fee_strategy,
|
params.gas_fee_strategy,
|
||||||
params.use_core_affinity,
|
params.use_core_affinity,
|
||||||
|
params.use_dedicated_sender_threads,
|
||||||
|
params.sender_thread_cores.as_ref().map(|a| a.as_slice()),
|
||||||
params.check_min_tip,
|
params.check_min_tip,
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
@@ -146,14 +168,12 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
let log_enabled = params.log_enabled && crate::common::sdk_log::sdk_log_enabled();
|
let log_enabled = params.log_enabled && crate::common::sdk_log::sdk_log_enabled();
|
||||||
|
|
||||||
let (ok, signatures, err, submit_timings) = match result {
|
let (ok, signatures, err, submit_timings) = match result {
|
||||||
Ok((success, sigs, last_error, timings)) => (
|
Ok((success, sigs, last_error, timings)) => {
|
||||||
success,
|
(success, sigs, last_error.map(|e| anyhow::anyhow!("{}", e)), timings)
|
||||||
sigs,
|
}
|
||||||
last_error.map(|e| anyhow::anyhow!("{}", e)),
|
|
||||||
timings,
|
|
||||||
),
|
|
||||||
Err(e) => (false, vec![], Some(anyhow::anyhow!("{}", e)), vec![]),
|
Err(e) => (false, vec![], Some(anyhow::anyhow!("{}", e)), vec![]),
|
||||||
};
|
};
|
||||||
|
// submit_timings 为完成先后顺序(先完成的先 push),打印不排序、不增加延迟
|
||||||
let submit_timings_ref: &[(crate::swqos::SwqosType, i64)] = submit_timings.as_slice();
|
let submit_timings_ref: &[(crate::swqos::SwqosType, i64)] = submit_timings.as_slice();
|
||||||
|
|
||||||
let result = if need_confirm {
|
let result = if need_confirm {
|
||||||
@@ -167,16 +187,26 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||||
if let Some(start_us) = timing_start_us {
|
if let Some(start_us) = timing_start_us {
|
||||||
if let Some(end_us) = build_end_us {
|
if let Some(end_us) = build_end_us {
|
||||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} build_instructions: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(end_us) = before_submit_us {
|
if let Some(end_us) = before_submit_us {
|
||||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} before_submit: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(confirm_us) = confirm_done_us {
|
if let Some(confirm_us) = confirm_done_us {
|
||||||
let total_ms = (confirm_us - start_us) as f64 / 1000.0;
|
let total_ms = (confirm_us - start_us) as f64 / 1000.0;
|
||||||
for (swqos_type, submit_done_us) in submit_timings_ref {
|
for (swqos_type, submit_done_us) in submit_timings_ref {
|
||||||
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
let submit_ms =
|
||||||
let confirmed_ms = (confirm_us - *submit_done_us).max(0) as f64 / 1000.0;
|
(*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||||
|
let confirmed_ms =
|
||||||
|
(confirm_us - *submit_done_us).max(0) as f64 / 1000.0;
|
||||||
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms", dir, swqos_type, submit_ms, confirmed_ms, total_ms);
|
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: {:.4} ms, total: {:.4} ms", dir, swqos_type, submit_ms, confirmed_ms, total_ms);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -196,14 +226,25 @@ impl TradeExecutor for GenericTradeExecutor {
|
|||||||
let dir = if is_buy { "Buy" } else { "Sell" };
|
let dir = if is_buy { "Buy" } else { "Sell" };
|
||||||
if let Some(start_us) = timing_start_us {
|
if let Some(start_us) = timing_start_us {
|
||||||
if let Some(end_us) = build_end_us {
|
if let Some(end_us) = build_end_us {
|
||||||
println!(" [SDK] {} build_instructions: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} build_instructions: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
if let Some(end_us) = before_submit_us {
|
if let Some(end_us) = before_submit_us {
|
||||||
println!(" [SDK] {} before_submit: {:.4} ms", dir, (end_us - start_us) as f64 / 1000.0);
|
println!(
|
||||||
|
" [SDK] {} before_submit: {:.4} ms",
|
||||||
|
dir,
|
||||||
|
(end_us - start_us) as f64 / 1000.0
|
||||||
|
);
|
||||||
}
|
}
|
||||||
for (swqos_type, submit_done_us) in submit_timings_ref {
|
for (swqos_type, submit_done_us) in submit_timings_ref {
|
||||||
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
let submit_ms = (*submit_done_us - start_us).max(0) as f64 / 1000.0;
|
||||||
println!(" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms", dir, swqos_type, submit_ms, submit_ms);
|
println!(
|
||||||
|
" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms",
|
||||||
|
dir, swqos_type, submit_ms, submit_ms
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -278,14 +319,14 @@ async fn simulate_transaction(
|
|||||||
.simulate_transaction_with_config(
|
.simulate_transaction_with_config(
|
||||||
&transaction,
|
&transaction,
|
||||||
RpcSimulateTransactionConfig {
|
RpcSimulateTransactionConfig {
|
||||||
sig_verify: false, // Don't verify signature during simulation for speed
|
sig_verify: false, // Don't verify signature during simulation for speed
|
||||||
replace_recent_blockhash: false, // Use actual blockhash from transaction
|
replace_recent_blockhash: false, // Use actual blockhash from transaction
|
||||||
commitment: Some(CommitmentConfig {
|
commitment: Some(CommitmentConfig {
|
||||||
commitment: CommitmentLevel::Processed, // Use Processed level to get latest state
|
commitment: CommitmentLevel::Processed, // Use Processed level to get latest state
|
||||||
}),
|
}),
|
||||||
encoding: Some(UiTransactionEncoding::Base64), // Base64 encoding
|
encoding: Some(UiTransactionEncoding::Base64), // Base64 encoding
|
||||||
accounts: None, // Don't return specific account states (can be specified if needed)
|
accounts: None, // Don't return specific account states (can be specified if needed)
|
||||||
min_context_slot: None, // Don't specify minimum context slot
|
min_context_slot: None, // Don't specify minimum context slot
|
||||||
inner_instructions: true, // Enable inner instructions for debugging and detailed execution flow
|
inner_instructions: true, // Enable inner instructions for debugging and detailed execution flow
|
||||||
},
|
},
|
||||||
)
|
)
|
||||||
@@ -353,10 +394,9 @@ mod tests {
|
|||||||
}
|
}
|
||||||
|
|
||||||
println!("\n--- 3. 不等待链上确认时:每行 total = 该通道 submit 耗时(独立)---\n");
|
println!("\n--- 3. 不等待链上确认时:每行 total = 该通道 submit 耗时(独立)---\n");
|
||||||
for (swqos_type, submit_ms, total_ms) in [
|
for (swqos_type, submit_ms, total_ms) in
|
||||||
(SwqosType::Jito, 44.20, 44.20),
|
[(SwqosType::Jito, 44.20, 44.20), (SwqosType::Helius, 51.80, 51.80)]
|
||||||
(SwqosType::Helius, 51.80, 51.80),
|
{
|
||||||
] {
|
|
||||||
println!(
|
println!(
|
||||||
" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms",
|
" [SDK] {} {:?} submit: {:.4} ms, confirmed: -, total: {:.4} ms",
|
||||||
dir, swqos_type, submit_ms, total_ms
|
dir, swqos_type, submit_ms, total_ms
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
|
pub mod async_executor;
|
||||||
|
pub mod execution;
|
||||||
|
pub mod executor;
|
||||||
pub mod params;
|
pub mod params;
|
||||||
pub mod traits;
|
pub mod traits;
|
||||||
pub mod executor;
|
|
||||||
pub mod async_executor;
|
|
||||||
pub mod transaction_pool;
|
pub mod transaction_pool;
|
||||||
pub mod execution;
|
|
||||||
@@ -56,7 +56,8 @@ pub struct SwapParams {
|
|||||||
pub wait_transaction_confirmed: bool,
|
pub wait_transaction_confirmed: bool,
|
||||||
pub protocol_params: DexParamEnum,
|
pub protocol_params: DexParamEnum,
|
||||||
pub open_seed_optimize: bool,
|
pub open_seed_optimize: bool,
|
||||||
pub swqos_clients: Vec<Arc<SwqosClient>>,
|
/// Arc<Vec<..>> so cloning from infrastructure is a single Arc clone.
|
||||||
|
pub swqos_clients: Arc<Vec<Arc<SwqosClient>>>,
|
||||||
pub middleware_manager: Option<Arc<MiddlewareManager>>,
|
pub middleware_manager: Option<Arc<MiddlewareManager>>,
|
||||||
pub durable_nonce: Option<DurableNonceInfo>,
|
pub durable_nonce: Option<DurableNonceInfo>,
|
||||||
pub with_tip: bool,
|
pub with_tip: bool,
|
||||||
@@ -71,6 +72,10 @@ pub struct SwapParams {
|
|||||||
pub log_enabled: bool,
|
pub log_enabled: bool,
|
||||||
/// Whether to pin parallel submit tasks to cores (from TradeConfig.use_core_affinity).
|
/// Whether to pin parallel submit tasks to cores (from TradeConfig.use_core_affinity).
|
||||||
pub use_core_affinity: bool,
|
pub use_core_affinity: bool,
|
||||||
|
/// Use dedicated sender threads (from TradeConfig.use_dedicated_sender_threads).
|
||||||
|
pub use_dedicated_sender_threads: bool,
|
||||||
|
/// Core indices for dedicated sender threads (from TradeConfig.sender_thread_cores). Arc avoids cloning the Vec on hot path.
|
||||||
|
pub sender_thread_cores: Option<Arc<Vec<usize>>>,
|
||||||
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). When false, skip filter for lower latency.
|
/// Whether to check minimum tip per SWQOS (from TradeConfig.check_min_tip). When false, skip filter for lower latency.
|
||||||
pub check_min_tip: bool,
|
pub check_min_tip: bool,
|
||||||
/// Optional event receive time in microseconds (same scale as sol-parser-sdk clock::now_micros). Used as timing start when log_enabled.
|
/// Optional event receive time in microseconds (same scale as sol-parser-sdk clock::now_micros). Used as timing start when log_enabled.
|
||||||
|
|||||||
@@ -9,7 +9,10 @@ pub trait TradeExecutor: Send + Sync {
|
|||||||
/// - bool: 是否至少有一个交易成功
|
/// - bool: 是否至少有一个交易成功
|
||||||
/// - Vec<Signature>: 所有提交的交易签名(按SWQOS顺序)
|
/// - Vec<Signature>: 所有提交的交易签名(按SWQOS顺序)
|
||||||
/// - Option<anyhow::Error>: 最后一个错误(如果全部失败)
|
/// - Option<anyhow::Error>: 最后一个错误(如果全部失败)
|
||||||
async fn swap(&self, params: SwapParams) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)>;
|
async fn swap(
|
||||||
|
&self,
|
||||||
|
params: SwapParams,
|
||||||
|
) -> Result<(bool, Vec<Signature>, Option<anyhow::Error>)>;
|
||||||
/// 获取协议名称
|
/// 获取协议名称
|
||||||
fn protocol_name(&self) -> &'static str;
|
fn protocol_name(&self) -> &'static str;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -12,13 +12,18 @@ const TX_BUILDER_INSTRUCTION_CAP: usize = 32;
|
|||||||
const TX_BUILDER_LOOKUP_TABLE_CAP: usize = 8;
|
const TX_BUILDER_LOOKUP_TABLE_CAP: usize = 8;
|
||||||
/// 对象池最大容量
|
/// 对象池最大容量
|
||||||
const TX_BUILDER_POOL_CAP: usize = 1000;
|
const TX_BUILDER_POOL_CAP: usize = 1000;
|
||||||
/// 启动时预填充对象池数量
|
/// 多路提交并发数(与 async_executor SWQOS_DEDICATED_DEFAULT_THREADS 一致,保证不串行)
|
||||||
const TX_BUILDER_POOL_PREFILL: usize = 100;
|
const PARALLEL_SENDER_COUNT: usize = 18;
|
||||||
|
/// 启动时预填充数量,必须 >= PARALLEL_SENDER_COUNT,否则 18 路并发 build 会触发分配或争抢
|
||||||
|
const TX_BUILDER_POOL_PREFILL: usize = 64;
|
||||||
|
|
||||||
use crossbeam_queue::ArrayQueue;
|
use crossbeam_queue::ArrayQueue;
|
||||||
use once_cell::sync::Lazy;
|
use once_cell::sync::Lazy;
|
||||||
use solana_sdk::{
|
use solana_sdk::{
|
||||||
hash::Hash, instruction::Instruction, message::{v0, AddressLookupTableAccount, Message, VersionedMessage}, pubkey::Pubkey
|
hash::Hash,
|
||||||
|
instruction::Instruction,
|
||||||
|
message::{v0, AddressLookupTableAccount, Message, VersionedMessage},
|
||||||
|
pubkey::Pubkey,
|
||||||
};
|
};
|
||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
/// 预分配的交易构建器
|
/// 预分配的交易构建器
|
||||||
@@ -91,11 +96,8 @@ impl PreallocatedTxBuilder {
|
|||||||
VersionedMessage::V0(message)
|
VersionedMessage::V0(message)
|
||||||
} else {
|
} else {
|
||||||
// ✅ 没有查找表,使用 Legacy 消息(兼容所有 RPC)
|
// ✅ 没有查找表,使用 Legacy 消息(兼容所有 RPC)
|
||||||
let message = Message::new_with_blockhash(
|
let message =
|
||||||
&self.instructions,
|
Message::new_with_blockhash(&self.instructions, Some(payer), &recent_blockhash);
|
||||||
Some(payer),
|
|
||||||
&recent_blockhash,
|
|
||||||
);
|
|
||||||
VersionedMessage::Legacy(message)
|
VersionedMessage::Legacy(message)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -104,20 +106,17 @@ impl PreallocatedTxBuilder {
|
|||||||
/// 🚀 全局交易构建器对象池
|
/// 🚀 全局交易构建器对象池
|
||||||
static TX_BUILDER_POOL: Lazy<Arc<ArrayQueue<PreallocatedTxBuilder>>> = Lazy::new(|| {
|
static TX_BUILDER_POOL: Lazy<Arc<ArrayQueue<PreallocatedTxBuilder>>> = Lazy::new(|| {
|
||||||
let pool = ArrayQueue::new(TX_BUILDER_POOL_CAP);
|
let pool = ArrayQueue::new(TX_BUILDER_POOL_CAP);
|
||||||
|
let prefill = TX_BUILDER_POOL_PREFILL.max(PARALLEL_SENDER_COUNT);
|
||||||
for _ in 0..TX_BUILDER_POOL_PREFILL {
|
for _ in 0..prefill {
|
||||||
let _ = pool.push(PreallocatedTxBuilder::new());
|
let _ = pool.push(PreallocatedTxBuilder::new());
|
||||||
}
|
}
|
||||||
|
|
||||||
Arc::new(pool)
|
Arc::new(pool)
|
||||||
});
|
});
|
||||||
|
|
||||||
/// 🚀 从池中获取构建器
|
/// 🚀 从池中获取构建器
|
||||||
#[inline(always)]
|
#[inline(always)]
|
||||||
pub fn acquire_builder() -> PreallocatedTxBuilder {
|
pub fn acquire_builder() -> PreallocatedTxBuilder {
|
||||||
TX_BUILDER_POOL
|
TX_BUILDER_POOL.pop().unwrap_or_else(|| PreallocatedTxBuilder::new())
|
||||||
.pop()
|
|
||||||
.unwrap_or_else(|| PreallocatedTxBuilder::new())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 🚀 归还构建器到池
|
/// 🚀 归还构建器到池
|
||||||
@@ -139,9 +138,7 @@ pub struct TxBuilderGuard {
|
|||||||
|
|
||||||
impl TxBuilderGuard {
|
impl TxBuilderGuard {
|
||||||
pub fn new() -> Self {
|
pub fn new() -> Self {
|
||||||
Self {
|
Self { builder: Some(acquire_builder()) }
|
||||||
builder: Some(acquire_builder()),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn get_mut(&mut self) -> &mut PreallocatedTxBuilder {
|
pub fn get_mut(&mut self) -> &mut PreallocatedTxBuilder {
|
||||||
|
|||||||
@@ -1,4 +1,4 @@
|
|||||||
pub mod traits;
|
|
||||||
pub mod builtin;
|
pub mod builtin;
|
||||||
|
pub mod traits;
|
||||||
|
|
||||||
pub use traits::{InstructionMiddleware, MiddlewareManager};
|
pub use traits::{InstructionMiddleware, MiddlewareManager};
|
||||||
|
|||||||
@@ -76,11 +76,8 @@ impl MiddlewareManager {
|
|||||||
is_buy: bool,
|
is_buy: bool,
|
||||||
) -> Result<Vec<Instruction>> {
|
) -> Result<Vec<Instruction>> {
|
||||||
for middleware in &self.middlewares {
|
for middleware in &self.middlewares {
|
||||||
full_instructions = middleware.process_full_instructions(
|
full_instructions =
|
||||||
full_instructions,
|
middleware.process_full_instructions(full_instructions, protocol_name, is_buy)?;
|
||||||
protocol_name,
|
|
||||||
is_buy,
|
|
||||||
)?;
|
|
||||||
if full_instructions.is_empty() {
|
if full_instructions.is_empty() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
pub mod pumpfun;
|
|
||||||
pub mod common;
|
|
||||||
pub mod pumpswap;
|
|
||||||
pub mod bonk;
|
pub mod bonk;
|
||||||
|
pub mod common;
|
||||||
|
pub mod pumpfun;
|
||||||
|
pub mod pumpswap;
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod raydium_cpmm;
|
pub mod raydium_cpmm;
|
||||||
+21
-4
@@ -14,7 +14,8 @@ impl TradingClient {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn get_payer_sol_balance(&self) -> Result<u64, anyhow::Error> {
|
pub async fn get_payer_sol_balance(&self) -> Result<u64, anyhow::Error> {
|
||||||
trading::common::utils::get_sol_balance(&self.infrastructure.rpc, &self.payer.pubkey()).await
|
trading::common::utils::get_sol_balance(&self.infrastructure.rpc, &self.payer.pubkey())
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
@@ -28,7 +29,12 @@ impl TradingClient {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn get_payer_token_balance(&self, mint: &Pubkey) -> Result<u64, anyhow::Error> {
|
pub async fn get_payer_token_balance(&self, mint: &Pubkey) -> Result<u64, anyhow::Error> {
|
||||||
trading::common::utils::get_token_balance(&self.infrastructure.rpc, &self.payer.pubkey(), mint).await
|
trading::common::utils::get_token_balance(
|
||||||
|
&self.infrastructure.rpc,
|
||||||
|
&self.payer.pubkey(),
|
||||||
|
mint,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
/// 使用与交易一致的 ATA 推导(含 seed 优化)查询 payer 某 mint 的余额;卖出前查余额应使用此接口并传入池的 base_token_program,否则若使用 seed ATA 会查错账户。
|
/// 使用与交易一致的 ATA 推导(含 seed 优化)查询 payer 某 mint 的余额;卖出前查余额应使用此接口并传入池的 base_token_program,否则若使用 seed ATA 会查错账户。
|
||||||
@@ -65,11 +71,22 @@ impl TradingClient {
|
|||||||
receive_wallet: &Pubkey,
|
receive_wallet: &Pubkey,
|
||||||
amount: u64,
|
amount: u64,
|
||||||
) -> Result<(), anyhow::Error> {
|
) -> Result<(), anyhow::Error> {
|
||||||
trading::common::utils::transfer_sol(&self.infrastructure.rpc, payer, receive_wallet, amount).await
|
trading::common::utils::transfer_sol(
|
||||||
|
&self.infrastructure.rpc,
|
||||||
|
payer,
|
||||||
|
receive_wallet,
|
||||||
|
amount,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
pub async fn close_token_account(&self, mint: &Pubkey) -> Result<(), anyhow::Error> {
|
pub async fn close_token_account(&self, mint: &Pubkey) -> Result<(), anyhow::Error> {
|
||||||
trading::common::utils::close_token_account(&self.infrastructure.rpc, self.payer.as_ref(), mint).await
|
trading::common::utils::close_token_account(
|
||||||
|
&self.infrastructure.rpc,
|
||||||
|
self.payer.as_ref(),
|
||||||
|
mint,
|
||||||
|
)
|
||||||
|
.await
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
pub mod bonk;
|
pub mod bonk;
|
||||||
|
pub mod common;
|
||||||
pub mod pumpfun;
|
pub mod pumpfun;
|
||||||
pub mod pumpswap;
|
pub mod pumpswap;
|
||||||
pub mod raydium_amm_v4;
|
pub mod raydium_amm_v4;
|
||||||
pub mod raydium_clmm;
|
pub mod raydium_clmm;
|
||||||
pub mod raydium_cpmm;
|
pub mod raydium_cpmm;
|
||||||
pub mod common;
|
|
||||||
|
|||||||
Reference in New Issue
Block a user