use std::{
collections::{hash_map::Entry, HashMap},
sync::Arc,
};
use chrono::{DateTime, Utc};
use tracing::{debug, warn};
use tycho_common::{
models::{token::Token, Chain},
simulation::protocol_sim::ProtocolSim,
Bytes,
};
use crate::{
protocol::models::ProtocolComponent,
snapshot_feed::{
errors::FeedError, SnapshotFeedEvent, SnapshotFeedOutcome, SnapshotFeedStream,
SnapshotFeedStreams, SnapshotFeedWatch,
},
};
pub mod all_pairs;
pub(crate) mod component;
pub use component::{decode_swap_directions, SWAP_DIRECTIONS_ATTRIBUTE};
pub(crate) mod levels;
pub use levels::{Levels, PriceLevel};
pub mod quote_tokens;
pub(crate) mod sim;
pub(crate) mod tvl;
pub(crate) mod wire;
#[derive(Clone, Debug)]
pub struct Book {
pub component: ProtocolComponent,
pub state: Arc<dyn ProtocolSim>,
pub updated_at: Option<DateTime<Utc>>,
}
#[derive(Debug, Default, derive_more::Deref)]
pub(crate) struct Books(HashMap<String, Book>);
impl Books {
pub fn new() -> Self {
Books::default()
}
pub fn insert(&mut self, book: Book) {
match self
.0
.entry(book.component.id.to_string())
{
Entry::Occupied(mut taken) => {
warn!(
component = %taken.key(),
"two books price one component, keeping the last"
);
taken.insert(book);
}
Entry::Vacant(free) => {
free.insert(book);
}
}
}
pub fn into_map(self) -> HashMap<String, Book> {
self.0
}
}
impl Extend<Book> for Books {
fn extend<I: IntoIterator<Item = Book>>(&mut self, books: I) {
for book in books {
self.insert(book);
}
}
}
#[derive(Clone, Debug)]
pub struct BookSnapshot<A> {
pub anchor: A,
pub books: Arc<HashMap<String, Book>>,
}
impl BookSnapshot<ReceivedAt> {
pub(crate) fn received_now(books: Books) -> Self {
BookSnapshot { anchor: ReceivedAt(Utc::now()), books: Arc::new(books.0) }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ReceivedAt(pub DateTime<Utc>);
#[derive(Clone, derive_more::Debug)]
pub struct BookFeedConfig {
pub chain: Chain,
#[debug("{} tokens", tokens.len())]
pub tokens: Arc<HashMap<Bytes, Token>>,
pub min_tvl_usd: f64,
}
impl BookFeedConfig {
pub(crate) fn pair_tokens(&self, a: &Bytes, b: &Bytes) -> Option<(&Token, &Token)> {
Some((self.tokens.get(a)?, self.tokens.get(b)?))
}
pub(crate) fn clears_min_tvl(&self, tvl_usd: f64, component_id: &Bytes) -> bool {
let clears = tvl_usd >= self.min_tvl_usd;
if !clears {
debug!(
book = %component_id,
tvl_usd,
min_tvl_usd = self.min_tvl_usd,
"filtering out book below the TVL floor"
);
}
clears
}
}
pub(crate) fn chain_id(chain: Chain) -> Result<u64, FeedError> {
chain
.try_id()
.map_err(|error| FeedError::Fatal(format!("no chain id for {chain}: {error}")))
}
pub type BookFeedStreams<A = ReceivedAt> = SnapshotFeedStreams<BookSnapshot<A>, FeedError>;
pub type BookFeedStream<A = ReceivedAt> = SnapshotFeedStream<BookSnapshot<A>, FeedError>;
pub type BookFeedEvent<A = ReceivedAt> = SnapshotFeedEvent<BookSnapshot<A>, FeedError>;
pub type BookFeedWatch<A = ReceivedAt> = SnapshotFeedWatch<BookSnapshot<A>, FeedError>;
pub type BookFeedOutcome = SnapshotFeedOutcome<FeedError>;
#[cfg(test)]
pub(crate) fn test_token_map(entries: &[(&Bytes, &str, u32)]) -> HashMap<Bytes, Token> {
entries
.iter()
.map(|(address, symbol, decimals)| {
(
(*address).clone(),
Token::new(address, symbol, *decimals, 0, &[Some(10_000)], Chain::Ethereum, 100),
)
})
.collect()
}
#[cfg(test)]
pub(crate) fn chain_without_id() -> Chain {
serde_json::from_str(r#"{"custom":"unregistered"}"#).unwrap()
}
#[cfg(test)]
pub(crate) fn assert_same_books(actual: &HashMap<String, Book>, expected: &HashMap<String, Book>) {
let mut actual_ids: Vec<_> = actual.keys().collect();
let mut expected_ids: Vec<_> = expected.keys().collect();
actual_ids.sort();
expected_ids.sort();
assert_eq!(actual_ids, expected_ids);
for (id, book) in actual {
let other = &expected[id];
assert_eq!(book.component, other.component, "{id}");
assert_eq!(book.updated_at, other.updated_at, "{id}");
assert!(book.state.eq(&*other.state), "{id}: states differ");
}
}
#[cfg(test)]
mod tests {
use tycho_common::models::Chain;
use super::*;
use crate::{book::component::pair_component, evm::decoder::MockProtocolSim};
fn book(base: &Bytes, quote: &Bytes) -> Book {
let token =
|address: &Bytes| Token::new(address, "T", 18, 0, &[Some(0)], Chain::Ethereum, 100);
Book {
component: pair_component(
component::pair_component_id("book:venue", base, quote),
"book:venue",
"venue_pool",
Chain::Ethereum,
token(base),
token(quote),
),
state: Arc::new(MockProtocolSim::new()),
updated_at: None,
}
}
#[test]
fn a_book_is_kept_under_its_own_component() {
let weth = Bytes::from(vec![0x11; 20]);
let usdc = Bytes::from(vec![0x22; 20]);
let mut books = Books::new();
books.insert(book(&weth, &usdc));
books.insert(book(&usdc, &weth));
books.insert(book(&weth, &usdc));
assert_eq!(books.len(), 2);
let ids: Vec<_> = books.keys().cloned().collect();
assert!(
ids.contains(&component::pair_component_id("book:venue", &weth, &usdc).to_string()),
"{ids:?}"
);
}
}