tycho-simulation 0.528.0

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
use std::{
    collections::{HashMap, HashSet},
    sync::Arc,
};

use chrono::DateTime;
use http::Request;
use tracing::{debug, warn};
use tycho_common::Bytes;

use crate::{
    book::{
        all_pairs::{BookCollector, Venue, VenueBook},
        component::pair_component_id,
        tvl::tvl_in_usd,
        Book, BookFeedConfig, BookSnapshot, Books, ReceivedAt,
    },
    rfq::protocols::euclid::{
        client::{EuclidClient, EuclidLevelsClient},
        models::{EuclidLevelsFrame, EuclidPrices, EuclidSupportedChain},
        state::{EuclidAllPairsState, EuclidState},
        PROTOCOL_SYSTEM, PROTOCOL_TYPE,
    },
    snapshot_feed::{
        errors::FeedError,
        ws::{WsPayload, WsSource},
    },
};

/// Streams Euclid's levels WebSocket and decodes every frame into the complete book its
/// [`EuclidBookAssembler`] makes of it.
#[derive(Clone, Debug)]
pub struct EuclidBookSource {
    pub(super) prices: EuclidPricesSource,
    pub(super) assembler: EuclidBookAssembler,
}

impl WsSource for EuclidBookSource {
    type Snapshot = BookSnapshot<ReceivedAt>;

    fn request(&self) -> Result<Request<()>, FeedError> {
        self.prices.request()
    }

    fn decode(
        &mut self,
        payload: WsPayload,
    ) -> Result<Option<BookSnapshot<ReceivedAt>>, FeedError> {
        Ok(self
            .prices
            .decode(payload)?
            .map(|prices| BookSnapshot::received_now(self.assembler.collect(prices))))
    }
}

/// Reads the levels WebSocket through an [`EuclidLevelsClient`].
#[derive(Clone, Debug)]
pub(super) struct EuclidPricesSource {
    client: EuclidLevelsClient,
}

impl EuclidPricesSource {
    pub(super) fn new(client: EuclidLevelsClient) -> Self {
        Self { client }
    }
}

impl WsSource for EuclidPricesSource {
    type Snapshot = EuclidPrices;

    fn request(&self) -> Result<Request<()>, FeedError> {
        self.client
            .levels_handshake()
            // No retry builds a different request, so the feed ends rather than reconnecting.
            .map_err(|e| FeedError::Fatal(format!("Failed to build the levels handshake: {e}")))
    }

    fn decode(&mut self, payload: WsPayload) -> Result<Option<EuclidPrices>, FeedError> {
        decode_frame(payload, self.client.chain().id())
    }
}

/// Decodes one levels frame of the stream opened for `chain_id`. A binary frame carries no
/// levels and yields `None`; a frame for another chain is an error, since the stream was asked
/// for this one.
fn decode_frame(payload: WsPayload, chain_id: u64) -> Result<Option<EuclidPrices>, FeedError> {
    let text = match payload {
        WsPayload::Text(text) => text,
        // The levels stream is JSON text; a binary frame carries no levels.
        WsPayload::Binary(_) => {
            warn!("unexpected binary frame on the levels stream");
            return Ok(None);
        }
    };
    let frame: EuclidLevelsFrame = serde_json::from_str(text.as_str())
        .map_err(|e| FeedError::Parsing(format!("Failed to parse Euclid levels frame: {e}")))?;
    if frame.chain_id != chain_id {
        return Err(FeedError::Parsing(format!(
            "Euclid levels frame is for chain {}, the stream was opened for chain {chain_id}",
            frame.chain_id
        )));
    }
    EuclidPrices::from_frame(frame).map(Some)
}

