tycho_simulation/price_level_stream/config.rs
1use std::{collections::HashMap, str::FromStr, sync::LazyLock};
2
3use num_bigint::BigUint;
4use tycho_common::Bytes;
5
6/// Protocol system family name of components sourced from the pAMM price level stream.
7///
8/// The full protocol system of a component is `pricelevelstream:{pamm}`, where `{pamm}` is the
9/// configured venue name (e.g. `pricelevelstream:fermiswap`) or, for auto-detected venues, the
10/// venue address (e.g. `pricelevelstream:0x5979…`); see the [module documentation](super) for
11/// details.
12pub const PRICE_LEVEL_STREAM_FAMILY: &str = "pricelevelstream";
13
14/// Protocol system family of components executed through Tycho's `TychoFallbackRouter`, which
15/// retries a reverted pAMM swap on the fallback pool the solver names in the swap's `user_data`.
16///
17/// Must match `tycho-execution`'s `FALLBACK_KEY`.
18pub const FALLBACK_FAMILY: &str = "fallback";
19
20/// Configuration of a single pAMM to be served from the price level stream.
21#[derive(Debug, Clone)]
22pub struct PriceLevelStreamConfig {
23 /// Bare pAMM name (e.g. `fermiswap`); the emitted components carry
24 /// `pricelevelstream:{protocol}` as their protocol system.
25 pub protocol: String,
26 /// The venue's canonical public identity: the address its swaps are sent to, which the
27 /// emitted components carry. Either of a venue's addresses may be given here — see
28 /// [`PAMM_ADDRESS_ALIASES`].
29 pub address: Bytes,
30 /// Constant per-swap gas cost estimate reported for every quote of this pAMM.
31 pub gas_cost: BigUint,
32}
33
34impl PriceLevelStreamConfig {
35 pub fn new(protocol: impl Into<String>, address: Bytes, gas_cost: BigUint) -> Self {
36 Self { protocol: protocol.into(), address, gas_cost }
37 }
38
39 /// The configuration an auto-detected pAMM (streamed by Titan but not otherwise configured)
40 /// is served under: named by its full lowercase hex address, with the given per-swap gas
41 /// cost.
42 pub(super) fn auto_detected(address: Bytes, gas_cost: BigUint) -> Self {
43 let protocol = address.to_string();
44 Self::new(protocol, address, gas_cost)
45 }
46
47 /// The protocol system identifier of components emitted for this pAMM.
48 pub fn protocol_system(&self) -> String {
49 format!("{PRICE_LEVEL_STREAM_FAMILY}:{}", self.protocol)
50 }
51
52 /// The protocol system identifier when this pAMM executes through `TychoFallbackRouter`.
53 pub fn fallback_protocol_system(&self) -> String {
54 format!("{FALLBACK_FAMILY}:{}", self.protocol)
55 }
56}
57
58/// Per-swap gas estimate for auto-detected pAMMs whose venue has not been measured: the maximum
59/// over the known venue profiles (see [`default_served_pamms`]), as the conservative choice.
60/// Overridable per stream via
61/// [`auto_detected_gas_cost`](super::stream::PriceLevelStreamBuilder::auto_detected_gas_cost).
62pub const DEFAULT_AUTO_DETECTED_GAS_COST: u64 = 335_000;
63
64/// The pAMMs known to be served by the Titan price level stream (as of 2026-10-19): FermiSwap,
65/// Kipseli, Metric, Bebop, TaurusFi, Tempest, Goliath, Stelaxis, and ElZorro.
66///
67/// Registered on a builder via
68/// [`with_known_pamms`](super::stream::PriceLevelStreamBuilder::with_known_pamms), so their
69/// components carry the venue name instead of the raw address; an
70/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) call for one of these
71/// addresses overrides the corresponding entry.
72///
73/// Only the venues' router addresses are registered, because an entry here doubles as the
74/// execution target ([`PAMM_ADDRESS_ATTRIBUTE`](super::stream::PAMM_ADDRESS_ATTRIBUTE)): it must
75/// be an address a swap can be sent to. A venue whose streamed key is not that address is
76/// bridged by [`PAMM_ADDRESS_ALIASES`] rather than registered under the streamed key.
77pub fn default_served_pamms() -> Vec<PriceLevelStreamConfig> {
78 // The venues' `IPropAMM::swap` gas, calibrated by replaying real fills on the live venues at
79 // fresh-oracle blocks via `debug_traceCall`, plus a small headroom. Deliberately excludes
80 // router-level overhead (user/input/fee transfers): tycho-execution's gas estimator accounts
81 // for those on top of this per-swap value.
82 let pamms = [
83 // The FermiSwapper router. Measured ~177k-182k (2026-08-18).
84 ("fermiswap", "0x5979458912f80b96d30d4220af8e2e4925a33320", 185_000u64),
85 // The KipseliPropAMMWrapper router. Measured ~308k-329k (2026-08-18). Titan's venue docs
86 // list a newer Kipseli router (0x342b8458…), which has no activity. The stream keys
87 // Kipseli's books by 0xc9a9… instead, which `PAMM_ADDRESS_ALIASES` maps onto this
88 // address.
89 ("kipseli", "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d", 335_000u64),
90 // The Metric router, per Titan's venue docs. It replaced 0xe715dc29…, which has had no
91 // activity since 2026-09-07. Titan's V2 socket streams Metric's books under
92 // 0xe8447019… instead, bridged by `PAMM_ADDRESS_ALIASES`. Its swap gas depends on the
93 // pair, so one value cannot fit all of them. Over 213 fills (2026-10-16), p50 was ~165k
94 // on USDC/USDT, ~245k on the WETH pairs and ~550k on WBTC/USDC; across all fills p50
95 // ~234k, p90 ~280k. This takes the p90: it overstates the stablecoin pair and
96 // understates WBTC/USDC.
97 ("metric", "0x99ab7c1c5eab47801f7937075998527a550fba8a", 280_000u64),
98 // The BopAMM (Bebop) router. It replaced 0xb09aaa56… on 2026-09-15, which has had no
99 // activity since. The bytecode is the same except for one embedded address, so the
100 // earlier measurement (~133k-136k, 2026-08-18) still applies.
101 ("bebop", "0xb09aaa8933626d7e4c48d65dad2d77021cfbca9a", 140_000u64),
102 // The TaurusFi router, which both sockets stream TaurusFi under: an ERC-1967 proxy that
103 // emits the pAMM swap event, so it needs no alias. It replaced 0x217d5893…, and in turn
104 // 0x3ce2672a… (tycho#1633), neither of which has had a swap in the last 7,200 blocks.
105 // Gas over 25 traced fills (2026-10-17): p50 ~49k, p90 ~66k, max ~109k.
106 ("taurusfi", "0x20861433d9119b866eeb398cb1ad46652a3cf953", 110_000u64),
107 // The Tempest router (unverified), per Titan's venue docs. Measured ~120k-155k
108 // (2026-09-11).
109 ("tempest", "0x00000003f1ec2379e79f58e12ec6c4f51ee92149", 160_000u64),
110 // The Goliath router, which the stream keys its books by. Gas over 80 traced fills
111 // (2026-10-19): p50 ~64k, p90 ~89k, max ~98k.
112 ("goliath", "0x4367985a63063fc970b009c6e599e9225181f551", 105_000u64),
113 // The Stelaxis router, which the stream keys its books by: a minimal proxy that emits
114 // the pAMM swap event. Gas over 72 traced fills (2026-10-19): p50 ~65k, p90 ~95k, max
115 // ~100k.
116 ("stelaxis", "0x77047af6cd8f7f84d96a020a2833d24916b75fde", 105_000u64),
117 // The ElZorro router, which the stream keys its books by: a minimal proxy that emits the
118 // pAMM swap event. Gas over 71 traced fills (2026-10-19): p50 ~35k, p90 ~68k, max ~97k.
119 ("elzorro", "0xcf211b4dd0d2be5c173ea57bcf938fc61d1d3bd3", 105_000u64),
120 ];
121 pamms
122 .into_iter()
123 .map(|(protocol, address, gas_cost)| {
124 PriceLevelStreamConfig::new(
125 protocol,
126 Bytes::from_str(address).expect("hardcoded pAMM address must parse"),
127 BigUint::from(gas_cost),
128 )
129 })
130 .collect()
131}
132
133/// The streamed venues known NOT to be executable through the generic executor, excluded from
134/// auto-detection via
135/// [`with_known_pamms`](super::stream::PriceLevelStreamBuilder::with_known_pamms): quoting them
136/// would advertise liquidity every routed swap reverts on. An
137/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) entry for one of these
138/// addresses overrides the denial.
139pub fn default_denied_pamms() -> Vec<Bytes> {
140 // No streamed venue is currently known to reject the executor's swap. This is where one
141 // goes that gates settlement — on a taker allowlist, say — or otherwise reverts a swap sent
142 // by an arbitrary caller.
143 Vec::new()
144}
145
146/// The streamed identities Titan streams some venues under, each paired with that venue's canonical
147/// public identity — the address a swap is sent to.
148///
149/// A streamed `quoteAddress` is a join key on Titan's streams, not necessarily an executable
150/// address. Where the two differ, the public identity is the executable one: it is what component
151/// ids, venue names, and the
152/// [`PAMM_ADDRESS_ATTRIBUTE`](super::stream::PAMM_ADDRESS_ATTRIBUTE) carry, and what
153/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) and
154/// [`deny_pamm`](super::stream::PriceLevelStreamBuilder::deny_pamm) are expected to name. Either
155/// address may be passed to those two, since both normalize through this table.
156///
157/// Venues absent from this table stream under their public identity, so they need no entry.
158pub const PAMM_ADDRESS_ALIASES: &[(&str, &str)] = &[
159 // Kipseli streams both its books and its overrides under 0xc9a9…, while its swaps go to the
160 // KipseliPropAMMWrapper router (0x71e7…) — the alias Titan's public taker docs publish, and
161 // the address `default_served_pamms` registers it under.
162 ("0xc9a956b5196dfe110debe8781857bc8b97d32091", "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d"),
163 // Metric streams its books under 0xe8447019…, which holds no swap entry point — it emits no
164 // pAMM swap event at all — while its swaps go to the router 0x99ab7c1c…, the address
165 // `default_served_pamms` registers it under.
166 //
167 // Metric streams a second key, 0x30a88bf8…, which also names 0x99ab7c1c… among the addresses
168 // it priced and quotes the same pairs from a different pricing instance. It is deliberately
169 // left unaliased: canonicalizing both onto one venue would give every shared pair two books
170 // per frame, and the duplicate rule keeps the last in stream order rather than the better
171 // price, so the served quote would swing arbitrarily between two makers. Its books are
172 // skipped and counted under `unregistered_pamm_entries_total` instead. Alias it only once
173 // there is a rule for choosing between two books of one pair.
174 ("0xe844701934d9c6085b292e428f41b911cc0b3872", "0x99ab7c1c5eab47801f7937075998527a550fba8a"),
175];
176
177/// [`PAMM_ADDRESS_ALIASES`] as a lookup, built once per process.
178static CANONICAL_PAMM_ADDRESSES: LazyLock<HashMap<Bytes, Bytes>> = LazyLock::new(|| {
179 PAMM_ADDRESS_ALIASES
180 .iter()
181 .map(|(streamed, public)| {
182 (
183 Bytes::from_str(streamed).expect("hardcoded streamed pAMM address must parse"),
184 Bytes::from_str(public).expect("hardcoded public pAMM address must parse"),
185 )
186 })
187 .collect()
188});
189
190/// The canonical public identity of the venue `address` names: the aliased address from
191/// [`PAMM_ADDRESS_ALIASES`], or `address` itself when no alias names it.
192///
193/// Idempotent — a public identity canonicalizes to itself — so normalizing an already
194/// canonical address is harmless.
195pub(super) fn canonical_pamm_address(address: &Bytes) -> Bytes {
196 CANONICAL_PAMM_ADDRESSES
197 .get(address)
198 .unwrap_or(address)
199 .clone()
200}
201
202#[cfg(test)]
203mod tests {
204 use super::*;
205
206 /// An alias exists to carry a streamed key onto an address a swap can be sent to, and
207 /// `default_served_pamms` is what makes that address a named venue. An alias pointing at an
208 /// address nothing registers therefore serves nothing: the books canonicalize onto a venue
209 /// the stream does not know, and are skipped as unregistered. That is how a venue goes dark
210 /// silently, so pin it.
211 #[test]
212 fn every_alias_points_at_a_registered_venue() {
213 let registered: Vec<Bytes> = default_served_pamms()
214 .into_iter()
215 .map(|config| config.address)
216 .collect();
217
218 for (streamed, public) in PAMM_ADDRESS_ALIASES {
219 let public = Bytes::from_str(public).expect("hardcoded public pAMM address");
220 assert!(
221 registered.contains(&public),
222 "the alias of {streamed} points at {public}, which no venue registers"
223 );
224 }
225 }
226
227 /// A streamed key and the public identity it aliases must differ, and no streamed key may be
228 /// registered as a venue: registering one would make the venue its own alias target and leave
229 /// the canonical address ambiguous.
230 #[test]
231 fn a_streamed_key_is_never_itself_a_registered_venue() {
232 let registered: Vec<Bytes> = default_served_pamms()
233 .into_iter()
234 .map(|config| config.address)
235 .collect();
236
237 for (streamed, public) in PAMM_ADDRESS_ALIASES {
238 let streamed = Bytes::from_str(streamed).expect("hardcoded streamed pAMM address");
239 assert_ne!(&streamed, &Bytes::from_str(public).expect("public"));
240 assert!(
241 !registered.contains(&streamed),
242 "{streamed} is both a streamed key and a registered venue"
243 );
244 }
245 }
246}