tycho-simulation 0.519.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
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
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
use std::{collections::HashMap, str::FromStr};

use alloy::primitives::{Address, U256};
use num_bigint::BigUint;
use reqwest::Client;
use tokio::time::{timeout, Duration};
use tracing::{debug, instrument, warn};
use tycho_common::{
    models::protocol::GetAmountOutParams, simulation::indicatively_priced::SignedQuote, Bytes,
};

use crate::{
    evm::protocol::u256_num::biguint_to_u256,
    rfq::{
        errors::RFQError,
        protocols::hashflow::models::{
            HashflowChain, HashflowError, HashflowFailure, HashflowMarketMakerLevels,
            HashflowMarketMakersResponse, HashflowPriceLevelsResponse, HashflowQuoteRequest,
            HashflowQuoteResponse, HashflowRFQ, HashflowRFQOptions,
        },
    },
    snapshot_feed::{errors::FeedError, http::fetch_json},
};

/// Whether Hashflow refused the request because it does not price the chain.
fn refuses_the_chain(body: &str) -> bool {
    serde_json::from_str::<HashflowFailure>(body)
        .is_ok_and(|failure| failure.error.refuses_the_chain())
}

/// Hashflow's public taker API, where a client talks unless it is given another.
const HASHFLOW_API_URL: &str = "https://api.hashflow.com";

/// Requests binding Hashflow quotes. One instance is shared (via `Arc`) by every state a
/// [`HashflowFeed`](super::feed::HashflowFeed) emits, so all of them reuse the same HTTP
/// connection pool.
#[derive(derive_more::Debug)]
pub struct HashflowClient {
    chain_id: u64,
    quote_endpoint: String,
    #[debug(skip)]
    source: String,
    #[debug(skip)]
    auth_key: String,
    quote_timeout: Duration,
    http: Client,
}

/// Reads the price levels Hashflow's market makers quote on one chain. It never requests a
/// quote, so it carries no quote timeout. `Debug` output omits the credentials.
#[derive(derive_more::Debug, Clone)]
pub struct HashflowLevelsClient {
    chain_id: u64,
    price_levels_endpoint: String,
    market_makers_endpoint: String,
    #[debug(skip)]
    source: String,
    #[debug(skip)]
    auth_key: String,
    http: Client,
}

/// The base of Hashflow's taker API endpoints on the deployment at `base_url`, or on the venue.
fn taker_url(base_url: Option<&str>) -> String {
    format!(
        "{}/taker/v3",
        base_url
            .unwrap_or(HASHFLOW_API_URL)
            .trim_end_matches('/')
    )
}

impl HashflowClient {
    /// A client for Hashflow's taker API, whose rfq endpoint sits on the version's own path.
    /// `base_url` points it somewhere else than the venue, which is how a test reaches a server
    /// of its own.
    pub fn new(
        base_url: Option<&str>,
        chain_id: u64,
        source: String,
        auth_key: String,
        quote_timeout: Duration,
    ) -> Self {
        HashflowClient {
            chain_id,
            quote_endpoint: format!("{}/rfq", taker_url(base_url)),
            source,
            auth_key,
            quote_timeout,
            http: Client::new(),
        }
    }

    /// Sends this client's requests through `http`, so it can share a connection pool with
    /// another client.
    pub(super) fn with_http_client(mut self, http: Client) -> Self {
        self.http = http;
        self
    }

