use std::{
collections::{BTreeMap, HashMap},
future::Future,
net::SocketAddr,
str::FromStr,
sync::{
atomic::{AtomicUsize, Ordering},
Arc,
},
time::{Duration, SystemTime, UNIX_EPOCH},
};
use futures::{future::BoxFuture, SinkExt};
use num_bigint::BigUint;
use tokio::{
net::{TcpListener, TcpStream},
task::JoinHandle,
};
use tokio_tungstenite::{tungstenite::Message, WebSocketStream};
use tycho_common::{
models::{token::Token, Chain},
Bytes,
};
use super::{
config::PriceLevelStreamConfig,
overrides::{AccountOverride, PammSimulationOverrides},
titan::{
self, EntryRejection, TitanBook, TitanPriceLevelMessage, TitanQuoteStreamMessage,
VenueOverrides,
},
};
pub(super) const PAMM: &str = "0x5979458912f80b96d30d4220af8e2e4925a33320";
pub(super) const KIPSELI: &str = "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d";
pub(super) const KIPSELI_STREAMED: &str = "0xc9a956b5196dfe110debe8781857bc8b97d32091";
pub(super) const WBTC: &str = "0x2260fac5e5542a773aa44fbcfedf7c193bc2c599";
pub(super) const USDC: &str = "0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48";
pub(super) const WETH: &str = "0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2";
pub(super) const USDT: &str = "0xdac17f958d2ee523a2206206994597c13d831ec7";
pub(super) const CBBTC: &str = "0xcbb7c0000ab88b473b1f5afd9ef808440eed33bf";
pub(super) const NVDAX: &str = "0xc845b2894dbddd03858fd2d643b4ef725fe0849d";
pub(super) fn address(hex: &str) -> Bytes {
Bytes::from_str(hex).expect("hex address")
}
pub(super) fn symbol_address(symbol: &str) -> &'static str {
match symbol {
"WBTC" => WBTC,
"USDC" => USDC,
"WETH" => WETH,
"USDT" => USDT,
"cbBTC" => CBBTC,
"NVDAx" => NVDAX,
other => panic!("no test address for {other}"),
}
}
pub(super) fn token(address: &str, symbol: &str, decimals: u32) -> Token {
Token::new(
&Bytes::from_str(address).unwrap(),
symbol,
decimals,
0,
&[Some(10_000)],
Chain::Ethereum,
100,
)
}
pub(super) fn token_map(tokens: impl IntoIterator<Item = Token>) -> HashMap<Bytes, Token> {
tokens
.into_iter()
.map(|token| (token.address.clone(), token))
.collect()
}
pub(super) fn tokens() -> HashMap<Bytes, Token> {
token_map([token(WBTC, "WBTC", 8), token(USDC, "USDC", 6), token(WETH, "WETH", 18)])
}
pub(super) fn captured_tokens() -> HashMap<Bytes, Token> {
token_map([
token(WBTC, "WBTC", 8),
token(USDC, "USDC", 6),
token(WETH, "WETH", 18),
token(USDT, "USDT", 6),
token(CBBTC, "cbBTC", 8),
])
}
pub(super) type FakeConnection = WebSocketStream<TcpStream>;
pub(super) struct FakeTitan {
addr: SocketAddr,
pub(super) connections: Arc<AtomicUsize>,
accept_task: Option<JoinHandle<()>>,
}
impl FakeTitan {
pub(super) async fn spawn<H, Fut>(handler: H) -> Self
where
H: Fn(usize, FakeConnection) -> Fut + Send + Sync + 'static,
Fut: Future<Output = ()> + Send + 'static,
{
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let addr = listener
.local_addr()
.expect("local addr");
let connections = Arc::new(AtomicUsize::new(0));
let counter = connections.clone();
let handler: Arc<dyn Fn(usize, FakeConnection) -> BoxFuture<'static, ()> + Send + Sync> =
Arc::new(move |index, socket| Box::pin(handler(index, socket)));
let accept_task = tokio::spawn(async move {
loop {
let Ok((socket, _)) = listener.accept().await else {
return;
};
let index = counter.fetch_add(1, Ordering::SeqCst);
let handler = handler.clone();
tokio::spawn(async move {
let Ok(socket) = tokio_tungstenite::accept_async(socket).await else {
return;
};
handler(index, socket).await;
});
}
});
Self { addr, connections, accept_task: Some(accept_task) }
}
pub(super) async fn spawn_hung() -> Self {
let listener = TcpListener::bind("127.0.0.1:0")
.await
.expect("bind");
let addr = listener
.local_addr()
.expect("local addr");
let connections = Arc::new(AtomicUsize::new(0));
let counter = connections.clone();
let accept_task = tokio::spawn(async move {
let mut accepted = Vec::new();
loop {
let Ok((socket, _)) = listener.accept().await else {
return;
};
counter.fetch_add(1, Ordering::SeqCst);
accepted.push(socket);
}
});
Self { addr, connections, accept_task: Some(accept_task) }
}
pub(super) fn url(&self) -> String {
format!("ws://{}", self.addr)
}
pub(super) fn shutdown(&mut self) {
if let Some(task) = self.accept_task.take() {
task.abort();
}
}
}
impl Drop for FakeTitan {
fn drop(&mut self) {
self.shutdown();
}
}
pub(super) fn wall_nanos_now() -> u64 {
u64::try_from(
SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("after epoch")
.as_nanos(),
)
.expect("unix nanoseconds fit in u64")
}
pub(super) fn fermiswap() -> PriceLevelStreamConfig {
PriceLevelStreamConfig::new("fermiswap", address(PAMM), BigUint::from(120_000u64))
}
pub(super) fn message_then_repeat(
first: Message,
repeat: Message,
interval: Duration,
) -> impl Fn(usize, FakeConnection) -> BoxFuture<'static, ()> + Send + Sync + 'static {
move |_, mut socket| {
let first = first.clone();
let repeat = repeat.clone();
Box::pin(async move {
if socket.send(first).await.is_err() {
return;
}
while socket
.send(repeat.clone())
.await
.is_ok()
{
tokio::time::sleep(interval).await;
}
})
}
}
pub(super) fn message_text(block: u64, ts: u64) -> String {
format!(
r#"{{"slot": 1, "block": {block}, "ts": {ts}, "books": [
{{"maker": "Fermi", "quoteAddress": "{PAMM}", "token1": "WBTC", "token2": "USDC",
"token1Address": "{WBTC}", "token2Address": "{USDC}",
"bids": [{{"price": 99900.0, "cumVolume": 1.0}}],
"asks": [{{"price": 100100.0, "cumVolume": 1.0}}]}}
]}}"#
)
}
const CAPTURED_MESSAGE: &str =
include_str!("test_responses/pamm_price_levels_v2_1792115918290990905.json");
pub(super) fn captured_books() -> Vec<TitanBook> {
serde_json::from_str::<TitanPriceLevelMessage>(CAPTURED_MESSAGE)
.expect("the captured message parses")
.books
}
pub(super) fn captured_books_of(maker: &str) -> Vec<TitanBook> {
let books: Vec<TitanBook> = captured_books()
.into_iter()
.filter(|book| book.maker.as_deref() == Some(maker))
.collect();
assert!(!books.is_empty(), "no captured book of {maker}");
books
}
pub(super) fn captured_book(maker: &str, token1: &str, token2: &str) -> TitanBook {
captured_books_of(maker)
.into_iter()
.find(|book| book.token1 == token1 && book.token2 == token2)
.expect("captured book")
}
pub(super) fn captured_message_text(maker: &str, block: u64, ts: u64) -> String {
let message: serde_json::Value =
serde_json::from_str(CAPTURED_MESSAGE).expect("the captured message parses");
let books: Vec<serde_json::Value> = message["books"]
.as_array()
.expect("the capture carries books")
.iter()
.filter(|book| book["maker"] == maker)
.cloned()
.collect();
assert!(!books.is_empty(), "no captured book of {maker}");
serde_json::json!({ "slot": 1, "block": block, "ts": ts, "books": books }).to_string()
}
pub(super) const CAPTURED_SLOT: u64 = 15_440_992;
const MATCHING_MESSAGE: &str =
include_str!("test_responses/pamm_price_levels_v2_1792115920294943036.json");
const CAPTURED_QUOTE_STREAM_MESSAGE: &str =
include_str!("test_responses/pamm_quote_stream_v2_1792115920248724389.json");
pub(super) fn matching_books() -> Vec<TitanBook> {
serde_json::from_str::<TitanPriceLevelMessage>(MATCHING_MESSAGE)
.expect("the captured message parses")
.books
}
pub(super) fn matching_message_text(block: u64, ts: u64) -> String {
let message = with_integer_field(MATCHING_MESSAGE, "block", block);
with_integer_field(&message, "ts", ts)
}
pub(super) fn captured_quote_stream_message() -> TitanQuoteStreamMessage {
serde_json::from_str(CAPTURED_QUOTE_STREAM_MESSAGE)
.expect("the captured quote stream message parses")
}
pub(super) fn captured_quote_stream_text() -> &'static str {
CAPTURED_QUOTE_STREAM_MESSAGE
}
pub(super) fn captured_venue_overrides(message: TitanQuoteStreamMessage) -> Vec<VenueOverrides> {
titan::validate(message)
.into_iter()
.filter_map(|outcome| match outcome {
Ok(entry) => Some(entry),
Err(EntryRejection::Empty) => None,
Err(reason) => panic!("refused a captured entry: {reason:?}"),
})
.collect()
}
pub(super) const SYNTHETIC_ACCOUNT: &str = "0xba443ecec71dc7123bd68c2082d13e3299cde896";
pub(super) fn test_overrides() -> PammSimulationOverrides {
PammSimulationOverrides {
accounts: BTreeMap::from([
(
address("0x48165e588ec68e724315d3e0fe7b0f3b9b6c7a6d"),
AccountOverride {
balance: Some(address("0x1b6008ea9711c3f3")),
nonce: Some(0xe40),
state_diff: BTreeMap::new(),
},
),
(
address("0xb261ef0a97bc7cf3af2025ab6b3792e6062d3d4a"),
AccountOverride {
balance: Some(address("0x00")),
nonce: Some(1),
state_diff: BTreeMap::from([(
address(
"0x0000000000000000000000000000000000000000000000000000000000000000",
),
address(
"0x000000006ad184d800003c06d28e200000000000000000000000000090db0604",
),
)]),
},
),
]),
block_number: Some(26_201_954),
block_timestamp: Some(1_792_115_927),
built_at_ns: 1_792_115_920_127_487_452,
}
}
fn with_integer_field(message: &str, key: &str, value: u64) -> String {
let field = format!("\"{key}\":");
let mut replaced = String::with_capacity(message.len());
let mut rest = message;
let mut fields = 0;
while let Some(start) = rest.find(&field) {
let (head, tail) = rest.split_at(start + field.len());
replaced.push_str(head);
let spaces = tail.len() - tail.trim_start_matches(' ').len();
let (padding, tail) = tail.split_at(spaces);
replaced.push_str(padding);
let digits = tail.len() -
tail.trim_start_matches(|character: char| character.is_ascii_digit())
.len();
assert!(digits > 0, "\"{key}\" is not an integer field");
replaced.push_str(&value.to_string());
let tail = &tail[digits..];
rest = tail;
fields += 1;
}
assert!(fields > 0, "the captured message carries no \"{key}\" field");
replaced.push_str(rest);
replaced
}