tycho-simulation 0.551.1

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
//! Reads every Hanji market the deployment lists over JSON-RPC, all at one block, in one
//! multicall.
//!
//! A proxy orderbook trades against virtual orders that one of two quoters places for the caller:
//! its FastQuoter for the transaction's sender and for callers on its whitelist, and a second
//! quoter, a few bps wider, for any other contract, such as a router (see the module docs). Each
//! quoter reports the book it would place with `assembleOrderbookFromOrders(lob, isAsk, depth)`,
//! where `lob` is the market's underlying CLOB.
//!
//! Hanji's documentation points aggregators to `FastQuoterHelper.assembleOrderbookFromOrders`,
//! which forwards to FastQuoter only, so it reports the book of the transaction's sender and
//! whitelisted callers and never the wider one other contracts are filled against. The reader
//! asks both quoters directly instead.
//!
//! A read is one `eth_call` of `Multicall3.aggregate3` at the latest block: the block's number,
//! timestamp and chain id, then for each market its proxy's `getConfig()`, whether it is paused,
//! its wiring (CLOB and quoters), whether the taker is whitelisted, and both pinned quoters' books
//! of the pinned CLOB. The deployment names each market's CLOB and the quoters, so the books are
//! asked for in the same multicall as the getters that check them.
//!
//! After the multicall, the reader checks each market against what the deployment pins (see the
//! module docs). A market that names another CLOB than its [`Market::clob`] or other quoters than
//! [`Deployment::quoters`] is left out without reading anything more. For the rest, it reads the
//! EIP-1967 implementation slot of each one's proxy and CLOB and of each [`Deployment::shared`]
//! contract, in one JSON-RPC batch of `eth_getStorageAt` at the read's block, since no call can
//! read another contract's storage. A market whose proxy or CLOB runs another implementation than
//! the one pinned is left out of the read, and so is every market while a shared contract does;
//! each market left out is logged once when that starts and once when a read serves it again.

use std::{
    collections::{HashMap, HashSet},
    sync::{Arc, Mutex, PoisonError},
};

use alloy::{
    eips::BlockId,
    primitives::{aliases::U24, b256, Address, Bytes as AlloyBytes, B256, U256},
    providers::{
        bindings::IMulticall3::{
            aggregate3Call, getBlockNumberCall, getChainIdCall, getCurrentBlockTimestampCall,
            Call3, Result as Call3Result,
        },
        Provider, RootProvider, MULTICALL3_ADDRESS,
    },
    rpc::{
        client::BatchRequest,
        types::{TransactionInput, TransactionRequest},
    },
    sol,
    sol_types::{SolCall, SolValue},
};
use reqwest::Url;
use tracing::{debug, error, info, warn};

use crate::{
    pamm::protocols::hanji::{
        market::{Market, NativeSide},
        state::Level,
        Deployment,
    },
    snapshot_feed::errors::FeedError,
};

// The proxy orderbook's config, as Hanji documents it at
// <https://docs.hanji.io/for-developers/liquidity-source-integration>, its whitelist, and the
// quoters' book view, which FastQuoterHelper forwards to with the same arguments.
sol! {
    #[derive(Debug)]
    function getConfig() external view returns (
        uint256 scalingFactorTokenX,
        uint256 scalingFactorTokenY,
        address tokenX,
        address tokenY,
        bool supportsNativeEth,
        bool isTokenXWeth,
        address askTrie,
        address bidTrie,
        uint64 adminCommissionRate,
        uint64 totalAggressiveCommissionRate,
        uint64 totalPassiveCommissionRate,
        uint64 passiveOrderPayoutRate,
        bool shouldInvokeOnTrade
    );

    #[derive(Debug)]
    function whitelisted(address caller) external view returns (bool);

    #[derive(Debug)]
    function paused() external view returns (bool);

    #[derive(Debug)]
    function assembleOrderbookFromOrders(address lobAddress, bool isAsk, uint24 maxPriceLevels)
        external view returns (uint72[] memory arrayPrices, uint128[] memory arrayShares);

}

