tycho-simulation 0.520.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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
use std::{collections::HashMap, str::FromStr, time::SystemTime};

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

use crate::{
    evm::protocol::utils::bytes_to_address,
    rfq::{
        errors::RFQError,
        protocols::native::models::{
            FirmQuoteRequest, FirmQuoteResponse, NativeApiErrorResponse, NativeOrderbook,
            NativeOrderbookEntry, NativeSupportedChain,
        },
    },
    snapshot_feed::{
        errors::FeedError,
        http::{fetch_bytes, nothing_refused},
    },
};

const MAX_QUOTE_ATTEMPTS: u32 = 3;
const TRANSIENT_RETRY_DELAY: Duration = Duration::from_millis(100);
const NATIVE_API_RETRY_DELAY: Duration = Duration::from_secs(1);
// V6 tradeRFQT: a dynamic quote tuple and two uint256 overrides, i.e. three ABI head words.
const TRADE_RFQT_SELECTOR: [u8; 4] = [0x70, 0x83, 0x52, 0x7c];
const MIN_TRADE_RFQT_CALLDATA_LEN: usize = 4 + 3 * 32;
const ACTUAL_SELLER_AMOUNT_OFFSET: usize = 4 + 32;
const ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET: usize = 4 + 2 * 32;

enum QuoteAttemptError {
    Retry { error: RFQError, delay: Duration },
    Fatal(RFQError),
}

/// Native Relay's swap API, where a client talks unless it is given another. The orderbook and
/// firm-quote paths are appended per request.
const NATIVE_API_URL: &str = "https://v2.api.native.org/swap-api-v2/v1";

/// Requests binding Native Relay quotes. One instance is shared (via `Arc`) by every state a
/// [`NativeFeed`](super::feed::NativeFeed) emits, so all of them reuse the same HTTP connection
/// pool.
#[derive(derive_more::Debug)]
pub struct NativeClient {
    chain: NativeSupportedChain,
    /// Base URL of the swap API; the firm-quote path is appended per request.
    endpoint: String,
    #[debug(skip)]
    api_key: String,
    quote_timeout: Duration,
    http: Client,
}

