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-11-17): FermiSwap,
65/// Kipseli, Metric, Bebop, TaurusFi, Tempest, Goliath, Stelaxis, ElZorro, and one venue without a
66/// public name.
67///
68/// Registered on a builder via
69/// [`with_known_pamms`](super::stream::PriceLevelStreamBuilder::with_known_pamms), so their
70/// components carry the venue name instead of the raw address; an
71/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) call for one of these
72/// addresses overrides the corresponding entry.
73///
74/// Only the venues' router addresses are registered, because an entry here doubles as the
75/// execution target ([`PAMM_ADDRESS_ATTRIBUTE`](super::stream::PAMM_ADDRESS_ATTRIBUTE)): it must
76/// be an address a swap can be sent to. A venue whose streamed key is not that address is
77/// bridged by [`PAMM_ADDRESS_ALIASES`] rather than registered under the streamed key.
78pub fn default_served_pamms() -> Vec<PriceLevelStreamConfig> {
79 // The venues' `IPropAMM::swap` gas, calibrated by replaying real fills on the live venues at
80 // fresh-oracle blocks via `debug_traceCall`, plus a small headroom. Deliberately excludes
81 // router-level overhead (user/input/fee transfers): tycho-execution's gas estimator accounts
82 // for those on top of this per-swap value.
83 let pamms = [
84 // The FermiSwapper router. Measured ~47k-165k (2026-11-19).
85 ("fermiswap", "0xf6d5b2fefec7b420d9990b95790adfd3d4c4f977", 170_000u64),
86 // The KipseliPropAMMWrapper router. Measured ~308k-329k (2026-08-18). Titan's venue docs
87 // list a newer Kipseli router (0x342b8458…), which has no activity. The stream keys
88 // Kipseli's books by 0xc9a9… instead, which `PAMM_ADDRESS_ALIASES` maps onto this
89 // address.
90 ("kipseli", "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d", 335_000u64),
91 // The Metric router, per Titan's venue docs. It replaced 0xe715dc29…, which has had no
92 // activity since 2026-09-07. Titan's V2 socket streams Metric's books under
93 // 0xe8447019… instead, bridged by `PAMM_ADDRESS_ALIASES`. Its swap gas depends on the
94 // pair, so one value cannot fit all of them. Over 213 fills (2026-10-16), p50 was ~165k
95 // on USDC/USDT, ~245k on the WETH pairs and ~550k on WBTC/USDC; across all fills p50
96 // ~234k, p90 ~280k. This takes the p90: it overstates the stablecoin pair and
97 // understates WBTC/USDC.
98 ("metric", "0x99ab7c1c5eab47801f7937075998527a550fba8a", 280_000u64),
99 // The BopAMM (Bebop) router. It replaced 0xb09aaa56… on 2026-09-15, which has had no
100 // activity since. The bytecode is the same except for one embedded address, so the
101 // earlier measurement (~133k-136k, 2026-08-18) still applies.
102 ("bebop", "0xb09aaa8933626d7e4c48d65dad2d77021cfbca9a", 140_000u64),
103 // The TaurusFi router, which both sockets stream TaurusFi under: an ERC-1967 proxy that
104 // emits the pAMM swap event, so it needs no alias. It replaced 0x217d5893…, and in turn
105 // 0x3ce2672a… (tycho#1633), neither of which has had a swap in the last 7,200 blocks.
106 // Gas over 25 traced fills (2026-10-17): p50 ~49k, p90 ~66k, max ~109k.
107 ("taurusfi", "0x20861433d9119b866eeb398cb1ad46652a3cf953", 110_000u64),
108 // The Tempest router (unverified), per Titan's venue docs. Measured ~120k-155k
109 // (2026-09-11).
110 ("tempest", "0x00000003f1ec2379e79f58e12ec6c4f51ee92149", 160_000u64),
111 // The Goliath router, which the stream keys its books by. Gas over 80 traced fills
112 // (2026-10-19): p50 ~64k, p90 ~89k, max ~98k.
113 ("goliath", "0x4367985a63063fc970b009c6e599e9225181f551", 105_000u64),
114 // The Stelaxis router, which the stream keys its books by: a minimal proxy that emits
115 // the pAMM swap event. Gas over 72 traced fills (2026-10-19): p50 ~65k, p90 ~95k, max
116 // ~100k.
117 ("stelaxis", "0x77047af6cd8f7f84d96a020a2833d24916b75fde", 105_000u64),
118 // The ElZorro router, which the stream keys its books by: a minimal proxy that emits the
119 // pAMM swap event. Gas over 71 traced fills (2026-10-19): p50 ~35k, p90 ~68k, max ~97k.
120 ("elzorro", "0xcf211b4dd0d2be5c173ea57bcf938fc61d1d3bd3", 105_000u64),
121 // A venue without a public name, named by its address as auto-detection names it.
122 // Gas is the router call measured by the integration test over 2 days (2026-11-17) less
123 // the router overhead, not traced fills: ~124k-142k.
124 (
125 "0x6e27bb694393840e253262361b79187d4899e9cf",
126 "0x6e27bb694393840e253262361b79187d4899e9cf",
127 145_000u64,
128 ),
129 ];
130 pamms
131 .into_iter()
132 .map(|(protocol, address, gas_cost)| {
133 PriceLevelStreamConfig::new(
134 protocol,
135 Bytes::from_str(address).expect("hardcoded pAMM address must parse"),
136 BigUint::from(gas_cost),
137 )
138 })
139 .collect()
140}
141
142/// The streamed venues known NOT to be executable through the generic executor, excluded from
143/// auto-detection via
144/// [`with_known_pamms`](super::stream::PriceLevelStreamBuilder::with_known_pamms): quoting them
145/// would advertise liquidity every routed swap reverts on. An
146/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) entry for one of these
147/// addresses overrides the denial.
148pub fn default_denied_pamms() -> Vec<Bytes> {
149 let pamms = [
150 // Unnamed venue that settles only for callers on its own allowlist, which Tycho's routers
151 // are not on; reverts `NotWhitelisted()` for the TychoRouterV3 (2026-11-17).
152 "0xb8d4e06e3038b07b4376ba3020eabce69f673463",
153 // Metric's second quote address (see `PAMM_ADDRESS_ALIASES`), which now streams books of
154 // its own but is not a swap entry point: every swap sent to it reverts
155 // `FeedsLengthMismatch()` (6,518 of 6,518 integration test swaps, 2026-11-22). Denial
156 // only keeps its books out; its quote stream entries still complete Metric's overrides
157 // through `pricedAddresses`.
158 "0x30a88bf894d1b806125a23ebf23d715496fd7102",
159 // Unnamed venue whose simulation overrides include Metric's streamed state; every swap
160 // reverts `Dispatcher__SwapReverted` (7,920 of 7,920 integration test swaps, 2026-11-22).
161 "0x38e6f145586043a030d02f1aa32eb55c65183a1d",
162 ];
163 pamms
164 .into_iter()
165 .map(|address| Bytes::from_str(address).expect("hardcoded pAMM address must parse"))
166 .collect()
167}
168
169/// The streamed identities Titan streams some venues under, each paired with that venue's canonical
170/// public identity — the address a swap is sent to.
171///
172/// A streamed `quoteAddress` is a join key on Titan's streams, not necessarily an executable
173/// address. Where the two differ, the public identity is the executable one: it is what component
174/// ids, venue names, and the
175/// [`PAMM_ADDRESS_ATTRIBUTE`](super::stream::PAMM_ADDRESS_ATTRIBUTE) carry, and what
176/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) and
177/// [`deny_pamm`](super::stream::PriceLevelStreamBuilder::deny_pamm) are expected to name. Either
178/// address may be passed to those two, since both normalize through this table.
179///
180/// Venues absent from this table stream under their public identity, so they need no entry.
181pub const PAMM_ADDRESS_ALIASES: &[(&str, &str)] = &[
182 // Kipseli streams both its books and its overrides under 0xc9a9…, while its swaps go to the
183 // KipseliPropAMMWrapper router (0x71e7…) — the alias Titan's public taker docs publish, and
184 // the address `default_served_pamms` registers it under.
185 ("0xc9a956b5196dfe110debe8781857bc8b97d32091", "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d"),
186 // Metric streams its books under 0xe8447019…, which holds no swap entry point — it emits no
187 // pAMM swap event at all — while its swaps go to the router 0x99ab7c1c…, the address
188 // `default_served_pamms` registers it under.
189 //
190 // Metric's router also reads the state of a second quote address, 0x30a88bf8…, which lists
191 // 0x99ab7c1c… in its quote stream entries' `pricedAddresses`. It also streams books of its
192 // own (seen 2026-11-22), which `default_denied_pamms` keeps out. It is deliberately left
193 // unaliased. The overrides path merges its entries into Metric's own through
194 // `pricedAddresses`; aliased, they would count as Metric's own entries and replace rather than
195 // complete them. And any book it streamed in future would become a second book of the same
196 // pair, where the duplicate rule keeps the last in stream order rather than the better price.
197 ("0xe844701934d9c6085b292e428f41b911cc0b3872", "0x99ab7c1c5eab47801f7937075998527a550fba8a"),
198];
199
200/// [`PAMM_ADDRESS_ALIASES`] as a lookup, built once per process.
201static CANONICAL_PAMM_ADDRESSES: LazyLock<HashMap<Bytes, Bytes>> = LazyLock::new(|| {
202 PAMM_ADDRESS_ALIASES
203 .iter()
204 .map(|(streamed, public)| {
205 (
206 Bytes::from_str(streamed).expect("hardcoded streamed pAMM address must parse"),
207 Bytes::from_str(public).expect("hardcoded public pAMM address must parse"),
208 )
209 })
210 .collect()
211});
212
213/// The canonical public identity of the venue `address` names: the aliased address from
214/// [`PAMM_ADDRESS_ALIASES`], or `address` itself when no alias names it.
215///
216/// Idempotent — a public identity canonicalizes to itself — so normalizing an already
217/// canonical address is harmless.
218pub(super) fn canonical_pamm_address(address: &Bytes) -> Bytes {
219 CANONICAL_PAMM_ADDRESSES
220 .get(address)
221 .unwrap_or(address)
222 .clone()
223}
224
225#[cfg(test)]
226mod tests {
227 use super::*;
228
229 /// An alias exists to carry a streamed key onto an address a swap can be sent to, and
230 /// `default_served_pamms` is what makes that address a named venue. An alias pointing at an
231 /// address nothing registers therefore serves nothing: the books canonicalize onto a venue
232 /// the stream does not know, and are skipped as unregistered. That is how a venue goes dark
233 /// silently, so pin it.
234 #[test]
235 fn every_alias_points_at_a_registered_venue() {
236 let registered: Vec<Bytes> = default_served_pamms()
237 .into_iter()
238 .map(|config| config.address)
239 .collect();
240
241 for (streamed, public) in PAMM_ADDRESS_ALIASES {
242 let public = Bytes::from_str(public).expect("hardcoded public pAMM address");
243 assert!(
244 registered.contains(&public),
245 "the alias of {streamed} points at {public}, which no venue registers"
246 );
247 }
248 }
249
250 /// A streamed key and the public identity it aliases must differ, and no streamed key may be
251 /// registered as a venue: registering one would make the venue its own alias target and leave
252 /// the canonical address ambiguous.
253 #[test]
254 fn a_streamed_key_is_never_itself_a_registered_venue() {
255 let registered: Vec<Bytes> = default_served_pamms()
256 .into_iter()
257 .map(|config| config.address)
258 .collect();
259
260 for (streamed, public) in PAMM_ADDRESS_ALIASES {
261 let streamed = Bytes::from_str(streamed).expect("hardcoded streamed pAMM address");
262 assert_ne!(&streamed, &Bytes::from_str(public).expect("public"));
263 assert!(
264 !registered.contains(&streamed),
265 "{streamed} is both a streamed key and a registered venue"
266 );
267 }
268 }
269}