use std::time::Duration;
use reqwest::{header, StatusCode};
use tokio::time::sleep;
use crate::error::QuorumError;
use crate::tx::QuorumSerializableTransaction;
use crate::types::{
CongestionSignal, ExecuteRequest, ExecutionResult, HealthStatus, Objective, Strategy,
ValidatorInfo,
};
pub const DEFAULT_ENDPOINT: &str = "https://api.quorumlabs.xyz";
const DEFAULT_TIMEOUT_SECS: u64 = 30;
const DEFAULT_MAX_RETRIES: usize = 3;
const MAX_WIRE_TX_BASE64_LEN: usize = 4096;
const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
#[derive(serde::Deserialize)]
#[serde(untagged)]
enum ValidatorsResponse {
Enveloped {
validators: Vec<ValidatorInfo>,
},
Flat(Vec<ValidatorInfo>),
}
pub struct QuorumClientBuilder {
endpoint: String,
timeout: Duration,
max_retries: usize,
api_key: Option<String>,
}
impl Default for QuorumClientBuilder {
fn default() -> Self {
Self::new()
}
}
impl QuorumClientBuilder {
pub fn new() -> Self {
let endpoint = std::env::var("QUORUM_API_URL")
.or_else(|_| std::env::var("QUORUM_ENDPOINT"))
.unwrap_or_else(|_| DEFAULT_ENDPOINT.to_string());
let api_key = std::env::var("QUORUM_API_KEY").ok();
Self {
endpoint,
timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
max_retries: DEFAULT_MAX_RETRIES,
api_key,
}
}
pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
self.endpoint = endpoint.into();
self
}
pub fn timeout(mut self, timeout: Duration) -> Self {
self.timeout = timeout;
self
}
pub fn max_retries(mut self, retries: usize) -> Self {
self.max_retries = retries;
self
}
pub fn api_key(mut self, key: impl Into<String>) -> Self {
self.api_key = Some(key.into());
self
}
pub fn build(self) -> Result<QuorumClient, QuorumError> {
let endpoint = self.endpoint.trim_end_matches('/').to_string();
url::Url::parse(&endpoint).map_err(|e| QuorumError::UrlParse(e.to_string()))?;
let mut headers = header::HeaderMap::new();
headers.insert(
header::USER_AGENT,
header::HeaderValue::from_static("quorum-rust-sdk/0.1.0"),
);
headers.insert(
header::ACCEPT,
header::HeaderValue::from_static("application/json"),
);
if let Some(key) = &self.api_key {
let value = header::HeaderValue::from_str(key)
.map_err(|_| QuorumError::UrlParse("invalid characters in API key".into()))?;
headers.insert("X-Api-Key", value);
}
let http = reqwest::Client::builder()
.timeout(self.timeout)
.default_headers(headers)
.build()
.map_err(QuorumError::Http)?;
Ok(QuorumClient {
endpoint,
http,
max_retries: self.max_retries,
})
}
}
pub struct QuorumClient {
endpoint: String,
http: reqwest::Client,
max_retries: usize,
}
impl Default for QuorumClient {
fn default() -> Self {
Self::new(DEFAULT_ENDPOINT)
}
}
impl std::fmt::Debug for QuorumClient {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("QuorumClient")
.field("endpoint", &"[REDACTED]")
.field("max_retries", &self.max_retries)
.finish()
}
}
impl QuorumClient {
pub fn new(endpoint: impl Into<String>) -> Self {
QuorumClient::builder()
.endpoint(endpoint)
.build()
.expect("invalid endpoint URL passed to QuorumClient::new")
}
pub fn try_new(endpoint: impl Into<String>) -> Result<Self, QuorumError> {
QuorumClient::builder().endpoint(endpoint).build()
}
pub fn from_env() -> Result<Self, QuorumError> {
QuorumClient::builder().build()
}
pub fn with_timeout(endpoint: impl Into<String>, timeout: Duration) -> Self {
QuorumClient::builder()
.endpoint(endpoint)
.timeout(timeout)
.build()
.expect("invalid endpoint URL passed to QuorumClient::with_timeout")
}
pub fn try_with_timeout(
endpoint: impl Into<String>,
timeout: Duration,
) -> Result<Self, QuorumError> {
QuorumClient::builder()
.endpoint(endpoint)
.timeout(timeout)
.build()
}
pub fn builder() -> QuorumClientBuilder {
QuorumClientBuilder::new()
}
pub async fn execute(
&self,
tx: &(impl QuorumSerializableTransaction + ?Sized),
objective: Objective,
) -> Result<ExecutionResult, QuorumError> {
let wire_b64 = tx.to_wire_base64()?;
self.execute_encoded(&wire_b64, objective).await
}
pub async fn execute_encoded(
&self,
wire_tx_b64: &str,
objective: Objective,
) -> Result<ExecutionResult, QuorumError> {
if wire_tx_b64.is_empty() {
return Err(QuorumError::Serialization("wire transaction is empty".into()));
}
if wire_tx_b64.len() > MAX_WIRE_TX_BASE64_LEN {
return Err(QuorumError::Serialization(
"wire transaction exceeds maximum allowed size".into(),
));
}
let body = ExecuteRequest {
wire_transaction_b64: wire_tx_b64.to_string(),
objective,
};
let url = format!("{}/v1/execute", self.endpoint);
self.post_with_retry(&url, &body).await
}
pub async fn get_recommended_fee(
&self,
objective: Objective,
) -> Result<u64, QuorumError> {
let strategy = self.get_strategy(objective).await?;
Ok(strategy.recommended_fee_microlamports)
}
pub async fn get_strategy(&self, objective: Objective) -> Result<Strategy, QuorumError> {
let url = format!("{}/v1/strategy?objective={}", self.endpoint, objective);
self.get_with_retry(&url).await
}
pub async fn get_validators(&self) -> Result<Vec<ValidatorInfo>, QuorumError> {
let url = format!("{}/v1/validators", self.endpoint);
let resp: ValidatorsResponse = self.get_with_retry(&url).await?;
match resp {
ValidatorsResponse::Enveloped { validators } => Ok(validators),
ValidatorsResponse::Flat(validators) => Ok(validators),
}
}
pub async fn get_congestion(&self) -> Result<CongestionSignal, QuorumError> {
let url = format!("{}/v1/congestion", self.endpoint);
self.get_with_retry(&url).await
}
pub async fn health(&self) -> Result<HealthStatus, QuorumError> {
let url = format!("{}/v1/health", self.endpoint);
self.get_with_retry(&url).await
}
async fn get_with_retry<T: serde::de::DeserializeOwned>(
&self,
url: &str,
) -> Result<T, QuorumError> {
let mut last_error = QuorumError::MaxRetriesExceeded {
attempts: 0,
last_error: String::new(),
};
for attempt in 0..=self.max_retries {
match self.http.get(url).send().await {
Ok(response) => {
let status = response.status();
if is_retryable_status(status) {
let retry_after = parse_retry_after(&response);
let raw_text = response
.text()
.await
.unwrap_or_else(|_| "<no body>".into());
last_error = QuorumError::Api {
status: status.as_u16(),
message: crate::utils::sanitize_text(&raw_text),
};
if attempt < self.max_retries {
let delay = retry_after.unwrap_or_else(|| {
Duration::from_millis(100u64 * (1 << attempt))
});
sleep(delay).await;
}
continue;
}
return Self::parse_json(response).await;
}
Err(e) => {
last_error = QuorumError::Http(e);
if attempt < self.max_retries {
sleep(Duration::from_millis(100u64 * (1 << attempt))).await;
}
continue;
}
}
}
Err(QuorumError::MaxRetriesExceeded {
attempts: self.max_retries,
last_error: last_error.to_string(),
})
}
async fn post_with_retry<B: serde::Serialize, T: serde::de::DeserializeOwned>(
&self,
url: &str,
body: &B,
) -> Result<T, QuorumError> {
let mut last_error = QuorumError::MaxRetriesExceeded {
attempts: 0,
last_error: String::new(),
};
for attempt in 0..=self.max_retries {
match self.http.post(url).json(body).send().await {
Ok(response) => {
let status = response.status();
if is_retryable_status(status) {
let retry_after = parse_retry_after(&response);
let raw_text = response
.text()
.await
.unwrap_or_else(|_| "<no body>".into());
last_error = QuorumError::Api {
status: status.as_u16(),
message: crate::utils::sanitize_text(&raw_text),
};
if attempt < self.max_retries {
let delay = retry_after.unwrap_or_else(|| {
Duration::from_millis(100u64 * (1 << attempt))
});
sleep(delay).await;
}
continue;
}
return Self::parse_json(response).await;
}
Err(e) => {
last_error = QuorumError::Http(e);
if attempt < self.max_retries {
sleep(Duration::from_millis(100u64 * (1 << attempt))).await;
}
continue;
}
}
}
Err(QuorumError::MaxRetriesExceeded {
attempts: self.max_retries,
last_error: last_error.to_string(),
})
}
async fn parse_json<T: serde::de::DeserializeOwned>(
response: reqwest::Response,
) -> Result<T, QuorumError> {
let status = response.status();
if !status.is_success() {
let message = response
.text()
.await
.unwrap_or_else(|_| "<no response body>".into());
return Err(QuorumError::Api {
status: status.as_u16(),
message: crate::utils::sanitize_text(&message),
});
}
let bytes = response.bytes().await?;
if bytes.len() > MAX_RESPONSE_BYTES {
return Err(QuorumError::InvalidResponse(
"response payload exceeded maximum allowed limit".into(),
));
}
serde_json::from_slice(&bytes)
.map_err(|e| QuorumError::InvalidResponse(e.to_string()))
}
}
fn is_retryable_status(status: StatusCode) -> bool {
status == StatusCode::TOO_MANY_REQUESTS || status == StatusCode::SERVICE_UNAVAILABLE
}
fn parse_retry_after(response: &reqwest::Response) -> Option<Duration> {
response
.headers()
.get(reqwest::header::RETRY_AFTER)
.and_then(|val| val.to_str().ok())
.and_then(|s| s.parse::<u64>().ok())
.map(Duration::from_secs)
}