impl NativeClient {
    /// A client for Native Relay's swap API. `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: NativeSupportedChain,
        api_key: String,
        quote_timeout: Duration,
    ) -> Self {
        let endpoint = base_url
            .unwrap_or(NATIVE_API_URL)
            .trim_end_matches('/')
            .to_string();
        NativeClient { chain, endpoint, api_key, quote_timeout, http: Client::new() }
    }

    /// The venue's aggregated orderbook: one entry per pair, side and orientation its makers
    /// quote.
    pub async fn fetch_orderbook(&self) -> Result<Vec<NativeOrderbookEntry>, FeedError> {
        let request = self
            .http
            .get(format!("{}/orderbook", self.endpoint))
            // `showNative` is not boolean: its value selects the address used for native-token
            // books. Request address(0) so the response matches Tycho's internal representation.
            .query(&[("chain", self.chain.as_str()), ("showNative", "0x0")])
            .header("accept", "application/json")
            .header("apikey", &self.api_key);

        let body = fetch_bytes(request, "Native Relay orderbook", nothing_refused).await?;

        // Native reports an authentication or request failure as an error envelope under HTTP
        // 200, so a successful response still has two possible shapes. The orderbook is tried
        // first: it is what almost every poll returns, and when neither shape matches, its parse
        // error is the one that says what the response actually looked like.
        serde_json::from_slice::<NativeOrderbook>(&body)
            .map(|orderbook| orderbook.0)
            .map_err(|orderbook_error| {
                match serde_json::from_slice::<NativeApiErrorResponse>(&body) {
                    // No failure the venue reports here is fatal, a refused key included: that
                    // is fixed at the venue while the feed polls, and the next poll serves the
                    // book again.
                    Ok(api_error) => FeedError::Connection(format!(
                        "Native API error {}: {}",
                        api_error.code, api_error.message
                    )),
                    Err(_) => FeedError::Parsing(format!(
                        "Failed to parse Native Relay orderbook: {orderbook_error}"
                    )),
                }
            })
    }

    #[instrument(
        name = "quote_request",
        level = "error",
        skip_all,
        fields(token_in = %params.token_in, token_out = %params.token_out, amount_in = %params.amount_in)
    )]
    pub async fn request_binding_quote(
        &self,
        params: &GetAmountOutParams,
    ) -> Result<SignedQuote, RFQError> {
        let receiver = bytes_to_address(&params.receiver)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;
        let token_in = bytes_to_address(&params.token_in)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;
        let token_out = bytes_to_address(&params.token_out)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;

        let request_data = FirmQuoteRequest {
            src_chain: self.chain,
            dst_chain: self.chain,
            from_address: receiver.to_string(),
            amount_wei: params.amount_in.to_string(),
            token_in: token_in.to_string(),
            token_out: token_out.to_string(),
            version: 6,
            allow_multihop: false,
        };
        let mut last_error = None;

        let attempts = async {
            for attempt in 1..=MAX_QUOTE_ATTEMPTS {
                match self
                    .try_quote(&request_data, params)
                    .await
                {
                    Ok(quote) => return Ok(quote),
                    Err(QuoteAttemptError::Fatal(error)) => return Err(error),
                    Err(QuoteAttemptError::Retry { error, delay }) => {
                        warn!(
                            attempt,
                            max_attempts = MAX_QUOTE_ATTEMPTS,
                            error = %error,
                            "quote attempt failed, retrying"
                        );
                        last_error = Some(error);

                        if attempt < MAX_QUOTE_ATTEMPTS {
                            tokio::time::sleep(delay).await;
                        }
                    }
                }
            }

            Err(last_error.take().unwrap_or_else(|| {
                RFQError::ConnectionError(
                    "Native quote request failed after all attempts".to_string(),
                )
            }))
        };

        // Bind the timeout result before inspecting last_error so the attempts future — and its
        // mutable borrow — has been dropped.
        let result = timeout(self.quote_timeout, attempts).await;
        match result {
            Ok(result) => result,
            Err(_) => Err(last_error.unwrap_or_else(|| {
                RFQError::ConnectionError(format!(
                    "Native quote request timed out after {:?}",
                    self.quote_timeout
                ))
            })),
        }
    }

    async fn try_quote(
        &self,
        request_data: &FirmQuoteRequest,
        params: &GetAmountOutParams,
    ) -> Result<SignedQuote, QuoteAttemptError> {
        let response = self
            .http
            .get(format!("{}/firm-quote", self.endpoint))
            .query(request_data)
            .header("apikey", &self.api_key)
            .send()
            .await
            .map_err(|e| QuoteAttemptError::Retry {
                error: RFQError::ConnectionError(format!(
                    "Failed to make Native quote request: {e}"
                )),
                delay: TRANSIENT_RETRY_DELAY,
            })?;

        let status = response.status();
        let response_body = response
            .bytes()
            .await
            .map_err(|e| QuoteAttemptError::Retry {
                error: RFQError::ConnectionError(format!(
                    "Failed to read Native quote response: {e}"
                )),
                delay: TRANSIENT_RETRY_DELAY,
            })?;

        // Native returns documented API error codes in the body, including with HTTP 200.
        if let Ok(api_error) = serde_json::from_slice::<NativeApiErrorResponse>(&response_body) {
            return Err(Self::classify_api_error(&api_error));
        }

        if !status.is_success() {
            let response_text = String::from_utf8_lossy(&response_body);
            if status.is_server_error() {
                return Err(QuoteAttemptError::Retry {
                    error: RFQError::ConnectionError(format!(
                        "Native quote server error ({status}): {response_text}"
                    )),
                    delay: TRANSIENT_RETRY_DELAY,
                });
            }

            return Err(QuoteAttemptError::Fatal(RFQError::ConnectionError(format!(
                "Unexpected Native quote HTTP response ({status}): {response_text}"
            ))));
        }

        let quote_response =
            serde_json::from_slice::<FirmQuoteResponse>(&response_body).map_err(|e| {
                QuoteAttemptError::Retry {
                    error: RFQError::ParsingError(format!(
                        "Failed to parse Native quote response: {e}"
                    )),
                    delay: TRANSIENT_RETRY_DELAY,
                }
            })?;

        Self::process_quote_response(&quote_response, params).map_err(QuoteAttemptError::Fatal)
    }

    // Native API error codes:
    // <https://docs.native.org/native-dev/build-with-native/swap-aggregators/firmquote-swap-apis/miscellaneous/error-handling#error-codes>
    fn classify_api_error(error: &NativeApiErrorResponse) -> QuoteAttemptError {
        let message = format!("Native API error {}: {}", error.code, error.message);
        match error.code {
            // Native documents these as temporary risk/rate-limit failures.
            301016 | 405030 => QuoteAttemptError::Retry {
                error: RFQError::QuoteNotFound(message),
                delay: NATIVE_API_RETRY_DELAY,
            },
            201005 => QuoteAttemptError::Retry {
                error: RFQError::ConnectionError(message),
                delay: NATIVE_API_RETRY_DELAY,
            },
            // The requested quote is unavailable for the current orderbook/liquidity.
            // 171055 is not in the public table, but Native returns it when the seller amount is
            // below the current book minimum.
            101010 | 171037 | 171011 | 171015 | 171055 | 101007 => {
                QuoteAttemptError::Fatal(RFQError::QuoteNotFound(message))
            }
            // The request itself must be corrected before another attempt can succeed.
            131003 | 131004 | 131011 | 171018 | 171053 | 131005 => {
                QuoteAttemptError::Fatal(RFQError::InvalidInput(message))
            }
            201001 => QuoteAttemptError::Fatal(RFQError::FatalError(message)),
            _ => QuoteAttemptError::Fatal(RFQError::FatalError(format!(
                "Unknown Native API error {}: {}",
                error.code, error.message
            ))),
        }
    }

    fn process_quote_response(
        quote_response: &FirmQuoteResponse,
        params: &GetAmountOutParams,
    ) -> Result<SignedQuote, RFQError> {
        if !quote_response.success {
            return Err(RFQError::QuoteNotFound(format!(
                "Native Relay quote request failed: {}",
                quote_response.error_message
            )));
        }

        if quote_response.router_version != "6" {
            return Err(RFQError::FatalError(format!(
                "Unexpected Native router version: expected 6, got {}",
                quote_response.router_version
            )));
        }

        let order = quote_response
            .orders
            .first()
            .ok_or_else(|| {
                RFQError::QuoteNotFound(format!(
                    "No Native Relay orders for {} {} -> {}",
                    params.amount_in, params.token_in, params.token_out,
                ))
            })?;

        // Prevents silently accepting a mismatched/malicious quote.
        let seller_token = bytes_to_address(&params.token_in)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;
        let buyer_token = bytes_to_address(&params.token_out)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;
        let order_seller_token = Address::from_str(&order.seller_token).map_err(|e| {
            RFQError::ParsingError(format!(
                "Invalid Native seller token {}: {e}",
                order.seller_token
            ))
        })?;
        let order_buyer_token = Address::from_str(&order.buyer_token).map_err(|e| {
            RFQError::ParsingError(format!("Invalid Native buyer token {}: {e}", order.buyer_token))
        })?;
        if order_seller_token != seller_token || order_buyer_token != buyer_token {
            return Err(RFQError::FatalError(format!(
                "Native Relay quote token mismatch: expected {}/{}, got {}/{}",
                seller_token, buyer_token, order_seller_token, order_buyer_token
            )));
        }

        let receiver = bytes_to_address(&params.receiver)
            .map_err(|e| RFQError::InvalidInput(e.to_string()))?;
        let order_recipient = Address::from_str(&order.recipient).map_err(|e| {
            RFQError::ParsingError(format!(
                "Invalid Native order recipient {}: {e}",
                order.recipient
            ))
        })?;
        if order_recipient != receiver {
            return Err(RFQError::FatalError(format!(
                "Native Relay quote recipient mismatch: expected {receiver}, got {order_recipient}"
            )));
        }

        // Reject already-expired quotes before building a SignedQuote.
        let now = SystemTime::now()
            .duration_since(SystemTime::UNIX_EPOCH)
            .map_err(|_before_epoch| {
                RFQError::ParsingError("SystemTime before UNIX EPOCH".to_string())
            })?
            .as_secs();

        if order.deadline_timestamp <= now {
            return Err(RFQError::QuoteNotFound(format!(
                "Native Relay quote already expired: deadline {} <= now {}",
                order.deadline_timestamp, now
            )));
        }

        // Bind Native's top-level amountIn and signed sellerTokenAmount to the requested quote
        // baseline. The encoder stores this baseline as signedAmountIn; the executor supplies
        // actualSellerAmount when execution receives a different amount from the preceding hop.
        let quoted_amount_in = BigUint::from_str(&quote_response.amount_in).map_err(|e| {
            RFQError::ParsingError(format!(
                "Failed to parse amount_in: {} ({e})",
                quote_response.amount_in
            ))
        })?;
        if quoted_amount_in != params.amount_in {
            return Err(RFQError::FatalError(format!(
                "Native Relay quote input amount mismatch: expected {}, got {}",
                params.amount_in, quoted_amount_in
            )));
        }

        let signed_amount_in = BigUint::from_str(&order.seller_token_amount).map_err(|e| {
            RFQError::ParsingError(format!(
                "Failed to parse signed seller token amount: {} ({e})",
                order.seller_token_amount
            ))
        })?;
        if signed_amount_in != params.amount_in {
            return Err(RFQError::FatalError(format!(
                "Native Relay signed input amount mismatch: expected {}, got {}",
                params.amount_in, signed_amount_in
            )));
        }

        // effectiveSellerTokenAmount may differ from the requested gross input for
        // fee-on-transfer tokens, so it is not an equality invariant here. amountIn and
        // sellerTokenAmount still bind the quote to Tycho's requested input.
        // Native requires txRequest.value for native-token quotes. Validate the quoted value here,
        // while it still describes the original signed amount. During execution, the preceding hop
        // may deliver either less or more; the executor handles that through actualSellerAmount.
        let quoted_value = BigUint::from_str(&quote_response.tx_request.value).map_err(|e| {
            RFQError::ParsingError(format!(
                "Failed to parse Native txRequest.value: {} ({e})",
                quote_response.tx_request.value
            ))
        })?;
        let expected_value =
            if seller_token == Address::ZERO { quoted_amount_in.clone() } else { BigUint::ZERO };
        if quoted_value != expected_value {
            return Err(RFQError::FatalError(format!(
                "Native Relay payable value mismatch: expected {}, got {}",
                expected_value, quoted_value
            )));
        }

        if quote_response
            .tx_request
            .calldata
            .is_empty()
        {
            return Err(RFQError::QuoteNotFound(
                "Native Relay quote did not include calldata".to_string(),
            ));
        }
        // Calldata is pre-built by Native Relay, ready to submit as-is.
        let calldata = hex::decode(
            quote_response
                .tx_request
                .calldata
                .trim_start_matches("0x"),
        )
        .map_err(|e| RFQError::ParsingError(format!("Failed to decode calldata: {e}")))?;

        if calldata.len() < MIN_TRADE_RFQT_CALLDATA_LEN {
            return Err(RFQError::FatalError(format!(
                "Native tradeRFQT calldata too short: expected at least {} bytes, got {}",
                MIN_TRADE_RFQT_CALLDATA_LEN,
                calldata.len()
            )));
        }

        if calldata[..TRADE_RFQT_SELECTOR.len()] != TRADE_RFQT_SELECTOR {
            return Err(RFQError::FatalError(format!(
                "Unexpected Native V6 selector: expected 0x{}, got 0x{}",
                hex::encode(TRADE_RFQT_SELECTOR),
                hex::encode(&calldata[..TRADE_RFQT_SELECTOR.len()]),
            )));
        }

        // These offsets are fixed by V6's tradeRFQT ABI (a dynamic quote tuple and
        // two uint256 overrides). Rejecting any other value catches an incompatible or malformed
        // API response before it reaches the encoder; the executor independently
        // hardcodes the same positions rather than trusting route data.
        if quote_response.amount_in_offset as usize != ACTUAL_SELLER_AMOUNT_OFFSET ||
            quote_response.amount_out_minimum_offset as usize != ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET
        {
            return Err(RFQError::FatalError(format!(
                "Unexpected Native V6 override offsets: expected {}/{} but got {}/{}",
                ACTUAL_SELLER_AMOUNT_OFFSET,
                ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET,
                quote_response.amount_in_offset,
                quote_response.amount_out_minimum_offset,
            )));
        }

        if calldata[ACTUAL_SELLER_AMOUNT_OFFSET..ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET]
            .iter()
            .any(|byte| *byte != 0)
        {
            return Err(RFQError::FatalError(
                "Native actualSellerAmount override must be zero".to_string(),
            ));
        }
        if calldata[ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET..MIN_TRADE_RFQT_CALLDATA_LEN]
            .iter()
            .any(|byte| *byte != 0)
        {
            return Err(RFQError::FatalError(
                "Native actualMinOutputAmount override must be zero".to_string(),
            ));
        }

        let target = Bytes::from_str(&quote_response.tx_request.target).map_err(|e| {
            RFQError::ParsingError(format!(
                "Failed to parse router target address: {} ({e})",
                quote_response.tx_request.target
            ))
        })?;

        let mut quote_attributes: HashMap<String, Bytes> = HashMap::new();
        quote_attributes.insert("target".to_string(), target);
        quote_attributes.insert("calldata".to_string(), Bytes::from(calldata));
        quote_attributes.insert(
            "deadline_timestamp".to_string(),
            Bytes::from(
                order
                    .deadline_timestamp
                    .to_be_bytes()
                    .to_vec(),
            ),
        );

        Ok(SignedQuote {
            base_token: params.token_in.clone(),
            quote_token: params.token_out.clone(),
            amount_in: quoted_amount_in,
            amount_out: BigUint::from_str(&quote_response.amount_out).map_err(|e| {
                RFQError::ParsingError(format!(
                    "Failed to parse amount_out: {} ({e})",
                    quote_response.amount_out
                ))
            })?,
            quote_attributes,
        })
    }
}

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

    use rstest::rstest;
    use tycho_common::models::Chain;

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

    fn successful_quote_json(amount_in: &str) -> serde_json::Value {
        let calldata = format!("0x7083527c{:064x}{:064x}{:064x}", 0x60u8, 0u8, 0u8);
        serde_json::json!({
            "success": true,
            "orders": [{
                "pool": "0x1111111111111111111111111111111111111111",
                "signer": "0x2222222222222222222222222222222222222222",
                "recipient": "0x4444444444444444444444444444444444444444",
                "sellerToken": "0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2",
                "buyerToken": "0xdAC17F958D2ee523a2206206994597C13D831ec7",
                "effectiveSellerTokenAmount": amount_in,
                "sellerTokenAmount": amount_in,
                "buyerTokenAmount": "2",
                "deadlineTimestamp": u64::MAX,
                "nonce": 1,
                "quoteId": "test-quote",
                "multiHop": false,
                "signature": "",
                "externalSwapCalldata": "",
                "amountOutMinimum": "2",
                "widgetFee": {
                    "signer": "0x0000000000000000000000000000000000000000",
                    "feeRecipient": "0x0000000000000000000000000000000000000000",
                    "feeRate": 0.0
                },
                "widgetFeeSignature": ""
            }],
            "widgetFee": {
                "signer": "0x0000000000000000000000000000000000000000",
                "feeRecipient": "0x0000000000000000000000000000000000000000",
                "feeRate": 0.0
            },
            "widgetFeeSignature": "",
            "recipient": "0x4444444444444444444444444444444444444444",
            "amountIn": amount_in,
            "amountOut": "2",
            "amountOutBeforeFee": "2",
            "fallbackSwapDataArray": null,
            "tokenTransferFeeOnPercent": 0.0,
            "txRequest": {
                "target": "0x4777A6B3A9A889ABfd4C7666Bdd2a7AB633293be",
                "calldata": calldata,
                "value": "0"
            },
            "source": [6],
            "errorMessage": "",
            "router_version": "6",
            "toWrap": false,
            "toUnwrap": false,
            "amountInOffset": 36,
            "amountOutMinimumOffset": 68
        })
    }

    fn successful_quote_response(amount_in: &str) -> FirmQuoteResponse {
        serde_json::from_value(successful_quote_json(amount_in)).unwrap()
    }

    fn create_test_client(endpoint: &str) -> NativeClient {
        NativeClient::new(
            Some(endpoint),
            NativeSupportedChain::Ethereum,
            "secret_key".to_string(),
            Duration::from_secs(5),
        )
    }

    fn create_test_quote_params() -> GetAmountOutParams {
        GetAmountOutParams {
            amount_in: BigUint::from(1u64),
            token_in: Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(),
            token_out: Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(),
            sender: Bytes::from_str("0x3333333333333333333333333333333333333333").unwrap(),
            receiver: Bytes::from_str("0x4444444444444444444444444444444444444444").unwrap(),
            origin: None,
        }
    }

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

        assert!(!rendered.contains("secret_key"));
        assert!(rendered.contains("native.example"));
    }

    #[test]
    fn accepts_quote_with_requested_input_amount() {
        let params = create_test_quote_params();
        let response = successful_quote_response(&params.amount_in.to_string());

        let quote = NativeClient::process_quote_response(&response, &params).unwrap();

        assert_eq!(quote.amount_in, params.amount_in);
        assert_eq!(
            quote
                .quote_attributes
                .get("deadline_timestamp")
                .unwrap()
                .as_ref(),
            u64::MAX.to_be_bytes()
        );
    }

    #[test]
    fn rejects_quote_with_mismatched_input_amount() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        // Keep sellerTokenAmount correct so only the top-level amountIn check can reject this.
        response.amount_in = "2".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("Native Relay quote input amount mismatch")
        ));
    }

    #[test]
    fn rejects_quote_with_mismatched_signed_input_amount() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.orders[0].seller_token_amount = "2".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("signed input amount mismatch")
        ));
    }

    #[test]
    fn accepts_quote_with_different_effective_input_amount() {
        let mut params = create_test_quote_params();
        params.amount_in = BigUint::from(100u64);
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.orders[0].effective_seller_token_amount = "99".to_string();

        let quote = NativeClient::process_quote_response(&response, &params).unwrap();

        assert_eq!(quote.amount_in, params.amount_in);
    }

    #[rstest]
    #[case::seller_token(true)]
    #[case::buyer_token(false)]
    fn rejects_quote_with_mismatched_token(#[case] mutate_seller_token: bool) {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        let mismatched_token = "0x5555555555555555555555555555555555555555".to_string();
        if mutate_seller_token {
            response.orders[0].seller_token = mismatched_token;
        } else {
            response.orders[0].buyer_token = mismatched_token;
        }

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("quote token mismatch")
        ));
    }

    #[test]
    fn rejects_quote_with_mismatched_recipient() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.orders[0].recipient = "0x5555555555555555555555555555555555555555".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("recipient mismatch")
        ));
    }

    #[test]
    fn rejects_quote_without_calldata() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.tx_request.calldata.clear();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::QuoteNotFound(message)) if message.contains("did not include calldata")
        ));
    }

    #[test]
    fn rejects_truncated_trade_calldata() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.tx_request.calldata = format!("0x7083527c{}", "00".repeat(95));

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("calldata too short")
        ));
    }

    #[test]
    fn rejects_quote_with_wrong_trade_rfqt_selector() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        let mut calldata = hex::decode(
            response
                .tx_request
                .calldata
                .trim_start_matches("0x"),
        )
        .unwrap();
        // V4 also exposes tradeRFQT, but its quote tuple has a different ABI.
        calldata[..4].copy_from_slice(&[0x09, 0x47, 0xc2, 0xd9]);
        response.tx_request.calldata = format!("0x{}", hex::encode(calldata));

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("selector")
        ));
    }

    #[rstest]
    #[case::v4("4")]
    #[case::unknown("7")]
    fn rejects_quote_with_wrong_router_version(#[case] version: &str) {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.router_version = version.to_string();

        assert!(matches!(
            NativeClient::process_quote_response(&response, &params),
            Err(RFQError::FatalError(message)) if message.contains("Unexpected Native router version")
        ));
    }

    #[rstest]
    #[case::seller_offset(68, 68)]
    #[case::minimum_offset(36, 36)]
    fn rejects_quote_with_noncanonical_override_offsets(
        #[case] amount_in_offset: u32,
        #[case] amount_out_minimum_offset: u32,
    ) {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.amount_in_offset = amount_in_offset;
        response.amount_out_minimum_offset = amount_out_minimum_offset;

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains(
                "Unexpected Native V6 override offsets"
            )
        ));
    }

    #[rstest]
    #[case::seller(ACTUAL_SELLER_AMOUNT_OFFSET, "actualSellerAmount")]
    #[case::minimum(ACTUAL_MIN_OUTPUT_AMOUNT_OFFSET, "actualMinOutputAmount")]
    fn rejects_quote_with_preset_override(
        #[case] override_offset: usize,
        #[case] field_name: &str,
    ) {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        let mut calldata = hex::decode(
            response
                .tx_request
                .calldata
                .trim_start_matches("0x"),
        )
        .unwrap();
        calldata[override_offset + 31] = 1;
        response.tx_request.calldata = format!("0x{}", hex::encode(calldata));

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains(field_name)
        ));
    }

    #[test]
    fn accepts_native_eth_response_using_zero_address() {
        let mut params = create_test_quote_params();
        params.token_in = Bytes::zero(20);
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.orders[0].seller_token = "0x0000000000000000000000000000000000000000".to_string();
        response.tx_request.value = params.amount_in.to_string();

        let quote = NativeClient::process_quote_response(&response, &params).unwrap();

        assert_eq!(quote.amount_in, params.amount_in);
    }

    #[test]
    fn rejects_native_quote_with_mismatched_payable_value() {
        let mut params = create_test_quote_params();
        params.token_in = Bytes::zero(20);
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.orders[0].seller_token = "0x0000000000000000000000000000000000000000".to_string();
        response.tx_request.value = "2".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("payable value mismatch")
        ));
    }

    #[test]
    fn rejects_malformed_payable_value() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.tx_request.value = "not-a-number".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::ParsingError(message)) if message.contains("txRequest.value")
        ));
    }

    #[test]
    fn rejects_erc20_quote_with_nonzero_payable_value() {
        let params = create_test_quote_params();
        let mut response = successful_quote_response(&params.amount_in.to_string());
        response.tx_request.value = "1".to_string();

        let result = NativeClient::process_quote_response(&response, &params);

        assert!(matches!(
            result,
            Err(RFQError::FatalError(message)) if message.contains("payable value mismatch")
        ));
    }

    #[tokio::test]
    async fn requests_v6_firm_quote() {
        let seen_target = Arc::new(Mutex::new(None));
        let record = Arc::clone(&seen_target);
        let server = spawn_http_server(move |request| {
            *record.lock().unwrap() = Some(request.target.to_string());
            Some(("200 OK", successful_quote_json("1").to_string()))
        })
        .await;
        let client = create_test_client(&server.url());
        let params = create_test_quote_params();

        let quote = client
            .request_binding_quote(&params)
            .await
            .unwrap();
        let target = seen_target
            .lock()
            .unwrap()
            .clone()
            .expect("one request");
        let url = reqwest::Url::parse(&format!("{}{target}", server.url())).unwrap();
        let query: HashMap<_, _> = url.query_pairs().into_owned().collect();

        assert_eq!(url.path(), "/firm-quote");
        assert_eq!(query.get("version").map(String::as_str), Some("6"));
        assert_eq!(
            query
                .get("allow_multihop")
                .map(String::as_str),
            Some("false")
        );
        assert_eq!(quote.amount_in, params.amount_in);
    }

    /// Answers every request only after an hour, so any client deadline fires first.
    async fn create_hanging_quote_server() -> MockHttpServer {
        spawn_http_server(|_| {
            Some(MockResponse {
                delay: Duration::from_secs(3600),
                ..MockResponse::from(("200 OK", String::new()))
            })
        })
        .await
    }

    #[tokio::test]
    async fn handles_documented_quote_error_without_retrying() {
        let server = spawn_http_server(|_| {
            Some((
                "200 OK",
                r#"{"code":171015,"message":"quoted token not available"}"#.to_string(),
            ))
        })
        .await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        match result {
            Err(RFQError::QuoteNotFound(message)) => {
                assert!(message.contains("171015"));
                assert!(message.contains("quoted token not available"));
            }
            other => panic!("Expected Native API error, got {other:?}"),
        }
        assert_eq!(server.request_count(), 1);
    }

    #[tokio::test]
    async fn handles_success_false_as_quote_not_found_without_retrying() {
        let mut response = successful_quote_json("1");
        response["success"] = serde_json::Value::Bool(false);
        response["errorMessage"] = serde_json::Value::String("quote unavailable".to_string());
        let body = response.to_string();
        let server = spawn_http_server(move |_| Some(("200 OK", body.clone()))).await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        assert!(matches!(
            result,
            Err(RFQError::QuoteNotFound(message)) if message.contains("quote unavailable")
        ));
        assert_eq!(server.request_count(), 1);
    }

    #[tokio::test]
    async fn retries_documented_temporary_api_error() {
        let server = spawn_http_server(|_| {
            Some((
                "200 OK",
                r#"{"code":301016,"message":"quote invalid, risk management checks failed"}"#
                    .to_string(),
            ))
        })
        .await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        assert!(matches!(result, Err(RFQError::QuoteNotFound(_))));
        assert_eq!(server.request_count(), 3);
    }

    #[tokio::test]
    async fn retries_server_error_without_native_error_envelope() {
        let server = spawn_http_server(|_| {
            Some(("503 Service Unavailable", "<html>upstream unavailable</html>".to_string()))
        })
        .await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        assert!(matches!(
            result,
            Err(RFQError::ConnectionError(message)) if message.contains("503 Service Unavailable")
        ));
        assert_eq!(server.request_count(), 3);
    }

    #[tokio::test]
    async fn retries_malformed_success_response() {
        let server =
            spawn_http_server(|_| Some(("200 OK", r#"{"unexpected":true}"#.to_string()))).await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        assert!(matches!(result, Err(RFQError::ParsingError(_))));
        assert_eq!(server.request_count(), 3);
    }

    #[tokio::test]
    async fn times_out_when_quote_response_stalls() {
        let server = create_hanging_quote_server().await;
        let client = NativeClient::new(
            Some(&server.url()),
            NativeSupportedChain::Ethereum,
            "secret_key".to_string(),
            Duration::from_millis(50),
        );

        let result = tokio::time::timeout(
            Duration::from_secs(1),
            client.request_binding_quote(&create_test_quote_params()),
        )
        .await
        .expect("Native quote timeout did not terminate the request");

        assert!(matches!(
            result,
            Err(RFQError::ConnectionError(message)) if message.contains("timed out after 50ms")
        ));
    }

    #[tokio::test]
    async fn shares_quote_timeout_across_retries() {
        let params = create_test_quote_params();
        let success_body = successful_quote_json(&params.amount_in.to_string()).to_string();
        let quote_timeout = NATIVE_API_RETRY_DELAY * 2;

        let attempts = AtomicUsize::new(0);
        let server = spawn_http_server(move |_| {
            let attempt = attempts.fetch_add(1, Ordering::SeqCst);
            if attempt == 0 {
                let retry_body =
                    r#"{"code":301016,"message":"quote invalid, risk management checks failed"}"#
                        .to_string();
                return Some(MockResponse::from(("200 OK", retry_body)));
            }
            // This fits a fresh timeout, but not the time left after the retry backoff.
            Some(MockResponse {
                delay: quote_timeout * 3 / 4,
                ..MockResponse::from(("200 OK", success_body.clone()))
            })
        })
        .await;

        let client = NativeClient::new(
            Some(&server.url()),
            NativeSupportedChain::Ethereum,
            "secret_key".to_string(),
            quote_timeout,
        );

        let result = timeout(Duration::from_secs(5), client.request_binding_quote(&params))
            .await
            .expect("Native quote timeout did not terminate the retries");

        assert!(matches!(
            result,
            Err(RFQError::QuoteNotFound(message)) if message.contains("301016")
        ));
        assert_eq!(server.request_count(), 2);
    }

    #[tokio::test]
    async fn does_not_retry_documented_authentication_error() {
        let server = spawn_http_server(|_| {
            Some((
                "200 OK",
                r#"{"code":201001,"message":"auth get api key is invalid"}"#.to_string(),
            ))
        })
        .await;
        let client = create_test_client(&server.url());

        let result = client
            .request_binding_quote(&create_test_quote_params())
            .await;

        assert!(matches!(result, Err(RFQError::FatalError(_))));
        assert_eq!(server.request_count(), 1);
    }

    /// Native refuses a chain it does not serve with `131005 chain parameters invalid`, so an
    /// orderbook that comes back is the venue confirming the chain. Nothing else keeps this
    /// enum in step with it.
    #[rstest]
    #[case::ethereum(Chain::Ethereum)]
    #[case::bsc(Chain::Bsc)]
    #[case::robinhood(Chain::Robinhood)]
    #[case::base(Chain::Base)]
    #[case::arbitrum(Chain::Arbitrum)]
    #[tokio::test]
    #[ignore = "hits Native's live API; requires NATIVE_API_KEY"]
    async fn live_native_api_serves_every_chain_the_enum_names(#[case] chain: Chain) {
        #[expect(
            clippy::unused_result_ok,
            reason = "a missing .env file is fine; the variables may come from the environment"
        )]
        dotenvy::dotenv().ok();
        let api_key = std::env::var("NATIVE_API_KEY").expect("NATIVE_API_KEY not set");
        let client = NativeClient::new(
            None,
            NativeSupportedChain::try_from(chain).unwrap(),
            api_key,
            Duration::from_secs(10),
        );

        client.fetch_orderbook().await.unwrap();
    }
}