use std::{
collections::{HashMap, HashSet},
sync::{
atomic::{AtomicBool, AtomicU64, Ordering},
Arc, Mutex, MutexGuard, PoisonError,
},
time::Duration,
};
use alloy::{
primitives::{address, aliases::U72, Address, U256},
providers::{
bindings::IMulticall3::{
aggregate3Call, getBlockNumberCall, getChainIdCall, getCurrentBlockTimestampCall,
Result as Call3Result,
},
MULTICALL3_ADDRESS,
},
sol_types::{SolCall, SolValue},
};
use reqwest::Url;
use serde::Deserialize;
use tycho_common::{
models::{token::Token, Chain},
Bytes,
};
use crate::{
book::{sim::SwapDirection, BookFeedConfig},
pamm::protocols::hanji::{
feed::{HanjiBookAssembler, HanjiBookSource},
market::Market,
reader::{
assembleOrderbookFromOrdersCall, assembleOrderbookFromOrdersReturn, getConfigCall,
getConfigReturn, pausedCall, whitelistedCall, BookRead, HanjiReader, MarketConfig,
MarketRead, CONTRACT_QUOTER_SELECTOR, LOB_SELECTOR, MAX_PRICE_LEVELS, QUOTER_SELECTOR,
},
state::{HanjiState, Level},
BASE_DEPLOYMENT, BASE_ROUTER,
},
snapshot_feed::http::test_support::{
spawn_http_server, MockHttpServer, MockRequest, MockResponse,
},
};
const RECORDING: &str = include_str!("testdata/live_64593995.json");
pub(super) const MARKETS_API: &str = "https://api-base.hanji.io/aggregators/markets";
pub(super) const USDC: Address = address!("833589fCD6eDb6E08f4c7C32D4f71b54bdA02913");
pub(super) const CBBTC: Address = address!("cbB7C0000aB88B473b1f5aFd9ef808440eed33Bf");
pub(super) const ETH_USDC: Address = address!("6a6951db3bb99f76a8ccb9f8a8399b613666298b");
pub(super) const CBBTC_USDC: Address = address!("15c8cb4e336b1e478d155d813830129fb225eee3");
pub(super) const CBBTC_ETH: Address = address!("f455b3c0756908c6a2f44a7f7390053cfe354eea");
pub(super) const NVDA_USDC: Address = address!("30bfa3b501c8f83114c1a789febb6281a0bcd751");
#[derive(Debug, Clone, Copy, PartialEq, Eq, Deserialize)]
#[serde(rename_all = "lowercase")]
pub(super) enum Caller {
Direct,
Contract,
Router,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct Fixture {
pub block: u64,
pub timestamp: u64,
pub implementations: HashMap<Address, Address>,
pub markets: Vec<FixtureMarket>,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureMarket {
pub api: serde_json::Value,
pub config: FixtureConfig,
pub wiring: FixtureWiring,
pub books: FixtureBooks,
pub cases: Vec<FixtureCase>,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureConfig {
pub scaling_x: U256,
pub scaling_y: U256,
pub token_x: Address,
pub token_y: Address,
pub supports_native_eth: bool,
pub is_token_x_weth: bool,
pub aggressive_commission_rate: U256,
pub passive_order_payout_rate: U256,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureWiring {
pub lob: Address,
pub quoter: Address,
pub contract_quoter: Address,
pub router_whitelisted: bool,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureBooks {
pub direct: FixtureBook,
pub contract: Option<FixtureBook>,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureBook {
pub asks: Vec<[U256; 2]>,
pub bids: Vec<[U256; 2]>,
}
#[derive(Debug, Clone, Deserialize)]
pub(super) struct FixtureCase {
pub caller: Caller,
pub sell_base: bool,
pub amount_in: U256,
pub shares: U256,
pub amount_out: U256,
pub gas: u64,
pub net_gas: u64,
}
pub(super) fn fixture() -> Fixture {
serde_json::from_str(RECORDING).expect("the recording parses")
}
pub(super) fn levels(side: &[[U256; 2]]) -> Vec<Level> {
side.iter()
.map(|[price, shares]| Level { price: *price, shares: *shares })
.collect()
}
impl FixtureCase {
pub(super) fn direction(&self) -> SwapDirection {
if self.sell_base {
SwapDirection::BaseToQuote
} else {
SwapDirection::QuoteToBase
}
}
}
impl FixtureConfig {
fn fee_rate(&self) -> u64 {
(self.aggressive_commission_rate + self.passive_order_payout_rate).to()
}
}
impl FixtureMarket {
pub(super) fn orderbook(&self) -> Address {
serde_json::from_value(self.api["orderbookAddress"].clone()).expect("an orderbook")
}
pub(super) fn deployed(&self) -> Option<Market> {
BASE_DEPLOYMENT
.markets
.iter()
.find(|market| market.orderbook == self.orderbook())
.copied()
}
pub(super) fn book(&self, caller: Caller) -> Option<&FixtureBook> {
let fast_quoter = match caller {
Caller::Direct => true,
Caller::Contract => false,
Caller::Router => self.wiring.router_whitelisted,
};
if fast_quoter {
Some(&self.books.direct)
} else {
self.books.contract.as_ref()
}
}
pub(super) fn read(&self, caller: Caller) -> Option<MarketRead> {
let book = self.book(caller)?;
Some(MarketRead {
market: self.deployed()?,
config: MarketConfig {
scaling_x: self.config.scaling_x,
scaling_y: self.config.scaling_y,
fee_rate: self.config.fee_rate(),
},
asks: levels(&book.asks),
bids: levels(&book.bids),
})
}
}
impl Fixture {
pub(super) fn market(&self, orderbook: Address) -> &FixtureMarket {
self.markets
.iter()
.find(|market| market.orderbook() == orderbook)
.expect("a recorded market")
}
pub(super) fn read(&self, caller: Caller) -> BookRead {
BookRead {
block_number: self.block,
timestamp: self.timestamp,
markets: self
.markets
.iter()
.filter_map(|market| market.read(caller))
.collect(),
}
}
}
fn bytes(address: Address) -> Bytes {
Bytes::from(address.to_vec())
}
pub(super) fn eth() -> Token {
Chain::Base.native_token()
}
pub(super) fn usdc() -> Token {
Token::new(&bytes(USDC), "USDC", 6, 0, &[Some(10_000)], Chain::Base, 100)
}
pub(super) fn cbbtc() -> Token {
Token::new(&bytes(CBBTC), "cbBTC", 8, 0, &[Some(10_000)], Chain::Base, 100)
}
pub(super) fn book_config() -> BookFeedConfig {
let tokens: HashMap<Bytes, Token> = [eth(), usdc(), cbbtc()]
.into_iter()
.map(|token| (token.address.clone(), token))
.collect();
BookFeedConfig { chain: Chain::Base, tokens: Arc::new(tokens), min_tvl_usd: 0.0 }
}
pub(super) fn state(orderbook: Address, caller: Caller) -> HanjiState {
let fixture = fixture();
let read = fixture
.market(orderbook)
.read(caller)
.expect("a recorded book");
let (base, quote) = match orderbook {
ETH_USDC => (eth(), usdc()),
CBBTC_USDC => (cbbtc(), usdc()),
CBBTC_ETH => (cbbtc(), eth()),
_ => panic!("no tokens for {orderbook}"),
};
HanjiState {
orderbook,
base_token: base,
quote_token: quote,
scaling_x: read.config.scaling_x,
scaling_y: read.config.scaling_y,
fee_rate: read.config.fee_rate,
gas: read.market.gas,
asks: read.asks,
bids: read.bids,
}
.validated()
.expect("a recorded state validates")
}
pub(super) struct FakeNode {
pub fixture: Fixture,
pub chain_id: u64,
pub block: AtomicU64,
pub reverting: HashSet<Address>,
pub misreporting: HashSet<Address>,
pub unwired: HashSet<Address>,
pub native_flipped: HashSet<Address>,
pub rates: Option<Rates>,
pub paused: HashSet<Address>,
pub whitelisting: Mutex<HashSet<Address>>,
pub rewired: Mutex<HashMap<Address, Address>>,
pub relinked: Mutex<HashMap<Address, Address>>,
pub node_delay: Mutex<Duration>,
pub implementations: Mutex<HashMap<Address, Address>>,
pub storage_failing: AtomicBool,
}
impl FakeNode {
pub(super) fn new() -> Self {
let fixture = fixture();
let whitelisting = fixture
.markets
.iter()
.filter(|market| market.wiring.router_whitelisted)
.map(FixtureMarket::orderbook)
.collect();
let implementations = Mutex::new(fixture.implementations.clone());
FakeNode {
block: AtomicU64::new(fixture.block),
fixture,
chain_id: 8453,
reverting: HashSet::new(),
misreporting: HashSet::new(),
native_flipped: HashSet::new(),
unwired: HashSet::new(),
rates: None,
paused: HashSet::new(),
whitelisting: Mutex::new(whitelisting),
rewired: Mutex::new(HashMap::new()),
relinked: Mutex::new(HashMap::new()),
node_delay: Mutex::new(Duration::ZERO),
implementations,
storage_failing: AtomicBool::new(false),
}
}
pub(super) fn whitelist_the_router_everywhere(&self, whitelisted: bool) {
let mut whitelisting = locked(&self.whitelisting);
for market in &self.fixture.markets {
if whitelisted {
whitelisting.insert(market.orderbook());
} else {
whitelisting.remove(&market.orderbook());
}
}
}
pub(super) async fn serve(self: Arc<Self>) -> MockHttpServer {
spawn_http_server(move |request: &MockRequest| Some(self.answer(request))).await
}
fn answer(&self, request: &MockRequest) -> MockResponse {
let request: serde_json::Value = serde_json::from_str(&request.body).unwrap();
if let Some(batch) = request.as_array() {
return self.answer_storage(batch);
}
assert_eq!(
request["method"], "eth_call",
"the reader sends eth_call and batched slot reads"
);
assert_eq!(request["params"][0]["to"], serde_json::json!(MULTICALL3_ADDRESS));
let delay = *locked(&self.node_delay);
MockResponse { status: "200 OK", body: self.answer_call(&request).to_string(), delay }
}
fn answer_call(&self, request: &serde_json::Value) -> serde_json::Value {
assert_eq!(request["params"][1], "latest", "a read asks for the latest block");
let input = request["params"][0]["input"]
.as_str()
.or_else(|| request["params"][0]["data"].as_str())
.unwrap();
let input = alloy::primitives::hex::decode(input).unwrap();
let calls = aggregate3Call::abi_decode(&input)
.unwrap()
.calls;
let answers: Vec<Call3Result> = calls
.iter()
.map(|call| {
let answer = self.call(call.target, &call.callData);
Call3Result {
success: answer.is_some(),
returnData: answer.unwrap_or_default().into(),
}
})
.collect();
let encoded = aggregate3Call::abi_encode_returns(&answers);
let result = alloy::primitives::hex::encode_prefixed(encoded);
serde_json::json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })
}
fn answer_storage(&self, batch: &[serde_json::Value]) -> MockResponse {
if self
.storage_failing
.load(Ordering::SeqCst)
{
return MockResponse::from(("502 Bad Gateway", "overloaded".to_string()));
}
let answers: Vec<_> = batch
.iter()
.map(|request| self.storage_answer(request))
.collect();
MockResponse::from(("200 OK", serde_json::Value::Array(answers).to_string()))
}
fn storage_answer(&self, request: &serde_json::Value) -> serde_json::Value {
assert_eq!(request["method"], "eth_getStorageAt", "a batch holds only slot reads");
let params = &request["params"];
let slot: U256 = serde_json::from_value(params[1].clone()).unwrap();
assert_eq!(
slot,
U256::from_be_bytes(
alloy::primitives::b256!(
"360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc"
)
.0
),
"the reader reads only the EIP-1967 implementation slot"
);
assert_eq!(
params[2],
serde_json::json!(format!("{:#x}", self.block.load(Ordering::SeqCst))),
"an implementation is read at the read's block"
);
let proxy: Address = serde_json::from_value(params[0].clone()).unwrap();
let implementation = locked(&self.implementations)
.get(&proxy)
.copied()
.unwrap_or_default();
let result = implementation.into_word();
serde_json::json!({ "jsonrpc": "2.0", "id": request["id"], "result": result })
}
fn market(&self, orderbook: Address) -> Option<&FixtureMarket> {
self.fixture
.markets
.iter()
.find(|market| market.orderbook() == orderbook)
}
fn contract_quoter(&self, orderbook: Address, market: &FixtureMarket) -> Address {
locked(&self.rewired)
.get(&orderbook)
.copied()
.unwrap_or(market.wiring.contract_quoter)
}
fn call(&self, target: Address, data: &[u8]) -> Option<Vec<u8>> {
let selector = <[u8; 4]>::try_from(&data[..4]).unwrap();
if target == MULTICALL3_ADDRESS {
let value = match selector {
getBlockNumberCall::SELECTOR => self.block.load(Ordering::SeqCst),
getCurrentBlockTimestampCall::SELECTOR => self.fixture.timestamp,
getChainIdCall::SELECTOR => self.chain_id,
_ => panic!("the fake node does not answer {selector:?} on Multicall3"),
};
return Some(U256::from(value).abi_encode());
}
if self.chain_id != Chain::Base.id() {
return Some(Vec::new());
}
if selector == assembleOrderbookFromOrdersCall::SELECTOR {
return self.book(target, data);
}
let market = self.market(target)?;
match selector {
LOB_SELECTOR if self.unwired.contains(&target) => None,
LOB_SELECTOR => Some(
locked(&self.relinked)
.get(&target)
.copied()
.unwrap_or(market.wiring.lob)
.abi_encode(),
),
QUOTER_SELECTOR => Some(market.wiring.quoter.abi_encode()),
CONTRACT_QUOTER_SELECTOR => Some(
self.contract_quoter(target, market)
.abi_encode(),
),
whitelistedCall::SELECTOR => {
let caller = whitelistedCall::abi_decode(data)
.unwrap()
.caller;
assert_eq!(caller, BASE_ROUTER, "the books are read for the configured taker");
let whitelisting = locked(&self.whitelisting);
Some(
whitelisting
.contains(&target)
.abi_encode(),
)
}
pausedCall::SELECTOR => Some(
self.paused
.contains(&target)
.abi_encode(),
),
getConfigCall::SELECTOR if self.reverting.contains(&target) => None,
getConfigCall::SELECTOR => Some(config_answer(
market,
self.misreporting.contains(&target),
self.native_flipped.contains(&target),
self.rates,
)),
_ => panic!("the fake node does not answer {selector:?} on {target}"),
}
}
fn book(&self, quoter: Address, data: &[u8]) -> Option<Vec<u8>> {
let call = assembleOrderbookFromOrdersCall::abi_decode(data).unwrap();
assert_eq!(call.maxPriceLevels, MAX_PRICE_LEVELS, "the reader asks for its fixed depth");
let market = self
.fixture
.markets
.iter()
.find(|market| market.wiring.lob == call.lobAddress)?;
let book = if quoter == market.wiring.quoter {
&market.books.direct
} else if quoter == market.wiring.contract_quoter {
market.books.contract.as_ref()?
} else {
return None;
};
let side = if call.isAsk { &book.asks } else { &book.bids };
let answer = assembleOrderbookFromOrdersReturn {
arrayPrices: side
.iter()
.map(|[price, _]| price.to::<U72>())
.collect(),
arrayShares: side
.iter()
.map(|[_, shares]| shares.to::<u128>())
.collect(),
};
Some(assembleOrderbookFromOrdersCall::abi_encode_returns(&answer))
}
}
#[derive(Debug, Clone, Copy)]
pub(super) struct Rates {
pub aggressive: u64,
pub passive: u64,
pub passive_payout: u64,
}
impl Rates {
pub(super) const DISTINCT: Rates = Rates {
aggressive: 100_000_000_000_007,
passive: 70_000_000_000_000,
passive_payout: 3_000,
};
pub(super) fn taker(self) -> u64 {
self.aggressive + self.passive_payout
}
}
fn config_answer(
market: &FixtureMarket,
swapped: bool,
native_flipped: bool,
rates: Option<Rates>,
) -> Vec<u8> {
let config = &market.config;
let (token_x, token_y) =
if swapped { (config.token_y, config.token_x) } else { (config.token_x, config.token_y) };
let rates = rates.unwrap_or_else(|| Rates {
aggressive: config.aggressive_commission_rate.to(),
passive: 0,
passive_payout: config.passive_order_payout_rate.to(),
});
getConfigCall::abi_encode_returns(&getConfigReturn {
scalingFactorTokenX: config.scaling_x,
scalingFactorTokenY: config.scaling_y,
tokenX: token_x,
tokenY: token_y,
supportsNativeEth: config.supports_native_eth,
isTokenXWeth: config.is_token_x_weth != native_flipped,
askTrie: Address::ZERO,
bidTrie: Address::ZERO,
adminCommissionRate: 0,
totalAggressiveCommissionRate: rates.aggressive,
totalPassiveCommissionRate: rates.passive,
passiveOrderPayoutRate: rates.passive_payout,
shouldInvokeOnTrade: false,
})
}
fn locked<T>(mutex: &Mutex<T>) -> MutexGuard<'_, T> {
mutex
.lock()
.unwrap_or_else(PoisonError::into_inner)
}
pub(super) fn source(server: &MockHttpServer, now_ms: u64) -> HanjiBookSource {
HanjiBookSource {
reader: HanjiReader::new(Url::parse(&server.url()).unwrap(), BASE_DEPLOYMENT, BASE_ROUTER),
assembler: HanjiBookAssembler::new(book_config()),
clock: Arc::new(move || now_ms),
last_block: Arc::new(AtomicU64::new(0)),
}
}