/// Turns [`EuclidPrices`] into the books [`EuclidFeed`](super::feed::EuclidFeed) would publish
/// for the same frame: each pair between the configured tokens whose TVL, valued in a USD quote
/// token, clears the threshold, as simulate-ready books whose states request binding quotes
/// through the assembler's client. Created by
/// [`EuclidBookAssemblerBuilder`](super::feed::EuclidBookAssemblerBuilder), which also makes the
/// one an [`EuclidFeed`](super::feed::EuclidFeed) uses.
#[derive(Clone, Debug)]
pub struct EuclidBookAssembler {
    /// The chain the books are for; prices for any other chain assemble into none.
    pub(super) chain: EuclidSupportedChain,
    pub(super) book_config: BookFeedConfig,
    /// USD-priced tokens a book's quote token is valued in before the threshold applies.
    pub(super) usd_quote_tokens: Arc<HashSet<Bytes>>,
    /// Requests binding quotes; shared with every state built here.
    pub(super) client: Arc<EuclidClient>,
    /// Whether Euclid's pairs are published as one component or one each. Euclid signs every
    /// quote from one maker inventory, so that component is quoted once per venue.
    pub(super) all_pairs: bool,
}

impl EuclidBookAssembler {
    /// Returns the books for `prices`, keyed by component id. Valuing a book's quote token in
    /// USD uses pairs from the whole frame, including pairs outside the configured tokens.
    pub fn books(&self, prices: EuclidPrices) -> HashMap<String, Book> {
        self.collect(prices).into_map()
    }

    pub(super) fn collect(&self, prices: EuclidPrices) -> Books {
        if prices.chain_id != self.chain.id() {
            warn!(
                frame_chain_id = prices.chain_id,
                chain_id = self.chain.id(),
                "prices are for another chain, assembling no books from them"
            );
            return Books::new();
        }
        let books = prices.pairs;

        // What one quote token of each book is worth in USD. The pair that prices a book's quote
        // token is another book in the same frame, so every book is valued before any of them is
        // consumed.
        let usd_per_quote_token: Vec<Option<f64>> = books
            .iter()
            .map(|book| {
                tvl_in_usd(
                    1.0,
                    &book.quote,
                    &self.usd_quote_tokens,
                    books
                        .iter()
                        .map(|other| (&other.base, &other.quote, &other.bids)),
                )
            })
            .collect();

        let mut collector = BookCollector::new(
            PROTOCOL_SYSTEM,
            PROTOCOL_TYPE,
            self.book_config.chain,
            self.all_pairs.then_some(()),
        );
        for (book, usd_per_quote_token) in books
            .into_iter()
            .zip(usd_per_quote_token)
        {
            let Some((base_token, quote_token)) = self
                .book_config
                .pair_tokens(&book.base, &book.quote)
            else {
                continue;
            };
            let component_id = pair_component_id(PROTOCOL_SYSTEM, &book.base, &book.quote);
            let Some(usd_per_quote_token) = usd_per_quote_token else {
                debug!(
                    %component_id,
                    "skipping pair, no book prices its quote token in a USD quote token"
                );
                continue;
            };
            if !self
                .book_config
                .clears_min_tvl(book.notional_tvl() * usd_per_quote_token, &component_id)
            {
                continue;
            }
            let Some(updated_at) = i64::try_from(book.updated_at_ms)
                .ok()
                .and_then(DateTime::from_timestamp_millis)
            else {
                warn!(
                    %component_id,
                    updated_at_ms = book.updated_at_ms,
                    "skipping pair, its timestamp is not a time"
                );
                continue;
            };
            let state = EuclidState::new(
                base_token.clone(),
                quote_token.clone(),
                book,
                Arc::clone(&self.client),
            );
            collector.push(
                component_id,
                VenueBook { signer: Venue, updated_at: Some(updated_at), state },
            );
        }
        collector.finish::<EuclidAllPairsState>()
    }
}

#[cfg(test)]
mod tests {
    use tokio::time::Duration;
    use tycho_common::models::Chain;

    use super::*;
    use crate::{
        book::{all_pairs::QuoteRule, assert_same_books, test_token_map},
        rfq::protocols::euclid::{
            client::EUCLID_API_URL,
            test_support::{bytes, LEVELS_FRAME, USDC, WETH},
        },
    };

    const WBTC: &str = "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599";

