tycho-simulation 0.472.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
use std::{collections::HashSet, future::Future, sync::Arc};

use tokio::time::Duration;
use tycho_common::Bytes;

use crate::{
    book::{BookFeedConfig, BookSnapshot, ReceivedAt},
    rfq::{
        constants::DEFAULT_QUOTE_TIMEOUT,
        protocols::bebop::{
            client::{BebopClient, QuoteOrigin},
            models::BebopSupportedChain,
            source::BebopBookSource,
            FALLBACK_PROTOCOL_SYSTEM, PROTOCOL_SYSTEM,
        },
    },
    snapshot_feed::{
        errors::FeedError,
        ws::{default_ws_feed_config, run_ws_feed, WsFeedConfig},
        Publisher, SnapshotFeed,
    },
};

/// Bebop's book feed: streams market-maker price levels over Bebop's pricing WebSocket and
/// publishes every update as a complete [`BookSnapshot`]. Built through [`BebopFeedBuilder`].
#[derive(Clone, Debug)]
pub struct BebopFeed {
    feed_config: WsFeedConfig,
    source: BebopBookSource,
}

/// Builds a [`BebopFeed`] from the shared [`BookFeedConfig`] and Bebop's API key.
pub struct BebopFeedBuilder {
    protocol_system: &'static str,
    book_config: BookFeedConfig,
    usd_quote_tokens: Arc<HashSet<Bytes>>,
    ws_key: String,
    quote_timeout: Duration,
    origin: QuoteOrigin,
    feed_config: WsFeedConfig,
    all_pairs: bool,
}

impl BebopFeedBuilder {
    pub fn new(
        book_config: BookFeedConfig,
        usd_quote_tokens: impl Into<Arc<HashSet<Bytes>>>,
        ws_key: String,
    ) -> Self {
        Self {
            book_config,
            usd_quote_tokens: usd_quote_tokens.into(),
            ws_key,
            quote_timeout: DEFAULT_QUOTE_TIMEOUT,
            origin: QuoteOrigin::default(),
            feed_config: Self::default_feed_config(),
            protocol_system: PROTOCOL_SYSTEM,
            all_pairs: false,
        }
    }

    /// Publishes Bebop as one component for every pair it prices, which a route may take a
    /// single quote from: Bebop picks the makers behind a firm quote itself and signs once, so
    /// a route that filled against two of its pairs would be quoted for one of them.
    ///
    /// One component per pair otherwise, in each orientation Bebop publishes it.
    pub fn all_pairs(mut self) -> Self {
        self.all_pairs = true;
        self
    }

    /// Deadline for binding quote requests.
    pub fn quote_timeout(mut self, timeout: Duration) -> Self {
        self.quote_timeout = timeout;
        self
    }

    /// Set the real end-user's EOA, for a taker that is not the end-user's own wallet, sent as
    /// `origin_address` with binding quote requests.
    ///
    /// Bebop screens quote requests by these three, and can configure an API account to require
    /// one and refuse a request that leaves it out. See
    /// <https://docs.bebop.xyz/rfq-api/guides/best-practices#6-pass-origin-so-we-can-identify-legitimate-flow>.
    pub fn origin_address(mut self, origin_address: Bytes) -> Self {
        self.origin.address = Some(origin_address);
        self
    }

    /// Set the `to` address of the resulting transaction, where a contract executes the swap,
    /// sent as `origin_target` with binding quote requests. See
    /// [`origin_address`](Self::origin_address) for what Bebop does with it.
    pub fn origin_target(mut self, origin_target: Bytes) -> Self {
        self.origin.target = Some(origin_target);
        self
    }

    /// Set a stable identifier for the upstream flow source, where a solver aggregates several,
    /// sent as `origin_source` with binding quote requests. See
    /// [`origin_address`](Self::origin_address) for what Bebop does with it.
    pub fn origin_source(mut self, origin_source: String) -> Self {
        self.origin.source = Some(origin_source);
        self
    }

    /// The feed tuning a new builder starts from: the set every WebSocket feed shares, since
    /// nothing about how often Bebop pushes, or how long it goes quiet, has been measured. Spread
    /// from it to change one field:
    ///
    /// ```
    /// # use std::time::Duration;
    /// # use tycho_simulation::rfq::protocols::bebop::feed::BebopFeedBuilder;
    /// # use tycho_simulation::snapshot_feed::ws::WsFeedConfig;
    /// let tuned = WsFeedConfig {
    ///     read_idle_timeout: Duration::from_secs(30),
    ///     ..BebopFeedBuilder::default_feed_config()
    /// };
    /// ```
    pub fn default_feed_config() -> WsFeedConfig {
        default_ws_feed_config()
    }

    /// Settles this venue's swaps through Tycho's `BebopFallbackRouter`, which retries
    /// against a solver-named fallback pool when the venue reverts. Components then carry
    /// [`FALLBACK_PROTOCOL_SYSTEM`] rather than [`PROTOCOL_SYSTEM`], which is what selects
    /// the fallback encoder. Off by default.
    pub fn with_fallback_router(mut self) -> Self {
        self.protocol_system = FALLBACK_PROTOCOL_SYSTEM;
        self
    }

