tycho-simulation 0.548.1

Provides tools for interacting with protocol states, calculating spot prices, and quoting token swaps.
Documentation
//! Hanji on Base: central limit order books whose depth is virtual liquidity placed by a quoter
//! around each swap, quoted and executed through one proxy orderbook per market.
//!
//! Reference: <https://docs.hanji.io/for-developers/liquidity-source-integration>
//!
//! # Where the books come from
//!
//! The feed serves the markets `BASE_DEPLOYMENT` lists, each with the contracts and tokens its
//! fills were recorded against. Every poll reads them all over JSON-RPC, at one block in one
//! `Multicall3.aggregate3` (see `reader.rs`). Hanji's aggregator API (`/aggregators/markets`)
//! lists more markets, but the feed does not read it: a market it adds can only be served once
//! its fills are recorded and its contracts pinned here, and the live test
//! `test_live_deployment_lists_served_markets` reports one the deployment lacks.
//! Events cannot rebuild these books: the quoter places its orders inside the swap and removes them
//! after, so no event ever records them.
//!
//! # Whose book
//!
//! A proxy fills a caller against the orders of one of two quoters. The transaction's sender and
//! callers on the proxy's whitelist (`whitelisted(address)`) get its FastQuoter
//! (`0x598877e528437c0b4429e910d0bba850708cd98c` on the three ETH and cbBTC markets); any other
//! contract, such as Tycho's router, gets a second quoter
//! (`0x611c491d84469c4498b2c4ffd56fd3adc7ce5a1f`) whose book is wider: at Base block 64,593,995
//! its best bid sat 2.0 bps under FastQuoter's on ETH/USDC, 2.1 bps on cbBTC/USDC and 6.2 bps on
//! cbBTC/ETH. FastQuoterHelper, which Hanji's documentation points aggregators to, reports only
//! FastQuoter's book. The feed reads both quoters' books, and whether its taker (Tycho's router
//! unless [`HanjiFeedBuilder::taker`] says otherwise) is whitelisted, and publishes the book the
//! proxy will fill the taker against. Hanji whitelisted Tycho's router on every Base market at
//! about block 62,515,500 (2026-11-26), so it is filled against FastQuoter's book.
//! The tokenized-equity markets name no second quoter and run other implementations, and their
//! fills and gas were not recorded, so the deployment does not list them. A paused
//! proxy reverts every fill while its quoters still report a book, so a paused market is left out.
//!
//! # One inventory, re-priced on every fill
//!
//! One FastQuoter and one contract quoter serve all three ETH and cbBTC markets, from one shared
//! inventory, and after every fill they place a new book on all three, at worse prices for a
//! second fill that takes the same token out. Measured on a fork of Base block 61,711,413: after a
//! cbBTC/USDC sell of about $2k a second cbBTC/USDC sell filled 1.5 bps under the levels the first
//! left, and 10.8 bps under after one of about $18k; after the $18k sell, selling ETH on ETH/USDC
//! filled 10.7 bps under its book. Depth came back each time, so the executor fills such a swap in
//! full, and only the route's `minAmountOut` meets the difference. No state here models it: a
//! simulated swap leaves the side it walked empty, so a route cannot use the same market twice in
//! one direction, but a route through two of these markets that takes the same token out of both
//! is over-quoted by about 0.75 bps per $1k the first hop took.
//!
//! # Freshness
//!
//! A fleet of keeper addresses pushes the quoters' prices several times a second (selector
//! `0xae7e8d81`). The book is empty from about 3 s after the last push, measured at Base block
//! 61,595,000 with `eth_call` time overrides. The feed publishes only reads whose block trails the
//! wall clock by little more than Base's whole-second timestamps explain, and withdraws a book
//! soon after the poll that read it, so a book is served about as long as the quoters keep it
//! without a newer price (`feed.rs` has the bound). A swap that lands after the book went empty
//! fills nothing, and the executor reverts it. The quoters also price off four Base pools seen in
//! their call traces (two Uniswap V3, one PancakeSwap V3 and one Aerodrome CL, whose TWAP they
//! read), so a route that trades through one of those before Hanji meets a different Hanji book
//! than the one simulated.
//!
//! # How a market fills
//!
//! A market trades token X (the base) against token Y (the quote). Prices are Y units per X unit
//! (`shares`), both scaled by the market's `scalingFactorTokenX`/`scalingFactorTokenY`. Recorded
//! at Base block 64,593,995 (`testdata/`) for the transaction's sender, for a contract off the
//! whitelist and for Tycho's whitelisted router, with each output measured as the caller's balance
//! gain, and matched wei for wei by [`HanjiState`] against the book each one gets:
//!
//! - Selling X sends `placeOrder` with `floor(amountIn / scalingX)` shares. They fill best bid
//!   first, and the taker receives `(value - fee) * scalingY`, where `value` is the sum of `shares
//!   * price` over the levels filled and `fee = ceil(value * rate / 1e18)`.
//! - Buying X sends `placeMarketOrderWithTargetValue` with a target of `floor(amountIn /
//!   scalingY)`. It buys, best ask first, the most shares whose `value + fee` fits in the target,
//!   and the taker receives `shares * scalingX`.
//!
//! The rate is `totalAggressiveCommissionRate + passiveOrderPayoutRate` from `getConfig()`; the
//! fee rounds up, where the documented formula reads as rounding down. `passiveOrderPayoutRate`
//! was zero on every recorded market, so whether a taker pays it is not measured. The proxy pulls
//! only what it fills and does not revert when its book runs out; tycho-execution's executor
//! reverts a fill short of the input instead. Within that, the input left over below one share
//! (selling) or one share's cost (buying) stays with the caller, which for a swap through Tycho's
//! router is the router, and a native input the proxy does not use is refunded to it. The quotes
//! are the exact fill of the input; the leftover is not returned to the user.
//!
//! # Native ETH
//!
//! On a market that trades ETH (`supportsNativeEth`), the ETH side is always paid out as native
//! ETH, whichever side it is, and taken as `msg.value`. Components therefore carry the chain's
//! native token (the zero address) in place of WETH, which the API lists for it.
//!
//! # What this integration depends on
//!
//! The proxies and the underlying CLOBs are UUPS proxies whose shells are verified on Sourcify;
//! their implementations and both quoters are not source-verified (checked 2026-11-26), and each
//! market's proxy runs its own implementation. One EOA,
//! `0xA24D2aF7B9d58579225800B32111D71fb34643C9`, owns them all and upgrades them without a
//! timelock: ETH/USDC's proxy was upgraded at Base blocks 56,481,785 and 59,531,598, cbBTC/ETH's at
//! 59,531,787, and Hanji says it adjusts the on-chain quoting logic from time to time. Beside what
//! Hanji documents (the API's market list, `getConfig()`, `assembleOrderbookFromOrders` and the
//! two swap methods), the feed calls three unnamed getters of the proxies, identified by what they
//! return (`reader.rs`), and `whitelisted(address)`; it does not call the API. The fill rules and
//! the choice of quoter were measured rather than read from source, so an upgrade can break the
//! quotes without failing any read. The feed therefore pins what the fills were recorded against:
//! the implementation each proxy and CLOB ran, and that of the LPManager
//! (`0x69a9f156d5902191dce331ab348f3e9e96e48b22`), a UUPS proxy of the same owner that holds the
//! quoters' shared inventory and is an immutable of both (`Deployment::shared`); the CLOB each
//! proxy names; and the two quoters every market names (`Deployment::quoters`). The quoters are
//! not proxies, and neither they nor the contracts FastQuoter embeds have a `DELEGATECALL`, so
//! their code cannot change; the owner can only point a proxy at another CLOB or quoter, which
//! every read checks. Every poll reads the implementations from their EIP-1967 slots, in one batch
//! at the read's block: a market whose proxy or CLOB runs another implementation, or that names
//! another CLOB or other quoters, is withheld until the pins are updated, and every market is
//! withheld while the LPManager runs another. The fixture records the implementations it ran
//! against, and the tests check the pins against it, so updating a pin means re-recording the
//! fixture with `testdata/record_fixture.py`, whose fills the state tests check across sizes.

