tycho-simulation 0.528.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
use std::time::{SystemTime, UNIX_EPOCH};

use alloy::{
    primitives::{address, Address, U256},
    sol,
    sol_types::SolCall,
};
use num_bigint::BigUint;
use num_traits::Zero;
use serde::{Deserialize, Serialize};
use serde_with::{serde_as, DisplayFromStr};
use tracing::debug;
use tycho_common::{
    models::{protocol::GetAmountOutParams, Chain},
    Bytes,
};

use crate::{
    book::{
        levels::{InvalidLevel, Levels, PriceLevel},
        wire::{EntryReader, SkipInvalidEntries},
    },
    evm::protocol::u256_num::u256_to_biguint,
    rfq::errors::RFQError,
    snapshot_feed::errors::FeedError,
};

sol! {
    /// A 1inch limit-order-protocol v3 RFQ order, the type the Aggregation Router v5 fills.
    struct OrderRFQ {
        uint256 info;
        address makerAsset;
        address takerAsset;
        address maker;
        address allowedSender;
        uint256 makingAmount;
        uint256 takingAmount;
    }

    /// `AggregationRouterV5.fillOrderRFQTo`, the only call a binding quote may carry.
    function fillOrderRFQTo(OrderRFQ order, bytes signature, uint256 flagsAndAmount, address target);
}

/// The chains Euclid's RFQ gateway quotes on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum EuclidSupportedChain {
    Ethereum,
}

impl EuclidSupportedChain {
    /// The chain id the gateway's endpoints address this chain by.
    pub fn id(self) -> u64 {
        match self {
            EuclidSupportedChain::Ethereum => 1,
        }
    }

    /// The 1inch Aggregation Router v5 on this chain, which settles every Euclid order there;
    /// the executor is deployed with the same address.
    pub fn settlement_router(self) -> Address {
        match self {
            EuclidSupportedChain::Ethereum => address!("1111111254EEB25477B68fb85Ed929f73A960582"),
        }
    }
}

impl TryFrom<Chain> for EuclidSupportedChain {
    type Error = String;

    #[expect(
        clippy::wildcard_enum_match_arm,
        reason = "Euclid serves one chain; every other, present or future, is refused"
    )]
    fn try_from(chain: Chain) -> Result<Self, Self::Error> {
        match chain {
            Chain::Ethereum => Ok(EuclidSupportedChain::Ethereum),
            other => Err(format!("Euclid does not serve {other}")),
        }
    }
}

/// One frame of the levels stream: every pair the gateway prices on the chain. Each frame
/// replaces the one before it, so a pair missing from a frame is no longer priced.
#[serde_as]
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidLevelsFrame {
    pub chain_id: u64,
    #[serde_as(deserialize_as = "SkipInvalidEntries")]
    pub pairs: Vec<EuclidPairLevels>,
}

/// One pair as the gateway publishes it. Prices and sizes travel as decimal strings.
#[serde_as]
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidPairLevels {
    pub base_address: Bytes,
    pub quote_address: Bytes,
    /// `[price, size]`, best first: quote per base unit, base quantity.
    #[serde_as(as = "Vec<(DisplayFromStr, DisplayFromStr)>")]
    pub bids: Vec<(f64, f64)>,
    #[serde_as(as = "Vec<(DisplayFromStr, DisplayFromStr)>")]
    pub asks: Vec<(f64, f64)>,
    /// When the gateway built these levels, in milliseconds since the epoch.
    pub timestamp: u64,
}

/// One pair's validated book: the bid and ask ladders between a base and a quote token. The
/// first level of each side is the least the gateway signs for on that side, at that side's
/// best price.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct EuclidBook {
    pub base: Bytes,
    pub quote: Bytes,
    /// When the gateway built these levels, in milliseconds since the epoch.
    pub updated_at_ms: u64,
    /// Selling base: `quote` per base unit, base quantities.
    pub bids: Levels,
    /// Buying base: `quote` per base unit, base quantities.
    pub asks: Levels,
}

impl TryFrom<EuclidPairLevels> for EuclidBook {
    type Error = InvalidLevel;

    fn try_from(pair: EuclidPairLevels) -> Result<Self, InvalidLevel> {
        let ladder = |side: Vec<(f64, f64)>| {
            Levels::new(
                side.into_iter()
                    .map(|(price, quantity)| PriceLevel { price, quantity })
                    .collect(),
            )
        };
        Ok(EuclidBook {
            bids: ladder(pair.bids)?,
            asks: ladder(pair.asks)?,
            base: pair.base_address,
            quote: pair.quote_address,
            updated_at_ms: pair.timestamp,
        })
    }
}