    /// A WETH/WBTC/USDC assembler with USDC as the only USD quote token.
    fn test_assembler(min_tvl_usd: f64, all_pairs: bool) -> EuclidBookAssembler {
        let (weth, usdc, wbtc) = (bytes(WETH), bytes(USDC), bytes(WBTC));
        let tokens = test_token_map(&[(&weth, "WETH", 18), (&usdc, "USDC", 6), (&wbtc, "WBTC", 8)]);
        EuclidBookAssembler {
            chain: EuclidSupportedChain::Ethereum,
            book_config: BookFeedConfig {
                chain: Chain::Ethereum,
                tokens: Arc::new(tokens),
                min_tvl_usd,
            },
            usd_quote_tokens: Arc::new(HashSet::from([usdc])),
            client: Arc::new(EuclidClient::new(
                EuclidSupportedChain::Ethereum,
                EUCLID_API_URL,
                Duration::from_secs(5),
            )),
            all_pairs,
        }
    }

    fn test_source(min_tvl_usd: f64, all_pairs: bool) -> EuclidBookSource {
        EuclidBookSource {
            prices: EuclidPricesSource::new(EuclidLevelsClient::new(
                EuclidSupportedChain::Ethereum,
                EUCLID_API_URL,
            )),
            assembler: test_assembler(min_tvl_usd, all_pairs),
        }
    }

    fn pair(base: &str, quote: &str, bid: &str, ask: &str, size: &str) -> String {
        format!(
            r#"{{"base_address":"{base}","quote_address":"{quote}","bids":[["{bid}","{size}"]],"asks":[["{ask}","{size}"]],"timestamp":1757500000000}}"#
        )
    }