    /// Requests a signed quote from `market_maker` alone: the API does not fall back to another
    /// maker when it declines, so a quote always comes from the maker whose levels priced it.
    #[instrument(
        name = "quote_request",
        level = "error",
        skip_all,
        fields(token_in = %params.token_in, token_out = %params.token_out, amount_in = %params.amount_in, %market_maker)
    )]
    pub async fn request_binding_quote(
        &self,
        params: &GetAmountOutParams,
        market_maker: String,
    ) -> Result<SignedQuote, RFQError> {
        let hashflow_chain = HashflowChain::evm(self.chain_id);
        // A fresh random address becomes the quote's effectiveTrader — the address Hashflow
        // scopes its strictly increasing quote nonces to — so quotes never invalidate each
        // other, at the cost of a cold nonce storage slot on Hashflow's router (~17k gas per
        // swap). The receiver executes the trade on-chain, so it is Hashflow's trader.
        let effective_trader = Bytes::from(Address::random().to_vec());
        let quote_request = HashflowQuoteRequest {
            source: self.source.clone(),
            base_chain: hashflow_chain.clone(),
            quote_chain: hashflow_chain,
            rfqs: vec![HashflowRFQ {
                base_token: params.token_in.to_string(),
                quote_token: params.token_out.to_string(),
                base_token_amount: Some(params.amount_in.to_string()),
                quote_token_amount: None,
                trader: params.receiver.to_string(),
                effective_trader: Some(effective_trader.to_string()),
                market_makers: vec![market_maker],
                options: HashflowRFQOptions { do_not_retry_with_other_makers: true },
            }],
            calldata: false,
        };

        let url = self.quote_endpoint.clone();

        let start_time = std::time::Instant::now();
        const MAX_RETRIES: u32 = 3;
        let mut last_error = None;

        for attempt in 0..MAX_RETRIES {
            // Check if we have time remaining for this attempt
            let elapsed = start_time.elapsed();
            if elapsed >= self.quote_timeout {
                return Err(last_error.unwrap_or_else(|| {
                    RFQError::ConnectionError(format!(
                        "Hashflow quote request timed out after {:?}",
                        self.quote_timeout
                    ))
                }));
            }

            let remaining_time = self.quote_timeout - elapsed;

            let request = self
                .http
                .post(&url)
                .json(&quote_request)
                .header("accept", "application/json")
                .header("Authorization", &self.auth_key);

            let response = match timeout(remaining_time, request.send()).await {
                Ok(Ok(resp)) => resp,
                Ok(Err(e)) => {
                    warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "quote request failed");
                    last_error = Some(RFQError::ConnectionError(format!(
                        "Failed to send Hashflow quote request: {e}"
                    )));
                    if attempt < MAX_RETRIES - 1 {
                        tokio::time::sleep(Duration::from_millis(100)).await;
                        continue;
                    }
                    return Err(last_error.unwrap());
                }
                Err(_) => {
                    return Err(RFQError::ConnectionError(format!(
                        "Hashflow quote request timed out after {:?}",
                        self.quote_timeout
                    )));
                }
            };

            if response.status() != 200 {
                let status = response.status();
                let err_msg = match response.text().await {
                    Ok(text) => text,
                    Err(e) => {
                        warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "error response parsing failed");
                        last_error = Some(RFQError::ParsingError(format!(
                            "Failed to read response text from Hashflow failed request: {e}"
                        )));
                        if attempt < MAX_RETRIES - 1 {
                            tokio::time::sleep(Duration::from_millis(100)).await;
                            continue;
                        }
                        return Err(last_error.unwrap());
                    }
                };
                // The venue answering a quote request at all means the request reached it,
                // so a status it refuses with is about this attempt: a rate limit, a gateway
                // between us and it, or a key to be fixed at the venue while the feed runs on.
                last_error = Some(RFQError::ConnectionError(format!(
                    "Hashflow quote request failed with {status}: {err_msg}",
                )));
                if attempt < MAX_RETRIES - 1 {
                    warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %err_msg, "returned non-200 status");
                    tokio::time::sleep(Duration::from_millis(100)).await;
                    continue;
                }
                return Err(last_error.unwrap());
            }

            let quote_response = match response
                .json::<HashflowQuoteResponse>()
                .await
            {
                Ok(resp) => resp,
                Err(e) => {
                    warn!(attempt = attempt + 1, max_attempts = MAX_RETRIES, error = %e, "quote response parsing failed");
                    last_error = Some(RFQError::ParsingError(format!(
                        "Failed to parse Hashflow quote response: {e}"
                    )));
                    if attempt < MAX_RETRIES - 1 {
                        tokio::time::sleep(Duration::from_millis(100)).await;
                        continue;
                    }
                    return Err(last_error.unwrap());
                }
            };

            match quote_response.status.as_str() {
                "success" => {
                    if let Some(quotes) = quote_response.quotes {
                        if quotes.is_empty() {
                            return Err(RFQError::QuoteNotFound(format!(
                                "Hashflow quote not found for {} {} ->{}",
                                params.amount_in, params.token_in, params.token_out,
                            )));
                        }
                        // We assume there will be only one quote request at a time
                        let quote = quotes[0].clone();
                        quote.validate(params, &effective_trader)?;

                        let mut quote_attributes: HashMap<String, Bytes> = HashMap::new();
                        quote_attributes.insert("pool".to_string(), quote.quote_data.pool);
                        if let Some(external_account) = quote.quote_data.external_account {
                            quote_attributes
                                .insert("external_account".to_string(), external_account);
                        } else {
                            quote_attributes.insert(
                                "external_account".to_string(),
                                Bytes::from_str(&Address::ZERO.to_string()).map_err(|e| {
                                    RFQError::ParsingError(format!(
                                        "Failed to parse zero address: {e}"
                                    ))
                                })?,
                            );
                        }
                        quote_attributes.insert("trader".to_string(), quote.quote_data.trader);
                        quote_attributes
                            .insert("effective_trader".to_string(), effective_trader.clone());
                        quote_attributes
                            .insert("base_token".to_string(), quote.quote_data.base_token);
                        quote_attributes
                            .insert("quote_token".to_string(), quote.quote_data.quote_token);
                        quote_attributes.insert(
                            "base_token_amount".to_string(),
                            Bytes::from(
                                biguint_to_u256(
                                    &BigUint::from_str(&quote.quote_data.base_token_amount)
                                        .map_err(|e| {
                                            RFQError::ParsingError(format!(
                                                "Failed to parse base token amount: {} ({e})",
                                                quote.quote_data.base_token_amount
                                            ))
                                        })?,
                                )
                                .to_be_bytes::<32>()
                                .to_vec(),
                            ),
                        );
                        quote_attributes.insert(
                            "quote_token_amount".to_string(),
                            Bytes::from(
                                biguint_to_u256(
                                    &BigUint::from_str(&quote.quote_data.quote_token_amount)
                                        .map_err(|e| {
                                            RFQError::ParsingError(format!(
                                                "Failed to parse quote token amount: {} ({e})",
                                                quote.quote_data.quote_token_amount
                                            ))
                                        })?,
                                )
                                .to_be_bytes::<32>()
                                .to_vec(),
                            ),
                        );
                        quote_attributes.insert(
                            "quote_expiry".to_string(),
                            Bytes::from(
                                U256::from(quote.quote_data.quote_expiry)
                                    .to_be_bytes::<32>()
                                    .to_vec(),
                            ),
                        );
                        quote_attributes.insert(
                            "nonce".to_string(),
                            Bytes::from(
                                U256::from(quote.quote_data.nonce)
                                    .to_be_bytes::<32>()
                                    .to_vec(),
                            ),
                        );
                        quote_attributes.insert("tx_id".to_string(), quote.quote_data.tx_id);
                        quote_attributes.insert("signature".to_string(), quote.signature);

                        let signed_quote = SignedQuote {
                            base_token: params.token_in.clone(),
                            quote_token: params.token_out.clone(),
                            amount_in: BigUint::from_str(&quote.quote_data.base_token_amount)
                                .map_err(|e| {
                                    RFQError::ParsingError(format!(
                                        "Failed to parse amount in string: {} ({e})",
                                        quote.quote_data.base_token_amount
                                    ))
                                })?,
                            amount_out: BigUint::from_str(&quote.quote_data.quote_token_amount)
                                .map_err(|e| {
                                    RFQError::ParsingError(format!(
                                        "Failed to parse amount out string: {} ({e})",
                                        quote.quote_data.quote_token_amount
                                    ))
                                })?,
                            quote_attributes,
                        };
                        return Ok(signed_quote);
                    }
                    return Err(RFQError::QuoteNotFound(format!(
                        "Hashflow quote not found for {} {} ->{}",
                        params.amount_in, params.token_in, params.token_out,
                    )));
                }
                "fail" => {
                    let Some(error) = quote_response.error else {
                        return Err(RFQError::FatalError(
                            "Hashflow API error: request failed without an error".to_string(),
                        ));
                    };
                    // A declined trade leaves the route to be priced elsewhere; a code the
                    // venue has not been seen to decline with is taken to be the request itself
                    // being wrong.
                    return Err(if error.declines_the_trade() {
                        RFQError::QuoteNotFound(format!("Hashflow quote: {error}"))
                    } else {
                        RFQError::FatalError(format!("Hashflow API error: {error}"))
                    });
                }
                _ => {
                    return Err(RFQError::FatalError(
                        "Hashflow API error: Unknown status".to_string(),
                    ));
                }
            }
        }

        Err(last_error.unwrap_or_else(|| {
            RFQError::ConnectionError("Hashflow quote request failed after retries".to_string())
        }))
    }
}

