fyuz-sdk 0.1.1

Async Rust client for the Fyuz public REST API — bonding-curve token market data on BNB Smart Chain.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
//! The HTTP client: construction, configuration and the retry loop.

use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::Arc;
use std::time::{Duration, SystemTime, UNIX_EPOCH};

use reqwest::header::{HeaderMap, HeaderName, HeaderValue, RETRY_AFTER};
use reqwest::{Method, StatusCode, Url};
use serde::de::DeserializeOwned;

use crate::api::distributor::Distributor;
use crate::error::{message_from_body, truncate, Error, Result};
use crate::rpc::DEFAULT_RPC_TIMEOUT;
use crate::trade::{TradeApi, TradeState};

/// Production base URL, used unless
/// [`FyuzClientBuilder::base_url`] overrides it.
pub const DEFAULT_BASE_URL: &str = "https://api.fyuz.fun";

/// Version of this crate, as reported in the `User-Agent`.
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Ceiling on any single response body this crate buffers, in bytes.
///
/// The largest honest response on this API is a page of tokens, comfortably
/// under 1 MiB. `reqwest` imposes no limit of its own, so without this a
/// hostile or broken endpoint can stream until the process runs out of memory —
/// and the excerpting in `Error` only shortens the *message*, long after the
/// whole body is already resident.
pub const MAX_RESPONSE_BYTES: usize = 1 << 20;

const DEFAULT_TIMEOUT: Duration = Duration::from_secs(30);
const DEFAULT_MAX_RETRIES: u32 = 3;
const DEFAULT_RETRY_BASE_DELAY: Duration = Duration::from_millis(250);
const DEFAULT_MAX_RETRY_DELAY: Duration = Duration::from_secs(8);

