tycho-simulation 0.550.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
//! Fixtures shared by the Hanji tests: a recording of the Base markets, the states and reads it
//! describes, and a JSON-RPC node that serves it.

use std::{
    collections::{HashMap, HashSet},
    sync::{
        atomic::{AtomicBool, AtomicU64, Ordering},
        Arc, Mutex, MutexGuard, PoisonError,
    },
    time::Duration,
};

use alloy::{
    primitives::{address, aliases::U72, Address, U256},
    providers::{
        bindings::IMulticall3::{
            aggregate3Call, getBlockNumberCall, getChainIdCall, getCurrentBlockTimestampCall,
            Result as Call3Result,
        },
        MULTICALL3_ADDRESS,
    },
    sol_types::{SolCall, SolValue},
};
use reqwest::Url;
use serde::Deserialize;
use tycho_common::{
    models::{token::Token, Chain},
    Bytes,
};

use crate::{
    book::{sim::SwapDirection, BookFeedConfig},
    pamm::protocols::hanji::{
        feed::{HanjiBookAssembler, HanjiBookSource},
        market::Market,
        reader::{
            assembleOrderbookFromOrdersCall, assembleOrderbookFromOrdersReturn, getConfigCall,
            getConfigReturn, pausedCall, whitelistedCall, BookRead, HanjiReader, MarketConfig,
            MarketRead, CONTRACT_QUOTER_SELECTOR, LOB_SELECTOR, MAX_PRICE_LEVELS, QUOTER_SELECTOR,
        },
        state::{HanjiState, Level},
        BASE_DEPLOYMENT, BASE_ROUTER,
    },
    snapshot_feed::http::test_support::{
        spawn_http_server, MockHttpServer, MockRequest, MockResponse,
    },
};

/// Recorded by `testdata/record_fixture.py` at Base block 64,593,995: the API's eight markets,
/// both quoters' books of each, and twelve fills per kind of caller on each of the three whose
/// tokens can be funded (ETH/USDC, cbBTC/USDC and cbBTC/ETH), each fill's output measured as the
/// caller's balance gain, and the implementation every proxy, CLOB and the LPManager ran. Every
/// market had whitelisted Tycho's router.
const RECORDING: &str = include_str!("testdata/live_64593995.json");

/// Hanji's aggregator market list on Base, which `testdata/record_fixture.py` records from and
/// the live test compares with the deployment.
pub(super) const MARKETS_API: &str = "https://api-base.hanji.io/aggregators/markets";

pub(super) const USDC: Address = address!("833589fCD6eDb6E08f4c7C32D4f71b54bdA02913");
pub(super) const CBBTC: Address = address!("cbB7C0000aB88B473b1f5aFd9ef808440eed33Bf");
pub(super) const ETH_USDC: Address = address!("6a6951db3bb99f76a8ccb9f8a8399b613666298b");
pub(super) const CBBTC_USDC: Address = address!("15c8cb4e336b1e478d155d813830129fb225eee3");
pub(super) const CBBTC_ETH: Address = address!("f455b3c0756908c6a2f44a7f7390053cfe354eea");
/// The NVDAc/USDC market, one of the tokenized equities, which have no contract quoter.
pub(super) const NVDA_USDC: Address = address!("30bfa3b501c8f83114c1a789febb6281a0bcd751");