use alloy::primitives::{address, Address};
use market::{FillGas, Market, NativeSide};
use tycho_common::models::Chain;

pub mod feed;
mod market;
mod reader;
pub mod state;

pub use feed::{HanjiFeed, HanjiFeedBuilder};
pub use state::HanjiState;

/// Protocol system stamped on every component this integration emits; tycho-execution keys
/// Hanji's encoder on it.
pub const PROTOCOL_SYSTEM: &str = "pamm:hanji";

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

/// Static attribute holding the market's proxy orderbook, which the encoder calls.
pub const ORDERBOOK_ATTRIBUTE: &str = "orderbook";

/// One chain's Hanji markets and what they all depend on.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Deployment {
    pub chain: Chain,
    /// The markets served, each pinned to what its fills were recorded against.
    pub markets: &'static [Market],
    /// Proxies every market's quotes depend on beyond its own proxy and CLOB, as (proxy,
    /// implementation): one running another implementation withholds every market.
    pub shared: &'static [(Address, Address)],
    /// The quoters every served market must name: those the fill rules were recorded against.
    pub quoters: Quoters,
}

/// The two quoters a proxy fills its callers against (see the module docs).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Quoters {
    /// For the transaction's sender and whitelisted callers.
    pub fast: Address,
    /// For any other contract.
    pub contract: Address,
}