    /// Tune the price feed loop (timeouts, backoff, failure limit)
    pub fn feed_config(mut self, feed_config: WsFeedConfig) -> Self {
        self.feed_config = feed_config;
        self
    }

    /// Fails for chains Bebop does not serve.
    pub fn build(self) -> Result<BebopFeed, FeedError> {
        let chain =
            BebopSupportedChain::try_from(self.book_config.chain).map_err(FeedError::Fatal)?;
        Ok(BebopFeed {
            feed_config: self.feed_config,
            source: BebopBookSource {
                protocol_system: self.protocol_system,
                book_config: self.book_config,
                usd_quote_tokens: self.usd_quote_tokens,
                client: Arc::new(BebopClient::new(
                    chain,
                    self.ws_key,
                    self.quote_timeout,
                    self.origin,
                )),
                all_pairs: self.all_pairs,
            },
        })
    }
}

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

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

#[cfg(test)]
mod tests {
    use std::{collections::HashMap, str::FromStr, time::Duration};

    use dotenv::dotenv;
    use num_bigint::BigUint;
    use tokio::time::timeout;
    use tycho_common::models::{protocol::GetAmountOutParams, Chain};

    use super::*;
    use crate::{
        book::{test_token_map, Book},
        snapshot_feed::SnapshotFeed,
    };

    /// BebopSettlement.swapSingle
    const SWAP_SINGLE_SELECTOR: [u8; 4] = [0x4d, 0xce, 0xbc, 0xba];
    /// BebopSettlement.swapAggregate
    const SWAP_AGGREGATE_SELECTOR: [u8; 4] = [0xa2, 0xf7, 0x48, 0x93];
    /// BebopRouter.swap
    const ROUTER_SWAP_SELECTOR: [u8; 4] = [0x95, 0x86, 0xd0, 0xe8];

    /// Waits until the receiver holds a snapshot and returns its books.
    async fn next_books(
        rx: &mut tokio::sync::watch::Receiver<Option<BookSnapshot<ReceivedAt>>>,
    ) -> Arc<HashMap<String, Book>> {
        loop {
            rx.changed().await.expect("feed ended");
            if let Some(snapshot) = &*rx.borrow_and_update() {
                return Arc::clone(&snapshot.books);
            }
        }
    }

    #[tokio::test]
    #[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
    async fn bebop_websocket_connection() {
        // We test with quote tokens that are not USDC in order to ensure our normalization works
        // fine
        let wbtc = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
        let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();

        dotenv().expect("Missing .env file");
        let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");

        let quote_tokens = HashSet::from([
            // Use addresses we forgot to checksum (to test checksumming)
            Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(), // USDC
            Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(), // USDT
        ]);

        let book_config = BookFeedConfig {
            chain: Chain::Ethereum,
            tokens: Arc::new(test_token_map(&[(&weth, "WETH", 18), (&wbtc, "WBTC", 8)])),
            min_tvl_usd: 10.0,
        };
        let feed = BebopFeedBuilder::new(book_config, quote_tokens, key)
            .quote_timeout(Duration::from_secs(30))
            .build()
            .unwrap();

        let (publisher, mut rx) = Publisher::channel();
        let _feed = tokio::spawn(feed.run(publisher));

        // Receiving a single decodable book is enough to prove the authenticated handshake and
        // protobuf decoding work. Bebop only pushes on price changes, so requiring more makes
        // the test flaky against market cadence.
        let pairs = timeout(Duration::from_secs(10), next_books(&mut rx))
            .await
            .expect("no book received within 10 seconds");

        assert!(!pairs.is_empty());
        println!("Received {} components in this book", pairs.len());
        for pair in pairs.values() {
            assert_eq!(pair.component.protocol_system, "rfq:bebop");
            assert_eq!(pair.component.protocol_type_name, "bebop_pool");
            assert_eq!(pair.component.chain, Chain::Ethereum);

            // A streamed state carries price levels: it can quote a spot price.
            let [base, quote] = pair.component.tokens.as_slice() else {
                panic!("expected exactly two tokens")
            };
            assert!(
                pair.state
                    .spot_price(base, quote)
                    .unwrap() >
                    0.0
            );
        }
    }

