Skip to main content

tycho_simulation/evm/protocol/vm/
state.rs

1#![expect(
2    deprecated,
3    reason = "reads and writes the deprecated balance_owner field of EVMPoolState"
4)]
5use std::{
6    any::Any,
7    collections::{HashMap, HashSet},
8    fmt::{self, Debug},
9    str::FromStr,
10    sync::{PoisonError, RwLock, RwLockReadGuard, RwLockWriteGuard},
11    time::{SystemTime, UNIX_EPOCH},
12};
13
14use alloy::primitives::{Address, U256};
15use itertools::Itertools;
16use num_bigint::BigUint;
17use revm::DatabaseRef;
18use rustc_hash::FxHashMap;
19use serde::{Deserialize, Serialize};
20use tokio::sync::watch;
21use tracing::{debug, warn};
22use tycho_common::{
23    dto::ProtocolStateDelta,
24    models::token::Token,
25    simulation::{
26        errors::{SimulationError, TransitionError},
27        protocol_sim::{Balances, GetAmountOutResult, ProtocolSim},
28    },
29    Bytes,
30};
31
32use super::{
33    constants::{EXTERNAL_ACCOUNT, MAX_BALANCE},
34    erc20_token::{Overwrites, TokenProxyOverwriteFactory},
35    models::Capability,
36    tycho_simulation_contract::TychoSimulationContract,
37};
38use crate::{
39    evm::{
40        engine_db::{engine_db_interface::EngineDatabaseInterface, tycho_db::PreCachedDB},
41        override_stream::{FailurePolicy, OverrideSnapshot},
42        protocol::{
43            u256_num::{u256_to_biguint, u256_to_f64},
44            utils::bytes_to_address,
45        },
46        simulation::BlockEnvOverrides,
47    },
48    utils::{decimals_exponent, decimals_i32},
49};
50
51/// Cached derived values (spot prices, swap limits) for one pool-state version.
52///
53/// Both maps live behind a single lock so the invalidation policy has one home:
54/// - [`Self::invalidate`] drops everything; call it whenever the pool's own state changes (the
55///   per-block update, a post-swap child state, attaching live overrides).
56/// - Cached limits additionally carry the [`LimitContext`] they were computed under; a context
57///   mismatch at read time is a miss, so limits self-correct when the engine's current block or the
58///   pool's block-env overrides move without any pool-level event.
59///
60/// Spot prices deliberately carry no block context: they are eagerly re-warmed each block by
61/// `update_pool_state` and are allowed to go stale on paths that skip it (the documented
62/// `manual_updates` contract).
63///
64/// Lock poisoning is recovered from rather than propagated: the critical sections only perform
65/// map reads/inserts/clears, so a poisoned guard cannot hold a torn value, while propagating
66/// would turn one panicked thread into a panic in every worker sharing the pool.
67#[derive(Default)]
68struct DerivedCaches {
69    inner: RwLock<CacheState>,
70}
71
72#[derive(Clone, Default)]
73struct CacheState {
74    /// Keyed by `(sell, buy)` — equivalently `(base, quote)` as used by
75    /// [`ProtocolSim::spot_price`].
76    spot_prices: FxHashMap<(Address, Address), f64>,
77    /// `(sell_limit, buy_limit)` keyed by `(sell, buy)`, valid only under `limit_context`.
78    limits: FxHashMap<(Address, Address), (U256, U256)>,
79    /// Context the cached `limits` were computed under; `None` while `limits` is empty.
80    limit_context: Option<LimitContext>,
81}
82
83/// Simulation context a cached limit depends on besides the pool's own state: the engine's
84/// current block and the pool's resolved block-env overrides.
85#[derive(Clone, Debug, PartialEq)]
86struct LimitContext {
87    /// `(number, timestamp, partial_block_index)` of the engine's current block.
88    block: Option<(u64, u64, Option<u32>)>,
89    block_env: Option<BlockEnvOverrides>,
90}
91
92impl DerivedCaches {
93    fn read(&self) -> RwLockReadGuard<'_, CacheState> {
94        self.inner
95            .read()
96            .unwrap_or_else(PoisonError::into_inner)
97    }
98
99    fn write(&self) -> RwLockWriteGuard<'_, CacheState> {
100        self.inner
101            .write()
102            .unwrap_or_else(PoisonError::into_inner)
103    }
104
105    fn get_spot_price(&self, key: (Address, Address)) -> Option<f64> {
106        self.read()
107            .spot_prices
108            .get(&key)
109            .copied()
110    }
111
112    fn insert_spot_price(&self, key: (Address, Address), price: f64) {
113        self.write()
114            .spot_prices
115            .insert(key, price);
116    }
117
118    fn get_limits(&self, key: (Address, Address), context: &LimitContext) -> Option<(U256, U256)> {
119        let state = self.read();
120        if state.limit_context.as_ref() != Some(context) {
121            return None;
122        }
123        state.limits.get(&key).copied()
124    }
125
126    fn insert_limits(&self, key: (Address, Address), limits: (U256, U256), context: LimitContext) {
127        let mut state = self.write();
128        if state.limit_context.as_ref() != Some(&context) {
129            state.limits.clear();
130            state.limit_context = Some(context);
131        }
132        state.limits.insert(key, limits);
133    }
134
135    /// Drops all cached values. The pool's own state changed, so nothing derived from the
136    /// previous version may be served again.
137    fn invalidate(&self) {
138        let mut state = self.write();
139        state.spot_prices.clear();
140        state.limits.clear();
141        state.limit_context = None;
142    }
143}
144
145impl Clone for DerivedCaches {
146    /// Deep copy: a clone owns an independent cache, never a shared lock.
147    fn clone(&self) -> Self {
148        Self { inner: RwLock::new(self.read().clone()) }
149    }
150}
151
152#[derive(Clone)]
153#[expect(
154    clippy::partial_pub_fields,
155    reason = "public API; making `tokens` private or the rest public is a breaking change"
156)]
157pub struct EVMPoolState<D: EngineDatabaseInterface + Clone + Debug>
158where
159    <D as DatabaseRef>::Error: Debug,
160    <D as EngineDatabaseInterface>::Error: Debug,
161{
162    /// The pool's identifier
163    id: String,
164    /// The pool's token's addresses
165    pub tokens: Vec<Bytes>,
166    /// The pool's component balances.
167    balances: HashMap<Address, U256>,
168    /// The contract address for where protocol balances are stored (i.e. a vault contract).
169    /// If given, balances will be overwritten here instead of on the pool contract during
170    /// simulations. This has been deprecated in favor of `contract_balances`.
171    #[deprecated(note = "Use contract_balances instead")]
172    balance_owner: Option<Address>,
173    /// Derived values cached for the current pool-state version; see [`DerivedCaches`].
174    ///
175    /// Regular pools read through both caches: `spot_price` lazily populates on a miss and
176    /// `update_pool_state` eagerly re-warms each block. Pools with live overrides only ever
177    /// populate spot prices eagerly (their override-derived prices change sub-block, so
178    /// `spot_price` errors on a miss instead of computing against a possibly newer snapshot)
179    /// and bypass the limit cache entirely.
180    caches: DerivedCaches,
181    /// The supported capabilities of this pool
182    capabilities: HashSet<Capability>,
183    /// Storage overwrites that will be applied to all simulations. They will be cleared
184    /// when ``update_pool_state`` is called, i.e. usually at each block. Hence, the name.
185    block_lasting_overwrites: HashMap<Address, Overwrites>,
186    /// A set of all contract addresses involved in the simulation of this pool.
187    involved_contracts: HashSet<Address>,
188    /// A map of contracts to their token balances.
189    contract_balances: HashMap<Address, HashMap<Address, U256>>,
190    /// Indicates if the protocol uses custom update rules and requires update
191    /// triggers to recalculate spot prices ect. Default is to update on all changes on
192    /// the pool.
193    manual_updates: bool,
194    /// Caller (`tx.origin`) for the adapter's `price()` query; `None` defaults to
195    /// `EXTERNAL_ACCOUNT`. Set per protocol in the decoder (see `spot_price_caller`).
196    spot_price_caller: Option<Address>,
197    /// The adapter contract. This is used to interact with the protocol when running simulations
198    adapter_contract: TychoSimulationContract<D>,
199    /// Tokens for which balance overwrites should be disabled.
200    disable_overwrite_tokens: HashSet<Address>,
201    /// Tokens whose protocol does not emit token contract storage (e.g. FermiSwap), so they are
202    /// bare `TokenProxy` accounts with no implementation in the shared DB. For these, the
203    /// overwrites keep transfers in the proxy's local bookkeeping — holders get a custom approval
204    /// and the swap recipient a custom balance — so a `transferFrom` never delegates to a real
205    /// implementation another VM protocol (curve, balancer) mounted on the same shared token,
206    /// which would revert with `SafeERC20FailedOperation` (ENG-6161). Rebase/fee tokens in
207    /// `disable_overwrite_tokens` are excluded.
208    self_contained_tokens: HashSet<Address>,
209    /// Block context overrides applied to this pool's adapter simulations.
210    block_overrides: Option<BlockEnvOverrides>,
211    /// Live per-block VM overrides (e.g. Titan pAMM oracle prices) read at simulation time.
212    ///
213    /// When set, the latest [`OverrideSnapshot`] is merged into the pool's storage overwrites and
214    /// block environment on every simulation, so sub-block updates are reflected without a Tycho
215    /// block update. Takes precedence over [`Self::block_lasting_overwrites`] and
216    /// [`Self::block_overrides`] on conflict.
217    live_overrides: Option<watch::Receiver<OverrideSnapshot>>,
218}
219
220impl<D> Debug for EVMPoolState<D>
221where
222    D: EngineDatabaseInterface + Clone + Debug,
223    <D as DatabaseRef>::Error: Debug,
224    <D as EngineDatabaseInterface>::Error: Debug,
225{
226    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227        f.debug_struct("EVMPoolState")
228            .field("id", &self.id)
229            .field("tokens", &self.tokens)
230            .field("balances", &self.balances)
231            .field("involved_contracts", &self.involved_contracts)
232            .field("contract_balances", &self.contract_balances)
233            .finish_non_exhaustive()
234    }
235}
236
237impl<D> EVMPoolState<D>
238where
239    D: EngineDatabaseInterface + Clone + Debug + 'static,
240    <D as DatabaseRef>::Error: Debug,
241    <D as EngineDatabaseInterface>::Error: Debug,
242{
243    /// Creates a new instance of `EVMPoolState` with the given attributes, with the ability to
244    /// simulate a protocol-agnostic transaction.
245    ///
246    /// See struct definition of `EVMPoolState` for attribute explanations.
247    #[expect(
248        clippy::too_many_arguments,
249        reason = "public API; grouping the arguments into a params struct or builder is a breaking change"
250    )]
251    pub fn new(
252        id: String,
253        tokens: Vec<Bytes>,
254        component_balances: HashMap<Address, U256>,
255        balance_owner: Option<Address>,
256        contract_balances: HashMap<Address, HashMap<Address, U256>>,
257        spot_prices: HashMap<(Address, Address), f64>,
258        capabilities: HashSet<Capability>,
259        block_lasting_overwrites: HashMap<Address, Overwrites>,
260        involved_contracts: HashSet<Address>,
261        manual_updates: bool,
262        adapter_contract: TychoSimulationContract<D>,
263        disable_overwrite_tokens: HashSet<Address>,
264        self_contained_tokens: HashSet<Address>,
265        block_overrides: Option<BlockEnvOverrides>,
266        spot_price_caller: Option<Address>,
267    ) -> Self {
268        let caches = DerivedCaches::default();
269        caches.write().spot_prices = spot_prices.into_iter().collect();
270        Self {
271            id,
272            tokens,
273            balances: component_balances,
274            balance_owner,
275            caches,
276            capabilities,
277            block_lasting_overwrites,
278            involved_contracts,
279            contract_balances,
280            manual_updates,
281            adapter_contract,
282            disable_overwrite_tokens,
283            self_contained_tokens,
284            block_overrides,
285            spot_price_caller,
286            live_overrides: None,
287        }
288    }
289
290    /// Attaches a live override channel (e.g. from a Titan pAMM provider).
291    ///
292    /// Once set, the latest snapshot is read on every simulation; see [`Self::live_overrides`].
293    pub fn set_live_overrides(&mut self, receiver: watch::Receiver<OverrideSnapshot>) {
294        self.live_overrides = Some(receiver);
295        // Values cached before the channel was attached were computed without overrides and
296        // would otherwise be served by the cache-read fast paths.
297        self.caches.invalidate();
298    }
299
300    /// A copy of this pool representing a new state version: identical inputs, fresh caches.
301    ///
302    /// Use this instead of `clone()` when the copy's state is about to diverge (e.g. the
303    /// post-swap state returned by `get_amount_out`), so the previous version's derived values
304    /// are never copied only to be discarded.
305    fn clone_invalidated(&self) -> Self {
306        Self {
307            id: self.id.clone(),
308            tokens: self.tokens.clone(),
309            balances: self.balances.clone(),
310            balance_owner: self.balance_owner,
311            caches: DerivedCaches::default(),
312            capabilities: self.capabilities.clone(),
313            block_lasting_overwrites: self.block_lasting_overwrites.clone(),
314            involved_contracts: self.involved_contracts.clone(),
315            contract_balances: self.contract_balances.clone(),
316            manual_updates: self.manual_updates,
317            adapter_contract: self.adapter_contract.clone(),
318            disable_overwrite_tokens: self.disable_overwrite_tokens.clone(),
319            self_contained_tokens: self.self_contained_tokens.clone(),
320            block_overrides: self.block_overrides.clone(),
321            spot_price_caller: self.spot_price_caller,
322            live_overrides: self.live_overrides.clone(),
323        }
324    }
325
326    /// `(number, timestamp, partial_block_index)` of the engine DB's current block, used to
327    /// stamp cached limits with the block they were computed under.
328    fn current_engine_block(&self) -> Option<(u64, u64, Option<u32>)> {
329        self.adapter_contract
330            .engine
331            .state
332            .get_current_block()
333            .map(|block| (block.number, block.timestamp, block.partial_block_index))
334    }
335
336    /// Reads the latest live override snapshot once, if a channel is attached and still fresh.
337    ///
338    /// The `watch::Ref` guard is released immediately; the returned value is a clone. A single
339    /// simulation resolves both its storage overwrites and its block environment from this one
340    /// snapshot, so it can never mix storage from one snapshot with a block environment from
341    /// another, and never holds the channel's read lock across EVM calls.
342    ///
343    /// Returns `None` once the snapshot has passed its provider-set expiry, so an expired override
344    /// is dropped and the pool transparently reverts to Tycho's indexed state.
345    fn get_live_snapshot(&self) -> Option<OverrideSnapshot> {
346        let snapshot = self
347            .live_overrides
348            .as_ref()
349            .map(|receiver| receiver.borrow().clone())?;
350        let now = SystemTime::now()
351            .duration_since(UNIX_EPOCH)
352            .map(|elapsed| elapsed.as_secs())
353            .unwrap_or(0);
354        if snapshot.is_expired(now) {
355            return None;
356        }
357        Some(snapshot)
358    }
359
360    /// Runs `simulate` against `live_snapshot` and, when the snapshot's provider opted into
361    /// [`FailurePolicy::FallbackToIndexedState`], retries a failure once on the plain indexed
362    /// state.
363    ///
364    /// `InvalidInput` failures are never retried: the simulation itself succeeded and the input
365    /// was merely clamped to the pool's limit. Note that under overrides the limit is itself
366    /// override-derived (it reflects the size the live maker quote covers), and that clamp is
367    /// treated as authoritative rather than retried against the indexed pool's larger limit.
368    fn run_with_indexed_fallback<T>(
369        pool_id: &str,
370        operation: &str,
371        live_snapshot: Option<&OverrideSnapshot>,
372        mut simulate: impl FnMut(Option<&OverrideSnapshot>) -> Result<T, SimulationError>,
373    ) -> Result<T, SimulationError> {
374        let attempt = simulate(live_snapshot);
375        let Err(error) = &attempt else { return attempt };
376        if matches!(error, SimulationError::InvalidInput(..)) {
377            return attempt;
378        }
379        let Some(snapshot) = live_snapshot
380            .filter(|snapshot| snapshot.failure_policy == FailurePolicy::FallbackToIndexedState)
381        else {
382            return attempt;
383        };
384        debug!(
385            pool = %pool_id,
386            %error,
387            snapshot_block = ?snapshot.block_number,
388            snapshot_ts = ?snapshot.block_timestamp,
389            expires_at = ?snapshot.expires_at,
390            override_accounts = snapshot.storage.len(),
391            "{operation} failed with live overrides; retrying on indexed state"
392        );
393        let retry = simulate(None);
394        if let Err(retry_error) = &retry {
395            warn!(pool = %pool_id, %retry_error, "{operation} retry on indexed state also failed");
396        }
397        retry
398    }
399
400    /// The block environment to apply to adapter simulations, resolved from a single pre-read
401    /// `live` snapshot: its block number/timestamp take precedence over the statically configured
402    /// [`Self::block_overrides`].
403    fn block_env(&self, live: Option<&OverrideSnapshot>) -> Option<BlockEnvOverrides> {
404        let base = self.block_overrides.to_owned();
405        let Some(snapshot) = live else {
406            return base;
407        };
408        if snapshot.block_number.is_none() && snapshot.block_timestamp.is_none() {
409            return base;
410        }
411        let mut overrides = base.unwrap_or_default();
412        if snapshot.block_number.is_some() {
413            overrides.number = snapshot.block_number;
414        }
415        if snapshot.block_timestamp.is_some() {
416            overrides.timestamp = snapshot.block_timestamp;
417        }
418        Some(overrides)
419    }
420
421    /// Sets the spot prices for a pool for all possible pairs of the given tokens.
422    ///
423    /// # Arguments
424    ///
425    /// * `tokens` - A hashmap of `Token` instances representing the tokens to calculate spot prices
426    ///   for.
427    ///
428    /// # Returns
429    ///
430    /// * `Result<(), SimulationError>` - Returns `Ok(())` if the spot prices are successfully set,
431    ///   or a `SimulationError` if an error occurs during the calculation or processing.
432    ///
433    /// # Behavior
434    ///
435    /// This function performs the following steps:
436    /// 1. Ensures the pool has the required capability to perform price calculations.
437    /// 2. Iterates over all permutations of token pairs (sell token and buy token). For each pair:
438    ///    - Retrieves all possible overwrites, considering the maximum balance limit.
439    ///    - Calculates the sell amount limit, considering the overwrites.
440    ///    - Invokes the adapter contract's `price` function to retrieve the calculated price for
441    ///      the token pair, considering the sell amount limit.
442    ///    - Processes the price based on whether the `ScaledPrice` capability is present:
443    ///       - If `ScaledPrice` is present, uses the price directly from the adapter contract.
444    ///       - If `ScaledPrice` is absent, scales the price by adjusting for token decimals.
445    ///    - Stores the calculated price in the `spot_prices` map with the token addresses as the
446    ///      key.
447    /// 3. Returns `Ok(())` upon successful completion or a `SimulationError` upon failure.
448    ///
449    /// # Usage
450    ///
451    /// Spot prices need to be set before attempting to retrieve prices using `spot_price`.
452    ///
453    /// Tip: Setting spot prices on the pool every time the pool actually changes will result in
454    /// faster price fetching than if prices are only set immediately before attempting to retrieve
455    /// prices.
456    pub fn set_spot_prices(&self, tokens: &HashMap<Bytes, Token>) -> Result<(), SimulationError> {
457        // Read the live snapshot once, so every pair (and both sub-swaps in the no-capability
458        // branch) simulates against one consistent snapshot.
459        let live_snapshot = self.get_live_snapshot();
460        Self::run_with_indexed_fallback(
461            &self.id,
462            "Spot prices",
463            live_snapshot.as_ref(),
464            |snapshot| self.set_spot_prices_with(tokens, snapshot),
465        )
466    }
467
468    /// Computes the spot price for a single `(sell, buy)` pair against `live_snapshot`'s overrides
469    /// (or the plain indexed state when `None`): via the adapter's `price` function when the pool
470    /// has the `PriceFunction` capability, otherwise approximated as a two-swap finite difference.
471    /// Does not touch the cache.
472    fn compute_spot_price(
473        &self,
474        tokens: &HashMap<Bytes, Token>,
475        sell_token_address: Address,
476        buy_token_address: Address,
477        live_snapshot: Option<&OverrideSnapshot>,
478    ) -> Result<f64, SimulationError> {
479        let block_overrides = self.block_env(live_snapshot);
480        if self
481            .capabilities
482            .contains(&Capability::PriceFunction)
483        {
484            let overwrites = Some(self.get_overwrites(
485                &[sell_token_address, buy_token_address],
486                *MAX_BALANCE / U256::from(100),
487                live_snapshot,
488            )?);
489
490            let (sell_amount_limit, _) = self.get_amount_limits(
491                &[sell_token_address, buy_token_address],
492                overwrites.clone(),
493                block_overrides.clone(),
494            )?;
495            let price_result = self.adapter_contract.price(
496                &self.id,
497                sell_token_address,
498                buy_token_address,
499                vec![sell_amount_limit / U256::from(100)],
500                overwrites,
501                self.spot_price_caller,
502                block_overrides,
503            )?;
504
505            if self
506                .capabilities
507                .contains(&Capability::ScaledPrice)
508            {
509                Ok(*price_result.first().ok_or_else(|| {
510                    SimulationError::FatalError("Calculated price array is empty".to_string())
511                })?)
512            } else {
513                let unscaled_price = price_result.first().ok_or_else(|| {
514                    SimulationError::FatalError("Calculated price array is empty".to_string())
515                })?;
516                let sell_token_decimals = self.get_decimals(tokens, &sell_token_address)?;
517                let buy_token_decimals = self.get_decimals(tokens, &buy_token_address)?;
518                Ok(*unscaled_price * 10f64.powi(decimals_i32(sell_token_decimals)?) /
519                    10f64.powi(decimals_i32(buy_token_decimals)?))
520            }
521        } else {
522            // If the pool does not support price function, we need to calculate spot prices by
523            // swapping two amounts and use the approximation to get the derivative.
524            let overwrites = Some(self.get_overwrites(
525                &[sell_token_address, buy_token_address],
526                *MAX_BALANCE / U256::from(100),
527                live_snapshot,
528            )?);
529
530            // Calculate the first sell amount (x1) as 1% of the maximum limit.
531            let x1 =
532                self.get_amount_limits(
533                    &[sell_token_address, buy_token_address],
534                    overwrites.clone(),
535                    block_overrides.clone(),
536                )?
537                .0 / U256::from(100);
538
539            // Calculate the second sell amount (x2) as x1 + 1% of x1. 1.01% of the max limit
540            let x2 = x1 + (x1 / U256::from(100));
541
542            // Perform a swap for the first sell amount (x1) and retrieve the received amount
543            // (y1).
544            let y1 = self
545                .adapter_contract
546                .swap(
547                    &self.id,
548                    sell_token_address,
549                    buy_token_address,
550                    false,
551                    x1,
552                    overwrites.clone(),
553                    block_overrides.clone(),
554                )?
555                .0
556                .received_amount;
557
558            // Perform a swap for the second sell amount (x2) and retrieve the received amount
559            // (y2).
560            let y2 = self
561                .adapter_contract
562                .swap(
563                    &self.id,
564                    sell_token_address,
565                    buy_token_address,
566                    false,
567                    x2,
568                    overwrites,
569                    block_overrides,
570                )?
571                .0
572                .received_amount;
573
574            let sell_token_decimals = self.get_decimals(tokens, &sell_token_address)?;
575            let buy_token_decimals = self.get_decimals(tokens, &buy_token_address)?;
576
577            let num = y2 - y1;
578            let den = x2 - x1;
579
580            // Calculate the marginal price, adjusting for token decimals.
581            let token_correction =
582                10f64.powi(decimals_exponent(sell_token_decimals, buy_token_decimals)?);
583            let num_f64 = u256_to_f64(num)?;
584            let den_f64 = u256_to_f64(den)?;
585            if den_f64 == 0.0 {
586                return Err(SimulationError::FatalError(
587                    "Failed to compute marginal price: denominator converted to 0".into(),
588                ));
589            }
590            Ok(num_f64 / den_f64 * token_correction)
591        }
592    }
593
594    /// Computes and stores spot prices against `live_snapshot`'s overrides (or the plain indexed
595    /// state when `None`).
596    fn set_spot_prices_with(
597        &self,
598        tokens: &HashMap<Bytes, Token>,
599        live_snapshot: Option<&OverrideSnapshot>,
600    ) -> Result<(), SimulationError> {
601        for [sell_token_address, buy_token_address] in self
602            .tokens
603            .iter()
604            .permutations(2)
605            .map(|p| [p[0], p[1]])
606        {
607            let sell_token_address = bytes_to_address(sell_token_address)?;
608            let buy_token_address = bytes_to_address(buy_token_address)?;
609
610            let price = self.compute_spot_price(
611                tokens,
612                sell_token_address,
613                buy_token_address,
614                live_snapshot,
615            )?;
616
617            self.caches
618                .insert_spot_price((sell_token_address, buy_token_address), price);
619        }
620
621        Ok(())
622    }
623
624    fn get_decimals(
625        &self,
626        tokens: &HashMap<Bytes, Token>,
627        sell_token_address: &Address,
628    ) -> Result<u32, SimulationError> {
629        tokens
630            .get(&Bytes::from(sell_token_address.as_slice()))
631            .map(|t| t.decimals)
632            .ok_or_else(|| {
633                SimulationError::FatalError(format!(
634                    "Failed to scale spot prices! Pool: {} Token 0x{:x} is not available!",
635                    self.id, sell_token_address
636                ))
637            })
638    }
639
640    /// Retrieves the sell and buy amount limit for a given pair of tokens and the given overwrites.
641    ///
642    /// Attempting to swap an amount of the sell token that exceeds the sell amount limit is not
643    /// advised and in most cases will result in a revert.
644    ///
645    /// Cached per `(sell, buy)` pair, stamped with the engine block and block-env overrides the
646    /// value was computed under; a stamp mismatch is a miss, so limits that depend on time (e.g.
647    /// an amplification ramp) self-correct each block even if the pool receives no deltas. The
648    /// cached value is assumed independent of the caller's overwrite amounts (guarded by
649    /// `test_get_limits_cached_matches_fresh`). Pools with live overrides derive limits from a
650    /// sub-block snapshot, so caching is bypassed and the adapter is called directly; see
651    /// [`Self::live_overrides`].
652    ///
653    /// # Arguments
654    ///
655    /// * `tokens` - A vec of tokens, where the first token is the sell token and the second is the
656    ///   buy token. The order of tokens in the input vector is significant and determines the
657    ///   direction of the price query.
658    /// * `overwrites` - A hashmap of overwrites to apply to the simulation.
659    ///
660    /// # Returns
661    ///
662    /// * `Result<(U256,U256), SimulationError>` - Returns the sell and buy amount limit as a `U256`
663    ///   if successful, or a `SimulationError` on failure.
664    fn get_amount_limits(
665        &self,
666        tokens: &[Address],
667        overwrites: Option<HashMap<Address, HashMap<U256, U256>>>,
668        block_overrides: Option<BlockEnvOverrides>,
669    ) -> Result<(U256, U256), SimulationError> {
670        if self.live_overrides.is_some() {
671            return self.adapter_contract.get_limits(
672                &self.id,
673                tokens[0],
674                tokens[1],
675                overwrites,
676                block_overrides,
677            );
678        }
679
680        let key = (tokens[0], tokens[1]);
681        let context =
682            LimitContext { block: self.current_engine_block(), block_env: block_overrides.clone() };
683        if let Some(limits) = self.caches.get_limits(key, &context) {
684            return Ok(limits);
685        }
686
687        let limits = self.adapter_contract.get_limits(
688            &self.id,
689            tokens[0],
690            tokens[1],
691            overwrites,
692            block_overrides,
693        )?;
694        self.caches
695            .insert_limits(key, limits, context);
696
697        Ok(limits)
698    }
699
700    /// Updates the pool state.
701    ///
702    /// It is assumed this is called on a new block. Therefore, first the pool's overwrites cache is
703    /// cleared, then the balances are updated and the spot prices are recalculated.
704    ///
705    /// # Arguments
706    ///
707    /// * `tokens` - A hashmap of token addresses to `Token` instances. This is necessary for
708    ///   calculating new spot prices.
709    /// * `balances` - A `Balances` instance containing all balance updates on the current block.
710    fn update_pool_state(
711        &mut self,
712        tokens: &HashMap<Bytes, Token>,
713        balances: &Balances,
714    ) -> Result<(), SimulationError> {
715        // clear cache
716        self.adapter_contract
717            .engine
718            .clear_temp_storage()
719            .map_err(|err| {
720                SimulationError::FatalError(format!("Failed to clear temporary storage: {err:?}",))
721            })?;
722        self.block_lasting_overwrites.clear();
723        self.caches.invalidate();
724
725        // Set balances. Component balances and contract balances are refreshed independently:
726        // hybrid pools (e.g. Balancer V3) carry both, and `get_balance_overwrites` layers
727        // contract balances over component balances. Skipping the contract-balance refresh
728        // whenever component balances exist would freeze contract balances at their snapshot
729        // values while the contract's indexed storage keeps advancing, which breaks any
730        // simulation that compares `balanceOf` against stored reserves (e.g. Balancer V3
731        // `settle` reverting with `BalanceNotSettled`).
732        if let Some(bals) = balances
733            .component_balances
734            .get(&self.id)
735        {
736            // Merge delta balances with existing balances instead of replacing them
737            // Prevents errors when delta balance changes do not affect all the pool tokens.
738            for (token, bal) in bals {
739                let addr = bytes_to_address(token).map_err(|e| {
740                    SimulationError::FatalError(format!(
741                        "Invalid token address in balance update: {token:?}: {e}"
742                    ))
743                })?;
744                self.balances
745                    .insert(addr, U256::from_be_slice(bal));
746            }
747        }
748        for contract in &self.involved_contracts {
749            if let Some(bals) = balances
750                .account_balances
751                .get(&Bytes::from(contract.as_slice()))
752            {
753                let contract_entry = self
754                    .contract_balances
755                    .entry(*contract)
756                    .or_default();
757                for (token, bal) in bals {
758                    let addr = bytes_to_address(token).map_err(|e| {
759                        SimulationError::FatalError(format!(
760                            "Invalid token address in balance update: {token:?}: {e}"
761                        ))
762                    })?;
763                    contract_entry.insert(addr, U256::from_be_slice(bal));
764                }
765            }
766        }
767
768        // reset spot prices
769        self.set_spot_prices(tokens)?;
770        Ok(())
771    }
772
773    fn get_overwrites(
774        &self,
775        tokens: &[Address],
776        max_amount: U256,
777        live: Option<&OverrideSnapshot>,
778    ) -> Result<HashMap<Address, Overwrites>, SimulationError> {
779        let token_overwrites = self.get_token_overwrites(tokens, max_amount)?;
780
781        // Merge `block_lasting_overwrites` with `token_overwrites`
782        let mut merged_overwrites =
783            Self::merge(self.block_lasting_overwrites.clone(), token_overwrites);
784
785        // Live overrides (e.g. Titan pAMM oracle state) take precedence on conflict.
786        if let Some(live) = live {
787            if !live.storage.is_empty() {
788                merged_overwrites = Self::merge(merged_overwrites, live.storage.as_ref().clone());
789            }
790        }
791
792        Ok(merged_overwrites)
793    }
794
795    fn get_token_overwrites(
796        &self,
797        tokens: &[Address],
798        max_amount: U256,
799    ) -> Result<HashMap<Address, Overwrites>, SimulationError> {
800        let sell_token = &tokens[0].clone(); //TODO: need to make it clearer from the interface
801        let mut res: Vec<HashMap<Address, Overwrites>> = Vec::new();
802        if !self
803            .capabilities
804            .contains(&Capability::TokenBalanceIndependent)
805        {
806            res.push(self.get_balance_overwrites()?);
807        }
808
809        let mut overwrites = TokenProxyOverwriteFactory::new(*sell_token, None);
810
811        overwrites.set_balance(max_amount, Address::from_slice(&*EXTERNAL_ACCOUNT.0));
812
813        // Set allowance for adapter_address to max_amount
814        overwrites.set_allowance(max_amount, self.adapter_contract.address, *EXTERNAL_ACCOUNT);
815
816        res.push(overwrites.get_overwrites());
817
818        // Self-contained tokens (see `self_contained_tokens`): pre-track EXTERNAL_ACCOUNT (the
819        // recipient) for each output token, so it's credited locally instead of bootstrapping its
820        // balance via the implementation.
821        for token in tokens.iter().skip(1) {
822            if self
823                .self_contained_tokens
824                .contains(token) &&
825                !self
826                    .disable_overwrite_tokens
827                    .contains(token)
828            {
829                let mut recipient = TokenProxyOverwriteFactory::new(*token, None);
830                recipient.set_balance(U256::ZERO, *EXTERNAL_ACCOUNT);
831                res.push(recipient.get_overwrites());
832            }
833        }
834
835        // Merge all overwrites into a single HashMap
836        Ok(res
837            .into_iter()
838            .fold(HashMap::new(), |acc, overwrite| Self::merge(acc, overwrite)))
839    }
840
841    /// Gets all balance overwrites for the pool's tokens.
842    ///
843    /// If the pool uses component balances, the balances are set for the balance owner (if exists)
844    /// or for the pool itself. If the pool uses contract balances, the balances are set for the
845    /// contracts involved in the pool.
846    ///
847    /// # Returns
848    ///
849    /// * `Result<HashMap<Address, Overwrites>, SimulationError>` - Returns a hashmap of address to
850    ///   `Overwrites` if successful, or a `SimulationError` on failure.
851    fn get_balance_overwrites(&self) -> Result<HashMap<Address, Overwrites>, SimulationError> {
852        let mut balance_overwrites: HashMap<Address, Overwrites> = HashMap::new();
853
854        // Use component balances for overrides
855        let address = match self.balance_owner {
856            Some(owner) => Some(owner),
857            None if !self.contract_balances.is_empty() => None,
858            None => Some(self.id.parse().map_err(|e| {
859                SimulationError::FatalError(format!(
860                    "Failed to get balance overwrites: Pool ID is not an address: {e}"
861                ))
862            })?),
863        };
864
865        if let Some(address) = address {
866            // Only override balances that are explicitly provided in self.balances
867            // This preserves existing balances for tokens not updated in delta transitions
868            for (token, bal) in &self.balances {
869                let mut overwrites = TokenProxyOverwriteFactory::new(*token, None);
870                overwrites.set_balance(*bal, address);
871                // Self-contained tokens (see `self_contained_tokens`): also grant a custom approval
872                // so `transferFrom` from the holder stays local instead of delegating to the impl.
873                if self
874                    .self_contained_tokens
875                    .contains(token)
876                {
877                    overwrites.set_has_custom_approval(address);
878                }
879                balance_overwrites.extend(overwrites.get_overwrites());
880            }
881        }
882
883        // Use contract balances for overrides (will overwrite component balances if they were set
884        // for a contract we explicitly track balances for)
885        for (contract, balances) in &self.contract_balances {
886            for (token, balance) in balances {
887                let mut overwrites = TokenProxyOverwriteFactory::new(*token, None);
888                overwrites.set_balance(*balance, *contract);
889                // Same as above: keep `transferFrom` from this contract local for self-contained
890                // tokens (see `self_contained_tokens`).
891                if self
892                    .self_contained_tokens
893                    .contains(token)
894                {
895                    overwrites.set_has_custom_approval(*contract);
896                }
897                balance_overwrites.extend(overwrites.get_overwrites());
898            }
899        }
900
901        // Apply disables for tokens that should not have any balance overrides
902        for token in &self.disable_overwrite_tokens {
903            balance_overwrites.remove(token);
904        }
905
906        Ok(balance_overwrites)
907    }
908
909    /// Merges `source` into `target` and returns the result. On a per-slot conflict, `source` wins.
910    fn merge(
911        mut target: HashMap<Address, Overwrites>,
912        source: HashMap<Address, Overwrites>,
913    ) -> HashMap<Address, Overwrites> {
914        for (key, source_inner) in source {
915            target
916                .entry(key)
917                .or_default()
918                .extend(source_inner);
919        }
920
921        target
922    }
923
924    #[cfg(test)]
925    pub fn get_involved_contracts(&self) -> HashSet<Address> {
926        self.involved_contracts.clone()
927    }
928
929    #[cfg(test)]
930    pub fn get_manual_updates(&self) -> bool {
931        self.manual_updates
932    }
933
934    #[cfg(test)]
935    pub fn get_spot_price_caller(&self) -> Option<Address> {
936        self.spot_price_caller
937    }
938
939    /// Simulates a sell of `amount_in` against `live_snapshot`'s overrides (or the plain indexed
940    /// state when `None`); see [`ProtocolSim::get_amount_out`] for the caller-facing contract.
941    fn get_amount_out_with(
942        &self,
943        amount_in: &BigUint,
944        token_in: &Token,
945        token_out: &Token,
946        live_snapshot: Option<&OverrideSnapshot>,
947    ) -> Result<GetAmountOutResult, SimulationError> {
948        let sell_token_address = bytes_to_address(&token_in.address)?;
949        let buy_token_address = bytes_to_address(&token_out.address)?;
950        let sell_amount = U256::from_be_slice(&amount_in.to_bytes_be());
951        let block_overrides = self.block_env(live_snapshot);
952        let overwrites = self.get_overwrites(
953            &[sell_token_address, buy_token_address],
954            *MAX_BALANCE / U256::from(100),
955            live_snapshot,
956        )?;
957        let (sell_amount_limit, _) = self.get_amount_limits(
958            &[sell_token_address, buy_token_address],
959            Some(overwrites.clone()),
960            block_overrides.clone(),
961        )?;
962        let (sell_amount_respecting_limit, sell_amount_exceeds_limit) = if self
963            .capabilities
964            .contains(&Capability::HardLimits) &&
965            sell_amount_limit < sell_amount
966        {
967            (sell_amount_limit, true)
968        } else {
969            (sell_amount, false)
970        };
971
972        let overwrites_with_sell_limit = self.get_overwrites(
973            &[sell_token_address, buy_token_address],
974            sell_amount_limit,
975            live_snapshot,
976        )?;
977        let complete_overwrites = Self::merge(overwrites, overwrites_with_sell_limit);
978
979        let (trade, state_changes) = self.adapter_contract.swap(
980            &self.id,
981            sell_token_address,
982            buy_token_address,
983            false,
984            sell_amount_respecting_limit,
985            Some(complete_overwrites),
986            block_overrides,
987        )?;
988
989        let mut new_state = self.clone_invalidated();
990
991        // Apply state changes to the new state
992        for (address, state_update) in state_changes {
993            if let Some(storage) = state_update.storage {
994                let block_overwrites = new_state
995                    .block_lasting_overwrites
996                    .entry(address)
997                    .or_default();
998                for (slot, value) in storage {
999                    let slot = U256::from_str(&slot.to_string()).map_err(|e| {
1000                        SimulationError::FatalError(format!("Failed to decode slot index: {e}"))
1001                    })?;
1002                    let value = U256::from_str(&value.to_string()).map_err(|e| {
1003                        SimulationError::FatalError(format!("Failed to decode slot overwrite: {e}"))
1004                    })?;
1005                    block_overwrites.insert(slot, value);
1006                }
1007            }
1008        }
1009
1010        if new_state.live_overrides.is_some() {
1011            // Override pools serve only eagerly-warmed spot prices (`spot_price` errors on a
1012            // miss rather than computing against a possibly newer snapshot), so the returned
1013            // state must be warmed here; failures fall back to the indexed state inside
1014            // `set_spot_prices`.
1015            let tokens = HashMap::from([
1016                (token_in.address.clone(), token_in.clone()),
1017                (token_out.address.clone(), token_out.clone()),
1018            ]);
1019            if let Err(error) = new_state.set_spot_prices(&tokens) {
1020                warn!(pool = %new_state.id, %error, "failed to warm spot prices of the returned state");
1021            }
1022        }
1023
1024        let buy_amount = trade.received_amount;
1025
1026        if sell_amount_exceeds_limit {
1027            return Err(SimulationError::InvalidInput(
1028                format!("Sell amount exceeds limit {sell_amount_limit}"),
1029                Some(GetAmountOutResult::new(
1030                    u256_to_biguint(buy_amount),
1031                    u256_to_biguint(trade.gas_used),
1032                    Box::new(new_state),
1033                )),
1034            ));
1035        }
1036        Ok(GetAmountOutResult::new(
1037            u256_to_biguint(buy_amount),
1038            u256_to_biguint(trade.gas_used),
1039            Box::new(new_state),
1040        ))
1041    }
1042
1043    /// Computes trade limits against `live_snapshot`'s overrides (or the plain indexed state when
1044    /// `None`); see [`ProtocolSim::get_limits`] for the caller-facing contract.
1045    fn get_limits_with(
1046        &self,
1047        sell_token: &Bytes,
1048        buy_token: &Bytes,
1049        live_snapshot: Option<&OverrideSnapshot>,
1050    ) -> Result<(BigUint, BigUint), SimulationError> {
1051        let sell_token = bytes_to_address(sell_token)?;
1052        let buy_token = bytes_to_address(buy_token)?;
1053        let overwrites = self.get_overwrites(
1054            &[sell_token, buy_token],
1055            *MAX_BALANCE / U256::from(100),
1056            live_snapshot,
1057        )?;
1058        let limits = self.get_amount_limits(
1059            &[sell_token, buy_token],
1060            Some(overwrites),
1061            self.block_env(live_snapshot),
1062        )?;
1063        Ok((u256_to_biguint(limits.0), u256_to_biguint(limits.1)))
1064    }
1065
1066    #[cfg(test)]
1067    pub fn get_balance_owner(&self) -> Option<Address> {
1068        self.balance_owner
1069    }
1070
1071    /// Get the component balances for validation purposes
1072    pub fn get_balances(&self) -> &HashMap<Address, U256> {
1073        &self.balances
1074    }
1075
1076    #[cfg(test)]
1077    pub fn get_block_overrides(&self) -> Option<BlockEnvOverrides> {
1078        let live_snapshot = self.get_live_snapshot();
1079        self.block_env(live_snapshot.as_ref())
1080    }
1081}
1082
1083impl<D> Serialize for EVMPoolState<D>
1084where
1085    D: EngineDatabaseInterface + Clone + Debug,
1086    <D as DatabaseRef>::Error: Debug,
1087    <D as EngineDatabaseInterface>::Error: Debug,
1088{
1089    fn serialize<S>(&self, _serializer: S) -> Result<S::Ok, S::Error>
1090    where
1091        S: serde::Serializer,
1092    {
1093        Err(serde::ser::Error::custom("not supported due vm state deps"))
1094    }
1095}
1096
1097impl<'de, D> Deserialize<'de> for EVMPoolState<D>
1098where
1099    D: EngineDatabaseInterface + Clone + Debug,
1100    <D as DatabaseRef>::Error: Debug,
1101    <D as EngineDatabaseInterface>::Error: Debug,
1102{
1103    fn deserialize<De>(_deserializer: De) -> Result<Self, De::Error>
1104    where
1105        De: serde::Deserializer<'de>,
1106    {
1107        Err(serde::de::Error::custom("not supported due vm state deps"))
1108    }
1109}
1110
1111#[typetag::serialize]
1112impl<D> ProtocolSim for EVMPoolState<D>
1113where
1114    D: EngineDatabaseInterface + Clone + Debug + 'static,
1115    <D as DatabaseRef>::Error: Debug,
1116    <D as EngineDatabaseInterface>::Error: Debug,
1117{
1118    #[expect(
1119        clippy::todo,
1120        reason = "fee() returns no error and the fee depends on the swap direction"
1121    )]
1122    fn fee(&self) -> f64 {
1123        todo!()
1124    }
1125
1126    fn spot_price(&self, base: &Token, quote: &Token) -> Result<f64, SimulationError> {
1127        let base_address = bytes_to_address(&base.address)?;
1128        let quote_address = bytes_to_address(&quote.address)?;
1129
1130        if let Some(price) = self
1131            .caches
1132            .get_spot_price((base_address, quote_address))
1133        {
1134            return Ok(price);
1135        }
1136
1137        // A pair the pool does not hold can never have a price; failing here keeps the error
1138        // actionable and spares the adapter one or two EVM simulations per bogus pair.
1139        if !self.tokens.contains(&base.address) || !self.tokens.contains(&quote.address) {
1140            return Err(SimulationError::FatalError(format!(
1141                "Spot price not found for base token {base_address} and quote token {quote_address}"
1142            )));
1143        }
1144
1145        // Pools with live overrides derive spot prices from a sub-block snapshot that changes
1146        // intra-block, so a lazily computed value could mix snapshots with the eagerly-warmed
1147        // pairs. Only the eagerly-warmed value is authoritative; a genuine miss is an error.
1148        if self.live_overrides.is_some() {
1149            return Err(SimulationError::FatalError(format!(
1150                "Spot price not found for base token {base_address} and quote token {quote_address}"
1151            )));
1152        }
1153
1154        // Compute this single pair on demand and cache it.
1155        let tokens = HashMap::from([
1156            (base.address.clone(), base.clone()),
1157            (quote.address.clone(), quote.clone()),
1158        ]);
1159        let price = self.compute_spot_price(&tokens, base_address, quote_address, None)?;
1160        self.caches
1161            .insert_spot_price((base_address, quote_address), price);
1162        Ok(price)
1163    }
1164
1165    fn get_amount_out(
1166        &self,
1167        amount_in: BigUint,
1168        token_in: &Token,
1169        token_out: &Token,
1170    ) -> Result<GetAmountOutResult, SimulationError> {
1171        // Read the live snapshot once so overwrites, limits and the swap use one snapshot.
1172        let live_snapshot = self.get_live_snapshot();
1173        Self::run_with_indexed_fallback(&self.id, "Swap", live_snapshot.as_ref(), |snapshot| {
1174            self.get_amount_out_with(&amount_in, token_in, token_out, snapshot)
1175        })
1176    }
1177
1178    fn get_limits(
1179        &self,
1180        sell_token: Bytes,
1181        buy_token: Bytes,
1182    ) -> Result<(BigUint, BigUint), SimulationError> {
1183        let live_snapshot = self.get_live_snapshot();
1184        Self::run_with_indexed_fallback(&self.id, "Limits", live_snapshot.as_ref(), |snapshot| {
1185            self.get_limits_with(&sell_token, &buy_token, snapshot)
1186        })
1187    }
1188
1189    fn delta_transition(
1190        &mut self,
1191        delta: ProtocolStateDelta,
1192        tokens: &HashMap<Bytes, Token>,
1193        balances: &Balances,
1194    ) -> Result<(), TransitionError> {
1195        if let Some(block_number) = delta
1196            .updated_attributes
1197            .get("override_block_number")
1198        {
1199            let number = <[u8; 8]>::try_from(block_number.as_ref())
1200                .map(u64::from_be_bytes)
1201                .map_err(|_wrong_length| {
1202                    TransitionError::DecodeError(
1203                        "override_block_number attribute must be an 8-byte big-endian u64"
1204                            .to_string(),
1205                    )
1206                })?;
1207            self.block_overrides
1208                .get_or_insert_with(BlockEnvOverrides::default)
1209                .number = Some(number);
1210        }
1211
1212        if let Some(block_timestamp) = delta
1213            .updated_attributes
1214            .get("override_block_timestamp")
1215        {
1216            let timestamp = <[u8; 8]>::try_from(block_timestamp.as_ref())
1217                .map(u64::from_be_bytes)
1218                .map_err(|_wrong_length| {
1219                    TransitionError::DecodeError(
1220                        "override_block_timestamp attribute must be an 8-byte big-endian u64"
1221                            .to_string(),
1222                    )
1223                })?;
1224            self.block_overrides
1225                .get_or_insert_with(BlockEnvOverrides::default)
1226                .timestamp = Some(timestamp);
1227        }
1228
1229        // No explicit cache handling is needed for the block-env updates above: cached limits
1230        // are stamped with the block env they were computed under (see `LimitContext`), so a
1231        // change here turns into a miss on the next read. Spot prices are deliberately allowed
1232        // to go stale when `update_pool_state` is skipped below — the `manual_updates` contract.
1233
1234        if self.manual_updates {
1235            // Directly check for "update_marker" in `updated_attributes`
1236            if let Some(marker) = delta
1237                .updated_attributes
1238                .get("update_marker")
1239            {
1240                // Assuming `marker` is of type `Bytes`, check its value for "truthiness"
1241                if !marker.is_empty() && marker[0] != 0 {
1242                    self.update_pool_state(tokens, balances)?;
1243                }
1244            }
1245        } else {
1246            self.update_pool_state(tokens, balances)?;
1247        }
1248
1249        Ok(())
1250    }
1251
1252    fn query_pool_swap(
1253        &self,
1254        params: &tycho_common::simulation::protocol_sim::QueryPoolSwapParams,
1255    ) -> Result<tycho_common::simulation::protocol_sim::PoolSwap, SimulationError> {
1256        crate::evm::query_pool_swap::query_pool_swap(self, params)
1257    }
1258
1259    fn clone_box(&self) -> Box<dyn ProtocolSim> {
1260        Box::new(self.clone())
1261    }
1262
1263    fn as_any(&self) -> &dyn Any {
1264        self
1265    }
1266
1267    fn as_any_mut(&mut self) -> &mut dyn Any {
1268        self
1269    }
1270
1271    fn eq(&self, other: &dyn ProtocolSim) -> bool {
1272        if let Some(other_state) = other
1273            .as_any()
1274            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1275        {
1276            self.id == other_state.id
1277        } else {
1278            false
1279        }
1280    }
1281
1282    /// Implemented manually because `typetag` macro not supports generics
1283    #[expect(
1284        clippy::unreachable,
1285        reason = "typetag only emits a call to this method to flag a missing attribute; it is never invoked"
1286    )]
1287    fn typetag_deserialize(&self) {
1288        // https://github.com/dtolnay/typetag/blob/21ae0d40c9f73443a20204ab4a134441355b52f7/impl/src/tagged_trait.rs#L140
1289        unreachable!("Only to catch missing typetag attribute on impl blocks. Not called.")
1290    }
1291}
1292
1293#[cfg(test)]
1294mod tests {
1295    use std::default::Default;
1296
1297    use num_traits::One;
1298    use revm::{
1299        primitives::KECCAK_EMPTY,
1300        state::{AccountInfo, Bytecode},
1301    };
1302    use serde_json::Value;
1303    use tycho_client::feed::BlockHeader;
1304    use tycho_common::models::Chain;
1305
1306    use super::*;
1307    use crate::evm::{
1308        engine_db::{create_engine, SHARED_TYCHO_DB},
1309        protocol::vm::{
1310            constants::{BALANCER_V2, ERC20_PROXY_BYTECODE},
1311            state_builder::EVMPoolStateBuilder,
1312        },
1313        simulation::SimulationEngine,
1314        tycho_models::AccountUpdate,
1315    };
1316
1317    fn dai() -> Token {
1318        Token::new(
1319            &Bytes::from_str("0x6b175474e89094c44da98b954eedeac495271d0f").unwrap(),
1320            "DAI",
1321            18,
1322            0,
1323            &[Some(10_000)],
1324            Chain::Ethereum,
1325            100,
1326        )
1327    }
1328
1329    fn bal() -> Token {
1330        Token::new(
1331            &Bytes::from_str("0xba100000625a3754423978a60c9317c58a424e3d").unwrap(),
1332            "BAL",
1333            18,
1334            0,
1335            &[Some(10_000)],
1336            Chain::Ethereum,
1337            100,
1338        )
1339    }
1340
1341    fn dai_addr() -> Address {
1342        bytes_to_address(&dai().address).unwrap()
1343    }
1344
1345    fn bal_addr() -> Address {
1346        bytes_to_address(&bal().address).unwrap()
1347    }
1348
1349    async fn setup_pool_state() -> EVMPoolState<PreCachedDB> {
1350        let data_str = include_str!("assets/balancer_contract_storage_block_20463609.json");
1351        let data: Value = serde_json::from_str(data_str).expect("Failed to parse JSON");
1352
1353        let accounts: Vec<AccountUpdate> = serde_json::from_value(data["accounts"].clone())
1354            .expect("Expected accounts to match AccountUpdate structure");
1355
1356        // The process-wide `SHARED_TYCHO_DB` holds a single current-block header, so tests
1357        // sharing it race; a fresh database keeps each pool independent.
1358        let db = PreCachedDB::new().expect("failed to create test database");
1359        let engine: SimulationEngine<_> = create_engine(db.clone(), false).unwrap();
1360
1361        let block = BlockHeader {
1362            number: 20463609,
1363            hash: Bytes::from_str(
1364                "0x4315fd1afc25cc2ebc72029c543293f9fd833eeb305e2e30159459c827733b1b",
1365            )
1366            .unwrap(),
1367            timestamp: 1722875891,
1368            ..Default::default()
1369        };
1370
1371        for account in accounts.clone() {
1372            engine
1373                .state
1374                .init_account(
1375                    account.address,
1376                    AccountInfo {
1377                        balance: account.balance.unwrap_or_default(),
1378                        nonce: 0u64,
1379                        code_hash: KECCAK_EMPTY,
1380                        code: account
1381                            .code
1382                            .clone()
1383                            .map(|arg0: Vec<u8>| Bytecode::new_raw(arg0.into())),
1384                    },
1385                    None,
1386                    false,
1387                )
1388                .expect("Failed to initialize account");
1389        }
1390        db.update(accounts, Some(block))
1391            .unwrap();
1392
1393        let tokens = vec![dai().address, bal().address];
1394        for token in &tokens {
1395            engine
1396                .state
1397                .init_account(
1398                    bytes_to_address(token).unwrap(),
1399                    AccountInfo {
1400                        balance: U256::from(0),
1401                        nonce: 0,
1402                        code_hash: KECCAK_EMPTY,
1403                        code: Some(Bytecode::new_raw(ERC20_PROXY_BYTECODE.into())),
1404                    },
1405                    None,
1406                    true,
1407                )
1408                .expect("Failed to initialize account");
1409        }
1410
1411        let block = BlockHeader {
1412            number: 18485417,
1413            hash: Bytes::from_str(
1414                "0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
1415            )
1416            .expect("Invalid block hash"),
1417            timestamp: 0,
1418            ..Default::default()
1419        };
1420        db.update(vec![], Some(block.clone()))
1421            .unwrap();
1422
1423        let pool_id: String =
1424            "0x4626d81b3a1711beb79f4cecff2413886d461677000200000000000000000011".into();
1425
1426        let stateless_contracts = HashMap::from([(
1427            String::from("0x3de27efa2f1aa663ae5d458857e731c129069f29"),
1428            Some(Vec::new()),
1429        )]);
1430
1431        let balances = HashMap::from([
1432            (dai_addr(), U256::from_str("178754012737301807104").unwrap()),
1433            (bal_addr(), U256::from_str("91082987763369885696").unwrap()),
1434        ]);
1435        let adapter_address =
1436            Address::from_str("0xA2C5C98A892fD6656a7F39A2f63228C0Bc846270").unwrap();
1437
1438        EVMPoolStateBuilder::new(pool_id, tokens, adapter_address)
1439            .balances(balances)
1440            .balance_owner(Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap())
1441            .adapter_contract_bytecode(Bytecode::new_raw(BALANCER_V2.into()))
1442            .stateless_contracts(stateless_contracts)
1443            .build(db)
1444            .await
1445            .expect("Failed to build pool state")
1446    }
1447
1448    #[tokio::test]
1449    async fn test_init() {
1450        let pool_state = setup_pool_state().await;
1451
1452        let expected_capabilities = vec![
1453            Capability::SellSide,
1454            Capability::BuySide,
1455            Capability::PriceFunction,
1456            Capability::HardLimits,
1457        ]
1458        .into_iter()
1459        .collect::<HashSet<_>>();
1460
1461        let capabilities_adapter_contract = pool_state
1462            .adapter_contract
1463            .get_capabilities(
1464                &pool_state.id,
1465                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1466                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1467            )
1468            .unwrap();
1469
1470        assert_eq!(capabilities_adapter_contract, expected_capabilities);
1471
1472        let capabilities_state = pool_state.clone().capabilities;
1473
1474        assert_eq!(capabilities_state, expected_capabilities);
1475
1476        // Verify all tokens are initialized in the engine
1477        let engine_accounts = pool_state
1478            .adapter_contract
1479            .engine
1480            .state
1481            .get_account_storage()
1482            .expect("Failed to get account storage");
1483        for token in pool_state.tokens {
1484            let account = engine_accounts
1485                .get_account_info(&bytes_to_address(&token).unwrap())
1486                .unwrap();
1487            assert_eq!(account.balance, U256::from(0));
1488            assert_eq!(account.nonce, 0u64);
1489            assert_eq!(account.code_hash, KECCAK_EMPTY);
1490            assert!(account.code.is_some());
1491        }
1492
1493        // Verify external account is initialized in the engine
1494        let external_account = engine_accounts
1495            .get_account_info(&EXTERNAL_ACCOUNT)
1496            .unwrap();
1497        assert_eq!(external_account.balance, U256::from(*MAX_BALANCE));
1498        assert_eq!(external_account.nonce, 0u64);
1499        assert_eq!(external_account.code_hash, KECCAK_EMPTY);
1500        assert!(external_account.code.is_none());
1501    }
1502
1503    #[tokio::test]
1504    async fn test_get_amount_out() {
1505        let pool_state = setup_pool_state().await;
1506
1507        let result = pool_state
1508            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1509            .unwrap();
1510        let new_state = result
1511            .new_state
1512            .as_any()
1513            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1514            .unwrap();
1515        assert_eq!(result.amount, BigUint::from_str("137780051463393923").unwrap());
1516        // The returned state starts with fresh caches; reading recomputes the post-swap price
1517        // lazily, which differs from the pre-swap price because the swap moved the pool.
1518        let pre = pool_state
1519            .spot_price(&dai(), &bal())
1520            .unwrap();
1521        let post = new_state
1522            .spot_price(&dai(), &bal())
1523            .unwrap();
1524        assert_ne!(pre, post);
1525        assert!(pool_state
1526            .block_lasting_overwrites
1527            .is_empty());
1528    }
1529
1530    #[tokio::test]
1531    async fn test_sequential_get_amount_outs() {
1532        let pool_state = setup_pool_state().await;
1533
1534        let result = pool_state
1535            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1536            .unwrap();
1537        let new_state = result
1538            .new_state
1539            .as_any()
1540            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1541            .unwrap();
1542        assert_eq!(result.amount, BigUint::from_str("137780051463393923").unwrap());
1543        // The returned state starts with fresh caches; a lazily-computed price against the
1544        // post-swap overwrites differs from the pre-swap price.
1545        let price_before_first_swap = pool_state
1546            .spot_price(&dai(), &bal())
1547            .unwrap();
1548        let price_after_first_swap = new_state
1549            .spot_price(&dai(), &bal())
1550            .unwrap();
1551        assert_ne!(price_before_first_swap, price_after_first_swap);
1552
1553        let new_result = new_state
1554            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1555            .unwrap();
1556        let new_state_second_swap = new_result
1557            .new_state
1558            .as_any()
1559            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1560            .unwrap();
1561
1562        assert_eq!(new_result.amount, BigUint::from_str("136964651490065626").unwrap());
1563        // Same after the second swap: the lazily recomputed price has moved again relative to
1564        // the state right after the first swap.
1565        let price_after_second_swap = new_state_second_swap
1566            .spot_price(&dai(), &bal())
1567            .unwrap();
1568        assert_ne!(price_after_first_swap, price_after_second_swap);
1569    }
1570
1571    #[tokio::test]
1572    async fn test_get_amount_out_dust() {
1573        let pool_state = setup_pool_state().await;
1574
1575        let result = pool_state
1576            .get_amount_out(BigUint::one(), &dai(), &bal())
1577            .unwrap();
1578
1579        let _ = result
1580            .new_state
1581            .as_any()
1582            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1583            .unwrap();
1584        assert_eq!(result.amount, BigUint::ZERO);
1585    }
1586
1587    #[tokio::test]
1588    async fn test_get_amount_out_sell_limit() {
1589        let pool_state = setup_pool_state().await;
1590
1591        let result = pool_state.get_amount_out(
1592            // sell limit is 100279494253364362835
1593            BigUint::from_str("100379494253364362835").unwrap(),
1594            &dai(),
1595            &bal(),
1596        );
1597
1598        assert!(result.is_err());
1599
1600        match result {
1601            Err(SimulationError::InvalidInput(msg1, amount_out_result)) => {
1602                assert_eq!(msg1, "Sell amount exceeds limit 100279494253364362835");
1603                assert!(amount_out_result.is_some());
1604            }
1605            _ => panic!("Test failed: was expecting an Err(SimulationError::RetryDifferentInput(_, _)) value"),
1606        }
1607    }
1608
1609    #[tokio::test]
1610    async fn test_get_amount_limits() {
1611        let pool_state = setup_pool_state().await;
1612
1613        let overwrites = pool_state
1614            .get_overwrites(
1615                &[
1616                    bytes_to_address(&pool_state.tokens[0]).unwrap(),
1617                    bytes_to_address(&pool_state.tokens[1]).unwrap(),
1618                ],
1619                *MAX_BALANCE / U256::from(100),
1620                None,
1621            )
1622            .unwrap();
1623        let (dai_limit, _) = pool_state
1624            .get_amount_limits(
1625                &[dai_addr(), bal_addr()],
1626                Some(overwrites.clone()),
1627                pool_state.block_env(None),
1628            )
1629            .unwrap();
1630        assert_eq!(dai_limit, U256::from_str("100279494253364362835").unwrap());
1631
1632        let (bal_limit, _) = pool_state
1633            .get_amount_limits(
1634                &[
1635                    bytes_to_address(&pool_state.tokens[1]).unwrap(),
1636                    bytes_to_address(&pool_state.tokens[0]).unwrap(),
1637                ],
1638                Some(overwrites),
1639                pool_state.block_env(None),
1640            )
1641            .unwrap();
1642        assert_eq!(bal_limit, U256::from_str("13997408640689987484").unwrap());
1643    }
1644
1645    #[tokio::test]
1646    async fn test_get_limits_cached_matches_fresh() {
1647        let pool_state = setup_pool_state().await;
1648        let overwrites = pool_state
1649            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
1650            .unwrap();
1651
1652        // First call populates the cache.
1653        let fresh = pool_state
1654            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1655            .unwrap();
1656        assert_eq!(
1657            pool_state
1658                .caches
1659                .read()
1660                .limits
1661                .get(&(dai_addr(), bal_addr()))
1662                .copied(),
1663            Some(fresh)
1664        );
1665
1666        // Second call returns the cached value, identical to the first.
1667        let cached = pool_state
1668            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites), None)
1669            .unwrap();
1670        assert_eq!(fresh, cached);
1671
1672        // The cache key deliberately excludes the overwrites: the limit must be independent of
1673        // the caller's overwrite amounts. Guard that by computing fresh, on a cold state, with
1674        // overwrites derived from a different amount, and comparing byte-for-byte.
1675        let cold = setup_pool_state().await;
1676        let different_overwrites = cold
1677            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(50), None)
1678            .unwrap();
1679        let independent = cold
1680            .get_amount_limits(&[dai_addr(), bal_addr()], Some(different_overwrites), None)
1681            .unwrap();
1682        assert_eq!(independent, fresh);
1683    }
1684
1685    /// A cached limit must not survive an engine-block advance, even when the pool receives no
1686    /// delta: the adapter computes limits against the engine's current block, so time-dependent
1687    /// limits (e.g. an amplification ramp) change with zero pool-level events.
1688    #[tokio::test]
1689    async fn test_engine_block_advance_invalidates_cached_limits() {
1690        let pool_state = setup_pool_state().await;
1691        let overwrites = pool_state
1692            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
1693            .unwrap();
1694        let real = pool_state
1695            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1696            .unwrap();
1697        let sentinel = (U256::from(1u64), U256::from(1u64));
1698        assert_ne!(real, sentinel);
1699        pool_state
1700            .caches
1701            .write()
1702            .limits
1703            .insert((dai_addr(), bal_addr()), sentinel);
1704
1705        // Sanity: the sentinel is served while the engine block is unchanged.
1706        let served = pool_state
1707            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1708            .unwrap();
1709        assert_eq!(served, sentinel);
1710
1711        // Advance the engine's current block without any pool-level event.
1712        let mut block = SHARED_TYCHO_DB
1713            .get_current_block()
1714            .expect("fixture sets an engine block");
1715        block.number += 1;
1716        block.timestamp += 12;
1717        SHARED_TYCHO_DB
1718            .update(vec![], Some(block))
1719            .expect("engine block update");
1720
1721        // The stamp mismatch turns the read into a miss: the sentinel is dead.
1722        let after = pool_state
1723            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites), None)
1724            .unwrap();
1725        assert_ne!(after, sentinel);
1726        assert_eq!(after, real);
1727    }
1728
1729    #[tokio::test]
1730    async fn test_set_spot_prices() {
1731        let pool_state = setup_pool_state().await;
1732
1733        pool_state
1734            .set_spot_prices(
1735                &vec![bal(), dai()]
1736                    .into_iter()
1737                    .map(|t| (t.address.clone(), t))
1738                    .collect(),
1739            )
1740            .unwrap();
1741
1742        let dai_bal_spot_price = pool_state
1743            .caches
1744            .get_spot_price((
1745                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1746                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1747            ))
1748            .unwrap();
1749        let bal_dai_spot_price = pool_state
1750            .caches
1751            .get_spot_price((
1752                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1753                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1754            ))
1755            .unwrap();
1756        assert_eq!(dai_bal_spot_price, 0.137_778_914_319_047_9);
1757        assert_eq!(bal_dai_spot_price, 7.071_503_245_428_246);
1758    }
1759
1760    #[tokio::test]
1761    async fn test_set_spot_prices_without_capability() {
1762        // Tests set Spot Prices functions when the pool doesn't have PriceFunction capability
1763        let mut pool_state = setup_pool_state().await;
1764
1765        pool_state
1766            .capabilities
1767            .remove(&Capability::PriceFunction);
1768
1769        pool_state
1770            .set_spot_prices(
1771                &vec![bal(), dai()]
1772                    .into_iter()
1773                    .map(|t| (t.address.clone(), t))
1774                    .collect(),
1775            )
1776            .unwrap();
1777
1778        let dai_bal_spot_price = pool_state
1779            .caches
1780            .get_spot_price((
1781                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1782                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1783            ))
1784            .unwrap();
1785        let bal_dai_spot_price = pool_state
1786            .caches
1787            .get_spot_price((
1788                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1789                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1790            ))
1791            .unwrap();
1792        assert_eq!(dai_bal_spot_price, 0.13736685496467538);
1793        assert_eq!(bal_dai_spot_price, 7.050354297665408);
1794    }
1795
1796    #[tokio::test]
1797    async fn test_spot_price_lazy_computes_on_miss() {
1798        let pool_state = setup_pool_state().await;
1799        // Non-override pool with a cold cache: the builder does not warm spot prices.
1800        assert!(pool_state
1801            .caches
1802            .read()
1803            .spot_prices
1804            .is_empty());
1805
1806        // Reading a pair computes it on demand, byte-identical to the eagerly-warmed values
1807        // pinned in `test_set_spot_prices`, and caches it.
1808        let dai_bal = pool_state
1809            .spot_price(&dai(), &bal())
1810            .unwrap();
1811        assert_eq!(dai_bal, 0.137_778_914_319_047_9);
1812        let bal_dai = pool_state
1813            .spot_price(&bal(), &dai())
1814            .unwrap();
1815        assert_eq!(bal_dai, 7.071_503_245_428_246);
1816        assert_eq!(
1817            pool_state
1818                .caches
1819                .get_spot_price((dai_addr(), bal_addr())),
1820            Some(dai_bal)
1821        );
1822    }
1823
1824    #[tokio::test]
1825    async fn test_get_balance_overwrites_with_component_balances() {
1826        let pool_state: EVMPoolState<PreCachedDB> = setup_pool_state().await;
1827
1828        let overwrites = pool_state
1829            .get_balance_overwrites()
1830            .unwrap();
1831
1832        let dai_address = dai_addr();
1833        let bal_address = bal_addr();
1834        assert!(overwrites.contains_key(&dai_address));
1835        assert!(overwrites.contains_key(&bal_address));
1836    }
1837
1838    #[tokio::test]
1839    async fn test_get_balance_overwrites_with_contract_balances() {
1840        let mut pool_state: EVMPoolState<PreCachedDB> = setup_pool_state().await;
1841
1842        let contract_address =
1843            Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap();
1844
1845        // Ensure no component balances are used
1846        pool_state.balances.clear();
1847        pool_state.balance_owner = None;
1848
1849        // Set contract balances
1850        let dai_address = dai_addr();
1851        let bal_address = bal_addr();
1852        pool_state.contract_balances = HashMap::from([(
1853            contract_address,
1854            HashMap::from([
1855                (dai_address, U256::from_str("7500000000000000000000").unwrap()), // 7500 DAI
1856                (bal_address, U256::from_str("1500000000000000000000").unwrap()), // 1500 BAL
1857            ]),
1858        )]);
1859
1860        let overwrites = pool_state
1861            .get_balance_overwrites()
1862            .unwrap();
1863
1864        assert!(overwrites.contains_key(&dai_address));
1865        assert!(overwrites.contains_key(&bal_address));
1866    }
1867
1868    #[tokio::test]
1869    async fn test_balance_merging_during_delta_transition() {
1870        use std::str::FromStr;
1871
1872        let mut pool_state = setup_pool_state().await;
1873        let pool_id = pool_state.id.clone();
1874
1875        // Test the balance merging logic more directly
1876        // Setup initial balances including DAI and BAL (which the pool already knows about)
1877        let dai_addr = dai_addr();
1878        let bal_addr = bal_addr();
1879        let new_token = Address::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(); // WETH
1880
1881        // Clear and setup clean initial state
1882        pool_state.balances.clear();
1883        pool_state
1884            .balances
1885            .insert(dai_addr, U256::from(1000000000u64));
1886        pool_state
1887            .balances
1888            .insert(bal_addr, U256::from(2000000000u64));
1889        pool_state
1890            .balances
1891            .insert(new_token, U256::from(3000000000u64));
1892
1893        // Create tokens mapping including the existing DAI and BAL
1894        let mut tokens = HashMap::new();
1895        tokens.insert(dai().address, dai());
1896        tokens.insert(bal().address, bal());
1897
1898        // Simulate a delta transition with only DAI balance update (missing BAL and new_token)
1899        let mut component_balances = HashMap::new();
1900        let mut delta_balances = HashMap::new();
1901        // Only update DAI balance, leave others unchanged in delta
1902        delta_balances.insert(dai().address, Bytes::from(vec![0x77, 0x35, 0x94, 0x00])); // 2000000000 (updated value)
1903        component_balances.insert(pool_id, delta_balances);
1904
1905        let balances = Balances { component_balances, account_balances: HashMap::new() };
1906
1907        // Record initial balance count
1908        let initial_balance_count = pool_state.balances.len();
1909        assert_eq!(initial_balance_count, 3);
1910
1911        // Apply delta transition
1912        pool_state
1913            .update_pool_state(&tokens, &balances)
1914            .unwrap();
1915
1916        // Verify that all 3 balances are preserved (BAL and new_token should still be there)
1917        assert_eq!(
1918            pool_state.balances.len(),
1919            3,
1920            "All balances should be preserved after delta transition"
1921        );
1922        assert!(
1923            pool_state
1924                .balances
1925                .contains_key(&dai_addr),
1926            "DAI balance should be present"
1927        );
1928        assert!(
1929            pool_state
1930                .balances
1931                .contains_key(&bal_addr),
1932            "BAL balance should be present"
1933        );
1934        assert!(
1935            pool_state
1936                .balances
1937                .contains_key(&new_token),
1938            "New token balance should be preserved from before delta"
1939        );
1940
1941        // Verify that updated token (DAI) has new value
1942        assert_eq!(
1943            pool_state.balances[&dai_addr],
1944            U256::from(2000000000u64),
1945            "DAI balance should be updated"
1946        );
1947
1948        // Verify that non-updated tokens retain their original values
1949        assert_eq!(
1950            pool_state.balances[&bal_addr],
1951            U256::from(2000000000u64),
1952            "BAL balance should be unchanged"
1953        );
1954        assert_eq!(
1955            pool_state.balances[&new_token],
1956            U256::from(3000000000u64),
1957            "New token balance should be unchanged"
1958        );
1959    }
1960
1961    #[tokio::test]
1962    async fn test_update_pool_state_warms_caches() {
1963        let mut pool_state = setup_pool_state().await;
1964        let tokens = HashMap::from([(dai().address, dai()), (bal().address, bal())]);
1965        let balances =
1966            Balances { component_balances: HashMap::new(), account_balances: HashMap::new() };
1967
1968        pool_state
1969            .update_pool_state(&tokens, &balances)
1970            .unwrap();
1971
1972        let caches = pool_state.caches.read();
1973        assert!(!caches.spot_prices.is_empty());
1974        assert!(!caches.limits.is_empty());
1975    }
1976
1977    #[tokio::test]
1978    async fn test_delta_transition_updates_block_overrides() {
1979        let mut pool_state = setup_pool_state().await;
1980        pool_state.manual_updates = true;
1981        pool_state.block_overrides = None;
1982
1983        let delta = ProtocolStateDelta {
1984            component_id: pool_state.id.clone(),
1985            updated_attributes: HashMap::from([
1986                ("override_block_number".to_string(), Bytes::from(123_u64.to_be_bytes().to_vec())),
1987                (
1988                    "override_block_timestamp".to_string(),
1989                    Bytes::from(456_u64.to_be_bytes().to_vec()),
1990                ),
1991            ]),
1992            deleted_attributes: HashSet::new(),
1993        };
1994
1995        pool_state
1996            .delta_transition(delta, &HashMap::new(), &Balances::default())
1997            .unwrap();
1998
1999        assert_eq!(
2000            pool_state.block_overrides,
2001            Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) })
2002        );
2003    }
2004
2005    #[tokio::test]
2006    async fn test_delta_transition_updates_partial_block_overrides() {
2007        let mut pool_state = setup_pool_state().await;
2008        pool_state.manual_updates = true;
2009        pool_state.block_overrides =
2010            Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) });
2011
2012        let delta = ProtocolStateDelta {
2013            component_id: pool_state.id.clone(),
2014            updated_attributes: HashMap::from([(
2015                "override_block_number".to_string(),
2016                Bytes::from(789_u64.to_be_bytes().to_vec()),
2017            )]),
2018            deleted_attributes: HashSet::new(),
2019        };
2020
2021        pool_state
2022            .delta_transition(delta, &HashMap::new(), &Balances::default())
2023            .unwrap();
2024
2025        assert_eq!(
2026            pool_state.block_overrides,
2027            Some(BlockEnvOverrides { number: Some(789), timestamp: Some(456) })
2028        );
2029    }
2030
2031    /// `update_pool_state` must refresh BOTH component balances and tracked contract balances,
2032    /// not treat them as mutually exclusive. Balancer V3 is hybrid (component balances at the
2033    /// vault owner + tracked vault contract balances); freezing contract balances while the
2034    /// vault's indexed reserves advance is what caused the WETH-in `BalanceNotSettled` failures.
2035    #[tokio::test]
2036    async fn test_delta_transition_refreshes_both_balance_maps() {
2037        let mut pool_state = setup_pool_state().await;
2038        let vault = Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap();
2039        // Non-manual pool (how Balancer V3 behaves once `manual_updates` is dropped): a contract
2040        // change routes the pool through delta_transition, which refreshes its balances.
2041        pool_state.manual_updates = false;
2042        pool_state.involved_contracts = HashSet::from([vault]);
2043        pool_state.contract_balances =
2044            HashMap::from([(vault, HashMap::from([(dai_addr(), U256::from(1u64))]))]);
2045
2046        let delta = ProtocolStateDelta {
2047            component_id: pool_state.id.clone(),
2048            updated_attributes: HashMap::new(),
2049            deleted_attributes: HashSet::new(),
2050        };
2051        let balances = Balances {
2052            component_balances: HashMap::new(),
2053            account_balances: HashMap::from([(
2054                Bytes::from(vault.as_slice()),
2055                HashMap::from([(dai().address, Bytes::from(42u64).lpad(32, 0))]),
2056            )]),
2057        };
2058
2059        // The spot-price refresh inside update_pool_state may fail in offline test
2060        // environments; the balance bookkeeping this test guards happens before it.
2061        #[expect(
2062            clippy::let_underscore_must_use,
2063            reason = "the offline spot-price refresh may fail; the assertions below cover the earlier bookkeeping"
2064        )]
2065        let _ = pool_state.delta_transition(delta, &HashMap::new(), &balances);
2066
2067        // Contract balance refreshed even though component balances are non-empty (the old
2068        // mutual-exclusion would have skipped this branch entirely).
2069        assert_eq!(pool_state.contract_balances[&vault][&dai_addr()], U256::from(42u64));
2070        // Component balances stay untouched by a contract-balance-only delta.
2071        assert_eq!(
2072            pool_state.balances[&dai_addr()],
2073            U256::from_str("178754012737301807104").unwrap()
2074        );
2075    }
2076
2077    /// A block-environment-only delta (no `update_marker`) on a `manual_updates` pool skips
2078    /// `update_pool_state`, but cached limits must not survive it: they are stamped with the
2079    /// block env they were computed under, so the changed env turns the next read into a miss.
2080    /// Spot prices are deliberately allowed to go stale in this skip path (the `manual_updates`
2081    /// contract).
2082    #[tokio::test]
2083    async fn test_block_override_delta_invalidates_cached_limits() {
2084        let mut pool_state = setup_pool_state().await;
2085        pool_state.manual_updates = true;
2086
2087        // Populate the limit cache, then poison the entry with a sentinel so a served cache hit
2088        // is distinguishable from a fresh computation.
2089        let overwrites = pool_state
2090            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
2091            .unwrap();
2092        let real = pool_state
2093            .get_amount_limits(
2094                &[dai_addr(), bal_addr()],
2095                Some(overwrites.clone()),
2096                pool_state.block_env(None),
2097            )
2098            .unwrap();
2099        let sentinel = (U256::from(1u64), U256::from(1u64));
2100        assert_ne!(real, sentinel);
2101        pool_state
2102            .caches
2103            .write()
2104            .limits
2105            .insert((dai_addr(), bal_addr()), sentinel);
2106
2107        // A delta that only changes the block env, with no `update_marker`.
2108        let delta = ProtocolStateDelta {
2109            component_id: pool_state.id.clone(),
2110            updated_attributes: HashMap::from([(
2111                "override_block_number".to_string(),
2112                Bytes::from(1234_u64.to_be_bytes().to_vec()),
2113            )]),
2114            deleted_attributes: HashSet::new(),
2115        };
2116        pool_state
2117            .delta_transition(delta, &HashMap::new(), &Balances::default())
2118            .unwrap();
2119
2120        // The changed block env must invalidate the sentinel: the read recomputes fresh.
2121        let after = pool_state
2122            .get_amount_limits(
2123                &[dai_addr(), bal_addr()],
2124                Some(overwrites),
2125                pool_state.block_env(None),
2126            )
2127            .unwrap();
2128        assert_ne!(after, sentinel);
2129    }
2130
2131    #[test]
2132    fn should_not_panic_at_typetag_deserialize() {
2133        let deserialized: Result<Box<dyn ProtocolSim>, _> = serde_json::from_str(
2134            r#"{"protocol":"EVMPoolState","state":{"reserve_0":1,"reserve_1":2}}"#,
2135        );
2136
2137        assert!(deserialized.is_err());
2138    }
2139
2140    /// A live snapshot's block number/timestamp take precedence over the static block overrides,
2141    /// field by field, while an absent or empty snapshot leaves them untouched.
2142    #[tokio::test]
2143    async fn test_block_env_prefers_live_overrides() {
2144        let mut pool_state = setup_pool_state().await;
2145        pool_state.block_overrides =
2146            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) });
2147
2148        // No live snapshot: the statically configured overrides are used unchanged.
2149        assert_eq!(
2150            pool_state.block_env(None),
2151            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) })
2152        );
2153
2154        // A live snapshot with neither field set does not touch the static overrides.
2155        let empty = OverrideSnapshot::default();
2156        assert_eq!(
2157            pool_state.block_env(Some(&empty)),
2158            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) })
2159        );
2160
2161        // Present live fields win; unset live fields keep the static value.
2162        let live = OverrideSnapshot {
2163            block_number: Some(200),
2164            block_timestamp: None,
2165            ..Default::default()
2166        };
2167        assert_eq!(
2168            pool_state.block_env(Some(&live)),
2169            Some(BlockEnvOverrides { number: Some(200), timestamp: Some(1_000) })
2170        );
2171
2172        // With no static overrides, the live block environment stands on its own.
2173        pool_state.block_overrides = None;
2174        let live = OverrideSnapshot {
2175            block_number: Some(300),
2176            block_timestamp: Some(3_000),
2177            ..Default::default()
2178        };
2179        assert_eq!(
2180            pool_state.block_env(Some(&live)),
2181            Some(BlockEnvOverrides { number: Some(300), timestamp: Some(3_000) })
2182        );
2183    }
2184
2185    /// Live storage is merged into the computed overwrites: a fresh contract is added, a value on a
2186    /// slot the baseline already sets is overridden (live wins on conflict), and empty live storage
2187    /// is a no-op.
2188    #[tokio::test]
2189    async fn test_get_overwrites_applies_live_storage() {
2190        let pool_state = setup_pool_state().await;
2191        let tokens = vec![dai_addr(), bal_addr()];
2192        let max = *MAX_BALANCE / U256::from(100);
2193
2194        let baseline = pool_state
2195            .get_overwrites(&tokens, max, None)
2196            .unwrap();
2197
2198        // An empty live snapshot leaves the overwrites unchanged.
2199        let empty = OverrideSnapshot::default();
2200        assert_eq!(
2201            pool_state
2202                .get_overwrites(&tokens, max, Some(&empty))
2203                .unwrap(),
2204            baseline
2205        );
2206
2207        // Pick an address/slot the baseline already sets, so we can assert live wins the conflict.
2208        let (conflict_addr, conflict_slot, baseline_val) = {
2209            let (addr, slots) = baseline
2210                .iter()
2211                .next()
2212                .expect("baseline has overwrites");
2213            let (slot, val) = slots
2214                .iter()
2215                .next()
2216                .expect("address has slots");
2217            (*addr, *slot, *val)
2218        };
2219        let sentinel = baseline_val + U256::from(1);
2220        let fresh = Address::from([0xAB; 20]);
2221        assert!(
2222            !baseline.contains_key(&fresh),
2223            "fresh address must originate from the live snapshot"
2224        );
2225
2226        let live = OverrideSnapshot {
2227            storage: std::sync::Arc::new(HashMap::from([
2228                (fresh, HashMap::from([(U256::from(7), U256::from(123))])),
2229                (conflict_addr, HashMap::from([(conflict_slot, sentinel)])),
2230            ])),
2231            ..Default::default()
2232        };
2233        let with_live = pool_state
2234            .get_overwrites(&tokens, max, Some(&live))
2235            .unwrap();
2236
2237        assert_eq!(
2238            with_live
2239                .get(&fresh)
2240                .and_then(|slots| slots.get(&U256::from(7))),
2241            Some(&U256::from(123)),
2242            "live storage for a fresh contract must be merged in"
2243        );
2244        assert_eq!(
2245            with_live
2246                .get(&conflict_addr)
2247                .and_then(|slots| slots.get(&conflict_slot)),
2248            Some(&sentinel),
2249            "live override must win on slot conflict"
2250        );
2251    }
2252
2253    /// `get_live_snapshot` returns the attached snapshot only while it is fresh: an expired one is
2254    /// dropped (so the pool reverts to indexed state), and no channel means no snapshot. Expiry is
2255    /// pinned to the extremes (`1` = long past, `u64::MAX` = effectively never) so the assertions
2256    /// are independent of the wall clock.
2257    #[tokio::test]
2258    async fn test_get_live_snapshot_drops_expired() {
2259        let mut pool_state = setup_pool_state().await;
2260
2261        // No channel attached: nothing to read.
2262        assert!(pool_state.get_live_snapshot().is_none());
2263
2264        // A snapshot without an expiry never goes stale.
2265        let never =
2266            OverrideSnapshot { block_number: Some(1), expires_at: None, ..Default::default() };
2267        let (_never_tx, never_rx) = watch::channel(never);
2268        pool_state.set_live_overrides(never_rx);
2269        assert_eq!(
2270            pool_state
2271                .get_live_snapshot()
2272                .and_then(|snapshot| snapshot.block_number),
2273            Some(1)
2274        );
2275
2276        // A snapshot whose expiry is far in the future is returned.
2277        let fresh = OverrideSnapshot {
2278            block_number: Some(42),
2279            expires_at: Some(u64::MAX),
2280            ..Default::default()
2281        };
2282        let (_fresh_tx, fresh_rx) = watch::channel(fresh);
2283        pool_state.set_live_overrides(fresh_rx);
2284        assert_eq!(
2285            pool_state
2286                .get_live_snapshot()
2287                .and_then(|snapshot| snapshot.block_number),
2288            Some(42)
2289        );
2290
2291        // A snapshot whose expiry is in the past is dropped.
2292        let expired =
2293            OverrideSnapshot { block_number: Some(42), expires_at: Some(1), ..Default::default() };
2294        let (_expired_tx, expired_rx) = watch::channel(expired);
2295        pool_state.set_live_overrides(expired_rx);
2296        assert!(pool_state.get_live_snapshot().is_none());
2297    }
2298
2299    /// Attaching a live override channel must drop any values cached while the pool had no
2300    /// overrides: they were computed against plain indexed state, and the cache-read fast paths
2301    /// would keep serving them.
2302    #[tokio::test]
2303    async fn test_set_live_overrides_clears_caches() {
2304        let mut pool_state = setup_pool_state().await;
2305        {
2306            let mut caches = pool_state.caches.write();
2307            caches
2308                .spot_prices
2309                .insert((dai_addr(), bal_addr()), 1.0);
2310            caches
2311                .limits
2312                .insert((dai_addr(), bal_addr()), (U256::from(1u64), U256::from(1u64)));
2313        }
2314
2315        let (_tx, rx) = watch::channel(OverrideSnapshot::default());
2316        pool_state.set_live_overrides(rx);
2317
2318        let caches = pool_state.caches.read();
2319        assert!(caches.spot_prices.is_empty());
2320        assert!(caches.limits.is_empty());
2321    }
2322
2323    /// A live snapshot that corrupts the Balancer Vault's low storage slots (pause / reentrancy
2324    /// state), guaranteeing that any simulation run with it applied reverts.
2325    fn poison_snapshot(failure_policy: FailurePolicy) -> OverrideSnapshot {
2326        let vault: Address = "0xBA12222222228d8Ba445958a75a0704d566BF2C8"
2327            .parse()
2328            .unwrap();
2329        let poisoned_slots = (0u64..10)
2330            .map(|slot| (U256::from(slot), U256::MAX))
2331            .collect();
2332        OverrideSnapshot {
2333            storage: std::sync::Arc::new(HashMap::from([(vault, poisoned_slots)])),
2334            failure_policy,
2335            ..Default::default()
2336        }
2337    }
2338
2339    /// With the default [`FailurePolicy::Error`], a snapshot that breaks the simulation surfaces
2340    /// the failure to the caller.
2341    #[tokio::test]
2342    async fn test_failing_overrides_error_by_default() {
2343        let mut pool_state = setup_pool_state().await;
2344        let poison = poison_snapshot(FailurePolicy::Error);
2345        let (_tx, rx) = watch::channel(poison);
2346        pool_state.set_live_overrides(rx);
2347
2348        assert!(pool_state
2349            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2350            .is_err());
2351    }
2352
2353    /// With [`FailurePolicy::FallbackToIndexedState`], a snapshot that breaks the simulation is
2354    /// dropped and the operation is retried on the plain indexed state, matching the result the
2355    /// pool produces without any live overrides.
2356    #[tokio::test]
2357    async fn test_failing_overrides_fall_back_to_indexed_state() {
2358        let pool_state = setup_pool_state().await;
2359        let expected = pool_state
2360            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2361            .unwrap();
2362        let expected_limits = pool_state
2363            .get_limits(dai().address, bal().address)
2364            .unwrap();
2365
2366        let mut pool_state = pool_state;
2367        let poison = poison_snapshot(FailurePolicy::FallbackToIndexedState);
2368        let (_tx, rx) = watch::channel(poison);
2369        pool_state.set_live_overrides(rx);
2370
2371        let result = pool_state
2372            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2373            .expect("must fall back to indexed state");
2374        assert_eq!(result.amount, expected.amount);
2375
2376        let limits = pool_state
2377            .get_limits(dai().address, bal().address)
2378            .expect("limits must fall back to indexed state");
2379        assert_eq!(limits, expected_limits);
2380
2381        let tokens = HashMap::from([(dai().address, dai()), (bal().address, bal())]);
2382        pool_state
2383            .set_spot_prices(&tokens)
2384            .expect("spot prices must fall back to indexed state");
2385    }
2386}