impl HashflowLevelsClient {
    /// A client for the market makers and price levels of Hashflow's taker API on `chain_id`.
    /// `base_url` points it somewhere else than the venue, as for [`HashflowClient::new`].
    pub fn new(base_url: Option<&str>, chain_id: u64, source: String, auth_key: String) -> Self {
        let taker = taker_url(base_url);
        HashflowLevelsClient {
            chain_id,
            price_levels_endpoint: format!("{taker}/price-levels"),
            market_makers_endpoint: format!("{taker}/market-makers"),
            source,
            auth_key,
            http: Client::new(),
        }
    }

    /// Sends this client's requests through `http`, so it can share a connection pool with
    /// another client.
    pub(super) fn with_http_client(mut self, http: Client) -> Self {
        self.http = http;
        self
    }

    /// The query every book request carries: who is asking and about which chain.
    fn chain_query(&self) -> Vec<(&'static str, String)> {
        vec![
            ("source", self.source.clone()),
            ("baseChainType", "evm".to_string()),
            ("baseChainId", self.chain_id.to_string()),
        ]
    }

    /// The makers currently quoting on this chain.
    pub async fn fetch_market_makers(&self) -> Result<Vec<String>, FeedError> {
        let request = self
            .http
            .get(&self.market_makers_endpoint)
            .query(&self.chain_query())
            .header("accept", "application/json")
            .header("Authorization", &self.auth_key);
        let mm_response: HashflowMarketMakersResponse =
            fetch_json(request, "Hashflow market makers", refuses_the_chain).await?;
        debug!(
            count = mm_response.market_makers.len(),
            market_makers = ?mm_response.market_makers,
            "fetched market makers"
        );
        Ok(mm_response.market_makers)
    }

