tycho_simulation/evm/stream.rs
1//! Builder for configuring a multi-protocol stream.
2//!
3//! Provides a builder for creating a multi-protocol stream that produces
4//! protocol state update messages. It runs one synchronization worker per protocol
5//! and a supervisor that aggregates updates, ensuring gap‑free streaming
6//! and robust state tracking.
7//!
8//! ## Context
9//!
10//! This stream wraps a `TychoStream` from `tycho-client`. It decodes `FeedMessage`s
11//! into protocol state updates. Internally, each protocol runs in its own
12//! synchronization worker, and a supervisor aggregates their messages per block.
13//!
14//! ### Protocol Synchronization Worker
15//! A synchronization worker runs the snapshot + delta protocol from `tycho-indexer`.
16//! - It first downloads components and their snapshots.
17//! - It then streams deltas.
18//! - It reacts to new or paused components by pulling snapshots or removing them from the active
19//! set.
20//!
21//! Each worker emits snapshots and deltas to the supervisor.
22//!
23//! ### Stream Supervisor
24//! The supervisor aggregates worker messages by block and assigns sync status.
25//! - It ensures workers produce gap-free messages.
26//! - It flags late workers as `Delayed`, and marks them `Stale` if they exceed `max_missed_blocks`.
27//! - It marks workers with terminal errors as `Ended`.
28//!
29//! Aggregating by block adds small latency, since the supervisor waits briefly for
30//! all workers to emit. This latency only applies to workers in `Ready` or `Delayed`.
31//!
32//! The stream ends only when **all** workers are `Stale` or `Ended`.
33//!
34//! ## Configuration
35//!
36//! The builder lets you customize:
37//!
38//! ### Protocols
39//! Select which protocols to synchronize.
40//!
41//! ### Tokens & Minimum Token Quality
42//! Provide token metadata up front so the decoder can initialize protocol states from startup
43//! snapshots. `set_tokens` does not act as an ongoing filter — components arriving after startup
44//! include their own token metadata. To restrict processing to specific tokens, apply that filter
45//! in your consumer when reading `new_components`. New tokens arriving via stream deltas are added
46//! automatically when their quality exceeds `min_token_quality`.
47//!
48//! ### StreamEndPolicy
49//! Control when the stream ends based on worker states. By default, it ends when all
50//! workers are `Stale` or `Ended`.
51//!
52//! ## Stream
53//! The stream emits one protocol state update every `block_time`. Each update
54//! reports protocol synchronization states and any changes.
55//!
56//! The `new_components` field lists newly deployed components and their tokens.
57//!
58//! The stream aims to run indefinitely. Internal retry and reconnect logic handle
59//! most errors, so users should rarely need to restart it manually.
60//!
61//! ## Example
62//! ```no_run
63//! use tycho_common::models::Chain;
64//! use tycho_simulation::evm::stream::ProtocolStreamBuilder;
65//! use tycho_simulation::utils::load_all_tokens;
66//! use futures::StreamExt;
67//! use tycho_client::feed::component_tracker::ComponentFilter;
68//! use tycho_simulation::evm::protocol::uniswap_v2::state::UniswapV2State;
69//!
70//! #[tokio::main]
71//! async fn main() {
72//! let all_tokens = load_all_tokens(
73//! "tycho-beta.propellerheads.xyz",
74//! false,
75//! Some("sampletoken"),
76//! true,
77//! Chain::Ethereum,
78//! None,
79//! None,
80//! )
81//! .await
82//! .expect("Failed loading tokens");
83//!
84//! let protocol_stream =
85//! ProtocolStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum)
86//! .auth_key(Some("sampletoken".to_string()))
87//! .skip_state_decode_failures(true)
88//! .exchange::<UniswapV2State>(
89//! "uniswap_v2", ComponentFilter::with_tvl_range(5.0, 10.0), None
90//! )
91//! .set_tokens(all_tokens)
92//! .await
93//! .build()
94//! .await
95//! .expect("Failed building protocol stream");
96//! tokio::pin!(protocol_stream);
97//!
98//! // Loop through block updates
99//! while let Some(msg) = protocol_stream.next().await {
100//! dbg!(msg).expect("failed decoding");
101//! }
102//! }
103//! ```
104use std::{
105 collections::{HashMap, HashSet},
106 sync::Arc,
107 time,
108};
109
110use futures::{future::Either, Stream, StreamExt};
111use tokio_stream::wrappers::ReceiverStream;
112use tracing::{debug, error, warn};
113use tycho_client::{
114 feed::{
115 component_tracker::ComponentFilter, synchronizer::ComponentWithState, BlockHeader,
116 BlockSynchronizerError, FeedMessage, SynchronizerState,
117 },
118 stream::{RetryConfiguration, StreamError, TychoStreamBuilder},
119};
120use tycho_common::{
121 models::{token::Token, Chain},
122 simulation::protocol_sim::ProtocolSim,
123 traits::TxDeltaIndexer,
124 Bytes,
125};
126
127use crate::{
128 evm::{
129 decoder::{StreamDecodeError, TychoStreamDecoder},
130 override_stream::{self, StateOverrideProvider},
131 pending::PendingBlockProcessor,
132 protocol::{
133 filters::uniswap_v4_non_angstrom_hook_pool_filter,
134 native_wrapper::state::NativeWrapperState,
135 uniswap_v4::hooks::hook_handler_creator::initialize_hook_handlers,
136 },
137 },
138 protocol::{
139 errors::InvalidSnapshotError,
140 models::{DecoderContext, TryFromWithBlock, Update},
141 },
142 utils::default_blocklist,
143};
144
145const EXCHANGES_REQUIRING_FILTER: [&str; 5] =
146 ["vm:balancer_v2", "fluid_v1", "erc4626", "ekubo_v3", "vm:curve"];
147
148/// The client-side filter exchange `name` always gets, in addition to any filter the caller
149/// provides.
150///
151/// `uniswap_v4_hooks`: without `ANGSTROM_API_KEY`, Angstrom swaps cannot be encoded (they carry
152/// per-block attestations from the Angstrom API), so Angstrom pools are excluded up front rather
153/// than failing every route that selects them at encoding time. A caller's own hook filter does
154/// not replace this one: the encoder still has no key.
155fn mandatory_filter_fn(name: &str) -> Option<fn(&ComponentWithState) -> bool> {
156 if name == "uniswap_v4_hooks" && std::env::var("ANGSTROM_API_KEY").is_err() {
157 warn!(
158 "ANGSTROM_API_KEY is not set: excluding Angstrom pools from '{name}'. \
159 Set the key to include them."
160 );
161 return Some(uniswap_v4_non_angstrom_hook_pool_filter);
162 }
163 None
164}
165
166#[derive(Default, Debug, Clone, Copy)]
167pub enum StreamEndPolicy {
168 /// End stream if all states are Stale or Ended (default)
169 #[default]
170 AllEndedOrStale,
171 /// End stream if any protocol ended
172 AnyEnded,
173 /// End stream if any protocol ended or is stale
174 AnyEndedOrStale,
175 /// End stream if any protocol is stale
176 AnyStale,
177}
178
179impl StreamEndPolicy {
180 fn should_end<'a>(&self, states: impl IntoIterator<Item = &'a SynchronizerState>) -> bool {
181 let mut it = states.into_iter();
182 match self {
183 StreamEndPolicy::AllEndedOrStale => false,
184 StreamEndPolicy::AnyEnded => it.any(|s| matches!(s, SynchronizerState::Ended(_))),
185 StreamEndPolicy::AnyStale => it.any(|s| matches!(s, SynchronizerState::Stale(_))),
186 StreamEndPolicy::AnyEndedOrStale => {
187 it.any(|s| matches!(s, SynchronizerState::Stale(_) | SynchronizerState::Ended(_)))
188 }
189 }
190 }
191}
192
193/// Handle returned by [`ProtocolStreamBuilder::with_step_controller`] that gives external
194/// control over when each buffered block is released for decoding.
195///
196/// Intended for complex test scenarios where the caller needs to observe what the next
197/// block contains before allowing the decoder pipeline to process it.
198///
199/// ## Drop behaviour
200///
201/// Dropping this controller ungates the stream: the gating task detects the closed trigger
202/// channel, forwards the currently-buffered block (if any), then continues passing subsequent
203/// blocks through without waiting for triggers — exactly as if step-control had never been
204/// enabled. The stream runs to its natural end.
205pub struct BlockStepController {
206 /// Sends a trigger signal to release the next buffered block.
207 trigger_tx: tokio::sync::mpsc::UnboundedSender<()>,
208 /// Watch channel containing the next buffered raw message, or `None` if no block is pending.
209 peek_rx: tokio::sync::watch::Receiver<Option<FeedMessage<BlockHeader>>>,
210}
211
212impl BlockStepController {
213 /// Releases the next buffered block for decoding and emission.
214 ///
215 /// Returns an error if the stream has already ended and the sender is disconnected.
216 pub fn trigger_next_block(&self) -> Result<(), tokio::sync::mpsc::error::SendError<()>> {
217 // Send a unit value on the trigger channel to unblock the gating task.
218 self.trigger_tx.send(())
219 }
220
221 /// Returns the currently buffered block immediately, or `None` if no block is buffered yet.
222 pub fn try_peek_next_block(&self) -> Option<FeedMessage<BlockHeader>> {
223 self.peek_rx.borrow().clone()
224 }
225
226 /// Waits until a block is buffered and returns it without consuming it.
227 ///
228 /// Returns `None` only if the stream has ended and no further blocks will arrive.
229 /// If a block is already buffered when this is called, it returns immediately.
230 pub async fn peek_next_block(&self) -> Option<FeedMessage<BlockHeader>> {
231 // Clone so we don't hold a mutable borrow on self; wait_for checks the current
232 // value first, so this returns immediately if a block is already present.
233 let mut rx = self.peek_rx.clone();
234 let guard = rx
235 .wait_for(|v| v.is_some())
236 .await
237 .ok()?;
238 guard.clone()
239 }
240}
241
242/// Protocol system family of components routed through tycho-execution's fallback router.
243pub const FALLBACK_PROTOCOL_FAMILY: &str = "fallback";
244
245/// Builds and configures the multi protocol stream described in the [module-level docs](self).
246///
247/// See the module documentation for details on protocols, configuration options, and
248/// stream behavior.
249pub struct ProtocolStreamBuilder {
250 decoder: TychoStreamDecoder<BlockHeader>,
251 stream_builder: TychoStreamBuilder,
252 stream_end_policy: StreamEndPolicy,
253 chain: Chain,
254 pending_indexers: HashMap<String, Box<dyn TxDeltaIndexer>>,
255 /// Watch sender used to publish the currently-buffered raw block so the controller can peek
256 /// at it before triggering. `Some` iff step-control mode is active.
257 step_peek_tx: Option<tokio::sync::watch::Sender<Option<FeedMessage<BlockHeader>>>>,
258 /// Receiver half of the trigger channel. Held here until `build()` / `build_with_pending()`
259 /// transfers ownership to the gating task. `Some` iff step-control mode is active.
260 step_trigger_rx: Option<tokio::sync::mpsc::UnboundedReceiver<()>>,
261 /// State-override providers explicitly registered by the consumer, keyed by `protocol_system`.
262 /// These take precedence over the built-in default registry and are installed onto the decoder
263 /// at build time.
264 override_providers: HashMap<String, Arc<dyn StateOverrideProvider>>,
265 /// Names of all exchanges registered on the builder, used to decide which built-in override
266 /// providers to auto-register at build time.
267 registered_exchanges: HashSet<String>,
268 /// Exchanges whose components are published as `fallback:{name}`, checked against
269 /// `registered_exchanges` at build time.
270 fallback_router_venues: HashSet<String>,
271}
272
273impl ProtocolStreamBuilder {
274 /// Creates a new builder for a multi-protocol stream.
275 ///
276 /// The shipped pool blocklist is applied by default, excluding components known to break
277 /// simulation. Use [`blocklist_components`](Self::blocklist_components) to exclude additional
278 /// components.
279 ///
280 /// See the [module-level docs](self) for full details on stream behavior and configuration.
281 pub fn new(tycho_url: &str, chain: Chain) -> Self {
282 Self {
283 decoder: TychoStreamDecoder::new(chain),
284 stream_builder: TychoStreamBuilder::new(tycho_url, chain)
285 .blocklisted_ids(default_blocklist()),
286 stream_end_policy: StreamEndPolicy::default(),
287 chain,
288 pending_indexers: HashMap::new(),
289 step_peek_tx: None,
290 step_trigger_rx: None,
291 override_providers: HashMap::new(),
292 registered_exchanges: HashSet::new(),
293 fallback_router_venues: HashSet::new(),
294 }
295 }
296
297 /// Adds a specific exchange to the stream.
298 ///
299 /// This configures the builder to include a new protocol synchronizer for `name`,
300 /// filtering its components according to `filter` and optionally `filter_fn`.
301 ///
302 /// The type parameter `T` specifies the decoder type for this exchange. All
303 /// component states for this exchange will be decoded into instances of `T`.
304 ///
305 /// # Parameters
306 ///
307 /// - `name`: The protocol or exchange name (e.g., `"uniswap_v4"`, `"vm:balancer_v2"`).
308 /// - `filter`: Defines the set of components to include in the stream.
309 /// - `filter_fn`: Optional custom filter function for client-side filtering of components not
310 /// expressible in `filter`.
311 ///
312 /// # Notes
313 ///
314 /// For certain protocols (e.g., `"uniswap_v4"`, `"vm:balancer_v2"`, `"vm:curve"`), omitting
315 /// `filter_fn` may cause decoding errors or incorrect results. In these cases, a proper
316 /// filter function is required to ensure correct decoding and quoting logic.
317 pub fn exchange<T>(
318 mut self,
319 name: &str,
320 filter: ComponentFilter,
321 filter_fn: Option<fn(&ComponentWithState) -> bool>,
322 ) -> Self
323 where
324 T: ProtocolSim
325 + TryFromWithBlock<ComponentWithState, BlockHeader, Error = InvalidSnapshotError>
326 + Send
327 + 'static,
328 {
329 self.stream_builder = self
330 .stream_builder
331 .exchange(name, filter);
332 self.registered_exchanges
333 .insert(name.to_string());
334 self.decoder.register_decoder::<T>(name);
335 if let Some(predicate) = filter_fn {
336 self.decoder
337 .register_filter(name, predicate);
338 }
339 if let Some(predicate) = mandatory_filter_fn(name) {
340 self.decoder
341 .register_filter(name, predicate);
342 }
343
344 if EXCHANGES_REQUIRING_FILTER.contains(&name) && filter_fn.is_none() {
345 warn!(
346 "Warning: For exchange type '{}', it is necessary to set a filter function because not all pools are supported. See all filters at src/evm/protocol/filters.rs",
347 name
348 );
349 }
350
351 self
352 }
353
354 /// Publishes `name`'s components as `fallback:{name}`, so swaps on them are encoded for
355 /// tycho-execution's fallback router: it quotes the venue on-chain and, when the venue
356 /// quotes worse or reverts, runs the fallback pool the solver names in `user_data`.
357 ///
358 /// For natively indexed `IPropAMM` venues (e.g. `"biconomy"`). The components keep their id
359 /// and state; a stream publishes each venue on one path only. `build` fails when `name` is
360 /// not a registered exchange.
361 pub fn via_fallback_router(mut self, name: &str) -> Self {
362 self.fallback_router_venues
363 .insert(name.to_string());
364 self
365 }
366
367 /// Labels the components of every `via_fallback_router` venue on the decoder.
368 ///
369 /// # Errors
370 ///
371 /// `SetUpError` naming the first venue that is not a registered exchange: its components
372 /// would otherwise keep their own protocol system and skip the fallback router.
373 fn install_fallback_router_labels(&mut self) -> Result<(), StreamError> {
374 for name in &self.fallback_router_venues {
375 if !self.registered_exchanges.contains(name) {
376 return Err(StreamError::SetUpError(format!(
377 "via_fallback_router({name}): no exchange is registered under this name"
378 )));
379 }
380 self.decoder
381 .label_components(name, format!("{FALLBACK_PROTOCOL_FAMILY}:{name}"));
382 }
383 Ok(())
384 }
385
386 /// Adds a specific exchange to the stream with decoder context.
387 ///
388 /// This configures the builder to include a new protocol synchronizer for `name`,
389 /// filtering its components according to `filter` and optionally `filter_fn`. It also registers
390 /// the DecoderContext (this is useful to test protocols that are not live yet)
391 ///
392 /// The type parameter `T` specifies the decoder type for this exchange. All
393 /// component states for this exchange will be decoded into instances of `T`.
394 ///
395 /// # Parameters
396 ///
397 /// - `name`: The protocol or exchange name (e.g., `"uniswap_v4"`, `"vm:balancer_v2"`).
398 /// - `filter`: Defines the set of components to include in the stream.
399 /// - `filter_fn`: Optional custom filter function for client-side filtering of components not
400 /// expressible in `filter`.
401 /// - `decoder_context`: The decoder context for this exchange
402 ///
403 /// # Notes
404 ///
405 /// For certain protocols (e.g., `"uniswap_v4"`, `"vm:balancer_v2"`, `"vm:curve"`), omitting
406 /// `filter_fn` may cause decoding errors or incorrect results. In these cases, a proper
407 /// filter function is required to ensure correct decoding and quoting logic.
408 pub fn exchange_with_decoder_context<T>(
409 mut self,
410 name: &str,
411 filter: ComponentFilter,
412 filter_fn: Option<fn(&ComponentWithState) -> bool>,
413 decoder_context: DecoderContext,
414 ) -> Self
415 where
416 T: ProtocolSim
417 + TryFromWithBlock<ComponentWithState, BlockHeader, Error = InvalidSnapshotError>
418 + Send
419 + 'static,
420 {
421 self.stream_builder = self
422 .stream_builder
423 .exchange(name, filter);
424 self.registered_exchanges
425 .insert(name.to_string());
426 self.decoder
427 .register_decoder_with_context::<T>(name, decoder_context);
428 if let Some(predicate) = filter_fn {
429 self.decoder
430 .register_filter(name, predicate);
431 }
432 if let Some(predicate) = mandatory_filter_fn(name) {
433 self.decoder
434 .register_filter(name, predicate);
435 }
436
437 if EXCHANGES_REQUIRING_FILTER.contains(&name) && filter_fn.is_none() {
438 warn!(
439 "Warning: For exchange type '{}', it is necessary to set a filter function because not all pools are supported. See all filters at src/evm/protocol/filters.rs",
440 name
441 );
442 }
443
444 self
445 }
446
447 /// Sets the block time interval for the stream.
448 ///
449 /// This controls how often the stream produces updates.
450 pub fn block_time(mut self, block_time: u64) -> Self {
451 self.stream_builder = self
452 .stream_builder
453 .block_time(block_time);
454 self
455 }
456
457 /// Sets the network operation timeout (deprecated).
458 ///
459 /// Use [`latency_buffer()`](Self::latency_buffer) instead for controlling latency.
460 /// This method is retained for backwards compatibility.
461 #[deprecated = "Use latency_buffer instead"]
462 pub fn timeout(mut self, timeout: u64) -> Self {
463 self.stream_builder = self.stream_builder.timeout(timeout);
464 self
465 }
466
467 /// Sets the latency buffer to aggregate same-block messages.
468 ///
469 /// This allows the supervisor to wait a short interval for all synchronizers to emit
470 /// before aggregating.
471 pub fn latency_buffer(mut self, timeout: u64) -> Self {
472 self.stream_builder = self.stream_builder.timeout(timeout);
473 self
474 }
475
476 /// Sets the maximum number of blocks a synchronizer may miss before being marked as `Stale`.
477 pub fn max_missed_blocks(mut self, n: u64) -> Self {
478 self.stream_builder = self.stream_builder.max_missed_blocks(n);
479 self
480 }
481
482 /// Sets how long a synchronizer may take to process the initial message.
483 ///
484 /// Useful for data-intensive protocols where startup decoding takes longer.
485 pub fn startup_timeout(mut self, timeout: time::Duration) -> Self {
486 self.stream_builder = self
487 .stream_builder
488 .startup_timeout(timeout);
489 self
490 }
491
492 /// Configures the stream to exclude state updates.
493 ///
494 /// This reduces bandwidth and decoding workload if protocol state is not of
495 /// interest (e.g. only process new tokens).
496 pub fn no_state(mut self, no_state: bool) -> Self {
497 self.stream_builder = self.stream_builder.no_state(no_state);
498 self
499 }
500
501 /// Sets the API key for authenticating with the Tycho server.
502 pub fn auth_key(mut self, auth_key: Option<String>) -> Self {
503 self.stream_builder = self.stream_builder.auth_key(auth_key);
504 self
505 }
506
507 /// Adds client-metadata entries forwarded to the server in the `X-Tycho-Client-Metadata`
508 /// header.
509 ///
510 /// See [`TychoStreamBuilder::add_client_metadata`]. Values are self-reported and may surface in
511 /// the server's metrics and logs — do not include secrets or personally identifiable
512 /// information.
513 pub fn add_client_metadata<I, K, V>(mut self, metadata: I) -> Self
514 where
515 I: IntoIterator<Item = (K, V)>,
516 K: Into<String>,
517 V: Into<String>,
518 {
519 self.stream_builder = self
520 .stream_builder
521 .add_client_metadata(metadata);
522 self
523 }
524
525 /// Disables TLS/ SSL for the connection, using http and ws protocols.
526 ///
527 /// This is not recommended for production use.
528 pub fn no_tls(mut self, no_tls: bool) -> Self {
529 self.stream_builder = self.stream_builder.no_tls(no_tls);
530 self
531 }
532
533 /// Disable compression for the connection.
534 pub fn disable_compression(mut self) -> Self {
535 self.stream_builder = self
536 .stream_builder
537 .disable_compression();
538 self
539 }
540
541 /// Enables partial block updates (flashblocks).
542 pub fn enable_partial_blocks(mut self) -> Self {
543 self.stream_builder = self
544 .stream_builder
545 .enable_partial_blocks();
546 self
547 }
548
549 /// Sets the number of deltas buffered for each underlying Tycho WebSocket subscription.
550 ///
551 /// See [`TychoStreamBuilder::subscription_buffer_size`].
552 pub fn subscription_buffer_size(mut self, subscription_buffer_size: usize) -> Self {
553 self.stream_builder = self
554 .stream_builder
555 .subscription_buffer_size(subscription_buffer_size);
556 self
557 }
558
559 /// Exclude additional component IDs from all registered exchanges.
560 ///
561 /// These IDs are added to the shipped blocklist that is already applied by default (see
562 /// [`new`](Self::new)).
563 pub fn blocklist_components(mut self, ids: HashSet<String>) -> Self {
564 if !ids.is_empty() {
565 tracing::info!("Blocklisting {} components", ids.len());
566 self.stream_builder = self.stream_builder.blocklisted_ids(ids);
567 }
568 self
569 }
570
571 /// Sets the stream end policy.
572 ///
573 /// Controls when the stream should stop based on synchronizer states.
574 ///
575 /// ## Note
576 /// The stream always ends latest if all protocols are stale or ended independent of
577 /// this configuration. This allows you to end the stream earlier than that.
578 ///
579 /// See [self::StreamEndPolicy] for possible configuration options.
580 pub fn stream_end_policy(mut self, stream_end_policy: StreamEndPolicy) -> Self {
581 self.stream_end_policy = stream_end_policy;
582 self
583 }
584
585 /// Provides token metadata used to decode startup snapshots and initialize protocol states.
586 ///
587 /// This is not a stream filter — components arriving after startup include their own token
588 /// metadata. To restrict to specific tokens, filter in your consumer logic. New tokens
589 /// arriving via stream deltas are added automatically if they meet the quality threshold.
590 pub async fn set_tokens(self, tokens: HashMap<Bytes, Token>) -> Self {
591 self.decoder.set_tokens(tokens).await;
592 self
593 }
594
595 /// Skips decoding errors for component state updates.
596 ///
597 /// Allows the stream to continue processing even if some states fail to decode,
598 /// logging a warning instead of panicking.
599 pub fn skip_state_decode_failures(mut self, skip: bool) -> Self {
600 self.decoder
601 .skip_state_decode_failures(skip);
602 self
603 }
604
605 /// Sets the minimum token quality for tokens added via the stream.
606 ///
607 /// Tokens arriving in stream deltas below this threshold are ignored. Defaults to 100.
608 /// Set this to the same value used in [`load_all_tokens()`](crate::utils::load_all_tokens) to
609 /// apply consistent filtering.
610 pub fn min_token_quality(mut self, quality: u32) -> Self {
611 self.decoder.min_token_quality(quality);
612 self
613 }
614
615 /// Configures the retry policy for websocket reconnects.
616 pub fn websocket_retry_config(mut self, config: &RetryConfiguration) -> Self {
617 self.stream_builder = self
618 .stream_builder
619 .websockets_retry_config(config);
620 self
621 }
622
623 /// Configures the retry policy for state synchronization.
624 pub fn state_synchronizer_retry_config(mut self, config: &RetryConfiguration) -> Self {
625 self.stream_builder = self
626 .stream_builder
627 .state_synchronizer_retry_config(config);
628 self
629 }
630
631 /// Sets the maximum random delay before a restarted synchronizer requests a snapshot.
632 ///
633 /// Defaults to 60 seconds. A `jitter` below 5 seconds is raised to 5 seconds.
634 pub fn snapshot_jitter(mut self, jitter: time::Duration) -> Self {
635 self.stream_builder = self
636 .stream_builder
637 .snapshot_jitter(jitter);
638 self
639 }
640
641 pub fn get_decoder(&self) -> &TychoStreamDecoder<BlockHeader> {
642 &self.decoder
643 }
644
645 /// Registers a [`TxDeltaIndexer`] for ephemeral pending-block simulation.
646 ///
647 /// `protocol_system` is the protocol system of the indexer's components, which is also the
648 /// exchange name (e.g. `"uniswap_v3"`). The indexer's account deltas reach only pools of that
649 /// protocol system, so the indexer must emit the writes to every account those pools read. Use
650 /// [`build_with_pending`](Self::build_with_pending) to obtain both the confirmed stream and
651 /// the pending processor.
652 ///
653 /// The exchange must decode into a state whose `delta_transition` can rebuild it from the
654 /// `state_deltas` the indexer produces, because
655 /// [`apply_deltas_ephemeral`](crate::evm::decoder::TychoStreamDecoder::apply_deltas_ephemeral)
656 /// writes nothing to the VM database. Native and hybrid states qualify; the generic VM adapter
657 /// does not, because it re-reads pool state from the VM database — an indexer registered for
658 /// one still gets its balance and block-environment attributes applied, but every
659 /// storage-derived value stays at the confirmed block, with no error.
660 #[expect(
661 clippy::unnecessary_wraps,
662 reason = "public API; changing the signature is a breaking change"
663 )]
664 pub fn with_pending_indexer(
665 mut self,
666 protocol_system: &str,
667 indexer: Box<dyn TxDeltaIndexer>,
668 ) -> Result<Self, StreamError> {
669 self.pending_indexers
670 .insert(protocol_system.to_string(), indexer);
671 Ok(self)
672 }
673
674 /// Enables controlled-step mode for testing.
675 ///
676 /// Returns a [`BlockStepController`] that lets the caller decide when each buffered block
677 /// is released for decoding. Call this before [`build`](Self::build) or
678 /// [`build_with_pending`](Self::build_with_pending) — both detect and wire up the gating
679 /// automatically.
680 ///
681 /// In production code, do not call this method; the stream runs at full speed.
682 pub fn with_step_controller(mut self) -> (Self, BlockStepController) {
683 let (trigger_tx, trigger_rx) = tokio::sync::mpsc::unbounded_channel::<()>();
684 let (peek_tx, peek_rx) =
685 tokio::sync::watch::channel::<Option<FeedMessage<BlockHeader>>>(None);
686
687 self.step_peek_tx = Some(peek_tx);
688 self.step_trigger_rx = Some(trigger_rx);
689
690 let controller = BlockStepController { trigger_tx, peek_rx };
691 (self, controller)
692 }
693
694 /// Spawns a background task that gates `FeedMessage` delivery.
695 ///
696 /// The task buffers each incoming message, publishes it to `peek_tx` so the
697 /// [`BlockStepController`] can inspect it, waits for a trigger, then forwards the message to
698 /// `output_tx` for the decode pipeline. If `advance_tx` is `Some`, a clone of the message is
699 /// also forwarded there (used by the pending-processor path) before the decode step.
700 /// When the input channel closes or a terminal error is received according to
701 /// `stream_end_policy`, the task exits and all output channels are dropped.
702 fn run_gating_task(
703 raw_rx: tokio::sync::mpsc::Receiver<
704 Result<FeedMessage<BlockHeader>, BlockSynchronizerError>,
705 >,
706 mut trigger_rx: tokio::sync::mpsc::UnboundedReceiver<()>,
707 peek_tx: tokio::sync::watch::Sender<Option<FeedMessage<BlockHeader>>>,
708 output_tx: tokio::sync::mpsc::Sender<FeedMessage<BlockHeader>>,
709 stream_end_policy: StreamEndPolicy,
710 ) {
711 tokio::spawn(async move {
712 let mut raw_stream = ReceiverStream::new(raw_rx);
713 loop {
714 let msg = match raw_stream.next().await {
715 Some(Ok(msg)) => msg,
716 Some(Err(e)) => {
717 error!("Block stream ended with terminal error: {e}");
718 break;
719 }
720 None => break,
721 };
722
723 if stream_end_policy.should_end(msg.sync_states.values()) {
724 error!(
725 "Block stream ended due to {:?}: {:?}",
726 stream_end_policy, msg.sync_states
727 );
728 break;
729 }
730
731 // Publish the buffered message so the caller can peek before triggering.
732 #[expect(
733 clippy::let_underscore_must_use,
734 reason = "the peek slot is optional; a send error only means the controller dropped its receiver"
735 )]
736 let _ = peek_tx.send(Some(msg.clone()));
737
738 // Block until the controller fires trigger_next_block(), or until it is dropped.
739 if trigger_rx.recv().await.is_none() {
740 // Controller dropped — forward the buffered message and drain the rest
741 // without gating, so the stream continues to its natural end.
742 #[expect(
743 clippy::let_underscore_must_use,
744 reason = "the peek slot is optional; a send error only means the controller dropped its receiver"
745 )]
746 let _ = peek_tx.send(None);
747 if output_tx.send(msg).await.is_err() {
748 break;
749 }
750 while let Some(item) = raw_stream.next().await {
751 let Ok(msg) = item else { break };
752 if stream_end_policy.should_end(msg.sync_states.values()) {
753 break;
754 }
755 if output_tx.send(msg).await.is_err() {
756 break;
757 }
758 }
759 break;
760 }
761
762 // Clear the peek slot before decoding so callers see None between blocks.
763 #[expect(
764 clippy::let_underscore_must_use,
765 reason = "the peek slot is optional; a send error only means the controller dropped its receiver"
766 )]
767 let _ = peek_tx.send(None);
768
769 if output_tx.send(msg).await.is_err() {
770 break;
771 }
772 }
773 });
774 }
775
776 /// Registers `provider` as the live override source for `protocol_system`.
777 ///
778 /// Explicit registrations take precedence over the built-in default registry, so this is how
779 /// you swap a venue (e.g. `vm:bopamm`) onto a different provider. Registering the same provider
780 /// for several protocols is cheap — it is shared via `Arc`, not duplicated.
781 pub fn with_override_provider(
782 mut self,
783 protocol_system: impl Into<String>,
784 provider: Arc<dyn StateOverrideProvider>,
785 ) -> Self {
786 self.override_providers
787 .insert(protocol_system.into(), provider);
788 self
789 }
790
791 /// Installs override providers onto the decoder before the stream is built.
792 ///
793 /// Explicit consumer registrations win; the built-in default registry (see
794 /// [`default_override_providers`](crate::evm::override_stream::default_override_providers))
795 /// then fills every remaining protocol it can serve.
796 fn install_override_providers(&mut self) {
797 let explicit = std::mem::take(&mut self.override_providers);
798 // Protocols eligible for a built-in default provider: registered exchanges not explicitly
799 // overridden by the consumer.
800 let uncovered = self
801 .registered_exchanges
802 .clone()
803 .into_iter()
804 .filter(|exchange| !explicit.contains_key(exchange));
805 let defaults = override_stream::default_override_providers(uncovered);
806 for (protocol_system, provider) in defaults.into_iter().chain(explicit) {
807 self.decoder
808 .set_override_provider(protocol_system, provider);
809 }
810 }
811
812 /// Builds the confirmed protocol stream and a [`PendingBlockProcessor`] that stays
813 /// in sync with it automatically.
814 ///
815 /// The stream pipeline forwards every confirmed [`FeedMessage`] to the processor via an
816 /// internal unbounded channel — it never blocks waiting for the consumer. The consumer
817 /// owns the returned `PendingBlockProcessor` exclusively and may wrap it in whatever
818 /// synchronisation primitive suits their use case (e.g. `Mutex` for shared access,
819 /// nothing for single-threaded use).
820 ///
821 /// Call [`generate_pending_update`](PendingBlockProcessor::generate_pending_update) to
822 /// simulate a candidate bundle; it drains the channel automatically before computing.
823 ///
824 /// Warns once for each pending indexer whose protocol system is not a registered exchange:
825 /// its deltas reach no pool.
826 pub async fn build_with_pending(
827 mut self,
828 ) -> Result<
829 (impl Stream<Item = Result<Update, StreamDecodeError>>, PendingBlockProcessor),
830 StreamError,
831 > {
832 self.install_fallback_router_labels()?;
833 for protocol_system in self.pending_indexers.keys() {
834 if !self
835 .registered_exchanges
836 .contains(protocol_system)
837 {
838 warn!(
839 protocol_system,
840 "Pending indexer reaches no pool: no exchange has this protocol system"
841 );
842 }
843 }
844 initialize_hook_handlers().map_err(|e| {
845 StreamError::SetUpError(format!("Error initializing hook handlers: {e:?}"))
846 })?;
847 self.install_override_providers();
848 let (_, rx) = self.stream_builder.build().await?;
849 let decoder = Arc::new(self.decoder);
850
851 let (advance_tx, advance_rx) =
852 tokio::sync::mpsc::unbounded_channel::<FeedMessage<BlockHeader>>();
853 let pending = PendingBlockProcessor::new(
854 self.pending_indexers,
855 decoder.clone(),
856 self.chain,
857 advance_rx,
858 );
859
860 let chain = self.chain;
861 let stream_end_policy = self.stream_end_policy;
862
863 let decode_stream: Box<dyn Stream<Item = FeedMessage<BlockHeader>> + Send + Unpin> =
864 if let (Some(peek_tx), Some(trigger_rx)) = (self.step_peek_tx, self.step_trigger_rx) {
865 let (gated_tx, gated_rx) =
866 tokio::sync::mpsc::channel::<FeedMessage<BlockHeader>>(1);
867 Self::run_gating_task(rx, trigger_rx, peek_tx, gated_tx, stream_end_policy);
868 Box::new(ReceiverStream::new(gated_rx))
869 } else {
870 let normal = ReceiverStream::new(rx)
871 .take_while(move |msg| match msg {
872 Ok(msg) => {
873 let states = msg.sync_states.values();
874 if stream_end_policy.should_end(states) {
875 error!(
876 "Block stream ended due to {:?}: {:?}",
877 stream_end_policy, msg.sync_states
878 );
879 futures::future::ready(false)
880 } else {
881 futures::future::ready(true)
882 }
883 }
884 Err(e) => {
885 error!("Block stream ended with terminal error: {e}");
886 futures::future::ready(false)
887 }
888 })
889 .map(|msg| msg.expect("Safe since stream ends if we receive an error"));
890 Box::new(Box::pin(normal))
891 };
892
893 let stream = Box::pin(decode_stream.then({
894 let decoder = decoder;
895 move |msg| {
896 let decoder = decoder.clone();
897 let advance_tx = advance_tx.clone();
898 async move {
899 if let Err(e) = advance_tx.send(msg.clone()) {
900 warn!(error = %e, "Pending block processor is gone; block not forwarded");
901 }
902 decoder.decode(&msg).await.map_err(|e| {
903 debug!(msg=?msg, "Decode error: {}", e);
904 e
905 })
906 }
907 }
908 }));
909 let stream = inject_native_wrapper(stream, chain);
910 Ok((stream, pending))
911 }
912
913 /// Builds and returns the configured protocol stream.
914 ///
915 /// See the module-level docs for details on stream behavior and emitted messages.
916 /// This method applies all builder settings and starts the stream.
917 pub async fn build(
918 mut self,
919 ) -> Result<impl Stream<Item = Result<Update, StreamDecodeError>>, StreamError> {
920 self.install_fallback_router_labels()?;
921 initialize_hook_handlers().map_err(|e| {
922 StreamError::SetUpError(format!("Error initializing hook handlers: {e:?}"))
923 })?;
924 self.install_override_providers();
925 let (_, rx) = self.stream_builder.build().await?;
926 let decoder = Arc::new(self.decoder);
927 let chain = self.chain;
928 let stream_end_policy = self.stream_end_policy;
929
930 let decode_stream: Box<dyn Stream<Item = FeedMessage<BlockHeader>> + Send + Unpin> =
931 if let (Some(peek_tx), Some(trigger_rx)) = (self.step_peek_tx, self.step_trigger_rx) {
932 let (gated_tx, gated_rx) =
933 tokio::sync::mpsc::channel::<FeedMessage<BlockHeader>>(1);
934 Self::run_gating_task(rx, trigger_rx, peek_tx, gated_tx, stream_end_policy);
935 Box::new(ReceiverStream::new(gated_rx))
936 } else {
937 let normal = ReceiverStream::new(rx)
938 .take_while(move |msg| match msg {
939 Ok(msg) => {
940 let states = msg.sync_states.values();
941 if stream_end_policy.should_end(states) {
942 error!(
943 "Block stream ended due to {:?}: {:?}",
944 stream_end_policy, msg.sync_states
945 );
946 futures::future::ready(false)
947 } else {
948 futures::future::ready(true)
949 }
950 }
951 Err(e) => {
952 error!("Block stream ended with terminal error: {e}");
953 futures::future::ready(false)
954 }
955 })
956 .map(|msg| msg.expect("Safe since stream ends if we receive an error"));
957 Box::new(Box::pin(normal))
958 };
959
960 let stream = Box::pin(decode_stream.then({
961 let decoder = decoder;
962 move |msg| {
963 let decoder = decoder.clone();
964 async move {
965 decoder.decode(&msg).await.map_err(|e| {
966 debug!(msg=?msg, "Decode error: {}", e);
967 e
968 })
969 }
970 }
971 }));
972 let stream = inject_native_wrapper(stream, chain);
973 Ok(stream)
974 }
975}
976
977/// Wraps a decoded protocol stream to inject a `NativeWrapperState` component
978/// on the first successful update.
979///
980/// Skips injection when the chain's native asset has no real wrapper contract.
981fn inject_native_wrapper(
982 inner: impl Stream<Item = Result<Update, StreamDecodeError>> + Unpin + Send + 'static,
983 chain: Chain,
984) -> impl Stream<Item = Result<Update, StreamDecodeError>> + Send {
985 let Some(native_wrapper) = NativeWrapperState::new(chain) else {
986 return Either::Left(inner);
987 };
988
989 let mut pending_wrapper = Some(native_wrapper);
990 Either::Right(inner.map(move |result| {
991 result.map(|mut update| {
992 if let Some(native_wrapper) = pending_wrapper.take() {
993 let component = native_wrapper.component();
994 let id = component.id.to_string();
995 update
996 .new_pairs
997 .insert(id.clone(), component);
998 update
999 .states
1000 .insert(id, Box::new(native_wrapper));
1001 debug!("Injected native_wrapper component for {chain}");
1002 }
1003 update
1004 })
1005 }))
1006}
1007
1008#[cfg(test)]
1009mod tests {
1010 use std::collections::HashMap;
1011
1012 use futures::{stream, StreamExt};
1013 use tycho_common::models::Chain;
1014
1015 use super::*;
1016 use crate::{
1017 evm::protocol::native_wrapper::state::NATIVE_WRAPPER_ID, protocol::models::Update,
1018 };
1019
1020 fn empty_update(block: u64) -> Update {
1021 Update::new(block, HashMap::new(), HashMap::new())
1022 }
1023
1024 #[tokio::test]
1025 async fn test_inject_native_wrapper_first_message_only() {
1026 let updates = vec![Ok(empty_update(1)), Ok(empty_update(2)), Ok(empty_update(3))];
1027 let input = stream::iter(updates);
1028
1029 let results: Vec<_> = inject_native_wrapper(input, Chain::Ethereum)
1030 .collect()
1031 .await;
1032
1033 assert_eq!(results.len(), 3);
1034
1035 let expected_id = NativeWrapperState::new(Chain::Ethereum)
1036 .expect("Ethereum should have a wrapper")
1037 .component()
1038 .id
1039 .to_string();
1040
1041 let first = results[0]
1042 .as_ref()
1043 .expect("first update ok");
1044 assert!(
1045 first
1046 .new_pairs
1047 .contains_key(&expected_id),
1048 "first message should have native_wrapper component"
1049 );
1050 assert!(
1051 first.states.contains_key(&expected_id),
1052 "first message should have native_wrapper state"
1053 );
1054
1055 let second = results[1]
1056 .as_ref()
1057 .expect("second update ok");
1058 assert!(
1059 !second
1060 .new_pairs
1061 .contains_key(&expected_id),
1062 "second message should NOT have native_wrapper component"
1063 );
1064 assert!(
1065 !second.states.contains_key(&expected_id),
1066 "second message should NOT have native_wrapper state"
1067 );
1068 }
1069
1070 #[tokio::test]
1071 async fn test_inject_native_wrapper_after_initial_decode_error() {
1072 let updates = vec![
1073 Err(StreamDecodeError::Fatal("decode failed".to_string())),
1074 Ok(empty_update(1)),
1075 Ok(empty_update(2)),
1076 ];
1077 let results: Vec<_> = inject_native_wrapper(stream::iter(updates), Chain::Ethereum)
1078 .collect()
1079 .await;
1080
1081 assert!(results[0].is_err(), "the decode error must pass through unchanged");
1082 let expected_id = NativeWrapperState::new(Chain::Ethereum)
1083 .expect("Ethereum should have a wrapper")
1084 .component()
1085 .id
1086 .to_string();
1087 let first_success = results[1]
1088 .as_ref()
1089 .expect("second stream item should decode");
1090 assert!(first_success
1091 .new_pairs
1092 .contains_key(&expected_id));
1093 assert!(first_success
1094 .states
1095 .contains_key(&expected_id));
1096
1097 let second_success = results[2]
1098 .as_ref()
1099 .expect("third stream item should decode");
1100 assert!(!second_success
1101 .new_pairs
1102 .contains_key(&expected_id));
1103 assert!(!second_success
1104 .states
1105 .contains_key(&expected_id));
1106 }
1107
1108 #[tokio::test]
1109 async fn test_does_not_inject_native_wrapper_for_arc_shared_balance() {
1110 let results: Vec<_> =
1111 inject_native_wrapper(stream::iter([Ok(empty_update(1))]), Chain::Arc)
1112 .collect()
1113 .await;
1114
1115 let update = results[0]
1116 .as_ref()
1117 .expect("update should decode");
1118 assert!(!update
1119 .new_pairs
1120 .contains_key(NATIVE_WRAPPER_ID));
1121 assert!(!update
1122 .states
1123 .contains_key(NATIVE_WRAPPER_ID));
1124 }
1125
1126 /// Verifies that `with_step_controller` returns both a modified builder and a controller.
1127 ///
1128 /// This test only checks that the builder method is callable and that the returned controller
1129 /// compiles — it does not start any network connection.
1130 #[tokio::test]
1131 async fn test_with_step_controller_returns_controller() {
1132 let builder = ProtocolStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum);
1133 let (_builder, controller) = builder.with_step_controller();
1134 // The controller was successfully returned — verifying the public API is callable.
1135 drop(controller);
1136 }
1137
1138 #[tokio::test]
1139 async fn test_subscription_buffer_size_forwards_zero_rejection() {
1140 let error = ProtocolStreamBuilder::new("not a valid endpoint", Chain::Ethereum)
1141 .subscription_buffer_size(0)
1142 .build()
1143 .await;
1144
1145 let Err(error) = error else {
1146 panic!("a zero subscription buffer size must be rejected during setup");
1147 };
1148
1149 assert!(
1150 error
1151 .to_string()
1152 .contains("subscription buffer size must be greater than zero"),
1153 "the underlying Tycho stream builder should return the configuration error: {error}"
1154 );
1155 }
1156
1157 #[tokio::test]
1158 async fn test_build_rejects_unregistered_fallback_router_venue() {
1159 use crate::evm::protocol::uniswap_v2::state::UniswapV2State;
1160
1161 let error = ProtocolStreamBuilder::new("not a valid endpoint", Chain::Ethereum)
1162 .exchange::<UniswapV2State>(
1163 "uniswap_v2",
1164 ComponentFilter::with_tvl_range(1.0, 1.0),
1165 None,
1166 )
1167 .via_fallback_router("uniswap_v3")
1168 .build()
1169 .await;
1170
1171 let Err(error) = error else {
1172 panic!("a fallback router venue with no registered exchange must be rejected");
1173 };
1174 assert!(
1175 error
1176 .to_string()
1177 .contains("via_fallback_router(uniswap_v3)"),
1178 "the error should name the venue: {error}"
1179 );
1180 }
1181
1182 #[test]
1183 fn test_fallback_router_venue_may_precede_its_exchange() {
1184 use crate::evm::protocol::uniswap_v2::state::UniswapV2State;
1185
1186 let mut builder = ProtocolStreamBuilder::new("not a valid endpoint", Chain::Ethereum)
1187 .via_fallback_router("uniswap_v2")
1188 .exchange::<UniswapV2State>(
1189 "uniswap_v2",
1190 ComponentFilter::with_tvl_range(1.0, 1.0),
1191 None,
1192 );
1193
1194 builder
1195 .install_fallback_router_labels()
1196 .expect("a registered exchange can be routed through the fallback router");
1197 }
1198
1199 #[tokio::test]
1200 async fn test_subscription_buffer_size_forwards_upper_bound_rejection() {
1201 let error = ProtocolStreamBuilder::new("not a valid endpoint", Chain::Ethereum)
1202 .subscription_buffer_size(usize::MAX)
1203 .build()
1204 .await;
1205
1206 let Err(error) = error else {
1207 panic!("an oversized subscription buffer size must be rejected during setup");
1208 };
1209
1210 assert!(
1211 error
1212 .to_string()
1213 .contains("subscription buffer size must not exceed"),
1214 "the underlying Tycho stream builder should return the configuration error: {error}"
1215 );
1216 }
1217
1218 /// Connects to a live Tycho instance, verifies that the stream blocks until
1219 /// `trigger_next_block` is called, and that `peek_next_block` exposes the buffered message.
1220 #[ignore = "requires live Tycho connection (TYCHO_AUTH_TOKEN env var)"]
1221 #[tokio::test]
1222 async fn test_step_controller_trigger_releases_block() {
1223 use std::{env, time::Duration};
1224
1225 use crate::evm::protocol::uniswap_v2::state::UniswapV2State;
1226
1227 let auth = env::var("TYCHO_AUTH_TOKEN").expect("TYCHO_AUTH_TOKEN must be set");
1228
1229 // Track a single well-known pool to minimise startup latency.
1230 let usdc_weth_v2 = "0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc".to_string();
1231 let (builder, controller) =
1232 ProtocolStreamBuilder::new("tycho-beta.propellerheads.xyz", Chain::Ethereum)
1233 .auth_key(Some(auth))
1234 .exchange::<UniswapV2State>(
1235 "uniswap_v2",
1236 ComponentFilter::Ids(vec![usdc_weth_v2]),
1237 None,
1238 )
1239 .with_step_controller();
1240
1241 let (stream, _pending) = builder
1242 .build_with_pending()
1243 .await
1244 .expect("build_with_pending failed");
1245 tokio::pin!(stream);
1246
1247 // Wait up to 60 s for the first block to arrive in the gating buffer.
1248 let peeked = tokio::time::timeout(Duration::from_secs(60), controller.peek_next_block())
1249 .await
1250 .expect("timed out waiting for first block to buffer")
1251 .expect("stream ended before a block arrived");
1252
1253 assert!(!peeked.sync_states.is_empty(), "peeked block should carry sync states");
1254
1255 // Stream must be empty before we trigger — the gating task should be holding the block.
1256 let pre_trigger = tokio::time::timeout(Duration::from_millis(200), stream.next()).await;
1257 assert!(
1258 pre_trigger.is_err(),
1259 "stream should be blocked before trigger_next_block, got an item"
1260 );
1261
1262 // Release the block.
1263 controller
1264 .trigger_next_block()
1265 .expect("trigger_next_block failed");
1266
1267 // Stream should now yield the decoded update within one block time.
1268 let update = tokio::time::timeout(Duration::from_secs(30), stream.next())
1269 .await
1270 .expect("timed out waiting for update after trigger")
1271 .expect("stream ended unexpectedly");
1272
1273 assert!(update.is_ok(), "decoded update should be Ok, got: {:?}", update);
1274 }
1275}