use std::{any::Any, borrow::Cow, collections::HashMap, sync::Arc};
use async_trait::async_trait;
use num_bigint::BigUint;
use serde::{Deserialize, Serialize};
use tycho_common::{
dto::ProtocolStateDelta,
models::{protocol::GetAmountOutParams, token::Token},
simulation::{
errors::{SimulationError, TransitionError},
indicatively_priced::{IndicativelyPriced, SignedQuote},
protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
},
Bytes,
};
use crate::{
book::{
all_pairs::{all_pairs_state, PricesAfterFill, RefusesQuote, SignedByVenue},
component::PairState,
levels::Levels,
sim::{self, SwapDirection},
},
rfq::protocols::bebop::{client::BebopClient, models::BebopBook},
};
const BEBOP_SWAP_GAS: u64 = 70_000;
const MIN_TRADE_USD: f64 = 1.0;
#[derive(Clone, derive_more::Debug, Serialize, Deserialize)]
pub struct BebopState {
pub(super) base_token: Token,
pub(super) quote_token: Token,
#[debug(skip)]
pub(super) book: BebopBook,
pub(super) usd_per_quote_token: f64,
#[serde(skip)]
#[debug(skip)]
client: Option<Arc<BebopClient>>,
}
impl BebopState {
pub(super) fn new(
base_token: Token,
quote_token: Token,
book: BebopBook,
usd_per_quote_token: f64,
client: Arc<BebopClient>,
) -> Self {
BebopState { base_token, quote_token, book, usd_per_quote_token, client: Some(client) }
}
fn ladder(&self, direction: SwapDirection) -> Cow<'_, Levels> {
match direction {
SwapDirection::BaseToQuote => Cow::Borrowed(&self.book.bids),
SwapDirection::QuoteToBase => Cow::Owned(self.book.asks.invert()),
}
}
}
impl PairState for BebopState {
fn base_token(&self) -> &Token {
&self.base_token
}
fn quote_token(&self) -> &Token {
&self.quote_token
}
fn directions(&self) -> Vec<(Bytes, Bytes)> {
sim::directions(
&self.base_token,
&self.quote_token,
!self.book.bids.is_empty(),
!self.book.asks.is_empty(),
)
}
}
impl PricesAfterFill for BebopState {
fn marginal_price(
&self,
token_in: &Bytes,
token_out: &Bytes,
filled: &BigUint,
) -> Result<f64, SimulationError> {
let direction =
SwapDirection::require(&self.base_token, &self.quote_token, token_in, token_out)?;
let (sell_decimals, _) = direction.decimals(&self.base_token, &self.quote_token);
sim::marginal_price(&self.ladder(direction), filled, sell_decimals)
}
}
#[typetag::serde]
impl ProtocolSim for BebopState {
fn fee(&self) -> f64 {
0.0
}
fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&base.address,
"e.address,
)?;
let best_bid = self
.book
.bids
.first()
.map(|level| level.price);
let best_ask = self
.book
.asks
.first()
.map(|level| level.price);
let average_price = match (best_bid, best_ask) {
(Some(best_bid), Some(best_ask)) => (best_bid + best_ask) / 2.0,
(Some(best_bid), None) => best_bid,
(None, Some(best_ask)) => best_ask,
(None, None) => {
return Err(SimulationError::RecoverableError("No liquidity available".to_string()))
}
};
match direction {
SwapDirection::BaseToQuote => Ok(average_price),
SwapDirection::QuoteToBase => Ok(1.0 / average_price),
}
}
fn get_amount_out(
&self,
amount_in: BigUint,
token_in: &Token,
token_out: &Token,
) -> Result<GetAmountOutResult, SimulationError> {
sim::require_positive_amount(&amount_in)?;
let direction = SwapDirection::require(
&self.base_token,
&self.quote_token,
&token_in.address,
&token_out.address,
)?;
let ladder = self.ladder(direction);
let amount_in = sim::to_human(&amount_in, token_in.decimals);
let fill = ladder.fill(amount_in);
let quote_amount = match direction {
SwapDirection::QuoteToBase => amount_in,
SwapDirection::BaseToQuote => fill.amount_out,
};
let worth_usd = quote_amount * self.usd_per_quote_token;
if fill.remaining_in < amount_in && worth_usd < MIN_TRADE_USD {
return Err(SimulationError::RecoverableError(format!(
"Trade is worth {worth_usd} USD, below the {MIN_TRADE_USD} USD Bebop quotes"
)));
}
sim::fill_result(fill, amount_in, token_out.decimals, BEBOP_SWAP_GAS, self)
}
fn get_limits(
&self,
sell_token: Bytes,
buy_token: Bytes,
) -> Result<(BigUint, BigUint), SimulationError> {
let direction =
SwapDirection::require(&self.base_token, &self.quote_token, &sell_token, &buy_token)?;
let ladder = self.ladder(direction);
if ladder.is_empty() {
return Err(SimulationError::RecoverableError("No liquidity".into()));
}
let (sell_decimals, buy_decimals) = direction.decimals(&self.base_token, &self.quote_token);
sim::limits(&ladder, sell_decimals, buy_decimals)
}
fn delta_transition(
&mut self,
_delta: ProtocolStateDelta,
_tokens: &HashMap<Bytes, Token>,
_balances: &Balances,
) -> Result<(), TransitionError> {
Err(TransitionError::DecodeError("Not implemented".into()))
}
fn clone_box(&self) -> Box<dyn ProtocolSim> {
Box::new(self.clone())
}
fn as_any(&self) -> &dyn Any {
self
}
fn as_any_mut(&mut self) -> &mut dyn Any {
self
}
fn eq(&self, other: &dyn ProtocolSim) -> bool {
if let Some(other_state) = other
.as_any()
.downcast_ref::<BebopState>()
{
self.base_token == other_state.base_token &&
self.quote_token == other_state.quote_token &&
self.book == other_state.book
} else {
false
}
}
fn as_indicatively_priced(&self) -> Result<&dyn IndicativelyPriced, SimulationError> {
Ok(self)
}
}
#[async_trait]
impl IndicativelyPriced for BebopState {
async fn request_signed_quote(
&self,
params: GetAmountOutParams,
) -> Result<SignedQuote, SimulationError> {
Ok(sim::quoting_client(self.client.as_ref(), "Bebop")?
.request_binding_quote(¶ms)
.await?)
}
}
all_pairs_state! {
BebopAllPairsState(BebopState, SignedByVenue);
}
impl RefusesQuote for BebopAllPairsState {}
#[cfg(test)]
mod tests {
use std::str::FromStr;
use rstest::rstest;
use tokio::time::Duration;
use tycho_common::models::Chain;
use super::*;
use crate::rfq::protocols::bebop::{
client::QuoteOrigin,
models::{BebopPriceData, BebopSupportedChain},
};
fn wbtc() -> Token {
Token::new(
&hex::decode("2260fac5e5542a773aa44fbcfedf7c193bc2c599")
.unwrap()
.into(),
"WBTC",
8,
0,
&[Some(10_000)],
Chain::Ethereum,
100,
)
}
fn usdc() -> Token {
Token::new(
&hex::decode("a0b86991c6218a76c1d19d4a2e9eb0ce3606eb48")
.unwrap()
.into(),
"USDC",
6,
0,
&[Some(10_000)],
Chain::Ethereum,
100,
)
}
fn weth() -> Token {
Token::new(
&Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(),
"WETH",
18,
0,
&[],
Default::default(),
100,
)
}
fn empty_client() -> Arc<BebopClient> {
Arc::new(BebopClient::new(
BebopSupportedChain::Ethereum,
String::new(),
Duration::from_secs(30),
QuoteOrigin::default(),
))
}
#[rstest]
#[case::half_a_dollar_of_usdc("500000", true, false)]
#[case::two_dollars_of_usdc("2000000", true, true)]
#[case::sixty_five_cents_of_wbtc("1000", false, false)]
#[case::six_dollars_of_wbtc("10000", false, true)]
fn a_trade_worth_less_than_a_dollar_is_refused(
#[case] amount_in: &str,
#[case] sell_quote: bool,
#[case] quotable: bool,
) {
let state = create_test_bebop_state();
let (token_in, token_out) = if sell_quote { (usdc(), wbtc()) } else { (wbtc(), usdc()) };
let result =
state.get_amount_out(BigUint::from_str(amount_in).unwrap(), &token_in, &token_out);
assert_eq!(result.is_ok(), quotable, "{result:?}");
if !quotable {
let error = result.unwrap_err().to_string();
assert!(error.contains("below the 1 USD Bebop quotes"), "{error}");
}
}
#[rstest]
#[case::six_dollars_of_wbtc("10000")]
#[case::sixty_five_cents_of_wbtc("1000")]
fn selling_into_a_side_with_no_bids_reports_no_liquidity(#[case] amount_in: &str) {
let mut state = create_test_bebop_state();
state.book.bids = Levels::default();
let error = state
.get_amount_out(BigUint::from_str(amount_in).unwrap(), &wbtc(), &usdc())
.unwrap_err();
assert!(
matches!(&error, SimulationError::InvalidInput(message, None)
if message.contains("no liquidity on this side")),
"{error:?}"
);
}
#[tokio::test]
async fn a_replayed_state_prices_but_cannot_quote() {
let state = create_test_bebop_state();
let replayed: BebopState =
serde_json::from_str(&serde_json::to_string(&state).unwrap()).unwrap();
let priced = replayed.get_amount_out(BigUint::from(10_000u64), &wbtc(), &usdc());
let quoted = replayed
.request_signed_quote(GetAmountOutParams {
amount_in: BigUint::from(10_000u64),
token_in: wbtc().address,
token_out: usdc().address,
sender: Bytes::zero(20),
receiver: Bytes::zero(20),
origin: None,
})
.await;
assert!(priced.is_ok(), "{priced:?}");
assert!(
matches!("ed, Err(SimulationError::FatalError(message))
if message.contains("carries no client")),
"{quoted:?}"
);
}
fn create_test_bebop_state() -> BebopState {
let price_data = BebopPriceData {
base: hex::decode("2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), last_update_ts: 1703097600,
bids: vec![65000.0f32, 1.5f32, 64950.0f32, 2.0f32, 64900.0f32, 0.5f32],
asks: vec![65100.0f32, 1.0f32, 65150.0f32, 2.5f32, 65200.0f32, 1.5f32],
};
BebopState {
base_token: wbtc(),
quote_token: usdc(),
book: BebopBook::try_from(price_data).unwrap(),
usd_per_quote_token: 1.0,
client: Some(empty_client()),
}
}
#[rstest]
#[case::selling_base_in_the_first_level(true, 100_000_000, Some(65000.0))]
#[case::selling_base_on_the_first_boundary(true, 150_000_000, Some(64950.0))]
#[case::selling_base_past_the_depth(true, 400_000_000, None)]
#[case::selling_quote_before_any_fill(false, 0, Some(1.0 / 65100.0))]
fn the_price_after_a_fill_is_the_level_where_it_stopped(
#[case] sell_base: bool,
#[case] filled: u64,
#[case] expected: Option<f64>,
) {
let state = create_test_bebop_state();
let (token_in, token_out) = if sell_base { (wbtc(), usdc()) } else { (usdc(), wbtc()) };
let price =
state.marginal_price(&token_in.address, &token_out.address, &BigUint::from(filled));
match (price, expected) {
(Ok(price), Some(expected)) => assert_eq!(price, expected),
(Err(SimulationError::RecoverableError(message)), None) => {
assert_eq!(message, "No liquidity")
}
(price, _) => panic!("expected {expected:?}, got {price:?}"),
}
}
#[test]
fn spot_price_matching_base_and_quote() {
let state = create_test_bebop_state();
let price = state
.spot_price(&wbtc(), &usdc())
.unwrap();
assert_eq!(price, 65050.0);
}
#[test]
fn spot_price_inverted_base_and_quote() {
let state = create_test_bebop_state();
let price = state
.spot_price(&usdc(), &wbtc())
.unwrap();
let expected = 0.00001537279;
assert!((price - expected).abs() < 1e-10);
}
#[test]
fn spot_price_empty_asks() {
let mut state = create_test_bebop_state();
state.book.asks = Levels::default();
let price = state
.spot_price(&wbtc(), &usdc())
.unwrap();
assert_eq!(price, 65000.0);
}
#[test]
fn spot_price_empty_bids() {
let mut state = create_test_bebop_state();
state.book.bids = Levels::default();
let price = state
.spot_price(&wbtc(), &usdc())
.unwrap();
assert_eq!(price, 65100.0);
}
#[test]
fn spot_price_no_liquidity() {
let mut state = create_test_bebop_state();
state.book.bids = Levels::default();
state.book.asks = Levels::default();
let result = state.spot_price(&wbtc(), &usdc());
assert!(result.is_err());
}
#[test]
fn get_limits_sell_base_for_quote() {
let state = create_test_bebop_state();
let (wbtc_limit, usdc_limit) = state
.get_limits(wbtc().address, usdc().address)
.unwrap();
let expected_wbtc_limit = BigUint::from(4u64) * BigUint::from(10u64).pow(8u32);
let expected_usdc_limit = BigUint::from(259850u64) * BigUint::from(10u64).pow(6u32);
assert_eq!(wbtc_limit, expected_wbtc_limit);
assert_eq!(usdc_limit, expected_usdc_limit);
}
#[test]
fn get_limits_buy_base_with_quote() {
let state = create_test_bebop_state();
let (usdc_limit, wbtc_limit) = state
.get_limits(usdc().address, wbtc().address)
.unwrap();
let expected_usdc_limit = BigUint::from(325775u64) * BigUint::from(10u64).pow(6u32);
let expected_wbtc_limit = BigUint::from(5u64) * BigUint::from(10u64).pow(8u32);
assert_eq!(usdc_limit, expected_usdc_limit);
assert_eq!(wbtc_limit, expected_wbtc_limit);
}
#[test]
fn rejects_tokens_outside_the_pair() {
let state = create_test_bebop_state();
let amount = BigUint::from_str("1000000000000000000").unwrap();
let results = [
state
.spot_price(&weth(), &usdc())
.map(|_| ()),
state
.get_amount_out(amount.clone(), &weth(), &usdc())
.map(|_| ()),
state
.get_amount_out(amount, &wbtc(), &weth())
.map(|_| ()),
state
.get_limits(weth().address, usdc().address)
.map(|_| ()),
];
for result in results {
assert!(
matches!(&result, Err(SimulationError::InvalidInput(msg, None)) if msg.contains("Invalid token addresses")),
"{result:?}"
);
}
}
#[test]
fn a_side_with_no_levels_has_nothing_to_offer() {
let mut state = create_test_bebop_state();
state.book.asks = Levels::default();
assert!(matches!(
state.get_amount_out(BigUint::from(2_000_000u64), &usdc(), &wbtc()),
Err(SimulationError::InvalidInput(_, None))
));
assert!(matches!(
state.get_limits(usdc().address, wbtc().address),
Err(SimulationError::RecoverableError(_))
));
}
#[test]
fn get_amount_out_walks_the_ladder_on_both_sides() {
let price_data = BebopPriceData {
base: hex::decode("C02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap(), quote: hex::decode("A0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48").unwrap(), last_update_ts: 1234567890,
bids: vec![3000.0f32, 2.0f32, 2900.0f32, 2.5f32],
asks: vec![3100.0f32, 1.5f32, 3000.0f32, 3.0f32],
};
let weth = weth();
let usdc = usdc();
let state = BebopState {
base_token: weth.clone(),
quote_token: usdc.clone(),
book: BebopBook::try_from(price_data).unwrap(),
usd_per_quote_token: 1.0,
client: Some(empty_client()),
};
let amount_out_result = state
.get_amount_out(BigUint::from_str("3_000000000000000000").unwrap(), &weth, &usdc)
.unwrap();
assert_eq!(amount_out_result.amount, BigUint::from_str("8900_000_000").unwrap());
let amount_out_result = state
.get_amount_out(BigUint::from_str("7000_000_000").unwrap(), &usdc, &weth)
.unwrap();
assert_eq!(amount_out_result.amount, BigUint::from_str("2_283333333333333248").unwrap());
}
#[test]
fn rejects_a_zero_amount() {
let state = create_test_bebop_state();
let result = state.get_amount_out(BigUint::ZERO, &wbtc(), &usdc());
assert!(matches!(result, Err(SimulationError::InvalidInput(_, None))), "{result:?}");
}
}