/// Who a recorded fill was sent by, which decides the quoter whose book fills it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Caller {
    /// The transaction's sender: the FastQuoter's book.
    Direct,
    /// A contract that is neither the sender nor whitelisted: the contract quoter's book.
    Contract,
    /// Tycho's router, as it calls the proxy in a swap: the FastQuoter's book where the market
    /// has whitelisted it, the contract quoter's otherwise.
    Router,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct Fixture {
    pub block: u64,
    pub timestamp: u64,
    /// The implementation in each proxy's EIP-1967 slot: every market's proxy and CLOB, and the
    /// LPManager.
    pub implementations: HashMap<Address, Address>,
    pub markets: Vec<FixtureMarket>,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureMarket {
    /// The market's entry in the API response, as sent.
    pub api: serde_json::Value,
    pub config: FixtureConfig,
    pub wiring: FixtureWiring,
    pub books: FixtureBooks,
    pub cases: Vec<FixtureCase>,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureConfig {
    pub scaling_x: U256,
    pub scaling_y: U256,
    pub token_x: Address,
    pub token_y: Address,
    pub supports_native_eth: bool,
    pub is_token_x_weth: bool,
    pub aggressive_commission_rate: U256,
    pub passive_order_payout_rate: U256,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureWiring {
    pub lob: Address,
    pub quoter: Address,
    /// Zero where the market has none.
    pub contract_quoter: Address,
    /// Whether the market had Tycho's router whitelisted.
    pub router_whitelisted: bool,
}

#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureBooks {
    pub direct: FixtureBook,
    /// `None` where the market has no contract quoter.
    pub contract: Option<FixtureBook>,
}

/// `[price, shares]` per level, best first.
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureBook {
    pub asks: Vec<[U256; 2]>,
    pub bids: Vec<[U256; 2]>,
}

/// One fill the proxy returned to `caller`: selling base (`placeOrder`) or buying it
/// (`placeMarketOrderWithTargetValue`) with `amount_in`, of which `amount_out` reached the caller.
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureCase {
    pub caller: Caller,
    pub sell_base: bool,
    pub amount_in: U256,
    /// The shares the proxy reported filled.
    pub shares: U256,
    pub amount_out: U256,
    /// The proxy call's own gas before refunds: for a direct caller, the transaction's less its
    /// intrinsic cost, which is after the refund already.
    pub gas: u64,
    /// The proxy call's gas once the refund the quoter earns by clearing its orders is paid back.
    pub net_gas: u64,
}

pub(super) fn fixture() -> Fixture {
    serde_json::from_str(RECORDING).expect("the recording parses")
}

pub(super) fn levels(side: &[[U256; 2]]) -> Vec<Level> {
    side.iter()
        .map(|[price, shares]| Level { price: *price, shares: *shares })
        .collect()
}

impl FixtureCase {
    pub(super) fn direction(&self) -> SwapDirection {
        if self.sell_base {
            SwapDirection::BaseToQuote
        } else {
            SwapDirection::QuoteToBase
        }
    }
}

impl FixtureConfig {
    fn fee_rate(&self) -> u64 {
        (self.aggressive_commission_rate + self.passive_order_payout_rate).to()
    }
}

impl FixtureMarket {
    /// The market's proxy orderbook, from its API entry.
    pub(super) fn orderbook(&self) -> Address {
        serde_json::from_value(self.api["orderbookAddress"].clone()).expect("an orderbook")
    }

    /// The deployment's entry for the market, or `None` where the deployment does not list it.
    pub(super) fn deployed(&self) -> Option<Market> {
        BASE_DEPLOYMENT
            .markets
            .iter()
            .find(|market| market.orderbook == self.orderbook())
            .copied()
    }

    /// The book the proxy fills `caller` against, or `None` where the market has no contract
    /// quoter and that caller would get its book.
    pub(super) fn book(&self, caller: Caller) -> Option<&FixtureBook> {
        let fast_quoter = match caller {
            Caller::Direct => true,
            Caller::Contract => false,
            Caller::Router => self.wiring.router_whitelisted,
        };
        if fast_quoter {
            Some(&self.books.direct)
        } else {
            self.books.contract.as_ref()
        }
    }

    /// The market as a read for `caller` reports it, or `None` where the deployment does not list
    /// it or it has no book for that caller.
    pub(super) fn read(&self, caller: Caller) -> Option<MarketRead> {
        let book = self.book(caller)?;
        Some(MarketRead {
            market: self.deployed()?,
            config: MarketConfig {
                scaling_x: self.config.scaling_x,
                scaling_y: self.config.scaling_y,
                fee_rate: self.config.fee_rate(),
            },
            asks: levels(&book.asks),
            bids: levels(&book.bids),
        })
    }
}

impl Fixture {
    pub(super) fn market(&self, orderbook: Address) -> &FixtureMarket {
        self.markets
            .iter()
            .find(|market| market.orderbook() == orderbook)
            .expect("a recorded market")
    }

    /// The read a feed for `caller` makes of the recording.
    pub(super) fn read(&self, caller: Caller) -> BookRead {
        BookRead {
            block_number: self.block,
            timestamp: self.timestamp,
            markets: self
                .markets
                .iter()
                .filter_map(|market| market.read(caller))
                .collect(),
        }
    }
}

fn bytes(address: Address) -> Bytes {
    Bytes::from(address.to_vec())
}

pub(super) fn eth() -> Token {
    Chain::Base.native_token()
}

pub(super) fn usdc() -> Token {
    Token::new(&bytes(USDC), "USDC", 6, 0, &[Some(10_000)], Chain::Base, 100)
}

pub(super) fn cbbtc() -> Token {
    Token::new(&bytes(CBBTC), "cbBTC", 8, 0, &[Some(10_000)], Chain::Base, 100)
}

/// ETH, USDC and cbBTC on Base, with no TVL floor: the tokenized equities are left out, as a
/// Tycho token universe leaves them out.
pub(super) fn book_config() -> BookFeedConfig {
    let tokens: HashMap<Bytes, Token> = [eth(), usdc(), cbbtc()]
        .into_iter()
        .map(|token| (token.address.clone(), token))
        .collect();
    BookFeedConfig { chain: Chain::Base, tokens: Arc::new(tokens), min_tvl_usd: 0.0 }
}

/// The recorded market behind `orderbook`, as a state of the book `caller` gets.
pub(super) fn state(orderbook: Address, caller: Caller) -> HanjiState {
    let fixture = fixture();
    let read = fixture
        .market(orderbook)
        .read(caller)
        .expect("a recorded book");
    let (base, quote) = match orderbook {
        ETH_USDC => (eth(), usdc()),
        CBBTC_USDC => (cbbtc(), usdc()),
        CBBTC_ETH => (cbbtc(), eth()),
        _ => panic!("no tokens for {orderbook}"),
    };
    HanjiState {
        orderbook,
        base_token: base,
        quote_token: quote,
        scaling_x: read.config.scaling_x,
        scaling_y: read.config.scaling_y,
        fee_rate: read.config.fee_rate,
        gas: read.market.gas,
        asks: read.asks,
        bids: read.bids,
    }
    .validated()
    .expect("a recorded state validates")
}

/// A JSON-RPC node serving the recording: it answers the reader's multicalls from the recorded
/// markets' configs, wiring and books, and its slot reads from the recorded implementations.
pub(super) struct FakeNode {
    pub fixture: Fixture,
    pub chain_id: u64,
    /// The block a read is answered from; the recording's unless a test moves it.
    pub block: AtomicU64,
    /// Proxies whose getConfig reverts.
    pub reverting: HashSet<Address>,
    /// Proxies whose getConfig names their tokens the other way round.
    pub misreporting: HashSet<Address>,
    /// Proxies whose CLOB getter reverts, so their wiring does not resolve.
    pub unwired: HashSet<Address>,
    /// Proxies whose getConfig puts native ETH on the other side of the market.
    pub native_flipped: HashSet<Address>,
    /// Rates every getConfig reports in place of the recorded ones.
    pub rates: Option<Rates>,
    /// Proxies that are paused.
    pub paused: HashSet<Address>,
    /// Proxies that have whitelisted Tycho's router: those recorded so, unless a test adds one.
    pub whitelisting: Mutex<HashSet<Address>>,
    /// Contract quoters a test has swapped in, by proxy.
    pub rewired: Mutex<HashMap<Address, Address>>,
    /// CLOBs a test has swapped in, by proxy.
    pub relinked: Mutex<HashMap<Address, Address>>,
    /// How long the node takes to answer a call.
    pub node_delay: Mutex<Duration>,
    /// The implementation in each proxy's EIP-1967 slot: those recorded unless a test upgrades
    /// one, so that a pin the fixture was not recorded against withholds its market.
    pub implementations: Mutex<HashMap<Address, Address>>,
    /// Whether implementation slot reads fail at the transport.
    pub storage_failing: AtomicBool,
}

impl FakeNode {
    pub(super) fn new() -> Self {
        let fixture = fixture();
        let whitelisting = fixture
            .markets
            .iter()
            .filter(|market| market.wiring.router_whitelisted)
            .map(FixtureMarket::orderbook)
            .collect();
        let implementations = Mutex::new(fixture.implementations.clone());
        FakeNode {
            block: AtomicU64::new(fixture.block),
            fixture,
            chain_id: 8453,
            reverting: HashSet::new(),
            misreporting: HashSet::new(),
            native_flipped: HashSet::new(),
            unwired: HashSet::new(),
            rates: None,
            paused: HashSet::new(),
            whitelisting: Mutex::new(whitelisting),
            rewired: Mutex::new(HashMap::new()),
            relinked: Mutex::new(HashMap::new()),
            node_delay: Mutex::new(Duration::ZERO),
            implementations,
            storage_failing: AtomicBool::new(false),
        }
    }

    /// Has every proxy put Tycho's router on its whitelist, or take it off.
    pub(super) fn whitelist_the_router_everywhere(&self, whitelisted: bool) {
        let mut whitelisting = locked(&self.whitelisting);
        for market in &self.fixture.markets {
            if whitelisted {
                whitelisting.insert(market.orderbook());
            } else {
                whitelisting.remove(&market.orderbook());
            }
        }
    }

    pub(super) async fn serve(self: Arc<Self>) -> MockHttpServer {
        spawn_http_server(move |request: &MockRequest| Some(self.answer(request))).await
    }

    fn answer(&self, request: &MockRequest) -> MockResponse {
        let request: serde_json::Value = serde_json::from_str(&request.body).unwrap();
        if let Some(batch) = request.as_array() {
            return self.answer_storage(batch);
        }
        assert_eq!(
            request["method"], "eth_call",
            "the reader sends eth_call and batched slot reads"
        );
        assert_eq!(request["params"][0]["to"], serde_json::json!(MULTICALL3_ADDRESS));
        let delay = *locked(&self.node_delay);
        MockResponse { status: "200 OK", body: self.answer_call(&request).to_string(), delay }
    }

    fn answer_call(&self, request: &serde_json::Value) -> serde_json::Value {
        assert_eq!(request["params"][1], "latest", "a read asks for the latest block");
        let input = request["params"][0]["input"]
            .as_str()
            .or_else(|| request["params"][0]["data"].as_str())
            .unwrap();
        let input = alloy::primitives::hex::decode(input).unwrap();
        let calls = aggregate3Call::abi_decode(&input)
            .unwrap()
            .calls;
        let answers: Vec<Call3Result> = calls
            .iter()
            .map(|call| {
                let answer = self.call(call.target, &call.callData);
                Call3Result {
                    success: answer.is_some(),
                    returnData: answer.unwrap_or_default().into(),
                }
            })
            .collect();
        let encoded = aggregate3Call::abi_encode_returns(&answers);
        let result = alloy::primitives::hex::encode_prefixed(encoded);
        serde_json::json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })
    }

    /// Answers a batch of implementation slot reads, each at the read's block.
    fn answer_storage(&self, batch: &[serde_json::Value]) -> MockResponse {
        if self
            .storage_failing
            .load(Ordering::SeqCst)
        {
            return MockResponse::from(("502 Bad Gateway", "overloaded".to_string()));
        }
        let answers: Vec<_> = batch
            .iter()
            .map(|request| self.storage_answer(request))
            .collect();
        MockResponse::from(("200 OK", serde_json::Value::Array(answers).to_string()))
    }

    fn storage_answer(&self, request: &serde_json::Value) -> serde_json::Value {
        assert_eq!(request["method"], "eth_getStorageAt", "a batch holds only slot reads");
        let params = &request["params"];
        let slot: U256 = serde_json::from_value(params[1].clone()).unwrap();
        assert_eq!(
            slot,
            U256::from_be_bytes(
                alloy::primitives::b256!(
                    "360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
                )
                .0
            ),
            "the reader reads only the EIP-1967 implementation slot"
        );
        assert_eq!(
            params[2],
            serde_json::json!(format!("{:#x}", self.block.load(Ordering::SeqCst))),
            "an implementation is read at the read's block"
        );
        let proxy: Address = serde_json::from_value(params[0].clone()).unwrap();
        let implementation = locked(&self.implementations)
            .get(&proxy)
            .copied()
            .unwrap_or_default();
        let result = implementation.into_word();
        serde_json::json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })
    }

    fn market(&self, orderbook: Address) -> Option<&FixtureMarket> {
        self.fixture
            .markets
            .iter()
            .find(|market| market.orderbook() == orderbook)
    }

    fn contract_quoter(&self, orderbook: Address, market: &FixtureMarket) -> Address {
        locked(&self.rewired)
            .get(&orderbook)
            .copied()
            .unwrap_or(market.wiring.contract_quoter)
    }

    /// The answer to one call, or `None` where the chain reverts.
    fn call(&self, target: Address, data: &[u8]) -> Option<Vec<u8>> {
        let selector = <[u8; 4]>::try_from(&data[..4]).unwrap();
        if target == MULTICALL3_ADDRESS {
            let value = match selector {
                getBlockNumberCall::SELECTOR => self.block.load(Ordering::SeqCst),
                getCurrentBlockTimestampCall::SELECTOR => self.fixture.timestamp,
                getChainIdCall::SELECTOR => self.chain_id,
                _ => panic!("the fake node does not answer {selector:?} on Multicall3"),
            };
            return Some(U256::from(value).abi_encode());
        }
        if self.chain_id != Chain::Base.id() {
            // On another chain the contracts have no code: a call succeeds and returns nothing.
            return Some(Vec::new());
        }
        if selector == assembleOrderbookFromOrdersCall::SELECTOR {
            return self.book(target, data);
        }
        let market = self.market(target)?;
        match selector {
            LOB_SELECTOR if self.unwired.contains(&target) => None,
            LOB_SELECTOR => Some(
                locked(&self.relinked)
                    .get(&target)
                    .copied()
                    .unwrap_or(market.wiring.lob)
                    .abi_encode(),
            ),
            QUOTER_SELECTOR => Some(market.wiring.quoter.abi_encode()),
            CONTRACT_QUOTER_SELECTOR => Some(
                self.contract_quoter(target, market)
                    .abi_encode(),
            ),
            whitelistedCall::SELECTOR => {
                let caller = whitelistedCall::abi_decode(data)
                    .unwrap()
                    .caller;
                assert_eq!(caller, BASE_ROUTER, "the books are read for the configured taker");
                let whitelisting = locked(&self.whitelisting);
                Some(
                    whitelisting
                        .contains(&target)
                        .abi_encode(),
                )
            }
            pausedCall::SELECTOR => Some(
                self.paused
                    .contains(&target)
                    .abi_encode(),
            ),
            getConfigCall::SELECTOR if self.reverting.contains(&target) => None,
            getConfigCall::SELECTOR => Some(config_answer(
                market,
                self.misreporting.contains(&target),
                self.native_flipped.contains(&target),
                self.rates,
            )),
            _ => panic!("the fake node does not answer {selector:?} on {target}"),
        }
    }

    /// A quoter's book of the CLOB `data` names: the quoter's or the contract quoter's, as
    /// recorded for the market of that CLOB. The reader asks for the depth the recording holds at
    /// most, so the whole recorded side answers it.
    fn book(&self, quoter: Address, data: &[u8]) -> Option<Vec<u8>> {
        let call = assembleOrderbookFromOrdersCall::abi_decode(data).unwrap();
        assert_eq!(call.maxPriceLevels, MAX_PRICE_LEVELS, "the reader asks for its fixed depth");
        let market = self
            .fixture
            .markets
            .iter()
            .find(|market| market.wiring.lob == call.lobAddress)?;
        let book = if quoter == market.wiring.quoter {
            &market.books.direct
        } else if quoter == market.wiring.contract_quoter {
            market.books.contract.as_ref()?
        } else {
            return None;
        };
        let side = if call.isAsk { &book.asks } else { &book.bids };
        let answer = assembleOrderbookFromOrdersReturn {
            arrayPrices: side
                .iter()
                .map(|[price, _]| price.to::<U72>())
                .collect(),
            arrayShares: side
                .iter()
                .map(|[_, shares]| shares.to::<u128>())
                .collect(),
        };
        Some(assembleOrderbookFromOrdersCall::abi_encode_returns(&answer))
    }
}