impl EuclidBook {
    /// The book's liquidity in quote-token units: the mean of what each side is worth.
    pub fn notional_tvl(&self) -> f64 {
        (self.bids.notional() + self.asks.notional()) / 2.0
    }
}

/// Pairs from one levels frame, excluding pairs with invalid levels, in the order Euclid sent
/// them: every pair the gateway prices on the chain, so a pair missing from one frame is no
/// longer priced.
///
/// The serde form follows the venue API model [`EuclidBook`], so the writer and the reader must
/// run the same tycho-simulation version.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct EuclidPrices {
    /// The chain the frame prices, as the gateway numbers it.
    pub chain_id: u64,
    /// The valid pairs of the frame, in the order Euclid sent them.
    pub pairs: Vec<EuclidBook>,
}

impl EuclidPrices {
    /// Reads every pair of `frame`, dropping the ones whose levels are invalid. Fails only when
    /// none is valid.
    pub(super) fn from_frame(frame: EuclidLevelsFrame) -> Result<Self, FeedError> {
        let mut reader = EntryReader::new();
        let pairs = reader.read(frame.pairs, EuclidBook::try_from);
        reader
            .finish()
            .map_err(|reason| FeedError::Parsing(format!("Euclid levels frame: {reason}")))?;
        debug!(pairs = pairs.len(), "decoded levels frame");
        Ok(EuclidPrices { chain_id: frame.chain_id, pairs })
    }
}

/// The gateway's answer to a binding quote request: the quote, or why it declined to give one.
#[derive(Debug, Clone, Deserialize)]
#[serde(untagged)]
pub enum EuclidFirmResponse {
    Quote(EuclidFirmQuote),
    Declined(EuclidDeclined),
}

/// A binding quote: `calldata` fills a maker-signed 1inch limit-order-protocol v3 RFQ order
/// through `tx_to`. Everything the fill pays, admits and expires at is in the signed order, so
/// it is read from there rather than from the fields beside it.
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidFirmQuote {
    pub tx_to: Bytes,
    pub calldata: Bytes,
    /// How the gateway records the fill.
    pub order_hash: Bytes,
}

/// Why the gateway declined a quote, e.g. `insufficient_liquidity`.
#[derive(Debug, Clone, Deserialize)]
pub struct EuclidDeclined {
    pub error: String,
}

impl EuclidFirmQuote {
    /// What the signed order pays for the trade `params` asked for on `chain`.
    ///
    /// A quote whose router, call, assets, fill amount, recipient or admitted filler differ from
    /// that trade is a `FatalError`: it would only revert on chain. An order that has expired,
    /// or that pays nothing for the fill, is `QuoteNotFound`, like a declined request: the
    /// router would refuse it too, and asking again may get a fresh order.
    pub fn amount_out(
        &self,
        chain: EuclidSupportedChain,
        params: &GetAmountOutParams,
    ) -> Result<BigUint, RFQError> {
        if self.tx_to.as_ref() != chain.settlement_router().as_slice() {
            return Err(RFQError::FatalError(format!(
                "Euclid order settles through {}, not the 1inch Aggregation Router v5",
                self.tx_to
            )));
        }
        let call = fillOrderRFQToCall::abi_decode(self.calldata.as_ref()).map_err(|e| {
            RFQError::FatalError(format!("Euclid calldata is not a fillOrderRFQTo call: {e}"))
        })?;
        let order = &call.order;
        if order.makerAsset.as_slice() != params.token_out.as_ref() {
            return Err(RFQError::FatalError(format!(
                "Euclid order pays {}, requested {}",
                order.makerAsset, params.token_out
            )));
        }
        if order.takerAsset.as_slice() != params.token_in.as_ref() {
            return Err(RFQError::FatalError(format!(
                "Euclid order takes {}, requested {}",
                order.takerAsset, params.token_in
            )));
        }
        // A plain amount: the router fills exactly this much of the taker asset.
        let fill = u256_to_biguint(call.flagsAndAmount);
        if fill != params.amount_in {
            return Err(RFQError::FatalError(format!(
                "Euclid calldata fills {fill}, requested {}",
                params.amount_in
            )));
        }
        let taking_amount = u256_to_biguint(order.takingAmount);
        if fill.is_zero() || fill > taking_amount {
            return Err(RFQError::FatalError(format!(
                "Euclid calldata fills {fill} of an order taking {taking_amount}"
            )));
        }
        if call.target.as_slice() != params.receiver.as_ref() {
            return Err(RFQError::FatalError(format!(
                "Euclid order delivers to {}, requested {}",
                call.target, params.receiver
            )));
        }
        if order.allowedSender.as_slice() != params.sender.as_ref() {
            return Err(RFQError::FatalError(format!(
                "Euclid order admits {} as its filler, requested sender {}",
                order.allowedSender, params.sender
            )));
        }
        // `info` carries the nonce in its low 64 bits and the expiry in the 64 above. The router
        // reads an expiry of 0 as an order that never expires.
        let expiry = ((order.info >> 64usize) & U256::from(u64::MAX)).to::<u64>();
        if expiry != 0 {
            let now = SystemTime::now()
                .duration_since(UNIX_EPOCH)
                .map_err(|_before_epoch| {
                    RFQError::FatalError("system clock is before the epoch".to_string())
                })?
                .as_secs();
            if expiry <= now {
                return Err(RFQError::QuoteNotFound(format!(
                    "Euclid order expired at {expiry}, now {now}"
                )));
            }
        }
        // What the router pays for `fill`: the maker's amount, pro rata, rounded down. The
        // router reverts a fill that pays nothing (`RFQSwapWithZeroAmount`).
        let amount_out = u256_to_biguint(order.makingAmount) * fill / taking_amount;
        if amount_out.is_zero() {
            return Err(RFQError::QuoteNotFound(format!(
                "Euclid order pays nothing for a fill of {}",
                params.amount_in
            )));
        }
        Ok(amount_out)
    }
}

