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