/// Unnamed getters of the proxy orderbooks' unverified implementations, each identified by what
/// it returns on the Base markets: the underlying CLOB, the FastQuoter that FastQuoterHelper
/// forwards to, and the quoter the proxy calls for a contract that is neither the transaction's
/// sender nor whitelisted (zero on the tokenized-equity markets, which name none).
pub(super) const LOB_SELECTOR: [u8; 4] = [0xf7, 0xd7, 0x45, 0x24];
pub(super) const QUOTER_SELECTOR: [u8; 4] = [0x93, 0x8c, 0x51, 0x32];
pub(super) const CONTRACT_QUOTER_SELECTOR: [u8; 4] = [0xf8, 0xbe, 0xd2, 0x5f];

/// How many price levels a read asks for per side. FastQuoter's books held five per side in the
/// recording; a side holding more is read up to this many, so its depth past them is not
/// offered.
pub(super) const MAX_PRICE_LEVELS: U24 = U24::from_limbs([32]);

/// Calls before the markets' in the read: block number, timestamp and chain id.
const HEAD_CALLS: usize = 3;

/// Calls per market in the read: config, pause, the three wiring getters, the taker's whitelist
/// entry, then asks and bids from the quoter and from the contract quoter.
const MARKET_CALLS: usize = 10;

/// EIP-1967's implementation slot, `keccak256("eip1967.proxy.implementation") - 1`.
const IMPLEMENTATION_SLOT: B256 =
    b256!("360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc");

/// Where a market's virtual orders come from, as its proxy's getters name them: the CLOB and
/// both quoters, the contract quoter zero where the proxy names none.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct Wiring {
    pub lob: Address,
    pub quoter: Address,
    pub contract_quoter: Address,
}

/// A market's config as the reader uses it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) struct MarketConfig {
    pub scaling_x: U256,
    pub scaling_y: U256,
    /// `totalAggressiveCommissionRate + passiveOrderPayoutRate`, per 1e18 of the executed value.
    pub fee_rate: u64,
}

/// One market as the chain reported it, checked against the deployment, with the book its proxy
/// quotes the taker.
#[derive(Debug, Clone)]
pub(super) struct MarketRead {
    pub market: Market,
    pub config: MarketConfig,
    /// Best first, as the quoters sort them.
    pub asks: Vec<Level>,
    pub bids: Vec<Level>,
}

