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