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, 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 = 70_000;
29
30const 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 pub(super) usd_per_quote_token: f64,
46 #[serde(skip)]
47 #[debug(skip)]
48 client: Option<Arc<BebopClient>>,
49}
50
51impl BebopState {
52 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 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
92#[typetag::serde]
93impl ProtocolSim for BebopState {
94 fn fee(&self) -> f64 {
95 0.0
96 }
97
98 fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
99 let direction = SwapDirection::require(
100 &self.base_token,
101 &self.quote_token,
102 &base.address,
103 "e.address,
104 )?;
105 let best_bid = self
108 .book
109 .bids
110 .first()
111 .map(|level| level.price);
112 let best_ask = self
113 .book
114 .asks
115 .first()
116 .map(|level| level.price);
117 let average_price = match (best_bid, best_ask) {
119 (Some(best_bid), Some(best_ask)) => (best_bid + best_ask) / 2.0,
120 (Some(best_bid), None) => best_bid,
121 (None, Some(best_ask)) => best_ask,
122 (None, None) => {
123 return Err(SimulationError::RecoverableError("No liquidity available".to_string()))
124 }
125 };
126 match direction {
127 SwapDirection::BaseToQuote => Ok(average_price),
128 SwapDirection::QuoteToBase => Ok(1.0 / average_price),
129 }
130 }
131
132 fn get_amount_out(
133 &self,
134 amount_in: BigUint,
135 token_in: &Token,
136 token_out: &Token,
137 ) -> Result<GetAmountOutResult, SimulationError> {
138 sim::require_positive_amount(&amount_in)?;
141
142 let direction = SwapDirection::require(
143 &self.base_token,
144 &self.quote_token,
145 &token_in.address,
146 &token_out.address,
147 )?;
148 let ladder = self.ladder(direction);
149 let amount_in = sim::to_human(&amount_in, token_in.decimals);
150 let fill = ladder.fill(amount_in);
151 let quote_amount = match direction {
157 SwapDirection::QuoteToBase => amount_in,
158 SwapDirection::BaseToQuote => fill.amount_out,
159 };
160 let worth_usd = quote_amount * self.usd_per_quote_token;
161 if fill.remaining_in < amount_in && worth_usd < MIN_TRADE_USD {
162 return Err(SimulationError::RecoverableError(format!(
163 "Trade is worth {worth_usd} USD, below the {MIN_TRADE_USD} USD Bebop quotes"
164 )));
165 }
166 sim::fill_result(fill, amount_in, token_out.decimals, BEBOP_SWAP_GAS, self)
168 }
169
170 fn get_limits(
171 &self,
172 sell_token: Bytes,
173 buy_token: Bytes,
174 ) -> Result<(BigUint, BigUint), SimulationError> {
175 let direction =
176 SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
177 let ladder = self.ladder(direction);
178 if ladder.is_empty() {
180 return Err(SimulationError::RecoverableError("No liquidity".into()));
181 }
182 let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
183 sim::limits(&ladder, sell_decimals, buy_decimals)
184 }
185
186 fn delta_transition(
187 &mut self,
188 _delta: ProtocolStateDelta,
189 _tokens: &HashMap<Bytes, Token>,
190 _balances: &Balances,
191 ) -> Result<(), TransitionError> {
192 Err(TransitionError::DecodeError("Not implemented".into()))
193 }
194
195 fn clone_box(&self) -> Box<dyn ProtocolSim> {
196 Box::new(self.clone())
197 }
198
199 fn as_any(&self) -> &dyn Any {
200 self
201 }
202
203 fn as_any_mut(&mut self) -> &mut dyn Any {
204 self
205 }
206
207 fn eq(&self, other: &dyn ProtocolSim) -> bool {
208 if let Some(other_state) = other
209 .as_any()
210 .downcast_ref::<BebopState>()
211 {
212 self.base_token == other_state.base_token &&
213 self.quote_token == other_state.quote_token &&
214 self.book == other_state.book
215 } else {
216 false
217 }
218 }
219
220 fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
221 Ok(self)
222 }
223}
224
225#[async_trait]
226impl IndicativelyPriced for BebopState {
227 async fn request_signed_quote(
228 &self,
229 params: GetAmountOutParams,
230 ) -> Result<SignedQuote, SimulationError> {
231 Ok(sim::quoting_client(self.client.as_ref(), "Bebop")?
232 .request_binding_quote(¶ms)
233 .await?)
234 }
235}
236
237all_pairs_state! {
238 BebopAllPairsState(BebopState, SignedByVenue);
244}
245
246impl RefusesQuote for BebopAllPairsState {}
247
248#[cfg(test)]
249mod tests {
250 use std::str::FromStr;
251
252 use rstest::rstest;
253 use tokio::time::Duration;
254 use tycho_common::models::Chain;
255
256 use super::*;
257 use crate::rfq::protocols::bebop::{
258 client::QuoteOrigin,
259 models::{BebopPriceData, BebopSupportedChain},
260 };
261
262 fn wbtc() -> Token {
263 Token::new(
264 &hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
265 .unwrap()
266 .into(),
267 "WBTC",
268 8,
269 0,
270 &[Some(10_000)],
271 Chain::Ethereum,
272 100,
273 )
274 }
275
276 fn usdc() -> Token {
277 Token::new(
278 &hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
279 .unwrap()
280 .into(),
281 "USDC",
282 6,
283 0,
284 &[Some(10_000)],
285 Chain::Ethereum,
286 100,
287 )
288 }
289
290 fn weth() -> Token {
291 Token::new(
292 &Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
293 "WETH",
294 18,
295 0,
296 &[],
297 Default::default(),
298 100,
299 )
300 }
301
302 fn empty_client() -> Arc<BebopClient> {
303 Arc::new(BebopClient::new(
304 BebopSupportedChain::Ethereum,
305 String::new(),
306 Duration::from_secs(30),
307 QuoteOrigin::default(),
308 ))
309 }
310
311 #[rstest]
315 #[case::half_a_dollar_of_usdc("500000", true, false)]
316 #[case::two_dollars_of_usdc("2000000", true, true)]
317 #[case::sixty_five_cents_of_wbtc("1000", false, false)]
318 #[case::six_dollars_of_wbtc("10000", false, true)]
319 fn a_trade_worth_less_than_a_dollar_is_refused(
320 #[case] amount_in: &str,
321 #[case] sell_quote: bool,
322 #[case] quotable: bool,
323 ) {
324 let state = create_test_bebop_state();
325 let (token_in, token_out) = if sell_quote { (usdc(), wbtc()) } else { (wbtc(), usdc()) };
326
327 let result =
328 state.get_amount_out(BigUint::from_str(amount_in).unwrap(), &token_in, &token_out);
329
330 assert_eq!(result.is_ok(), quotable, "{result:?}");
331 if !quotable {
332 let error = result.unwrap_err().to_string();
333 assert!(error.contains("below the 1 USD Bebop quotes"), "{error}");
334 }
335 }
336
337 #[rstest]
341 #[case::six_dollars_of_wbtc("10000")]
342 #[case::sixty_five_cents_of_wbtc("1000")]
343 fn selling_into_a_side_with_no_bids_reports_no_liquidity(#[case] amount_in: &str) {
344 let mut state = create_test_bebop_state();
345 state.book.bids = Levels::default();
346
347 let error = state
348 .get_amount_out(BigUint::from_str(amount_in).unwrap(), &wbtc(), &usdc())
349 .unwrap_err();
350
351 assert!(
352 matches!(&error, SimulationError::InvalidInput(message, None)
353 if message.contains("no liquidity on this side")),
354 "{error:?}"
355 );
356 }
357
358 #[tokio::test]
362 async fn a_replayed_state_prices_but_cannot_quote() {
363 let state = create_test_bebop_state();
364 let replayed: BebopState =
365 serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
366
367 let priced = replayed.get_amount_out(BigUint::from(10_000u64), &wbtc(), &usdc());
368 let quoted = replayed
369 .request_signed_quote(GetAmountOutParams {
370 amount_in: BigUint::from(10_000u64),
371 token_in: wbtc().address,
372 token_out: usdc().address,
373 sender: Bytes::zero(20),
374 receiver: Bytes::zero(20),
375 origin: None,
376 })
377 .await;
378
379 assert!(priced.is_ok(), "{priced:?}");
380 assert!(
381 matches!("ed, Err(SimulationError::FatalError(message))
382 if message.contains("carries no client")),
383 "{quoted:?}"
384 );
385 }
386
387 fn create_test_bebop_state() -> BebopState {
388 let price_data = BebopPriceData {
389 base: hex::decode("2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), last_update_ts: 1703097600,
392 bids: vec![65000.0f32, 1.5f32, 64950.0f32, 2.0f32, 64900.0f32, 0.5f32],
393 asks: vec![65100.0f32, 1.0f32, 65150.0f32, 2.5f32, 65200.0f32, 1.5f32],
394 };
395 BebopState {
396 base_token: wbtc(),
397 quote_token: usdc(),
398 book: BebopBook::try_from(price_data).unwrap(),
399 usd_per_quote_token: 1.0,
401 client: Some(empty_client()),
402 }
403 }
404
405 #[test]
406 fn spot_price_matching_base_and_quote() {
407 let state = create_test_bebop_state();
408
409 let price = state
411 .spot_price(&wbtc(), &usdc())
412 .unwrap();
413 assert_eq!(price, 65050.0);
414 }
415
416 #[test]
417 fn spot_price_inverted_base_and_quote() {
418 let state = create_test_bebop_state();
419
420 let price = state
422 .spot_price(&usdc(), &wbtc())
423 .unwrap();
424 let expected = 0.00001537279;
425 assert!((price - expected).abs() < 1e-10);
426 }
427
428 #[test]
429 fn spot_price_empty_asks() {
430 let mut state = create_test_bebop_state();
431 state.book.asks = Levels::default();
432
433 let price = state
435 .spot_price(&wbtc(), &usdc())
436 .unwrap();
437 assert_eq!(price, 65000.0);
438 }
439
440 #[test]
441 fn spot_price_empty_bids() {
442 let mut state = create_test_bebop_state();
443 state.book.bids = Levels::default();
444 let price = state
446 .spot_price(&wbtc(), &usdc())
447 .unwrap();
448 assert_eq!(price, 65100.0);
449 }
450
451 #[test]
452 fn spot_price_no_liquidity() {
453 let mut state = create_test_bebop_state();
454 state.book.bids = Levels::default();
455 state.book.asks = Levels::default();
456 let result = state.spot_price(&wbtc(), &usdc());
458 assert!(result.is_err());
459 }
460
461 #[test]
462 fn get_limits_sell_base_for_quote() {
463 let state = create_test_bebop_state();
464
465 let (wbtc_limit, usdc_limit) = state
467 .get_limits(wbtc().address.clone(), usdc().address.clone())
468 .unwrap();
469
470 let expected_wbtc_limit = BigUint::from(4u64) * BigUint::from(10u64).pow(8u32);
474
475 let expected_usdc_limit = BigUint::from(259850u64) * BigUint::from(10u64).pow(6u32);
478
479 assert_eq!(wbtc_limit, expected_wbtc_limit);
480 assert_eq!(usdc_limit, expected_usdc_limit);
481 }
482
483 #[test]
484 fn get_limits_buy_base_with_quote() {
485 let state = create_test_bebop_state();
486
487 let (usdc_limit, wbtc_limit) = state
489 .get_limits(usdc().address.clone(), wbtc().address.clone())
490 .unwrap();
491
492 let expected_usdc_limit = BigUint::from(325775u64) * BigUint::from(10u64).pow(6u32);
497
498 let expected_wbtc_limit = BigUint::from(5u64) * BigUint::from(10u64).pow(8u32);
500
501 assert_eq!(usdc_limit, expected_usdc_limit);
502 assert_eq!(wbtc_limit, expected_wbtc_limit);
503 }
504
505 #[test]
508 fn rejects_tokens_outside_the_pair() {
509 let state = create_test_bebop_state();
510 let amount = BigUint::from_str("1000000000000000000").unwrap();
511 let results = [
512 state
513 .spot_price(&weth(), &usdc())
514 .map(|_| ()),
515 state
516 .get_amount_out(amount.clone(), &weth(), &usdc())
517 .map(|_| ()),
518 state
519 .get_amount_out(amount, &wbtc(), &weth())
520 .map(|_| ()),
521 state
522 .get_limits(weth().address.clone(), usdc().address.clone())
523 .map(|_| ()),
524 ];
525
526 for result in results {
527 assert!(
528 matches!(&result, Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")),
529 "{result:?}"
530 );
531 }
532 }
533
534 #[test]
536 fn a_side_with_no_levels_has_nothing_to_offer() {
537 let mut state = create_test_bebop_state();
538 state.book.asks = Levels::default();
539
540 assert!(matches!(
541 state.get_amount_out(BigUint::from(2_000_000u64), &usdc(), &wbtc()),
542 Err(SimulationError::InvalidInput(_, None))
543 ));
544 assert!(matches!(
545 state.get_limits(usdc().address.clone(), wbtc().address.clone()),
546 Err(SimulationError::RecoverableError(_))
547 ));
548 }
549
550 #[test]
551 fn get_amount_out_walks_the_ladder_on_both_sides() {
552 let price_data = BebopPriceData {
554 base: hex::decode("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), last_update_ts: 1234567890,
557 bids: vec![3000.0f32, 2.0f32, 2900.0f32, 2.5f32],
558 asks: vec![3100.0f32, 1.5f32, 3000.0f32, 3.0f32],
559 };
560
561 let weth = weth();
562 let usdc = usdc();
563 let state = BebopState {
564 base_token: weth.clone(),
565 quote_token: usdc.clone(),
566 book: BebopBook::try_from(price_data).unwrap(),
567 usd_per_quote_token: 1.0,
569 client: Some(empty_client()),
570 };
571
572 let amount_out_result = state
574 .get_amount_out(BigUint::from_str("3_000000000000000000").unwrap(), &weth, &usdc)
575 .unwrap();
576
577 assert_eq!(amount_out_result.amount, BigUint::from_str("8900_000_000").unwrap());
579
580 let amount_out_result = state
582 .get_amount_out(BigUint::from_str("7000_000_000").unwrap(), &usdc, &weth)
583 .unwrap();
584
585 assert_eq!(amount_out_result.amount, BigUint::from_str("2_283333333333333248").unwrap());
587 }
588
589 #[test]
591 fn rejects_a_zero_amount() {
592 let state = create_test_bebop_state();
593
594 let result = state.get_amount_out(BigUint::ZERO, &wbtc(), &usdc());
595
596 assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
597 }
598}