Skip to main content

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