#[cfg(test)]
mod tests {
    use std::str::FromStr;

    use rstest::rstest;

    use super::*;
    use crate::rfq::protocols::euclid::test_support::{
        bytes, quote_with, recorded_params, LEVELS_FRAME, RECORDED_AMOUNT_OUT, USDC, WETH,
    };

    #[test]
    fn a_recorded_frame_parses_into_validated_books() {
        let frame: EuclidLevelsFrame = serde_json::from_str(LEVELS_FRAME).unwrap();
        assert_eq!(frame.chain_id, 1);
        assert_eq!(frame.pairs.len(), 1);

        let book = EuclidBook::try_from(frame.pairs[0].clone()).unwrap();
        assert_eq!(book.base, bytes(WETH));
        assert_eq!(book.quote, bytes(USDC));
        assert_eq!(book.updated_at_ms, 1_794_312_452_328);
        // The gateway publishes its minimum trade as the first level of each side, at that
        // side's best price, so the first two levels share a price.
        let level = |price, quantity| PriceLevel { price, quantity };
        assert_eq!(
            book.bids[..],
            [level(2074.90778485, 0.00096390), level(2074.90778485, 0.00534533)]
        );
        assert_eq!(
            book.asks[..],
            [level(2103.07940882, 0.00095099), level(2103.07940882, 0.00152401)]
        );
    }

