Skip to main content

tycho_simulation/pamm/protocols/elfomofi/
models.rs

1//! The helper's ABI, the chains it is deployed on with their tuning, and the checks every book
2//! passes before it is priced.
3
4use 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    /// One rung of a cumulative ladder: in total, `amountIn` of the token sold buys `amountOut`
26    /// of the token bought, net of fees.
27    #[derive(Debug)]
28    struct CumulativeLevel {
29        uint256 amountIn;
30        uint256 amountOut;
31    }
32
33    /// One pair's book. Asks sell `quote` for `base`, bids sell `base` for `quote`. The balances
34    /// are the vault's whole balance of each token, repeated in every book that holds it.
35    #[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    /// Every book, and the block the helper read them at. On Robinhood the block number is
46    /// ArbSys's `arbBlockNumber()`.
47    function getAllOrderbooks() external view
48        returns (PairOrderbook[] books, uint256 blockNumber, uint256 blockTimestamp);
49}
50
51/// The marker some contracts use for the native token. The helper should never name it, and a
52/// book that does is skipped: the router trades ERC20s only.
53const NATIVE_MARKER: Address = address!("eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee");
54
55/// A chain ElFomoFi is deployed on, with the helper that serves its books and the feed's tuning
56/// there.
57#[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    /// The helper serving this chain's books. Each chain has its own: on BSC, the Base helper's
97    /// address holds an unrelated contract.
98    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    /// How far behind the local clock a read's block may be before the poll is refused.
109    ///
110    /// The venue worsens its prices in steps as the operator's last push ages. Measured on
111    /// 2026-11-27 from the timestamp of the block a poll reads, prices hold for 4 s on Base and
112    /// BSC and 5 s on Robinhood. Past that, the next step costs Base and Robinhood about 25 bps and
113    /// BSC 75 bps. Books empty at 14-16 s
114    /// (Base), 10-12 s (BSC) and 12-16 s (Robinhood).
115    ///
116    /// This lag, plus [`Self::max_snapshot_age`], plus the time a transaction takes to land, should
117    /// stay inside that hold. A typical fill takes about 1 s of lag, 0.5 s of snapshot age and
118    /// 1 s to land, and does. One at both limits does not: on Base and Robinhood it fills about
119    /// 25 bps below the quote, and on BSC 75 bps below, which the route's `min_amount_out`
120    /// usually reverts. A tighter bound costs reads:
121    /// read lag was p50/p99 0.66/1.43 s on Base, 1.09/2.09 s on BSC and 0.91/3.85 s on Robinhood,
122    /// so 1.5 s refuses 12% of BSC reads where 2 s refuses 1.2%.
123    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    /// The longest a published snapshot may serve without a refresh, and the feed's default.
132    /// Under the same bound as [`Self::max_read_lag`]. It cannot go much lower: a poll every
133    /// second, with a p99 round trip of about 1.2 s, already leaves up to 2 s between snapshots.
134    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    /// Gas of the protocol part of one swap: the executor and the router's
143    /// `swapWithContractBalance`, as tycho-execution's gas estimator counts it.
144    ///
145    /// Measured by tycho-execution's `Elfomofi.t.sol` (`testGas`, every account cold) selling the
146    /// base token of one pair per chain, rounded up: WETH/USDC on Base at 64,420,000 (435,067),
147    /// the highest of samples taken every 190,000 blocks from 62,900,000 to 64,610,000; ETH/USDT
148    /// on BSC at 134,869,000 (469,523; its book was empty at every later sample); and NVDA/USDG on
149    /// Robinhood at 126,465,000 (386,394), the highest of samples from 121,390,000 to
150    /// 127,190,000. Each chain's gas test asserts the swap stays within its value here; change both
151    /// together. Selling the quote token costs 7k to 25k less.
152    ///
153    /// These values go stale without a code change: the cost grows with the venue's state. On
154    /// every swap the pricing asks a fee registry (the pricing proxy's slot 0x67) for a
155    /// caller-dependent charge, and the registry loops over an array it keeps in its slot 2, at
156    /// about 9,200 gas per element. What the elements mean is not known: the registry is
157    /// unverified, and every element tried as the caller or the origin was charged nothing. On
158    /// Base the array grew from 3 elements at 62,900,000 to 10 at 64,610,000 (2026-11-27 to
159    /// 2026-12-01), which took the swap from 356,680 to 432,157. Re-measure when it grows (its
160    /// length is the registry's slot 2), when the proxy points at another registry, or when the
161    /// pricing contract is upgraded. The venue's pricing also reads reference pools that differ per
162    /// pair, so other pairs cost somewhat more or less.
163    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/// One book that passed the checks, in raw units of its tokens.
173#[derive(Debug, Clone, PartialEq)]
174pub(super) struct PairBook {
175    pub base: Bytes,
176    pub quote: Bytes,
177    /// Sells quote, buys base.
178    pub asks: Ladder,
179    /// Sells base, buys quote.
180    pub bids: Ladder,
181    pub balance_base: BigUint,
182    pub balance_quote: BigUint,
183}
184
185/// What one helper call returned, with the books that failed a check left out.
186#[derive(Debug, Clone)]
187pub(super) struct HelperRead {
188    pub block_number: u64,
189    pub block_timestamp: u64,
190    pub books: Vec<PairBook>,
191}
192
193/// Decodes the helper's answer and checks every book. A book that fails a check is skipped, and
194/// so is every book of a pair the answer names more than once: which of them prices the pair
195/// would be a guess.
196///
197/// Fails when the answer does not decode, or when it holds books and none of them passes: an
198/// answer that withdraws every pair because its format changed is an outage, not an empty venue.
199/// An answer with no books at all is the venue serving nothing, and succeeds.
200pub(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
233/// The book in raw units, or why it cannot be priced.
234fn 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
264/// `books` without any pair that appears more than once, in either orientation; each repeated
265/// pair's books are added to `rejected`.
266fn 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    /// One book of each recording, checked to the wei against the helper's raw answer (decoded
313    /// independently with `cast`).
314    #[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    /// Which of two books for one pair prices it would be a guess, so neither does; a pair named
379    /// the other way round is the same pair.
380    #[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}