/// A market whose calls could not be decoded, and why.
type MarketFailure = (&'static Market, String);

/// Everything one read returned, at one block.
#[derive(Debug, Clone)]
pub(super) struct BookRead {
    pub block_number: u64,
    pub timestamp: u64,
    /// The markets that read cleanly, in the order they were asked for.
    pub markets: Vec<MarketRead>,
}

#[derive(Clone, derive_more::Debug)]
pub(super) struct HanjiReader {
    #[debug(skip)]
    provider: RootProvider,
    /// Removed from transport errors before they are reported: see [`Self::connection_error`].
    #[debug(skip)]
    rpc_url: String,
    deployment: Deployment,
    /// The caller whose book is read: Tycho's router unless the feed was built for another.
    taker: Address,
    /// The proxies whose market the last read left out for what it runs, so that the change is
    /// logged once each way.
    #[debug(skip)]
    withheld: Arc<Mutex<HashSet<Address>>>,
    /// The proxies whose market's calls the last read could not decode, likewise.
    #[debug(skip)]
    failing: Arc<Mutex<HashSet<Address>>>,
}

impl HanjiReader {
    pub(super) fn new(rpc_url: Url, deployment: Deployment, taker: Address) -> Self {
        Self {
            rpc_url: rpc_url.to_string(),
            provider: RootProvider::new_http(rpc_url),
            deployment,
            taker,
            withheld: Arc::new(Mutex::new(HashSet::new())),
            failing: Arc::new(Mutex::new(HashSet::new())),
        }
    }

    /// Reads every market of the deployment at the latest block. A market whose calls revert or
    /// whose config names other tokens or another native side than the deployment is left out,
    /// logged with its reason when that starts and again when it reads; the read fails when every
    /// market was left out that way, and fails fatally when the node serves another chain. A paused
    /// market, and one that runs or names anything the deployment does not pin, is left out without
    /// failing anything; a node that cannot report the implementations fails the read.
    pub(super) async fn read(&self) -> Result<BookRead, FeedError> {
        let markets = self.deployment.markets;
        let mut calls = vec![
            call(MULTICALL3_ADDRESS, getBlockNumberCall {}.abi_encode()),
            call(MULTICALL3_ADDRESS, getCurrentBlockTimestampCall {}.abi_encode()),
            call(MULTICALL3_ADDRESS, getChainIdCall {}.abi_encode()),
        ];
        for market in markets {
            calls.extend(self.market_calls(market));
        }
        let answers = self.aggregate(calls).await?;
        let (head, market_answers) = answers.split_at(HEAD_CALLS);
        let mut read = self.decode_head(head)?;
        let (decoded, first_failure) = self.decode_markets(market_answers);
        if decoded.is_empty() {
            if let Some((market, reason)) = first_failure {
                return Err(FeedError::Parsing(format!(
                    "Hanji: none of the {} markets read cleanly; {} ({}) failed with: {reason}",
                    markets.len(),
                    market.name,
                    market.orderbook
                )));
            }
        }
        read.markets = self
            .withhold_unpinned(read.block_number, decoded)
            .await?;
        Ok(read)
    }

    /// Each market's answers decoded, in the deployment's order, with the first market that
    /// failed and why. A market is logged when it starts failing, with its reason, and when it
    /// decodes again.
    fn decode_markets(
        &self,
        market_answers: &[Call3Result],
    ) -> (Vec<(MarketRead, Wiring)>, Option<MarketFailure>) {
        let mut decoded = Vec::new();
        let mut first_failure = None;
        let mut failing = self
            .failing
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        // `aggregate` checked the answer count, so the chunks are whole and one per market.
        let (market_answers, _) = market_answers.as_chunks::<MARKET_CALLS>();
        for (market, answers) in self
            .deployment
            .markets
            .iter()
            .zip(market_answers)
        {
            match Self::decode_market(*market, answers) {
                Ok(decoded_market) => {
                    if failing.remove(&market.orderbook) {
                        info!(market = market.name, orderbook = %market.orderbook, "Hanji market reads again");
                    }
                    decoded.extend(decoded_market);
                }
                Err(reason) => {
                    if failing.insert(market.orderbook) {
                        warn!(market = market.name, orderbook = %market.orderbook, %reason, "skipping Hanji market whose calls do not read");
                    }
                    first_failure.get_or_insert((market, reason));
                }
            }
        }
        (decoded, first_failure)
    }

    /// The markets of `decoded` (each with the wiring its proxy named) that run and name what the
    /// deployment pins. A market whose wiring differs from the pins is left out before anything
    /// is read; the implementations of the others' proxies and CLOBs, and of the shared
    /// contracts, are read in one batch at `block`.
    async fn withhold_unpinned(
        &self,
        block: u64,
        decoded: Vec<(MarketRead, Wiring)>,
    ) -> Result<Vec<MarketRead>, FeedError> {
        let shared = self.deployment.shared;
        let mut refusals: HashMap<Address, String> = HashMap::new();
        let mut contracts: Vec<Address> = shared
            .iter()
            .map(|(contract, _)| *contract)
            .collect();
        for (market_read, wiring) in &decoded {
            let market = &market_read.market;
            match self.wiring_refusal(market, wiring) {
                Some(reason) => {
                    refusals.insert(market.orderbook, reason);
                }
                None => contracts.extend([market.orderbook, market.clob]),
            }
        }
        let found = if contracts.len() > shared.len() {
            self.implementations(&contracts, block)
                .await?
        } else {
            HashMap::new()
        };
        let shared_refusal = shared
            .iter()
            .find_map(|(contract, pinned)| implementation_refusal(*contract, *pinned, &found));
        let mut withheld = self
            .withheld
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        let mut pinned = Vec::new();
        for (market_read, _) in decoded {
            let market = market_read.market;
            let orderbook = market.orderbook;
            let refusal = refusals
                .remove(&orderbook)
                .or_else(|| shared_refusal.clone())
                .or_else(|| {
                    [
                        (orderbook, market.orderbook_implementation),
                        (market.clob, market.clob_implementation),
                    ]
                    .into_iter()
                    .find_map(|(contract, pinned)| implementation_refusal(contract, pinned, &found))
                });
            match refusal {
                Some(reason) => {
                    if withheld.insert(orderbook) {
                        error!(market = market.name, %orderbook, block, %reason, "withholding \
                            Hanji market: it does not run what its fills were recorded against");
                    }
                }
                None => {
                    if withheld.remove(&orderbook) {
                        info!(market = market.name, %orderbook, block, "Hanji market runs what \
                            its fills were recorded against again");
                    }
                    pinned.push(market_read);
                }
            }
        }
        Ok(pinned)
    }

    /// Why a market whose proxy names `wiring` is not served whatever its contracts run: it names
    /// another CLOB than the deployment's or other quoters than the pinned ones.
    fn wiring_refusal(&self, market: &Market, wiring: &Wiring) -> Option<String> {
        let quoters = self.deployment.quoters;
        let pinned =
            Wiring { lob: market.clob, quoter: quoters.fast, contract_quoter: quoters.contract };
        (*wiring != pinned).then(|| format!("names {wiring:?}, not the pinned {pinned:?}"))
    }

    /// The implementation in each of `contracts`' EIP-1967 slot at `block`, read in one batch.
    async fn implementations(
        &self,
        contracts: &[Address],
        block: u64,
    ) -> Result<HashMap<Address, Address>, FeedError> {
        let block = BlockId::number(block);
        let slot = U256::from_be_bytes(IMPLEMENTATION_SLOT.0);
        let mut batch = BatchRequest::new(self.provider.client());
        let mut reads = Vec::with_capacity(contracts.len());
        for contract in contracts {
            let read = batch
                .add_call::<_, U256>("eth_getStorageAt", &(contract, slot, block))
                .map_err(|e| self.connection_error("implementation slot", e))?;
            reads.push((*contract, read));
        }
        batch
            .send()
            .await
            .map_err(|e| self.connection_error("implementation slots", e))?;
        let mut found = HashMap::with_capacity(reads.len());
        for (contract, read) in reads {
            let word = read
                .await
                .map_err(|e| self.connection_error("implementation slot", e))?;
            found.insert(contract, Address::from_word(B256::from(word)));
        }
        Ok(found)
    }

    /// The market's calls in the order [`Self::decode_market`] reads them. Each may revert, so
    /// that one market's revert leaves the others' answers standing.
    fn market_calls(&self, market: &Market) -> [Call3; MARKET_CALLS] {
        let orderbook = market.orderbook;
        let quoters = self.deployment.quoters;
        [
            call(orderbook, getConfigCall {}.abi_encode()),
            call(orderbook, pausedCall {}.abi_encode()),
            call(orderbook, LOB_SELECTOR.to_vec()),
            call(orderbook, QUOTER_SELECTOR.to_vec()),
            call(orderbook, CONTRACT_QUOTER_SELECTOR.to_vec()),
            call(orderbook, whitelistedCall { caller: self.taker }.abi_encode()),
            call(quoters.fast, book_call(market.clob, true)),
            call(quoters.fast, book_call(market.clob, false)),
            call(quoters.contract, book_call(market.clob, true)),
            call(quoters.contract, book_call(market.clob, false)),
        ]
    }

    /// The read's block, with no markets yet. The chain id is checked before anything else is
    /// decoded: on another chain the markets answer from addresses with no code.
    fn decode_head(&self, head: &[Call3Result]) -> Result<BookRead, FeedError> {
        let [block_number, timestamp, chain_id] = head else {
            return Err(FeedError::Parsing("Hanji multicall answered too few calls".into()));
        };
        self.check_chain(chain_id)?;
        let block_number = decode::<getBlockNumberCall>(block_number, "block number")?;
        let timestamp = decode::<getCurrentBlockTimestampCall>(timestamp, "timestamp")?;
        Ok(BookRead {
            block_number: to_u64(block_number, "block number")?,
            timestamp: to_u64(timestamp, "timestamp")?,
            markets: Vec::new(),
        })
    }

    /// Fails fatally when the node serves another chain than the deployment's.
    fn check_chain(&self, answer: &Call3Result) -> Result<(), FeedError> {
        let served = to_u64(decode::<getChainIdCall>(answer, "chain id")?, "chain id")?;
        let chain = self.deployment.chain;
        if served != chain.id() {
            return Err(FeedError::Fatal(format!(
                "Hanji: the RPC node serves chain {served}, not the deployment's chain {}",
                chain.id()
            )));
        }
        Ok(())
    }

    /// One market's answers, with the wiring its proxy named: `Ok(None)`, logged, when the proxy
    /// is paused, `Err` when it cannot be served from them.
    fn decode_market(
        market: Market,
        answers: &[Call3Result; MARKET_CALLS],
    ) -> Result<Option<(MarketRead, Wiring)>, String> {
        let [config, paused, lob, quoter, contract, whitelisted, quoter_asks, quoter_bids, contract_asks, contract_bids] =
            answers;
        let wiring = decode_wiring(lob, quoter, contract)?;
        let config = decode_config(market, config)?;
        if decode_answer::<pausedCall>(paused, "paused")? {
            debug!(market = market.name, orderbook = %market.orderbook, "skipping paused Hanji market");
            return Ok(None);
        }
        let whitelisted = decode_answer::<whitelistedCall>(whitelisted, "whitelisted")?;
        let (asks, bids) =
            if whitelisted { (quoter_asks, quoter_bids) } else { (contract_asks, contract_bids) };
        let market_read = MarketRead {
            market,
            config,
            asks: decode_levels(asks, "asks")?,
            bids: decode_levels(bids, "bids")?,
        };
        Ok(Some((market_read, wiring)))
    }

    async fn aggregate(&self, calls: Vec<Call3>) -> Result<Vec<Call3Result>, FeedError> {
        let expected = calls.len();
        let request = TransactionRequest::default()
            .to(MULTICALL3_ADDRESS)
            .input(TransactionInput::new(
                aggregate3Call { calls }
                    .abi_encode()
                    .into(),
            ));
        let raw = self
            .provider
            .call(request)
            .block(BlockId::latest())
            .await
            .map_err(|e| self.connection_error("multicall", e))?;
        let answers = aggregate3Call::abi_decode_returns(&raw)
            .map_err(|e| FeedError::Parsing(format!("Hanji multicall: {e}")))?;
        if answers.len() != expected {
            return Err(FeedError::Parsing(format!(
                "Hanji multicall answered {} of {expected} calls",
                answers.len()
            )));
        }
        Ok(answers)
    }

    /// A transport failure, with the RPC URL removed: it commonly carries a key, and the HTTP
    /// client's errors quote the URL they failed on.
    fn connection_error(&self, what: &str, error: impl std::fmt::Display) -> FeedError {
        let error = error
            .to_string()
            .replace(&self.rpc_url, "<rpc url>");
        FeedError::Connection(format!("Hanji {what}: {error}"))
    }
}

/// Why `contract` is not served given the implementations `found`: `None` when it runs
/// `pinned`.
fn implementation_refusal(
    contract: Address,
    pinned: Address,
    found: &HashMap<Address, Address>,
) -> Option<String> {
    match found.get(&contract) {
        None => Some(format!("{contract}'s implementation was not read")),
        Some(found) if *found != pinned => {
            Some(format!("{contract} runs implementation {found}, not the pinned {pinned}"))
        }
        Some(_) => None,
    }
}

/// The market's config, checked against the deployment: the same tokens with the native token on
/// the same side.
fn decode_config(market: Market, answer: &Call3Result) -> Result<MarketConfig, String> {
    let config = decode_answer::<getConfigCall>(answer, "getConfig")?;
    if (config.tokenX, config.tokenY) != (market.token_x, market.token_y) {
        return Err(format!(
            "getConfig trades {} against {}, the deployment {} against {}",
            config.tokenX, config.tokenY, market.token_x, market.token_y
        ));
    }
    let native = match (config.supportsNativeEth, config.isTokenXWeth) {
        (false, _) => NativeSide::None,
        (true, true) => NativeSide::X,
        (true, false) => NativeSide::Y,
    };
    if native != market.native {
        return Err(format!(
            "getConfig makes {native:?} the native side, the deployment {:?}",
            market.native
        ));
    }
    let fee_rate = config
        .totalAggressiveCommissionRate
        .checked_add(config.passiveOrderPayoutRate)
        .ok_or("its commission rates overflow")?;
    Ok(MarketConfig {
        scaling_x: config.scalingFactorTokenX,
        scaling_y: config.scalingFactorTokenY,
        fee_rate,
    })
}

/// The wiring the getters answered.
fn decode_wiring(
    lob: &Call3Result,
    quoter: &Call3Result,
    contract_quoter: &Call3Result,
) -> Result<Wiring, String> {
    let address = |answer: &Call3Result, what: &str| -> Result<Address, String> {
        if !answer.success {
            return Err(format!("its {what} getter reverted"));
        }
        Address::abi_decode(&answer.returnData)
            .map_err(|e| format!("its {what} did not decode: {e}"))
    };
    Ok(Wiring {
        lob: address(lob, "CLOB")?,
        quoter: address(quoter, "quoter")?,
        contract_quoter: address(contract_quoter, "contract quoter")?,
    })
}

fn book_call(lob: Address, is_ask: bool) -> Vec<u8> {
    assembleOrderbookFromOrdersCall {
        lobAddress: lob,
        isAsk: is_ask,
        maxPriceLevels: MAX_PRICE_LEVELS,
    }
    .abi_encode()
}

/// Every call may fail, so that a reverting market is told apart from a node that failed.
fn call(target: Address, data: Vec<u8>) -> Call3 {
    Call3 { target, allowFailure: true, callData: AlloyBytes::from(data) }
}

fn decode_levels(answer: &Call3Result, side: &str) -> Result<Vec<Level>, String> {
    let levels = decode_answer::<assembleOrderbookFromOrdersCall>(answer, side)?;
    if levels.arrayPrices.len() != levels.arrayShares.len() {
        return Err(format!(
            "its {side} hold {} prices for {} share counts",
            levels.arrayPrices.len(),
            levels.arrayShares.len()
        ));
    }
    Ok(levels
        .arrayPrices
        .iter()
        .zip(&levels.arrayShares)
        .map(|(price, shares)| Level { price: U256::from(*price), shares: U256::from(*shares) })
        .collect())
}

fn decode_answer<C: SolCall>(answer: &Call3Result, what: &str) -> Result<C::Return, String> {
    if !answer.success {
        return Err(format!("{what} reverted"));
    }
    C::abi_decode_returns(&answer.returnData).map_err(|e| format!("{what} did not decode: {e}"))
}

/// A head call's answer; Multicall3's own views do not revert.
fn decode<C: SolCall>(answer: &Call3Result, what: &str) -> Result<C::Return, FeedError> {
    decode_answer::<C>(answer, what).map_err(|e| FeedError::Parsing(format!("Hanji {e}")))
}

fn to_u64(value: U256, what: &str) -> Result<u64, FeedError> {
    // ruint's error says only that the value does not fit, which the message states.
    value
        .try_into()
        .map_err(|_too_large| FeedError::Parsing(format!("Hanji {what} {value} exceeds 64 bits")))
}

#[cfg(test)]
mod tests {
    use alloy::primitives::{aliases::U72, hex, keccak256};
    use rstest::rstest;

    use super::*;

    fn answer(success: bool, data: Vec<u8>) -> Call3Result {
        Call3Result { success, returnData: data.into() }
    }

    fn address_answer(byte: u8) -> Call3Result {
        answer(true, Address::repeat_byte(byte).abi_encode())
    }

    #[test]
    fn test_decode_wiring() {
        let wiring = decode_wiring(&address_answer(1), &address_answer(2), &address_answer(3));

        assert_eq!(
            wiring,
            Ok(Wiring {
                lob: Address::repeat_byte(1),
                quoter: Address::repeat_byte(2),
                contract_quoter: Address::repeat_byte(3),
            })
        );
    }

    #[rstest]
    #[case::clob_reverts(answer(false, Vec::new()), address_answer(2), "CLOB getter reverted")]
    #[case::quoter_reverts(address_answer(1), answer(false, Vec::new()), "quoter getter reverted")]
    #[case::no_code(address_answer(1), answer(true, Vec::new()), "quoter did not decode")]
    fn test_decode_wiring_undecodable(
        #[case] lob: Call3Result,
        #[case] quoter: Call3Result,
        #[case] reason: &str,
    ) {
        let wiring = decode_wiring(&lob, &quoter, &address_answer(3));

        let error = wiring.unwrap_err();
        assert!(error.contains(reason), "{error}");
    }

    #[test]
    fn test_implementation_refusal() {
        let contract = Address::repeat_byte(9);
        let (pinned, other) = (Address::repeat_byte(1), Address::repeat_byte(2));
        let found = |implementation| HashMap::from([(contract, implementation)]);

        let changed = implementation_refusal(contract, pinned, &found(other)).unwrap();
        let unread = implementation_refusal(contract, pinned, &HashMap::new()).unwrap();

        assert_eq!(implementation_refusal(contract, pinned, &found(pinned)), None);
        assert!(changed.contains("not the pinned"), "{changed}");
        assert!(unread.contains("was not read"), "{unread}");
    }

    #[test]
    fn test_implementation_slot_is_eip_1967() {
        let slot = U256::from_be_bytes(keccak256("eip1967.proxy.implementation").0) - U256::from(1);

        assert_eq!(B256::from(slot), IMPLEMENTATION_SLOT);
    }

    #[test]
    fn test_decode_levels_length_mismatch() {
        let side = assembleOrderbookFromOrdersCall::abi_encode_returns(
            &assembleOrderbookFromOrdersReturn {
                arrayPrices: vec![U72::from(2), U72::from(1)],
                arrayShares: vec![5],
            },
        );

        let error = decode_levels(&answer(true, side), "bids").unwrap_err();

        assert!(error.contains("2 prices for 1 share counts"), "{error}");
    }

    /// `testdata/record_fixture.py` records what the feed reads: the same depth, getters, router
    /// and LPManager, from the market list the live test compares with the deployment.
    #[test]
    fn test_recorder_constants_match() {
        let script = include_str!("testdata/record_fixture.py");
        let expected = [
            format!("DEPTH = {}", MAX_PRICE_LEVELS),
            format!("LOB_SELECTOR = \"{}\"", hex::encode(LOB_SELECTOR)),
            format!("QUOTER_SELECTOR = \"{}\"", hex::encode(QUOTER_SELECTOR)),
            format!("CONTRACT_QUOTER_SELECTOR = \"{}\"", hex::encode(CONTRACT_QUOTER_SELECTOR)),
            format!("TYCHO_ROUTER = \"{:#x}\"", crate::pamm::protocols::hanji::BASE_ROUTER),
            format!("API = \"{}\"", crate::pamm::protocols::hanji::test_support::MARKETS_API),
            format!("IMPLEMENTATION_SLOT = \"{IMPLEMENTATION_SLOT}\""),
            format!(
                "LP_MANAGER = \"{:#x}\"",
                crate::pamm::protocols::hanji::BASE_DEPLOYMENT.shared[0].0
            ),
        ];
        for line in expected {
            assert!(script.contains(&line), "record_fixture.py lacks `{line}`");
        }
    }
}