Compare commits
5 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 07e45d136f | |||
| 20d053bab3 | |||
| 5d921f23ff | |||
| a187126554 | |||
| 6ea8c27824 |
+9
-27
@@ -1,30 +1,12 @@
|
||||
# Generated by Cargo
|
||||
# will have compiled files and executables
|
||||
debug/
|
||||
target/
|
||||
# Proto 生成工具和生成的代码(用户不需要)
|
||||
/proto/gen/
|
||||
|
||||
# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries
|
||||
# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html
|
||||
# 预生成的 proto Rust 代码(提交到仓库,但用户不应修改)
|
||||
# /src/swqos/pb/serverpb.rs <- 这个文件已经提交,用户不应修改
|
||||
|
||||
# Build artifacts
|
||||
/target/
|
||||
Cargo.lock
|
||||
|
||||
# These are backup files generated by rustfmt
|
||||
**/*.rs.bk
|
||||
|
||||
# MSVC Windows builds of rustc generate these, which store debugging information
|
||||
*.pdb
|
||||
|
||||
# RustRover
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
|
||||
.cargo/
|
||||
|
||||
tmp_*.rs
|
||||
tmp_*.log
|
||||
|
||||
|
||||
.claude/
|
||||
.serena/
|
||||
# Proto sources
|
||||
/proto/
|
||||
|
||||
+5
-1
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sol-trade-sdk"
|
||||
version = "3.6.5"
|
||||
version = "4.0.0"
|
||||
edition = "2021"
|
||||
authors = [
|
||||
"William <byteblock6@gmail.com>",
|
||||
@@ -135,6 +135,10 @@ incremental = true # 增量编译 - 大幅加速重新编译
|
||||
opt-level = 1 # 开发时适度优化
|
||||
overflow-checks = true # 开发时启用溢出检查
|
||||
|
||||
# 🚀 构建依赖
|
||||
# 注意:proto 代码已预生成在 src/swqos/pb/serverpb.rs
|
||||
# 开发者如需重新生成代码,请运行 gen_proto 目录下的工具
|
||||
|
||||
# 🚀 性能关键依赖的特殊优化
|
||||
[profile.release.package.solana-sdk]
|
||||
opt-level = 3
|
||||
|
||||
@@ -90,14 +90,14 @@ Add the dependency to your `Cargo.toml`:
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.4" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.0" }
|
||||
```
|
||||
|
||||
### Use crates.io
|
||||
|
||||
```toml
|
||||
# Add to your Cargo.toml
|
||||
sol-trade-sdk = "3.6.4"
|
||||
sol-trade-sdk = "4.0.0"
|
||||
```
|
||||
|
||||
## 🛠️ Usage Examples
|
||||
|
||||
+2
-2
@@ -90,14 +90,14 @@ git clone https://github.com/0xfnzero/sol-trade-sdk
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "3.6.4" }
|
||||
sol-trade-sdk = { path = "./sol-trade-sdk", version = "4.0.0" }
|
||||
```
|
||||
|
||||
### 使用 crates.io
|
||||
|
||||
```toml
|
||||
# 添加到您的 Cargo.toml
|
||||
sol-trade-sdk = "3.6.4"
|
||||
sol-trade-sdk = "4.0.0"
|
||||
```
|
||||
|
||||
## 🛠️ 使用示例
|
||||
|
||||
@@ -1,8 +0,0 @@
|
||||
# Release v3.6.4
|
||||
|
||||
## Changes from v3.6.3
|
||||
|
||||
- **Examples**: All workspace examples are verified to build successfully (`cargo build --workspace`).
|
||||
- **Docs**: Version references in README.md and README_CN.md updated to 3.6.4.
|
||||
|
||||
No API or behavior changes in this release.
|
||||
@@ -111,6 +111,7 @@ pub const BLOCKRAZOR_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("AP6qExwrbRgBAVaehg4b5xHENX815sMabtBzUzVB4v8S"),
|
||||
];
|
||||
|
||||
/// Astralane tip wallets. Extended with new addresses for improved routing and reduced write-lock contention (see portal.astralane.io/blockline).
|
||||
pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("astrazznxsGUhWShqgNtAdfrzP2G83DzcWVJDxwV9bF"),
|
||||
pubkey!("astra4uejePWneqNaJKuFFA8oonqCE1sqF6b45kDMZm"),
|
||||
@@ -120,6 +121,16 @@ pub const ASTRALANE_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
pubkey!("astraubkDw81n4LuutzSQ8uzHCv4BhPVhfvTcYv8SKC"),
|
||||
pubkey!("astraZW5GLFefxNPAatceHhYjfA1ciq9gvfEg2S47xk"),
|
||||
pubkey!("astrawVNP4xDBKT7rAdxrLYiTSTdqtUr63fSMduivXK"),
|
||||
// New tip wallets (2025) for improved performance and reduced write-lock delays
|
||||
pubkey!("AstrA1ejL4UeXC2SBP4cpeEmtcFPZVLxx3XGKXyCW6to"),
|
||||
pubkey!("AsTra79FET4aCKWspPqeSFvjJNyp96SvAnrmyAxqg5b7"),
|
||||
pubkey!("AstrABAu8CBTyuPXpV4eSCJ5fePEPnxN8NqBaPKQ9fHR"),
|
||||
pubkey!("AsTRADtvb6tTmrsqULQ9Wji9PigDMjhfEMza6zkynEvV"),
|
||||
pubkey!("AsTRAEoyMofR3vUPpf9k68Gsfb6ymTZttEtsAbv8Bk4d"),
|
||||
pubkey!("AStrAJv2RN2hKCHxwUMtqmSxgdcNZbihCwc1mCSnG83W"),
|
||||
pubkey!("Astran35aiQUF57XZsmkWMtNCtXGLzs8upfiqXxth2bz"),
|
||||
pubkey!("AStRAnpi6kFrKypragExgeRoJ1QnKH7pbSjLAKQVWUum"),
|
||||
pubkey!("ASTRaoF93eYt73TYvwtsv6fMWHWbGmMUZfVZPo3CRU9C"),
|
||||
];
|
||||
|
||||
pub const STELLIUM_TIP_ACCOUNTS: &[Pubkey] = &[
|
||||
|
||||
+292
-100
@@ -17,15 +17,91 @@ use crate::{common::SolanaRpcClient, constants::swqos::BLOCKRAZOR_TIP_ACCOUNTS};
|
||||
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tokio::task::JoinHandle;
|
||||
use tonic::transport::Channel;
|
||||
use tonic::metadata::AsciiMetadataValue;
|
||||
|
||||
// Include pre-generated gRPC code
|
||||
pub mod serverpb {
|
||||
include!("pb/serverpb.rs");
|
||||
}
|
||||
|
||||
// gRPC client wrapper
|
||||
#[derive(Clone)]
|
||||
pub struct BlockRazorGrpcClient {
|
||||
channel: Channel,
|
||||
auth_token: String,
|
||||
}
|
||||
|
||||
impl BlockRazorGrpcClient {
|
||||
pub fn new(channel: Channel, auth_token: String) -> Self {
|
||||
Self { channel, auth_token }
|
||||
}
|
||||
|
||||
pub async fn get_health(&self) -> Result<String> {
|
||||
let mut client = serverpb::server_client::ServerClient::new(self.channel.clone());
|
||||
let apikey = AsciiMetadataValue::try_from(self.auth_token.as_str())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid API key format: {}", e))?;
|
||||
|
||||
let mut request = tonic::Request::new(serverpb::HealthRequest {});
|
||||
request.metadata_mut().insert("apikey", apikey);
|
||||
|
||||
let response = client.get_health(request).await
|
||||
.map_err(|e| anyhow::anyhow!("gRPC health check failed: {}", e))?;
|
||||
Ok(response.into_inner().status)
|
||||
}
|
||||
|
||||
pub async fn send_transaction(
|
||||
&self,
|
||||
transaction: String,
|
||||
mode: String,
|
||||
safe_window: Option<i32>,
|
||||
revert_protection: bool,
|
||||
) -> Result<String> {
|
||||
// 检查交易数据大小
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor transaction size: {} bytes", transaction.len());
|
||||
}
|
||||
|
||||
let mut client = serverpb::server_client::ServerClient::new(self.channel.clone());
|
||||
let apikey = AsciiMetadataValue::try_from(self.auth_token.as_str())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid API key format: {}", e))?;
|
||||
|
||||
let mut request = tonic::Request::new(serverpb::SendRequest {
|
||||
transaction,
|
||||
mode: String::from(mode),
|
||||
safe_window,
|
||||
revert_protection,
|
||||
});
|
||||
request.metadata_mut().insert("apikey", apikey);
|
||||
|
||||
let response = client.send_transaction(request).await
|
||||
.map_err(|e| anyhow::anyhow!("gRPC send transaction failed: {}", e))?;
|
||||
Ok(response.into_inner().signature)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub enum BlockRazorBackend {
|
||||
Grpc {
|
||||
endpoint: String,
|
||||
auth_token: String,
|
||||
grpc_client: Arc<BlockRazorGrpcClient>,
|
||||
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
stop_ping: Arc<AtomicBool>,
|
||||
},
|
||||
Http {
|
||||
endpoint: String,
|
||||
auth_token: String,
|
||||
http_client: Client,
|
||||
ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
stop_ping: Arc<AtomicBool>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct BlockRazorClient {
|
||||
pub endpoint: String,
|
||||
pub auth_token: String,
|
||||
pub rpc_client: Arc<SolanaRpcClient>,
|
||||
pub http_client: Client,
|
||||
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
pub stop_ping: Arc<AtomicBool>,
|
||||
backend: BlockRazorBackend,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -36,7 +112,7 @@ impl SwqosClientTrait for BlockRazorClient {
|
||||
transaction: &VersionedTransaction,
|
||||
wait_confirmation: bool,
|
||||
) -> Result<()> {
|
||||
self.send_transaction(trade_type, transaction, wait_confirmation).await
|
||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await
|
||||
}
|
||||
|
||||
async fn send_transactions(
|
||||
@@ -45,7 +121,10 @@ impl SwqosClientTrait for BlockRazorClient {
|
||||
transactions: &Vec<VersionedTransaction>,
|
||||
wait_confirmation: bool,
|
||||
) -> Result<()> {
|
||||
self.send_transactions(trade_type, transactions, wait_confirmation).await
|
||||
for transaction in transactions {
|
||||
self.send_transaction_impl(trade_type, transaction, wait_confirmation).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn get_tip_account(&self) -> Result<String> {
|
||||
@@ -62,21 +141,62 @@ impl SwqosClientTrait for BlockRazorClient {
|
||||
}
|
||||
|
||||
impl BlockRazorClient {
|
||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||
pub async fn new(rpc_url: String, endpoint: String, auth_token: String) -> Result<Self> {
|
||||
// 默认使用 HTTP 模式,避免 gRPC FRAME_SIZE_ERROR
|
||||
Ok(Self::new_http(rpc_url, endpoint, auth_token))
|
||||
}
|
||||
|
||||
pub async fn new_grpc(rpc_url: String, endpoint: String, auth_token: String) -> Result<Self> {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
// 官方文档:請求中唯一允許的 header 是 Content-Type: text/plain;避免默认 User-Agent 等导致 500
|
||||
let http_client = default_http_client_builder().user_agent("").build().unwrap();
|
||||
|
||||
// 配置 Channel,增加连接超时
|
||||
let channel = tonic::transport::Channel::from_shared(endpoint.clone())
|
||||
.map_err(|e| anyhow::anyhow!("Invalid gRPC endpoint: {}", e))?
|
||||
.timeout(Duration::from_secs(30))
|
||||
.connect()
|
||||
.await
|
||||
.map_err(|e| anyhow::anyhow!("Failed to connect to gRPC endpoint: {}", e))?;
|
||||
|
||||
let grpc_client = Arc::new(BlockRazorGrpcClient::new(channel, auth_token.clone()));
|
||||
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
|
||||
let stop_ping = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||
backend: BlockRazorBackend::Grpc {
|
||||
endpoint,
|
||||
auth_token,
|
||||
grpc_client,
|
||||
ping_handle,
|
||||
stop_ping,
|
||||
},
|
||||
};
|
||||
|
||||
let client_clone = client.clone();
|
||||
tokio::spawn(async move {
|
||||
client_clone.start_ping_task().await;
|
||||
});
|
||||
|
||||
Ok(client)
|
||||
}
|
||||
|
||||
pub fn new_http(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let http_client = default_http_client_builder().user_agent("").build().unwrap();
|
||||
let ping_handle = Arc::new(tokio::sync::Mutex::new(None));
|
||||
let stop_ping = Arc::new(AtomicBool::new(false));
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
backend: BlockRazorBackend::Http {
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle,
|
||||
stop_ping,
|
||||
},
|
||||
};
|
||||
|
||||
// Start ping task
|
||||
let client_clone = client.clone();
|
||||
tokio::spawn(async move {
|
||||
client_clone.start_ping_task().await;
|
||||
@@ -85,47 +205,87 @@ impl BlockRazorClient {
|
||||
client
|
||||
}
|
||||
|
||||
/// Start periodic ping task to keep connections active
|
||||
async fn start_ping_task(&self) {
|
||||
let endpoint = self.endpoint.clone();
|
||||
let auth_token = self.auth_token.clone();
|
||||
let http_client = self.http_client.clone();
|
||||
let stop_ping = self.stop_ping.clone();
|
||||
match &self.backend {
|
||||
BlockRazorBackend::Grpc {
|
||||
grpc_client,
|
||||
ping_handle,
|
||||
stop_ping,
|
||||
..
|
||||
} => {
|
||||
let grpc_client = grpc_client.clone();
|
||||
let ping_handle = ping_handle.clone();
|
||||
let stop_ping = stop_ping.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
// Immediate first ping to warm connection and reduce first-submit cold start latency
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive to avoid server ~5min idle close
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await
|
||||
{
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor ping request failed: {}", e);
|
||||
let handle = tokio::spawn(async move {
|
||||
if let Err(e) = grpc_client.get_health().await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor gRPC ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = grpc_client.get_health().await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor gRPC ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Update ping_handle - use Mutex to safely update
|
||||
{
|
||||
let mut ping_guard = self.ping_handle.lock().await;
|
||||
if let Some(old_handle) = ping_guard.as_ref() {
|
||||
old_handle.abort();
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(old_handle) = ping_guard.as_ref() {
|
||||
old_handle.abort();
|
||||
}
|
||||
*ping_guard = Some(handle);
|
||||
}
|
||||
BlockRazorBackend::Http {
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle,
|
||||
stop_ping,
|
||||
} => {
|
||||
let endpoint = endpoint.clone();
|
||||
let auth_token = auth_token.clone();
|
||||
let http_client = http_client.clone();
|
||||
let ping_handle = ping_handle.clone();
|
||||
let stop_ping = stop_ping.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor HTTP ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30));
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = Self::send_http_ping(&http_client, &endpoint, &auth_token).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("BlockRazor HTTP ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(old_handle) = ping_guard.as_ref() {
|
||||
old_handle.abort();
|
||||
}
|
||||
*ping_guard = Some(handle);
|
||||
}
|
||||
*ping_guard = Some(handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Send ping request: POST /v2/health?auth=... (Keep Alive). Only required param: auth.
|
||||
async fn send_ping_request(
|
||||
async fn send_http_ping(
|
||||
http_client: &Client,
|
||||
endpoint: &str,
|
||||
auth_token: &str,
|
||||
@@ -142,51 +302,94 @@ impl BlockRazorClient {
|
||||
let status = response.status();
|
||||
let _ = response.bytes().await;
|
||||
if !status.is_success() {
|
||||
eprintln!("BlockRazor ping request failed with status: {}", status);
|
||||
eprintln!("BlockRazor HTTP ping request failed with status: {}", status);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Send transaction via v2 API: plain Base64 body, Content-Type: text/plain. Only required URI param: auth.
|
||||
/// 文档要求:auth 以 URI 参数传入;body 为纯 Base64 编码交易;唯一允许的 header 为 Content-Type: text/plain。
|
||||
pub async fn send_transaction(
|
||||
async fn send_transaction_impl(
|
||||
&self,
|
||||
trade_type: TradeType,
|
||||
transaction: &VersionedTransaction,
|
||||
wait_confirmation: bool,
|
||||
) -> Result<()> {
|
||||
let start_time = Instant::now();
|
||||
let (content, signature) =
|
||||
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||
|
||||
let response = self
|
||||
.http_client
|
||||
.post(&self.endpoint)
|
||||
.query(&[("auth", self.auth_token.as_str())])
|
||||
.header("Content-Type", "text/plain")
|
||||
.body(content)
|
||||
.send()
|
||||
.await?;
|
||||
match &self.backend {
|
||||
BlockRazorBackend::Grpc {
|
||||
grpc_client,
|
||||
..
|
||||
} => {
|
||||
let (content, _signature) =
|
||||
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
let _ = response.bytes().await;
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submitted("blockrazor", trade_type, start_time.elapsed());
|
||||
let signature = grpc_client.send_transaction(
|
||||
content,
|
||||
"fast".to_string(),
|
||||
None,
|
||||
false,
|
||||
).await;
|
||||
match signature {
|
||||
Ok(sig) => {
|
||||
if !sig.is_empty() {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submitted("BlockRazor", trade_type, start_time.elapsed());
|
||||
}
|
||||
} else {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), "empty signature".to_string());
|
||||
}
|
||||
return Err(anyhow::anyhow!("BlockRazor gRPC returned empty signature"));
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("BlockRazor", trade_type, start_time.elapsed(), format!("gRPC error: {}", e));
|
||||
}
|
||||
return Err(anyhow::anyhow!("BlockRazor gRPC sendTransaction failed: {}", e));
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("blockrazor", trade_type, start_time.elapsed(), format!("status {} body: {}", status, body));
|
||||
BlockRazorBackend::Http {
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
..
|
||||
} => {
|
||||
let (content, _signature) =
|
||||
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||
|
||||
let response = http_client
|
||||
.post(endpoint)
|
||||
.query(&[("auth", auth_token.as_str())])
|
||||
.header("Content-Type", "text/plain")
|
||||
.body(content)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
let status = response.status();
|
||||
if status.is_success() {
|
||||
let _ = response.bytes().await;
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submitted("blockrazor", trade_type, start_time.elapsed());
|
||||
}
|
||||
} else {
|
||||
let body = response.text().await.unwrap_or_default();
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("blockrazor", trade_type, start_time.elapsed(), format!("status {} body: {}", status, body));
|
||||
}
|
||||
return Err(anyhow::anyhow!(
|
||||
"BlockRazor HTTP sendTransaction failed: status {} body: {}",
|
||||
status,
|
||||
body
|
||||
));
|
||||
}
|
||||
}
|
||||
return Err(anyhow::anyhow!(
|
||||
"BlockRazor sendTransaction failed: status {} body: {}",
|
||||
status,
|
||||
body
|
||||
));
|
||||
}
|
||||
|
||||
let start_time = Instant::now();
|
||||
let signature = transaction.signatures[0];
|
||||
|
||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
@@ -210,34 +413,23 @@ impl BlockRazorClient {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_transactions(
|
||||
&self,
|
||||
trade_type: TradeType,
|
||||
transactions: &Vec<VersionedTransaction>,
|
||||
wait_confirmation: bool,
|
||||
) -> Result<()> {
|
||||
for transaction in transactions {
|
||||
self.send_transaction(trade_type, transaction, wait_confirmation).await?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for BlockRazorClient {
|
||||
fn drop(&mut self) {
|
||||
// Ensure ping task stops when client is destroyed
|
||||
self.stop_ping.store(true, Ordering::Relaxed);
|
||||
match &self.backend {
|
||||
BlockRazorBackend::Grpc { stop_ping, ping_handle, .. } | BlockRazorBackend::Http { stop_ping, ping_handle, .. } => {
|
||||
stop_ping.store(true, Ordering::Relaxed);
|
||||
|
||||
// Try to stop ping task immediately
|
||||
// Use tokio::spawn to avoid blocking Drop
|
||||
let ping_handle = self.ping_handle.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(handle) = ping_guard.as_ref() {
|
||||
handle.abort();
|
||||
let ping_handle = ping_handle.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(handle) = ping_guard.as_ref() {
|
||||
handle.abort();
|
||||
}
|
||||
*ping_guard = None;
|
||||
});
|
||||
}
|
||||
*ping_guard = None;
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+19
-8
@@ -224,8 +224,8 @@ pub enum SwqosConfig {
|
||||
Node1(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||
/// FlashBlock(api_token, region, custom_url)
|
||||
FlashBlock(String, SwqosRegion, Option<String>),
|
||||
/// BlockRazor(api_token, region, custom_url)
|
||||
BlockRazor(String, SwqosRegion, Option<String>),
|
||||
/// BlockRazor(api_token, region, custom_url, transport). transport=None => gRPC; Some(Http) => HTTP.
|
||||
BlockRazor(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||
/// Astralane(api_token, region, custom_url, transport). transport=None 表示 Http。
|
||||
Astralane(String, SwqosRegion, Option<String>, Option<SwqosTransport>),
|
||||
/// Stellium(api_token, region, custom_url)
|
||||
@@ -255,7 +255,7 @@ impl SwqosConfig {
|
||||
SwqosConfig::ZeroSlot(_, _, _) => SwqosType::ZeroSlot,
|
||||
SwqosConfig::Node1(_, _, _, _) => SwqosType::Node1,
|
||||
SwqosConfig::FlashBlock(_, _, _) => SwqosType::FlashBlock,
|
||||
SwqosConfig::BlockRazor(_, _, _) => SwqosType::BlockRazor,
|
||||
SwqosConfig::BlockRazor(_, _, _, _) => SwqosType::BlockRazor,
|
||||
SwqosConfig::Astralane(_, _, _, _) => SwqosType::Astralane,
|
||||
SwqosConfig::Stellium(_, _, _) => SwqosType::Stellium,
|
||||
SwqosConfig::Lightspeed(_, _, _) => SwqosType::Lightspeed,
|
||||
@@ -351,11 +351,22 @@ impl SwqosConfig {
|
||||
FlashBlockClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||
Ok(Arc::new(flashblock_client))
|
||||
}
|
||||
SwqosConfig::BlockRazor(auth_token, region, url) => {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
||||
let blockrazor_client =
|
||||
BlockRazorClient::new(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||
Ok(Arc::new(blockrazor_client))
|
||||
SwqosConfig::BlockRazor(auth_token, region, url, transport) => {
|
||||
// BlockRazor: transport=None 或 transport=Http 时使用 HTTP,否则使用 gRPC
|
||||
// 默认使用 HTTP,避免 gRPC FRAME_SIZE_ERROR
|
||||
let use_http = transport.map_or(true, |t| t == SwqosTransport::Http);
|
||||
if use_http {
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
||||
let blockrazor_client =
|
||||
BlockRazorClient::new_http(rpc_url.clone(), endpoint.to_string(), auth_token);
|
||||
Ok(Arc::new(blockrazor_client))
|
||||
} else {
|
||||
// 使用 gRPC 模式(用户明确指定了非 Http 的 transport)
|
||||
let endpoint = SwqosConfig::get_endpoint(SwqosType::BlockRazor, region, url);
|
||||
let blockrazor_client =
|
||||
BlockRazorClient::new_grpc(rpc_url.clone(), endpoint.to_string(), auth_token).await?;
|
||||
Ok(Arc::new(blockrazor_client))
|
||||
}
|
||||
}
|
||||
SwqosConfig::Astralane(auth_token, region, url, transport) => {
|
||||
let use_quic = transport.map_or(false, |t| t == SwqosTransport::Quic);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# Proto 生成的代码说明
|
||||
|
||||
## 概述
|
||||
|
||||
这个目录包含了从 `.proto` 文件预生成的 Rust 代码。
|
||||
|
||||
## 文件说明
|
||||
|
||||
- `serverpb.rs` - 从 `blockrazor.proto` 生成的 gRPC 代码
|
||||
- 消息类型: `SendRequest`, `SendResponse`, `HealthRequest`, `HealthResponse`
|
||||
- gRPC 客户端: `server_client::ServerClient`
|
||||
- gRPC 服务端: `server_server::Server`
|
||||
|
||||
## 用户使用
|
||||
|
||||
用户**不需要**安装 `protoc` 或编译 proto 文件。这些代码已经预生成好了,可以直接使用。
|
||||
|
||||
在 `blockrazor.rs` 中使用:
|
||||
```rust
|
||||
pub mod serverpb {
|
||||
include!("pb/serverpb.rs");
|
||||
}
|
||||
```
|
||||
|
||||
## 开发者如何重新生成代码
|
||||
|
||||
如果你修改了 `.proto` 文件并需要重新生成代码:
|
||||
|
||||
```bash
|
||||
cd sol-trade-sdk/proto/gen
|
||||
cargo run
|
||||
```
|
||||
|
||||
这会在 `src/swqos/pb/serverpb.rs` 生成新的代码。
|
||||
|
||||
## 技术细节
|
||||
|
||||
生成工具使用 `tonic-prost-build` crate:
|
||||
- 输出目录: `src/swqos/pb`
|
||||
- Proto 文件: `proto/blockrazor.proto`
|
||||
- 生成工具: `proto/gen/`
|
||||
- 包含完整的客户端和服务端代码
|
||||
@@ -0,0 +1,383 @@
|
||||
// This file is @generated by prost-build.
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct SendRequest {
|
||||
#[prost(string, tag = "1")]
|
||||
pub transaction: ::prost::alloc::string::String,
|
||||
#[prost(string, tag = "2")]
|
||||
pub mode: ::prost::alloc::string::String,
|
||||
/// only take effect in sandwichMitigation mode
|
||||
#[prost(int32, optional, tag = "3")]
|
||||
pub safe_window: ::core::option::Option<i32>,
|
||||
#[prost(bool, tag = "4")]
|
||||
pub revert_protection: bool,
|
||||
}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct SendResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
pub signature: ::prost::alloc::string::String,
|
||||
}
|
||||
#[derive(Clone, Copy, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct HealthRequest {}
|
||||
#[derive(Clone, PartialEq, Eq, Hash, ::prost::Message)]
|
||||
pub struct HealthResponse {
|
||||
#[prost(string, tag = "1")]
|
||||
pub status: ::prost::alloc::string::String,
|
||||
}
|
||||
/// Generated client implementations.
|
||||
pub mod server_client {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value,
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
use tonic::codegen::http::Uri;
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ServerClient<T> {
|
||||
inner: tonic::client::Grpc<T>,
|
||||
}
|
||||
impl ServerClient<tonic::transport::Channel> {
|
||||
/// Attempt to create a new client by connecting to a given endpoint.
|
||||
pub async fn connect<D>(dst: D) -> Result<Self, tonic::transport::Error>
|
||||
where
|
||||
D: TryInto<tonic::transport::Endpoint>,
|
||||
D::Error: Into<StdError>,
|
||||
{
|
||||
let conn = tonic::transport::Endpoint::new(dst)?.connect().await?;
|
||||
Ok(Self::new(conn))
|
||||
}
|
||||
}
|
||||
impl<T> ServerClient<T>
|
||||
where
|
||||
T: tonic::client::GrpcService<tonic::body::Body>,
|
||||
T::Error: Into<StdError>,
|
||||
T::ResponseBody: Body<Data = Bytes> + std::marker::Send + 'static,
|
||||
<T::ResponseBody as Body>::Error: Into<StdError> + std::marker::Send,
|
||||
{
|
||||
pub fn new(inner: T) -> Self {
|
||||
let inner = tonic::client::Grpc::new(inner);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_origin(inner: T, origin: Uri) -> Self {
|
||||
let inner = tonic::client::Grpc::with_origin(inner, origin);
|
||||
Self { inner }
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> ServerClient<InterceptedService<T, F>>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
T::ResponseBody: Default,
|
||||
T: tonic::codegen::Service<
|
||||
http::Request<tonic::body::Body>,
|
||||
Response = http::Response<
|
||||
<T as tonic::client::GrpcService<tonic::body::Body>>::ResponseBody,
|
||||
>,
|
||||
>,
|
||||
<T as tonic::codegen::Service<
|
||||
http::Request<tonic::body::Body>,
|
||||
>>::Error: Into<StdError> + std::marker::Send + std::marker::Sync,
|
||||
{
|
||||
ServerClient::new(InterceptedService::new(inner, interceptor))
|
||||
}
|
||||
/// Compress requests with the given encoding.
|
||||
///
|
||||
/// This requires the server to support it otherwise it might respond with an
|
||||
/// error.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.send_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Enable decompressing responses.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.inner = self.inner.accept_compressed(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_decoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.inner = self.inner.max_encoding_message_size(limit);
|
||||
self
|
||||
}
|
||||
pub async fn send_transaction(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::SendRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::SendResponse>, tonic::Status> {
|
||||
self.inner
|
||||
.ready()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tonic::Status::unknown(
|
||||
format!("Service was not ready: {}", e.into()),
|
||||
)
|
||||
})?;
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/serverpb.Server/SendTransaction",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut()
|
||||
.insert(GrpcMethod::new("serverpb.Server", "SendTransaction"));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
pub async fn get_health(
|
||||
&mut self,
|
||||
request: impl tonic::IntoRequest<super::HealthRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::HealthResponse>, tonic::Status> {
|
||||
self.inner
|
||||
.ready()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
tonic::Status::unknown(
|
||||
format!("Service was not ready: {}", e.into()),
|
||||
)
|
||||
})?;
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let path = http::uri::PathAndQuery::from_static(
|
||||
"/serverpb.Server/GetHealth",
|
||||
);
|
||||
let mut req = request.into_request();
|
||||
req.extensions_mut().insert(GrpcMethod::new("serverpb.Server", "GetHealth"));
|
||||
self.inner.unary(req, path, codec).await
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated server implementations.
|
||||
pub mod server_server {
|
||||
#![allow(
|
||||
unused_variables,
|
||||
dead_code,
|
||||
missing_docs,
|
||||
clippy::wildcard_imports,
|
||||
clippy::let_unit_value,
|
||||
)]
|
||||
use tonic::codegen::*;
|
||||
/// Generated trait containing gRPC methods that should be implemented for use with ServerServer.
|
||||
#[async_trait]
|
||||
pub trait Server: std::marker::Send + std::marker::Sync + 'static {
|
||||
async fn send_transaction(
|
||||
&self,
|
||||
request: tonic::Request<super::SendRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::SendResponse>, tonic::Status>;
|
||||
async fn get_health(
|
||||
&self,
|
||||
request: tonic::Request<super::HealthRequest>,
|
||||
) -> std::result::Result<tonic::Response<super::HealthResponse>, tonic::Status>;
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub struct ServerServer<T> {
|
||||
inner: Arc<T>,
|
||||
accept_compression_encodings: EnabledCompressionEncodings,
|
||||
send_compression_encodings: EnabledCompressionEncodings,
|
||||
max_decoding_message_size: Option<usize>,
|
||||
max_encoding_message_size: Option<usize>,
|
||||
}
|
||||
impl<T> ServerServer<T> {
|
||||
pub fn new(inner: T) -> Self {
|
||||
Self::from_arc(Arc::new(inner))
|
||||
}
|
||||
pub fn from_arc(inner: Arc<T>) -> Self {
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: Default::default(),
|
||||
send_compression_encodings: Default::default(),
|
||||
max_decoding_message_size: None,
|
||||
max_encoding_message_size: None,
|
||||
}
|
||||
}
|
||||
pub fn with_interceptor<F>(
|
||||
inner: T,
|
||||
interceptor: F,
|
||||
) -> InterceptedService<Self, F>
|
||||
where
|
||||
F: tonic::service::Interceptor,
|
||||
{
|
||||
InterceptedService::new(Self::new(inner), interceptor)
|
||||
}
|
||||
/// Enable decompressing requests with the given encoding.
|
||||
#[must_use]
|
||||
pub fn accept_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.accept_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Compress responses with the given encoding, if the client supports it.
|
||||
#[must_use]
|
||||
pub fn send_compressed(mut self, encoding: CompressionEncoding) -> Self {
|
||||
self.send_compression_encodings.enable(encoding);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of a decoded message.
|
||||
///
|
||||
/// Default: `4MB`
|
||||
#[must_use]
|
||||
pub fn max_decoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_decoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
/// Limits the maximum size of an encoded message.
|
||||
///
|
||||
/// Default: `usize::MAX`
|
||||
#[must_use]
|
||||
pub fn max_encoding_message_size(mut self, limit: usize) -> Self {
|
||||
self.max_encoding_message_size = Some(limit);
|
||||
self
|
||||
}
|
||||
}
|
||||
impl<T, B> tonic::codegen::Service<http::Request<B>> for ServerServer<T>
|
||||
where
|
||||
T: Server,
|
||||
B: Body + std::marker::Send + 'static,
|
||||
B::Error: Into<StdError> + std::marker::Send + 'static,
|
||||
{
|
||||
type Response = http::Response<tonic::body::Body>;
|
||||
type Error = std::convert::Infallible;
|
||||
type Future = BoxFuture<Self::Response, Self::Error>;
|
||||
fn poll_ready(
|
||||
&mut self,
|
||||
_cx: &mut Context<'_>,
|
||||
) -> Poll<std::result::Result<(), Self::Error>> {
|
||||
Poll::Ready(Ok(()))
|
||||
}
|
||||
fn call(&mut self, req: http::Request<B>) -> Self::Future {
|
||||
match req.uri().path() {
|
||||
"/serverpb.Server/SendTransaction" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct SendTransactionSvc<T: Server>(pub Arc<T>);
|
||||
impl<T: Server> tonic::server::UnaryService<super::SendRequest>
|
||||
for SendTransactionSvc<T> {
|
||||
type Response = super::SendResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
tonic::Status,
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::SendRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as Server>::send_transaction(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = SendTransactionSvc(inner);
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
"/serverpb.Server/GetHealth" => {
|
||||
#[allow(non_camel_case_types)]
|
||||
struct GetHealthSvc<T: Server>(pub Arc<T>);
|
||||
impl<T: Server> tonic::server::UnaryService<super::HealthRequest>
|
||||
for GetHealthSvc<T> {
|
||||
type Response = super::HealthResponse;
|
||||
type Future = BoxFuture<
|
||||
tonic::Response<Self::Response>,
|
||||
tonic::Status,
|
||||
>;
|
||||
fn call(
|
||||
&mut self,
|
||||
request: tonic::Request<super::HealthRequest>,
|
||||
) -> Self::Future {
|
||||
let inner = Arc::clone(&self.0);
|
||||
let fut = async move {
|
||||
<T as Server>::get_health(&inner, request).await
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
}
|
||||
let accept_compression_encodings = self.accept_compression_encodings;
|
||||
let send_compression_encodings = self.send_compression_encodings;
|
||||
let max_decoding_message_size = self.max_decoding_message_size;
|
||||
let max_encoding_message_size = self.max_encoding_message_size;
|
||||
let inner = self.inner.clone();
|
||||
let fut = async move {
|
||||
let method = GetHealthSvc(inner);
|
||||
let codec = tonic_prost::ProstCodec::default();
|
||||
let mut grpc = tonic::server::Grpc::new(codec)
|
||||
.apply_compression_config(
|
||||
accept_compression_encodings,
|
||||
send_compression_encodings,
|
||||
)
|
||||
.apply_max_message_size_config(
|
||||
max_decoding_message_size,
|
||||
max_encoding_message_size,
|
||||
);
|
||||
let res = grpc.unary(method, req).await;
|
||||
Ok(res)
|
||||
};
|
||||
Box::pin(fut)
|
||||
}
|
||||
_ => {
|
||||
Box::pin(async move {
|
||||
let mut response = http::Response::new(
|
||||
tonic::body::Body::default(),
|
||||
);
|
||||
let headers = response.headers_mut();
|
||||
headers
|
||||
.insert(
|
||||
tonic::Status::GRPC_STATUS,
|
||||
(tonic::Code::Unimplemented as i32).into(),
|
||||
);
|
||||
headers
|
||||
.insert(
|
||||
http::header::CONTENT_TYPE,
|
||||
tonic::metadata::GRPC_CONTENT_TYPE,
|
||||
);
|
||||
Ok(response)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl<T> Clone for ServerServer<T> {
|
||||
fn clone(&self) -> Self {
|
||||
let inner = self.inner.clone();
|
||||
Self {
|
||||
inner,
|
||||
accept_compression_encodings: self.accept_compression_encodings,
|
||||
send_compression_encodings: self.send_compression_encodings,
|
||||
max_decoding_message_size: self.max_decoding_message_size,
|
||||
max_encoding_message_size: self.max_encoding_message_size,
|
||||
}
|
||||
}
|
||||
}
|
||||
/// Generated gRPC service name
|
||||
pub const SERVICE_NAME: &str = "serverpb.Server";
|
||||
impl<T> tonic::server::NamedService for ServerServer<T> {
|
||||
const NAME: &'static str = SERVICE_NAME;
|
||||
}
|
||||
}
|
||||
+158
-33
@@ -1,12 +1,12 @@
|
||||
use crate::swqos::common::{
|
||||
default_http_client_builder, poll_transaction_confirmation, serialize_transaction_and_encode,
|
||||
default_http_client_builder, poll_transaction_confirmation,
|
||||
};
|
||||
use rand::seq::IndexedRandom;
|
||||
use reqwest::Client;
|
||||
use serde_json::json;
|
||||
use std::{sync::Arc, time::Instant};
|
||||
|
||||
use solana_transaction_status::UiTransactionEncoding;
|
||||
use std::{sync::Arc, time::Instant, time::Duration};
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
use tokio::task::JoinHandle;
|
||||
use bincode;
|
||||
|
||||
use crate::swqos::SwqosClientTrait;
|
||||
use crate::swqos::{SwqosType, TradeType};
|
||||
@@ -21,6 +21,8 @@ pub struct ZeroSlotClient {
|
||||
pub auth_token: String,
|
||||
pub rpc_client: Arc<SolanaRpcClient>,
|
||||
pub http_client: Client,
|
||||
pub ping_handle: Arc<tokio::sync::Mutex<Option<JoinHandle<()>>>>,
|
||||
pub stop_ping: Arc<AtomicBool>,
|
||||
}
|
||||
|
||||
#[async_trait::async_trait]
|
||||
@@ -60,7 +62,79 @@ impl ZeroSlotClient {
|
||||
pub fn new(rpc_url: String, endpoint: String, auth_token: String) -> Self {
|
||||
let rpc_client = SolanaRpcClient::new(rpc_url);
|
||||
let http_client = default_http_client_builder().build().unwrap();
|
||||
Self { rpc_client: Arc::new(rpc_client), endpoint, auth_token, http_client }
|
||||
|
||||
let client = Self {
|
||||
rpc_client: Arc::new(rpc_client),
|
||||
endpoint,
|
||||
auth_token,
|
||||
http_client,
|
||||
ping_handle: Arc::new(tokio::sync::Mutex::new(None)),
|
||||
stop_ping: Arc::new(AtomicBool::new(false)),
|
||||
};
|
||||
|
||||
// Start ping task
|
||||
let client_clone = client.clone();
|
||||
tokio::spawn(async move {
|
||||
client_clone.start_ping_task().await;
|
||||
});
|
||||
|
||||
client
|
||||
}
|
||||
|
||||
/// Start periodic ping task to keep connections active
|
||||
async fn start_ping_task(&self) {
|
||||
let endpoint = self.endpoint.clone();
|
||||
let auth_token = self.auth_token.clone();
|
||||
let http_client = self.http_client.clone();
|
||||
let stop_ping = self.stop_ping.clone();
|
||||
|
||||
let handle = tokio::spawn(async move {
|
||||
// Immediate first ping to warm connection and reduce first-submit cold start latency
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("0slot ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
let mut interval = tokio::time::interval(Duration::from_secs(30)); // 30s keepalive under 65s server timeout
|
||||
loop {
|
||||
interval.tick().await;
|
||||
if stop_ping.load(Ordering::Relaxed) {
|
||||
break;
|
||||
}
|
||||
if let Err(e) = Self::send_ping_request(&http_client, &endpoint, &auth_token).await {
|
||||
if crate::common::sdk_log::sdk_log_enabled() {
|
||||
eprintln!("0slot ping request failed: {}", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// Update ping_handle - use Mutex to safely update
|
||||
{
|
||||
let mut ping_guard = self.ping_handle.lock().await;
|
||||
if let Some(old_handle) = ping_guard.as_ref() {
|
||||
old_handle.abort();
|
||||
}
|
||||
*ping_guard = Some(handle);
|
||||
}
|
||||
}
|
||||
|
||||
/// Send ping request: POST with getHealth method (Keep Alive). Free operation, not counted toward TPS.
|
||||
async fn send_ping_request(
|
||||
http_client: &Client,
|
||||
endpoint: &str,
|
||||
auth_token: &str,
|
||||
) -> Result<()> {
|
||||
let url = format!("{}/?api-key={}", endpoint, auth_token);
|
||||
let response = http_client
|
||||
.post(&url)
|
||||
.header("Content-Type", "application/json")
|
||||
.timeout(Duration::from_millis(1500))
|
||||
.body(r#"{"jsonrpc":"2.0","id":1,"method":"getHealth"}"#)
|
||||
.send()
|
||||
.await?;
|
||||
let _ = response.bytes().await;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn send_transaction(
|
||||
@@ -70,47 +144,80 @@ impl ZeroSlotClient {
|
||||
wait_confirmation: bool,
|
||||
) -> Result<()> {
|
||||
let start_time = Instant::now();
|
||||
let (content, signature) =
|
||||
serialize_transaction_and_encode(transaction, UiTransactionEncoding::Base64)?;
|
||||
|
||||
let request_body = serde_json::to_string(&json!({
|
||||
"jsonrpc": "2.0",
|
||||
"id": 1,
|
||||
"method": "sendTransaction",
|
||||
"params": [
|
||||
content,
|
||||
{ "encoding": "base64", "skipPreflight": true }
|
||||
]
|
||||
}))?;
|
||||
// Binary-Tx: Send raw binary transaction bytes directly
|
||||
// This is faster than JSON-RPC as it avoids unnecessary encoding/decoding
|
||||
let tx_bytes = bincode::serialize(transaction)?;
|
||||
|
||||
// Build URL for Binary-Tx endpoint: {endpoint}/txb?api-key={auth_token}
|
||||
let mut url = String::with_capacity(self.endpoint.len() + self.auth_token.len() + 20);
|
||||
url.push_str(&self.endpoint);
|
||||
url.push_str("/?api-key=");
|
||||
url.push_str("/txb?api-key=");
|
||||
url.push_str(&self.auth_token);
|
||||
|
||||
// 4. Use `text().await?` directly, avoiding async JSON parsing from `json().await?`
|
||||
let response_text = self
|
||||
// Send binary transaction directly
|
||||
let response = self
|
||||
.http_client
|
||||
.post(&url)
|
||||
.body(request_body) // Pass string directly, avoiding `json()` overhead
|
||||
.header("Content-Type", "application/json") // Explicitly specify JSON header
|
||||
.header("User-Agent", "") // Optional: 0slot recommends empty User-Agent
|
||||
.body(tx_bytes)
|
||||
.send()
|
||||
.await?
|
||||
.text()
|
||||
.await?;
|
||||
|
||||
// 5. Use `serde_json::from_str()` to parse JSON, reducing extra wait from `.json().await?`
|
||||
if let Ok(response_json) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||
if response_json.get("result").is_some() {
|
||||
crate::common::sdk_log::log_swqos_submitted("0slot", trade_type, start_time.elapsed());
|
||||
} else if let Some(_error) = response_json.get("error") {
|
||||
eprintln!(" [0slot] {} submission failed after {:?}: {:?}", trade_type, start_time.elapsed(), _error);
|
||||
let status = response.status();
|
||||
let response_text = response.text().await?;
|
||||
|
||||
// Binary-Tx returns JSON-RPC 2.0 format responses
|
||||
// 200: success with result field containing signature, or error field with code/message
|
||||
// 403: api-key error (null, doesn't exist, or expired)
|
||||
// 419: rate limit exceeded
|
||||
// 500: submission failed
|
||||
match status.as_u16() {
|
||||
200 => {
|
||||
if let Ok(json_value) = serde_json::from_str::<serde_json::Value>(&response_text) {
|
||||
if json_value.get("result").is_some() {
|
||||
crate::common::sdk_log::log_swqos_submitted("0slot", trade_type, start_time.elapsed());
|
||||
} else if let Some(error) = json_value.get("error") {
|
||||
let code = error.get("code")
|
||||
.and_then(|c| c.as_i64())
|
||||
.map(|c| c.to_string())
|
||||
.unwrap_or_else(|| "unknown".to_string());
|
||||
let message = error.get("message")
|
||||
.and_then(|m| m.as_str())
|
||||
.unwrap_or("unknown error");
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("code {}: {}", code, message));
|
||||
return Err(anyhow::anyhow!("0slot Binary-Tx error: {}", message));
|
||||
} else {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("unexpected JSON: {}", response_text));
|
||||
return Err(anyhow::anyhow!("0slot Binary-Tx unexpected JSON: {}", response_text));
|
||||
}
|
||||
} else {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("invalid JSON: {}", response_text));
|
||||
return Err(anyhow::anyhow!("0slot Binary-Tx invalid JSON: {}", response_text));
|
||||
}
|
||||
}
|
||||
403 => {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
|
||||
return Err(anyhow::anyhow!("0slot API key error: {}", response_text));
|
||||
}
|
||||
419 => {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text.clone());
|
||||
return Err(anyhow::anyhow!("0slot rate limit exceeded"));
|
||||
}
|
||||
500 => {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), "submission failed".to_string());
|
||||
return Err(anyhow::anyhow!("0slot transaction submission failed"));
|
||||
}
|
||||
_ => {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), format!("status {} body: {}", status, response_text));
|
||||
return Err(anyhow::anyhow!("0slot Binary-Tx failed with status {}: {}", status, response_text));
|
||||
}
|
||||
} else {
|
||||
crate::common::sdk_log::log_swqos_submission_failed("0slot", trade_type, start_time.elapsed(), response_text);
|
||||
}
|
||||
|
||||
let start_time: Instant = Instant::now();
|
||||
// Get transaction signature from the transaction for confirmation polling
|
||||
let signature = transaction.signatures[0];
|
||||
|
||||
let start_time = Instant::now();
|
||||
match poll_transaction_confirmation(&self.rpc_client, signature, wait_confirmation).await {
|
||||
Ok(_) => (),
|
||||
Err(e) => {
|
||||
@@ -139,3 +246,21 @@ impl ZeroSlotClient {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for ZeroSlotClient {
|
||||
fn drop(&mut self) {
|
||||
// Ensure ping task stops when client is destroyed
|
||||
self.stop_ping.store(true, Ordering::Relaxed);
|
||||
|
||||
// Try to stop ping task immediately
|
||||
// Use tokio::spawn to avoid blocking Drop
|
||||
let ping_handle = self.ping_handle.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut ping_guard = ping_handle.lock().await;
|
||||
if let Some(handle) = ping_guard.as_ref() {
|
||||
handle.abort();
|
||||
}
|
||||
*ping_guard = None;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user