tycho-simulation 0.551.2

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
//! Hanji's book feed: polls every market of the deployment over JSON-RPC and publishes every poll
//! as a complete [`BookSnapshot`].

use std::{
    collections::HashSet,
    future::Future,
    sync::{
        atomic::{AtomicU64, Ordering},
        Arc, Mutex, PoisonError,
    },
    time::{Duration, SystemTime, UNIX_EPOCH},
};

use alloy::primitives::Address;
use chrono::DateTime;
use reqwest::Url;
use tracing::{debug, info, warn};
use tycho_common::{simulation::errors::SimulationError, Bytes};

use crate::{
    book::{
        component::{maker_component_id, pair_book},
        levels::{InvalidLevel, Levels, PriceLevel},
        quote_tokens::usd_stablecoins_for_chain,
        sim,
        tvl::tvl_in_usd,
        BookFeedConfig, BookSnapshot, Books, ReceivedAt,
    },
    evm::protocol::u256_num::u256_to_biguint,
    pamm::protocols::hanji::{
        reader::{BookRead, HanjiReader, MarketRead},
        state::{HanjiState, Level},
        BASE_DEPLOYMENT, BASE_ROUTER, ORDERBOOK_ATTRIBUTE, PROTOCOL_SYSTEM, PROTOCOL_TYPE,
    },
    snapshot_feed::{
        errors::FeedError,
        http::{default_http_feed_config, run_http_poll_feed, HttpFeedConfig, HttpSource},
        Publisher, SnapshotFeed,
    },
};

/// How many milliseconds a read's block timestamp may trail the wall clock read just before the
/// read is sent. Base block timestamps are whole seconds, shared by about five 200 ms blocks, so
/// a synced node's latest block already trails the clock by up to a second; past that, the node
/// is lagging. The quoters' books empty about 3 s after their keepers last pushed a price, and
/// they push several times a second. With [`MAX_SNAPSHOT_AGE`], a book is withdrawn at most
/// 3.5 s after its block's timestamp plus the poll's two round trips (the read, then the batch of
/// implementations), each up to the request timeout: half a second plus those round trips past
/// the point where a book whose keepers stopped at that block would have emptied.
const MAX_READ_LAG_MS: u64 = 1_500;

/// How long a book is served after the poll that read it, unless a later poll replaces it.
const MAX_SNAPSHOT_AGE: Duration = Duration::from_secs(2);

/// Hanji's book feed. Built through [`HanjiFeedBuilder`]. Neither its `Debug` output nor its
/// errors carry the RPC URL, which commonly carries a key.
#[derive(Debug, Clone)]
pub struct HanjiFeed {
    feed_config: HttpFeedConfig,
    source: HanjiBookSource,
}

/// Builds a [`HanjiFeed`] from the shared [`BookFeedConfig`] and a Base JSON-RPC URL. A poll sends
/// one `eth_call` at the latest block and one batch of `eth_getStorageAt` at the read's block for
/// the implementations it pins, so a full node that serves recent state is enough.
pub struct HanjiFeedBuilder {
    book_config: BookFeedConfig,
    rpc_url: String,
    taker: Bytes,
    feed_config: HttpFeedConfig,
}

impl HanjiFeedBuilder {
    pub fn new(book_config: BookFeedConfig, rpc_url: String) -> Self {
        Self {
            book_config,
            rpc_url,
            taker: Bytes::from(BASE_ROUTER.to_vec()),
            feed_config: Self::default_feed_config(),
        }
    }

    /// The address that calls the proxy orderbooks, replacing Tycho's router on Base. A proxy
    /// fills a contract against a wider book than the one it fills a whitelisted caller against,
    /// and the books are read for this one, so set it when swaps go through another router.
    pub fn taker(mut self, taker: Bytes) -> Self {
        self.taker = taker;
        self
    }

    /// Tune the poll loop (poll cadence, request timeout, failure limit, snapshot age). This
    /// replaces [`Self::default_feed_config`] whole, including its `max_snapshot_age`, which keeps
    /// a book from being served after the quoters stop quoting it; start from that default.
    pub fn feed_config(mut self, feed_config: HttpFeedConfig) -> Self {
        self.feed_config = feed_config;
        self
    }

    /// The feed tuning a new builder starts from, set by the quoters' freshness: a poll every
    /// second, given 2 s, and a book withdrawn 2 s after the poll that read it, so that with the
    /// read lag allowed it is gone about when the quoters stop quoting without a newer price.
    pub fn default_feed_config() -> HttpFeedConfig {
        HttpFeedConfig {
            poll_interval: Duration::from_secs(1),
            request_timeout: Duration::from_secs(2),
            max_snapshot_age: Some(MAX_SNAPSHOT_AGE),
            ..default_http_feed_config()
        }
    }