    /// The price levels the given makers are quoting, keyed by maker name.
    pub async fn fetch_price_levels(
        &self,
        market_makers: &[String],
    ) -> Result<HashMap<String, Vec<HashflowMarketMakerLevels>>, FeedError> {
        let mut query_params = self.chain_query();
        // Add market makers as array parameters
        for mm in market_makers {
            query_params.push(("marketMakers[]", mm.clone()));
        }
        let request = self
            .http
            .get(&self.price_levels_endpoint)
            .query(&query_params)
            .header("accept", "application/json")
            .header("Authorization", &self.auth_key);
        let price_response: HashflowPriceLevelsResponse =
            fetch_json(request, "Hashflow price levels", refuses_the_chain).await?;
        if price_response.status != "success" {
            let refuses_the_chain = price_response
                .error
                .as_ref()
                .is_some_and(HashflowError::refuses_the_chain);
            let error = match price_response.error {
                Some(error) => error.to_string(),
                None => "no error details".to_string(),
            };
            let message = format!("API returned error status: {error}");
            return Err(if refuses_the_chain {
                FeedError::Fatal(message)
            } else {
                FeedError::Connection(message)
            });
        }
        price_response
            .levels
            .ok_or_else(|| FeedError::Parsing("API response missing levels".to_string()))
    }
}

#[cfg(test)]
mod tests {
    use std::{
        str::FromStr,
        sync::{
            atomic::{AtomicUsize, Ordering},
            Arc, Mutex,
        },
    };