    fn text_frame(chain_id: u64, pairs: &str) -> WsPayload {
        WsPayload::Text(format!(r#"{{"chain_id":{chain_id},"pairs":[{pairs}]}}"#).into())
    }

    /// The prices of a frame for chain 1 carrying `pairs`.
    fn prices(pairs: &str) -> EuclidPrices {
        decode_frame(text_frame(1, pairs), 1)
            .unwrap()
            .unwrap()
    }

    #[test]
    fn a_recorded_frame_becomes_one_book_per_pair() {
        let mut source = test_source(0.0, false);
        let snapshot = source
            .decode(WsPayload::Text(LEVELS_FRAME.into()))
            .unwrap()
            .unwrap();

        let id = pair_component_id(PROTOCOL_SYSTEM, &bytes(WETH), &bytes(USDC));
        let book = &snapshot.books[&id.to_string()];
        assert_eq!(book.component.protocol_system, PROTOCOL_SYSTEM);
        assert_eq!(book.component.protocol_type_name, PROTOCOL_TYPE);
        assert_eq!(
            book.component
                .tokens
                .iter()
                .map(|token| token.address.clone())
                .collect::<Vec<_>>(),
            vec![bytes(WETH), bytes(USDC)]
        );
        assert!(book.updated_at.is_some());
        assert!(book
            .state
            .as_any()
            .downcast_ref::<EuclidState>()
            .is_some());
    }

    /// Books rebuilt from serialized prices match the source's published books for the same
    /// frame.
    #[test]
    fn prices_round_trip_builds_the_published_books() {
        let mut source = test_source(0.0, false);
        let published = source
            .decode(WsPayload::Text(LEVELS_FRAME.into()))
            .unwrap()
            .unwrap();

        let prices = decode_frame(WsPayload::Text(LEVELS_FRAME.into()), 1)
            .unwrap()
            .unwrap();
        let sent = serde_json::to_string(&prices).unwrap();
        let received: EuclidPrices = serde_json::from_str(&sent).unwrap();
        assert_eq!(received, prices);

        assert_eq!(published.books.len(), 1);
        assert_same_books(&source.assembler.books(received), &published.books);
    }

    #[test]
    fn pairs_outside_the_configured_tokens_are_skipped() {
        let unconfigured = "0x1111111111111111111111111111111111111111";
        let books = test_assembler(0.0, false).collect(prices(
            &[pair(WETH, USDC, "3000", "3001", "1"), pair(unconfigured, USDC, "1", "2", "10")]
                .join(","),
        ));
        assert_eq!(books.len(), 1);
    }

    /// Euclid sends its whole book in one frame, so a level it got wrong on one pair costs that
    /// pair and no other.
    #[test]
    fn a_frame_decodes_into_its_valid_pairs() {
        let decoded = prices(
            &[pair(WETH, USDC, "3000", "3001", "1"), pair(WBTC, USDC, "-1", "65000", "1")]
                .join(","),
        );
        assert_eq!(decoded.pairs.len(), 1);
        assert_eq!(decoded.pairs[0].base, bytes(WETH));
    }

    /// A frame with nothing readable in it fails the poll: a published snapshot is complete, so
    /// one carrying no books would withdraw every pair Euclid was serving.
    #[test]
    fn a_frame_with_nothing_valid_in_it_is_an_error() {
        let error =
            decode_frame(text_frame(1, &pair(WETH, USDC, "-1", "3001", "1")), 1).unwrap_err();
        assert!(matches!(error, FeedError::Parsing(_)), "{error:?}");
    }

    #[test]
    fn an_empty_frame_publishes_an_empty_book() {
        // The gateway sends no pairs while its own grid is stale: nothing is priced.
        let books = test_assembler(0.0, false).collect(prices(""));
        assert_eq!(books.len(), 0);
    }

    #[test]
    fn books_below_the_tvl_floor_are_filtered() {
        // (3000 * 0.1 + 3001 * 0.1) / 2 = 300.05 USD
        let thin = prices(&pair(WETH, USDC, "3000", "3001", "0.1"));
        assert_eq!(
            test_assembler(300.0, false)
                .collect(thin.clone())
                .len(),
            1
        );
        assert_eq!(
            test_assembler(301.0, false)
                .collect(thin)
                .len(),
            0
        );
    }

    /// WETH/WBTC is quoted in WBTC, which its own book sells at 60000 USDC: the 0.0505 WBTC of
    /// liquidity in it is worth 3030 USD against the floor.
    #[test]
    fn a_quote_token_is_valued_through_the_pair_that_prices_it() {
        let frame =
            [pair(WETH, WBTC, "0.05", "0.051", "1"), pair(WBTC, USDC, "60000", "60100", "1")]
                .join(",");
        let id = pair_component_id(PROTOCOL_SYSTEM, &bytes(WETH), &bytes(WBTC)).to_string();
        assert!(test_assembler(3000.0, false)
            .collect(prices(&frame))
            .contains_key(&id));
        assert!(!test_assembler(3100.0, false)
            .collect(prices(&frame))
            .contains_key(&id));
    }

    #[test]
    fn a_quote_token_nothing_values_in_usd_is_skipped() {
        let books =
            test_assembler(0.0, false).collect(prices(&pair(WETH, WBTC, "0.05", "0.051", "1")));
        assert_eq!(books.len(), 0);
    }

    #[test]
    fn a_frame_for_another_chain_is_rejected() {
        let other_chain = text_frame(8453, &pair(WETH, USDC, "3000", "3001", "1"));
        assert!(matches!(decode_frame(other_chain, 1), Err(FeedError::Parsing(_))));
    }

    /// Prices handed to an assembler for another chain — a wiring mistake between a prices
    /// reader and its assembler — make no books rather than books on the wrong chain.
    #[test]
    fn prices_for_another_chain_assemble_no_books() {
        let prices =
            EuclidPrices { chain_id: 8453, ..prices(&pair(WETH, USDC, "3000", "3001", "1")) };
        assert!(test_assembler(0.0, false)
            .books(prices)
            .is_empty());
    }

    #[test]
    fn every_pair_is_published_under_one_component_for_all_pairs() {
        let books = test_assembler(0.0, true).collect(prices(
            &[pair(WETH, USDC, "3000", "3001", "1"), pair(WBTC, USDC, "60000", "60100", "1")]
                .join(","),
        ));
        assert_eq!(books.len(), 1);
        let book = books.values().next().unwrap();
        assert_eq!(
            QuoteRule::from_attributes(&book.component.static_attributes).unwrap(),
            Some(QuoteRule::OncePerVenue)
        );
        assert!(book
            .state
            .as_any()
            .downcast_ref::<EuclidAllPairsState>()
            .is_some());
    }

    #[test]
    fn decode_skips_binary_frames_and_fails_on_malformed_text() {
        let mut source = test_source(0.0, false);
        assert!(source
            .decode(WsPayload::Binary(vec![1, 2, 3].into()))
            .unwrap()
            .is_none());
        assert!(matches!(
            source.decode(WsPayload::Text("not json".into())),
            Err(FeedError::Parsing(_))
        ));
    }
}