/// Base's wrapped native token, which `getConfig()` names for a native side.
const BASE_WETH: Address = address!("4200000000000000000000000000000000000006");
const BASE_USDC: Address = address!("833589fcd6edb6e08f4c7c32d4f71b54bda02913");
const BASE_CBBTC: Address = address!("cbb7c0000ab88b473b1f5afd9ef808440eed33bf");

/// The CLOB implementation all three markets' CLOBs run.
const BASE_CLOB_IMPLEMENTATION: Address = address!("f1466addf635bf0ba0a0c4bb9fecaa03b0945510");

/// Hanji's LPManager on Base, which holds the quoters' shared inventory.
const BASE_LP_MANAGER: Address = address!("69a9f156d5902191dce331ab348f3e9e96e48b22");

/// The Base deployment, as recorded in the fixture at Base block 64,593,995 (2026-12-01).
///
/// Each market's gas covers what the proxy call costs a contract caller once its refund is paid
/// back, measured with `debug_traceCall` of both swap methods sent through a forwarding contract
/// (the `net_gas` of the recording's "contract" and "router" cases). Most of the gas is the quoter
/// placing and removing its virtual orders around the fill and re-reading the pools it prices
/// from; clearing those orders earns a refund of 10% to 14% of the call's gas, under the 20% of a
/// transaction's gas a refund may pay back. In the recording, after the refund, a first-level fill
/// cost at most 919,606 on ETH/USDC, 1,097,234 on cbBTC/USDC and 1,367,593 on cbBTC/ETH, and each
/// further level at most 229,796, 275,491 and 224,922 more, averaged over the levels a fill
/// touched; the figures sit 3% above those. Tycho's router, whitelisted and served from
/// FastQuoter, and a contract off the whitelist cost within 3% of each other, so the model does not
/// tell the two apart. Re-measure when the recorded gas stops fitting
/// (`test_gas_covers_every_recorded_contract_fill`). The router's own transfers and approval are
/// added on top by tycho-execution's gas estimator.
pub(crate) const BASE_DEPLOYMENT: Deployment = Deployment {
    chain: Chain::Base,
    markets: &[
        Market {
            name: "ETH/USDC",
            orderbook: address!("6a6951db3bb99f76a8ccb9f8a8399b613666298b"),
            orderbook_implementation: address!("d6e13dfc6730d6eafbb0d1c605e78d97767fc3a3"),
            clob: address!("7c976801c8589d924ce93bbcce6966d34edf91bf"),
            clob_implementation: BASE_CLOB_IMPLEMENTATION,
            token_x: BASE_WETH,
            token_y: BASE_USDC,
            native: NativeSide::X,
            gas: FillGas { first_level: 950_000, per_further_level: 237_000 },
        },
        Market {
            name: "cbBTC/USDC",
            orderbook: address!("15c8cb4e336b1e478d155d813830129fb225eee3"),
            orderbook_implementation: address!("8a5417c47d3c56dadb232cb8b40ecb135752737c"),
            clob: address!("84792a7e7d80e20404d8ebb77574cfdf91093bfd"),
            clob_implementation: BASE_CLOB_IMPLEMENTATION,
            token_x: BASE_CBBTC,
            token_y: BASE_USDC,
            native: NativeSide::None,
            gas: FillGas { first_level: 1_130_000, per_further_level: 285_000 },
        },
        Market {
            name: "cbBTC/ETH",
            orderbook: address!("f455b3c0756908c6a2f44a7f7390053cfe354eea"),
            orderbook_implementation: address!("db613bf573977aa8948b43e5ab794c980e812d02"),
            clob: address!("b6e72302898ec065038cefacf014b45f0b7e8498"),
            clob_implementation: BASE_CLOB_IMPLEMENTATION,
            token_x: BASE_CBBTC,
            token_y: BASE_WETH,
            native: NativeSide::Y,
            gas: FillGas { first_level: 1_410_000, per_further_level: 232_000 },
        },
    ],
    shared: &[(BASE_LP_MANAGER, address!("836310b078f21872b353ae66a3fe4595db73e104"))],
    quoters: Quoters {
        fast: address!("598877e528437c0b4429e910d0bba850708cd98c"),
        contract: address!("611c491d84469c4498b2c4ffd56fd3adc7ce5a1f"),
    },
};

