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