Skip to main content

tycho_simulation/rfq/protocols/bebop/
state.rs

1use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};
2
3use async_trait::async_trait;
4use num_bigint::BigUint;
5use serde::{Deserialize, Serialize};
6use tycho_common::{
7    dto::ProtocolStateDelta,
8    models::{protocol::GetAmountOutParams, token::Token},
9    simulation::{
10        errors::{SimulationError, TransitionError},
11        indicatively_priced::{IndicativelyPriced, SignedQuote},
12        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
13    },
14    Bytes,
15};
16
17use crate::{
18    book::{
19        all_pairs::{all_pairs_state, PricesAfterFill, RefusesQuote, SignedByVenue},
20        component::PairState,
21        levels::Levels,
22        sim::{self, SwapDirection},
23    },
24    rfq::protocols::bebop::{client::BebopClient, models::BebopBook},
25};
26
27/// Rough gas estimate for one Bebop settlement.
28const BEBOP_SWAP_GAS: u64 = 70_000;
29
30/// What Bebop's quote endpoint refuses below, measured against the live API on Ethereum and
31/// Base in both directions: a trade worth less than one US dollar on the side being sold, the
32/// same figure for every pair. The venue says so in the refusal — `MinSize: Request quotes over
33/// $1.` — and publishes no per-token minimum, so this constant and a price are the whole rule.
34const MIN_TRADE_USD: f64 = 1.0;
35
36#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
37pub struct BebopState {
38    pub(super) base_token: Token,
39    pub(super) quote_token: Token,
40    #[debug(skip)]
41    pub(super) book: BebopBook,
42    /// What one quote token is worth in US dollars, from the pair that prices it in a USD quote
43    /// token at the moment this book was published. It is what turns the venue's dollar floor
44    /// into an amount of a token.
45    pub(super) usd_per_quote_token: f64,
46    #[serde(skip)]
47    #[debug(skip)]
48    client: Option<Arc<BebopClient>>,
49}
50
51impl BebopState {
52    /// A book this venue prices, with the client its binding quotes go to.
53    pub(super) fn new(
54        base_token: Token,
55        quote_token: Token,
56        book: BebopBook,
57        usd_per_quote_token: f64,
58        client: Arc<BebopClient>,
59    ) -> Self {
60        BebopState { base_token, quote_token, book, usd_per_quote_token, client: Some(client) }
61    }
62
63    /// The ladder a swap in `direction` consumes, in the units of the token sold: the bids as
64    /// published for selling base, the asks re-expressed per quote unit for selling quote.
65    fn ladder(&self, direction: SwapDirection) -> Cow<'_, Levels> {
66        match direction {
67            SwapDirection::BaseToQuote => Cow::Borrowed(&self.book.bids),
68            SwapDirection::QuoteToBase => Cow::Owned(self.book.asks.invert()),
69        }
70    }
71}
72
73impl PairState for BebopState {
74    fn base_token(&self) -> &Token {
75        &self.base_token
76    }
77
78    fn quote_token(&self) -> &Token {
79        &self.quote_token
80    }
81
82    fn directions(&self) -> Vec<(Bytes, Bytes)> {
83        sim::directions(
84            &self.base_token,
85            &self.quote_token,
86            !self.book.bids.is_empty(),
87            !self.book.asks.is_empty(),
88        )
89    }
90}
91
92impl PricesAfterFill for BebopState {
93    fn marginal_price(
94        &self,
95        token_in: &Bytes,
96        token_out: &Bytes,
97        filled: &BigUint,
98    ) -> Result<f64, SimulationError> {
99        let direction =
100            SwapDirection::require(&self.base_token, &self.quote_token, token_in, token_out)?;
101        let (sell_decimals, _) = direction.decimals(&self.base_token, &self.quote_token);
102        sim::marginal_price(&self.ladder(direction), filled, sell_decimals)
103    }
104}
105
106#[typetag::serde]
107impl ProtocolSim for BebopState {
108    fn fee(&self) -> f64 {
109        0.0
110    }
111
112    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
113        let direction = SwapDirection::require(
114            &self.base_token,
115            &self.quote_token,
116            &base.address,
117            &quote.address,
118        )?;
119        // Since this method does not care about sell direction, we average the price of the best
120        // bid and ask
121        let best_bid = self
122            .book
123            .bids
124            .first()
125            .map(|level| level.price);
126        let best_ask = self
127            .book
128            .asks
129            .first()
130            .map(|level| level.price);
131        // If just one is available, only consider that one
132        let average_price = match (best_bid, best_ask) {
133            (Some(best_bid), Some(best_ask)) => (best_bid + best_ask) / 2.0,
134            (Some(best_bid), None) => best_bid,
135            (None, Some(best_ask)) => best_ask,
136            (None, None) => {
137                return Err(SimulationError::RecoverableError("No liquidity available".to_string()))
138            }
139        };
140        match direction {
141            SwapDirection::BaseToQuote => Ok(average_price),
142            SwapDirection::QuoteToBase => Ok(1.0 / average_price),
143        }
144    }
145
146    fn get_amount_out(
147        &self,
148        amount_in: BigUint,
149        token_in: &Token,
150        token_out: &Token,
151    ) -> Result<GetAmountOutResult, SimulationError> {
152        // Bebop refuses a zero amount with `101 InvalidApiRequest: Sell amounts must be
153        // higher than 0.`, before the dollar floor below has anything to say.
154        sim::require_positive_amount(&amount_in)?;
155
156        let direction = SwapDirection::require(
157            &self.base_token,
158            &self.quote_token,
159            &token_in.address,
160            &token_out.address,
161        )?;
162        let ladder = self.ladder(direction);
163        let amount_in = sim::to_human(&amount_in, token_in.decimals);
164        let fill = ladder.fill(amount_in);
165        // The trade's worth is read on the quote side, which the swap already expresses: the
166        // amount sold when the quote token is sold, and what the ladder pays otherwise. The
167        // floor speaks for a book that took something: a side with no levels takes none of any
168        // amount and so is worth nothing, which the fill below reports as the absence of
169        // liquidity it is, the same answer at every size.
170        let quote_amount = match direction {
171            SwapDirection::QuoteToBase => amount_in,
172            SwapDirection::BaseToQuote => fill.amount_out,
173        };
174        let worth_usd = quote_amount * self.usd_per_quote_token;
175        if fill.remaining_in < amount_in && worth_usd < MIN_TRADE_USD {
176            return Err(SimulationError::RecoverableError(format!(
177                "Trade is worth {worth_usd} USD, below the {MIN_TRADE_USD} USD Bebop quotes"
178            )));
179        }
180        // The state doesn't change after a swap.
181        sim::fill_result(fill, amount_in, token_out.decimals, BEBOP_SWAP_GAS, self)
182    }
183
184    fn get_limits(
185        &self,
186        sell_token: Bytes,
187        buy_token: Bytes,
188    ) -> Result<(BigUint, BigUint), SimulationError> {
189        let direction =
190            SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
191        let ladder = self.ladder(direction);
192        // Nothing on this side is no swap at any size, so there is no limit to report.
193        if ladder.is_empty() {
194            return Err(SimulationError::RecoverableError("No liquidity".into()));
195        }
196        let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
197        sim::limits(&ladder, sell_decimals, buy_decimals)
198    }
199
200    fn delta_transition(
201        &mut self,
202        _delta: ProtocolStateDelta,
203        _tokens: &HashMap<Bytes, Token>,
204        _balances: &Balances,
205    ) -> Result<(), TransitionError> {
206        Err(TransitionError::DecodeError("Not implemented".into()))
207    }
208
209    fn clone_box(&self) -> Box<dyn ProtocolSim> {
210        Box::new(self.clone())
211    }
212
213    fn as_any(&self) -> &dyn Any {
214        self
215    }
216
217    fn as_any_mut(&mut self) -> &mut dyn Any {
218        self
219    }
220
221    fn eq(&self, other: &dyn ProtocolSim) -> bool {
222        if let Some(other_state) = other
223            .as_any()
224            .downcast_ref::<BebopState>()
225        {
226            self.base_token == other_state.base_token &&
227                self.quote_token == other_state.quote_token &&
228                self.book == other_state.book
229        } else {
230            false
231        }
232    }
233
234    fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
235        Ok(self)
236    }
237}
238
239#[async_trait]
240impl IndicativelyPriced for BebopState {
241    async fn request_signed_quote(
242        &self,
243        params: GetAmountOutParams,
244    ) -> Result<SignedQuote, SimulationError> {
245        Ok(sim::quoting_client(self.client.as_ref(), "Bebop")?
246            .request_binding_quote(&params)
247            .await?)
248    }
249}
250
251all_pairs_state! {
252    /// Bebop's books on one chain behind one component.
253    ///
254    /// Bebop signs its quotes itself and names no market maker, so all of its books share one
255    /// turn: a route takes one quote from the venue, and the swap that takes it spends every
256    /// book behind the component.
257    BebopAllPairsState(BebopState, SignedByVenue);
258}
259
260impl RefusesQuote for BebopAllPairsState {}
261
262#[cfg(test)]
263mod tests {
264    use std::str::FromStr;
265
266    use rstest::rstest;
267    use tokio::time::Duration;
268    use tycho_common::models::Chain;
269
270    use super::*;
271    use crate::rfq::protocols::bebop::{
272        client::QuoteOrigin,
273        models::{BebopPriceData, BebopSupportedChain},
274    };
275
276    fn wbtc() -> Token {
277        Token::new(
278            &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
279                .unwrap()
280                .into(),
281            "WBTC",
282            8,
283            0,
284            &[Some(10_000)],
285            Chain::Ethereum,
286            100,
287        )
288    }
289
290    fn usdc() -> Token {
291        Token::new(
292            &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
293                .unwrap()
294                .into(),
295            "USDC",
296            6,
297            0,
298            &[Some(10_000)],
299            Chain::Ethereum,
300            100,
301        )
302    }
303
304    fn weth() -> Token {
305        Token::new(
306            &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
307            "WETH",
308            18,
309            0,
310            &[],
311            Default::default(),
312            100,
313        )
314    }
315
316    fn empty_client() -> Arc<BebopClient> {
317        Arc::new(BebopClient::new(
318            BebopSupportedChain::Ethereum,
319            String::new(),
320            Duration::from_secs(30),
321            QuoteOrigin::default(),
322        ))
323    }
324
325    /// Bebop will not sign a trade worth less than a dollar, so simulating one advertises a
326    /// quote that cannot be had. This book quotes WBTC in USDC — a dollar is one USDC going in,
327    /// and 1539 satoshi coming out at the 65 000 USDC best bid.
328    #[rstest]
329    #[case::half_a_dollar_of_usdc("500000", true, false)]
330    #[case::two_dollars_of_usdc("2000000", true, true)]
331    #[case::sixty_five_cents_of_wbtc("1000", false, false)]
332    #[case::six_dollars_of_wbtc("10000", false, true)]
333    fn a_trade_worth_less_than_a_dollar_is_refused(
334        #[case] amount_in: &str,
335        #[case] sell_quote: bool,
336        #[case] quotable: bool,
337    ) {
338        let state = create_test_bebop_state();
339        let (token_in, token_out) = if sell_quote { (usdc(), wbtc()) } else { (wbtc(), usdc()) };
340
341        let result =
342            state.get_amount_out(BigUint::from_str(amount_in).unwrap(), &token_in, &token_out);
343
344        assert_eq!(result.is_ok(), quotable, "{result:?}");
345        if !quotable {
346            let error = result.unwrap_err().to_string();
347            assert!(error.contains("below the 1 USD Bebop quotes"), "{error}");
348        }
349    }
350
351    /// Nobody bidding is the absence of liquidity, not a trade too small to quote: the amount
352    /// is irrelevant, so both a trade well over the dollar floor and one under it get the same
353    /// answer.
354    #[rstest]
355    #[case::six_dollars_of_wbtc("10000")]
356    #[case::sixty_five_cents_of_wbtc("1000")]
357    fn selling_into_a_side_with_no_bids_reports_no_liquidity(#[case] amount_in: &str) {
358        let mut state = create_test_bebop_state();
359        state.book.bids = Levels::default();
360
361        let error = state
362            .get_amount_out(BigUint::from_str(amount_in).unwrap(), &wbtc(), &usdc())
363            .unwrap_err();
364
365        assert!(
366            matches!(&error, SimulationError::InvalidInput(message, None)
367                if message.contains("no liquidity on this side")),
368            "{error:?}"
369        );
370    }
371
372    /// A state read back from a recording carries no client: the venue's credentials are not
373    /// part of what is serialized, so a replayed book still prices but has nothing to ask for a
374    /// firm quote through.
375    #[tokio::test]
376    async fn a_replayed_state_prices_but_cannot_quote() {
377        let state = create_test_bebop_state();
378        let replayed: BebopState =
379            serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
380
381        let priced = replayed.get_amount_out(BigUint::from(10_000u64), &wbtc(), &usdc());
382        let quoted = replayed
383            .request_signed_quote(GetAmountOutParams {
384                amount_in: BigUint::from(10_000u64),
385                token_in: wbtc().address,
386                token_out: usdc().address,
387                sender: Bytes::zero(20),
388                receiver: Bytes::zero(20),
389                origin: None,
390            })
391            .await;
392
393        assert!(priced.is_ok(), "{priced:?}");
394        assert!(
395            matches!(&quoted, Err(SimulationError::FatalError(message))
396                if message.contains("carries no client")),
397            "{quoted:?}"
398        );
399    }
400
401    fn create_test_bebop_state() -> BebopState {
402        let price_data = BebopPriceData {
403            base: hex::decode("2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(), // WBTC
404            quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), // USDC
405            last_update_ts: 1703097600,
406            bids: vec![65000.0f32, 1.5f32, 64950.0f32, 2.0f32, 64900.0f32, 0.5f32],
407            asks: vec![65100.0f32, 1.0f32, 65150.0f32, 2.5f32, 65200.0f32, 1.5f32],
408        };
409        BebopState {
410            base_token: wbtc(),
411            quote_token: usdc(),
412            book: BebopBook::try_from(price_data).unwrap(),
413            // The pair's quote token is USDC.
414            usd_per_quote_token: 1.0,
415            client: Some(empty_client()),
416        }
417    }
418
419    /// After some input went in, the next unit is priced at the level where the fill stopped, on
420    /// the side of the book a swap in that direction fills.
421    #[rstest]
422    #[case::selling_base_in_the_first_level(true, 100_000_000, Some(65000.0))]
423    #[case::selling_base_on_the_first_boundary(true, 150_000_000, Some(64950.0))]
424    #[case::selling_base_past_the_depth(true, 400_000_000, None)]
425    #[case::selling_quote_before_any_fill(false, 0, Some(1.0 / 65100.0))]
426    fn the_price_after_a_fill_is_the_level_where_it_stopped(
427        #[case] sell_base: bool,
428        #[case] filled: u64,
429        #[case] expected: Option<f64>,
430    ) {
431        let state = create_test_bebop_state();
432        let (token_in, token_out) = if sell_base { (wbtc(), usdc()) } else { (usdc(), wbtc()) };
433
434        let price =
435            state.marginal_price(&token_in.address, &token_out.address, &BigUint::from(filled));
436
437        match (price, expected) {
438            (Ok(price), Some(expected)) => assert_eq!(price, expected),
439            (Err(SimulationError::RecoverableError(message)), None) => {
440                assert_eq!(message, "No liquidity")
441            }
442            (price, _) => panic!("expected {expected:?}, got {price:?}"),
443        }
444    }
445
446    #[test]
447    fn spot_price_matching_base_and_quote() {
448        let state = create_test_bebop_state();
449
450        // Test WBTC/USDC (base/quote) - should use average of best bid and ask
451        let price = state
452            .spot_price(&wbtc(), &usdc())
453            .unwrap();
454        assert_eq!(price, 65050.0);
455    }
456
457    #[test]
458    fn spot_price_inverted_base_and_quote() {
459        let state = create_test_bebop_state();
460
461        // Test USDC/WBTC (quote/base) - should use average of best bid and ask, then invert
462        let price = state
463            .spot_price(&usdc(), &wbtc())
464            .unwrap();
465        let expected = 0.00001537279;
466        assert!((price - expected).abs() < 1e-10);
467    }
468
469    #[test]
470    fn spot_price_empty_asks() {
471        let mut state = create_test_bebop_state();
472        state.book.asks = Levels::default();
473
474        // Test WBTC/USDC with no asks - should use only best bid
475        let price = state
476            .spot_price(&wbtc(), &usdc())
477            .unwrap();
478        assert_eq!(price, 65000.0);
479    }
480
481    #[test]
482    fn spot_price_empty_bids() {
483        let mut state = create_test_bebop_state();
484        state.book.bids = Levels::default();
485        // Test WBTC/USDC with no bids - should use only best ask
486        let price = state
487            .spot_price(&wbtc(), &usdc())
488            .unwrap();
489        assert_eq!(price, 65100.0);
490    }
491
492    #[test]
493    fn spot_price_no_liquidity() {
494        let mut state = create_test_bebop_state();
495        state.book.bids = Levels::default();
496        state.book.asks = Levels::default();
497        // Test with no liquidity at all - should return error
498        let result = state.spot_price(&wbtc(), &usdc());
499        assert!(result.is_err());
500    }
501
502    #[test]
503    fn get_limits_sell_base_for_quote() {
504        let state = create_test_bebop_state();
505
506        // Test selling WBTC for USDC (should use bids)
507        let (wbtc_limit, usdc_limit) = state
508            .get_limits(wbtc().address, usdc().address)
509            .unwrap();
510
511        // Use bids: vec![(65000.0, 1.5), (64950.0, 2.0), (64900.0, 0.5)]
512
513        // Total WBTC available: 1.5 + 2.0 + 0.5 = 4.0 WBTC
514        let expected_wbtc_limit = BigUint::from(4u64) * BigUint::from(10u64).pow(8u32);
515
516        // Total USDC value: (65000*1.5) + (64950*2.0) + (64900*0.5) = 97500 + 129900 + 32450 =
517        // 259850
518        let expected_usdc_limit = BigUint::from(259850u64) * BigUint::from(10u64).pow(6u32);
519
520        assert_eq!(wbtc_limit, expected_wbtc_limit);
521        assert_eq!(usdc_limit, expected_usdc_limit);
522    }
523
524    #[test]
525    fn get_limits_buy_base_with_quote() {
526        let state = create_test_bebop_state();
527
528        // Test buying WBTC with USDC (should use asks)
529        let (usdc_limit, wbtc_limit) = state
530            .get_limits(usdc().address, wbtc().address)
531            .unwrap();
532
533        // Use asks: vec![(65100.0, 1.0), (65150.0, 2.5), (65200.0, 1.5)]
534
535        // Total USDC needed: (65100*1.0) + (65150*2.5) + (65200*1.5) = 65100 + 162875 + 97800 =
536        // 325775
537        let expected_usdc_limit = BigUint::from(325775u64) * BigUint::from(10u64).pow(6u32);
538
539        // Total WBTC available: 1.0 + 2.5 + 1.5 = 5.0 WBTC
540        let expected_wbtc_limit = BigUint::from(5u64) * BigUint::from(10u64).pow(8u32);
541
542        assert_eq!(usdc_limit, expected_usdc_limit);
543        assert_eq!(wbtc_limit, expected_wbtc_limit);
544    }
545
546    /// Bebop's book prices both directions, so what it cannot answer is a token that is not in
547    /// the pair — whichever of the three questions it is asked.
548    #[test]
549    fn rejects_tokens_outside_the_pair() {
550        let state = create_test_bebop_state();
551        let amount = BigUint::from_str("1000000000000000000").unwrap();
552        let results = [
553            state
554                .spot_price(&weth(), &usdc())
555                .map(|_| ()),
556            state
557                .get_amount_out(amount.clone(), &weth(), &usdc())
558                .map(|_| ()),
559            state
560                .get_amount_out(amount, &wbtc(), &weth())
561                .map(|_| ()),
562            state
563                .get_limits(weth().address, usdc().address)
564                .map(|_| ()),
565        ];
566
567        for result in results {
568            assert!(
569                matches!(&result, Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")),
570                "{result:?}"
571            );
572        }
573    }
574
575    /// A side the venue is not quoting has no depth to report and no swap to price.
576    #[test]
577    fn a_side_with_no_levels_has_nothing_to_offer() {
578        let mut state = create_test_bebop_state();
579        state.book.asks = Levels::default();
580
581        assert!(matches!(
582            state.get_amount_out(BigUint::from(2_000_000u64), &usdc(), &wbtc()),
583            Err(SimulationError::InvalidInput(_, None))
584        ));
585        assert!(matches!(
586            state.get_limits(usdc().address, wbtc().address),
587            Err(SimulationError::RecoverableError(_))
588        ));
589    }
590
591    #[test]
592    fn get_amount_out_walks_the_ladder_on_both_sides() {
593        // WETH/USDC
594        let price_data = BebopPriceData {
595            base: hex::decode("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(), // WETH
596            quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), // USDC
597            last_update_ts: 1234567890,
598            bids: vec![3000.0f32, 2.0f32, 2900.0f32, 2.5f32],
599            asks: vec![3100.0f32, 1.5f32, 3000.0f32, 3.0f32],
600        };
601
602        let weth = weth();
603        let usdc = usdc();
604        let state = BebopState {
605            base_token: weth.clone(),
606            quote_token: usdc.clone(),
607            book: BebopBook::try_from(price_data).unwrap(),
608            // The pair's quote token is USDC.
609            usd_per_quote_token: 1.0,
610            client: Some(empty_client()),
611        };
612
613        // swap 3 WETH -> USDC
614        let amount_out_result = state
615            .get_amount_out(BigUint::from_str("3_000000000000000000").unwrap(), &weth, &usdc)
616            .unwrap();
617
618        // 6000 from level 1 + 2900 from level 2 = 8900 USDC
619        assert_eq!(amount_out_result.amount, BigUint::from_str("8900_000_000").unwrap());
620
621        // swap 7000 USDC -> WETH
622        let amount_out_result = state
623            .get_amount_out(BigUint::from_str("7000_000_000").unwrap(), &usdc, &weth)
624            .unwrap();
625
626        // 1.5 from level 1 + 0.78333 from level 2 = 2.283333 WETH
627        assert_eq!(amount_out_result.amount, BigUint::from_str("2_283333333333333248").unwrap());
628    }
629
630    /// The venue refuses a swap of nothing, so simulating one must not report a fill.
631    #[test]
632    fn rejects_a_zero_amount() {
633        let state = create_test_bebop_state();
634
635        let result = state.get_amount_out(BigUint::ZERO, &wbtc(), &usdc());
636
637        assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
638    }
639}