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
27const BEBOP_SWAP_GAS: u64 = 285_000;
31
32const 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 pub(super) usd_per_quote_token: f64,
48 #[serde(skip)]
49 #[debug(skip)]
50 client: Option<Arc<BebopClient>>,
51}
52
53impl BebopState {
54 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 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 "e.address,
120 )?;
121 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 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 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 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 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 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(¶ms)
249 .await?)
250 }
251}
252
253all_pairs_state! {
254 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 #[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 #[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 #[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!("ed, 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(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), 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 usd_per_quote_token: 1.0,
417 client: Some(empty_client()),
418 }
419 }
420
421 #[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 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 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 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 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 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 let (wbtc_limit, usdc_limit) = state
510 .get_limits(wbtc().address, usdc().address)
511 .unwrap();
512
513 let expected_wbtc_limit = BigUint::from(4u64) * BigUint::from(10u64).pow(8u32);
517
518 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 let (usdc_limit, wbtc_limit) = state
532 .get_limits(usdc().address, wbtc().address)
533 .unwrap();
534
535 let expected_usdc_limit = BigUint::from(325775u64) * BigUint::from(10u64).pow(6u32);
540
541 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 #[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 #[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 let price_data = BebopPriceData {
597 base: hex::decode("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), 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 usd_per_quote_token: 1.0,
612 client: Some(empty_client()),
613 };
614
615 let amount_out_result = state
617 .get_amount_out(BigUint::from_str("3_000000000000000000").unwrap(), &weth, &usdc)
618 .unwrap();
619
620 assert_eq!(amount_out_result.amount, BigUint::from_str("8900_000_000").unwrap());
622
623 let amount_out_result = state
625 .get_amount_out(BigUint::from_str("7000_000_000").unwrap(), &usdc, &weth)
626 .unwrap();
627
628 assert_eq!(amount_out_result.amount, BigUint::from_str("2_283333333333333248").unwrap());
630 }
631
632 #[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}