    #[test]
    fn a_pair_that_does_not_parse_is_dropped_and_the_rest_kept() {
        let frame = format!(
            r#"{{"chain_id":1,"pairs":[
                {{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["not a price","1"]],"asks":[],"timestamp":1}},
                {{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","1"]],"asks":[["3001","1"]],"timestamp":2}}
            ]}}"#
        );
        let frame: EuclidLevelsFrame = serde_json::from_str(&frame).unwrap();
        assert_eq!(frame.pairs.len(), 1);
        assert_eq!(frame.pairs[0].timestamp, 2);
    }

    #[test]
    fn a_frame_whose_every_pair_fails_to_parse_is_an_error() {
        let frame = format!(
            r#"{{"chain_id":1,"pairs":[{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["x","1"]],"asks":[],"timestamp":1}}]}}"#
        );
        assert!(serde_json::from_str::<EuclidLevelsFrame>(&frame).is_err());
    }

    #[test]
    fn a_frame_with_no_pairs_parses_as_empty() {
        let frame: EuclidLevelsFrame =
            serde_json::from_str(r#"{"chain_id":1,"timestamp":0,"pairs":[]}"#).unwrap();
        assert!(frame.pairs.is_empty());
    }

    #[rstest]
    #[case::negative_size("3000", "-1", InvalidLevel::Quantity(-1.0))]
    #[case::zero_price("0", "1", InvalidLevel::Price(0.0))]
    fn an_invalid_level_rejects_the_book(
        #[case] price: &str,
        #[case] size: &str,
        #[case] expected: InvalidLevel,
    ) {
        let pair: EuclidPairLevels = serde_json::from_str(&format!(
            r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["{price}","{size}"]],"asks":[],"timestamp":1}}"#
        ))
        .unwrap();
        assert_eq!(EuclidBook::try_from(pair).unwrap_err(), expected);
    }

    /// A pair with an invalid level costs that pair and no other; a frame with none valid fails.
    #[test]
    fn prices_keep_the_valid_pairs_of_a_frame() {
        let frame = |pairs: &str| -> EuclidLevelsFrame {
            serde_json::from_str(&format!(r#"{{"chain_id":1,"pairs":[{pairs}]}}"#)).unwrap()
        };
        let valid = format!(
            r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","1"]],"asks":[["3001","1"]],"timestamp":2}}"#
        );
        let invalid = format!(
            r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","-1"]],"asks":[],"timestamp":1}}"#
        );

        let prices = EuclidPrices::from_frame(frame(&format!("{invalid},{valid}"))).unwrap();
        assert_eq!(prices.chain_id, 1);
        assert_eq!(prices.pairs.len(), 1);
        assert_eq!(prices.pairs[0].updated_at_ms, 2);

        assert!(matches!(EuclidPrices::from_frame(frame(&invalid)), Err(FeedError::Parsing(_))));
        assert!(EuclidPrices::from_frame(frame(""))
            .unwrap()
            .pairs
            .is_empty());
    }

    #[test]
    fn prices_survive_a_serde_round_trip() {
        let frame: EuclidLevelsFrame = serde_json::from_str(LEVELS_FRAME).unwrap();
        let prices = EuclidPrices::from_frame(frame).unwrap();
        let sent = serde_json::to_string(&prices).unwrap();
        let received: EuclidPrices = serde_json::from_str(&sent).unwrap();
        assert_eq!(received, prices);
    }

    #[test]
    fn notional_tvl_is_the_mean_of_both_sides() {
        let pair: EuclidPairLevels = serde_json::from_str(&format!(
            r#"{{"base_address":"{WETH}","quote_address":"{USDC}","bids":[["3000","2"]],"asks":[["3002","1"]],"timestamp":1}}"#
        ))
        .unwrap();
        // (3000 * 2 + 3002 * 1) / 2
        assert_eq!(
            EuclidBook::try_from(pair)
                .unwrap()
                .notional_tvl(),
            4501.0
        );
    }

    #[test]
    fn a_decline_parses_as_one() {
        let response: EuclidFirmResponse =
            serde_json::from_str(r#"{"error":"insufficient_liquidity"}"#).unwrap();
        assert!(
            matches!(response, EuclidFirmResponse::Declined(d) if d.error == "insufficient_liquidity")
        );
    }

    /// The recorded quote is the trade it was requested for, and pays what its signed order
    /// says.
    #[test]
    fn the_recorded_quote_pays_what_its_order_signs() {
        let amount_out = quote_with(|_| {})
            .amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
            .unwrap();
        assert_eq!(amount_out, BigUint::from_str(RECORDED_AMOUNT_OUT).unwrap());
    }

    /// A smaller fill of the same order pays pro rata, rounded down, as the router does. Half
    /// the order divides exactly; a third of it and one wei pays 6241692 * (1e15 + 1) / 3e15 =
    /// 2080564.000...002, which the router rounds down to 2080564 where rounding up would give
    /// 2080565.
    #[rstest]
    #[case::half(1_500_000_000_000_000, 3_120_846)]
    #[case::a_third_and_a_wei(1_000_000_000_000_001, 2_080_564)]
    fn a_partial_fill_pays_pro_rata_rounded_down(#[case] fill: u64, #[case] expected: u64) {
        let quote = quote_with(|call| call.flagsAndAmount = U256::from(fill));
        let params = GetAmountOutParams { amount_in: BigUint::from(fill), ..recorded_params() };
        assert_eq!(
            quote
                .amount_out(EuclidSupportedChain::Ethereum, &params)
                .unwrap(),
            BigUint::from(expected)
        );
    }

    /// Every way a quote can disagree with the request it answers fails, each for its own
    /// reason.
    #[rstest]
    #[case::fill_word(
        |_: &mut GetAmountOutParams, c: &mut fillOrderRFQToCall| c.flagsAndAmount = U256::from(1u8),
        "calldata fills 1, requested 3000000000000000"
    )]
    #[case::token_in(
        |p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.token_in = bytes(USDC),
        "order takes"
    )]
    #[case::token_out(
        |p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.token_out = bytes(WETH),
        "order pays"
    )]
    #[case::receiver(
        |p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.receiver = bytes(USDC),
        "delivers to"
    )]
    #[case::sender(
        |p: &mut GetAmountOutParams, _: &mut fillOrderRFQToCall| p.sender = bytes(USDC),
        "admits"
    )]
    fn a_quote_that_disagrees_with_the_request_fails(
        #[case] tamper: fn(&mut GetAmountOutParams, &mut fillOrderRFQToCall),
        #[case] reason: &str,
    ) {
        let mut params = recorded_params();
        let quote = quote_with(|call| tamper(&mut params, call));
        let error = quote
            .amount_out(EuclidSupportedChain::Ethereum, &params)
            .unwrap_err();
        assert!(
            matches!(&error, RFQError::FatalError(message) if message.contains(reason)),
            "expected a failure about {reason:?}, got {error:?}"
        );
    }

    /// An expired order is no quote rather than a fatal error: asking again gets a fresh one.
    #[test]
    fn an_expired_order_is_no_quote() {
        let quote = quote_with(|call| {
            call.order.info = call.order.info & U256::from(u64::MAX) | (U256::from(1u8) << 64usize);
        });
        let error = quote
            .amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
            .unwrap_err();
        assert!(
            matches!(&error, RFQError::QuoteNotFound(message) if message.contains("expired at 1,")),
            "{error:?}"
        );
    }

    /// An expiry of 0 is an order that never expires, as the router reads it.
    #[test]
    fn an_order_without_an_expiry_is_quoted() {
        let quote = quote_with(|call| call.order.info &= U256::from(u64::MAX));
        let amount_out = quote
            .amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
            .unwrap();
        assert_eq!(amount_out, BigUint::from(6_241_692u64));
    }

    /// A fill of one wei pays 6241692 * 1 / 3e15, which rounds down to nothing, a fill the
    /// router reverts; so it is no quote.
    #[test]
    fn a_fill_that_pays_nothing_is_no_quote() {
        let quote = quote_with(|call| call.flagsAndAmount = U256::from(1u8));
        let params = GetAmountOutParams { amount_in: BigUint::from(1u8), ..recorded_params() };
        let error = quote
            .amount_out(EuclidSupportedChain::Ethereum, &params)
            .unwrap_err();
        assert!(
            matches!(&error, RFQError::QuoteNotFound(message) if message.contains("pays nothing")),
            "{error:?}"
        );
    }

    /// A fill of more than the order takes would revert at the router, so it fails here; so
    /// does a fill of nothing, which the router would read as the whole order.
    #[rstest]
    #[case::over_the_order(|taking: U256| taking + U256::from(1u8))]
    #[case::nothing(|_: U256| U256::ZERO)]
    fn a_fill_the_order_does_not_cover_fails(#[case] fill: fn(U256) -> U256) {
        let mut params = recorded_params();
        let quote = quote_with(|call| {
            call.flagsAndAmount = fill(call.order.takingAmount);
            params.amount_in = u256_to_biguint(call.flagsAndAmount);
        });
        let error = quote
            .amount_out(EuclidSupportedChain::Ethereum, &params)
            .unwrap_err();
        assert!(
            matches!(&error, RFQError::FatalError(message) if message.contains("of an order taking")),
            "{error:?}"
        );
    }

    /// Calldata that is not a `fillOrderRFQTo` call, or not a whole one, fails before any field
    /// is read; an order for another router fails whatever the calldata says.
    #[rstest]
    #[case::selector(|q: &mut EuclidFirmQuote| {
        let mut calldata = q.calldata.to_vec();
        calldata[0] ^= 0xff;
        q.calldata = calldata.into();
    }, "not a fillOrderRFQTo call")]
    #[case::truncated(|q: &mut EuclidFirmQuote| {
        q.calldata = q.calldata[..4 + 9 * 32].to_vec().into();
    }, "not a fillOrderRFQTo call")]
    #[case::tx_to(|q: &mut EuclidFirmQuote| q.tx_to = bytes(USDC), "settles through")]
    fn a_quote_that_is_not_a_router_fill_fails(
        #[case] tamper: fn(&mut EuclidFirmQuote),
        #[case] reason: &str,
    ) {
        let mut quote = quote_with(|_| {});
        tamper(&mut quote);
        let error = quote
            .amount_out(EuclidSupportedChain::Ethereum, &recorded_params())
            .unwrap_err();
        assert!(
            matches!(&error, RFQError::FatalError(message) if message.contains(reason)),
            "expected a failure about {reason:?}, got {error:?}"
        );
    }

    #[test]
    fn only_ethereum_is_served() {
        assert_eq!(
            EuclidSupportedChain::try_from(Chain::Ethereum),
            Ok(EuclidSupportedChain::Ethereum)
        );
        assert!(EuclidSupportedChain::try_from(Chain::Base).is_err());
        assert_eq!(EuclidSupportedChain::Ethereum.id(), 1);
    }
}