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 two venues 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 ~177k-182k (2026-08-18).
85 ("fermiswap", "0x5979458912f80b96d30d4220af8e2e4925a33320", 185_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 // Two venues without a public name, named by their address as auto-detection names them.
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 for the first, ~178k-262k (p50
124 // ~202k) for the second.
125 (
126 "0x6e27bb694393840e253262361b79187d4899e9cf",
127 "0x6e27bb694393840e253262361b79187d4899e9cf",
128 145_000u64,
129 ),
130 (
131 "0xf6d5b2fefec7b420d9990b95790adfd3d4c4f977",
132 "0xf6d5b2fefec7b420d9990b95790adfd3d4c4f977",
133 210_000u64,
134 ),
135 ];
136 pamms
137 .into_iter()
138 .map(|(protocol, address, gas_cost)| {
139 PriceLevelStreamConfig::new(
140 protocol,
141 Bytes::from_str(address).expect("hardcoded pAMM address must parse"),
142 BigUint::from(gas_cost),
143 )
144 })
145 .collect()
146}
147
148/// The streamed venues known NOT to be executable through the generic executor, excluded from
149/// auto-detection via
150/// [`with_known_pamms`](super::stream::PriceLevelStreamBuilder::with_known_pamms): quoting them
151/// would advertise liquidity every routed swap reverts on. An
152/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) entry for one of these
153/// addresses overrides the denial.
154pub fn default_denied_pamms() -> Vec<Bytes> {
155 // No streamed venue is currently known to reject the executor's swap. This is where one
156 // goes that gates settlement — on a taker allowlist, say — or otherwise reverts a swap sent
157 // by an arbitrary caller.
158 Vec::new()
159}
160
161/// The streamed identities Titan streams some venues under, each paired with that venue's canonical
162/// public identity — the address a swap is sent to.
163///
164/// A streamed `quoteAddress` is a join key on Titan's streams, not necessarily an executable
165/// address. Where the two differ, the public identity is the executable one: it is what component
166/// ids, venue names, and the
167/// [`PAMM_ADDRESS_ATTRIBUTE`](super::stream::PAMM_ADDRESS_ATTRIBUTE) carry, and what
168/// [`add_pamm`](super::stream::PriceLevelStreamBuilder::add_pamm) and
169/// [`deny_pamm`](super::stream::PriceLevelStreamBuilder::deny_pamm) are expected to name. Either
170/// address may be passed to those two, since both normalize through this table.
171///
172/// Venues absent from this table stream under their public identity, so they need no entry.
173pub const PAMM_ADDRESS_ALIASES: &[(&str, &str)] = &[
174 // Kipseli streams both its books and its overrides under 0xc9a9…, while its swaps go to the
175 // KipseliPropAMMWrapper router (0x71e7…) — the alias Titan's public taker docs publish, and
176 // the address `default_served_pamms` registers it under.
177 ("0xc9a956b5196dfe110debe8781857bc8b97d32091", "0x71e790dd841c8a9061487cb3e78c288e75ce0b3d"),
178 // Metric streams its books under 0xe8447019…, which holds no swap entry point — it emits no
179 // pAMM swap event at all — while its swaps go to the router 0x99ab7c1c…, the address
180 // `default_served_pamms` registers it under.
181 //
182 // Metric's router also reads the state of a second quote address, 0x30a88bf8…, which streams
183 // no books of its own (2026-10-21) but lists 0x99ab7c1c… in its quote stream entries'
184 // `pricedAddresses`. It is deliberately left unaliased. The overrides path merges its entries
185 // into Metric's own through `pricedAddresses`; aliased, they would count as Metric's own
186 // entries and replace rather than complete them. And any book it streamed in future would
187 // become a second book of the same pair, where the duplicate rule keeps the last in stream
188 // order rather than the better price.
189 ("0xe844701934d9c6085b292e428f41b911cc0b3872", "0x99ab7c1c5eab47801f7937075998527a550fba8a"),
190];
191
192/// [`PAMM_ADDRESS_ALIASES`] as a lookup, built once per process.
193static CANONICAL_PAMM_ADDRESSES: LazyLock<HashMap<Bytes, Bytes>> = LazyLock::new(|| {
194 PAMM_ADDRESS_ALIASES
195 .iter()
196 .map(|(streamed, public)| {
197 (
198 Bytes::from_str(streamed).expect("hardcoded streamed pAMM address must parse"),
199 Bytes::from_str(public).expect("hardcoded public pAMM address must parse"),
200 )
201 })
202 .collect()
203});
204
205/// The canonical public identity of the venue `address` names: the aliased address from
206/// [`PAMM_ADDRESS_ALIASES`], or `address` itself when no alias names it.
207///
208/// Idempotent — a public identity canonicalizes to itself — so normalizing an already
209/// canonical address is harmless.
210pub(super) fn canonical_pamm_address(address: &Bytes) -> Bytes {
211 CANONICAL_PAMM_ADDRESSES
212 .get(address)
213 .unwrap_or(address)
214 .clone()
215}
216
217#[cfg(test)]
218mod tests {
219 use super::*;
220
221 /// An alias exists to carry a streamed key onto an address a swap can be sent to, and
222 /// `default_served_pamms` is what makes that address a named venue. An alias pointing at an
223 /// address nothing registers therefore serves nothing: the books canonicalize onto a venue
224 /// the stream does not know, and are skipped as unregistered. That is how a venue goes dark
225 /// silently, so pin it.
226 #[test]
227 fn every_alias_points_at_a_registered_venue() {
228 let registered: Vec<Bytes> = default_served_pamms()
229 .into_iter()
230 .map(|config| config.address)
231 .collect();
232
233 for (streamed, public) in PAMM_ADDRESS_ALIASES {
234 let public = Bytes::from_str(public).expect("hardcoded public pAMM address");
235 assert!(
236 registered.contains(&public),
237 "the alias of {streamed} points at {public}, which no venue registers"
238 );
239 }
240 }
241
242 /// A streamed key and the public identity it aliases must differ, and no streamed key may be
243 /// registered as a venue: registering one would make the venue its own alias target and leave
244 /// the canonical address ambiguous.
245 #[test]
246 fn a_streamed_key_is_never_itself_a_registered_venue() {
247 let registered: Vec<Bytes> = default_served_pamms()
248 .into_iter()
249 .map(|config| config.address)
250 .collect();
251
252 for (streamed, public) in PAMM_ADDRESS_ALIASES {
253 let streamed = Bytes::from_str(streamed).expect("hardcoded streamed pAMM address");
254 assert_ne!(&streamed, &Bytes::from_str(public).expect("public"));
255 assert!(
256 !registered.contains(&streamed),
257 "{streamed} is both a streamed key and a registered venue"
258 );
259 }
260 }
261}