    /// The feed. Fails for a chain other than Base, the only Tycho chain Hanji is deployed on, for
    /// an RPC URL that is not one, and for a taker that is not an address. The node's chain is
    /// checked on every poll, which fails fatally when the node serves another one.
    pub fn build(self) -> Result<HanjiFeed, FeedError> {
        let deployment = BASE_DEPLOYMENT;
        if self.book_config.chain != deployment.chain {
            return Err(FeedError::InvalidInput(format!(
                "Hanji is integrated on Base only, not {}",
                self.book_config.chain
            )));
        }
        let rpc_url = Url::parse(&self.rpc_url)
            .map_err(|e| FeedError::InvalidInput(format!("Hanji RPC URL: {e}")))?;
        // The slice error says only that the length is not 20 bytes, which the message states.
        let taker = Address::try_from(self.taker.as_ref()).map_err(|_wrong_length| {
            FeedError::InvalidInput(format!("Hanji taker {} is not a 20-byte address", self.taker))
        })?;
        Ok(HanjiFeed {
            source: HanjiBookSource {
                reader: HanjiReader::new(rpc_url, deployment, taker),
                assembler: HanjiBookAssembler::new(self.book_config),
                clock: Arc::new(unix_now_ms),
                last_block: Arc::new(AtomicU64::new(0)),
            },
            feed_config: self.feed_config,
        })
    }
}

impl SnapshotFeed for HanjiFeed {
    type Snapshot = BookSnapshot<ReceivedAt>;
    type Error = FeedError;

    fn run(
        self,
        publisher: Publisher<Self::Snapshot>,
    ) -> impl Future<Output = Result<(), FeedError>> + Send + 'static {
        run_http_poll_feed(self.feed_config, publisher, self.source)
    }
}

/// One poll: every market of the deployment read from the chain and turned into books.
#[derive(Clone, derive_more::Debug)]
pub(super) struct HanjiBookSource {
    pub(super) reader: HanjiReader,
    pub(super) assembler: HanjiBookAssembler,
    /// The current Unix time in milliseconds.
    #[debug(skip)]
    pub(super) clock: Arc<dyn Fn() -> u64 + Send + Sync>,
    /// The newest block a poll has read, so that a node answering from an older one is caught.
    pub(super) last_block: Arc<AtomicU64>,
}

impl HttpSource for HanjiBookSource {
    type Snapshot = BookSnapshot<ReceivedAt>;

    /// A read that fails fails the poll, and so does one from a block older than a previous
    /// poll's or more than [`MAX_READ_LAG_MS`] behind the wall clock: a load-balanced or
    /// lagging node would otherwise roll the books back or publish books the quoters no longer
    /// quote.
    async fn fetch(&self) -> Result<BookSnapshot<ReceivedAt>, FeedError> {
        // Read just before the read is sent, so the lag measures the node and not round trips.
        let now_ms = (self.clock)();
        let read = self.reader.read().await?;
        let block_ms = read.timestamp.saturating_mul(1_000);
        if now_ms > block_ms.saturating_add(MAX_READ_LAG_MS) {
            return Err(FeedError::Connection(format!(
                "Hanji node is {} ms behind: its latest block {} is from {}",
                now_ms.saturating_sub(block_ms),
                read.block_number,
                read.timestamp
            )));
        }
        let newest = self
            .last_block
            .fetch_max(read.block_number, Ordering::Relaxed);
        if read.block_number < newest {
            return Err(FeedError::Connection(format!(
                "Hanji node answered from block {}, older than block {newest} already read",
                read.block_number
            )));
        }
        Ok(BookSnapshot::received_now(self.assembler.books(&read)?))
    }
}

/// The wall clock in Unix milliseconds. A clock set before 1970 reads as `u64::MAX`, which fails
/// every read's lag check rather than passing it.
fn unix_now_ms() -> u64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(u64::MAX, |elapsed| u64::try_from(elapsed.as_millis()).unwrap_or(u64::MAX))
}

/// Turns one [`BookRead`] into books: one per market between served tokens with a quotable side
/// that clears the TVL floor.
#[derive(Debug, Clone)]
pub(super) struct HanjiBookAssembler {
    pub(super) book_config: BookFeedConfig,
    /// The proxies whose market the last read reported malformed, so that the change is logged
    /// once each way.
    malformed: Arc<Mutex<HashSet<Address>>>,
}

/// A served market's state, with both sides of its book in whole tokens.
struct ServedMarket<'r> {
    market_read: &'r MarketRead,
    state: HanjiState,
    asks: Levels,
    bids: Levels,
}

impl HanjiBookAssembler {
    pub(super) fn new(book_config: BookFeedConfig) -> Self {
        Self { book_config, malformed: Arc::new(Mutex::new(HashSet::new())) }
    }