/// Tycho's default router on Base, the taker the books are read for unless
/// [`HanjiFeedBuilder::taker`] sets another.
pub(crate) const BASE_ROUTER: Address = address!("d374c00614f95492D816b5957E3797ce3f0c445C");

#[cfg(test)]
mod test_support;

#[cfg(test)]
mod tests {
    use tycho_execution::encoding::evm::{
        get_router_address, HANJI_ORDERBOOK_ATTRIBUTE, HANJI_PROTOCOL_SYSTEM,
    };

    use super::*;

    /// By default the books are read for the router tycho-execution encodes Hanji swaps through.
    #[test]
    fn test_default_taker_is_base_router() {
        let router = get_router_address(&Chain::Base).unwrap();

        assert_eq!(router.as_ref(), BASE_ROUTER.as_slice());
    }

    /// Each market is what the fixture recorded at its proxy: the implementations of its proxy and
    /// CLOB, the CLOB and quoters it names, and the tokens and native side of its `getConfig()`;
    /// each shared contract ran its pinned implementation; and every market with recorded fills
    /// is listed, each proxy once.
    #[test]
    fn test_deployment_matches_fixture() {
        let fixture = test_support::fixture();
        let recorded_implementation = |contract: Address| fixture.implementations.get(&contract);

        for market in BASE_DEPLOYMENT.markets {
            let recorded = fixture.market(market.orderbook);
            let config = &recorded.config;
            let native = match (config.supports_native_eth, config.is_token_x_weth) {
                (false, _) => NativeSide::None,
                (true, true) => NativeSide::X,
                (true, false) => NativeSide::Y,
            };
            assert_eq!(
                recorded_implementation(market.orderbook),
                Some(&market.orderbook_implementation),
                "{}",
                market.name
            );
            assert_eq!(
                recorded_implementation(market.clob),
                Some(&market.clob_implementation),
                "{}",
                market.name
            );
            assert_eq!(recorded.wiring.lob, market.clob, "{}", market.name);
            let quoters =
                Quoters { fast: recorded.wiring.quoter, contract: recorded.wiring.contract_quoter };
            assert_eq!(quoters, BASE_DEPLOYMENT.quoters, "{}", market.name);
            assert_eq!(
                (config.token_x, config.token_y, native),
                (market.token_x, market.token_y, market.native),
                "{}",
                market.name
            );
        }
        for (contract, implementation) in BASE_DEPLOYMENT.shared {
            assert_eq!(recorded_implementation(*contract), Some(implementation), "{contract}");
        }
        for recorded in fixture
            .markets
            .iter()
            .filter(|market| !market.cases.is_empty())
        {
            let listed = BASE_DEPLOYMENT
                .markets
                .iter()
                .filter(|market| market.orderbook == recorded.orderbook())
                .count();
            assert_eq!(listed, 1, "{}", recorded.orderbook());
        }
    }

    /// The tokens the deployment names are the chain's: Base's wrapped native token, and the USDC
    /// and cbBTC of the test universe.
    #[test]
    fn test_deployment_tokens_match_chain() {
        let weth = Chain::Base
            .wrapped_native_token()
            .unwrap();

        assert_eq!(weth.address.as_ref(), BASE_WETH.as_slice());
        assert_eq!(BASE_USDC, test_support::USDC);
        assert_eq!(BASE_CBBTC, test_support::CBBTC);
    }

    /// tycho-execution keys Hanji's encoder on the protocol system and reads the orderbook from
    /// the attribute, keeping its own copy of each; this holds the two crates to one spelling.
    #[test]
    fn test_component_names_match_encoder() {
        assert_eq!(PROTOCOL_SYSTEM, HANJI_PROTOCOL_SYSTEM);
        assert_eq!(ORDERBOOK_ATTRIBUTE, HANJI_ORDERBOOK_ATTRIBUTE);
    }
}