1use std::time::Duration;
2
3use reqwest::{header, StatusCode};
4use tokio::time::sleep;
5
6use crate::error::QuorumError;
7use crate::tx::QuorumSerializableTransaction;
8use crate::types::{
9 CongestionSignal, ExecuteRequest, ExecutionResult, HealthStatus, Objective, Strategy,
10 ValidatorInfo,
11};
12
13pub const DEFAULT_ENDPOINT: &str = "https://api.quorumlabs.xyz";
14const DEFAULT_TIMEOUT_SECS: u64 = 30;
15const DEFAULT_MAX_RETRIES: usize = 3;
16const MAX_WIRE_TX_BASE64_LEN: usize = 4096;
17const MAX_RESPONSE_BYTES: usize = 1024 * 1024;
18
19#[derive(serde::Deserialize)]
20#[serde(untagged)]
21enum ValidatorsResponse {
22 Enveloped {
23 validators: Vec<ValidatorInfo>,
24 },
25 Flat(Vec<ValidatorInfo>),
26}
27
28pub struct QuorumClientBuilder {
29 endpoint: String,
30 timeout: Duration,
31 max_retries: usize,
32 api_key: Option<String>,
33}
34
35impl Default for QuorumClientBuilder {
36 fn default() -> Self {
37 Self::new()
38 }
39}
40
41impl QuorumClientBuilder {
42 pub fn new() -> Self {
43 let endpoint = std::env::var("QUORUM_API_URL")
44 .or_else(|_| std::env::var("QUORUM_ENDPOINT"))
45 .unwrap_or_else(|_| DEFAULT_ENDPOINT.to_string());
46
47 let api_key = std::env::var("QUORUM_API_KEY").ok();
48
49 Self {
50 endpoint,
51 timeout: Duration::from_secs(DEFAULT_TIMEOUT_SECS),
52 max_retries: DEFAULT_MAX_RETRIES,
53 api_key,
54 }
55 }
56
57 pub fn endpoint(mut self, endpoint: impl Into<String>) -> Self {
58 self.endpoint = endpoint.into();
59 self
60 }
61
62 pub fn timeout(mut self, timeout: Duration) -> Self {
63 self.timeout = timeout;
64 self
65 }
66
67 pub fn max_retries(mut self, retries: usize) -> Self {
68 self.max_retries = retries;
69 self
70 }
71
72 pub fn api_key(mut self, key: impl Into<String>) -> Self {
73 self.api_key = Some(key.into());
74 self
75 }
76
77 pub fn build(self) -> Result<QuorumClient, QuorumError> {
78 let endpoint = self.endpoint.trim_end_matches('/').to_string();
79 url::Url::parse(&endpoint).map_err(|e| QuorumError::UrlParse(e.to_string()))?;
80
81 let mut headers = header::HeaderMap::new();
82 headers.insert(
83 header::USER_AGENT,
84 header::HeaderValue::from_static("quorum-rust-sdk/0.1.0"),
85 );
86 headers.insert(
87 header::ACCEPT,
88 header::HeaderValue::from_static("application/json"),
89 );
90
91 if let Some(key) = &self.api_key {
92 let value = header::HeaderValue::from_str(key)
93 .map_err(|_| QuorumError::UrlParse("invalid characters in API key".into()))?;
94 headers.insert("X-Api-Key", value);
95 }
96
97 let http = reqwest::Client::builder()
98 .timeout(self.timeout)
99 .default_headers(headers)
100 .build()
101 .map_err(QuorumError::Http)?;
102
103 Ok(QuorumClient {
104 endpoint,
105 http,
106 max_retries: self.max_retries,
107 })
108 }
109}
110
111pub struct QuorumClient {
112 endpoint: String,
113 http: reqwest::Client,
114 max_retries: usize,
115}
116
117impl Default for QuorumClient {
118 fn default() -> Self {
119 Self::new(DEFAULT_ENDPOINT)
120 }
121}
122
123impl std::fmt::Debug for QuorumClient {
124 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
125 f.debug_struct("QuorumClient")
126 .field("endpoint", &"[REDACTED]")
127 .field("max_retries", &self.max_retries)
128 .finish()
129 }
130}
131
132impl QuorumClient {
133 pub fn new(endpoint: impl Into<String>) -> Self {
138 QuorumClient::builder()
139 .endpoint(endpoint)
140 .build()
141 .expect("invalid endpoint URL passed to QuorumClient::new")
142 }
143
144 pub fn try_new(endpoint: impl Into<String>) -> Result<Self, QuorumError> {
146 QuorumClient::builder().endpoint(endpoint).build()
147 }
148
149 pub fn from_env() -> Result<Self, QuorumError> {
152 QuorumClient::builder().build()
153 }
154
155 pub fn with_timeout(endpoint: impl Into<String>, timeout: Duration) -> Self {
160 QuorumClient::builder()
161 .endpoint(endpoint)
162 .timeout(timeout)
163 .build()
164 .expect("invalid endpoint URL passed to QuorumClient::with_timeout")
165 }
166
167 pub fn try_with_timeout(
169 endpoint: impl Into<String>,
170 timeout: Duration,
171 ) -> Result<Self, QuorumError> {
172 QuorumClient::builder()
173 .endpoint(endpoint)
174 .timeout(timeout)
175 .build()
176 }
177
178 pub fn builder() -> QuorumClientBuilder {
179 QuorumClientBuilder::new()
180 }
181
182 pub async fn execute(
183 &self,
184 tx: &(impl QuorumSerializableTransaction + ?Sized),
185 objective: Objective,
186 ) -> Result<ExecutionResult, QuorumError> {
187 let wire_b64 = tx.to_wire_base64()?;
188 self.execute_encoded(&wire_b64, objective).await
189 }
190
191 pub async fn execute_encoded(
192 &self,
193 wire_tx_b64: &str,
194 objective: Objective,
195 ) -> Result<ExecutionResult, QuorumError> {
196 if wire_tx_b64.is_empty() {
197 return Err(QuorumError::Serialization("wire transaction is empty".into()));
198 }
199 if wire_tx_b64.len() > MAX_WIRE_TX_BASE64_LEN {
200 return Err(QuorumError::Serialization(
201 "wire transaction exceeds maximum allowed size".into(),
202 ));
203 }
204
205 let body = ExecuteRequest {
206 wire_transaction_b64: wire_tx_b64.to_string(),
207 objective,
208 };
209 let url = format!("{}/v1/execute", self.endpoint);
210 self.post_with_retry(&url, &body).await
211 }
212
213 pub async fn get_recommended_fee(
214 &self,
215 objective: Objective,
216 ) -> Result<u64, QuorumError> {
217 let strategy = self.get_strategy(objective).await?;
218 Ok(strategy.recommended_fee_microlamports)
219 }
220
221 pub async fn get_strategy(&self, objective: Objective) -> Result<Strategy, QuorumError> {
222 let url = format!("{}/v1/strategy?objective={}", self.endpoint, objective);
223 self.get_with_retry(&url).await
224 }
225
226 pub async fn get_validators(&self) -> Result<Vec<ValidatorInfo>, QuorumError> {
227 let url = format!("{}/v1/validators", self.endpoint);
228 let resp: ValidatorsResponse = self.get_with_retry(&url).await?;
229 match resp {
230 ValidatorsResponse::Enveloped { validators } => Ok(validators),
231 ValidatorsResponse::Flat(validators) => Ok(validators),
232 }
233 }
234
235 pub async fn get_congestion(&self) -> Result<CongestionSignal, QuorumError> {
236 let url = format!("{}/v1/congestion", self.endpoint);
237 self.get_with_retry(&url).await
238 }
239
240 pub async fn health(&self) -> Result<HealthStatus, QuorumError> {
241 let url = format!("{}/v1/health", self.endpoint);
242 self.get_with_retry(&url).await
243 }
244
245 async fn get_with_retry<T: serde::de::DeserializeOwned>(
246 &self,
247 url: &str,
248 ) -> Result<T, QuorumError> {
249 let mut last_error = QuorumError::MaxRetriesExceeded {
250 attempts: 0,
251 last_error: String::new(),
252 };
253
254 for attempt in 0..=self.max_retries {
255 match self.http.get(url).send().await {
256 Ok(response) => {
257 let status = response.status();
258 if is_retryable_status(status) {
259 let retry_after = parse_retry_after(&response);
260 let raw_text = response
261 .text()
262 .await
263 .unwrap_or_else(|_| "<no body>".into());
264 last_error = QuorumError::Api {
265 status: status.as_u16(),
266 message: crate::utils::sanitize_text(&raw_text),
267 };
268
269 if attempt < self.max_retries {
270 let delay = retry_after.unwrap_or_else(|| {
271 Duration::from_millis(100u64 * (1 << attempt))
272 });
273 sleep(delay).await;
274 }
275 continue;
276 }
277 return Self::parse_json(response).await;
278 }
279 Err(e) => {
280 last_error = QuorumError::Http(e);
281 if attempt < self.max_retries {
282 sleep(Duration::from_millis(100u64 * (1 << attempt))).await;
283 }
284 continue;
285 }
286 }
287 }
288
289 Err(QuorumError::MaxRetriesExceeded {
290 attempts: self.max_retries,
291 last_error: last_error.to_string(),
292 })
293 }
294
295 async fn post_with_retry<B: serde::Serialize, T: serde::de::DeserializeOwned>(
296 &self,
297 url: &str,
298 body: &B,
299 ) -> Result<T, QuorumError> {
300 let mut last_error = QuorumError::MaxRetriesExceeded {
301 attempts: 0,
302 last_error: String::new(),
303 };
304
305 for attempt in 0..=self.max_retries {
306 match self.http.post(url).json(body).send().await {
307 Ok(response) => {
308 let status = response.status();
309 if is_retryable_status(status) {
310 let retry_after = parse_retry_after(&response);
311 let raw_text = response
312 .text()
313 .await
314 .unwrap_or_else(|_| "<no body>".into());
315 last_error = QuorumError::Api {
316 status: status.as_u16(),
317 message: crate::utils::sanitize_text(&raw_text),
318 };
319
320 if attempt < self.max_retries {
321 let delay = retry_after.unwrap_or_else(|| {
322 Duration::from_millis(100u64 * (1 << attempt))
323 });
324 sleep(delay).await;
325 }
326 continue;
327 }
328 return Self::parse_json(response).await;
329 }
330 Err(e) => {
331 last_error = QuorumError::Http(e);
332 if attempt < self.max_retries {
333 sleep(Duration::from_millis(100u64 * (1 << attempt))).await;
334 }
335 continue;
336 }
337 }
338 }
339
340 Err(QuorumError::MaxRetriesExceeded {
341 attempts: self.max_retries,
342 last_error: last_error.to_string(),
343 })
344 }
345
346 async fn parse_json<T: serde::de::DeserializeOwned>(
347 response: reqwest::Response,
348 ) -> Result<T, QuorumError> {
349 let status = response.status();
350 if !status.is_success() {
351 let message = response
352 .text()
353 .await
354 .unwrap_or_else(|_| "<no response body>".into());
355 return Err(QuorumError::Api {
356 status: status.as_u16(),
357 message: crate::utils::sanitize_text(&message),
358 });
359 }
360 let bytes = response.bytes().await?;
361 if bytes.len() > MAX_RESPONSE_BYTES {
362 return Err(QuorumError::InvalidResponse(
363 "response payload exceeded maximum allowed limit".into(),
364 ));
365 }
366 serde_json::from_slice(&bytes)
367 .map_err(|e| QuorumError::InvalidResponse(e.to_string()))
368 }
369}
370
371fn is_retryable_status(status: StatusCode) -> bool {
372 status == StatusCode::TOO_MANY_REQUESTS || status == StatusCode::SERVICE_UNAVAILABLE
373}
374
375fn parse_retry_after(response: &reqwest::Response) -> Option<Duration> {
376 response
377 .headers()
378 .get(reqwest::header::RETRY_AFTER)
379 .and_then(|val| val.to_str().ok())
380 .and_then(|s| s.parse::<u64>().ok())
381 .map(Duration::from_secs)
382}