    /// Every market of `read` that is served: those between served tokens whose book has a level
    /// and reads as one the contracts could report. A malformed market is logged when it starts
    /// and stops being one. Fails when every market read is malformed, which is a change in what
    /// the chain reports rather than in its books.
    fn served<'r>(&self, read: &'r BookRead) -> Result<Vec<ServedMarket<'r>>, FeedError> {
        let native = self
            .book_config
            .chain
            .native_token()
            .address;
        let mut served = Vec::new();
        let mut first_malformed = None;
        let mut malformed_count = 0;
        let mut malformed = self
            .malformed
            .lock()
            .unwrap_or_else(PoisonError::into_inner);
        for market_read in &read.markets {
            let market = &market_read.market;
            match self.served_market(market_read, &native) {
                Ok(served_market) => {
                    if malformed.remove(&market.orderbook) {
                        info!(market = market.name, orderbook = %market.orderbook, "Hanji market reads as well-formed again");
                    }
                    served.extend(served_market);
                }
                Err(error) => {
                    if malformed.insert(market.orderbook) {
                        warn!(market = market.name, orderbook = %market.orderbook, %error, "skipping Hanji market the chain reports malformed");
                    }
                    malformed_count += 1;
                    first_malformed.get_or_insert((market, error));
                }
            }
        }
        if let Some((market, error)) = first_malformed {
            if malformed_count == read.markets.len() {
                return Err(FeedError::Parsing(format!(
                    "Hanji: all {malformed_count} markets read are malformed; {} ({}): {error}",
                    market.name, market.orderbook
                )));
            }
        }
        Ok(served)
    }

    /// The books of `read`'s served markets that clear the TVL floor: see [`Self::served`].
    pub(super) fn books(&self, read: &BookRead) -> Result<Books, FeedError> {
        let served = self.served(read)?;
        let usd_tokens = usd_stablecoins_for_chain(self.book_config.chain).unwrap_or_default();
        let bids: Vec<(&Bytes, &Bytes, &Levels)> = served
            .iter()
            .filter(|market| !market.bids.is_empty())
            .map(|market| {
                (&market.state.base_token.address, &market.state.quote_token.address, &market.bids)
            })
            .collect();
        let updated_at = i64::try_from(read.timestamp)
            .ok()
            .and_then(|seconds| DateTime::from_timestamp(seconds, 0));
        let mut priced = Vec::with_capacity(served.len());
        for market in &served {
            let raw_tvl = market.asks.notional() + market.bids.notional();
            let tvl = tvl_in_usd(
                raw_tvl,
                &market.state.quote_token.address,
                &usd_tokens,
                bids.iter().copied(),
            );
            priced.push(tvl);
        }
        let mut books = Books::new();
        for (ServedMarket { market_read, state, .. }, tvl) in served.into_iter().zip(priced) {
            let orderbook = market_read.market.orderbook;
            // A pair could be listed on two proxies, each its own market, so the proxy is part of
            // the id.
            let component_id = maker_component_id(
                PROTOCOL_SYSTEM,
                &state.base_token.address,
                &state.quote_token.address,
                &orderbook.to_string(),
            );
            let Some(tvl) = tvl else {
                debug!(%component_id, "skipping Hanji market whose quote token has no USD price");
                continue;
            };
            if !self
                .book_config
                .clears_min_tvl(tvl, &component_id)
            {
                continue;
            }
            let mut book = pair_book(
                PROTOCOL_SYSTEM,
                PROTOCOL_TYPE,
                self.book_config.chain,
                component_id,
                state,
                updated_at,
            );
            book.component
                .static_attributes
                .insert(ORDERBOOK_ATTRIBUTE.to_string(), Bytes::from(orderbook.to_vec()));
            books.insert(book);
        }
        Ok(books)
    }

    /// The market's state and levels; `None`, logged, when its tokens are not served or neither
    /// side of its book holds a level; an error when the chain reports it malformed.
    fn served_market<'r>(
        &self,
        market_read: &'r MarketRead,
        native: &Bytes,
    ) -> Result<Option<ServedMarket<'r>>, SimulationError> {
        let market = &market_read.market;
        let (base, quote) = market.published_tokens(native);
        let Some((base_token, quote_token)) = self
            .book_config
            .pair_tokens(&base, &quote)
        else {
            debug!(orderbook = %market.orderbook, %base, %quote, "skipping Hanji market of unserved tokens");
            return Ok(None);
        };
        if market_read.asks.is_empty() && market_read.bids.is_empty() {
            debug!(orderbook = %market.orderbook, "skipping Hanji market with an empty book");
            return Ok(None);
        }
        let state = HanjiState {
            orderbook: market.orderbook,
            base_token: base_token.clone(),
            quote_token: quote_token.clone(),
            scaling_x: market_read.config.scaling_x,
            scaling_y: market_read.config.scaling_y,
            fee_rate: market_read.config.fee_rate,
            gas: market.gas,
            asks: market_read.asks.clone(),
            bids: market_read.bids.clone(),
        };
        let state = state.validated()?;
        let level_error = |error: InvalidLevel| {
            SimulationError::InvalidInput(format!("Hanji level: {error}"), None)
        };
        let asks = human_levels(&state, &state.asks).map_err(level_error)?;
        let bids = human_levels(&state, &state.bids).map_err(level_error)?;
        Ok(Some(ServedMarket { market_read, state, asks, bids }))
    }
}