    use dotenvy::dotenv;
    use rstest::rstest;
    use tycho_common::models::Chain;

    use super::*;
    use crate::snapshot_feed::http::test_support::{
        spawn_http_server, MockHttpServer, MockResponse,
    };

    /// Response template; the mock server replaces `{{EFFECTIVE_TRADER}}` with the address the
    /// request carried, echoing it like the real API.
    const QUOTE_RESPONSE: &str = r#"{"status":"success","error":null,"rfqId":"test-rfq-id","internalRfqIds":null,"quotes":[{"quoteData":{"pool":"0x71D9750ECF0c5081FAE4E3EDC4253E52024b0B59","externalAccount":null,"trader":"0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35","effectiveTrader":"{{EFFECTIVE_TRADER}}","baseToken":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","baseTokenAmount":"1000000000000000000","quoteToken":"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599","quoteTokenAmount":"3329502","quoteExpiry":1707847360,"nonce":1707844960943648659,"txid":"0x0000000000000000000000000000000000000000000000000000000000000001"},"signature":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"}]}"#;

    const QUOTE_RESPONSE_WITHOUT_EFFECTIVE_TRADER: &str = r#"{"status":"success","error":null,"rfqId":"test-rfq-id","internalRfqIds":null,"quotes":[{"quoteData":{"pool":"0x71D9750ECF0c5081FAE4E3EDC4253E52024b0B59","externalAccount":null,"trader":"0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35","baseToken":"0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2","baseTokenAmount":"1000000000000000000","quoteToken":"0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599","quoteTokenAmount":"3329502","quoteExpiry":1707847360,"nonce":1707844960943648659,"txid":"0x0000000000000000000000000000000000000000000000000000000000000001"},"signature":"0x1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef12"}]}"#;

    /// Extracts the effectiveTrader value from a request body.
    fn effective_trader_of(request_body: &str) -> String {
        let start = request_body
            .find("\"effectiveTrader\":\"")
            .expect("request carries no effectiveTrader") +
            "\"effectiveTrader\":\"".len();
        request_body[start..start + request_body[start..].find('"').unwrap()].to_string()
    }

    /// A server answering every quote request with `json_response`, after `delay`, with the
    /// request's own `effectiveTrader` put where the response names one. The bodies it was
    /// asked with are recorded in the returned log.
    async fn quote_server(
        delay: Duration,
        json_response: &'static str,
    ) -> (MockHttpServer, Arc<Mutex<Vec<String>>>) {
        let request_log: Arc<Mutex<Vec<String>>> = Arc::default();
        let recorded = Arc::clone(&request_log);
        let server = spawn_http_server(move |request| {
            recorded
                .lock()
                .unwrap()
                .push(request.body.clone());
            Some(MockResponse {
                status: "200 OK",
                body: json_response
                    .replace("{{EFFECTIVE_TRADER}}", &effective_trader_of(&request.body)),
                delay,
            })
        })
        .await;
        (server, request_log)
    }

    fn create_test_client(base_url: &str, quote_timeout: Duration) -> HashflowClient {
        HashflowClient::new(
            Some(base_url),
            Chain::Ethereum.id(),
            "test_user".to_string(),
            "test_key".to_string(),
            quote_timeout,
        )
    }

    #[test]
    fn debug_output_omits_credentials() {
        let client = create_test_client("https://hashflow.example", Duration::from_secs(1));
        let rendered = format!("{client:?}");

        assert!(!rendered.contains("test_user"));
        assert!(!rendered.contains("test_key"));
        assert!(rendered.contains("hashflow.example"));
    }

    /// A status the venue refuses a quote with says the request reached it and this attempt
    /// failed — a rate limit, a gateway in between, a key to be fixed at the venue — so the
    /// state asks again instead of being retired.
    #[tokio::test]
    async fn a_refused_status_leaves_the_component_quotable() {
        let server =
            spawn_http_server(|_| Some(("429 Too Many Requests", "slow down".to_string()))).await;
        let client = create_test_client(&server.url(), Duration::from_secs(1));

        let error = client
            .request_binding_quote(&create_test_quote_params(), "mm1".to_string())
            .await
            .unwrap_err();

        assert!(matches!(error, RFQError::ConnectionError(_)), "{error}");
        assert!(error.to_string().contains("429"), "{error}");
    }

