1use std::{
5 collections::{HashMap, HashSet},
6 time::Duration,
7};
8
9use alloy::{
10 primitives::{address, Address, U256},
11 sol,
12 sol_types::SolCall,
13};
14use num_bigint::BigUint;
15use serde::{Deserialize, Serialize};
16use tracing::warn;
17use tycho_common::{models::Chain, Bytes};
18
19use crate::{
20 evm::protocol::u256_num::u256_to_biguint, pamm::protocols::elfomofi::state::Ladder,
21 snapshot_feed::errors::FeedError,
22};
23
24sol! {
25 #[derive(Debug)]
28 struct CumulativeLevel {
29 uint256 amountIn;
30 uint256 amountOut;
31 }
32
33 #[derive(Debug)]
36 struct PairOrderbook {
37 address base;
38 address quote;
39 CumulativeLevel[] askCumulativeLevels;
40 CumulativeLevel[] bidCumulativeLevels;
41 uint256 balanceBase;
42 uint256 balanceQuote;
43 }
44
45 function getAllOrderbooks() external view
48 returns (PairOrderbook[] books, uint256 blockNumber, uint256 blockTimestamp);
49}
50
51const NATIVE_MARKER: Address = address!("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
54
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
58pub enum ElfomofiSupportedChain {
59 Base,
60 Bsc,
61 Robinhood,
62}
63
64impl TryFrom<Chain> for ElfomofiSupportedChain {
65 type Error = FeedError;
66
67 fn try_from(chain: Chain) -> Result<Self, Self::Error> {
68 match chain {
69 Chain::Base => Ok(ElfomofiSupportedChain::Base),
70 Chain::Bsc => Ok(ElfomofiSupportedChain::Bsc),
71 Chain::Robinhood => Ok(ElfomofiSupportedChain::Robinhood),
72 Chain::Ethereum |
73 Chain::Starknet |
74 Chain::ZkSync |
75 Chain::Arbitrum |
76 Chain::Unichain |
77 Chain::Polygon |
78 Chain::Plasma |
79 Chain::Arc |
80 Chain::Elysium |
81 Chain::Custom(_) |
82 _ => Err(FeedError::InvalidInput(format!("ElFomoFi is not deployed on {chain}"))),
83 }
84 }
85}
86
87impl ElfomofiSupportedChain {
88 pub fn chain(self) -> Chain {
89 match self {
90 ElfomofiSupportedChain::Base => Chain::Base,
91 ElfomofiSupportedChain::Bsc => Chain::Bsc,
92 ElfomofiSupportedChain::Robinhood => Chain::Robinhood,
93 }
94 }
95
96 pub(super) fn helper(self) -> Address {
99 match self {
100 ElfomofiSupportedChain::Base => address!("c1b13606fc7227f2554067afb3fb12de75c02d81"),
101 ElfomofiSupportedChain::Bsc => address!("78015e3544d989f0712a0b9986cb05838c3fe06d"),
102 ElfomofiSupportedChain::Robinhood => {
103 address!("20d24ee45c9b338ef7acf2eede75183b9e2c9e3c")
104 }
105 }
106 }
107
108 pub(super) fn max_read_lag(self) -> Duration {
124 match self {
125 ElfomofiSupportedChain::Base |
126 ElfomofiSupportedChain::Bsc |
127 ElfomofiSupportedChain::Robinhood => Duration::from_secs(2),
128 }
129 }
130
131 pub fn max_snapshot_age(self) -> Duration {
135 match self {
136 ElfomofiSupportedChain::Base |
137 ElfomofiSupportedChain::Bsc |
138 ElfomofiSupportedChain::Robinhood => Duration::from_secs(2),
139 }
140 }
141
142 pub(super) fn swap_gas(self) -> u64 {
164 match self {
165 ElfomofiSupportedChain::Base => 436_000,
166 ElfomofiSupportedChain::Bsc => 470_000,
167 ElfomofiSupportedChain::Robinhood => 387_000,
168 }
169 }
170}
171
172#[derive(Debug, Clone, PartialEq)]
174pub(super) struct PairBook {
175 pub base: Bytes,
176 pub quote: Bytes,
177 pub asks: Ladder,
179 pub bids: Ladder,
181 pub balance_base: BigUint,
182 pub balance_quote: BigUint,
183}
184
185#[derive(Debug, Clone)]
187pub(super) struct HelperRead {
188 pub block_number: u64,
189 pub block_timestamp: u64,
190 pub books: Vec<PairBook>,
191}
192
193pub(super) fn decode_orderbooks(raw: &[u8]) -> Result<HelperRead, FeedError> {
201 let answer = getAllOrderbooksCall::abi_decode_returns(raw)
202 .map_err(|e| FeedError::Parsing(format!("ElFomoFi getAllOrderbooks: {e}")))?;
203 let block_number = to_u64(answer.blockNumber, "block number")?;
204 let block_timestamp = to_u64(answer.blockTimestamp, "block timestamp")?;
205 let received = answer.books.len();
206
207 let mut rejected = Vec::new();
208 let mut checked = Vec::with_capacity(received);
209 for book in answer.books {
210 let pair = format!("{}/{}", book.base, book.quote);
211 match check_book(book) {
212 Ok(book) => checked.push(book),
213 Err(reason) => rejected.push(format!("{pair}: {reason}")),
214 }
215 }
216 let books = without_repeated_pairs(checked, &mut rejected);
217
218 if let Some(first) = rejected.first() {
219 warn!(skipped = rejected.len(), received, first_reason = %first, "skipping ElFomoFi books");
220 }
221 if received > 0 && books.is_empty() {
222 return Err(FeedError::Parsing(format!(
223 "none of the {received} ElFomoFi books passed the checks; first: {}",
224 rejected
225 .first()
226 .map(String::as_str)
227 .unwrap_or_default()
228 )));
229 }
230 Ok(HelperRead { block_number, block_timestamp, books })
231}
232
233fn check_book(book: PairOrderbook) -> Result<PairBook, String> {
235 for (name, token) in [("base", book.base), ("quote", book.quote)] {
236 if token == Address::ZERO || token == NATIVE_MARKER {
237 return Err(format!("{name} token is {token}, not an ERC20"));
238 }
239 }
240 if book.base == book.quote {
241 return Err("base and quote are the same token".to_string());
242 }
243 let asks = ladder(book.askCumulativeLevels).map_err(|e| format!("asks: {e}"))?;
244 let bids = ladder(book.bidCumulativeLevels).map_err(|e| format!("bids: {e}"))?;
245 Ok(PairBook {
246 base: Bytes::from(book.base.to_vec()),
247 quote: Bytes::from(book.quote.to_vec()),
248 asks,
249 bids,
250 balance_base: u256_to_biguint(book.balanceBase),
251 balance_quote: u256_to_biguint(book.balanceQuote),
252 })
253}
254
255fn ladder(levels: Vec<CumulativeLevel>) -> Result<Ladder, String> {
256 Ladder::new(
257 levels
258 .into_iter()
259 .map(|level| (u256_to_biguint(level.amountIn), u256_to_biguint(level.amountOut)))
260 .collect(),
261 )
262}
263
264fn without_repeated_pairs(books: Vec<PairBook>, rejected: &mut Vec<String>) -> Vec<PairBook> {
267 let pair_key = |book: &PairBook| {
268 if book.base < book.quote {
269 (book.base.clone(), book.quote.clone())
270 } else {
271 (book.quote.clone(), book.base.clone())
272 }
273 };
274 let mut counts: HashMap<(Bytes, Bytes), usize> = HashMap::new();
275 for book in &books {
276 *counts
277 .entry(pair_key(book))
278 .or_default() += 1;
279 }
280 let repeated: HashSet<_> = counts
281 .into_iter()
282 .filter(|(_, count)| *count > 1)
283 .map(|(pair, _)| pair)
284 .collect();
285 let mut kept = Vec::with_capacity(books.len());
286 for book in books {
287 if repeated.contains(&pair_key(&book)) {
288 rejected.push(format!("{}/{}: the pair appears more than once", book.base, book.quote));
289 } else {
290 kept.push(book);
291 }
292 }
293 kept
294}
295
296fn to_u64(value: U256, what: &str) -> Result<u64, FeedError> {
297 value
298 .try_into()
299 .map_err(|e| FeedError::Parsing(format!("ElFomoFi {what} {value}: {e}")))
300}
301
302#[cfg(test)]
303mod tests {
304 use rstest::rstest;
305
306 use super::*;
307 use crate::pamm::protocols::elfomofi::test_support::{
308 big, bytes, helper_answer, ladder, recording, weth_usdc_wire, wire_book, BASE_RECORDING,
309 BSC_RECORDING, CBBTC, ROBINHOOD_RECORDING, USDC, WETH,
310 };
311
312 #[rstest]
315 #[case::base(
316 BASE_RECORDING,
317 (62_017_050, 1_795_593_785, 12),
318 address!("b200000000000000000000c2e324d24d7eecd1fb"),
319 (60_456_809, 17_146_572),
320 (9_735_857_880, 34_167_438_981),
321 (134_146_572, 34_167_438_987)
322 )]
323 #[case::bsc(
324 BSC_RECORDING,
325 (135_619_488, 1_795_593_787, 14),
326 address!("21caef8a43163eea865baee23b9c2e327696a3bf"),
327 (253_292_575_996_800_000_000, 72_000),
328 (24_231_680, 48_505_176_275_990_400_000_000),
329 (752_320, 59_581_064_238_861_470_876_832)
330 )]
331 #[case::robinhood(
332 ROBINHOOD_RECORDING,
333 (122_891_612, 1_795_593_786, 11),
334 address!("39dbed3a2bd333467115de45665cc57f813c4571"),
335 (165_515_119, 1_890_000_000_000_000_000_000),
336 (657_542_294_937_822_440_589_292, 29_076_102_682),
337 (236_903_547_961_879_156_240_201, 29_076_102_685)
338 )]
339 fn recordings_decode_to_the_wei(
340 #[case] hex: &str,
341 #[case] (block, timestamp, count): (u64, u64, usize),
342 #[case] base: Address,
343 #[case] first_ask: (u128, u128),
344 #[case] last_bid: (u128, u128),
345 #[case] balances: (u128, u128),
346 ) {
347 let read = decode_orderbooks(&recording(hex)).unwrap();
348
349 assert_eq!(
350 (read.block_number, read.block_timestamp, read.books.len()),
351 (block, timestamp, count)
352 );
353 let book = read
354 .books
355 .iter()
356 .find(|book| book.base == bytes(base))
357 .unwrap();
358 assert_eq!(book.asks.first_rung(), Some((&big(first_ask.0), &big(first_ask.1))));
359 assert_eq!(book.bids.last_rung(), Some((&big(last_bid.0), &big(last_bid.1))));
360 assert_eq!((&book.balance_base, &book.balance_quote), (&big(balances.0), &big(balances.1)));
361 }
362
363 #[rstest]
364 #[case::zero_base(wire_book(Address::ZERO, USDC, &[], &[(1, 1)], (1, 1)))]
365 #[case::native_quote(wire_book(WETH, NATIVE_MARKER, &[], &[(1, 1)], (1, 1)))]
366 #[case::same_token(wire_book(WETH, WETH, &[], &[(1, 1)], (1, 1)))]
367 #[case::falling_asks(wire_book(WETH, USDC, &[(2, 2), (1, 3)], &[], (1, 1)))]
368 #[case::flat_bids(wire_book(WETH, USDC, &[], &[(1, 2), (2, 2)], (1, 1)))]
369 fn a_book_failing_a_check_is_skipped(#[case] bad: PairOrderbook) {
370 let answer = helper_answer(vec![bad, weth_usdc_wire()], 1, 1);
371
372 let read = decode_orderbooks(&answer).unwrap();
373
374 assert_eq!(read.books.len(), 1);
375 assert_eq!(read.books[0].base, bytes(WETH));
376 }
377
378 #[rstest]
381 #[case::same_orientation(WETH, USDC)]
382 #[case::flipped(USDC, WETH)]
383 fn every_book_of_a_repeated_pair_is_skipped(#[case] base: Address, #[case] quote: Address) {
384 let repeated = wire_book(base, quote, &[], &[(1, 1)], (1, 1));
385 let other = wire_book(CBBTC, USDC, &[], &[(1, 1)], (1, 1));
386 let answer = helper_answer(vec![weth_usdc_wire(), repeated, other], 1, 1);
387
388 let read = decode_orderbooks(&answer).unwrap();
389
390 assert_eq!(read.books.len(), 1);
391 assert_eq!(read.books[0].base, bytes(CBBTC));
392 }
393
394 #[test]
395 fn an_answer_whose_books_all_fail_fails_the_poll() {
396 let answer = helper_answer(vec![wire_book(WETH, WETH, &[], &[(1, 1)], (1, 1))], 1, 1);
397
398 let error = decode_orderbooks(&answer).unwrap_err();
399
400 assert!(matches!(error, FeedError::Parsing(_)), "{error}");
401 }
402
403 #[test]
404 fn an_answer_without_books_is_an_empty_venue() {
405 let read = decode_orderbooks(&helper_answer(vec![], 7, 8)).unwrap();
406
407 assert!(read.books.is_empty());
408 assert_eq!((read.block_number, read.block_timestamp), (7, 8));
409 }
410
411 #[test]
412 fn an_answer_that_does_not_decode_fails_the_poll() {
413 let error = decode_orderbooks(&[0u8; 31]).unwrap_err();
414
415 assert!(matches!(error, FeedError::Parsing(_)), "{error}");
416 }
417
418 #[test]
419 fn a_book_keeps_its_ladders_and_balances() {
420 let read = decode_orderbooks(&helper_answer(vec![weth_usdc_wire()], 1, 1)).unwrap();
421
422 let book = &read.books[0];
423 assert_eq!(book.bids, ladder(&crate::pamm::protocols::elfomofi::test_support::BIDS));
424 assert_eq!(book.asks, ladder(&crate::pamm::protocols::elfomofi::test_support::ASKS));
425 assert_eq!(book.quote, bytes(USDC));
426 }
427
428 #[rstest]
429 #[case::base(Chain::Base, ElfomofiSupportedChain::Base)]
430 #[case::bsc(Chain::Bsc, ElfomofiSupportedChain::Bsc)]
431 #[case::robinhood(Chain::Robinhood, ElfomofiSupportedChain::Robinhood)]
432 fn deployed_chains_resolve_both_ways(
433 #[case] chain: Chain,
434 #[case] supported: ElfomofiSupportedChain,
435 ) {
436 assert_eq!(ElfomofiSupportedChain::try_from(chain).unwrap(), supported);
437 assert_eq!(supported.chain(), chain);
438 }
439
440 #[test]
441 fn another_chain_is_invalid_input() {
442 let error = ElfomofiSupportedChain::try_from(Chain::Ethereum).unwrap_err();
443
444 assert!(matches!(error, FeedError::InvalidInput(_)), "{error}");
445 }
446}