/// One side of `state`'s book in whole tokens: base quantities, priced in quote per base. The
/// book's depth in USD is valued from these: in its quote token, then converted through the bids
/// of a market that sells the quote token for a USD stablecoin (see [`tvl_in_usd`]).
fn human_levels(state: &HanjiState, side: &[Level]) -> Result<Levels, InvalidLevel> {
    let scaling_x = u256_to_biguint(state.scaling_x);
    let scaling_y = u256_to_biguint(state.scaling_y);
    let base_per_share = sim::to_human(&scaling_x, state.base_token.decimals);
    let mut levels = Vec::with_capacity(side.len());
    for level in side {
        let base = u256_to_biguint(level.shares) * &scaling_x;
        let quote_per_share = u256_to_biguint(level.price) * &scaling_y;
        levels.push(PriceLevel {
            quantity: sim::to_human(&base, state.base_token.decimals),
            price: sim::to_human(&quote_per_share, state.quote_token.decimals) / base_per_share,
        });
    }
    Levels::new(levels)
}

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

    use rstest::rstest;
    use tycho_common::models::{token::Token, Chain};

    use super::*;
    use crate::pamm::protocols::hanji::{
        state::Level,
        test_support::{
            book_config, cbbtc, eth, fixture, levels, source, state, usdc, Caller, FakeNode, Rates,
            CBBTC_ETH, CBBTC_USDC, ETH_USDC, MARKETS_API, NVDA_USDC,
        },
    };

    fn component_id(base: &Token, quote: &Token, orderbook: Address) -> String {
        maker_component_id(PROTOCOL_SYSTEM, &base.address, &quote.address, &orderbook.to_string())
            .to_string()
    }

    fn recorded_bids(orderbook: Address, caller: Caller) -> Vec<Level> {
        let fixture = fixture();
        levels(
            &fixture
                .market(orderbook)
                .book(caller)
                .unwrap()
                .bids,
        )
    }

    fn published_bids(snapshot: &BookSnapshot<ReceivedAt>, id: &str) -> Vec<Level> {
        snapshot.books[id]
            .state
            .as_any()
            .downcast_ref::<HanjiState>()
            .unwrap()
            .bids
            .clone()
    }

    /// A node, a source reading it for Tycho's router at the recorded block, and the server they
    /// talk through.
    async fn served(
        node: FakeNode,
    ) -> (Arc<FakeNode>, HanjiBookSource, crate::snapshot_feed::http::test_support::MockHttpServer)
    {
        let node = Arc::new(node);
        let server = Arc::clone(&node).serve().await;
        let source = source(&server, node.fixture.timestamp * 1_000);
        (node, source, server)
    }

    /// A poll at the recorded block publishes the three markets whose tokens the universe holds,
    /// with ETH as the native token on whichever side it is, the proxy each trades through, and
    /// the book the proxy fills Tycho's router against: FastQuoter's, since every market had
    /// whitelisted it at the recorded block.
    #[tokio::test]
    async fn test_poll_publishes_served_markets() {
        let (_node, source, _server) = served(FakeNode::new()).await;

        let snapshot = source.fetch().await.unwrap();

        let expected = [
            (component_id(&eth(), &usdc(), ETH_USDC), ETH_USDC),
            (component_id(&cbbtc(), &usdc(), CBBTC_USDC), CBBTC_USDC),
            (component_id(&cbbtc(), &eth(), CBBTC_ETH), CBBTC_ETH),
        ];
        assert_eq!(snapshot.books.len(), expected.len());
        for (id, orderbook) in &expected {
            let book = &snapshot.books[id];
            assert_eq!(book.component.protocol_system, PROTOCOL_SYSTEM);
            assert_eq!(
                book.component.static_attributes[ORDERBOOK_ATTRIBUTE],
                Bytes::from(orderbook.to_vec())
            );
            assert_eq!(published_bids(&snapshot, id), recorded_bids(*orderbook, Caller::Router));
        }
        let eth_usdc = &snapshot.books[&expected[0].0].component;
        assert_eq!(eth_usdc.tokens, vec![eth(), usdc()]);
    }

    /// Each published state is the market's config and the book its proxy fills the taker
    /// against, field for field: both scalings, the taker's rate (the aggressive commission plus
    /// the passive payout, not the passive commission), and both sides from the same quoter.
    #[rstest]
    #[case::whitelisted_taker(Caller::Direct)]
    #[case::contract_taker(Caller::Contract)]
    #[tokio::test]
    async fn test_published_state(#[case] book: Caller) {
        let node = FakeNode { rates: Some(Rates::DISTINCT), ..FakeNode::new() };
        node.whitelist_the_router_everywhere(book == Caller::Direct);
        let (_node, source, _server) = served(node).await;

        let snapshot = source.fetch().await.unwrap();

        for (base, quote, orderbook) in
            [(eth(), usdc(), ETH_USDC), (cbbtc(), usdc(), CBBTC_USDC), (cbbtc(), eth(), CBBTC_ETH)]
        {
            let published = snapshot.books[&component_id(&base, &quote, orderbook)]
                .state
                .as_any()
                .downcast_ref::<HanjiState>()
                .unwrap()
                .clone();
            let mut expected = state(orderbook, book);
            expected.fee_rate = Rates::DISTINCT.taker();
            assert_eq!(published, expected, "{orderbook}");
        }
    }

    /// The TVL floor applies in USD: cbBTC/ETH's depth, valued in ETH, is converted through
    /// ETH/USDC's bids. At the recorded block every book is worth more than 100k USD and less
    /// than 100M.
    #[test]
    fn test_tvl_floor_in_usd() {
        let fixture = fixture();
        let read = fixture.read(Caller::Router);
        let published = |min_tvl_usd| {
            HanjiBookAssembler::new(BookFeedConfig { min_tvl_usd, ..book_config() })
                .books(&read)
                .unwrap()
                .into_map()
                .len()
        };

        assert_eq!(published(100_000.0), 3);
        assert_eq!(published(100_000_000.0), 0);
    }

    /// A read whose every market is malformed fails rather than publishing nothing; one malformed
    /// market among others is left out.
    #[test]
    fn test_assembler_malformed_markets() {
        let fixture = fixture();
        let assembler = HanjiBookAssembler::new(book_config());
        let mut read = fixture.read(Caller::Router);
        read.markets[0].config.scaling_x = alloy::primitives::U256::ZERO;
        let served = assembler.served(&read).unwrap().len();
        for market in &mut read.markets {
            market.config.scaling_x = alloy::primitives::U256::ZERO;
        }

        let all_malformed = assembler.served(&read);

        assert_eq!(served, 2);
        assert!(matches!(all_malformed, Err(FeedError::Parsing(_))));
    }

    #[test]
    fn test_assembler_empty_book() {
        let fixture = fixture();
        let mut read = fixture.read(Caller::Router);
        for market in &mut read.markets {
            market.asks.clear();
            market.bids.clear();
        }

        let books = HanjiBookAssembler::new(book_config())
            .books(&read)
            .unwrap();

        assert!(books.into_map().is_empty());
    }

    /// A read whose block trails the clock by the allowed lag is published; one more millisecond
    /// fails the poll.
    #[rstest]
    #[case::at_the_allowed_lag(MAX_READ_LAG_MS, true)]
    #[case::past_the_allowed_lag(MAX_READ_LAG_MS + 1, false)]
    #[tokio::test]
    async fn test_poll_node_lag(#[case] lag_ms: u64, #[case] published: bool) {
        let node = Arc::new(FakeNode::new());
        let server = Arc::clone(&node).serve().await;
        let source = source(&server, node.fixture.timestamp * 1_000 + lag_ms);

        let result = source.fetch().await;

        assert_eq!(result.is_ok(), published);
        assert!(result.is_ok() || matches!(result, Err(FeedError::Connection(_))));
    }

    /// The lag is measured just before the read is sent: a read that takes 500 ms to answer does
    /// not count, so a node 250 ms inside the allowed lag when the read leaves is published.
    #[tokio::test]
    async fn test_poll_lag_measured_at_send() {
        let node = Arc::new(FakeNode::new());
        *node.node_delay.lock().unwrap() = Duration::from_millis(500);
        let server = Arc::clone(&node).serve().await;
        let started = std::time::Instant::now();
        let start_ms = node.fixture.timestamp * 1_000 + MAX_READ_LAG_MS - 250;
        let mut source = source(&server, start_ms);
        source.clock =
            Arc::new(move || start_ms + u64::try_from(started.elapsed().as_millis()).unwrap());

        let result = source.fetch().await;

        assert!(result.is_ok(), "{result:?}");
    }

    #[tokio::test]
    async fn test_poll_older_block() {
        let (node, source, _server) = served(FakeNode::new()).await;
        source.fetch().await.unwrap();

        node.block
            .fetch_sub(1, Ordering::SeqCst);
        let result = source.fetch().await;

        assert!(matches!(result, Err(FeedError::Connection(_))));
    }

    #[tokio::test]
    async fn test_poll_other_chain() {
        let (_node, source, _server) = served(FakeNode { chain_id: 1, ..FakeNode::new() }).await;

        let result = source.fetch().await;

        assert!(matches!(result, Err(FeedError::Fatal(_))));
    }

    /// What a test makes one proxy report.
    #[derive(Debug, Clone, Copy)]
    enum Fault {
        /// `getConfig()` reverts.
        Reverting,
        /// `getConfig()` puts native ETH on the other side than the deployment.
        NativeFlipped,
        /// `getConfig()` names other tokens than the deployment.
        Misreporting,
        /// The CLOB getter reverts.
        Unwired,
        /// The proxy is paused: it fills nothing, though its quoters still report a book.
        Paused,
    }

    /// A market whose proxy reports `fault` is left out; the others are still published.
    #[rstest]
    #[case::reverting(Fault::Reverting)]
    #[case::native_flipped(Fault::NativeFlipped)]
    #[case::misreporting(Fault::Misreporting)]
    #[case::unwired(Fault::Unwired)]
    #[case::paused(Fault::Paused)]
    #[tokio::test]
    async fn test_faulty_market_is_left_out(#[case] fault: Fault) {
        let mut node = FakeNode::new();
        let faulty = match fault {
            Fault::Reverting => &mut node.reverting,
            Fault::NativeFlipped => &mut node.native_flipped,
            Fault::Misreporting => &mut node.misreporting,
            Fault::Unwired => &mut node.unwired,
            Fault::Paused => &mut node.paused,
        };
        faulty.insert(CBBTC_ETH);
        let (_node, source, _server) = served(node).await;

        let snapshot = source.fetch().await.unwrap();

        assert_left_out(&snapshot, &component_id(&cbbtc(), &eth(), CBBTC_ETH));
    }

    /// Only the market `id` is missing from the snapshot of the three.
    fn assert_left_out(snapshot: &BookSnapshot<ReceivedAt>, id: &str) {
        assert_eq!(snapshot.books.len(), 2, "{:?}", snapshot.books.keys());
        assert!(!snapshot.books.contains_key(id));
    }

    fn next_block(node: &FakeNode) {
        node.block
            .fetch_add(1, Ordering::SeqCst);
    }

    /// Collects the warnings logged on this thread while it is alive.
    struct CapturedWarnings {
        logs: Arc<Mutex<Vec<u8>>>,
        _guard: tracing::subscriber::DefaultGuard,
    }

    struct CaptureWriter(Arc<Mutex<Vec<u8>>>);

    impl std::io::Write for CaptureWriter {
        fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
            self.0
                .lock()
                .map_err(|e| std::io::Error::other(e.to_string()))?
                .extend_from_slice(buf);
            Ok(buf.len())
        }

        fn flush(&mut self) -> std::io::Result<()> {
            Ok(())
        }
    }

    impl CapturedWarnings {
        fn start() -> Self {
            let logs = Arc::new(Mutex::new(Vec::new()));
            let writer = Arc::clone(&logs);
            let subscriber = tracing_subscriber::fmt()
                .with_env_filter(tracing_subscriber::EnvFilter::new("warn"))
                .with_writer(move || CaptureWriter(Arc::clone(&writer)))
                .with_ansi(false)
                .finish();
            Self { logs, _guard: tracing::subscriber::set_default(subscriber) }
        }

        /// How many logged lines contain `message`.
        fn count(&self, message: &str) -> usize {
            let logs = String::from_utf8(self.logs.lock().unwrap().clone()).unwrap();
            logs.lines()
                .filter(|line| line.contains(message))
                .count()
        }
    }

    /// A market that keeps failing to read is warned about once, not on every poll.
    #[tokio::test]
    async fn test_failing_market_warned_once() {
        let mut node = FakeNode::new();
        node.unwired.insert(CBBTC_ETH);
        let (node, source, _server) = served(node).await;
        let warnings = CapturedWarnings::start();

        for _ in 0..3 {
            source.fetch().await.unwrap();
            next_block(&node);
        }

        assert_eq!(warnings.count("skipping Hanji market whose calls do not read"), 1);
    }

    /// A market the chain keeps reporting malformed is warned about once, not on every read.
    #[test]
    fn test_malformed_market_warned_once() {
        let fixture = fixture();
        let assembler = HanjiBookAssembler::new(book_config());
        let mut read = fixture.read(Caller::Router);
        read.markets[0].config.scaling_x = alloy::primitives::U256::ZERO;
        let warnings = CapturedWarnings::start();

        for _ in 0..3 {
            assembler.books(&read).unwrap();
        }

        assert_eq!(warnings.count("skipping Hanji market the chain reports malformed"), 1);
    }

    /// A poll where no market reads cleanly fails instead of publishing nothing.
    #[tokio::test]
    async fn test_poll_no_market_reads() {
        let mut node = FakeNode::new();
        node.reverting = BASE_DEPLOYMENT
            .markets
            .iter()
            .map(|market| market.orderbook)
            .collect();
        let (_node, source, _server) = served(node).await;

        assert!(matches!(source.fetch().await, Err(FeedError::Parsing(_))));
    }

    /// Every poll asks the node twice: once for the read and once for the batch of
    /// implementations.
    #[tokio::test]
    async fn test_poll_request_count() {
        let (_node, source, server) = served(FakeNode::new()).await;

        for _ in 0..3 {
            source.fetch().await.unwrap();
        }

        assert_eq!(server.request_count(), 3 * 2);
    }

    /// Once the proxies take the taker off their whitelist, they fill it against the contract
    /// quoter's book, and the feed publishes that one from the next poll.
    #[tokio::test]
    async fn test_whitelist_change() {
        let (node, source, _server) = served(FakeNode::new()).await;
        let id = component_id(&eth(), &usdc(), ETH_USDC);
        let before = source.fetch().await.unwrap();

        node.whitelist_the_router_everywhere(false);
        next_block(&node);
        let after = source.fetch().await.unwrap();

        assert_eq!(published_bids(&before, &id), recorded_bids(ETH_USDC, Caller::Direct));
        assert_eq!(published_bids(&after, &id), recorded_bids(ETH_USDC, Caller::Contract));
    }

    /// A market the deployment does not list (the tokenized equities) is not published, even
    /// with its tokens served.
    #[tokio::test]
    async fn test_poll_unlisted_market() {
        let (_node, mut source, _server) = served(FakeNode::new()).await;
        let nvda = Token::new(
            &Bytes::from("0xb20000000000000000000078ee7ce2fe4908108c"),
            "NVDAc",
            8,
            0,
            &[Some(10_000)],
            Chain::Base,
            100,
        );
        let mut tokens = (*book_config().tokens).clone();
        tokens.insert(nvda.address.clone(), nvda.clone());
        source.assembler.book_config.tokens = Arc::new(tokens);

        let snapshot = source.fetch().await.unwrap();

        assert!(!snapshot
            .books
            .contains_key(&component_id(&nvda, &usdc(), NVDA_USDC)));
        assert_eq!(snapshot.books.len(), 3);
    }

    /// A proxy that starts naming another quoter or CLOB is withheld from the read that sees
    /// the change, while the others are published, and published again from the read that sees
    /// it name the pinned ones.
    #[rstest]
    #[case::another_contract_quoter(Wiring::ContractQuoter)]
    #[case::no_contract_quoter(Wiring::NoContractQuoter)]
    #[case::another_clob(Wiring::Clob)]
    #[tokio::test]
    async fn test_rewired_market_withheld(#[case] change: Wiring) {
        let (node, source, _server) = served(FakeNode::new()).await;
        let id = component_id(&cbbtc(), &usdc(), CBBTC_USDC);
        let other = node
            .fixture
            .market(CBBTC_ETH)
            .wiring
            .lob;
        let before = source.fetch().await.unwrap();

        match change {
            Wiring::ContractQuoter => {
                let fastquoter = BASE_DEPLOYMENT.quoters.fast;
                node.rewired
                    .lock()
                    .unwrap()
                    .insert(CBBTC_USDC, fastquoter);
            }
            Wiring::NoContractQuoter => {
                node.rewired
                    .lock()
                    .unwrap()
                    .insert(CBBTC_USDC, Address::ZERO);
            }
            Wiring::Clob => {
                node.relinked
                    .lock()
                    .unwrap()
                    .insert(CBBTC_USDC, other);
            }
        }
        next_block(&node);
        let changed = source.fetch().await.unwrap();
        node.rewired.lock().unwrap().clear();
        node.relinked.lock().unwrap().clear();
        next_block(&node);
        let restored = source.fetch().await.unwrap();

        assert!(before.books.contains_key(&id));
        assert_left_out(&changed, &id);
        assert_eq!(published_bids(&restored, &id), recorded_bids(CBBTC_USDC, Caller::Router));
    }

    /// What a test changes in a proxy's wiring.
    #[derive(Debug, Clone, Copy)]
    enum Wiring {
        ContractQuoter,
        NoContractQuoter,
        Clob,
    }

    /// A market whose proxy or CLOB is upgraded to an implementation not pinned is withheld from
    /// the poll that reads the upgrade, while the others are published, and published again once
    /// it runs the pinned one.
    #[rstest]
    #[case::proxy(false)]
    #[case::clob(true)]
    #[tokio::test]
    async fn test_upgraded_market_withheld(#[case] clob: bool) {
        let (node, source, _server) = served(FakeNode::new()).await;
        let id = component_id(&cbbtc(), &usdc(), CBBTC_USDC);
        let market = BASE_DEPLOYMENT.markets[1];
        assert_eq!(market.orderbook, CBBTC_USDC);
        let (upgraded, pinned) = if clob {
            (market.clob, market.clob_implementation)
        } else {
            (market.orderbook, market.orderbook_implementation)
        };
        let before = source.fetch().await.unwrap();

        node.implementations
            .lock()
            .unwrap()
            .insert(upgraded, Address::repeat_byte(0x11));
        next_block(&node);
        let withheld = source.fetch().await.unwrap();
        node.implementations
            .lock()
            .unwrap()
            .insert(upgraded, pinned);
        next_block(&node);
        let restored = source.fetch().await.unwrap();

        assert!(before.books.contains_key(&id));
        assert_left_out(&withheld, &id);
        assert!(restored.books.contains_key(&id));
    }

    /// The LPManager holds every market's inventory: while it runs an implementation not pinned,
    /// every market is withheld.
    #[tokio::test]
    async fn test_upgraded_lp_manager_withholds_all() {
        let node = FakeNode::new();
        let (lp_manager, _) = BASE_DEPLOYMENT.shared[0];
        node.implementations
            .lock()
            .unwrap()
            .insert(lp_manager, Address::repeat_byte(0x11));
        let (_node, source, _server) = served(node).await;

        let snapshot = source.fetch().await.unwrap();

        assert!(snapshot.books.is_empty());
    }

    /// Withholding the markets that read cleanly publishes nothing rather than failing the poll,
    /// which would only back the feed off, even when the other markets failed to read.
    #[tokio::test]
    async fn test_poll_all_readable_markets_upgraded() {
        let mut node = FakeNode::new();
        node.reverting.insert(CBBTC_USDC);
        for implementation in node
            .implementations
            .get_mut()
            .unwrap()
            .values_mut()
        {
            *implementation = Address::repeat_byte(0x11);
        }
        let (_node, source, _server) = served(node).await;

        let snapshot = source.fetch().await.unwrap();

        assert!(snapshot.books.is_empty());
    }

    /// A node that cannot report the implementations fails the poll: nothing is published that
    /// could not be checked.
    #[tokio::test]
    async fn test_poll_unreadable_implementations() {
        let node = FakeNode::new();
        node.storage_failing
            .store(true, Ordering::SeqCst);
        let (_node, source, _server) = served(node).await;

        let result = source.fetch().await;

        assert!(matches!(result, Err(FeedError::Connection(_))), "{result:?}");
    }

    /// Against Base mainnet: a poll publishes every market of the deployment, so each one's
    /// proxy and CLOB still run and name what is pinned.
    #[tokio::test]
    #[ignore = "reads Base mainnet; set BASE_RPC_URL"]
    async fn test_live_markets_run_pinned_implementations() {
        let url = std::env::var("BASE_RPC_URL").expect("BASE_RPC_URL not set");
        let feed = HanjiFeedBuilder::new(book_config(), url)
            .build()
            .unwrap();

        let snapshot = feed.source.fetch().await.unwrap();

        assert_eq!(
            snapshot.books.len(),
            BASE_DEPLOYMENT.markets.len(),
            "{:?}",
            snapshot.books.keys()
        );
    }

    /// Against Hanji's aggregator API and Base mainnet: every market the API lists whose proxy
    /// names the pinned contract quoter, as the deployment's markets do, is in the deployment
    /// with the tokens and native side the API gives it, and every market of the deployment is
    /// still listed. A market the API adds fails this test until its fills are recorded and it
    /// is pinned; one the API drops fails it until the deployment drops it. The tokenized
    /// equities name no contract quoter and are not served.
    #[tokio::test]
    #[ignore = "reads Hanji's API and Base mainnet; set BASE_RPC_URL"]
    async fn test_live_deployment_lists_served_markets() {
        use alloy::{
            providers::{Provider, RootProvider},
            rpc::types::{TransactionInput, TransactionRequest},
            sol_types::SolValue,
        };

        use crate::pamm::protocols::hanji::{market::NativeSide, reader::CONTRACT_QUOTER_SELECTOR};

        let url = std::env::var("BASE_RPC_URL").expect("BASE_RPC_URL not set");
        let provider: RootProvider = RootProvider::new_http(url.parse().unwrap());
        let listed: Vec<serde_json::Value> = reqwest::Client::new()
            .get(MARKETS_API)
            .timeout(Duration::from_secs(10))
            .send()
            .await
            .unwrap()
            .error_for_status()
            .unwrap()
            .json()
            .await
            .unwrap();
        let address = |value: &serde_json::Value| -> Address {
            serde_json::from_value(value.clone()).unwrap()
        };
        let weth = Chain::Base
            .wrapped_native_token()
            .unwrap()
            .address;
        let weth = Address::try_from(weth.as_ref()).unwrap();

        let mut missing = Vec::new();
        let mut listed_orderbooks = Vec::new();
        for entry in &listed {
            let orderbook = address(&entry["orderbookAddress"]);
            listed_orderbooks.push(orderbook);
            let request = TransactionRequest::default()
                .to(orderbook)
                .input(TransactionInput::new(CONTRACT_QUOTER_SELECTOR.to_vec().into()));
            let answer = provider.call(request).await.unwrap();
            let contract_quoter = Address::abi_decode(&answer).unwrap();
            if contract_quoter != BASE_DEPLOYMENT.quoters.contract {
                continue;
            }
            let Some(market) = BASE_DEPLOYMENT
                .markets
                .iter()
                .find(|market| market.orderbook == orderbook)
            else {
                missing.push(entry.clone());
                continue;
            };
            let (base, quote) = (&entry["baseToken"], &entry["quoteToken"]);
            let native = match (base["isNative"].as_bool(), quote["isNative"].as_bool()) {
                (Some(true), _) => NativeSide::X,
                (_, Some(true)) => NativeSide::Y,
                _ => NativeSide::None,
            };
            assert_eq!(
                (address(&base["contractAddress"]), address(&quote["contractAddress"]), native),
                (market.token_x, market.token_y, market.native),
                "{}: the API lists it differently",
                market.name
            );
            let native_token = match native {
                NativeSide::None => None,
                NativeSide::X => Some(market.token_x),
                NativeSide::Y => Some(market.token_y),
            };
            assert!(native_token.is_none_or(|token| token == weth), "{}", market.name);
        }

        assert!(missing.is_empty(), "the API lists markets the deployment lacks: {missing:#?}");
        for market in BASE_DEPLOYMENT.markets {
            assert!(
                listed_orderbooks.contains(&market.orderbook),
                "{} ({}) is no longer listed",
                market.name,
                market.orderbook
            );
        }
    }

    #[test]
    fn test_builder_invalid_input() {
        let rpc = "http://localhost:8545".to_string();
        let on_ethereum = BookFeedConfig { chain: Chain::Ethereum, ..book_config() };

        let other_chain = HanjiFeedBuilder::new(on_ethereum, rpc.clone()).build();
        let bad_url = HanjiFeedBuilder::new(book_config(), "not a url".into()).build();
        let bad_taker = HanjiFeedBuilder::new(book_config(), rpc.clone())
            .taker(Bytes::from("0x1234"))
            .build();

        assert!(matches!(other_chain, Err(FeedError::InvalidInput(_))));
        assert!(matches!(bad_url, Err(FeedError::InvalidInput(_))));
        assert!(matches!(bad_taker, Err(FeedError::InvalidInput(_))));
        assert!(HanjiFeedBuilder::new(book_config(), rpc)
            .build()
            .is_ok());
    }

    /// The RPC URL commonly carries a key: neither the feed's `Debug` output nor a failed poll's
    /// error repeats it.
    #[tokio::test]
    async fn test_rpc_url_redacted() {
        let rpc = "http://127.0.0.1:1/secret-key".to_string();
        let feed = HanjiFeedBuilder::new(book_config(), rpc)
            .build()
            .unwrap();
        let reader = feed.source.reader.clone();

        let debug = format!("{feed:?}");
        let error = reader
            .read()
            .await
            .unwrap_err()
            .to_string();

        assert!(!debug.contains("secret-key"), "{debug}");
        assert!(!error.contains("secret-key"), "{error}");
    }
}