    /// Helper function to create test quote params
    fn create_test_quote_params() -> GetAmountOutParams {
        let token_in = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
        let token_out = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
        let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();

        GetAmountOutParams {
            amount_in: BigUint::from(1_000000000000000000u64),
            token_in,
            token_out,
            sender: router.clone(),
            receiver: router,
            origin: None,
        }
    }

    #[tokio::test]
    async fn request_binding_quote_without_effective_trader() {
        // A response that drops the requested effectiveTrader would leave the quote in the
        // trader's shared nonce scope, so the client rejects it.
        let (server, _) =
            quote_server(Duration::ZERO, QUOTE_RESPONSE_WITHOUT_EFFECTIVE_TRADER).await;
        let client = create_test_client(&server.url(), Duration::from_secs(1));
        let params = create_test_quote_params();

        let err = client
            .request_binding_quote(&params, "mm1".to_string())
            .await
            .unwrap_err();

        assert!(format!("{err:?}").contains("Effective trader mismatch"));
    }

    /// A maker declining arrives as `fail` inside an HTTP 200; the first two bodies are recorded
    /// from the live API. Both say the trade is unavailable now, which leaves the route to be
    /// priced elsewhere. The third carries the same envelope with the error the API answers an
    /// unserved chain with, for what becomes of a code that is not a decline.
    #[rstest]
    #[case::no_maker_supports_the_request(
        r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":82,"message":"No maker supports this request"}}"#,
        true,
        "No maker supports this request (code 82)"
    )]
    #[case::below_minimum_amount(
        r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":79,"message":"Below minimum amount"}}"#,
        true,
        "Below minimum amount (code 79)"
    )]
    #[case::exceeds_supported_amounts(
        r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317498228a10fe0000","error":{"code":76,"message":"Exceeds supported amounts"}}"#,
        true,
        "Exceeds supported amounts (code 76)"
    )]
    #[case::a_code_that_is_not_a_decline(
        r#"{"status":"fail","rfqId":"0x225000000000000000000000000000ffffffffffffff00317477065b24ec0000","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
        false,
        "Invalid chainId: 130 (code 42)"
    )]
    #[tokio::test]
    async fn only_a_failure_that_is_not_a_decline_is_fatal(
        #[case] body: &'static str,
        #[case] declined: bool,
        #[case] says: &str,
    ) {
        let (server, _) = quote_server(Duration::ZERO, body).await;
        let client = create_test_client(&server.url(), Duration::from_secs(1));

        let error = client
            .request_binding_quote(&create_test_quote_params(), "mm1".to_string())
            .await
            .unwrap_err();

        assert!(
            if declined {
                matches!(error, RFQError::QuoteNotFound(_))
            } else {
                matches!(error, RFQError::FatalError(_))
            },
            "{error}"
        );
        assert!(error.to_string().contains(says), "{error}");
    }

    #[tokio::test]
    async fn request_binding_quote_field_mapping() {
        // The wire request carries the receiver as Hashflow's trader, a fresh random address as
        // the effectiveTrader — a new one per quote request — and the one maker it goes to.
        let (server, request_log) = quote_server(Duration::ZERO, QUOTE_RESPONSE).await;
        let client = create_test_client(&server.url(), Duration::from_secs(1));
        let params = create_test_quote_params();

        let first_quote = client
            .request_binding_quote(&params, "mm1".to_string())
            .await
            .unwrap();
        client
            .request_binding_quote(&params, "mm1".to_string())
            .await
            .unwrap();

        let requests = request_log.lock().unwrap();
        assert_eq!(requests.len(), 2);
        for body in requests.iter() {
            assert!(
                body.contains(&format!("\"trader\":\"{}\"", params.receiver)),
                "trader is not the receiver: {body}"
            );
            assert!(
                body.contains(
                    r#""marketMakers":["mm1"],"options":{"doNotRetryWithOtherMakers":true}"#
                ),
                "request is not pinned to the state's maker: {body}"
            );
        }
        let first = effective_trader_of(&requests[0]);
        let second = effective_trader_of(&requests[1]);
        assert_eq!(first.len(), 42, "effective trader is not an address");
        assert_ne!(first, second, "effective traders are not unique per quote");
        assert_ne!(first, params.receiver.to_string(), "effective trader equals the trader");
        assert_eq!(
            first_quote
                .quote_attributes
                .get("effective_trader")
                .unwrap()
                .to_string(),
            first,
            "quote attributes do not carry the requested effective trader"
        );
    }

    #[tokio::test]
    async fn hashflow_quote_timeout() {
        let (server, _) = quote_server(Duration::from_millis(500), QUOTE_RESPONSE).await;

        // Test 1: Client with short timeout (200ms) - should timeout
        let client_short_timeout = create_test_client(&server.url(), Duration::from_millis(200));
        let params = create_test_quote_params();

        // This should timeout after 200ms
        let start = std::time::Instant::now();
        let result = client_short_timeout
            .request_binding_quote(&params, "mm1".to_string())
            .await;
        let elapsed = start.elapsed();

        // Verify that we got a timeout error
        assert!(result.is_err());
        let err = result.unwrap_err();
        match err {
            RFQError::ConnectionError(msg) => {
                assert!(msg.contains("timed out"), "Expected timeout error, got: {}", msg);
            }
            RFQError::ParsingError(_) |
            RFQError::FatalError(_) |
            RFQError::InvalidInput(_) |
            RFQError::QuoteNotFound(_) => panic!("Expected ConnectionError, got: {:?}", err),
        }
        // Should have timed out around 200ms, definitely less than 400ms
        assert!(
            elapsed.as_millis() >= 200 && elapsed.as_millis() < 400,
            "Expected timeout around 200ms, got: {:?}",
            elapsed
        );

        // Test 2: Client with long timeout (1 second) - should wait and receive response
        // Note: With retry logic, we may need multiple attempts if the response is malformed,
        // so we need a longer timeout to account for retries
        let client_long_timeout = create_test_client(&server.url(), Duration::from_secs(1));

        // This should wait for the response (500ms)
        let result = client_long_timeout
            .request_binding_quote(&params, "mm1".to_string())
            .await;

        // Should succeed - the server waits 500ms which is within the 1s timeout
        assert!(result.is_ok(), "Expected success, got: {:?}", result);
    }

    #[tokio::test]
    async fn hashflow_quote_retry_on_bad_response() {
        // The venue answers the first two attempts with a server error and the third with a
        // quote.
        // The route counts its own attempts, so one test's retries never reach another's.
        let attempts = Arc::new(AtomicUsize::new(0));
        let server = spawn_http_server(move |request| {
            Some(if attempts.fetch_add(1, Ordering::SeqCst) < 2 {
                ("500 Internal Server Error", "Internal Server Error".to_string())
            } else {
                (
                    "200 OK",
                    QUOTE_RESPONSE
                        .replace("{{EFFECTIVE_TRADER}}", &effective_trader_of(&request.body)),
                )
            })
        })
        .await;

        let client = create_test_client(&server.url(), Duration::from_secs(5));
        let params = create_test_quote_params();
        let result = client
            .request_binding_quote(&params, "mm1".to_string())
            .await;

        assert!(result.is_ok(), "Expected success after retries, got: {:?}", result);
        let quote = result.unwrap();

        // Verify the quote is parsed as expected
        assert_eq!(quote.amount_in, BigUint::from(1_000000000000000000u64));
        assert_eq!(quote.amount_out, BigUint::from(3329502u64));

        // Verify exactly 3 requests were made (2 failures + 1 success)
        assert_eq!(server.request_count(), 3);
    }

    /// Both book endpoints ask about the chain under the parameter Hashflow reads it from.
    #[tokio::test]
    async fn the_book_requests_carry_the_chain_id() {
        let targets = Arc::new(Mutex::new(Vec::new()));
        let recorded = Arc::clone(&targets);
        let server = spawn_http_server(move |request| {
            recorded
                .lock()
                .unwrap()
                .push(request.target.to_string());
            if request
                .target
                .starts_with("/taker/v3/market-makers")
            {
                Some(("200 OK", r#"{"marketMakers":["mm1"]}"#.to_string()))
            } else {
                Some(("200 OK", r#"{"status":"success","levels":{"mm1":[]}}"#.to_string()))
            }
        })
        .await;
        let url = server.url();
        let chain_id = Chain::Arbitrum.id();
        let client = HashflowLevelsClient::new(
            Some(&url),
            chain_id,
            "test_user".to_string(),
            "test_key".to_string(),
        );

        let makers = client
            .fetch_market_makers()
            .await
            .unwrap();
        client
            .fetch_price_levels(&makers)
            .await
            .unwrap();

        let targets = targets.lock().unwrap();
        assert_eq!(targets.len(), 2, "{targets:?}");
        assert!(
            targets
                .iter()
                .all(|target| target.contains(&format!("baseChainId={chain_id}"))),
            "{targets:?}"
        );
    }

    /// Unichain (130) is a chain Hashflow does not price, and the words it refuses one with are
    /// what this client reads to stop the feed instead of polling on.
    #[tokio::test]
    #[ignore = "hits Hashflow's live API; requires HASHFLOW_USER and HASHFLOW_KEY"]
    async fn live_hashflow_api_refuses_a_chain_it_does_not_price() {
        #[expect(
            clippy::unused_result_ok,
            reason = "a missing .env file is fine; the variables may come from the environment"
        )]
        dotenv().ok();
        let source = std::env::var("HASHFLOW_USER").expect("HASHFLOW_USER not set");
        let auth_key = std::env::var("HASHFLOW_KEY").expect("HASHFLOW_KEY not set");
        let client = HashflowLevelsClient::new(None, Chain::Unichain.id(), source, auth_key);

        let error = client
            .fetch_market_makers()
            .await
            .unwrap_err();

        assert!(error.is_fatal(), "{error}");
    }

    /// A bad request is ordinarily worth another poll — a maker can vanish between two calls —
    /// so only the refusal that names the chain ends the feed.
    #[rstest]
    #[case::an_unserved_chain(
        r#"{"status":"fail","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
        true
    )]
    #[case::an_unknown_market_maker(
        r#"{"status":"fail","error":{"code":42,"message":"Unknown market maker: mm1"}}"#,
        false
    )]
    #[tokio::test]
    async fn only_the_refusal_naming_the_chain_is_fatal(
        #[case] body: &'static str,
        #[case] fatal: bool,
    ) {
        let server = spawn_http_server(move |_| Some(("400 Bad Request", body.to_string()))).await;
        let url = server.url();
        let client = HashflowLevelsClient::new(
            Some(&url),
            Chain::Unichain.id(),
            "test_user".to_string(),
            "test_key".to_string(),
        );

        let error = client
            .fetch_market_makers()
            .await
            .unwrap_err();

        assert_eq!(error.is_fatal(), fatal, "{error}");
    }

    /// Hashflow also carries a failure in the body of a 200, where the same words mean the same
    /// thing.
    #[rstest]
    #[case::an_unserved_chain(
        r#"{"status":"fail","error":{"code":42,"message":"Invalid chainId: 130"}}"#,
        true
    )]
    #[case::an_unknown_market_maker(
        r#"{"status":"fail","error":{"code":42,"message":"Unknown market maker: mm1"}}"#,
        false
    )]
    #[tokio::test]
    async fn a_failure_inside_a_successful_response_is_judged_the_same_way(
        #[case] body: &'static str,
        #[case] fatal: bool,
    ) {
        let server = spawn_http_server(move |_| Some(("200 OK", body.to_string()))).await;
        let url = server.url();
        let client = HashflowLevelsClient::new(
            Some(&url),
            Chain::Unichain.id(),
            "test_user".to_string(),
            "test_key".to_string(),
        );

        let error = client
            .fetch_price_levels(&["mm1".to_string()])
            .await
            .unwrap_err();

        assert_eq!(error.is_fatal(), fatal, "{error}");
    }
}