Skip to main content

tycho_simulation/evm/
decoder.rs

1use std::{
2    any::Any,
3    collections::{hash_map::Entry, HashMap, HashSet},
4    future::Future,
5    pin::Pin,
6    sync::Arc,
7};
8
9use alloy::primitives::{Address, U256};
10use thiserror::Error;
11use tokio::sync::{watch, RwLock, RwLockReadGuard};
12use tracing::{debug, error, info, warn};
13use tycho_client::feed::{synchronizer::ComponentWithState, BlockHeader, FeedMessage, HeaderLike};
14use tycho_common::{
15    dto::{ChangeType, ProtocolStateDelta},
16    models::{blockchain::BlockAggregatedChanges, token::Token, Chain},
17    simulation::protocol_sim::{Balances, BlockContext, ProtocolSim},
18    Bytes,
19};
20#[cfg(test)]
21use {
22    mockall::mock,
23    num_bigint::BigUint,
24    tycho_common::simulation::{
25        errors::{SimulationError, TransitionError},
26        protocol_sim::GetAmountOutResult,
27    },
28};
29
30use crate::{
31    evm::{
32        engine_db::{update_engine, SHARED_TYCHO_DB},
33        override_stream::{OverrideSnapshot, StateOverrideProvider},
34        protocol::{
35            utils::bytes_to_address,
36            vm::{constants::ERC20_PROXY_BYTECODE, erc20_token::IMPLEMENTATION_SLOT},
37        },
38        simulation::{BlockEnvOverrides, PendingOverrides},
39        tycho_models::{AccountUpdate, ResponseAccount},
40    },
41    protocol::{
42        errors::InvalidSnapshotError,
43        models::{DecoderContext, ProtocolComponent, TryFromWithBlock, Update},
44    },
45};
46
47#[derive(Error, Debug)]
48pub enum StreamDecodeError {
49    #[error("{0}")]
50    Fatal(String),
51}
52
53#[derive(Default)]
54struct DecoderState {
55    tokens: HashMap<Bytes, Token>,
56    states: HashMap<String, Box<dyn ProtocolSim>>,
57    components: HashMap<String, ProtocolComponent>,
58    // maps contract address to the pools they affect
59    contracts_map: HashMap<Bytes, HashSet<String>>,
60    // Maps original token address to their new proxy token address
61    proxy_token_addresses: HashMap<Address, Address>,
62    // Set of failed components, these are components that failed to decode and will not be emitted
63    // again TODO: handle more gracefully inside tycho-client. We could fetch the snapshot and
64    // try to decode it again.
65    failed_components: HashSet<String>,
66    // The block number of the last confirmed block decoded via `decode()`.
67    current_block_number: u64,
68}
69
70type DecodeFut =
71    Pin<Box<dyn Future<Output = Result<Box<dyn ProtocolSim>, InvalidSnapshotError>> + Send + Sync>>;
72type AccountBalances = HashMap<Bytes, HashMap<Bytes, Bytes>>;
73type RegistryFn<H> = dyn Fn(
74        ComponentWithState,
75        H,
76        AccountBalances,
77        Arc<RwLock<DecoderState>>,
78        Option<watch::Receiver<OverrideSnapshot>>,
79    ) -> DecodeFut
80    + Send
81    + Sync;
82type FilterFn = fn(&ComponentWithState) -> bool;
83
84/// A decoder to process raw messages.
85///
86/// This struct decodes incoming messages of type `FeedMessage` and converts it into the
87/// `BlockUpdate` struct.
88///
89/// # Important:
90/// - Supports registering exchanges and their associated filters for specific protocol components.
91/// - Allows the addition of client-side filters for custom conditions.
92///
93/// **Note:** Tokens provided via [`set_tokens`](Self::set_tokens) are used to decode startup
94/// snapshots and initialize protocol states. This is not an ongoing filter — components arriving
95/// after startup include their own token metadata.
96pub struct TychoStreamDecoder<H>
97where
98    H: HeaderLike,
99{
100    state: Arc<RwLock<DecoderState>>,
101    skip_state_decode_failures: bool,
102    min_token_quality: u32,
103    registry: HashMap<String, Box<RegistryFn<H>>>,
104    inclusion_filters: HashMap<String, Vec<FilterFn>>,
105    /// Protocols whose components drop an unknown token and keep the rest.
106    protocols_skip_unknown_tokens: HashSet<String>,
107    /// Live override providers keyed by `protocol_system`. A pool of that protocol subscribes to
108    /// its provider at creation time and reads fresh overrides on every simulation.
109    override_providers: HashMap<String, Arc<dyn StateOverrideProvider>>,
110    /// Seconds between blocks, used to project a confirmed block header onto the next block when
111    /// deriving the execution block for block-sensitive states.
112    block_time_secs: u64,
113    /// Chain every component this decoder handles lives on. Stamped into each registered
114    /// [`DecoderContext`] so chain-specific decoders cannot be pointed at the wrong chain.
115    chain: Chain,
116}
117
118/// Curve migrated from the generic VM adapter (`EVMPoolState`) to the native [`CurveState`]
119/// decoder. Returns true when `vm:curve` is registered with any other type — i.e. the deprecated
120/// VM-adapter path, still supported for a few releases before removal.
121fn is_deprecated_curve_registration<T: 'static>(exchange: &str) -> bool {
122    exchange == "vm:curve" &&
123        std::any::type_name::<T>() !=
124            std::any::type_name::<crate::evm::protocol::curve::CurveState>()
125}
126
127impl<H> TychoStreamDecoder<H>
128where
129    H: HeaderLike + Clone + Sync + Send + 'static + std::fmt::Debug,
130{
131    /// Creates a decoder for `chain`.
132    ///
133    /// # Panics
134    ///
135    /// Panics if `chain` is a custom chain with no registered config.
136    pub fn new(chain: Chain) -> Self {
137        Self {
138            state: Arc::new(RwLock::new(DecoderState::default())),
139            skip_state_decode_failures: false,
140            min_token_quality: 100,
141            registry: HashMap::new(),
142            inclusion_filters: HashMap::new(),
143            protocols_skip_unknown_tokens: HashSet::new(),
144            override_providers: HashMap::new(),
145            block_time_secs: chain.block_time_secs(),
146            chain,
147        }
148    }
149
150    /// The block a quote produced from `header` is expected to execute in.
151    ///
152    /// A partial (flashblock) header describes a block that is still open, so a quote can still
153    /// land in it. A confirmed header describes a closed block, so the quote targets the next one.
154    fn execution_block(&self, header: &BlockHeader) -> BlockContext {
155        if header.partial_block_index.is_some() {
156            BlockContext::new(header.number, header.timestamp)
157        } else {
158            BlockContext::new(header.number + 1, header.timestamp + self.block_time_secs)
159        }
160    }
161
162    /// Advances every state to `execution_block` via [`ProtocolSim::apply_block`].
163    ///
164    /// States already being emitted are advanced in place. Stored states absent from this
165    /// message are advanced in place under the write guard and cloned into `updated_states`
166    /// only when their quoting behavior changed — so an idle block-sensitive pool costs one
167    /// virtual call per message and zero clones, and consumers are only told about pools whose
168    /// quotes actually moved. Stored states of failed or removed components are left untouched,
169    /// so a component the consumer was told is gone is never re-emitted.
170    fn refresh_execution_block<C>(
171        updated_states: &mut HashMap<String, Box<dyn ProtocolSim>>,
172        stored_states: &mut HashMap<String, Box<dyn ProtocolSim>>,
173        failed_components: &HashSet<String>,
174        removed_components: &HashMap<String, C>,
175        execution_block: &BlockContext,
176    ) {
177        for state in updated_states.values_mut() {
178            state.apply_block(execution_block);
179        }
180        for (id, state) in stored_states.iter_mut() {
181            if failed_components.contains(id) ||
182                removed_components.contains_key(id) ||
183                updated_states.contains_key(id)
184            {
185                continue;
186            }
187            if state.apply_block(execution_block) {
188                updated_states.insert(id.clone(), state.clone_box());
189            }
190        }
191    }
192
193    /// Registers `provider` as the live override source for `protocol_system`.
194    ///
195    /// Pools of that protocol subscribe to it at creation time, so overrides apply from the first
196    /// simulation onward. A later call for the same `protocol_system` replaces the previous
197    /// provider.
198    pub fn set_override_provider(
199        &mut self,
200        protocol_system: String,
201        provider: Arc<dyn StateOverrideProvider>,
202    ) {
203        self.override_providers
204            .insert(protocol_system, provider);
205    }
206
207    /// Provides token metadata used to decode startup snapshots and initialize protocol states.
208    ///
209    /// This is not an ongoing stream filter. Components arriving after startup include their
210    /// own token metadata for decoding.
211    pub async fn set_tokens(&self, tokens: HashMap<Bytes, Token>) {
212        let mut guard = self.state.write().await;
213        guard.tokens = tokens;
214    }
215
216    /// Returns read access to the decoder's token metadata, keyed by token address.
217    pub(crate) async fn tokens(&self) -> RwLockReadGuard<'_, HashMap<Bytes, Token>> {
218        RwLockReadGuard::map(self.state.read().await, |state| &state.tokens)
219    }
220
221    pub fn skip_state_decode_failures(&mut self, skip: bool) {
222        self.skip_state_decode_failures = skip;
223    }
224
225    /// Sets the minimum token quality for decoding.
226    ///
227    /// Tokens arriving in stream deltas below this threshold are ignored. Defaults to 100.
228    /// Set this to the same value used in [`load_all_tokens()`](crate::utils::load_all_tokens) to
229    /// apply consistent filtering.
230    pub fn min_token_quality(&mut self, quality: u32) {
231        self.min_token_quality = quality;
232    }
233
234    /// Registers a decoder for a given exchange with a decoder context.
235    ///
236    /// This method maps an exchange identifier to a specific protocol simulation type.
237    /// The associated type must implement the `TryFromWithBlock` trait to enable decoding
238    /// of state updates from `ComponentWithState` objects. This allows the decoder to transform
239    /// the component data into the appropriate protocol simulation type based on the current
240    /// blockchain state and the provided block header.
241    /// For example, to register a decoder for the `uniswap_v2` exchange with an additional decoder
242    /// context, you must call this function with
243    /// `register_decoder_with_context::<UniswapV2State>("uniswap_v2", context)`.
244    /// This ensures that the exchange ID `uniswap_v2` is properly associated with the
245    /// `UniswapV2State` decoder for use in the protocol stream.
246    ///
247    /// The decoder's own chain is stamped into `context`, overriding any chain the caller set.
248    pub fn register_decoder_with_context<T>(&mut self, exchange: &str, mut context: DecoderContext)
249    where
250        T: ProtocolSim
251            + TryFromWithBlock<ComponentWithState, H, Error = InvalidSnapshotError>
252            + Send
253            + 'static,
254    {
255        if let Some(requested) = context
256            .chain
257            .filter(|requested| *requested != self.chain)
258        {
259            warn!(
260                exchange,
261                requested_chain = %requested,
262                decoder_chain = %self.chain,
263                "DecoderContext declares a different chain than the decoder; using the decoder's \
264                 chain"
265            );
266        }
267        context.chain = Some(self.chain);
268
269        if is_deprecated_curve_registration::<T>(exchange) {
270            warn!(
271                registered_type = std::any::type_name::<T>(),
272                "Registering \"vm:curve\" with the generic VM adapter is deprecated; register the \
273                 native `CurveState` decoder instead (`exchange::<CurveState>(\"vm:curve\", ...)`). \
274                 The VM-adapter path still works but will be removed in a future release."
275            );
276        }
277        let decoder = Box::new(
278            move |component: ComponentWithState,
279                  header: H,
280                  account_balances: AccountBalances,
281                  state: Arc<RwLock<DecoderState>>,
282                  live_override: Option<watch::Receiver<OverrideSnapshot>>| {
283                let mut context = context.clone();
284                context.live_override = live_override;
285                Box::pin(async move {
286                    let guard = state.read().await;
287                    T::try_from_with_header(
288                        component,
289                        header,
290                        &account_balances,
291                        &guard.tokens,
292                        &context,
293                    )
294                    .await
295                    .map(|c| Box::new(c) as Box<dyn ProtocolSim>)
296                }) as DecodeFut
297            },
298        );
299        self.registry
300            .insert(exchange.to_string(), decoder);
301    }
302
303    /// Registers a decoder for a given exchange.
304    ///
305    /// This method maps an exchange identifier to a specific protocol simulation type.
306    /// The associated type must implement the `TryFromWithBlock` trait to enable decoding
307    /// of state updates from `ComponentWithState` objects. This allows the decoder to transform
308    /// the component data into the appropriate protocol simulation type based on the current
309    /// blockchain state and the provided block header.
310    /// For example, to register a decoder for the `uniswap_v2` exchange, you must call
311    /// this function with `register_decoder::<UniswapV2State>("uniswap_v2", vm_attributes)`.
312    /// This ensures that the exchange ID `uniswap_v2` is properly associated with the
313    /// `UniswapV2State` decoder for use in the protocol stream.
314    pub fn register_decoder<T>(&mut self, exchange: &str)
315    where
316        T: ProtocolSim
317            + TryFromWithBlock<ComponentWithState, H, Error = InvalidSnapshotError>
318            + Send
319            + 'static,
320    {
321        let context = DecoderContext::new();
322        self.register_decoder_with_context::<T>(exchange, context);
323    }
324
325    /// Registers a decoder for `exchange` that drops a token it does not know, or whose address it
326    /// cannot decode, and keeps the component. Other registrations fail the component. Use it for
327    /// a component with a fixed id, such as an all-pairs RFQ component: a failed one stays failed.
328    pub fn register_decoder_dropping_unknown_tokens<T>(&mut self, exchange: &str)
329    where
330        T: ProtocolSim
331            + TryFromWithBlock<ComponentWithState, H, Error = InvalidSnapshotError>
332            + Send
333            + 'static,
334    {
335        self.register_decoder::<T>(exchange);
336        self.protocols_skip_unknown_tokens
337            .insert(exchange.to_string());
338    }
339
340    /// Registers a client-side filter function for a given exchange.
341    ///
342    /// Associates a filter function with an exchange ID, enabling custom filtering of protocol
343    /// components. The filter function is applied client-side to refine the data received from the
344    /// stream. It can be used to exclude certain components based on attributes or conditions that
345    /// are not supported by the server-side filtering logic. This is particularly useful for
346    /// implementing custom behaviors, such as:
347    /// - Filtering out pools with specific attributes (e.g., unsupported features).
348    /// - Blacklisting pools based on custom criteria.
349    /// - Excluding pools that do not meet certain requirements (e.g., token pairs or liquidity
350    ///   constraints).
351    ///
352    /// For example, you might use a filter to exclude pools that are not fully supported in the
353    /// protocol, or to ignore pools with certain attributes that are irrelevant to your
354    /// application.
355    ///
356    /// Filters accumulate: registering a second predicate for the same exchange keeps the first,
357    /// and a component is admitted only when every registered predicate accepts it.
358    pub fn register_filter(&mut self, exchange: &str, predicate: FilterFn) {
359        self.inclusion_filters
360            .entry(exchange.to_string())
361            .or_default()
362            .push(predicate);
363    }
364
365    /// Whether every filter registered for `exchange` accepts `snapshot`. An exchange with no
366    /// registered filter admits every component.
367    fn admits(&self, exchange: &str, snapshot: &ComponentWithState) -> bool {
368        let Some(predicates) = self.inclusion_filters.get(exchange) else { return true };
369        predicates
370            .iter()
371            .all(|predicate| predicate(snapshot))
372    }
373
374    /// Decodes a `FeedMessage` into a `BlockUpdate` containing the updated states of protocol
375    /// components
376    pub async fn decode(&self, msg: &FeedMessage<H>) -> Result<Update, StreamDecodeError> {
377        // stores all states updated in this tick/msg
378        let mut updated_states = HashMap::new();
379        let mut new_pairs = HashMap::new();
380        let mut removed_pairs = HashMap::new();
381        let mut contracts_map = HashMap::new();
382        let mut msg_failed_components = HashSet::new();
383
384        let header = msg
385            .state_msgs
386            .values()
387            .next()
388            .ok_or_else(|| StreamDecodeError::Fatal("Missing block!".into()))?
389            .header
390            .clone();
391
392        let block_number = header
393            .clone()
394            .block_number_or_timestamp();
395        let current_block = header.clone().block();
396        let is_partial = current_block
397            .as_ref()
398            .map(|h| h.partial_block_index.is_some())
399            .unwrap_or(false);
400
401        for (protocol, protocol_msg) in msg.state_msgs.iter() {
402            let drops_unknown_tokens = self
403                .protocols_skip_unknown_tokens
404                .contains(protocol.as_str());
405            // Add any new tokens
406            if let Some(deltas) = protocol_msg.deltas.as_ref() {
407                let mut state_guard = self.state.write().await;
408
409                let new_tokens = deltas
410                    .new_tokens
411                    .iter()
412                    .filter(|(addr, t)| {
413                        t.quality >= self.min_token_quality &&
414                            !state_guard.tokens.contains_key(*addr)
415                    })
416                    .map(|(addr, t)| (addr.clone(), t.clone()))
417                    .collect::<HashMap<Bytes, Token>>();
418
419                if !new_tokens.is_empty() {
420                    debug!(n = new_tokens.len(), "NewTokens");
421                    state_guard.tokens.extend(new_tokens);
422                }
423            }
424
425            // Remove untracked components
426            {
427                let mut state_guard = self.state.write().await;
428                let removed_components: Vec<(String, ProtocolComponent)> = protocol_msg
429                    .removed_components
430                    .iter()
431                    .map(|(id, comp)| {
432                        if *id != comp.id {
433                            error!(
434                                "Component id mismatch in removed components {id} != {}",
435                                comp.id
436                            );
437                            return Err(StreamDecodeError::Fatal("Component id mismatch".into()));
438                        }
439
440                        let tokens = comp
441                            .tokens
442                            .iter()
443                            .flat_map(|addr| state_guard.tokens.get(addr).cloned())
444                            .collect::<Vec<_>>();
445
446                        if tokens.len() == comp.tokens.len() {
447                            Ok(Some((
448                                id.clone(),
449                                ProtocolComponent::from_with_tokens(comp.clone(), tokens),
450                            )))
451                        } else {
452                            Ok(None)
453                        }
454                    })
455                    .collect::<Result<Vec<Option<(String, ProtocolComponent)>>, StreamDecodeError>>(
456                    )?
457                    .into_iter()
458                    .flatten()
459                    .collect();
460
461                // Remove components from state and add to removed_pairs
462                for (id, component) in removed_components {
463                    state_guard.components.remove(&id);
464                    state_guard.states.remove(&id);
465                    removed_pairs.insert(id, component);
466                }
467
468                // UPDATE VM STORAGE
469                info!(
470                    "Processing {} contracts from snapshots",
471                    protocol_msg
472                        .snapshots
473                        .get_vm_storage()
474                        .len()
475                );
476
477                let mut proxy_token_accounts: HashMap<Address, AccountUpdate> = HashMap::new();
478                let mut storage_by_address: HashMap<Address, ResponseAccount> = HashMap::new();
479                for (key, value) in protocol_msg
480                    .snapshots
481                    .get_vm_storage()
482                    .iter()
483                {
484                    let account: ResponseAccount = value.clone().into();
485
486                    if state_guard.tokens.contains_key(key) {
487                        let original_address = account.address;
488                        // To work with Tycho's token overwrites system, if we get account
489                        // snapshots for a token we must handle them with a proxy/wrapper
490                        // contract.
491                        // Note: storage for the original contract must be set at the proxy
492                        // contract address. This is because the proxy contract uses
493                        // delegatecall to the original (implementation) contract.
494
495                        // Handle proxy token accounts
496                        let (impl_addr, proxy_state) = match state_guard
497                            .proxy_token_addresses
498                            .get(&original_address)
499                        {
500                            Some(impl_addr) => {
501                                // Token already has a proxy contract, simply update it.
502
503                                // Note: we apply the snapshot as an update. This is to cover the
504                                // case where a contract may be stale as it stopped being tracked
505                                // for some reason (e.g. due to a drop in tvl) and is now being
506                                // tracked again.
507                                let proxy_state = AccountUpdate::new(
508                                    original_address,
509                                    value.chain,
510                                    account.slots.clone(),
511                                    Some(account.native_balance),
512                                    None,
513                                    ChangeType::Update,
514                                );
515                                (*impl_addr, proxy_state)
516                            }
517                            None => {
518                                // Token does not have a proxy contract yet, create one
519
520                                // Assign original token contract to new address
521                                let impl_addr = generate_proxy_token_address(
522                                    state_guard.proxy_token_addresses.len(),
523                                )?;
524                                state_guard
525                                    .proxy_token_addresses
526                                    .insert(original_address, impl_addr);
527
528                                // Add proxy token contract at original token address
529                                let proxy_state = create_proxy_token_account(
530                                    original_address,
531                                    Some(impl_addr),
532                                    &account.slots,
533                                    value.chain,
534                                    Some(account.native_balance),
535                                );
536
537                                (impl_addr, proxy_state)
538                            }
539                        };
540
541                        proxy_token_accounts.insert(original_address, proxy_state);
542
543                        // Assign original token contract to the implementation address
544                        let impl_update = ResponseAccount {
545                            address: impl_addr,
546                            slots: HashMap::new(),
547                            ..account
548                        };
549                        storage_by_address.insert(impl_addr, impl_update);
550                    } else {
551                        // Not a token, apply snapshot to the account at its original address
552                        storage_by_address.insert(account.address, account);
553                    }
554                }
555
556                // Split proxy accounts by change type:
557                // - Creation: new proxies that must overwrite any existing placeholder
558                // - Update: existing proxies whose storage is being refreshed (handled normally)
559                let mut proxy_creates: Vec<AccountUpdate> = Vec::new();
560                let mut proxy_updates: HashMap<Address, AccountUpdate> = HashMap::new();
561                for (addr, update) in proxy_token_accounts {
562                    if matches!(update.change, ChangeType::Creation) {
563                        proxy_creates.push(update);
564                    } else {
565                        proxy_updates.insert(addr, update);
566                    }
567                }
568
569                info!("Updating engine with {} contracts from snapshots", storage_by_address.len());
570                update_engine(
571                    SHARED_TYCHO_DB.clone(),
572                    header.clone().block(),
573                    Some(storage_by_address),
574                    proxy_updates,
575                )
576                .map_err(|e| StreamDecodeError::Fatal(e.to_string()))?;
577
578                // Force-overwrite new proxy token accounts so that authoritative vm_storage data
579                // always wins over any empty placeholder previously inserted by engine setup
580                // (which uses init_account / init-if-not-exists).
581                if !proxy_creates.is_empty() {
582                    SHARED_TYCHO_DB
583                        .force_update_accounts(proxy_creates)
584                        .map_err(|e| StreamDecodeError::Fatal(e.to_string()))?;
585                }
586                info!("Engine updated");
587                drop(state_guard);
588            }
589
590            // Construct a contract to token balances map: HashMap<ContractAddress,
591            // HashMap<TokenAddress, Balance>>
592            let account_balances = protocol_msg
593                .clone()
594                .snapshots
595                .get_vm_storage()
596                .iter()
597                .filter_map(|(addr, acc)| {
598                    if acc.token_balances.is_empty() {
599                        return None;
600                    }
601                    let balances = acc
602                        .token_balances
603                        .iter()
604                        .map(|(token_addr, ab)| (token_addr.clone(), ab.balance.clone()))
605                        .collect::<HashMap<Bytes, Bytes>>();
606                    Some((addr.clone(), balances))
607                })
608                .collect::<AccountBalances>();
609
610            let mut new_components = HashMap::new();
611            let mut count_token_skips = 0;
612            let mut components_to_store = HashMap::new();
613            {
614                let state_guard = self.state.read().await;
615
616                // PROCESS SNAPSHOTS
617                'snapshot_loop: for (id, snapshot) in protocol_msg
618                    .snapshots
619                    .get_states()
620                    .clone()
621                {
622                    // Skip any unsupported pools
623                    if !self.admits(protocol.as_str(), &snapshot) {
624                        continue;
625                    }
626
627                    // Construct component from snapshot
628                    let mut component_tokens = Vec::new();
629                    let mut new_tokens_accounts = HashMap::new();
630                    for token in snapshot.component.tokens.clone() {
631                        match state_guard.tokens.get(&token) {
632                            Some(token) => {
633                                // If the token is not an existing proxy token, we need to add it to
634                                // the simulation engine
635                                let token_address = match bytes_to_address(&token.address) {
636                                    Ok(addr) => addr,
637                                    Err(_) if drops_unknown_tokens => {
638                                        warn!(
639                                            "Token address could not be decoded {}, ignoring the token in component {:x?}",
640                                            token.address, id
641                                        );
642                                        continue;
643                                    }
644                                    Err(_) => {
645                                        count_token_skips += 1;
646                                        msg_failed_components.insert(id.clone());
647                                        warn!(
648                                            "Token address could not be decoded {}, ignoring pool {:x?}",
649                                            token.address, id
650                                        );
651                                        continue 'snapshot_loop;
652                                    }
653                                };
654                                component_tokens.push(token.clone());
655                                // Deploy a proxy account without an implementation set
656                                if !state_guard
657                                    .proxy_token_addresses
658                                    .contains_key(&token_address)
659                                {
660                                    new_tokens_accounts.insert(
661                                        token_address,
662                                        create_proxy_token_account(
663                                            token_address,
664                                            None,
665                                            &HashMap::new(),
666                                            snapshot.component.chain,
667                                            None,
668                                        ),
669                                    );
670                                }
671                            }
672                            None if drops_unknown_tokens => {
673                                warn!(
674                                    "Token not found {}, ignoring the token in component {:x?}",
675                                    token, id
676                                );
677                            }
678                            None => {
679                                count_token_skips += 1;
680                                msg_failed_components.insert(id.clone());
681                                debug!("Token not found {}, ignoring pool {:x?}", token, id);
682                                continue 'snapshot_loop;
683                            }
684                        }
685                    }
686                    let component = ProtocolComponent::from_with_tokens(
687                        snapshot.component.clone(),
688                        component_tokens,
689                    );
690
691                    // Add new tokens to the simulation engine
692                    if !new_tokens_accounts.is_empty() {
693                        update_engine(
694                            SHARED_TYCHO_DB.clone(),
695                            header.clone().block(),
696                            None,
697                            new_tokens_accounts,
698                        )
699                        .map_err(|e| StreamDecodeError::Fatal(e.to_string()))?;
700                    }
701
702                    // collect contracts:ids mapping for states that should update on contract
703                    // changes (non-manual updates)
704                    if !component
705                        .static_attributes
706                        .contains_key("manual_updates")
707                    {
708                        for contract in &component.contract_ids {
709                            contracts_map
710                                .entry(contract.clone())
711                                .or_insert_with(HashSet::new)
712                                .insert(id.clone());
713                        }
714                        // Add DCI contracts so changes to these contracts trigger
715                        // an update
716                        for (_, tracing) in snapshot.entrypoints.iter() {
717                            for contract in tracing.accessed_slots.keys().cloned() {
718                                contracts_map
719                                    .entry(contract)
720                                    .or_insert_with(HashSet::new)
721                                    .insert(id.clone());
722                            }
723                        }
724                    }
725
726                    // Collect new pairs (components)
727                    new_pairs.insert(id.clone(), component.clone());
728
729                    // Store component for later batch insertion
730                    components_to_store.insert(id.clone(), component);
731
732                    // Construct state from snapshot
733                    if let Some(state_decode_f) = self.registry.get(protocol.as_str()) {
734                        let live_override = self
735                            .override_providers
736                            .get(protocol.as_str())
737                            .and_then(|provider| provider.subscribe(protocol.as_str()));
738                        match state_decode_f(
739                            snapshot,
740                            header.clone(),
741                            account_balances.clone(),
742                            self.state.clone(),
743                            live_override,
744                        )
745                        .await
746                        {
747                            Ok(state) => {
748                                new_components.insert(id.clone(), state);
749                            }
750                            Err(e) => {
751                                if self.skip_state_decode_failures {
752                                    warn!(pool = id, error = %e, "StateDecodingFailure");
753                                    msg_failed_components.insert(id.clone());
754                                    continue 'snapshot_loop;
755                                }
756                                error!(pool = id, error = %e, "StateDecodingFailure");
757                                return Err(StreamDecodeError::Fatal(format!("{e}")));
758                            }
759                        }
760                    } else if self.skip_state_decode_failures {
761                        warn!(pool = id, "MissingDecoderRegistration");
762                        msg_failed_components.insert(id.clone());
763                    } else {
764                        error!(pool = id, "MissingDecoderRegistration");
765                        return Err(StreamDecodeError::Fatal(format!(
766                            "Missing decoder registration for: {id}"
767                        )));
768                    }
769                }
770            }
771
772            // Batch insert components into state
773            if !components_to_store.is_empty() {
774                let mut state_guard = self.state.write().await;
775                for (id, component) in components_to_store {
776                    state_guard
777                        .components
778                        .insert(id, component);
779                }
780            }
781
782            if !protocol_msg.snapshots.states.is_empty() {
783                info!("Decoded {} snapshots for protocol {protocol}", new_components.len());
784            }
785            if count_token_skips > 0 {
786                info!("Skipped {count_token_skips} pools due to missing tokens");
787            }
788
789            //TODO: should we remove failed components for new_components?
790            updated_states.extend(new_components);
791
792            // PROCESS DELTAS
793            if let Some(deltas) = protocol_msg.deltas.clone() {
794                // Update engine with account changes
795                let mut state_guard = self.state.write().await;
796
797                let mut account_update_by_address: HashMap<Address, AccountUpdate> = HashMap::new();
798                // New proxy token accounts that must overwrite any existing placeholder.
799                let mut new_proxy_accounts: Vec<AccountUpdate> = Vec::new();
800                for (key, value) in deltas.account_deltas.iter() {
801                    let mut update: AccountUpdate = value.clone().into();
802
803                    // TEMP PATCH (ENG-4993)
804                    //
805                    // The indexer may emit Creation deltas with no code for EOA addresses.
806                    // Treat them as EOAs (empty code) rather than downgrading to Update, which
807                    // would skip init_account and cause "uninitialized account" warnings.
808                    if update.code.is_none() && matches!(update.change, ChangeType::Creation) {
809                        error!(
810                            update = ?update,
811                            "FaultyCreationDelta"
812                        );
813                        update.code = Some(vec![]);
814                    }
815
816                    if state_guard.tokens.contains_key(key) {
817                        let original_address = update.address;
818                        // If the account is a token, we need to handle it with a proxy contract.
819                        // Storage updates apply to the proxy contract (at original address).
820                        // Code updates (if any) apply to the token implementation contract (at
821                        // impl_addr).
822
823                        // Handle proxy contract updates
824                        let impl_addr = match state_guard
825                            .proxy_token_addresses
826                            .get(&original_address)
827                        {
828                            Some(impl_addr) => {
829                                // Token already has a proxy contract.
830
831                                // The proxy account already exists, so this is always a plain
832                                // storage update regardless of the incoming change type.
833                                let proxy_update = AccountUpdate {
834                                    code: None,
835                                    change: ChangeType::Update,
836                                    ..update.clone()
837                                };
838                                account_update_by_address.insert(original_address, proxy_update);
839
840                                *impl_addr
841                            }
842                            None => {
843                                // Token does not have a proxy contract yet, create one
844
845                                // Assign original token (implementation) contract to new proxy
846                                // address
847                                let impl_addr = generate_proxy_token_address(
848                                    state_guard.proxy_token_addresses.len(),
849                                )?;
850                                state_guard
851                                    .proxy_token_addresses
852                                    .insert(original_address, impl_addr);
853
854                                // Create proxy token account with original account's storage (at
855                                // original address). Track it separately so it can be
856                                // force-overwritten and win over any placeholder that an engine
857                                // setup routine may have written earlier.
858                                let proxy_state = create_proxy_token_account(
859                                    original_address,
860                                    Some(impl_addr),
861                                    &update.slots,
862                                    update.chain,
863                                    update.balance,
864                                );
865                                new_proxy_accounts.push(proxy_state);
866
867                                impl_addr
868                            }
869                        };
870
871                        // Apply code update to token implementation contract
872                        if update.code.is_some() {
873                            let impl_update = AccountUpdate {
874                                address: impl_addr,
875                                slots: HashMap::new(),
876                                ..update
877                            };
878                            account_update_by_address.insert(impl_addr, impl_update);
879                        }
880                    } else {
881                        // Not a token, apply update to the account at its original address
882                        account_update_by_address.insert(update.address, update);
883                    }
884                }
885                drop(state_guard);
886
887                let state_guard = self.state.read().await;
888                info!("Updating engine with {} contract deltas", deltas.account_deltas.len());
889                update_engine(
890                    SHARED_TYCHO_DB.clone(),
891                    header.clone().block(),
892                    None,
893                    account_update_by_address,
894                )
895                .map_err(|e| StreamDecodeError::Fatal(e.to_string()))?;
896
897                // Force-overwrite any newly-created proxy token accounts so they always win
898                // over placeholder entries inserted by engine setup.
899                if !new_proxy_accounts.is_empty() {
900                    SHARED_TYCHO_DB
901                        .force_update_accounts(new_proxy_accounts)
902                        .map_err(|e| StreamDecodeError::Fatal(e.to_string()))?;
903                }
904                info!("Engine updated");
905
906                // Collect all pools related to the updated accounts
907                let mut pools_to_update = HashSet::new();
908                for (account, _update) in deltas.account_deltas {
909                    // get new pools related to the account updated
910                    pools_to_update.extend(
911                        contracts_map
912                            .get(&account)
913                            .cloned()
914                            .unwrap_or_default(),
915                    );
916                    // get existing pools related to the account updated
917                    pools_to_update.extend(
918                        state_guard
919                            .contracts_map
920                            .get(&account)
921                            .cloned()
922                            .unwrap_or_default(),
923                    );
924                }
925
926                // Collect all balance changes this block
927                let all_balances = Balances {
928                    component_balances: deltas
929                        .component_balances
930                        .iter()
931                        .map(|(pool_id, bals)| {
932                            let mut balances = HashMap::new();
933                            for (t, b) in bals {
934                                balances.insert(t.clone(), b.balance.clone());
935                            }
936                            pools_to_update.insert(pool_id.clone());
937                            (pool_id.clone(), balances)
938                        })
939                        .collect(),
940                    account_balances: deltas
941                        .account_balances
942                        .iter()
943                        .map(|(account, bals)| {
944                            let mut balances = HashMap::new();
945                            for (t, b) in bals {
946                                balances.insert(t.clone(), b.balance.clone());
947                            }
948                            pools_to_update.extend(
949                                contracts_map
950                                    .get(account)
951                                    .cloned()
952                                    .unwrap_or_default(),
953                            );
954                            (account.clone(), balances)
955                        })
956                        .collect(),
957                };
958
959                // update states with protocol state deltas (attribute changes etc.)
960                for (id, update) in deltas.state_deltas {
961                    // TODO: is this needed?
962                    let update_with_block = Self::add_block_info_to_delta(
963                        ProtocolStateDelta::from(update),
964                        current_block.clone(),
965                    );
966                    match Self::apply_update(
967                        &id,
968                        update_with_block,
969                        &mut updated_states,
970                        &state_guard,
971                        &all_balances,
972                    ) {
973                        Ok(_) => {
974                            pools_to_update.remove(&id);
975                        }
976                        Err(e) => {
977                            if self.skip_state_decode_failures {
978                                warn!(pool = id, error = %e, "Failed to apply state update, marking component as removed");
979                                // Remove from updated_states if it was there
980                                updated_states.remove(&id);
981                                // Try to get component from new_pairs first, then from state
982                                if let Some(component) = new_pairs.remove(&id) {
983                                    removed_pairs.insert(id.clone(), component);
984                                } else if let Some(component) = state_guard.components.get(&id) {
985                                    removed_pairs.insert(id.clone(), component.clone());
986                                } else {
987                                    // Component not found in new_pairs or state, this shouldn't
988                                    // happen
989                                    warn!(pool = id, "Component not found in new_pairs or state, cannot add to removed_pairs");
990                                }
991                                pools_to_update.remove(&id);
992
993                                // Add to failed components
994                                msg_failed_components.insert(id.clone());
995                            } else {
996                                return Err(e);
997                            }
998                        }
999                    }
1000                }
1001
1002                // update remaining pools linked to updated contracts/updated balances
1003                for pool in pools_to_update {
1004                    // TODO: is this needed?
1005                    let default_delta_with_block = Self::add_block_info_to_delta(
1006                        ProtocolStateDelta::default(),
1007                        current_block.clone(),
1008                    );
1009                    match Self::apply_update(
1010                        &pool,
1011                        default_delta_with_block,
1012                        &mut updated_states,
1013                        &state_guard,
1014                        &all_balances,
1015                    ) {
1016                        Ok(_) => {}
1017                        Err(e) => {
1018                            if self.skip_state_decode_failures {
1019                                warn!(pool = pool, error = %e, "Failed to apply contract/balance update, marking component as removed");
1020                                // Remove from updated_states if it was there
1021                                updated_states.remove(&pool);
1022                                // Try to get component from new_pairs first, then from state
1023                                if let Some(component) = new_pairs.remove(&pool) {
1024                                    removed_pairs.insert(pool.clone(), component);
1025                                } else if let Some(component) = state_guard.components.get(&pool) {
1026                                    removed_pairs.insert(pool.clone(), component.clone());
1027                                } else {
1028                                    // Component not found in new_pairs or state, this shouldn't
1029                                    // happen
1030                                    warn!(pool = pool, "Component not found in new_pairs or state, cannot add to removed_pairs");
1031                                }
1032
1033                                // Add to failed components
1034                                msg_failed_components.insert(pool.clone());
1035                            } else {
1036                                return Err(e);
1037                            }
1038                        }
1039                    }
1040                }
1041            };
1042        }
1043
1044        // Persist the newly added/updated states
1045        let mut state_guard = self.state.write().await;
1046
1047        // Update failed components with any new ones
1048        state_guard
1049            .failed_components
1050            .extend(msg_failed_components);
1051
1052        // Remove any failed components from Updates
1053        // Perf: we could do it directly in the decoder logic to avoid some steps, but this logic is
1054        // complex and this is more robust.
1055        updated_states.retain(|id, _| {
1056            !state_guard
1057                .failed_components
1058                .contains(id)
1059        });
1060        new_pairs.retain(|id, _| {
1061            !state_guard
1062                .failed_components
1063                .contains(id)
1064        });
1065
1066        if let Some(header) = current_block.as_ref() {
1067            let execution_block = self.execution_block(header);
1068            let decoder_state = &mut *state_guard;
1069            Self::refresh_execution_block(
1070                &mut updated_states,
1071                &mut decoder_state.states,
1072                &decoder_state.failed_components,
1073                &removed_pairs,
1074                &execution_block,
1075            );
1076        }
1077
1078        state_guard
1079            .states
1080            .extend(updated_states.clone());
1081
1082        state_guard.current_block_number = block_number;
1083
1084        // Add new components to persistent state
1085        for (id, component) in new_pairs.iter() {
1086            state_guard
1087                .components
1088                .insert(id.clone(), component.clone());
1089        }
1090
1091        // Remove components from persistent state
1092        for id in removed_pairs.keys() {
1093            state_guard.components.remove(id);
1094        }
1095
1096        for (key, values) in contracts_map {
1097            state_guard
1098                .contracts_map
1099                .entry(key)
1100                .or_insert_with(HashSet::new)
1101                .extend(values);
1102        }
1103
1104        // Send the tick with all updated states
1105        Ok(Update::new(block_number, updated_states, new_pairs)
1106            .set_is_partial(is_partial)
1107            .set_removed_pairs(removed_pairs)
1108            .set_sync_states(msg.sync_states.clone()))
1109    }
1110
1111    /// Applies pending deltas from one or more `TxDeltaIndexer`s against the current confirmed
1112    /// state and returns an ephemeral `Update`.
1113    ///
1114    /// This is the read-only counterpart of `decode()`. It clones pool states, applies the
1115    /// supplied `pending_deltas`, and returns the result — **without writing back** to
1116    /// `DecoderState`. Calling this method twice with the same input produces identical results.
1117    ///
1118    /// This method writes nothing to the VM database. A protocol decoding into the generic VM
1119    /// adapter therefore cannot take part: it re-reads pool state from that database, so its
1120    /// storage-derived values stay at the confirmed block — even though the delta's balance and
1121    /// block-environment attributes do get applied.
1122    ///
1123    /// # Parameters
1124    /// * `pending_deltas` — map from protocol system to the `BlockAggregatedChanges` that its
1125    ///   `TxDeltaIndexer::generate_deltas()` produced. The account deltas under each key reach only
1126    ///   pools of that protocol system, so that key's indexer must emit the writes to every account
1127    ///   those pools read.
1128    /// * `header` — the target block header. Its `block_number_or_timestamp()` is stamped on the
1129    ///   returned [`Update`]; its `block_number` and `block_timestamp` are injected into each state
1130    ///   delta so that protocols relying on block context (e.g. aerodrome slipstreams, etherfi)
1131    ///   receive correct values.
1132    pub async fn apply_deltas_ephemeral(
1133        &self,
1134        pending_deltas: &HashMap<String, BlockAggregatedChanges>,
1135        header: H,
1136    ) -> Result<Update, StreamDecodeError> {
1137        let block_number = header
1138            .clone()
1139            .block_number_or_timestamp();
1140        let current_block = header.block();
1141        let state_guard = self.state.read().await;
1142
1143        let mut updated_states: HashMap<String, Box<dyn ProtocolSim>> = HashMap::new();
1144        for (protocol_system, deltas) in pending_deltas {
1145            let changes = ExtractorChanges::new(protocol_system, deltas);
1146            let mut failed_pools = HashSet::new();
1147            for (id, state_delta) in &deltas.state_deltas {
1148                let dto_delta = Self::add_block_info_to_delta(
1149                    ProtocolStateDelta::from(state_delta.clone()),
1150                    current_block.clone(),
1151                );
1152                if let Err(e) = Self::apply_update(
1153                    id,
1154                    dto_delta,
1155                    &mut updated_states,
1156                    &state_guard,
1157                    &changes.balances,
1158                ) {
1159                    warn!(pool = id, error = %e, "EphemeralDeltaTransitionError");
1160                    failed_pools.insert(id);
1161                }
1162            }
1163            if !deltas.account_deltas.is_empty() {
1164                Self::apply_pending_overrides(
1165                    &changes,
1166                    &failed_pools,
1167                    current_block.as_ref(),
1168                    &mut updated_states,
1169                    &state_guard,
1170                )?;
1171            }
1172        }
1173
1174        // `header` is the block being built, so it already *is* the execution block — unlike
1175        // `decode`, there is nothing to project forward here. Only the delta-applied clones need
1176        // advancing: this path is read-only, and the stored states were already advanced to this
1177        // block by `decode()` on the confirmed stream.
1178        if let Some(header) = current_block.as_ref() {
1179            let execution_block = BlockContext::new(header.number, header.timestamp);
1180            for state in updated_states.values_mut() {
1181                state.apply_block(&execution_block);
1182            }
1183        }
1184
1185        Ok(Update::new(block_number, updated_states, HashMap::new()))
1186    }
1187
1188    /// Sets one extractor's account deltas as overrides on each pool that has the extractor's
1189    /// protocol system and is linked to a written account.
1190    ///
1191    /// A hooked pool prices from its hook's storage, which only the account deltas carry. An
1192    /// override for an account a hook never reads is inert.
1193    ///
1194    /// Skips pools of other protocol systems, even when they are linked to a written account such
1195    /// as a token contract. A pool holds one override set, so another extractor's set would
1196    /// replace the pool's own. Linking such a pool would also rebuild it from confirmed state with
1197    /// an empty delta. For a pool whose transition reads the VM, each rebuild costs one EVM call
1198    /// and changes nothing.
1199    ///
1200    /// Skips the pools in `failed_pools`, whose own state delta failed. A rebuild would pair the
1201    /// pool's confirmed state with the pending overrides and return the mix as pending. Left out,
1202    /// the pool stays at confirmed state for a consumer that overlays the update on it.
1203    ///
1204    /// # Errors
1205    /// Fails when a pool rejects the overrides' type, since its quotes would silently run
1206    /// against confirmed state.
1207    fn apply_pending_overrides(
1208        changes: &ExtractorChanges<'_>,
1209        failed_pools: &HashSet<&String>,
1210        current_block: Option<&BlockHeader>,
1211        updated_states: &mut HashMap<String, Box<dyn ProtocolSim>>,
1212        state_guard: &RwLockReadGuard<'_, DecoderState>,
1213    ) -> Result<(), StreamDecodeError> {
1214        let is_linkable = |id: &&String| {
1215            !failed_pools.contains(id) &&
1216                state_guard
1217                    .components
1218                    .get(*id)
1219                    .is_some_and(|component| {
1220                        component.protocol_system == changes.protocol_system
1221                    })
1222        };
1223        let mut linked_pools: HashSet<&String> = HashSet::new();
1224        for account in changes.deltas.account_deltas.keys() {
1225            if let Some(pools) = state_guard.contracts_map.get(account) {
1226                linked_pools.extend(pools.iter().filter(is_linkable));
1227            }
1228        }
1229        if linked_pools.is_empty() {
1230            return Ok(());
1231        }
1232
1233        let block = current_block
1234            .map(|h| BlockEnvOverrides { number: Some(h.number), timestamp: Some(h.timestamp) });
1235        let overrides: Arc<dyn Any + Send + Sync> =
1236            Arc::new(PendingOverrides::from_account_deltas(&changes.deltas.account_deltas, block));
1237        for id in linked_pools {
1238            if !updated_states.contains_key(id) {
1239                let empty_delta = Self::add_block_info_to_delta(
1240                    ProtocolStateDelta { component_id: id.clone(), ..Default::default() },
1241                    current_block.cloned(),
1242                );
1243                if let Err(e) = Self::apply_update(
1244                    id,
1245                    empty_delta,
1246                    updated_states,
1247                    state_guard,
1248                    &changes.balances,
1249                ) {
1250                    warn!(pool = id, error = %e, "EphemeralDeltaTransitionError");
1251                    continue;
1252                }
1253            }
1254            if let Some(state) = updated_states.get_mut(id) {
1255                state
1256                    .set_pending_overrides(Arc::clone(&overrides))
1257                    .map_err(|e| {
1258                        StreamDecodeError::Fatal(format!("Pending overrides for pool {id}: {e}"))
1259                    })?;
1260            }
1261        }
1262        Ok(())
1263    }
1264
1265    /// Add current block information (number and timestamp) to a ProtocolStateDelta.
1266    fn add_block_info_to_delta(
1267        mut delta: ProtocolStateDelta,
1268        block_header_opt: Option<BlockHeader>,
1269    ) -> ProtocolStateDelta {
1270        if let Some(header) = block_header_opt {
1271            // Add block_number and block_timestamp attributes to ensure pool states
1272            // receive current block information during delta_transition
1273            delta.updated_attributes.insert(
1274                "block_number".to_string(),
1275                Bytes::from(header.number.to_be_bytes().to_vec()),
1276            );
1277            delta.updated_attributes.insert(
1278                "block_timestamp".to_string(),
1279                Bytes::from(header.timestamp.to_be_bytes().to_vec()),
1280            );
1281        }
1282        delta
1283    }
1284
1285    fn apply_update(
1286        id: &String,
1287        update: ProtocolStateDelta,
1288        updated_states: &mut HashMap<String, Box<dyn ProtocolSim>>,
1289        state_guard: &RwLockReadGuard<'_, DecoderState>,
1290        all_balances: &Balances,
1291    ) -> Result<(), StreamDecodeError> {
1292        match updated_states.entry(id.clone()) {
1293            Entry::Occupied(mut entry) => {
1294                // If state exists in updated_states, apply the delta to it
1295                let state: &mut Box<dyn ProtocolSim> = entry.get_mut();
1296                state
1297                    .delta_transition(update, &state_guard.tokens, all_balances)
1298                    .map_err(|e| {
1299                        error!(pool = id, error = ?e, "DeltaTransitionError");
1300                        StreamDecodeError::Fatal(format!("TransitionFailure: {e:?}"))
1301                    })?;
1302            }
1303            Entry::Vacant(_) => {
1304                match state_guard.states.get(id) {
1305                    // If state does not exist in updated_states, apply the delta to the stored
1306                    // state
1307                    Some(stored_state) => {
1308                        let mut state = stored_state.clone();
1309                        state
1310                            .delta_transition(update, &state_guard.tokens, all_balances)
1311                            .map_err(|e| {
1312                                error!(pool = id, error = ?e, "DeltaTransitionError");
1313                                StreamDecodeError::Fatal(format!("TransitionFailure: {e:?}"))
1314                            })?;
1315                        updated_states.insert(id.clone(), state);
1316                    }
1317                    None => debug!(pool = id, reason = "MissingState", "DeltaTransitionError"),
1318                }
1319            }
1320        }
1321        Ok(())
1322    }
1323}
1324
1325/// One extractor's pending changes, with its `pending_deltas` key and its component balances.
1326struct ExtractorChanges<'a> {
1327    protocol_system: &'a str,
1328    deltas: &'a BlockAggregatedChanges,
1329    balances: Balances,
1330}
1331
1332impl<'a> ExtractorChanges<'a> {
1333    /// Collects the component balances in `deltas`, with empty account balances.
1334    fn new(protocol_system: &'a str, deltas: &'a BlockAggregatedChanges) -> Self {
1335        let mut all_component_balances = HashMap::with_capacity(deltas.component_balances.len());
1336        for (pool_id, pool_balances) in &deltas.component_balances {
1337            let pool_balances = pool_balances
1338                .iter()
1339                .map(|(token, balance)| (token.clone(), balance.balance.clone()))
1340                .collect();
1341            all_component_balances.insert(pool_id.clone(), pool_balances);
1342        }
1343        let balances = Balances {
1344            component_balances: all_component_balances,
1345            account_balances: HashMap::new(),
1346        };
1347        Self { protocol_system, deltas, balances }
1348    }
1349}
1350
1351/// Generate a proxy token address for a given token index
1352fn generate_proxy_token_address(idx: usize) -> Result<Address, StreamDecodeError> {
1353    let padded_idx = format!("{idx:x}");
1354    let padded_zeroes = "0".repeat(33 - padded_idx.len());
1355    let proxy_token_address = format!("{padded_zeroes}{padded_idx}BAdbaBe");
1356    let decoded = hex::decode(proxy_token_address).map_err(|e| {
1357        StreamDecodeError::Fatal(format!("Invalid proxy token address encoding: {e}"))
1358    })?;
1359
1360    const ADDRESS_LENGTH: usize = 20;
1361    if decoded.len() != ADDRESS_LENGTH {
1362        return Err(StreamDecodeError::Fatal(format!(
1363            "Invalid proxy token address length: expected {}, got {}",
1364            ADDRESS_LENGTH,
1365            decoded.len(),
1366        )));
1367    }
1368
1369    Ok(Address::from_slice(&decoded))
1370}
1371
1372/// Create a proxy token account for a token at a given address
1373///
1374/// The proxy token account is created at the original token address and points to the new token
1375/// address.
1376fn create_proxy_token_account(
1377    addr: Address,
1378    new_address: Option<Address>,
1379    storage: &HashMap<U256, U256>,
1380    chain: Chain,
1381    balance: Option<U256>,
1382) -> AccountUpdate {
1383    let mut slots = storage.clone();
1384    if let Some(new_address) = new_address {
1385        slots.insert(*IMPLEMENTATION_SLOT, U256::from_be_slice(new_address.as_slice()));
1386    }
1387
1388    AccountUpdate {
1389        address: addr,
1390        chain,
1391        slots,
1392        balance,
1393        code: Some(ERC20_PROXY_BYTECODE.to_vec()),
1394        change: ChangeType::Creation,
1395    }
1396}
1397
1398#[cfg(test)]
1399#[expect(
1400    clippy::same_name_method,
1401    reason = "mockall generates the inherent methods the ProtocolSim impl forwards to"
1402)]
1403mod protocol_sim_mock {
1404    use super::*;
1405
1406    mock! {
1407        #[derive(Debug)]
1408        pub ProtocolSim {
1409            pub fn fee(&self) -> f64;
1410            pub fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError>;
1411            pub fn get_amount_out(
1412                &self,
1413                amount_in: BigUint,
1414                token_in: &Token,
1415                token_out: &Token,
1416            ) -> Result<GetAmountOutResult, SimulationError>;
1417            pub fn get_limits(
1418                &self,
1419                sell_token: Bytes,
1420                buy_token: Bytes,
1421            ) -> Result<(BigUint, BigUint), SimulationError>;
1422            pub fn delta_transition(
1423                &mut self,
1424                delta: ProtocolStateDelta,
1425                tokens: &HashMap<Bytes, Token>,
1426                balances: &Balances,
1427            ) -> Result<(), TransitionError>;
1428            pub fn clone_box(&self) -> Box<dyn ProtocolSim>;
1429            pub fn eq(&self, other: &dyn ProtocolSim) -> bool;
1430            pub fn base_token(&self) -> &Token;
1431            pub fn quote_token(&self) -> &Token;
1432            pub fn directions(&self) -> Vec<(Bytes, Bytes)>;
1433            pub fn set_pending_overrides(
1434                &mut self,
1435                overrides: Arc<dyn Any + Send + Sync>,
1436            ) -> Result<(), SimulationError>;
1437        }
1438    }
1439}
1440
1441#[cfg(test)]
1442pub use protocol_sim_mock::MockProtocolSim;
1443
1444#[cfg(test)]
1445crate::impl_non_serializable_protocol!(MockProtocolSim, "test protocol");
1446
1447#[cfg(test)]
1448impl ProtocolSim for MockProtocolSim {
1449    fn fee(&self) -> f64 {
1450        self.fee()
1451    }
1452
1453    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
1454        self.spot_price(base, quote)
1455    }
1456
1457    fn get_amount_out(
1458        &self,
1459        amount_in: BigUint,
1460        token_in: &Token,
1461        token_out: &Token,
1462    ) -> Result<GetAmountOutResult, SimulationError> {
1463        self.get_amount_out(amount_in, token_in, token_out)
1464    }
1465
1466    fn get_limits(
1467        &self,
1468        sell_token: Bytes,
1469        buy_token: Bytes,
1470    ) -> Result<(BigUint, BigUint), SimulationError> {
1471        self.get_limits(sell_token, buy_token)
1472    }
1473
1474    fn delta_transition(
1475        &mut self,
1476        delta: ProtocolStateDelta,
1477        tokens: &HashMap<Bytes, Token>,
1478        balances: &Balances,
1479    ) -> Result<(), TransitionError> {
1480        self.delta_transition(delta, tokens, balances)
1481    }
1482
1483    fn clone_box(&self) -> Box<dyn ProtocolSim> {
1484        self.clone_box()
1485    }
1486
1487    fn set_pending_overrides(
1488        &mut self,
1489        overrides: Arc<dyn Any + Send + Sync>,
1490    ) -> Result<(), SimulationError> {
1491        self.set_pending_overrides(overrides)
1492    }
1493
1494    fn as_any(&self) -> &dyn Any {
1495        panic!("MockProtocolSim does not support as_any")
1496    }
1497
1498    fn as_any_mut(&mut self) -> &mut dyn Any {
1499        panic!("MockProtocolSim does not support as_any_mut")
1500    }
1501
1502    fn eq(&self, other: &dyn ProtocolSim) -> bool {
1503        self.eq(other)
1504    }
1505
1506    fn typetag_name(&self) -> &'static str {
1507        // typetag reads the tag before Serialize, so a panic here would hide Serialize's error.
1508        "MockProtocolSim"
1509    }
1510
1511    #[expect(clippy::unreachable, reason = "the mock is never deserialized through its typetag")]
1512    fn typetag_deserialize(&self) {
1513        unreachable!()
1514    }
1515}
1516
1517/// Lets the mock stand in for a book's state wherever one pair's tokens and directions are
1518/// what the code under test reads.
1519#[cfg(test)]
1520impl crate::book::component::PairState for MockProtocolSim {
1521    fn base_token(&self) -> &Token {
1522        self.base_token()
1523    }
1524
1525    fn quote_token(&self) -> &Token {
1526        self.quote_token()
1527    }
1528
1529    fn directions(&self) -> Vec<(Bytes, Bytes)> {
1530        self.directions()
1531    }
1532}
1533
1534#[cfg(test)]
1535mod tests {
1536    use std::str::FromStr;
1537
1538    use alloy::primitives::address;
1539    use mockall::predicate::*;
1540    use rstest::*;
1541    use tycho_client::feed::BlockHeader;
1542    use tycho_common::{models::Chain, Bytes};
1543
1544    use super::*;
1545
1546    fn header_at(number: u64, timestamp: u64, partial: Option<u32>) -> BlockHeader {
1547        BlockHeader {
1548            hash: Bytes::from([0u8; 32]),
1549            number,
1550            parent_hash: Bytes::from([0u8; 32]),
1551            revert: false,
1552            timestamp,
1553            partial_block_index: partial,
1554        }
1555    }
1556
1557    /// A block-sensitive state whose execution timestamp we can read back.
1558    fn block_sensitive_state() -> Box<dyn ProtocolSim> {
1559        use crate::evm::protocol::{
1560            aerodrome_slipstreams::state::AerodromeSlipstreamsState,
1561            utils::{
1562                slipstreams::{dynamic_fee_module::DynamicFeeConfig, observations::Observation},
1563                uniswap::{tick_list::TickInfo, tick_math::get_sqrt_ratio_at_tick},
1564            },
1565        };
1566
1567        Box::new(
1568            AerodromeSlipstreamsState::new(
1569                "block-sensitive".to_string(),
1570                0,
1571                1_000_000_000_000_000_000,
1572                get_sqrt_ratio_at_tick(0).unwrap(),
1573                0,
1574                1,
1575                3000,
1576                1,
1577                0,
1578                vec![TickInfo::new(-120, 0).unwrap(), TickInfo::new(120, 0).unwrap()],
1579                vec![Observation { block_timestamp: 500, initialized: true, ..Default::default() }],
1580                DynamicFeeConfig::new(2700, 30_000, 0, true, 750),
1581            )
1582            .expect("state should build")
1583            // These fixtures exercise the fee-flip path, which needs the optimistic mode:
1584            // under the worst-case default a flat-fee pool never flips.
1585            .with_position_assumption(crate::protocol::models::BlockPositionAssumption::First),
1586        )
1587    }
1588
1589    #[test]
1590    fn confirmed_header_targets_the_next_block() {
1591        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Base);
1592
1593        let execution_block = decoder.execution_block(&header_at(100, 1_000, None));
1594
1595        assert_eq!(execution_block.number(), 101);
1596        assert_eq!(execution_block.timestamp(), 1_000 + Chain::Base.block_time_secs());
1597    }
1598
1599    #[test]
1600    fn partial_header_targets_the_block_that_is_still_open() {
1601        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
1602
1603        let execution_block = decoder.execution_block(&header_at(100, 1_000, Some(3)));
1604
1605        assert_eq!(execution_block.number(), 100);
1606        assert_eq!(execution_block.timestamp(), 1_000);
1607    }
1608
1609    #[test]
1610    fn refresh_re_emits_a_state_whose_fee_flipped_without_a_delta() {
1611        // The pool traded in block 100 and has no delta afterwards. Crossing into block 101
1612        // flips its fee branch (dynamic -> initial), so the refresh must advance the stored
1613        // state in place and emit a copy to consumers.
1614        let mut stored = HashMap::from([("block-sensitive".to_string(), {
1615            let mut state = block_sensitive_state();
1616            state.apply_block(&BlockContext::new(100, 500));
1617            state
1618        })]);
1619        let mut updated: HashMap<String, Box<dyn ProtocolSim>> = HashMap::new();
1620
1621        TychoStreamDecoder::<BlockHeader>::refresh_execution_block(
1622            &mut updated,
1623            &mut stored,
1624            &HashSet::new(),
1625            &HashMap::<String, ()>::new(),
1626            &BlockContext::new(101, 502),
1627        );
1628
1629        let emitted = updated
1630            .get("block-sensitive")
1631            .expect("a fee flip must be emitted even without a delta");
1632        assert_eq!(emitted.fee(), 750.0 / 1_000_000.0);
1633        // The stored copy was advanced in place as well.
1634        assert_eq!(stored["block-sensitive"].fee(), 750.0 / 1_000_000.0);
1635    }
1636
1637    #[test]
1638    fn refresh_never_re_emits_failed_components() {
1639        // A failed component's stored state may linger; the sweep must not resurrect it for
1640        // consumers that were told the component was removed — even when its fee flipped.
1641        let mut stored = HashMap::from([("zombie".to_string(), {
1642            let mut state = block_sensitive_state();
1643            state.apply_block(&BlockContext::new(100, 500));
1644            state
1645        })]);
1646        let failed = HashSet::from(["zombie".to_string()]);
1647        let mut updated: HashMap<String, Box<dyn ProtocolSim>> = HashMap::new();
1648
1649        TychoStreamDecoder::<BlockHeader>::refresh_execution_block(
1650            &mut updated,
1651            &mut stored,
1652            &failed,
1653            &HashMap::<String, ()>::new(),
1654            &BlockContext::new(101, 502),
1655        );
1656
1657        assert!(updated.is_empty());
1658    }
1659
1660    #[test]
1661    fn refresh_never_re_emits_removed_components() {
1662        // The stored state of a component reported in `removed_pairs` stays in place; the sweep
1663        // must not surface it again, even when its fee flipped in the execution block.
1664        let mut stored = HashMap::from([("gone".to_string(), {
1665            let mut state = block_sensitive_state();
1666            state.apply_block(&BlockContext::new(100, 500));
1667            state
1668        })]);
1669        let removed = HashMap::from([("gone".to_string(), ())]);
1670        let mut updated: HashMap<String, Box<dyn ProtocolSim>> = HashMap::new();
1671
1672        TychoStreamDecoder::<BlockHeader>::refresh_execution_block(
1673            &mut updated,
1674            &mut stored,
1675            &HashSet::new(),
1676            &removed,
1677            &BlockContext::new(101, 502),
1678        );
1679
1680        assert!(updated.is_empty());
1681    }
1682
1683    #[test]
1684    fn refresh_stays_quiet_when_no_fee_changed() {
1685        // An idle block-sensitive pool (fee branch unchanged) and a block-insensitive pool:
1686        // neither must be re-emitted.
1687        let mut stored: HashMap<String, Box<dyn ProtocolSim>> = HashMap::from([
1688            ("idle-sensitive".to_string(), {
1689                let mut state = block_sensitive_state();
1690                state.apply_block(&BlockContext::new(101, 502));
1691                state
1692            }),
1693            (
1694                "univ2".to_string(),
1695                Box::new(crate::evm::protocol::uniswap_v2::state::UniswapV2State::new(
1696                    U256::from(1_000_000u64),
1697                    U256::from(1_000_000u64),
1698                )) as Box<dyn ProtocolSim>,
1699            ),
1700        ]);
1701        let mut updated: HashMap<String, Box<dyn ProtocolSim>> = HashMap::new();
1702
1703        TychoStreamDecoder::<BlockHeader>::refresh_execution_block(
1704            &mut updated,
1705            &mut stored,
1706            &HashSet::new(),
1707            &HashMap::<String, ()>::new(),
1708            &BlockContext::new(102, 504),
1709        );
1710
1711        assert!(updated.is_empty());
1712    }
1713    use crate::evm::protocol::{curve::CurveState, uniswap_v2::state::UniswapV2State};
1714
1715    #[test]
1716    fn curve_vm_adapter_registration_flagged_deprecated() {
1717        // The native decoder is the supported path — not flagged.
1718        assert!(!is_deprecated_curve_registration::<CurveState>("vm:curve"));
1719        // Any other type for vm:curve is the deprecated VM-adapter path.
1720        assert!(is_deprecated_curve_registration::<UniswapV2State>("vm:curve"));
1721        // Other exchanges are unaffected.
1722        assert!(!is_deprecated_curve_registration::<UniswapV2State>("uniswap_v2"));
1723    }
1724
1725    async fn setup_decoder(set_tokens: bool) -> TychoStreamDecoder<BlockHeader> {
1726        let mut decoder = TychoStreamDecoder::new(Chain::Ethereum);
1727        decoder.register_decoder::<UniswapV2State>("uniswap_v2");
1728        if set_tokens {
1729            let tokens = [
1730                Bytes::from("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").lpad(20, 0),
1731                Bytes::from("0xdac17f958d2ee523a2206206994597c13d831ec7").lpad(20, 0),
1732            ]
1733            .iter()
1734            .map(|addr| {
1735                let addr_str = format!("{addr:x}");
1736                (
1737                    addr.clone(),
1738                    Token::new(addr, &addr_str, 18, 100, &[Some(100_000)], Chain::Ethereum, 100),
1739                )
1740            })
1741            .collect();
1742            decoder.set_tokens(tokens).await;
1743        }
1744        decoder
1745    }
1746
1747    fn load_test_msg(name: &str) -> FeedMessage<BlockHeader> {
1748        use std::{fs, path::Path};
1749
1750        use tycho_client::feed::dto;
1751        let project_root = env!("CARGO_MANIFEST_DIR");
1752        let asset_path = Path::new(project_root).join(format!("tests/assets/decoder/{name}.json"));
1753        let json_data = fs::read_to_string(asset_path).expect("Failed to read test asset");
1754        let feed_msg: dto::FeedMessage<BlockHeader> =
1755            serde_json::from_str(&json_data).expect("Failed to deserialize FeedMsg json!");
1756        FeedMessage::from(feed_msg)
1757    }
1758
1759    #[tokio::test]
1760    async fn test_decode() {
1761        let decoder = setup_decoder(true).await;
1762
1763        let msg = load_test_msg("uniswap_v2_snapshot");
1764        let res1 = decoder
1765            .decode(&msg)
1766            .await
1767            .expect("decode failure");
1768        let msg = load_test_msg("uniswap_v2_delta");
1769        let res2 = decoder
1770            .decode(&msg)
1771            .await
1772            .expect("decode failure");
1773
1774        assert_eq!(res1.states.len(), 1);
1775        assert_eq!(res2.states.len(), 1);
1776        assert_eq!(res1.sync_states.len(), 1);
1777        assert_eq!(res2.sync_states.len(), 1);
1778    }
1779
1780    #[tokio::test]
1781    async fn test_decode_token_creation_delta_with_existing_proxy() {
1782        let decoder = setup_decoder(true).await;
1783        let msg = load_test_msg("uniswap_v2_delta_token_creation");
1784
1785        // First decode: the token has no proxy yet, so the Creation delta takes the
1786        // proxy-creating branch.
1787        decoder
1788            .decode(&msg)
1789            .await
1790            .expect("first decode (proxy creation) failed");
1791
1792        // Second decode: the proxy exists, so the same Creation delta must decode as a
1793        // storage update on the proxy account — not a code-less Creation, which the
1794        // engine rejects as "MissingCode".
1795        decoder
1796            .decode(&msg)
1797            .await
1798            .expect("decode of a token Creation delta with an existing proxy failed");
1799    }
1800
1801    #[tokio::test]
1802    async fn test_decode_component_missing_token() {
1803        let decoder = setup_decoder(false).await;
1804        let tokens = [Bytes::from("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").lpad(20, 0)]
1805            .iter()
1806            .map(|addr| {
1807                let addr_str = format!("{addr:x}");
1808                (
1809                    addr.clone(),
1810                    Token::new(addr, &addr_str, 18, 100, &[Some(100_000)], Chain::Ethereum, 100),
1811                )
1812            })
1813            .collect();
1814        decoder.set_tokens(tokens).await;
1815
1816        let msg = load_test_msg("uniswap_v2_snapshot");
1817        let res1 = decoder
1818            .decode(&msg)
1819            .await
1820            .expect("decode failure");
1821
1822        assert_eq!(res1.states.len(), 0);
1823    }
1824
1825    #[rstest]
1826    #[case::unknown_token(false)]
1827    #[case::undecodable_address(true)]
1828    #[tokio::test]
1829    async fn test_dropping_decoder_keeps_component(#[case] bad_address: bool) {
1830        let weth = Bytes::from("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").lpad(20, 0);
1831        // The unknown token is not in the decoder. The bad address is, but 21 bytes are no address.
1832        let other = match bad_address {
1833            true => Bytes::from([1u8; 21].to_vec()),
1834            false => Bytes::from("0xdac17f958d2ee523a2206206994597c13d831ec7").lpad(20, 0),
1835        };
1836        let mut decoder = TychoStreamDecoder::new(Chain::Ethereum);
1837        decoder.register_decoder_dropping_unknown_tokens::<UniswapV2State>("uniswap_v2");
1838        let token = |address: &Bytes, symbol| {
1839            let token =
1840                Token::new(address, symbol, 18, 100, &[Some(100_000)], Chain::Ethereum, 100);
1841            (address.clone(), token)
1842        };
1843        let mut known = HashMap::from([token(&weth, "WETH")]);
1844        if bad_address {
1845            known.extend([token(&other, "OTHER")]);
1846        }
1847        decoder.set_tokens(known).await;
1848        let mut msg = load_test_msg("uniswap_v2_snapshot");
1849        let (id, snapshot) = msg
1850            .state_msgs
1851            .get_mut("uniswap_v2")
1852            .unwrap()
1853            .snapshots
1854            .states
1855            .iter_mut()
1856            .next()
1857            .unwrap();
1858        snapshot.component.tokens = vec![weth, other];
1859        let id = id.clone();
1860
1861        let update = decoder.decode(&msg).await.unwrap();
1862
1863        let symbols: Vec<_> = update.new_pairs[&id]
1864            .tokens
1865            .iter()
1866            .map(|token| token.symbol.as_str())
1867            .collect();
1868        assert_eq!(symbols, ["WETH"]);
1869        assert_eq!(update.states.len(), 1);
1870    }
1871
1872    #[tokio::test]
1873    async fn test_decode_component_bad_id() {
1874        let decoder = setup_decoder(true).await;
1875        let msg = load_test_msg("uniswap_v2_snapshot_broken_id");
1876
1877        match decoder.decode(&msg).await {
1878            Err(StreamDecodeError::Fatal(msg)) => {
1879                assert_eq!(msg, "Component id mismatch");
1880            }
1881            Ok(_) => {
1882                panic!("Expected failures to be raised")
1883            }
1884        }
1885    }
1886
1887    #[rstest]
1888    #[case(true)]
1889    #[case(false)]
1890    #[tokio::test]
1891    async fn test_decode_component_bad_state(#[case] skip_failures: bool) {
1892        let mut decoder = setup_decoder(true).await;
1893        decoder.skip_state_decode_failures = skip_failures;
1894
1895        let msg = load_test_msg("uniswap_v2_snapshot_broken_state");
1896        match decoder.decode(&msg).await {
1897            Err(StreamDecodeError::Fatal(msg)) => {
1898                if !skip_failures {
1899                    assert_eq!(msg, "Missing attributes reserve0");
1900                } else {
1901                    panic!("Expected failures to be ignored. Err: {msg}")
1902                }
1903            }
1904            Ok(res) => {
1905                if !skip_failures {
1906                    panic!("Expected failures to be raised")
1907                }
1908                assert_eq!(res.states.len(), 0);
1909            }
1910        }
1911    }
1912
1913    #[tokio::test]
1914    async fn test_decode_updates_state_on_contract_change() {
1915        let decoder = setup_decoder(true).await;
1916
1917        // Create the mock instances
1918        let mut mock_state = MockProtocolSim::new();
1919
1920        mock_state
1921            .expect_clone_box()
1922            .times(1)
1923            .returning(|| {
1924                let mut cloned_mock_state = MockProtocolSim::new();
1925                // Expect `delta_transition` to be called once with any parameters
1926                cloned_mock_state
1927                    .expect_delta_transition()
1928                    .times(1)
1929                    .returning(|_, _, _| Ok(()));
1930                cloned_mock_state
1931                    .expect_clone_box()
1932                    .times(1)
1933                    .returning(|| Box::new(MockProtocolSim::new()));
1934                Box::new(cloned_mock_state)
1935            });
1936
1937        // Insert mock state into `updated_states`
1938        let pool_id =
1939            "0x93d199263632a4ef4bb438f1feb99e57b4b5f0bd0000000000000000000005c2".to_string();
1940        decoder
1941            .state
1942            .write()
1943            .await
1944            .states
1945            .insert(pool_id.clone(), Box::new(mock_state) as Box<dyn ProtocolSim>);
1946        decoder
1947            .state
1948            .write()
1949            .await
1950            .contracts_map
1951            .insert(
1952                Bytes::from("0xba12222222228d8ba445958a75a0704d566bf2c8").lpad(20, 0),
1953                HashSet::from([pool_id.clone()]),
1954            );
1955
1956        // Load a test message containing a contract update
1957        let msg = load_test_msg("balancer_v2_delta");
1958
1959        // Decode the message
1960        let _ = decoder
1961            .decode(&msg)
1962            .await
1963            .expect("decode failure");
1964
1965        // The mock framework will assert that `delta_transition` was called exactly once
1966    }
1967
1968    /// The pending block's account deltas must reach the clone of every pool linked to a written
1969    /// account, and never the stored confirmed state.
1970    #[tokio::test]
1971    async fn test_apply_deltas_ephemeral_sets_pending_overrides_on_the_clone_only() {
1972        use tycho_common::models::{
1973            blockchain::BlockAggregatedChanges, contract::AccountDelta,
1974            protocol::ProtocolComponentStateDelta, ChangeType as ModelChangeType,
1975        };
1976
1977        use crate::evm::protocol::uniswap_v4::state::{UniswapV4Fees, UniswapV4State};
1978
1979        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
1980        let pool_id = "0xhooked".to_string();
1981        let quiet_pool_id = "0xhooked-no-log".to_string();
1982        let pool = UniswapV4State::new(
1983            1000,
1984            U256::from(1u8) << 96,
1985            UniswapV4Fees::new(0, 0, 3000),
1986            0,
1987            60,
1988            vec![],
1989        )
1990        .unwrap();
1991        let hook = Bytes::from(vec![7u8; 20]);
1992        {
1993            let mut state = decoder.state.write().await;
1994            state
1995                .states
1996                .insert(pool_id.clone(), Box::new(pool.clone()));
1997            state
1998                .states
1999                .insert(quiet_pool_id.clone(), Box::new(pool));
2000            state
2001                .contracts_map
2002                .insert(hook.clone(), HashSet::from([pool_id.clone(), quiet_pool_id.clone()]));
2003            for id in [&pool_id, &quiet_pool_id] {
2004                state
2005                    .components
2006                    .insert(id.clone(), component_with_protocol_system(id, "uniswap_v4_hooks"));
2007            }
2008        }
2009
2010        let deltas = BlockAggregatedChanges {
2011            extractor: "uniswap_v4_hooks".to_string(),
2012            state_deltas: HashMap::from([(
2013                pool_id.clone(),
2014                ProtocolComponentStateDelta {
2015                    component_id: pool_id.clone(),
2016                    updated_attributes: HashMap::from([(
2017                        "liquidity".to_string(),
2018                        Bytes::from(2000_u64.to_be_bytes().to_vec()),
2019                    )]),
2020                    deleted_attributes: HashSet::new(),
2021                    created_attributes: HashSet::new(),
2022                },
2023            )]),
2024            account_deltas: HashMap::from([(
2025                hook.clone(),
2026                AccountDelta::new(
2027                    Chain::Ethereum,
2028                    hook.clone(),
2029                    HashMap::from([(Bytes::from(vec![0u8]), Some(Bytes::from(vec![9u8])))]),
2030                    None,
2031                    None,
2032                    ModelChangeType::Update,
2033                ),
2034            )]),
2035            ..Default::default()
2036        };
2037        let header = BlockHeader { number: 10, timestamp: 20, ..Default::default() };
2038
2039        let update = decoder
2040            .apply_deltas_ephemeral(
2041                &HashMap::from([("uniswap_v4_hooks".to_string(), deltas)]),
2042                header,
2043            )
2044            .await
2045            .unwrap();
2046
2047        let clone = update.states[&pool_id]
2048            .as_any()
2049            .downcast_ref::<UniswapV4State>()
2050            .unwrap();
2051        let pending = clone
2052            .pending_overrides()
2053            .expect("the clone carries the pending block's overrides");
2054        assert_eq!(
2055            pending.block,
2056            Some(BlockEnvOverrides { number: Some(10), timestamp: Some(20) })
2057        );
2058        assert_eq!(
2059            pending.storage.as_ref().unwrap()[&Address::from_slice(&hook)][&U256::ZERO],
2060            U256::from(9)
2061        );
2062        let quiet = update.states[&quiet_pool_id]
2063            .as_any()
2064            .downcast_ref::<UniswapV4State>()
2065            .expect("a pool whose hook was written is cloned without a delta of its own");
2066        assert!(quiet.pending_overrides().is_some());
2067
2068        let stored = decoder.state.read().await;
2069        for id in [&pool_id, &quiet_pool_id] {
2070            let stored = stored.states[id]
2071                .as_any()
2072                .downcast_ref::<UniswapV4State>()
2073                .unwrap();
2074            assert!(stored.pending_overrides().is_none(), "confirmed state is never overlaid");
2075        }
2076    }
2077
2078    fn component_with_protocol_system(id: &str, protocol_system: &str) -> ProtocolComponent {
2079        ProtocolComponent::new(
2080            Bytes::from(id.as_bytes().to_vec()),
2081            protocol_system.to_string(),
2082            "test".to_string(),
2083            Chain::Ethereum,
2084            vec![],
2085            vec![],
2086            HashMap::new(),
2087            Bytes::default(),
2088            chrono::NaiveDateTime::default(),
2089        )
2090    }
2091
2092    /// Builds account deltas that set slot 0 of `account` to `value`.
2093    fn account_write(
2094        account: &Bytes,
2095        value: u8,
2096    ) -> HashMap<Bytes, tycho_common::models::contract::AccountDelta> {
2097        use tycho_common::models::{contract::AccountDelta, ChangeType as ModelChangeType};
2098
2099        HashMap::from([(
2100            account.clone(),
2101            AccountDelta::new(
2102                Chain::Ethereum,
2103                account.clone(),
2104                HashMap::from([(Bytes::from(vec![0u8]), Some(Bytes::from(vec![value])))]),
2105                None,
2106                None,
2107                ModelChangeType::Update,
2108            ),
2109        )])
2110    }
2111
2112    /// Builds a state delta for `pool_id` that sets its `reserves` attribute.
2113    fn reserves_delta(
2114        pool_id: &str,
2115    ) -> HashMap<String, tycho_common::models::protocol::ProtocolComponentStateDelta> {
2116        use tycho_common::models::protocol::ProtocolComponentStateDelta;
2117
2118        HashMap::from([(
2119            pool_id.to_string(),
2120            ProtocolComponentStateDelta {
2121                component_id: pool_id.to_string(),
2122                updated_attributes: HashMap::from([(
2123                    "reserves".to_string(),
2124                    Bytes::from(vec![1u8]),
2125                )]),
2126                deleted_attributes: HashSet::new(),
2127                created_attributes: HashSet::new(),
2128            },
2129        )])
2130    }
2131
2132    /// Whether `overrides` are `PendingOverrides` that set slot 0 of `account` to `value`.
2133    fn sets_slot_zero(overrides: &Arc<dyn Any + Send + Sync>, account: &Bytes, value: u8) -> bool {
2134        overrides
2135            .downcast_ref::<PendingOverrides>()
2136            .and_then(|pending| pending.storage.as_ref())
2137            .and_then(|storage| storage.get(&Address::from_slice(account)))
2138            .and_then(|slots| slots.get(&U256::ZERO))
2139            .is_some_and(|slot| *slot == U256::from(value))
2140    }
2141
2142    /// Builds a decoder that stores `stored` as `pool_id` and links it to `account`. Adds a
2143    /// component of `protocol_system` for the pool only when `protocol_system` is `Some`.
2144    async fn decoder_with_linked_pool(
2145        pool_id: &str,
2146        stored: MockProtocolSim,
2147        account: &Bytes,
2148        protocol_system: Option<&str>,
2149    ) -> TychoStreamDecoder<BlockHeader> {
2150        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
2151        {
2152            let mut state = decoder.state.write().await;
2153            state
2154                .states
2155                .insert(pool_id.to_string(), Box::new(stored));
2156            state
2157                .contracts_map
2158                .insert(account.clone(), HashSet::from([pool_id.to_string()]));
2159            if let Some(protocol_system) = protocol_system {
2160                state.components.insert(
2161                    pool_id.to_string(),
2162                    component_with_protocol_system(pool_id, protocol_system),
2163                );
2164            }
2165        }
2166        decoder
2167    }
2168
2169    /// When one extractor has both a state delta for a pool and a write to an account linked to
2170    /// that pool, the decoder clones the pool once, applies the delta with the extractor's
2171    /// component balances, then sets the overrides on that clone.
2172    #[tokio::test]
2173    async fn test_apply_deltas_ephemeral_applies_state_delta_before_overrides() {
2174        use tycho_common::models::protocol::ComponentBalance;
2175
2176        let pool_id = "0xpool";
2177        let account = Bytes::from(vec![5u8; 20]);
2178        let token = Bytes::from(vec![3u8; 20]);
2179        let mut sequence = mockall::Sequence::new();
2180        let mut clone = MockProtocolSim::new();
2181        let expected_token = token.clone();
2182        clone
2183            .expect_delta_transition()
2184            .withf(move |delta, _, balances| {
2185                delta
2186                    .updated_attributes
2187                    .contains_key("reserves") &&
2188                    balances.component_balances[pool_id][&expected_token] == vec![7u8]
2189            })
2190            .times(1)
2191            .in_sequence(&mut sequence)
2192            .returning(|_, _, _| Ok(()));
2193        clone
2194            .expect_set_pending_overrides()
2195            .times(1)
2196            .in_sequence(&mut sequence)
2197            .returning(|_| Ok(()));
2198        let mut stored = MockProtocolSim::new();
2199        stored
2200            .expect_clone_box()
2201            .times(1)
2202            .return_once(move || Box::new(clone));
2203        let decoder =
2204            decoder_with_linked_pool(pool_id, stored, &account, Some("uniswap_v4_hooks")).await;
2205        let balance = ComponentBalance::new(
2206            token.clone(),
2207            Bytes::from(vec![7u8]),
2208            7.0,
2209            Bytes::default(),
2210            pool_id,
2211        );
2212        let pending = HashMap::from([(
2213            "uniswap_v4_hooks".to_string(),
2214            BlockAggregatedChanges {
2215                state_deltas: reserves_delta(pool_id),
2216                account_deltas: account_write(&account, 1),
2217                component_balances: HashMap::from([(
2218                    pool_id.to_string(),
2219                    HashMap::from([(token, balance)]),
2220                )]),
2221                ..Default::default()
2222            },
2223        )]);
2224
2225        let update = decoder
2226            .apply_deltas_ephemeral(&pending, BlockHeader { number: 10, ..Default::default() })
2227            .await
2228            .unwrap();
2229
2230        assert!(update.states.contains_key(pool_id));
2231    }
2232
2233    /// When an extractor writes an account linked to a pool of another protocol system, or to a
2234    /// pool with no component, the decoder neither clones the pool nor sets overrides on it.
2235    #[rstest]
2236    #[case::other_protocol_system(Some("fluid_v1"), "vm:curve")]
2237    #[case::no_component(None, "fluid_v1")]
2238    #[tokio::test]
2239    async fn test_apply_deltas_ephemeral_skips_pools_of_other_protocol_systems(
2240        #[case] pool_protocol_system: Option<&str>,
2241        #[case] extractor_key: &str,
2242    ) {
2243        let account = Bytes::from(vec![6u8; 20]);
2244        let mut stored = MockProtocolSim::new();
2245        stored.expect_clone_box().times(0);
2246        let decoder =
2247            decoder_with_linked_pool("0xpool", stored, &account, pool_protocol_system).await;
2248        let pending = HashMap::from([(
2249            extractor_key.to_string(),
2250            BlockAggregatedChanges {
2251                account_deltas: account_write(&account, 1),
2252                ..Default::default()
2253            },
2254        )]);
2255
2256        let update = decoder
2257            .apply_deltas_ephemeral(&pending, BlockHeader { number: 10, ..Default::default() })
2258            .await
2259            .unwrap();
2260
2261        assert!(update.states.is_empty());
2262    }
2263
2264    /// When two extractors write the same account, linked to one pool of each, each pool takes
2265    /// only its own extractor's overrides, whatever order the extractors run in.
2266    #[tokio::test]
2267    async fn test_apply_deltas_ephemeral_gives_each_pool_its_own_extractors_overrides() {
2268        let account = Bytes::from(vec![8u8; 20]);
2269        let pools = [("0xfluid", "fluid_v1", 1u8), ("0xhooked", "uniswap_v4_hooks", 2u8)];
2270        let decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
2271        {
2272            let mut state = decoder.state.write().await;
2273            for (pool_id, protocol_system, value) in pools {
2274                let expected_account = account.clone();
2275                let mut clone = MockProtocolSim::new();
2276                clone
2277                    .expect_delta_transition()
2278                    .returning(|_, _, _| Ok(()));
2279                clone
2280                    .expect_set_pending_overrides()
2281                    .withf(move |overrides| sets_slot_zero(overrides, &expected_account, value))
2282                    .times(1)
2283                    .returning(|_| Ok(()));
2284                let mut stored = MockProtocolSim::new();
2285                stored
2286                    .expect_clone_box()
2287                    .times(1)
2288                    .return_once(move || Box::new(clone));
2289                state
2290                    .states
2291                    .insert(pool_id.to_string(), Box::new(stored));
2292                state.components.insert(
2293                    pool_id.to_string(),
2294                    component_with_protocol_system(pool_id, protocol_system),
2295                );
2296            }
2297            state.contracts_map.insert(
2298                account.clone(),
2299                pools
2300                    .map(|(pool_id, ..)| pool_id.to_string())
2301                    .into(),
2302            );
2303        }
2304        let pending: HashMap<String, BlockAggregatedChanges> = pools
2305            .into_iter()
2306            .map(|(_, protocol_system, value)| {
2307                let changes = BlockAggregatedChanges {
2308                    account_deltas: account_write(&account, value),
2309                    ..Default::default()
2310                };
2311                (protocol_system.to_string(), changes)
2312            })
2313            .collect();
2314
2315        let update = decoder
2316            .apply_deltas_ephemeral(&pending, BlockHeader { number: 10, ..Default::default() })
2317            .await
2318            .unwrap();
2319
2320        assert_eq!(update.states.len(), 2);
2321    }
2322
2323    /// The decoder links pools by the `pending_deltas` key and ignores
2324    /// `BlockAggregatedChanges::extractor`.
2325    #[tokio::test]
2326    async fn test_apply_deltas_ephemeral_links_pools_by_pending_deltas_key() {
2327        let pool_id = "0xfluid";
2328        let account = Bytes::from(vec![6u8; 20]);
2329        let mut clone = MockProtocolSim::new();
2330        clone
2331            .expect_delta_transition()
2332            .returning(|_, _, _| Ok(()));
2333        clone
2334            .expect_set_pending_overrides()
2335            .times(1)
2336            .returning(|_| Ok(()));
2337        let mut stored = MockProtocolSim::new();
2338        stored
2339            .expect_clone_box()
2340            .times(1)
2341            .return_once(move || Box::new(clone));
2342        let decoder = decoder_with_linked_pool(pool_id, stored, &account, Some("fluid_v1")).await;
2343        let pending = HashMap::from([(
2344            "fluid_v1".to_string(),
2345            BlockAggregatedChanges {
2346                extractor: "fluid".to_string(),
2347                account_deltas: account_write(&account, 1),
2348                ..Default::default()
2349            },
2350        )]);
2351
2352        let update = decoder
2353            .apply_deltas_ephemeral(&pending, BlockHeader { number: 10, ..Default::default() })
2354            .await
2355            .unwrap();
2356
2357        assert!(update.states.contains_key(pool_id));
2358    }
2359
2360    /// When a pool's own state delta fails, the decoder leaves the pool out of the update, even
2361    /// when the same extractor writes an account linked to it.
2362    #[tokio::test]
2363    async fn test_apply_deltas_ephemeral_leaves_out_a_pool_whose_own_delta_failed() {
2364        let pool_id = "0xpool";
2365        let account = Bytes::from(vec![5u8; 20]);
2366        let mut stored = MockProtocolSim::new();
2367        stored
2368            .expect_clone_box()
2369            .times(1)
2370            .returning(|| {
2371                let mut clone = MockProtocolSim::new();
2372                clone
2373                    .expect_delta_transition()
2374                    .returning(|_, _, _| Err(TransitionError::DecodeError("reserves".to_string())));
2375                Box::new(clone)
2376            });
2377        let decoder = decoder_with_linked_pool(pool_id, stored, &account, Some("fluid_v1")).await;
2378        let pending = HashMap::from([(
2379            "fluid_v1".to_string(),
2380            BlockAggregatedChanges {
2381                state_deltas: reserves_delta(pool_id),
2382                account_deltas: account_write(&account, 1),
2383                ..Default::default()
2384            },
2385        )]);
2386
2387        let update = decoder
2388            .apply_deltas_ephemeral(&pending, BlockHeader { number: 10, ..Default::default() })
2389            .await
2390            .unwrap();
2391
2392        assert!(!update.states.contains_key(pool_id));
2393    }
2394
2395    #[test]
2396    fn test_generate_proxy_token_address() {
2397        let idx = 1;
2398        let generated_address =
2399            generate_proxy_token_address(idx).expect("proxy token address should be valid");
2400        assert_eq!(generated_address, address!("000000000000000000000000000000001badbabe"));
2401
2402        let idx = 123456;
2403        let generated_address =
2404            generate_proxy_token_address(idx).expect("proxy token address should be valid");
2405        assert_eq!(generated_address, address!("00000000000000000000000000001e240badbabe"));
2406    }
2407
2408    /// A single-block feed message holding one tokenless Uniswap V4 pool whose `hooks` attribute
2409    /// points at an address no native handler is registered for.
2410    ///
2411    /// The component has no tokens and the message no VM storage, so decoding it neither reads
2412    /// nor writes the process-wide simulation engine and cannot disturb other tests.
2413    fn hooked_v4_msg() -> FeedMessage<BlockHeader> {
2414        use tycho_client::feed::synchronizer::{Snapshot, StateSyncMessage};
2415        use tycho_common::models::protocol::{ProtocolComponent, ProtocolComponentState};
2416
2417        let id = "0x00000000000000000000000000000000000000000000000000000000000000c4";
2418        let static_attributes = HashMap::from([
2419            ("key_lp_fee".to_string(), Bytes::from(500_i32.to_be_bytes().to_vec())),
2420            ("tick_spacing".to_string(), Bytes::from(60_i32.to_be_bytes().to_vec())),
2421            (
2422                "hooks".to_string(),
2423                Bytes::from_str("0x00000000000000000000000000000000000000c4").unwrap(),
2424            ),
2425        ]);
2426        let attributes = HashMap::from([
2427            ("liquidity".to_string(), Bytes::from(100_u64.to_be_bytes().to_vec())),
2428            ("tick".to_string(), Bytes::from(300_i32.to_be_bytes().to_vec())),
2429            (
2430                "sqrt_price_x96".to_string(),
2431                Bytes::from(
2432                    79228162514264337593543950336_u128
2433                        .to_be_bytes()
2434                        .to_vec(),
2435                ),
2436            ),
2437            ("protocol_fees/zero2one".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
2438            ("protocol_fees/one2zero".to_string(), Bytes::from(0_u32.to_be_bytes().to_vec())),
2439            ("ticks/60/net_liquidity".to_string(), Bytes::from(400_i128.to_be_bytes().to_vec())),
2440        ]);
2441
2442        let snapshot = ComponentWithState {
2443            state: ProtocolComponentState::new(id, attributes, HashMap::new()),
2444            component: ProtocolComponent {
2445                id: id.to_string(),
2446                static_attributes,
2447                ..Default::default()
2448            },
2449            component_tvl: None,
2450            entrypoints: Vec::new(),
2451        };
2452
2453        FeedMessage {
2454            state_msgs: HashMap::from([(
2455                "uniswap_v4_hooks".to_string(),
2456                StateSyncMessage {
2457                    header: header_at(1, 1_000, None),
2458                    snapshots: Snapshot {
2459                        states: HashMap::from([(id.to_string(), snapshot)]),
2460                        vm_storage: HashMap::new(),
2461                    },
2462                    deltas: None,
2463                    removed_components: HashMap::new(),
2464                },
2465            )]),
2466            sync_states: HashMap::new(),
2467        }
2468    }
2469
2470    /// A decoder for `chain` that decodes [`hooked_v4_msg`].
2471    fn hooked_v4_decoder(chain: Chain, context: DecoderContext) -> TychoStreamDecoder<BlockHeader> {
2472        let mut decoder = TychoStreamDecoder::new(chain);
2473        decoder.register_decoder_with_context::<crate::evm::protocol::uniswap_v4::state::UniswapV4State>(
2474            "uniswap_v4_hooks", context
2475        );
2476        decoder
2477    }
2478
2479    #[tokio::test]
2480    async fn test_unregistered_hook_is_rejected_off_the_generic_vm_chains() {
2481        let decoder = hooked_v4_decoder(Chain::Robinhood, DecoderContext::new());
2482
2483        let Err(StreamDecodeError::Fatal(message)) = decoder.decode(&hooked_v4_msg()).await else {
2484            panic!("a hooked pool on robinhood must not decode");
2485        };
2486
2487        assert!(message.contains("unsupported uniswap v4 hook"), "{message}");
2488        assert!(message.contains("robinhood"), "{message}");
2489    }
2490
2491    #[tokio::test]
2492    async fn test_decoder_chain_overrides_the_registered_context_chain() {
2493        let decoder =
2494            hooked_v4_decoder(Chain::Robinhood, DecoderContext::new().chain(Chain::Ethereum));
2495
2496        let Err(StreamDecodeError::Fatal(message)) = decoder.decode(&hooked_v4_msg()).await else {
2497            panic!("the decoder's chain must win over the context's");
2498        };
2499
2500        assert!(message.contains("robinhood"), "{message}");
2501    }
2502
2503    #[tokio::test]
2504    async fn test_unregistered_hook_takes_the_generic_path_on_ethereum() {
2505        let decoder = hooked_v4_decoder(Chain::Ethereum, DecoderContext::new());
2506
2507        let Err(StreamDecodeError::Fatal(message)) = decoder.decode(&hooked_v4_msg()).await else {
2508            panic!("the generic VM creator has no balance_owner attribute to work from");
2509        };
2510
2511        assert!(!message.contains("unsupported uniswap v4 hook"), "{message}");
2512        assert!(message.contains("balance_owner"), "{message}");
2513    }
2514
2515    #[tokio::test(flavor = "multi_thread")]
2516    async fn test_euler_hook_low_pool_manager_balance() {
2517        let mut decoder = TychoStreamDecoder::new(Chain::Ethereum);
2518
2519        decoder.register_decoder_with_context::<crate::evm::protocol::uniswap_v4::state::UniswapV4State>(
2520            "uniswap_v4_hooks", DecoderContext::new().vm_traces(true)
2521        );
2522
2523        let weth = Bytes::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap();
2524        let teth = Bytes::from_str("0xd11c452fc99cf405034ee446803b6f6c1f6d5ed8").unwrap();
2525        let tokens = HashMap::from([
2526            (
2527                weth.clone(),
2528                Token::new(&weth, "WETH", 18, 100, &[Some(100_000)], Chain::Ethereum, 100),
2529            ),
2530            (
2531                teth.clone(),
2532                Token::new(&teth, "tETH", 18, 100, &[Some(100_000)], Chain::Ethereum, 100),
2533            ),
2534        ]);
2535
2536        decoder.set_tokens(tokens.clone()).await;
2537
2538        let msg = load_test_msg("euler_hook_snapshot");
2539        let res = decoder
2540            .decode(&msg)
2541            .await
2542            .expect("decode failure");
2543
2544        let pool_state = res
2545            .states
2546            .get("0xc70d7fbd7fcccdf726e02fed78548b40dc52502b097c7a1ee7d995f4d4396134")
2547            .expect("Couldn't find target pool");
2548        let amount_out = pool_state
2549            .get_amount_out(
2550                BigUint::from_str("1000000000000000000").unwrap(),
2551                tokens.get(&teth).unwrap(),
2552                tokens.get(&weth).unwrap(),
2553            )
2554            .expect("Get amount out failed");
2555
2556        assert_eq!(amount_out.amount, BigUint::from_str("1216190190361759119").unwrap());
2557    }
2558
2559    /// A single-block feed message carrying `snapshot` as a `uniswap_v4_hooks` component.
2560    fn pons_feed_message(snapshot: ComponentWithState) -> FeedMessage<BlockHeader> {
2561        use tycho_client::feed::synchronizer::{Snapshot, StateSyncMessage};
2562
2563        use crate::evm::protocol::uniswap_v4::pons_fixture;
2564
2565        FeedMessage {
2566            state_msgs: HashMap::from([(
2567                "uniswap_v4_hooks".to_string(),
2568                StateSyncMessage {
2569                    header: pons_fixture::header(),
2570                    snapshots: Snapshot {
2571                        states: HashMap::from([(pons_fixture::POOL_ID.to_string(), snapshot)]),
2572                        vm_storage: HashMap::new(),
2573                    },
2574                    deltas: None,
2575                    removed_components: HashMap::new(),
2576                },
2577            )]),
2578            sync_states: HashMap::new(),
2579        }
2580    }
2581
2582    /// A decoder for Robinhood that knows the fixture pool's two tokens.
2583    async fn pons_stream_decoder() -> TychoStreamDecoder<BlockHeader> {
2584        use crate::evm::protocol::uniswap_v4::{
2585            hooks::hook_handler_creator::initialize_hook_handlers, pons_fixture,
2586            state::UniswapV4State,
2587        };
2588
2589        initialize_hook_handlers().expect("hook handler registration should succeed");
2590        let mut decoder = TychoStreamDecoder::new(Chain::Robinhood);
2591        decoder.register_decoder::<UniswapV4State>("uniswap_v4_hooks");
2592        decoder
2593            .set_tokens(pons_fixture::tokens())
2594            .await;
2595        decoder
2596    }
2597
2598    /// The whole stream path on Robinhood: a Pons pool arrives in a snapshot, is emitted as a
2599    /// `UniswapV4State` carrying the native handler, and quotes the hookless output less the fee
2600    /// and the tax `registerPool` froze for it.
2601    #[tokio::test]
2602    async fn test_pons_pool_decodes_through_the_stream_decoder_on_robinhood() {
2603        use crate::evm::protocol::uniswap_v4::{
2604            hooks::pons_v2::hook_handler::PonsV2HookHandler, pons_fixture, state::UniswapV4State,
2605        };
2606
2607        let decoder = pons_stream_decoder().await;
2608
2609        let result = decoder
2610            .decode(&pons_feed_message(pons_fixture::snapshot()))
2611            .await
2612            .expect("decode failure");
2613
2614        let emitted = result
2615            .states
2616            .get(pons_fixture::POOL_ID)
2617            .expect("the Pons pool must reach consumers");
2618        let pool = emitted
2619            .as_any()
2620            .downcast_ref::<UniswapV4State>()
2621            .expect("a uniswap_v4_hooks component decodes into a UniswapV4State");
2622        let handler = pool
2623            .hook
2624            .as_ref()
2625            .expect("a Pons pool must carry a hook handler");
2626        let pons = handler
2627            .as_any()
2628            .downcast_ref::<PonsV2HookHandler>()
2629            .expect("the registry must hand back the native Pons handler");
2630        assert_eq!(u32::from(pons.hook_fee_bps()), pons_fixture::HOOK_FEE_BPS);
2631        assert_eq!(u32::from(pons.creator_tax_bps()), pons_fixture::CREATOR_TAX_BPS);
2632
2633        let core = pons_fixture::decode_on(pons_fixture::hookless_snapshot(), Chain::Robinhood)
2634            .await
2635            .expect("the same pool with no hook must decode too");
2636        let (xlg, nvda) = (pons_fixture::xlg(), pons_fixture::nvda());
2637        let amount_in = BigUint::from(10u64).pow(18);
2638        for (token_in, token_out) in [(&xlg, &nvda), (&nvda, &xlg)] {
2639            let core_out = core
2640                .get_amount_out(amount_in.clone(), token_in, token_out)
2641                .expect("the reference pool quotes one whole token")
2642                .amount;
2643            let hooked_out = emitted
2644                .get_amount_out(amount_in.clone(), token_in, token_out)
2645                .expect("the emitted pool quotes one whole token")
2646                .amount;
2647
2648            let expected = pons_fixture::net_of_hook_take(&core_out);
2649            assert!(expected < core_out, "the hook must take something out of {core_out}");
2650            assert_eq!(hooked_out, expected, "{} -> {}", token_in.symbol, token_out.symbol);
2651        }
2652    }
2653
2654    /// The same pool behind a hook with no native handler never reaches consumers, even when the
2655    /// stream is configured to carry on past a decode failure.
2656    #[tokio::test]
2657    async fn test_unknown_hook_component_is_not_emitted_on_robinhood() {
2658        use crate::evm::protocol::uniswap_v4::pons_fixture;
2659
2660        let mut decoder = pons_stream_decoder().await;
2661        decoder.skip_state_decode_failures(true);
2662
2663        let result = decoder
2664            .decode(&pons_feed_message(pons_fixture::unknown_hook_snapshot()))
2665            .await
2666            .expect("a skipped decode failure is not fatal");
2667
2668        assert!(
2669            !result
2670                .states
2671                .contains_key(pons_fixture::POOL_ID),
2672            "a pool whose hook cannot be modelled must not be quoted"
2673        );
2674        assert!(result.states.is_empty());
2675    }
2676
2677    fn component_with_id(id: &str) -> ComponentWithState {
2678        use tycho_common::models::protocol::{ProtocolComponent, ProtocolComponentState};
2679
2680        ComponentWithState {
2681            state: ProtocolComponentState::new(id, HashMap::new(), HashMap::new()),
2682            component: ProtocolComponent { id: id.to_string(), ..Default::default() },
2683            component_tvl: None,
2684            entrypoints: Vec::new(),
2685        }
2686    }
2687
2688    fn rejects_a(component: &ComponentWithState) -> bool {
2689        component.component.id != "a"
2690    }
2691
2692    fn rejects_b(component: &ComponentWithState) -> bool {
2693        component.component.id != "b"
2694    }
2695
2696    #[test]
2697    fn test_admits_requires_every_registered_filter() {
2698        // Two filters on one exchange both apply: the second registration does not replace the
2699        // first, and a component must pass both. An exchange without filters admits everything.
2700        let mut decoder = TychoStreamDecoder::<BlockHeader>::new(Chain::Ethereum);
2701        decoder.register_filter("x", rejects_a);
2702        decoder.register_filter("x", rejects_b);
2703
2704        assert!(!decoder.admits("x", &component_with_id("a")));
2705        assert!(!decoder.admits("x", &component_with_id("b")));
2706        assert!(decoder.admits("x", &component_with_id("c")));
2707        assert!(decoder.admits("y", &component_with_id("a")));
2708    }
2709}