/// The commission rates a proxy's `getConfig()` reports, each per 1e18 of the executed value.
#[derive(Debug, Clone, Copy)]
pub(super) struct Rates {
    pub aggressive: u64,
    pub passive: u64,
    pub passive_payout: u64,
}

impl Rates {
    /// Distinct and non-zero, so that reading the wrong one shows.
    pub(super) const DISTINCT: Rates = Rates {
        aggressive: 100_000_000_000_007,
        passive: 70_000_000_000_000,
        passive_payout: 3_000,
    };

    /// The taker's rate the state charges.
    pub(super) fn taker(self) -> u64 {
        self.aggressive + self.passive_payout
    }
}

/// What a proxy answers `getConfig()` with: as recorded, with its tokens swapped, with native ETH
/// on the other side, or with other rates.
fn config_answer(
    market: &FixtureMarket,
    swapped: bool,
    native_flipped: bool,
    rates: Option<Rates>,
) -> Vec<u8> {
    let config = &market.config;
    let (token_x, token_y) =
        if swapped { (config.token_y, config.token_x) } else { (config.token_x, config.token_y) };
    let rates = rates.unwrap_or_else(|| Rates {
        aggressive: config.aggressive_commission_rate.to(),
        passive: 0,
        passive_payout: config.passive_order_payout_rate.to(),
    });
    getConfigCall::abi_encode_returns(&getConfigReturn {
        scalingFactorTokenX: config.scaling_x,
        scalingFactorTokenY: config.scaling_y,
        tokenX: token_x,
        tokenY: token_y,
        supportsNativeEth: config.supports_native_eth,
        isTokenXWeth: config.is_token_x_weth != native_flipped,
        askTrie: Address::ZERO,
        bidTrie: Address::ZERO,
        adminCommissionRate: 0,
        totalAggressiveCommissionRate: rates.aggressive,
        totalPassiveCommissionRate: rates.passive,
        passiveOrderPayoutRate: rates.passive_payout,
        shouldInvokeOnTrade: false,
    })
}

/// The guard of a lock a panicking test thread may have poisoned: the node's state stays usable.
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
    mutex
        .lock()
        .unwrap_or_else(PoisonError::into_inner)
}

/// A source reading `server` as the node, for Tycho's router, its clock at `now_ms` (Unix
/// milliseconds).
pub(super) fn source(server: &MockHttpServer, now_ms: u64) -> HanjiBookSource {
    HanjiBookSource {
        reader: HanjiReader::new(Url::parse(&server.url()).unwrap(), BASE_DEPLOYMENT, BASE_ROUTER),
        assembler: HanjiBookAssembler::new(book_config()),
        clock: Arc::new(move || now_ms),
        last_block: Arc::new(AtomicU64::new(0)),
    }
}