use std::{collections::HashSet, future::Future, sync::Arc};
use tokio::time::Duration;
use tycho_common::Bytes;
use crate::{
book::{BookFeedConfig, BookSnapshot, ReceivedAt},
rfq::{
constants::DEFAULT_QUOTE_TIMEOUT,
protocols::bebop::{
client::{BebopClient, QuoteOrigin},
models::BebopSupportedChain,
source::BebopBookSource,
FALLBACK_PROTOCOL_SYSTEM, PROTOCOL_SYSTEM,
},
},
snapshot_feed::{
errors::FeedError,
ws::{default_ws_feed_config, run_ws_feed, WsFeedConfig},
Publisher, SnapshotFeed,
},
};
#[derive(Clone, Debug)]
pub struct BebopFeed {
feed_config: WsFeedConfig,
source: BebopBookSource,
}
pub struct BebopFeedBuilder {
protocol_system: &'static str,
book_config: BookFeedConfig,
usd_quote_tokens: Arc<HashSet<Bytes>>,
ws_key: String,
quote_timeout: Duration,
origin: QuoteOrigin,
feed_config: WsFeedConfig,
all_pairs: bool,
}
impl BebopFeedBuilder {
pub fn new(
book_config: BookFeedConfig,
usd_quote_tokens: impl Into<Arc<HashSet<Bytes>>>,
ws_key: String,
) -> Self {
Self {
book_config,
usd_quote_tokens: usd_quote_tokens.into(),
ws_key,
quote_timeout: DEFAULT_QUOTE_TIMEOUT,
origin: QuoteOrigin::default(),
feed_config: Self::default_feed_config(),
protocol_system: PROTOCOL_SYSTEM,
all_pairs: false,
}
}
pub fn all_pairs(mut self) -> Self {
self.all_pairs = true;
self
}
pub fn quote_timeout(mut self, timeout: Duration) -> Self {
self.quote_timeout = timeout;
self
}
pub fn origin_address(mut self, origin_address: Bytes) -> Self {
self.origin.address = Some(origin_address);
self
}
pub fn origin_target(mut self, origin_target: Bytes) -> Self {
self.origin.target = Some(origin_target);
self
}
pub fn origin_source(mut self, origin_source: String) -> Self {
self.origin.source = Some(origin_source);
self
}
pub fn default_feed_config() -> WsFeedConfig {
default_ws_feed_config()
}
pub fn with_fallback_router(mut self) -> Self {
self.protocol_system = FALLBACK_PROTOCOL_SYSTEM;
self
}
pub fn feed_config(mut self, feed_config: WsFeedConfig) -> Self {
self.feed_config = feed_config;
self
}
pub fn build(self) -> Result<BebopFeed, FeedError> {
let chain =
BebopSupportedChain::try_from(self.book_config.chain).map_err(FeedError::Fatal)?;
Ok(BebopFeed {
feed_config: self.feed_config,
source: BebopBookSource {
protocol_system: self.protocol_system,
book_config: self.book_config,
usd_quote_tokens: self.usd_quote_tokens,
client: Arc::new(BebopClient::new(
chain,
self.ws_key,
self.quote_timeout,
self.origin,
)),
all_pairs: self.all_pairs,
},
})
}
}
impl SnapshotFeed for BebopFeed {
type Snapshot = BookSnapshot<ReceivedAt>;
type Error = FeedError;
fn run(
self,
publisher: Publisher<Self::Snapshot>,
) -> impl Future<Output = Result<(), FeedError>> + Send + 'static {
run_ws_feed(self.feed_config, publisher, self.source)
}
}
#[cfg(test)]
mod tests {
use std::{collections::HashMap, str::FromStr, time::Duration};
use dotenv::dotenv;
use num_bigint::BigUint;
use tokio::time::timeout;
use tycho_common::models::{protocol::GetAmountOutParams, Chain};
use super::*;
use crate::{
book::{test_token_map, Book},
snapshot_feed::SnapshotFeed,
};
const SWAP_SINGLE_SELECTOR: [u8; 4] = [0x4d, 0xce, 0xbc, 0xba];
const SWAP_AGGREGATE_SELECTOR: [u8; 4] = [0xa2, 0xf7, 0x48, 0x93];
const ROUTER_SWAP_SELECTOR: [u8; 4] = [0x95, 0x86, 0xd0, 0xe8];
async fn next_books(
rx: &mut tokio::sync::watch::Receiver<Option<BookSnapshot<ReceivedAt>>>,
) -> Arc<HashMap<String, Book>> {
loop {
rx.changed().await.expect("feed ended");
if let Some(snapshot) = &*rx.borrow_and_update() {
return Arc::clone(&snapshot.books);
}
}
}
#[tokio::test]
#[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
async fn bebop_websocket_connection() {
let wbtc = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
let weth = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
dotenv().expect("Missing .env file");
let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");
let quote_tokens = HashSet::from([
Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap(), Bytes::from_str("0xdac17f958d2ee523a2206206994597c13d831ec7").unwrap(), ]);
let book_config = BookFeedConfig {
chain: Chain::Ethereum,
tokens: Arc::new(test_token_map(&[(&weth, "WETH", 18), (&wbtc, "WBTC", 8)])),
min_tvl_usd: 10.0,
};
let feed = BebopFeedBuilder::new(book_config, quote_tokens, key)
.quote_timeout(Duration::from_secs(30))
.build()
.unwrap();
let (publisher, mut rx) = Publisher::channel();
let _feed = tokio::spawn(feed.run(publisher));
let pairs = timeout(Duration::from_secs(10), next_books(&mut rx))
.await
.expect("no book received within 10 seconds");
assert!(!pairs.is_empty());
println!("Received {} components in this book", pairs.len());
for pair in pairs.values() {
assert_eq!(pair.component.protocol_system, "rfq:bebop");
assert_eq!(pair.component.protocol_type_name, "bebop_pool");
assert_eq!(pair.component.chain, Chain::Ethereum);
let [base, quote] = pair.component.tokens.as_slice() else {
panic!("expected exactly two tokens")
};
assert!(
pair.state
.spot_price(base, quote)
.unwrap() >
0.0
);
}
}
#[tokio::test]
#[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
async fn bebop_quote_single_order() {
let token_in = Bytes::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2").unwrap();
let token_out = Bytes::from_str("0x2260FAC5E5542a773Aa44fBCfeDf7C193bc2C599").unwrap();
dotenv().expect("Missing .env file");
let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");
let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();
let book_config = BookFeedConfig {
chain: Chain::Ethereum,
tokens: Arc::new(test_token_map(&[
(&token_in, "TOKEN_IN", 18),
(&token_out, "TOKEN_OUT", 18),
])),
min_tvl_usd: 10.0,
};
let feed = BebopFeedBuilder::new(book_config, HashSet::new(), key)
.quote_timeout(Duration::from_secs(30))
.origin_address(Bytes::from_str("0x00000000219ab540356cBB839Cbe05303d7705Fa").unwrap())
.origin_target(router.clone())
.origin_source("tycho-test".to_string())
.build()
.unwrap();
let params = GetAmountOutParams {
amount_in: BigUint::from(1_000000000000000000u64),
token_in: token_in.clone(),
token_out: token_out.clone(),
sender: router.clone(),
receiver: router,
origin: None,
};
let quote = feed
.source
.client
.request_binding_quote(¶ms)
.await
.unwrap();
assert_eq!(quote.base_token, token_in);
assert_eq!(quote.quote_token, token_out);
assert_eq!(quote.amount_in, BigUint::from(1_000000000000000000u64));
assert!(quote.amount_out > BigUint::from(1_000_000u64));
let selector = "e
.quote_attributes
.get("calldata")
.unwrap()[..4];
if selector == SWAP_SINGLE_SELECTOR {
let partial_fill_offset_slice = quote
.quote_attributes
.get("partial_fill_offset")
.unwrap()
.as_ref();
let mut partial_fill_offset_array = [0u8; 8];
partial_fill_offset_array.copy_from_slice(partial_fill_offset_slice);
assert_eq!(u64::from_be_bytes(partial_fill_offset_array), 12);
} else {
assert_eq!(selector, ROUTER_SWAP_SELECTOR);
}
}
#[tokio::test]
#[ignore = "hits Bebop's live API; requires BEBOP_KEY"]
async fn bebop_quote_aggregate_order() {
let token_in = Bytes::from_str("0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48").unwrap();
let token_out = Bytes::from_str("0xfAbA6f8e4a5E8Ab82F62fe7C39859FA577269BE3").unwrap();
dotenv().expect("Missing .env file");
let key = std::env::var("BEBOP_KEY").expect("BEBOP_KEY not set");
let router = Bytes::from_str("0xfD0b31d2E955fA55e3fa641Fe90e08b677188d35").unwrap();
let book_config = BookFeedConfig {
chain: Chain::Ethereum,
tokens: Arc::new(test_token_map(&[
(&token_in, "TOKEN_IN", 18),
(&token_out, "TOKEN_OUT", 18),
])),
min_tvl_usd: 10.0,
};
let feed = BebopFeedBuilder::new(book_config, HashSet::new(), key)
.quote_timeout(Duration::from_secs(30))
.origin_address(Bytes::from_str("0x00000000219ab540356cBB839Cbe05303d7705Fa").unwrap())
.origin_target(router.clone())
.origin_source("tycho-test".to_string())
.build()
.unwrap();
let amount_in = BigUint::from_str("20_000_000_000").unwrap(); let params = GetAmountOutParams {
amount_in: amount_in.clone(),
token_in: token_in.clone(),
token_out: token_out.clone(),
sender: router.clone(),
receiver: router,
origin: None,
};
let quote = feed
.source
.client
.request_binding_quote(¶ms)
.await
.unwrap();
assert_eq!(quote.base_token, token_in);
assert_eq!(quote.quote_token, token_out);
assert_eq!(quote.amount_in, amount_in);
assert!(quote.amount_out > BigUint::from_str("18000000000000000000000").unwrap());
let selector = "e
.quote_attributes
.get("calldata")
.unwrap()[..4];
if selector == SWAP_AGGREGATE_SELECTOR {
let partial_fill_offset_slice = quote
.quote_attributes
.get("partial_fill_offset")
.unwrap()
.as_ref();
let mut partial_fill_offset_array = [0u8; 8];
partial_fill_offset_array.copy_from_slice(partial_fill_offset_slice);
assert_eq!(u64::from_be_bytes(partial_fill_offset_array), 2);
} else {
assert_eq!(selector, ROUTER_SWAP_SELECTOR);
}
}
#[test]
fn building_for_a_chain_bebop_does_not_serve_is_fatal() {
let config = BookFeedConfig {
chain: Chain::ZkSync,
tokens: Arc::new(HashMap::new()),
min_tvl_usd: 0.0,
};
let error = BebopFeedBuilder::new(config, HashSet::new(), "key".to_string())
.build()
.unwrap_err();
assert!(error.is_fatal(), "{error}");
}
}