    #[tokio::test]
    #[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
    async fn bebop_quote_single_order() {
        let token_in = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
        let token_out = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
        dotenv().expect("Missing .env file");
        let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");

        let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();

        let book_config = BookFeedConfig {
            chain: Chain::Ethereum,
            tokens: Arc::new(test_token_map(&[
                (&token_in, "TOKEN_IN", 18),
                (&token_out, "TOKEN_OUT", 18),
            ])),
            min_tvl_usd: 10.0,
        };
        let feed = BebopFeedBuilder::new(book_config, HashSet::new(), key)
            .quote_timeout(Duration::from_secs(30))
            .origin_address(Bytes::from_str("0x00000000219ab540356cBB839Cbe05303d7705Fa").unwrap())
            .origin_target(router.clone())
            .origin_source("tycho-test".to_string())
            .build()
            .unwrap();

        let params = GetAmountOutParams {
            amount_in: BigUint::from(1_000000000000000000u64),
            token_in: token_in.clone(),
            token_out: token_out.clone(),
            sender: router.clone(),
            receiver: router,
            origin: None,
        };
        let quote = feed
            .source
            .client
            .request_binding_quote(&params)
            .await
            .unwrap();

        assert_eq!(quote.base_token, token_in);
        assert_eq!(quote.quote_token, token_out);
        assert_eq!(quote.amount_in, BigUint::from(1_000000000000000000u64));

        // Conservative sanity bound (0.01 WBTC for 1 WETH) — proves a real, non-dust quote came
        // back without depending closely on the live WETH/WBTC price.
        assert!(quote.amount_out > BigUint::from(1_000_000u64));

        // The settlement mode depends on the API account configuration behind BEBOP_KEY:
        // settlement-mode accounts get BebopSettlement.swapSingle calldata, router-mode
        // accounts get BebopRouter.swap calldata.
        let selector = &quote
            .quote_attributes
            .get("calldata")
            .unwrap()[..4];
        if selector == SWAP_SINGLE_SELECTOR {
            let partial_fill_offset_slice = quote
                .quote_attributes
                .get("partial_fill_offset")
                .unwrap()
                .as_ref();
            let mut partial_fill_offset_array = [0u8; 8];
            partial_fill_offset_array.copy_from_slice(partial_fill_offset_slice);

            assert_eq!(u64::from_be_bytes(partial_fill_offset_array), 12);
        } else {
            assert_eq!(selector, ROUTER_SWAP_SELECTOR);
        }
    }

    #[tokio::test]
    #[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
    async fn bebop_quote_aggregate_order() {
        // This will make a quote request similar to the previous test but with a very big amount
        // We expect the Bebop Quote to have an aggregate order (split between different mms)
        let token_in = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
        let token_out = Bytes::from_str("0xfAbA6f8e4a5E8Ab82F62fe7C39859FA577269BE3").unwrap();
        dotenv().expect("Missing .env file");
        let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");

        let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();

        let book_config = BookFeedConfig {
            chain: Chain::Ethereum,
            tokens: Arc::new(test_token_map(&[
                (&token_in, "TOKEN_IN", 18),
                (&token_out, "TOKEN_OUT", 18),
            ])),
            min_tvl_usd: 10.0,
        };
        let feed = BebopFeedBuilder::new(book_config, HashSet::new(), key)
            .quote_timeout(Duration::from_secs(30))
            .origin_address(Bytes::from_str("0x00000000219ab540356cBB839Cbe05303d7705Fa").unwrap())
            .origin_target(router.clone())
            .origin_source("tycho-test".to_string())
            .build()
            .unwrap();

        let amount_in = BigUint::from_str("20_000_000_000").unwrap(); // 20k USDC
        let params = GetAmountOutParams {
            amount_in: amount_in.clone(),
            token_in: token_in.clone(),
            token_out: token_out.clone(),
            sender: router.clone(),
            receiver: router,
            origin: None,
        };
        let quote = feed
            .source
            .client
            .request_binding_quote(&params)
            .await
            .unwrap();

        assert_eq!(quote.base_token, token_in);
        assert_eq!(quote.quote_token, token_out);
        assert_eq!(quote.amount_in, amount_in);

        // Assuming the USDC - ONDO price doesn't change too much at the time of running this
        assert!(quote.amount_out > BigUint::from_str("18000000000000000000000").unwrap()); // ~19k ONDO

        // The settlement mode depends on the API account configuration behind BEBOP_KEY:
        // settlement-mode accounts get BebopSettlement.swapAggregate calldata, router-mode
        // accounts get BebopRouter.swap calldata.
        let selector = &quote
            .quote_attributes
            .get("calldata")
            .unwrap()[..4];
        if selector == SWAP_AGGREGATE_SELECTOR {
            let partial_fill_offset_slice = quote
                .quote_attributes
                .get("partial_fill_offset")
                .unwrap()
                .as_ref();
            let mut partial_fill_offset_array = [0u8; 8];
            partial_fill_offset_array.copy_from_slice(partial_fill_offset_slice);

            // This is the only attribute that is significantly different for the Single and
            // Aggregate Order
            assert_eq!(u64::from_be_bytes(partial_fill_offset_array), 2);
        } else {
            assert_eq!(selector, ROUTER_SWAP_SELECTOR);
        }
    }

    #[test]
    fn building_for_a_chain_bebop_does_not_serve_is_fatal() {
        let config = BookFeedConfig {
            chain: Chain::ZkSync,
            tokens: Arc::new(HashMap::new()),
            min_tvl_usd: 0.0,
        };

        let error = BebopFeedBuilder::new(config, HashSet::new(), "key".to_string())
            .build()
            .unwrap_err();

        assert!(error.is_fatal(), "{error}");
    }
}