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                            .map(|arg0: Vec<u8>| Bytecode::new_raw(arg0.into())),
1383                    },
1384                    None,
1385                    false,
1386                )
1387                .expect("Failed to initialize account");
1388        }
1389        db.update(accounts, Some(block))
1390            .unwrap();
1391
1392        let tokens = vec![dai().address, bal().address];
1393        for token in &tokens {
1394            engine
1395                .state
1396                .init_account(
1397                    bytes_to_address(token).unwrap(),
1398                    AccountInfo {
1399                        balance: U256::from(0),
1400                        nonce: 0,
1401                        code_hash: KECCAK_EMPTY,
1402                        code: Some(Bytecode::new_raw(ERC20_PROXY_BYTECODE.into())),
1403                    },
1404                    None,
1405                    true,
1406                )
1407                .expect("Failed to initialize account");
1408        }
1409
1410        let block = BlockHeader {
1411            number: 18485417,
1412            hash: Bytes::from_str(
1413                "0x28d41d40f2ac275a4f5f621a636b9016b527d11d37d610a45ac3a821346ebf8c",
1414            )
1415            .expect("Invalid block hash"),
1416            timestamp: 0,
1417            ..Default::default()
1418        };
1419        db.update(vec![], Some(block.clone()))
1420            .unwrap();
1421
1422        let pool_id: String =
1423            "0x4626d81b3a1711beb79f4cecff2413886d461677000200000000000000000011".into();
1424
1425        let stateless_contracts = HashMap::from([(
1426            String::from("0x3de27efa2f1aa663ae5d458857e731c129069f29"),
1427            Some(Vec::new()),
1428        )]);
1429
1430        let balances = HashMap::from([
1431            (dai_addr(), U256::from_str("178754012737301807104").unwrap()),
1432            (bal_addr(), U256::from_str("91082987763369885696").unwrap()),
1433        ]);
1434        let adapter_address =
1435            Address::from_str("0xA2C5C98A892fD6656a7F39A2f63228C0Bc846270").unwrap();
1436
1437        EVMPoolStateBuilder::new(pool_id, tokens, adapter_address)
1438            .balances(balances)
1439            .balance_owner(Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap())
1440            .adapter_contract_bytecode(Bytecode::new_raw(BALANCER_V2.into()))
1441            .stateless_contracts(stateless_contracts)
1442            .build(db)
1443            .await
1444            .expect("Failed to build pool state")
1445    }
1446
1447    #[tokio::test]
1448    async fn test_init() {
1449        let pool_state = setup_pool_state().await;
1450
1451        let expected_capabilities = vec![
1452            Capability::SellSide,
1453            Capability::BuySide,
1454            Capability::PriceFunction,
1455            Capability::HardLimits,
1456        ]
1457        .into_iter()
1458        .collect::<HashSet<_>>();
1459
1460        let capabilities_adapter_contract = pool_state
1461            .adapter_contract
1462            .get_capabilities(
1463                &pool_state.id,
1464                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1465                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1466            )
1467            .unwrap();
1468
1469        assert_eq!(capabilities_adapter_contract, expected_capabilities);
1470
1471        let capabilities_state = pool_state.clone().capabilities;
1472
1473        assert_eq!(capabilities_state, expected_capabilities);
1474
1475        // Verify all tokens are initialized in the engine
1476        let engine_accounts = pool_state
1477            .adapter_contract
1478            .engine
1479            .state
1480            .get_account_storage()
1481            .expect("Failed to get account storage");
1482        for token in pool_state.tokens {
1483            let account = engine_accounts
1484                .get_account_info(&bytes_to_address(&token).unwrap())
1485                .unwrap();
1486            assert_eq!(account.balance, U256::from(0));
1487            assert_eq!(account.nonce, 0u64);
1488            assert_eq!(account.code_hash, KECCAK_EMPTY);
1489            assert!(account.code.is_some());
1490        }
1491
1492        // Verify external account is initialized in the engine
1493        let external_account = engine_accounts
1494            .get_account_info(&EXTERNAL_ACCOUNT)
1495            .unwrap();
1496        assert_eq!(external_account.balance, U256::from(*MAX_BALANCE));
1497        assert_eq!(external_account.nonce, 0u64);
1498        assert_eq!(external_account.code_hash, KECCAK_EMPTY);
1499        assert!(external_account.code.is_none());
1500    }
1501
1502    #[tokio::test]
1503    async fn test_get_amount_out() {
1504        let pool_state = setup_pool_state().await;
1505
1506        let result = pool_state
1507            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1508            .unwrap();
1509        let new_state = result
1510            .new_state
1511            .as_any()
1512            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1513            .unwrap();
1514        assert_eq!(result.amount, BigUint::from_str("137780051463393923").unwrap());
1515        // The returned state starts with fresh caches; reading recomputes the post-swap price
1516        // lazily, which differs from the pre-swap price because the swap moved the pool.
1517        let pre = pool_state
1518            .spot_price(&dai(), &bal())
1519            .unwrap();
1520        let post = new_state
1521            .spot_price(&dai(), &bal())
1522            .unwrap();
1523        assert_ne!(pre, post);
1524        assert!(pool_state
1525            .block_lasting_overwrites
1526            .is_empty());
1527    }
1528
1529    #[tokio::test]
1530    async fn test_sequential_get_amount_outs() {
1531        let pool_state = setup_pool_state().await;
1532
1533        let result = pool_state
1534            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1535            .unwrap();
1536        let new_state = result
1537            .new_state
1538            .as_any()
1539            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1540            .unwrap();
1541        assert_eq!(result.amount, BigUint::from_str("137780051463393923").unwrap());
1542        // The returned state starts with fresh caches; a lazily-computed price against the
1543        // post-swap overwrites differs from the pre-swap price.
1544        let price_before_first_swap = pool_state
1545            .spot_price(&dai(), &bal())
1546            .unwrap();
1547        let price_after_first_swap = new_state
1548            .spot_price(&dai(), &bal())
1549            .unwrap();
1550        assert_ne!(price_before_first_swap, price_after_first_swap);
1551
1552        let new_result = new_state
1553            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
1554            .unwrap();
1555        let new_state_second_swap = new_result
1556            .new_state
1557            .as_any()
1558            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1559            .unwrap();
1560
1561        assert_eq!(new_result.amount, BigUint::from_str("136964651490065626").unwrap());
1562        // Same after the second swap: the lazily recomputed price has moved again relative to
1563        // the state right after the first swap.
1564        let price_after_second_swap = new_state_second_swap
1565            .spot_price(&dai(), &bal())
1566            .unwrap();
1567        assert_ne!(price_after_first_swap, price_after_second_swap);
1568    }
1569
1570    #[tokio::test]
1571    async fn test_get_amount_out_dust() {
1572        let pool_state = setup_pool_state().await;
1573
1574        let result = pool_state
1575            .get_amount_out(BigUint::one(), &dai(), &bal())
1576            .unwrap();
1577
1578        let _ = result
1579            .new_state
1580            .as_any()
1581            .downcast_ref::<EVMPoolState<PreCachedDB>>()
1582            .unwrap();
1583        assert_eq!(result.amount, BigUint::ZERO);
1584    }
1585
1586    #[tokio::test]
1587    async fn test_get_amount_out_sell_limit() {
1588        let pool_state = setup_pool_state().await;
1589
1590        let result = pool_state.get_amount_out(
1591            // sell limit is 100279494253364362835
1592            BigUint::from_str("100379494253364362835").unwrap(),
1593            &dai(),
1594            &bal(),
1595        );
1596
1597        assert!(result.is_err());
1598
1599        match result {
1600            Err(SimulationError::InvalidInput(msg1, amount_out_result)) => {
1601                assert_eq!(msg1, "Sell amount exceeds limit 100279494253364362835");
1602                assert!(amount_out_result.is_some());
1603            }
1604            _ => panic!("Test failed: was expecting an Err(SimulationError::RetryDifferentInput(_, _)) value"),
1605        }
1606    }
1607
1608    #[tokio::test]
1609    async fn test_get_amount_limits() {
1610        let pool_state = setup_pool_state().await;
1611
1612        let overwrites = pool_state
1613            .get_overwrites(
1614                &[
1615                    bytes_to_address(&pool_state.tokens[0]).unwrap(),
1616                    bytes_to_address(&pool_state.tokens[1]).unwrap(),
1617                ],
1618                *MAX_BALANCE / U256::from(100),
1619                None,
1620            )
1621            .unwrap();
1622        let (dai_limit, _) = pool_state
1623            .get_amount_limits(
1624                &[dai_addr(), bal_addr()],
1625                Some(overwrites.clone()),
1626                pool_state.block_env(None),
1627            )
1628            .unwrap();
1629        assert_eq!(dai_limit, U256::from_str("100279494253364362835").unwrap());
1630
1631        let (bal_limit, _) = pool_state
1632            .get_amount_limits(
1633                &[
1634                    bytes_to_address(&pool_state.tokens[1]).unwrap(),
1635                    bytes_to_address(&pool_state.tokens[0]).unwrap(),
1636                ],
1637                Some(overwrites),
1638                pool_state.block_env(None),
1639            )
1640            .unwrap();
1641        assert_eq!(bal_limit, U256::from_str("13997408640689987484").unwrap());
1642    }
1643
1644    #[tokio::test]
1645    async fn test_get_limits_cached_matches_fresh() {
1646        let pool_state = setup_pool_state().await;
1647        let overwrites = pool_state
1648            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
1649            .unwrap();
1650
1651        // First call populates the cache.
1652        let fresh = pool_state
1653            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1654            .unwrap();
1655        assert_eq!(
1656            pool_state
1657                .caches
1658                .read()
1659                .limits
1660                .get(&(dai_addr(), bal_addr()))
1661                .copied(),
1662            Some(fresh)
1663        );
1664
1665        // Second call returns the cached value, identical to the first.
1666        let cached = pool_state
1667            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites), None)
1668            .unwrap();
1669        assert_eq!(fresh, cached);
1670
1671        // The cache key deliberately excludes the overwrites: the limit must be independent of
1672        // the caller's overwrite amounts. Guard that by computing fresh, on a cold state, with
1673        // overwrites derived from a different amount, and comparing byte-for-byte.
1674        let cold = setup_pool_state().await;
1675        let different_overwrites = cold
1676            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(50), None)
1677            .unwrap();
1678        let independent = cold
1679            .get_amount_limits(&[dai_addr(), bal_addr()], Some(different_overwrites), None)
1680            .unwrap();
1681        assert_eq!(independent, fresh);
1682    }
1683
1684    /// A cached limit must not survive an engine-block advance, even when the pool receives no
1685    /// delta: the adapter computes limits against the engine's current block, so time-dependent
1686    /// limits (e.g. an amplification ramp) change with zero pool-level events.
1687    #[tokio::test]
1688    async fn test_engine_block_advance_invalidates_cached_limits() {
1689        let pool_state = setup_pool_state().await;
1690        let overwrites = pool_state
1691            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
1692            .unwrap();
1693        let real = pool_state
1694            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1695            .unwrap();
1696        let sentinel = (U256::from(1u64), U256::from(1u64));
1697        assert_ne!(real, sentinel);
1698        pool_state
1699            .caches
1700            .write()
1701            .limits
1702            .insert((dai_addr(), bal_addr()), sentinel);
1703
1704        // Sanity: the sentinel is served while the engine block is unchanged.
1705        let served = pool_state
1706            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites.clone()), None)
1707            .unwrap();
1708        assert_eq!(served, sentinel);
1709
1710        // Advance the engine's current block without any pool-level event.
1711        let mut block = SHARED_TYCHO_DB
1712            .get_current_block()
1713            .expect("fixture sets an engine block");
1714        block.number += 1;
1715        block.timestamp += 12;
1716        SHARED_TYCHO_DB
1717            .update(vec![], Some(block))
1718            .expect("engine block update");
1719
1720        // The stamp mismatch turns the read into a miss: the sentinel is dead.
1721        let after = pool_state
1722            .get_amount_limits(&[dai_addr(), bal_addr()], Some(overwrites), None)
1723            .unwrap();
1724        assert_ne!(after, sentinel);
1725        assert_eq!(after, real);
1726    }
1727
1728    #[tokio::test]
1729    async fn test_set_spot_prices() {
1730        let pool_state = setup_pool_state().await;
1731
1732        pool_state
1733            .set_spot_prices(
1734                &vec![bal(), dai()]
1735                    .into_iter()
1736                    .map(|t| (t.address.clone(), t))
1737                    .collect(),
1738            )
1739            .unwrap();
1740
1741        let dai_bal_spot_price = pool_state
1742            .caches
1743            .get_spot_price((
1744                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1745                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1746            ))
1747            .unwrap();
1748        let bal_dai_spot_price = pool_state
1749            .caches
1750            .get_spot_price((
1751                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1752                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1753            ))
1754            .unwrap();
1755        assert_eq!(dai_bal_spot_price, 0.137_778_914_319_047_9);
1756        assert_eq!(bal_dai_spot_price, 7.071_503_245_428_246);
1757    }
1758
1759    #[tokio::test]
1760    async fn test_set_spot_prices_without_capability() {
1761        // Tests set Spot Prices functions when the pool doesn't have PriceFunction capability
1762        let mut pool_state = setup_pool_state().await;
1763
1764        pool_state
1765            .capabilities
1766            .remove(&Capability::PriceFunction);
1767
1768        pool_state
1769            .set_spot_prices(
1770                &vec![bal(), dai()]
1771                    .into_iter()
1772                    .map(|t| (t.address.clone(), t))
1773                    .collect(),
1774            )
1775            .unwrap();
1776
1777        let dai_bal_spot_price = pool_state
1778            .caches
1779            .get_spot_price((
1780                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1781                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1782            ))
1783            .unwrap();
1784        let bal_dai_spot_price = pool_state
1785            .caches
1786            .get_spot_price((
1787                bytes_to_address(&pool_state.tokens[1]).unwrap(),
1788                bytes_to_address(&pool_state.tokens[0]).unwrap(),
1789            ))
1790            .unwrap();
1791        assert_eq!(dai_bal_spot_price, 0.13736685496467538);
1792        assert_eq!(bal_dai_spot_price, 7.050354297665408);
1793    }
1794
1795    #[tokio::test]
1796    async fn test_spot_price_lazy_computes_on_miss() {
1797        let pool_state = setup_pool_state().await;
1798        // Non-override pool with a cold cache: the builder does not warm spot prices.
1799        assert!(pool_state
1800            .caches
1801            .read()
1802            .spot_prices
1803            .is_empty());
1804
1805        // Reading a pair computes it on demand, byte-identical to the eagerly-warmed values
1806        // pinned in `test_set_spot_prices`, and caches it.
1807        let dai_bal = pool_state
1808            .spot_price(&dai(), &bal())
1809            .unwrap();
1810        assert_eq!(dai_bal, 0.137_778_914_319_047_9);
1811        let bal_dai = pool_state
1812            .spot_price(&bal(), &dai())
1813            .unwrap();
1814        assert_eq!(bal_dai, 7.071_503_245_428_246);
1815        assert_eq!(
1816            pool_state
1817                .caches
1818                .get_spot_price((dai_addr(), bal_addr())),
1819            Some(dai_bal)
1820        );
1821    }
1822
1823    #[tokio::test]
1824    async fn test_get_balance_overwrites_with_component_balances() {
1825        let pool_state: EVMPoolState<PreCachedDB> = setup_pool_state().await;
1826
1827        let overwrites = pool_state
1828            .get_balance_overwrites()
1829            .unwrap();
1830
1831        let dai_address = dai_addr();
1832        let bal_address = bal_addr();
1833        assert!(overwrites.contains_key(&dai_address));
1834        assert!(overwrites.contains_key(&bal_address));
1835    }
1836
1837    #[tokio::test]
1838    async fn test_get_balance_overwrites_with_contract_balances() {
1839        let mut pool_state: EVMPoolState<PreCachedDB> = setup_pool_state().await;
1840
1841        let contract_address =
1842            Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap();
1843
1844        // Ensure no component balances are used
1845        pool_state.balances.clear();
1846        pool_state.balance_owner = None;
1847
1848        // Set contract balances
1849        let dai_address = dai_addr();
1850        let bal_address = bal_addr();
1851        pool_state.contract_balances = HashMap::from([(
1852            contract_address,
1853            HashMap::from([
1854                (dai_address, U256::from_str("7500000000000000000000").unwrap()), // 7500 DAI
1855                (bal_address, U256::from_str("1500000000000000000000").unwrap()), // 1500 BAL
1856            ]),
1857        )]);
1858
1859        let overwrites = pool_state
1860            .get_balance_overwrites()
1861            .unwrap();
1862
1863        assert!(overwrites.contains_key(&dai_address));
1864        assert!(overwrites.contains_key(&bal_address));
1865    }
1866
1867    #[tokio::test]
1868    async fn test_balance_merging_during_delta_transition() {
1869        use std::str::FromStr;
1870
1871        let mut pool_state = setup_pool_state().await;
1872        let pool_id = pool_state.id.clone();
1873
1874        // Test the balance merging logic more directly
1875        // Setup initial balances including DAI and BAL (which the pool already knows about)
1876        let dai_addr = dai_addr();
1877        let bal_addr = bal_addr();
1878        let new_token = Address::from_str("0xc02aaa39b223fe8d0a0e5c4f27ead9083c756cc2").unwrap(); // WETH
1879
1880        // Clear and setup clean initial state
1881        pool_state.balances.clear();
1882        pool_state
1883            .balances
1884            .insert(dai_addr, U256::from(1000000000u64));
1885        pool_state
1886            .balances
1887            .insert(bal_addr, U256::from(2000000000u64));
1888        pool_state
1889            .balances
1890            .insert(new_token, U256::from(3000000000u64));
1891
1892        // Create tokens mapping including the existing DAI and BAL
1893        let mut tokens = HashMap::new();
1894        tokens.insert(dai().address, dai());
1895        tokens.insert(bal().address, bal());
1896
1897        // Simulate a delta transition with only DAI balance update (missing BAL and new_token)
1898        let mut component_balances = HashMap::new();
1899        let mut delta_balances = HashMap::new();
1900        // Only update DAI balance, leave others unchanged in delta
1901        delta_balances.insert(dai().address, Bytes::from(vec![0x77, 0x35, 0x94, 0x00])); // 2000000000 (updated value)
1902        component_balances.insert(pool_id, delta_balances);
1903
1904        let balances = Balances { component_balances, account_balances: HashMap::new() };
1905
1906        // Record initial balance count
1907        let initial_balance_count = pool_state.balances.len();
1908        assert_eq!(initial_balance_count, 3);
1909
1910        // Apply delta transition
1911        pool_state
1912            .update_pool_state(&tokens, &balances)
1913            .unwrap();
1914
1915        // Verify that all 3 balances are preserved (BAL and new_token should still be there)
1916        assert_eq!(
1917            pool_state.balances.len(),
1918            3,
1919            "All balances should be preserved after delta transition"
1920        );
1921        assert!(
1922            pool_state
1923                .balances
1924                .contains_key(&dai_addr),
1925            "DAI balance should be present"
1926        );
1927        assert!(
1928            pool_state
1929                .balances
1930                .contains_key(&bal_addr),
1931            "BAL balance should be present"
1932        );
1933        assert!(
1934            pool_state
1935                .balances
1936                .contains_key(&new_token),
1937            "New token balance should be preserved from before delta"
1938        );
1939
1940        // Verify that updated token (DAI) has new value
1941        assert_eq!(
1942            pool_state.balances[&dai_addr],
1943            U256::from(2000000000u64),
1944            "DAI balance should be updated"
1945        );
1946
1947        // Verify that non-updated tokens retain their original values
1948        assert_eq!(
1949            pool_state.balances[&bal_addr],
1950            U256::from(2000000000u64),
1951            "BAL balance should be unchanged"
1952        );
1953        assert_eq!(
1954            pool_state.balances[&new_token],
1955            U256::from(3000000000u64),
1956            "New token balance should be unchanged"
1957        );
1958    }
1959
1960    #[tokio::test]
1961    async fn test_update_pool_state_warms_caches() {
1962        let mut pool_state = setup_pool_state().await;
1963        let tokens = HashMap::from([(dai().address, dai()), (bal().address, bal())]);
1964        let balances =
1965            Balances { component_balances: HashMap::new(), account_balances: HashMap::new() };
1966
1967        pool_state
1968            .update_pool_state(&tokens, &balances)
1969            .unwrap();
1970
1971        let caches = pool_state.caches.read();
1972        assert!(!caches.spot_prices.is_empty());
1973        assert!(!caches.limits.is_empty());
1974    }
1975
1976    #[tokio::test]
1977    async fn test_delta_transition_updates_block_overrides() {
1978        let mut pool_state = setup_pool_state().await;
1979        pool_state.manual_updates = true;
1980        pool_state.block_overrides = None;
1981
1982        let delta = ProtocolStateDelta {
1983            component_id: pool_state.id.clone(),
1984            updated_attributes: HashMap::from([
1985                ("override_block_number".to_string(), Bytes::from(123_u64.to_be_bytes().to_vec())),
1986                (
1987                    "override_block_timestamp".to_string(),
1988                    Bytes::from(456_u64.to_be_bytes().to_vec()),
1989                ),
1990            ]),
1991            deleted_attributes: HashSet::new(),
1992        };
1993
1994        pool_state
1995            .delta_transition(delta, &HashMap::new(), &Balances::default())
1996            .unwrap();
1997
1998        assert_eq!(
1999            pool_state.block_overrides,
2000            Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) })
2001        );
2002    }
2003
2004    #[tokio::test]
2005    async fn test_delta_transition_updates_partial_block_overrides() {
2006        let mut pool_state = setup_pool_state().await;
2007        pool_state.manual_updates = true;
2008        pool_state.block_overrides =
2009            Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) });
2010
2011        let delta = ProtocolStateDelta {
2012            component_id: pool_state.id.clone(),
2013            updated_attributes: HashMap::from([(
2014                "override_block_number".to_string(),
2015                Bytes::from(789_u64.to_be_bytes().to_vec()),
2016            )]),
2017            deleted_attributes: HashSet::new(),
2018        };
2019
2020        pool_state
2021            .delta_transition(delta, &HashMap::new(), &Balances::default())
2022            .unwrap();
2023
2024        assert_eq!(
2025            pool_state.block_overrides,
2026            Some(BlockEnvOverrides { number: Some(789), timestamp: Some(456) })
2027        );
2028    }
2029
2030    /// `update_pool_state` must refresh BOTH component balances and tracked contract balances,
2031    /// not treat them as mutually exclusive. Balancer V3 is hybrid (component balances at the
2032    /// vault owner + tracked vault contract balances); freezing contract balances while the
2033    /// vault's indexed reserves advance is what caused the WETH-in `BalanceNotSettled` failures.
2034    #[tokio::test]
2035    async fn test_delta_transition_refreshes_both_balance_maps() {
2036        let mut pool_state = setup_pool_state().await;
2037        let vault = Address::from_str("0xBA12222222228d8Ba445958a75a0704d566BF2C8").unwrap();
2038        // Non-manual pool (how Balancer V3 behaves once `manual_updates` is dropped): a contract
2039        // change routes the pool through delta_transition, which refreshes its balances.
2040        pool_state.manual_updates = false;
2041        pool_state.involved_contracts = HashSet::from([vault]);
2042        pool_state.contract_balances =
2043            HashMap::from([(vault, HashMap::from([(dai_addr(), U256::from(1u64))]))]);
2044
2045        let delta = ProtocolStateDelta {
2046            component_id: pool_state.id.clone(),
2047            updated_attributes: HashMap::new(),
2048            deleted_attributes: HashSet::new(),
2049        };
2050        let balances = Balances {
2051            component_balances: HashMap::new(),
2052            account_balances: HashMap::from([(
2053                Bytes::from(vault.as_slice()),
2054                HashMap::from([(dai().address, Bytes::from(42u64).lpad(32, 0))]),
2055            )]),
2056        };
2057
2058        // The spot-price refresh inside update_pool_state may fail in offline test
2059        // environments; the balance bookkeeping this test guards happens before it.
2060        #[expect(
2061            clippy::let_underscore_must_use,
2062            reason = "the offline spot-price refresh may fail; the assertions below cover the earlier bookkeeping"
2063        )]
2064        let _ = pool_state.delta_transition(delta, &HashMap::new(), &balances);
2065
2066        // Contract balance refreshed even though component balances are non-empty (the old
2067        // mutual-exclusion would have skipped this branch entirely).
2068        assert_eq!(pool_state.contract_balances[&vault][&dai_addr()], U256::from(42u64));
2069        // Component balances stay untouched by a contract-balance-only delta.
2070        assert_eq!(
2071            pool_state.balances[&dai_addr()],
2072            U256::from_str("178754012737301807104").unwrap()
2073        );
2074    }
2075
2076    /// A block-environment-only delta (no `update_marker`) on a `manual_updates` pool skips
2077    /// `update_pool_state`, but cached limits must not survive it: they are stamped with the
2078    /// block env they were computed under, so the changed env turns the next read into a miss.
2079    /// Spot prices are deliberately allowed to go stale in this skip path (the `manual_updates`
2080    /// contract).
2081    #[tokio::test]
2082    async fn test_block_override_delta_invalidates_cached_limits() {
2083        let mut pool_state = setup_pool_state().await;
2084        pool_state.manual_updates = true;
2085
2086        // Populate the limit cache, then poison the entry with a sentinel so a served cache hit
2087        // is distinguishable from a fresh computation.
2088        let overwrites = pool_state
2089            .get_overwrites(&[dai_addr(), bal_addr()], *MAX_BALANCE / U256::from(100), None)
2090            .unwrap();
2091        let real = pool_state
2092            .get_amount_limits(
2093                &[dai_addr(), bal_addr()],
2094                Some(overwrites.clone()),
2095                pool_state.block_env(None),
2096            )
2097            .unwrap();
2098        let sentinel = (U256::from(1u64), U256::from(1u64));
2099        assert_ne!(real, sentinel);
2100        pool_state
2101            .caches
2102            .write()
2103            .limits
2104            .insert((dai_addr(), bal_addr()), sentinel);
2105
2106        // A delta that only changes the block env, with no `update_marker`.
2107        let delta = ProtocolStateDelta {
2108            component_id: pool_state.id.clone(),
2109            updated_attributes: HashMap::from([(
2110                "override_block_number".to_string(),
2111                Bytes::from(1234_u64.to_be_bytes().to_vec()),
2112            )]),
2113            deleted_attributes: HashSet::new(),
2114        };
2115        pool_state
2116            .delta_transition(delta, &HashMap::new(), &Balances::default())
2117            .unwrap();
2118
2119        // The changed block env must invalidate the sentinel: the read recomputes fresh.
2120        let after = pool_state
2121            .get_amount_limits(
2122                &[dai_addr(), bal_addr()],
2123                Some(overwrites),
2124                pool_state.block_env(None),
2125            )
2126            .unwrap();
2127        assert_ne!(after, sentinel);
2128    }
2129
2130    #[test]
2131    fn should_not_panic_at_typetag_deserialize() {
2132        let deserialized: Result<Box<dyn ProtocolSim>, _> = serde_json::from_str(
2133            r#"{"protocol":"EVMPoolState","state":{"reserve_0":1,"reserve_1":2}}"#,
2134        );
2135
2136        assert!(deserialized.is_err());
2137    }
2138
2139    /// A live snapshot's block number/timestamp take precedence over the static block overrides,
2140    /// field by field, while an absent or empty snapshot leaves them untouched.
2141    #[tokio::test]
2142    async fn test_block_env_prefers_live_overrides() {
2143        let mut pool_state = setup_pool_state().await;
2144        pool_state.block_overrides =
2145            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) });
2146
2147        // No live snapshot: the statically configured overrides are used unchanged.
2148        assert_eq!(
2149            pool_state.block_env(None),
2150            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) })
2151        );
2152
2153        // A live snapshot with neither field set does not touch the static overrides.
2154        let empty = OverrideSnapshot::default();
2155        assert_eq!(
2156            pool_state.block_env(Some(&empty)),
2157            Some(BlockEnvOverrides { number: Some(100), timestamp: Some(1_000) })
2158        );
2159
2160        // Present live fields win; unset live fields keep the static value.
2161        let live = OverrideSnapshot {
2162            block_number: Some(200),
2163            block_timestamp: None,
2164            ..Default::default()
2165        };
2166        assert_eq!(
2167            pool_state.block_env(Some(&live)),
2168            Some(BlockEnvOverrides { number: Some(200), timestamp: Some(1_000) })
2169        );
2170
2171        // With no static overrides, the live block environment stands on its own.
2172        pool_state.block_overrides = None;
2173        let live = OverrideSnapshot {
2174            block_number: Some(300),
2175            block_timestamp: Some(3_000),
2176            ..Default::default()
2177        };
2178        assert_eq!(
2179            pool_state.block_env(Some(&live)),
2180            Some(BlockEnvOverrides { number: Some(300), timestamp: Some(3_000) })
2181        );
2182    }
2183
2184    /// Live storage is merged into the computed overwrites: a fresh contract is added, a value on a
2185    /// slot the baseline already sets is overridden (live wins on conflict), and empty live storage
2186    /// is a no-op.
2187    #[tokio::test]
2188    async fn test_get_overwrites_applies_live_storage() {
2189        let pool_state = setup_pool_state().await;
2190        let tokens = vec![dai_addr(), bal_addr()];
2191        let max = *MAX_BALANCE / U256::from(100);
2192
2193        let baseline = pool_state
2194            .get_overwrites(&tokens, max, None)
2195            .unwrap();
2196
2197        // An empty live snapshot leaves the overwrites unchanged.
2198        let empty = OverrideSnapshot::default();
2199        assert_eq!(
2200            pool_state
2201                .get_overwrites(&tokens, max, Some(&empty))
2202                .unwrap(),
2203            baseline
2204        );
2205
2206        // Pick an address/slot the baseline already sets, so we can assert live wins the conflict.
2207        let (conflict_addr, conflict_slot, baseline_val) = {
2208            let (addr, slots) = baseline
2209                .iter()
2210                .next()
2211                .expect("baseline has overwrites");
2212            let (slot, val) = slots
2213                .iter()
2214                .next()
2215                .expect("address has slots");
2216            (*addr, *slot, *val)
2217        };
2218        let sentinel = baseline_val + U256::from(1);
2219        let fresh = Address::from([0xAB; 20]);
2220        assert!(
2221            !baseline.contains_key(&fresh),
2222            "fresh address must originate from the live snapshot"
2223        );
2224
2225        let live = OverrideSnapshot {
2226            storage: std::sync::Arc::new(HashMap::from([
2227                (fresh, HashMap::from([(U256::from(7), U256::from(123))])),
2228                (conflict_addr, HashMap::from([(conflict_slot, sentinel)])),
2229            ])),
2230            ..Default::default()
2231        };
2232        let with_live = pool_state
2233            .get_overwrites(&tokens, max, Some(&live))
2234            .unwrap();
2235
2236        assert_eq!(
2237            with_live
2238                .get(&fresh)
2239                .and_then(|slots| slots.get(&U256::from(7))),
2240            Some(&U256::from(123)),
2241            "live storage for a fresh contract must be merged in"
2242        );
2243        assert_eq!(
2244            with_live
2245                .get(&conflict_addr)
2246                .and_then(|slots| slots.get(&conflict_slot)),
2247            Some(&sentinel),
2248            "live override must win on slot conflict"
2249        );
2250    }
2251
2252    /// `get_live_snapshot` returns the attached snapshot only while it is fresh: an expired one is
2253    /// dropped (so the pool reverts to indexed state), and no channel means no snapshot. Expiry is
2254    /// pinned to the extremes (`1` = long past, `u64::MAX` = effectively never) so the assertions
2255    /// are independent of the wall clock.
2256    #[tokio::test]
2257    async fn test_get_live_snapshot_drops_expired() {
2258        let mut pool_state = setup_pool_state().await;
2259
2260        // No channel attached: nothing to read.
2261        assert!(pool_state.get_live_snapshot().is_none());
2262
2263        // A snapshot without an expiry never goes stale.
2264        let never =
2265            OverrideSnapshot { block_number: Some(1), expires_at: None, ..Default::default() };
2266        let (_never_tx, never_rx) = watch::channel(never);
2267        pool_state.set_live_overrides(never_rx);
2268        assert_eq!(
2269            pool_state
2270                .get_live_snapshot()
2271                .and_then(|snapshot| snapshot.block_number),
2272            Some(1)
2273        );
2274
2275        // A snapshot whose expiry is far in the future is returned.
2276        let fresh = OverrideSnapshot {
2277            block_number: Some(42),
2278            expires_at: Some(u64::MAX),
2279            ..Default::default()
2280        };
2281        let (_fresh_tx, fresh_rx) = watch::channel(fresh);
2282        pool_state.set_live_overrides(fresh_rx);
2283        assert_eq!(
2284            pool_state
2285                .get_live_snapshot()
2286                .and_then(|snapshot| snapshot.block_number),
2287            Some(42)
2288        );
2289
2290        // A snapshot whose expiry is in the past is dropped.
2291        let expired =
2292            OverrideSnapshot { block_number: Some(42), expires_at: Some(1), ..Default::default() };
2293        let (_expired_tx, expired_rx) = watch::channel(expired);
2294        pool_state.set_live_overrides(expired_rx);
2295        assert!(pool_state.get_live_snapshot().is_none());
2296    }
2297
2298    /// Attaching a live override channel must drop any values cached while the pool had no
2299    /// overrides: they were computed against plain indexed state, and the cache-read fast paths
2300    /// would keep serving them.
2301    #[tokio::test]
2302    async fn test_set_live_overrides_clears_caches() {
2303        let mut pool_state = setup_pool_state().await;
2304        {
2305            let mut caches = pool_state.caches.write();
2306            caches
2307                .spot_prices
2308                .insert((dai_addr(), bal_addr()), 1.0);
2309            caches
2310                .limits
2311                .insert((dai_addr(), bal_addr()), (U256::from(1u64), U256::from(1u64)));
2312        }
2313
2314        let (_tx, rx) = watch::channel(OverrideSnapshot::default());
2315        pool_state.set_live_overrides(rx);
2316
2317        let caches = pool_state.caches.read();
2318        assert!(caches.spot_prices.is_empty());
2319        assert!(caches.limits.is_empty());
2320    }
2321
2322    /// A live snapshot that corrupts the Balancer Vault's low storage slots (pause / reentrancy
2323    /// state), guaranteeing that any simulation run with it applied reverts.
2324    fn poison_snapshot(failure_policy: FailurePolicy) -> OverrideSnapshot {
2325        let vault: Address = "0xBA12222222228d8Ba445958a75a0704d566BF2C8"
2326            .parse()
2327            .unwrap();
2328        let poisoned_slots = (0u64..10)
2329            .map(|slot| (U256::from(slot), U256::MAX))
2330            .collect();
2331        OverrideSnapshot {
2332            storage: std::sync::Arc::new(HashMap::from([(vault, poisoned_slots)])),
2333            failure_policy,
2334            ..Default::default()
2335        }
2336    }
2337
2338    /// With the default [`FailurePolicy::Error`], a snapshot that breaks the simulation surfaces
2339    /// the failure to the caller.
2340    #[tokio::test]
2341    async fn test_failing_overrides_error_by_default() {
2342        let mut pool_state = setup_pool_state().await;
2343        let poison = poison_snapshot(FailurePolicy::Error);
2344        let (_tx, rx) = watch::channel(poison);
2345        pool_state.set_live_overrides(rx);
2346
2347        assert!(pool_state
2348            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2349            .is_err());
2350    }
2351
2352    /// With [`FailurePolicy::FallbackToIndexedState`], a snapshot that breaks the simulation is
2353    /// dropped and the operation is retried on the plain indexed state, matching the result the
2354    /// pool produces without any live overrides.
2355    #[tokio::test]
2356    async fn test_failing_overrides_fall_back_to_indexed_state() {
2357        let pool_state = setup_pool_state().await;
2358        let expected = pool_state
2359            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2360            .unwrap();
2361        let expected_limits = pool_state
2362            .get_limits(dai().address, bal().address)
2363            .unwrap();
2364
2365        let mut pool_state = pool_state;
2366        let poison = poison_snapshot(FailurePolicy::FallbackToIndexedState);
2367        let (_tx, rx) = watch::channel(poison);
2368        pool_state.set_live_overrides(rx);
2369
2370        let result = pool_state
2371            .get_amount_out(BigUint::from_str("1000000000000000000").unwrap(), &dai(), &bal())
2372            .expect("must fall back to indexed state");
2373        assert_eq!(result.amount, expected.amount);
2374
2375        let limits = pool_state
2376            .get_limits(dai().address, bal().address)
2377            .expect("limits must fall back to indexed state");
2378        assert_eq!(limits, expected_limits);
2379
2380        let tokens = HashMap::from([(dai().address, dai()), (bal().address, bal())]);
2381        pool_state
2382            .set_spot_prices(&tokens)
2383            .expect("spot prices must fall back to indexed state");
2384    }
2385}