tycho-simulation 0.551.2

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
//! ElFomoFi on Base, BSC and Robinhood: per-pair books quoted by an operator and filled from one
//! shared vault.
//!
//! The feed polls one view per chain over JSON-RPC, the helper's `getAllOrderbooks()`, which
//! returns every pair's cumulative ask and bid ladders (net of fees, cut at the vault's balance
//! of the output token) and the block it read them at. The states price swaps by interpolating
//! those ladders; they do not model the venue's pricing contracts, whose quoter and engine are
//! unverified and replaced without events, so the helper's answer is the whole model.
//!
//! # What this integration depends on
//!
//! The same three contracts sit at the same addresses on every chain:
//!
//! | Contract | Address                                      | Notes                              |
//! |----------|----------------------------------------------|------------------------------------|
//! | Router   | `0xf0f0F0F0FB0d738452EfD03A28e8be14C76d5f73` | not upgradeable; the fill entry    |
//! | Pricing  | `0xffffffbb2d432b8acb4c57d556c0c721a431d038` | transparent proxy, router-only     |
//! | Vault    | `0xbb1b19f138db3925883a96ff7a304277460e0c99` | Safe; every pair's inventory       |
//!
//! The helper is per chain (`models::ElfomofiSupportedChain::helper`). The pricing proxy was last
//! upgraded on 2026-11-20 on all three chains (Base 59,985,486, BSC 134,716,965, Robinhood
//! 119,145,799); the recordings in `testdata/` postdate it.
//!
//! # Known limits
//!
//! - Quotes worsen in steps from 4-5 s after the block a poll reads and empty after 10-16 s
//!   (`models::ElfomofiSupportedChain::max_read_lag` has the per-chain figures), and a pair
//!   following a reference AMM pool drops to zero when that pool moves about 1%. The feed withdraws
//!   books that are 2 s old. A swap carries no minimum of its own, so a quote that goes stale in
//!   flight fills worse until the route's `min_amount_out` reverts it; through the fallback router
//!   the on-chain quote shows it and the fallback pool fills instead when it pays more.
//! - Every pair's ladder is cut at the vault's whole balance of its output token, so pairs that
//!   share a token each claim all of it. When two fills in one block together exceed it, the second
//!   pays only what is left of the balance and keeps the whole input, which the route's
//!   `min_amount_out` catches; with the vault empty the venue reverts it.
//! - A fill moves the rest of the same-direction ladder about 0.1% worse at the next levels
//!   (measured on a Base fork); a continued fill priced on the pre-fill ladder does not include
//!   that, and the route's slippage absorbs it. How the opposite direction moves after a fill is
//!   not known, so a state that has filled one way refuses the other.
//! - The gas a swap reports (`models::ElfomofiSupportedChain::swap_gas`) is a measured constant,
//!   and the real cost drifts with the venue's state: on Base it rose about 20% in the four days
//!   from 2026-11-27 to 2026-12-01 as the venue's fee registry grew. The estimate only ranks
//!   routes; the transaction's gas limit comes from the node, so a stale value makes ElFomoFi look
//!   cheaper or dearer than it is, not revert.
//! - The feed reads the books with no caller (`from` unset), and the books assume the caller does
//!   not change the price. The router hands the caller to the venue's pricing, which may charge a
//!   caller-dependent term; it was zero for the TychoRouter when measured (fork fills match the
//!   books to the wei on Base and BSC, and within 1.5e-9 on Robinhood). A nonzero term would make
//!   fills worse than quoted, down to the route's `min_amount_out`.

mod client;
pub mod feed;
mod models;
mod source;
pub mod state;
#[cfg(test)]
mod test_support;

pub use models::ElfomofiSupportedChain;

/// Protocol system stamped on every component this integration emits.
pub const PROTOCOL_SYSTEM: &str = "pamm:elfomofi";

/// Protocol system of the components a feed built
/// [`with_fallback_router`](feed::ElfomofiFeedBuilder::with_fallback_router) emits.
pub const FALLBACK_PROTOCOL_SYSTEM: &str = "fallback:pamm:elfomofi";

/// Component type stamped on every pair this integration emits.
pub(crate) const PROTOCOL_TYPE: &str = "elfomofi_pair";

#[cfg(test)]
mod tests {
    use tycho_common::{models::protocol::ProtocolComponent, Bytes};
    use tycho_execution::encoding::{
        evm::swap_encoder::swap_encoder_registry::SwapEncoderRegistry,
        models::{EncodingContext, Swap},
    };

    use super::*;
    use crate::pamm::protocols::elfomofi::test_support::{usdc, weth};

    /// tycho-execution's encoder registry keys the encoders on its own copies of these strings.
    #[test]
    fn the_protocol_systems_are_the_keys_the_encoder_registry_expects() {
        assert_eq!(PROTOCOL_SYSTEM, tycho_execution::encoding::evm::ELFOMOFI_PROTOCOL_SYSTEM);
        assert_eq!(
            FALLBACK_PROTOCOL_SYSTEM,
            tycho_execution::encoding::evm::ELFOMOFI_FALLBACK_PROTOCOL_SYSTEM
        );
    }

    /// A component of either label encodes through the default registry: the tokens, then for
    /// the fallback router the pool its `user_data` names.
    #[test]
    fn components_of_both_labels_encode() {
        let pool = "0xd0b53d9277642d899df5c87a3966a349a798f224";
        let tokens = [weth().address.to_vec(), usdc().address.to_vec()].concat();
        for (protocol_system, user_data, suffix) in [
            (PROTOCOL_SYSTEM, None, Vec::new()),
            (
                FALLBACK_PROTOCOL_SYSTEM,
                Some(format!(r#"{{"fallback_protocol":"uniswap_v3","pool":"{pool}"}}"#)),
                [vec![1u8], Bytes::from(pool).to_vec()].concat(),
            ),
        ] {
            let component = ProtocolComponent {
                id: "elfomofi".to_string(),
                protocol_system: protocol_system.to_string(),
                chain: tycho_common::models::Chain::Base,
                tokens: vec![weth().address, usdc().address],
                ..Default::default()
            };
            let mut swap = Swap::new(component, weth(), usdc(), Default::default());
            if let Some(user_data) = user_data {
                swap = swap.with_user_data(Bytes::from(user_data.into_bytes()));
            }
            let executors =
                format!(r#"{{"base": {{"{protocol_system}": "{}"}}}}"#, Bytes::zero(20));
            let registry = SwapEncoderRegistry::new(tycho_common::models::Chain::Base)
                .add_default_encoders(Some(executors))
                .unwrap();
            let context = EncodingContext {
                router_address: None,
                group_token_in: weth().address,
                group_token_out: usdc().address,
                origin: None,
            };

            let data = registry
                .get_encoder(protocol_system)
                .unwrap()
                .encode_swap(&swap, &context)
                .unwrap();

            assert_eq!(data, [tokens.clone(), suffix].concat(), "{protocol_system}");
        }
    }
}