/// Query string pairs, in the order they will be encoded.
pub(crate) type QueryPairs = Vec<(&'static str, String)>;

/// Async client for the Fyuz public REST API.
///
/// Cloning is cheap — the underlying `reqwest::Client` and configuration are
/// shared behind an [`Arc`], and the connection pool is shared with it. Create
/// one per process and clone it around rather than building a new one per call.
///
/// ```no_run
/// # async fn demo() -> Result<(), fyuz::Error> {
/// use fyuz::{DiscoverParams, DiscoverTab, FyuzClient};
///
/// let client = FyuzClient::new()?;
///
/// let trending = client
///     .discover(&DiscoverParams::new().tab(DiscoverTab::Trending).limit(10))
///     .await?;
///
/// for token in &trending {
///     println!("{} {:.0}% to graduation", token.symbol, token.graduation_pct);
/// }
/// # Ok(())
/// # }
/// ```
#[derive(Debug, Clone)]
pub struct FyuzClient {
    inner: Arc<Inner>,
}

#[derive(Debug)]
struct Inner {
    http: reqwest::Client,
    base_url: Url,
    max_retries: u32,
    retry_base_delay: Duration,
    max_retry_delay: Duration,
    /// Jitter source. A tiny xorshift keeps `rand` out of the dependency list;
    /// nothing here is security sensitive.
    rng: AtomicU64,
    /// JSON-RPC override for the trading layer. `None` falls back to whatever
    /// `GET /config` publishes for the chain.
    rpc_url: Option<String>,
    /// Block tag every `eth_call` is evaluated against. `None` means `"latest"`.
    rpc_block: Option<String>,
    /// The transport every [`RpcClient`](crate::RpcClient) in the trading layer
    /// shares: one connection pool and one header set for every chain, built
    /// once here rather than per chain on first use.
    rpc_http: reqwest::Client,
    /// Memoised `/config` and the per-chain RPC clients.
    trade_state: TradeState,
}

impl FyuzClient {
    /// Build a client pointed at <https://api.fyuz.fun> with the default 30s
    /// timeout and 3 retries.
    ///
    /// ```no_run
    /// # async fn demo() -> Result<(), fyuz::Error> {
    /// let client = fyuz::FyuzClient::new()?;
    /// println!("{}", client.health().await?.status);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new() -> Result<Self> {
        Self::builder().build()
    }

    /// Start configuring a client.
    ///
    /// ```no_run
    /// # fn demo() -> Result<(), fyuz::Error> {
    /// use std::time::Duration;
    ///
    /// let client = fyuz::FyuzClient::builder()
    ///     .base_url("http://127.0.0.1:8080")?
    ///     .timeout(Duration::from_secs(5))
    ///     .max_retries(5)
    ///     .build()?;
    /// # let _ = client;
    /// # Ok(())
    /// # }
    /// ```
    pub fn builder() -> FyuzClientBuilder {
        FyuzClientBuilder::new()
    }

    /// The base URL every request is resolved against.
    pub fn base_url(&self) -> &Url {
        &self.inner.base_url
    }

    /// The Distributor endpoints (`/distributor/*`), grouped together.
    ///
    /// ```no_run
    /// # async fn demo() -> Result<(), fyuz::Error> {
    /// let client = fyuz::FyuzClient::new()?;
    /// let pot = client.distributor().get_pot().await?;
    /// match pot.pot_bnb {
    ///     Some(bnb) => println!("{bnb} BNB in the pot"),
    ///     // `None` means unknown, never zero.
    ///     None => println!("pot unavailable right now"),
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn distributor(&self) -> Distributor<'_> {
        Distributor::new(self)
    }

    /// Bonding-curve trading: quotes, and unsigned buy/sell/approve transactions.
    ///
    /// Builds transactions only — it never handles a key. See [`TradeApi`].
    ///
    /// ```no_run
    /// # async fn demo() -> Result<(), fyuz::Error> {
    /// use fyuz::{parse_units, BuyParams};
    ///
    /// let client = fyuz::FyuzClient::new()?;
    /// let built = client
    ///     .trade()
    ///     .build_buy(
    ///         &BuyParams::new("0x0000000000000000000000000000000000000001", parse_units("0.5", 18)?)
    ///             .slippage_bps(100),
    ///     )
    ///     .await?;
    /// println!("{}", built.transaction.data);
    /// # Ok(())
    /// # }
    /// ```
    pub fn trade(&self) -> TradeApi<'_> {
        TradeApi::new(self)
    }

    pub(crate) fn rpc_url(&self) -> Option<&str> {
        self.inner.rpc_url.as_deref()
    }

    pub(crate) fn rpc_block(&self) -> Option<&str> {
        self.inner.rpc_block.as_deref()
    }

    pub(crate) fn rpc_http(&self) -> &reqwest::Client {
        &self.inner.rpc_http
    }

    pub(crate) fn trade_state(&self) -> &TradeState {
        &self.inner.trade_state
    }

    pub(crate) async fn get_json<T: DeserializeOwned>(
        &self,
        path: &str,
        query: QueryPairs,
    ) -> Result<T> {
        self.request(Method::GET, path, query, None).await
    }

    pub(crate) async fn post_json<T: DeserializeOwned>(
        &self,
        path: &str,
        query: QueryPairs,
        body: serde_json::Value,
    ) -> Result<T> {
        self.request(Method::POST, path, query, Some(body)).await
    }

    async fn request<T: DeserializeOwned>(
        &self,
        method: Method,
        path: &str,
        query: QueryPairs,
        body: Option<serde_json::Value>,
    ) -> Result<T> {
        let bytes = self.send_with_retry(method, path, query, body).await?;
        serde_json::from_slice(&bytes).map_err(|e| Error::Decode {
            message: e.to_string(),
            body: truncate(String::from_utf8_lossy(&bytes).trim(), 256),
        })
    }

    /// Send, retrying 429s, 5xx and transport failures with exponential backoff
    /// and full jitter. 4xx statuses other than 429 return immediately.
    async fn send_with_retry(
        &self,
        method: Method,
        path: &str,
        query: QueryPairs,
        body: Option<serde_json::Value>,
    ) -> Result<Vec<u8>> {
        let url = build_url(&self.inner.base_url, path);
        let mut attempt: u32 = 0;

        loop {
            match self.attempt(&method, &url, &query, body.as_ref()).await {
                Ok(bytes) => return Ok(bytes),
                Err(Failure::Fatal(err)) => return Err(err),
                Err(Failure::Retryable { error, retry_after }) => {
                    if attempt >= self.inner.max_retries {
                        return Err(error);
                    }
                    let delay = match retry_after {
                        // `Retry-After` is the one delay an outside party
                        // chooses, so it is held to the same ceiling as the
                        // computed backoff — a hostile or buggy header must not
                        // be able to park the caller's task. The floor keeps
                        // `Retry-After: 0` from spinning the retries away with
                        // no sleep at all.
                        Some(after) => after
                            .max(self.inner.retry_base_delay)
                            .min(self.inner.max_retry_delay),
                        None => self.backoff(attempt),
                    };
                    tokio::time::sleep(delay).await;
                    attempt += 1;
                }
            }
        }
    }

    async fn attempt(
        &self,
        method: &Method,
        url: &Url,
        query: &QueryPairs,
        body: Option<&serde_json::Value>,
    ) -> std::result::Result<Vec<u8>, Failure> {
        let mut request = self.inner.http.request(method.clone(), url.clone());
        if !query.is_empty() {
            request = request.query(query);
        }
        if let Some(body) = body {
            request = request.json(body);
        }

        let response = match request.send().await {
            Ok(response) => response,
            Err(err) => {
                let retryable = err.is_timeout() || err.is_connect() || err.is_request();
                return Err(if retryable {
                    Failure::Retryable {
                        error: Error::Transport(err),
                        retry_after: None,
                    }
                } else {
                    Failure::Fatal(Error::Transport(err))
                });
            }
        };

        let status = response.status();
        let retry_after = parse_retry_after(response.headers());
        let bytes = match read_capped(response).await {
            Ok(bytes) => bytes,
            // The status line arrived but the body did not. For this read-only
            // API every request is safe to repeat, so treat it as retryable.
            Err(BodyError::Transport(err)) => {
                return Err(Failure::Retryable {
                    error: Error::Transport(err),
                    retry_after,
                })
            }
            // Not retryable: repeating the request gets the same oversized body,
            // and buffering it again is the thing the ceiling exists to prevent.
            Err(BodyError::TooLarge(seen)) => {
                return Err(Failure::Fatal(Error::Api {
                    status: status.as_u16(),
                    message: format!(
                        "response body is at least {seen} bytes, past the \
                         {MAX_RESPONSE_BYTES}-byte ceiling"
                    ),
                }))
            }
        };

        if status.is_success() {
            return Ok(bytes);
        }

        let message = message_from_body(&bytes, status);

        if status == StatusCode::TOO_MANY_REQUESTS {
            return Err(Failure::Retryable {
                error: Error::RateLimited {
                    message,
                    retry_after,
                },
                retry_after,
            });
        }

        let error = Error::Api {
            status: status.as_u16(),
            message,
        };

        Err(if status.is_server_error() {
            Failure::Retryable { error, retry_after }
        } else {
            Failure::Fatal(error)
        })
    }

    /// Full jitter: sleep a uniform random duration in `[0, cap]`, where `cap`
    /// doubles per attempt up to `max_retry_delay`.
    fn backoff(&self, attempt: u32) -> Duration {
        let factor = 1u32 << attempt.min(16);
        let cap = self
            .inner
            .retry_base_delay
            .saturating_mul(factor)
            .min(self.inner.max_retry_delay);
        let cap_ms = cap.as_millis() as u64;
        if cap_ms == 0 {
            return Duration::ZERO;
        }
        Duration::from_millis(self.next_random() % (cap_ms + 1))
    }

    /// xorshift64, seeded from the clock at construction time.
    ///
    /// The advance is a compare-and-swap, not a load/store pair: clones of one
    /// client share this state, and two tasks that read it concurrently would
    /// otherwise compute the same "jitter" and sleep in lockstep — exactly the
    /// thundering herd the jitter exists to break up.
    fn next_random(&self) -> u64 {
        let previous = self
            .inner
            .rng
            .fetch_update(Ordering::Relaxed, Ordering::Relaxed, |state| {
                Some(xorshift(state))
            })
            // The closure never returns `None`, so `fetch_update` cannot fail.
            .unwrap_or(1);
        xorshift(previous)
    }
}

/// One step of xorshift64. Zero is a fixed point, which the seed rules out.
fn xorshift(mut state: u64) -> u64 {
    state ^= state << 13;
    state ^= state >> 7;
    state ^= state << 17;
    state
}

/// Why a response body could not be buffered.
enum BodyError {
    /// The body passed [`MAX_RESPONSE_BYTES`]; the value is how far the read got.
    TooLarge(usize),
    /// The connection failed partway through the body.
    Transport(reqwest::Error),
}

/// Read a response body, refusing to buffer more than [`MAX_RESPONSE_BYTES`].
///
/// `Content-Length` is checked first so an oversized body costs nothing to
/// reject, but it is only a hint — a chunked response carries none, and a lying
/// one is free to send — so the accumulating read is what actually enforces the
/// bound.
async fn read_capped(mut response: reqwest::Response) -> std::result::Result<Vec<u8>, BodyError> {
    if let Some(declared) = response.content_length() {
        if declared > MAX_RESPONSE_BYTES as u64 {
            return Err(BodyError::TooLarge(declared as usize));
        }
    }

    let mut body: Vec<u8> = Vec::new();
    while let Some(chunk) = response.chunk().await.map_err(BodyError::Transport)? {
        if body.len() + chunk.len() > MAX_RESPONSE_BYTES {
            return Err(BodyError::TooLarge(body.len() + chunk.len()));
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

/// Outcome of one HTTP attempt that did not produce a usable body.
enum Failure {
    Fatal(Error),
    Retryable {
        error: Error,
        retry_after: Option<Duration>,
    },
}

/// Percent-encode one value for use as a single path segment.
///
/// Everything outside the RFC 3986 *unreserved* set is escaped, `/` included.
/// That is the point: [`build_url`] treats `/` as structure, so an unencoded one
/// inside a caller-supplied address would add a path segment and send the
/// request to a different endpoint than the method promises.
///
/// Encoding happens exactly once, here — [`build_url`] joins the result
/// verbatim rather than escaping the `%` a second time.
///
/// The one thing this cannot express is a segment that *is* `.` or `..`: the
/// URL standard resolves those away before any escaping is looked at, and every
/// `%2e` spelling with them. A value of `".."` therefore drops its own segment
/// rather than travelling as data. It costs the request, not the target of a
/// neighbouring endpoint, and no address or chain slug is ever spelled that way.
pub(crate) fn seg(value: &str) -> String {
    const HEX: &[u8; 16] = b"0123456789ABCDEF";

    let mut encoded = String::with_capacity(value.len());
    for byte in value.bytes() {
        match byte {
            b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => {
                encoded.push(byte as char)
            }
            _ => {
                encoded.push('%');
                encoded.push(HEX[usize::from(byte >> 4)] as char);
                encoded.push(HEX[usize::from(byte & 0x0f)] as char);
            }
        }
    }
    encoded
}

/// Join a `/`-separated path onto the base URL.
///
/// Segments arrive already encoded — the structural parts are ASCII literals in
/// this crate, and every caller-supplied value goes through [`seg`] first — so
/// they are joined as they are. `Url::set_path` leaves an existing `%XX` alone
/// and still escapes anything unsafe that reached it raw.
fn build_url(base: &Url, path: &str) -> Url {
    let mut url = base.clone();
    let mut joined = url.path().trim_end_matches('/').to_string();
    for segment in path.split('/').filter(|s| !s.is_empty()) {
        joined.push('/');
        joined.push_str(segment);
    }
    url.set_path(&joined);
    url
}

/// `Retry-After` in delta-seconds form. The HTTP-date form is ignored, which
/// falls the caller back onto ordinary exponential backoff.
fn parse_retry_after(headers: &reqwest::header::HeaderMap) -> Option<Duration> {
    let raw = headers.get(RETRY_AFTER)?.to_str().ok()?;
    let seconds: u64 = raw.trim().parse().ok()?;
    Some(Duration::from_secs(seconds))
}

/// Builder for [`FyuzClient`]. Created with [`FyuzClient::builder`].
#[derive(Debug, Clone)]
pub struct FyuzClientBuilder {
    base_url: Url,
    user_agent: String,
    timeout: Duration,
    max_retries: u32,
    retry_base_delay: Duration,
    max_retry_delay: Duration,
    rpc_url: Option<String>,
    rpc_timeout: Option<Duration>,
    rpc_block: Option<String>,
    rpc_headers: HeaderMap,
}

impl FyuzClientBuilder {
    /// A builder with every default in place: production base URL, 30s timeout,
    /// 3 retries.
    pub fn new() -> Self {
        Self {
            base_url: Url::parse(DEFAULT_BASE_URL).expect("DEFAULT_BASE_URL is a valid URL"),
            user_agent: format!("fyuz-sdk-rust/{VERSION}"),
            timeout: DEFAULT_TIMEOUT,
            max_retries: DEFAULT_MAX_RETRIES,
            retry_base_delay: DEFAULT_RETRY_BASE_DELAY,
            max_retry_delay: DEFAULT_MAX_RETRY_DELAY,
            rpc_url: None,
            rpc_timeout: None,
            rpc_block: None,
            rpc_headers: HeaderMap::new(),
        }
    }

    /// Point the client somewhere other than <https://api.fyuz.fun> — a staging
    /// host, a caching proxy, or a stub server in tests.
    ///
    /// A path prefix is respected: `http://gateway/fyuz/` sends `/health` to
    /// `http://gateway/fyuz/health`.
    pub fn base_url(mut self, base_url: &str) -> Result<Self> {
        let mut parsed = Url::parse(base_url).map_err(|e| Error::InvalidBaseUrl {
            url: base_url.to_string(),
            message: e.to_string(),
        })?;

        if parsed.cannot_be_a_base() {
            return Err(Error::InvalidBaseUrl {
                url: base_url.to_string(),
                message: "URL cannot be used as a base".to_string(),
            });
        }
        if !matches!(parsed.scheme(), "http" | "https") {
            return Err(Error::InvalidBaseUrl {
                url: base_url.to_string(),
                message: format!(
                    "unsupported scheme {:?}, expected http or https",
                    parsed.scheme()
                ),
            });
        }

        // Normalise to a trailing slash so path joining is unambiguous.
        if !parsed.path().ends_with('/') {
            let path = format!("{}/", parsed.path());
            parsed.set_path(&path);
        }

        self.base_url = parsed;
        Ok(self)
    }

    /// Override the `User-Agent`. Defaults to `fyuz-sdk-rust/<version>`.
    ///
    /// Identifying your application here is appreciated — it is what lets the
    /// Fyuz team raise your rate-limit allowance.
    pub fn user_agent(mut self, user_agent: impl Into<String>) -> Self {
        self.user_agent = user_agent.into();
        self
    }

    /// Per-request timeout, covering connect plus response body. Default 30s.
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = timeout;
        self
    }

    /// How many times to retry a 429, a 5xx or a transport failure. Default 3;
    /// `0` disables retrying entirely.
    ///
    /// One call therefore blocks for at most
    /// `max_retries × max_retry_delay` of waiting on top of the request time —
    /// 24s of waiting with the defaults.
    pub fn max_retries(mut self, max_retries: u32) -> Self {
        self.max_retries = max_retries;
        self
    }

    /// First backoff window. Attempt `n` sleeps a uniform random duration in
    /// `[0, base * 2^n]`, capped by [`max_retry_delay`](Self::max_retry_delay).
    /// Default 250ms.
    pub fn retry_base_delay(mut self, delay: Duration) -> Self {
        self.retry_base_delay = delay;
        self
    }

    /// Ceiling on a single wait between attempts. Default 8s.
    ///
    /// This bounds *every* delay the client takes, the computed backoff window
    /// and a server's `Retry-After` alike. A server that asks for longer than
    /// this is retried at the ceiling instead, and if it keeps refusing, the
    /// [`Error::RateLimited`](crate::Error::RateLimited) that comes back still
    /// carries the server's own
    /// [`retry_after`](crate::Error::retry_after) for the caller to honour.
    pub fn max_retry_delay(mut self, delay: Duration) -> Self {
        self.max_retry_delay = delay;
        self
    }

    /// Point the trading layer at a JSON-RPC endpoint of your choosing.
    ///
    /// Without this, [`FyuzClient::trade`] uses whatever `GET /config` publishes
    /// for the chain. That endpoint belongs to the API operator, is shared by
    /// every caller, and can change without notice — so set your own for
    /// anything in production.
    pub fn rpc_url(mut self, url: impl Into<String>) -> Self {
        self.rpc_url = Some(url.into());
        self
    }

    /// Per-call timeout for JSON-RPC requests. Defaults to
    /// [`DEFAULT_RPC_TIMEOUT`](crate::DEFAULT_RPC_TIMEOUT).
    pub fn rpc_timeout(mut self, timeout: Duration) -> Self {
        self.rpc_timeout = Some(timeout);
        self
    }

    /// Attach a header to every JSON-RPC request. Call it once per header.
    ///
    /// This is how a paid node is reached: most providers authenticate either by
    /// a key in the path — which [`rpc_url`](Self::rpc_url) already covers — or
    /// by a header such as `X-API-Key`, which nothing else here could express.
    /// The header goes only to the RPC endpoint, never to the Fyuz API.
    ///
    /// Fails if `name` or `value` is not legal in an HTTP header.
    pub fn rpc_header(mut self, name: &str, value: &str) -> Result<Self> {
        let name = HeaderName::from_bytes(name.as_bytes()).map_err(|e| Error::InvalidArgument {
            message: format!("{name:?} is not a valid header name: {e}"),
        })?;
        // The value is deliberately not echoed back: it is usually a credential,
        // and error messages get logged.
        let value = HeaderValue::from_str(value).map_err(|e| Error::InvalidArgument {
            message: format!("the value for header {name:?} is not a valid header value: {e}"),
        })?;
        self.rpc_headers.insert(name, value);
        Ok(self)
    }

    /// Evaluate every `eth_call` against this block instead of `"latest"` — a
    /// decimal or `0x`-prefixed height, or a tag the node knows.
    ///
    /// Pinning a block is what makes two quotes comparable: `"latest"` moves
    /// under you between calls, so a buy priced at one height and a sell priced
    /// at the next are not describing the same curve.
    pub fn rpc_block(mut self, block: impl Into<String>) -> Self {
        self.rpc_block = Some(block.into());
        self
    }

    /// Build the client.
    ///
    /// Fails only if the TLS backend or DNS resolver cannot be initialised.
    pub fn build(self) -> Result<FyuzClient> {
        let http = reqwest::Client::builder()
            .user_agent(&self.user_agent)
            .timeout(self.timeout)
            .build()?;

        // A second transport rather than a second use of the first: the RPC
        // endpoint has its own timeout, its own headers, and — for anyone who
        // set `rpc_header` — credentials that must not travel to the Fyuz API.
        // It is still built once and shared by every chain.
        let rpc_http = reqwest::Client::builder()
            .user_agent(&self.user_agent)
            .timeout(self.rpc_timeout.unwrap_or(DEFAULT_RPC_TIMEOUT))
            .default_headers(self.rpc_headers)
            .build()?;

        let seed = SystemTime::now()
            .duration_since(UNIX_EPOCH)
            .map(|d| d.as_nanos() as u64)
            .unwrap_or(0x9E37_79B9_7F4A_7C15)
            // xorshift is a fixed point at zero.
            | 1;

        Ok(FyuzClient {
            inner: Arc::new(Inner {
                http,
                base_url: self.base_url,
                max_retries: self.max_retries,
                retry_base_delay: self.retry_base_delay,
                max_retry_delay: self.max_retry_delay,
                rng: AtomicU64::new(seed),
                rpc_url: self.rpc_url,
                rpc_block: self.rpc_block,
                rpc_http,
                trade_state: TradeState::default(),
            }),
        })
    }
}

impl Default for FyuzClientBuilder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn base(url: &str) -> Url {
        FyuzClientBuilder::new().base_url(url).unwrap().base_url
    }

    #[test]
    fn joins_paths_onto_a_bare_host() {
        assert_eq!(
            build_url(&base("http://127.0.0.1:8080"), "/tokens/king").as_str(),
            "http://127.0.0.1:8080/tokens/king"
        );
    }

    #[test]
    fn joins_paths_onto_a_prefixed_base() {
        assert_eq!(
            build_url(&base("http://gateway/fyuz"), "/distributor/rounds/7").as_str(),
            "http://gateway/fyuz/distributor/rounds/7"
        );
    }

    #[test]
    fn percent_encodes_path_segments() {
        let url = build_url(&base("https://api.fyuz.fun"), "/wallet/0x00 ff");
        assert_eq!(url.as_str(), "https://api.fyuz.fun/wallet/0x00%20ff");
    }

    #[test]
    fn seg_escapes_everything_outside_the_unreserved_set() {
        assert_eq!(
            seg("0x1111111111111111111111111111111111111111"),
            "0x1111111111111111111111111111111111111111"
        );
        assert_eq!(seg("-._~"), "-._~", "unreserved punctuation stays literal");
        assert_eq!(seg("a/b"), "a%2Fb", "a slash must not become structure");
        assert_eq!(seg("a?b=c#d"), "a%3Fb%3Dc%23d");
        assert_eq!(seg("0x00 ff"), "0x00%20ff");
        assert_eq!(seg("%2F"), "%252F", "a pre-escaped slash is data too");
        assert_eq!(seg("é"), "%C3%A9", "non-ASCII is escaped per UTF-8 byte");
    }

    #[test]
    fn a_slash_in_an_argument_cannot_retarget_the_request() {
        let base = base("https://api.fyuz.fun");

        let url = build_url(&base, &format!("/wallet/{}", seg("../distributor/stats")));
        assert_eq!(
            url.path(),
            "/wallet/..%2Fdistributor%2Fstats",
            "the argument must stay one segment"
        );

        let url = build_url(&base, &format!("/tier/{}", seg("0xabc/../../health")));
        assert_eq!(url.path(), "/tier/0xabc%2F..%2F..%2Fhealth");
    }

    #[test]
    fn a_bare_dot_segment_collapses_rather_than_reaching_a_sibling_endpoint() {
        // Documented limitation of URL semantics, pinned so it cannot drift into
        // something worse: `..` loses its own segment, it does not walk up and
        // pick a different endpoint the way an unencoded `/` used to.
        let url = build_url(
            &base("https://api.fyuz.fun"),
            &format!("/wallet/{}", seg("..")),
        );
        assert_eq!(url.path(), "/");
        assert_eq!(seg(".."), "..");
    }

    #[test]
    fn build_url_does_not_escape_an_already_escaped_segment_twice() {
        let url = build_url(
            &base("https://api.fyuz.fun"),
            &format!("/wallet/{}", seg("a b")),
        );
        assert_eq!(url.as_str(), "https://api.fyuz.fun/wallet/a%20b");
    }

    #[test]
    fn rejects_non_http_base_urls() {
        let err = FyuzClientBuilder::new()
            .base_url("ftp://example.com")
            .unwrap_err();
        assert!(matches!(err, Error::InvalidBaseUrl { .. }));
        let err = FyuzClientBuilder::new().base_url("not a url").unwrap_err();
        assert!(matches!(err, Error::InvalidBaseUrl { .. }));
    }

    #[test]
    fn parses_retry_after_seconds() {
        let mut headers = reqwest::header::HeaderMap::new();
        headers.insert(RETRY_AFTER, "3".parse().unwrap());
        assert_eq!(parse_retry_after(&headers), Some(Duration::from_secs(3)));

        headers.insert(
            RETRY_AFTER,
            "Wed, 21 Oct 2026 07:28:00 GMT".parse().unwrap(),
        );
        assert_eq!(parse_retry_after(&headers), None);
    }

    #[test]
    fn backoff_stays_within_the_cap() {
        let client = FyuzClientBuilder::new()
            .retry_base_delay(Duration::from_millis(100))
            .max_retry_delay(Duration::from_millis(400))
            .build()
            .unwrap();

        for attempt in 0..6 {
            let delay = client.backoff(attempt);
            assert!(delay <= Duration::from_millis(400), "{delay:?}");
        }
        assert!(client.backoff(0) <= Duration::from_millis(100));
    }
}