Skip to main content

tycho_simulation/evm/
simulation.rs

1use std::{clone::Clone, collections::HashMap, default::Default, env, fmt::Debug};
2
3use alloy::primitives::{Address, Bytes, U256};
4use revm::{
5    context::{
6        result::{EVMError, ExecutionResult, Output, ResultAndState},
7        BlockEnv, CfgEnv, Context, TxEnv,
8    },
9    context_interface::JournalTr,
10    interpreter::{return_ok, InstructionResult},
11    primitives::{hardfork::SpecId, TxKind},
12    state::EvmState,
13    DatabaseRef, ExecuteEvm, InspectEvm, MainBuilder, MainContext,
14};
15use revm_inspectors::tracing::{TracingInspector, TracingInspectorConfig};
16use strum_macros::Display;
17use tokio::runtime::{Handle, Runtime};
18use tracing::{debug, warn};
19use tycho_common::models::contract::AccountDelta;
20
21use super::{
22    account_storage::StateUpdate,
23    traces::{handle_traces, TraceResult},
24};
25use crate::evm::engine_db::{
26    engine_db_interface::EngineDatabaseInterface, simulation_db::OverriddenSimulationDB,
27};
28
29/// An error representing any transaction simulation result other than successful execution
30#[derive(Debug, Display, Clone, PartialEq)]
31pub enum SimulationEngineError {
32    /// Something went wrong while getting storage; might be caused by network issues.
33    /// Retrying may help.
34    StorageError(String),
35    /// Gas limit has been reached. Retrying while increasing gas limit or waiting for a gas price
36    /// reduction may help.
37    OutOfGas(String, String),
38    /// Simulation didn't succeed; likely not related to network or gas, so retrying won't help
39    TransactionError { data: String, gas_used: Option<u64> },
40    /// Processing traces failed.
41    TraceError(String),
42}
43
44/// A result of a successful transaction simulation
45#[derive(Debug, Clone, Default)]
46pub struct SimulationResult {
47    /// Output of transaction execution as bytes
48    pub result: Bytes,
49    /// State changes caused by the transaction
50    pub state_updates: HashMap<Address, StateUpdate>,
51    /// Gas used by the transaction (already reduced by the refunded gas)
52    pub gas_used: u64,
53    /// Transient storage changes captured during the simulation
54    pub transient_storage: HashMap<Address, HashMap<U256, U256>>,
55}
56
57/// Simulation engine
58#[derive(Debug, Clone)]
59pub struct SimulationEngine<D: EngineDatabaseInterface + Clone + Debug>
60where
61    <D as DatabaseRef>::Error: Debug,
62    <D as EngineDatabaseInterface>::Error: Debug,
63{
64    pub state: D,
65    pub trace: bool,
66}
67
68impl<D: EngineDatabaseInterface + Clone + Debug> SimulationEngine<D>
69where
70    <D as DatabaseRef>::Error: Debug,
71    <D as EngineDatabaseInterface>::Error: Debug,
72{
73    /// Create a new simulation engine
74    ///
75    /// # Arguments
76    ///
77    /// * `state` - Database reference to be used for simulation
78    /// * `trace` - Whether to print the entire execution trace
79    ///
80    /// # Notes
81    /// If you set traces to true, consider setting the ETHERSCAN_API_KEY env variable
82    /// so the tracer can pull contract metadata from etherscan.
83    pub fn new(state: D, trace: bool) -> Self {
84        Self { state, trace }
85    }
86
87    /// Simulate a transaction
88    ///
89    /// State's block will be modified to be the last block before the simulation's block.
90    pub fn simulate(
91        &self,
92        params: &SimulationParameters,
93    ) -> Result<SimulationResult, SimulationEngineError> {
94        // We allocate a new EVM so we can work with a simple referenced DB instead of a fully
95        // concurrently save shared reference and write locked object. Note that concurrently
96        // calling this method is therefore not possible.
97        // There is no need to keep an EVM on the struct as it only holds the environment and the
98        // db, the db is simply a reference wrapper. To avoid lifetimes leaking we don't let the evm
99        // struct outlive this scope.
100
101        // Borrowed, not cloned: an override map can hold every storage slot a pending block
102        // touched, and this runs once per pool.
103        let no_storage_overrides = HashMap::new();
104        let no_balance_overrides = HashMap::new();
105        let db_ref = OverriddenSimulationDB {
106            inner_db: &self.state,
107            overrides: params
108                .overrides
109                .as_ref()
110                .unwrap_or(&no_storage_overrides),
111            native_balance_overrides: params
112                .native_balance_overrides
113                .as_ref()
114                .unwrap_or(&no_balance_overrides),
115        };
116
117        let tx_env = TxEnv {
118            caller: params.caller,
119            gas_limit: params.gas_limit.unwrap_or(8_000_000),
120            kind: TxKind::Call(params.to),
121            value: params.value,
122            data: Bytes::copy_from_slice(&params.data),
123            ..Default::default()
124        };
125
126        let mut block = self
127            .state
128            .get_current_block()
129            .ok_or_else(|| {
130                SimulationEngineError::StorageError(
131                    "Current block not set in SimulationEngine.".into(),
132                )
133            })?;
134
135        if let Some(overrides) = &params.block_overrides {
136            if let Some(number) = overrides.number {
137                block.number = number;
138            }
139            if let Some(timestamp) = overrides.timestamp {
140                block.timestamp = timestamp;
141            }
142        }
143
144        let block_env = BlockEnv {
145            number: U256::from(block.number),
146            timestamp: U256::from(block.timestamp),
147            ..Default::default()
148        };
149
150        let mut cfg_env: CfgEnv<SpecId> = CfgEnv::new_with_spec(SpecId::PRAGUE);
151        cfg_env.disable_nonce_check = true;
152        cfg_env.disable_eip3607 = true;
153
154        let context = Context::mainnet()
155            .with_cfg(cfg_env)
156            .with_ref_db(db_ref)
157            .with_block(block_env)
158            .with_tx(tx_env.clone())
159            .modify_journal_chained(|journal| {
160                if let Some(transient_storage) = params.transient_storage.clone() {
161                    for (address, slots) in transient_storage {
162                        for (slot, value) in slots {
163                            journal.tstore(address, slot, value);
164                        }
165                    }
166                }
167                if let Some(overrides) = &params.overrides {
168                    for (address, storage) in overrides {
169                        let keys = storage.keys().copied();
170                        if let Err(e) = journal.warm_account_and_storage(*address, keys) {
171                            warn!(%address, error = ?e, "Failed to warm overridden account");
172                        }
173                    }
174                }
175            });
176
177        let evm_result = if self.trace {
178            let mut tracer = TracingInspector::new(TracingInspectorConfig::default());
179
180            let res = {
181                let mut vm = context.build_mainnet_with_inspector(&mut tracer);
182
183                debug!(
184                    "Starting simulation with tx parameters: {:#?} {:#?}",
185                    vm.ctx.tx, vm.ctx.block
186                );
187                vm.inspect_tx(tx_env)
188            };
189
190            Self::print_traces(tracer, res.as_ref().ok())?;
191
192            res
193        } else {
194            let mut vm = context.build_mainnet();
195
196            debug!("Starting simulation with tx parameters: {:#?} {:#?}", vm.ctx.tx, vm.ctx.block);
197
198            vm.replay()
199        };
200
201        // TODO: update revm to 25.0.0 and get transient storage from the journaled state
202        interpret_evm_result(evm_result, HashMap::new())
203    }
204
205    pub fn clear_temp_storage(&mut self) -> Result<(), <D as EngineDatabaseInterface>::Error> {
206        self.state.clear_temp_storage()
207    }
208
209    fn print_traces(
210        tracer: TracingInspector,
211        res: Option<&ResultAndState>,
212    ) -> Result<(), SimulationEngineError> {
213        let (exit_reason, _gas_refunded, gas_used, _out, _exec_logs) = match res {
214            Some(ResultAndState { result, state: _ }) => {
215                // let ResultAndState { result, state: _ } = res;
216                match result.clone() {
217                    ExecutionResult::Success {
218                        reason,
219                        gas_used,
220                        gas_refunded,
221                        output,
222                        logs,
223                        ..
224                    } => (reason.into(), gas_refunded, gas_used, Some(output), logs),
225                    ExecutionResult::Revert { gas_used, output } => {
226                        // Need to fetch the unused gas
227                        (
228                            InstructionResult::Revert,
229                            0_u64,
230                            gas_used,
231                            Some(Output::Call(output)),
232                            vec![],
233                        )
234                    }
235                    ExecutionResult::Halt { reason, gas_used } => {
236                        (reason.into(), 0_u64, gas_used, None, vec![])
237                    }
238                }
239            }
240            _ => (InstructionResult::Stop, 0_u64, 0, None, vec![]),
241        };
242
243        let trace_res = TraceResult {
244            success: matches!(exit_reason, return_ok!()),
245            traces: Some(vec![tracer.into_traces()]),
246            gas_used,
247        };
248
249        #[expect(
250            clippy::disallowed_methods,
251            reason = "trace printing, a debugging aid, works outside a runtime and on a multi-thread one; on a current-thread runtime it panics"
252        )]
253        tokio::task::block_in_place(|| -> Result<(), SimulationEngineError> {
254            let future = async {
255                handle_traces(
256                    trace_res,
257                    env::var("ETHERSCAN_API_KEY").ok(),
258                    tycho_common::models::Chain::Ethereum,
259                )
260                .await
261                .map_err(|err| SimulationEngineError::TraceError(err.to_string()))
262            };
263            if let Ok(handle) = Handle::try_current() {
264                // If successful, use the existing runtime to block on the future
265                handle.block_on(future)
266            } else {
267                // If no runtime is found, create a new one and block on the future
268                let rt = Runtime::new().map_err(|err| {
269                    SimulationEngineError::TraceError(format!(
270                        "Failed to create a new runtime: {err}"
271                    ))
272                })?;
273                rt.block_on(future)
274            }
275        })?;
276
277        Ok(())
278    }
279}
280
281/// Convert a complex EVMResult into a simpler structure
282///
283/// EVMResult is not of an error type even if the transaction was not successful.
284/// This function returns an Ok if and only if the transaction was successful.
285/// In case the transaction was reverted, halted, or another error occurred (like an error
286/// when accessing storage), this function returns an Err with a simple String description
287/// of an underlying cause.
288///
289/// # Arguments
290///
291/// * `evm_result` - output from calling `revm.transact()`
292///
293/// # Errors
294///
295/// * `SimulationError` - simulation wasn't successful for any reason. See variants for details.
296fn interpret_evm_result<DBError: Debug>(
297    evm_result: Result<ResultAndState, EVMError<DBError>>,
298    transient_storage: HashMap<Address, HashMap<U256, U256>>,
299) -> Result<SimulationResult, SimulationEngineError> {
300    match evm_result {
301        Ok(result_and_state) => match result_and_state.result {
302            ExecutionResult::Success { gas_used, gas_refunded, output, .. } => {
303                Ok(interpret_evm_success(
304                    gas_used,
305                    gas_refunded,
306                    output,
307                    result_and_state.state,
308                    transient_storage,
309                ))
310            }
311            ExecutionResult::Revert { output, gas_used } => {
312                Err(SimulationEngineError::TransactionError {
313                    data: format!("0x{encoded}", encoded = hex::encode::<Vec<u8>>(output.into())),
314                    gas_used: Some(gas_used),
315                })
316            }
317            ExecutionResult::Halt { reason, gas_used } => {
318                Err(SimulationEngineError::TransactionError {
319                    data: format!("{reason:?}"),
320                    gas_used: Some(gas_used),
321                })
322            }
323        },
324        Err(evm_error) => match evm_error {
325            EVMError::Transaction(invalid_tx) => Err(SimulationEngineError::TransactionError {
326                data: format!("EVM error: {invalid_tx:?}"),
327                gas_used: None,
328            }),
329            EVMError::Database(db_error) => {
330                Err(SimulationEngineError::StorageError(format!("Storage error: {db_error:?}")))
331            }
332            EVMError::Custom(err) => Err(SimulationEngineError::TransactionError {
333                data: format!("Unexpected error {err}"),
334                gas_used: None,
335            }),
336            EVMError::Header(err) => Err(SimulationEngineError::TransactionError {
337                data: format!("Unexpected error {err}"),
338                gas_used: None,
339            }),
340        },
341    }
342}
343
344// Helper function to extract some details from a successful transaction execution
345fn interpret_evm_success(
346    gas_used: u64,
347    gas_refunded: u64,
348    output: Output,
349    state: EvmState,
350    transient_storage: HashMap<Address, HashMap<U256, U256>>,
351) -> SimulationResult {
352    SimulationResult {
353        result: output.into_data(),
354        state_updates: {
355            // For each account mentioned in state updates in REVM output, we will have
356            // one record in our hashmap. Such record contains *new* values of account's
357            // state. This record's optional `storage` field will contain
358            // account's storage changes (as a hashmap from slot index to slot value),
359            // unless REVM output doesn't contain any storage for this account, in which case
360            // we set this field to None. If REVM did return storage, we return one record
361            // per *modified* slot (sometimes REVM returns a storage record for an account
362            // even if the slots are not modified).
363            let mut account_updates: HashMap<Address, StateUpdate> = HashMap::new();
364            for (address, account) in state {
365                account_updates.insert(
366                    address,
367                    StateUpdate {
368                        // revm doesn't say if the balance was actually changed
369                        balance: Some(account.info.balance),
370                        // revm doesn't say if the code was actually changed
371                        storage: {
372                            if account.storage.is_empty() {
373                                None
374                            } else {
375                                let mut slot_updates: HashMap<U256, U256> = HashMap::new();
376                                for (index, slot) in account.storage {
377                                    if slot.is_changed() {
378                                        slot_updates.insert(index, slot.present_value);
379                                    }
380                                }
381                                if slot_updates.is_empty() {
382                                    None
383                                } else {
384                                    Some(slot_updates)
385                                }
386                            }
387                        },
388                    },
389                );
390            }
391            account_updates
392        },
393        gas_used: gas_used - gas_refunded,
394        transient_storage,
395    }
396}
397
398#[derive(Debug, Default)]
399/// Data needed to invoke a transaction simulation
400pub struct SimulationParameters {
401    /// Address of the sending account
402    pub caller: Address,
403    /// Address of the receiving account/contract
404    pub to: Address,
405    /// Calldata
406    pub data: Vec<u8>,
407    /// Amount of native token sent
408    pub value: U256,
409    /// EVM state overrides.
410    /// Will be merged with existing state. Will take effect only for current simulation.
411    pub overrides: Option<HashMap<Address, HashMap<U256, U256>>>,
412    /// Limit of gas to be used by the transaction
413    pub gas_limit: Option<u64>,
414    /// Map of the address whose transient storage will be overwritten, to a map of storage slot
415    /// and value.
416    pub transient_storage: Option<HashMap<Address, HashMap<U256, U256>>>,
417    /// Per-call block context overrides.
418    pub block_overrides: Option<BlockEnvOverrides>,
419    /// Native balance overrides. Same per-call scoping as `overrides`.
420    pub native_balance_overrides: Option<HashMap<Address, U256>>,
421}
422
423#[derive(Debug, Clone, Default, PartialEq, Eq)]
424pub struct BlockEnvOverrides {
425    pub number: Option<u64>,
426    pub timestamp: Option<u64>,
427}
428
429/// State a view call runs against, overriding what the engine's database holds.
430///
431/// `Default` means no overrides, so a call reads the engine's confirmed state.
432#[derive(Debug, Clone, Default)]
433pub struct PendingOverrides {
434    pub storage: Option<HashMap<Address, HashMap<U256, U256>>>,
435    pub native_balances: Option<HashMap<Address, U256>>,
436    pub block: Option<BlockEnvOverrides>,
437}
438
439impl PendingOverrides {
440    /// The state `accounts` would leave behind, under the `block` environment.
441    ///
442    /// Only the accounts given appear, so every slot they did not write keeps its confirmed
443    /// value. A cleared slot is stored as `None` and reads back as zero, which is what the EVM
444    /// would see. Values shorter than 32 bytes are left-padded, which is how the indexer stores
445    /// slots and balances with leading zeros trimmed.
446    pub fn from_account_deltas(
447        accounts: &HashMap<tycho_common::Bytes, AccountDelta>,
448        block: Option<BlockEnvOverrides>,
449    ) -> Self {
450        let mut storage: HashMap<Address, HashMap<U256, U256>> = HashMap::new();
451        let mut native_balances: HashMap<Address, U256> = HashMap::new();
452        for (address, delta) in accounts {
453            if address.len() != 20 {
454                continue;
455            }
456            let address = Address::from_slice(address.as_ref());
457            let slots: HashMap<U256, U256> = delta
458                .slots
459                .iter()
460                .map(|(slot, value)| {
461                    (
462                        U256::from_be_slice(slot.as_ref()),
463                        value
464                            .as_ref()
465                            .map_or(U256::ZERO, |v| U256::from_be_slice(v.as_ref())),
466                    )
467                })
468                .collect();
469            if !slots.is_empty() {
470                storage.insert(address, slots);
471            }
472            if let Some(balance) = &delta.balance {
473                native_balances.insert(address, U256::from_be_slice(balance.as_ref()));
474            }
475        }
476        PendingOverrides {
477            storage: (!storage.is_empty()).then_some(storage),
478            native_balances: (!native_balances.is_empty()).then_some(native_balances),
479            block,
480        }
481    }
482
483    /// Parameters for a `data` view call to `to` from the zero address, under these overrides.
484    ///
485    /// Clones the override maps, which `SimulationParameters` owns. Callers that issue many
486    /// calls per pending block pay that clone per call.
487    pub fn view_call(&self, to: Address, data: Vec<u8>) -> SimulationParameters {
488        SimulationParameters {
489            caller: Address::ZERO,
490            to,
491            data,
492            overrides: self.storage.clone(),
493            native_balance_overrides: self.native_balances.clone(),
494            block_overrides: self.block.clone(),
495            ..Default::default()
496        }
497    }
498}
499
500#[cfg(test)]
501mod pending_overrides_tests {
502    use std::collections::HashMap;
503
504    use alloy::primitives::{Address, U256};
505    use tycho_common::{
506        models::{contract::AccountDelta, Chain, ChangeType},
507        Bytes,
508    };
509
510    use super::{BlockEnvOverrides, PendingOverrides};
511
512    fn account_delta(
513        address: [u8; 20],
514        slots: Vec<(Vec<u8>, Option<Vec<u8>>)>,
515        balance: Option<Vec<u8>>,
516    ) -> (Bytes, AccountDelta) {
517        let address = Bytes::from(address.to_vec());
518        (
519            address.clone(),
520            AccountDelta::new(
521                Chain::Ethereum,
522                address,
523                slots
524                    .into_iter()
525                    .map(|(slot, value)| (Bytes::from(slot), value.map(Bytes::from)))
526                    .collect(),
527                balance.map(Bytes::from),
528                None,
529                ChangeType::Update,
530            ),
531        )
532    }
533
534    #[test]
535    fn test_slots_and_balances_reach_the_overrides() {
536        let account = [0xaau8; 20];
537        let block = BlockEnvOverrides { number: Some(3), timestamp: Some(4) };
538        let overrides = PendingOverrides::from_account_deltas(
539            &HashMap::from([account_delta(
540                account,
541                vec![(vec![3], Some(vec![7]))],
542                Some(vec![0x0d, 0xe0]),
543            )]),
544            Some(block.clone()),
545        );
546
547        let address = Address::from_slice(&account);
548        assert_eq!(
549            overrides
550                .storage
551                .as_ref()
552                .and_then(|s| s.get(&address))
553                .and_then(|slots| slots.get(&U256::from(3))),
554            Some(&U256::from(7)),
555            "a written slot must be overridden"
556        );
557        assert_eq!(
558            overrides
559                .native_balances
560                .as_ref()
561                .and_then(|b| b.get(&address)),
562            Some(&U256::from(0x0de0)),
563            "a native balance must be overridden"
564        );
565        assert_eq!(overrides.block, Some(block));
566    }
567
568    #[test]
569    fn test_cleared_slot_reads_as_zero() {
570        let account = [0xbbu8; 20];
571        let overrides = PendingOverrides::from_account_deltas(
572            &HashMap::from([account_delta(account, vec![(vec![1], None)], None)]),
573            None,
574        );
575
576        assert_eq!(
577            overrides
578                .storage
579                .as_ref()
580                .and_then(|s| s.get(&Address::from_slice(&account)))
581                .and_then(|slots| slots.get(&U256::from(1))),
582            Some(&U256::ZERO),
583            "a cleared slot must override to zero, not vanish"
584        );
585        assert!(overrides.native_balances.is_none());
586    }
587
588    #[test]
589    fn test_no_accounts_means_no_overrides() {
590        let overrides = PendingOverrides::from_account_deltas(&HashMap::new(), None);
591        assert!(overrides.storage.is_none());
592        assert!(overrides.native_balances.is_none());
593        assert!(overrides.block.is_none());
594    }
595
596    /// Every override a caller sets must reach the parameters, or a pool would silently be
597    /// priced against confirmed state.
598    #[test]
599    fn test_view_call_carries_every_override() {
600        let account = Address::repeat_byte(7);
601        let overrides = PendingOverrides {
602            storage: Some(HashMap::from([(account, HashMap::from([(U256::ZERO, U256::from(1))]))])),
603            native_balances: Some(HashMap::from([(account, U256::from(2))])),
604            block: Some(BlockEnvOverrides { number: Some(3), timestamp: Some(4) }),
605        };
606
607        let params = overrides.view_call(account, vec![0xab]);
608
609        assert_eq!(params.overrides, overrides.storage);
610        assert_eq!(params.native_balance_overrides, overrides.native_balances);
611        assert_eq!(params.block_overrides, overrides.block);
612        assert_eq!(params.caller, Address::ZERO, "A view call must not impersonate an account.");
613        assert_eq!(params.to, account);
614        assert_eq!(params.data, vec![0xab]);
615        assert_eq!(params.value, U256::ZERO, "A view call must not transfer value.");
616    }
617
618    #[test]
619    fn test_default_view_call_overrides_nothing() {
620        let params = PendingOverrides::default().view_call(Address::ZERO, Vec::new());
621
622        assert!(params.overrides.is_none());
623        assert!(params
624            .native_balance_overrides
625            .is_none());
626        assert!(params.block_overrides.is_none());
627    }
628}
629
630#[cfg(test)]
631mod tests {
632    use std::{str::FromStr, time::Instant};
633
634    use alloy::{
635        primitives::{Address, Bytes, Keccak256, B256},
636        sol_types::SolValue,
637        transports::{RpcError, TransportError, TransportErrorKind},
638    };
639    use revm::{
640        context::result::{HaltReason, InvalidTransaction, OutOfGasError, SuccessReason},
641        state::{
642            Account, AccountInfo, AccountStatus, Bytecode, EvmState as rState, EvmStorageSlot,
643        },
644    };
645    use tycho_client::feed::BlockHeader;
646
647    use super::*;
648    use crate::evm::engine_db::{
649        engine_db_interface::EngineDatabaseInterface,
650        simulation_db::{EVMProvider, SimulationDB},
651        tycho_db::PreCachedDB,
652        utils::{get_client, get_runtime},
653    };
654
655    #[test]
656    fn test_interpret_result_ok_success() {
657        let evm_result: Result<ResultAndState, EVMError<TransportError>> = Ok(ResultAndState {
658            result: ExecutionResult::Success {
659                reason: SuccessReason::Return,
660                gas_used: 100_u64,
661                gas_refunded: 10_u64,
662                logs: Vec::new(),
663                output: Output::Call(Bytes::from_static(b"output")),
664            },
665            state: [(
666                // storage has changed
667                Address::ZERO,
668                Account {
669                    info: AccountInfo {
670                        balance: U256::from_limbs([1, 0, 0, 0]),
671                        nonce: 2,
672                        code_hash: B256::ZERO,
673                        code: None,
674                    },
675                    transaction_id: 0,
676                    storage: [
677                        // this slot has changed
678                        (
679                            U256::from_limbs([3, 1, 0, 0]),
680                            EvmStorageSlot {
681                                original_value: U256::from_limbs([4, 0, 0, 0]),
682                                present_value: U256::from_limbs([5, 0, 0, 0]),
683                                transaction_id: 0,
684                                is_cold: true,
685                            },
686                        ),
687                        // this slot hasn't changed
688                        (
689                            U256::from_limbs([3, 2, 0, 0]),
690                            EvmStorageSlot {
691                                original_value: U256::from_limbs([4, 0, 0, 0]),
692                                present_value: U256::from_limbs([4, 0, 0, 0]),
693                                transaction_id: 0,
694                                is_cold: true,
695                            },
696                        ),
697                    ]
698                    .iter()
699                    .cloned()
700                    .collect(),
701                    status: AccountStatus::Touched,
702                },
703            )]
704            .iter()
705            .cloned()
706            .collect(),
707        });
708
709        let transient_storage = HashMap::from([(
710            Address::from_str("0x1f98400000000000000000000000000000000004").unwrap(),
711            HashMap::from([(U256::from(0), U256::from(1))]),
712        )]);
713        let result = interpret_evm_result(evm_result, transient_storage.clone());
714        let simulation_result = result.unwrap();
715
716        assert_eq!(simulation_result.result, Bytes::from_static(b"output"));
717        let expected_state_updates = [(
718            Address::ZERO,
719            StateUpdate {
720                storage: Some(
721                    [(U256::from_limbs([3, 1, 0, 0]), U256::from_limbs([5, 0, 0, 0]))]
722                        .iter()
723                        .cloned()
724                        .collect(),
725                ),
726                balance: Some(U256::from_limbs([1, 0, 0, 0])),
727            },
728        )]
729        .iter()
730        .cloned()
731        .collect();
732        assert_eq!(simulation_result.state_updates, expected_state_updates);
733        assert_eq!(simulation_result.gas_used, 90);
734        assert_eq!(simulation_result.transient_storage, transient_storage);
735    }
736
737    #[test]
738    fn test_interpret_result_ok_revert() {
739        let evm_result: Result<ResultAndState, EVMError<TransportError>> = Ok(ResultAndState {
740            result: ExecutionResult::Revert {
741                gas_used: 100_u64,
742                output: Bytes::from_static(b"output"),
743            },
744            state: rState::default(),
745        });
746
747        let result = interpret_evm_result(evm_result, HashMap::new());
748
749        assert!(result.is_err());
750        let err = result.err().unwrap();
751        match err {
752            SimulationEngineError::TransactionError { data: _, gas_used } => {
753                assert_eq!(
754                    format!("0x{}", hex::encode::<Vec<u8>>("output".into())),
755                    "0x6f7574707574"
756                );
757                assert_eq!(gas_used, Some(100));
758            }
759            SimulationEngineError::StorageError(_) |
760            SimulationEngineError::OutOfGas(..) |
761            SimulationEngineError::TraceError(_) => panic!("Wrong type of SimulationError!"),
762        }
763    }
764
765    #[test]
766    fn test_interpret_result_ok_halt() {
767        let evm_result: Result<ResultAndState, EVMError<TransportError>> = Ok(ResultAndState {
768            result: ExecutionResult::Halt {
769                reason: HaltReason::OutOfGas(OutOfGasError::Basic),
770                gas_used: 100_u64,
771            },
772            state: rState::default(),
773        });
774
775        let result = interpret_evm_result(evm_result, HashMap::new());
776
777        assert!(result.is_err());
778        let err = result.err().unwrap();
779        match err {
780            SimulationEngineError::TransactionError { data, gas_used } => {
781                assert_eq!(data, "OutOfGas(Basic)");
782                assert_eq!(gas_used, Some(100));
783            }
784            SimulationEngineError::StorageError(_) |
785            SimulationEngineError::OutOfGas(..) |
786            SimulationEngineError::TraceError(_) => panic!("Wrong type of SimulationError!"),
787        }
788    }
789
790    #[test]
791    fn test_interpret_result_err_invalid_transaction() {
792        let evm_result: Result<ResultAndState, EVMError<TransportError>> =
793            Err(EVMError::Transaction(InvalidTransaction::PriorityFeeGreaterThanMaxFee));
794
795        let result = interpret_evm_result(evm_result, HashMap::new());
796
797        assert!(result.is_err());
798        let err = result.err().unwrap();
799        match err {
800            SimulationEngineError::TransactionError { data, gas_used } => {
801                assert_eq!(data, "EVM error: PriorityFeeGreaterThanMaxFee");
802                assert_eq!(gas_used, None);
803            }
804            SimulationEngineError::StorageError(_) |
805            SimulationEngineError::OutOfGas(..) |
806            SimulationEngineError::TraceError(_) => panic!("Wrong type of SimulationError!"),
807        }
808    }
809
810    #[test]
811    fn test_interpret_result_err_db_error() {
812        let evm_result: Result<ResultAndState, EVMError<TransportError>> = Err(EVMError::Database(
813            RpcError::Transport(TransportErrorKind::Custom(Box::from("boo".to_string()))),
814        ));
815
816        let result = interpret_evm_result(evm_result, HashMap::new());
817
818        assert!(result.is_err());
819        let err = result.err().unwrap();
820        match err {
821            SimulationEngineError::StorageError(msg) => {
822                assert_eq!(msg, "Storage error: Transport(Custom(\"boo\"))")
823            }
824            SimulationEngineError::OutOfGas(..) |
825            SimulationEngineError::TransactionError { .. } |
826            SimulationEngineError::TraceError(_) => panic!("Wrong type of SimulationError!"),
827        }
828    }
829    fn new_state() -> SimulationDB<EVMProvider> {
830        let runtime = get_runtime().expect("Failed to create test runtime");
831        let client = get_client(None).expect("Failed to create test client");
832        SimulationDB::new(client, runtime, None)
833    }
834
835    #[test]
836    fn test_simulate_applies_block_env_overrides() {
837        let state = PreCachedDB::new().expect("PreCachedDB creation succeeds");
838        let contract =
839            Address::from_str("0x0000000000000000000000000000000000001234").expect("valid address");
840        // Minimal runtime bytecode equivalent to the following Solidity contract:
841        //
842        // // SPDX-License-Identifier: UNLICENSED
843        // pragma solidity ^0.8.26;
844        //
845        // contract BlockNumberTest {
846        //     function test() external view returns (uint256) {
847        //         return block.number;
848        //     }
849        // }
850        let bytecode = Bytecode::new_raw(Bytes::from_static(&[
851            0x43, // NUMBER
852            0x60, 0x00, // PUSH1 0
853            0x52, // MSTORE
854            0x60, 0x20, // PUSH1 32
855            0x60, 0x00, // PUSH1 0
856            0xf3, // RETURN
857        ]));
858        let account = AccountInfo::new(U256::ZERO, 0, bytecode.hash_slow(), bytecode);
859        state
860            .init_account(contract, account, None, true)
861            .expect("contract account init succeeds");
862        state
863            .init_account(Address::ZERO, AccountInfo::default(), None, true)
864            .expect("caller account init succeeds");
865        state
866            .update(Vec::new(), Some(BlockHeader { number: 1, timestamp: 2, ..Default::default() }))
867            .expect("block header update succeeds");
868
869        let sim_params = SimulationParameters {
870            caller: Address::ZERO,
871            to: contract,
872            data: Vec::new(),
873            value: U256::ZERO,
874            block_overrides: Some(BlockEnvOverrides { number: Some(123), timestamp: Some(456) }),
875            ..Default::default()
876        };
877
878        let engine = SimulationEngine::new(state, false);
879        let result = engine
880            .simulate(&sim_params)
881            .expect("simulation should apply block env overrides");
882
883        assert_eq!(U256::from_be_slice(result.result.as_ref()), U256::from(123));
884    }
885
886    #[test]
887    fn test_simulate_applies_native_balance_overrides() {
888        let state = PreCachedDB::new().expect("PreCachedDB creation succeeds");
889        let contract =
890            Address::from_str("0x0000000000000000000000000000000000001234").expect("valid address");
891        let bytecode = Bytecode::new_raw(Bytes::from_static(&[
892            0x47, // SELFBALANCE
893            0x60, 0x00, // PUSH1 0
894            0x52, // MSTORE
895            0x60, 0x20, // PUSH1 32
896            0x60, 0x00, // PUSH1 0
897            0xf3, // RETURN
898        ]));
899        let account = AccountInfo::new(U256::ZERO, 0, bytecode.hash_slow(), bytecode);
900        state
901            .init_account(contract, account, None, true)
902            .expect("contract account init succeeds");
903        state
904            .init_account(Address::ZERO, AccountInfo::default(), None, true)
905            .expect("caller account init succeeds");
906        state
907            .update(Vec::new(), Some(BlockHeader { number: 1, timestamp: 2, ..Default::default() }))
908            .expect("block header update succeeds");
909        let expected_balance = U256::from(4_200_000_000_000_000_000u64);
910        let sim_params = SimulationParameters {
911            caller: Address::ZERO,
912            to: contract,
913            native_balance_overrides: Some(HashMap::from([(contract, expected_balance)])),
914            ..Default::default()
915        };
916
917        let result = SimulationEngine::new(state, false)
918            .simulate(&sim_params)
919            .expect("simulation should apply the native balance override");
920
921        assert_eq!(U256::from_be_slice(result.result.as_ref()), expected_balance);
922    }
923
924    #[test]
925    fn test_integration_revm_v2_swap() {
926        let state = new_state();
927
928        // any random address will work
929        let caller = Address::from_str("0x0000000000000000000000000000000000000000")
930            .expect("valid caller address");
931        let router_addr = Address::from_str("0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D")
932            .expect("valid router address");
933        let weth_addr = Address::from_str("0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2")
934            .expect("valid WETH address");
935        let usdc_addr = Address::from_str("0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48")
936            .expect("valid USDC address");
937
938        // Define the function selector and input arguments
939        let selector = "getAmountsOut(uint256,address[])";
940        let amount_in = U256::from(100_000_000);
941        let path = vec![usdc_addr, weth_addr];
942
943        let encoded = {
944            let args = (amount_in, path);
945            let mut hasher = Keccak256::new();
946            hasher.update(selector.as_bytes());
947            let selector_bytes = &hasher.finalize()[..4];
948            let mut data = selector_bytes.to_vec();
949            let mut encoded_args = args.abi_encode();
950            // Remove extra prefix if present (32 bytes for dynamic data)
951            if encoded_args.len() > 32 &&
952                encoded_args[..32] ==
953                    [0u8; 31]
954                        .into_iter()
955                        .chain([32].to_vec())
956                        .collect::<Vec<u8>>()
957            {
958                encoded_args = encoded_args[32..].to_vec();
959            }
960            data.extend(encoded_args);
961            data
962        };
963
964        // Simulation parameters
965        let sim_params =
966            SimulationParameters { caller, to: router_addr, data: encoded, ..Default::default() };
967        let mut eng = SimulationEngine::new(state, true);
968
969        let block = BlockHeader {
970            number: 23428552,
971            hash: tycho_common::Bytes::from_str(
972                "0x0000000000000000000000000000000000000000000000000000000000000000",
973            )
974            .unwrap(),
975            timestamp: 1758665355,
976            ..Default::default()
977        };
978        eng.state.set_block(Some(block));
979
980        let result = eng.simulate(&sim_params);
981        type BalanceReturn = Vec<U256>;
982        let amounts_out: Vec<U256> = match result {
983            Ok(SimulationResult { result, .. }) => BalanceReturn::abi_decode(&result)
984                .unwrap_or_else(|e| panic!("Failed to decode result: {e:?}")),
985            _ => panic!("Execution reverted!"),
986        };
987
988        println!(
989            "Swap yielded {} WETH",
990            amounts_out
991                .last()
992                .expect("Empty decoding result")
993        );
994
995        let start = Instant::now();
996        let n_iter = 1000;
997        for _ in 0..n_iter {
998            eng.simulate(&sim_params).unwrap();
999        }
1000        let duration = start.elapsed();
1001
1002        println!("Using revm:");
1003        println!("Total Duration [n_iter={n_iter}]: {duration:?}");
1004        println!("Single get_amount_out call: {per_call:?}", per_call = duration / n_iter);
1005    }
1006
1007    #[test]
1008    fn test_contract_deployment() {
1009        let readonly_state = new_state();
1010        let state = new_state();
1011
1012        let selector = "balanceOf(address)";
1013        let eoa_address = Address::from_str("0xDFd5293D8e347dFe59E90eFd55b2956a1343963d")
1014            .expect("valid EOA address");
1015        let calldata = {
1016            let args = eoa_address;
1017            let mut hasher = Keccak256::new();
1018            hasher.update(selector.as_bytes());
1019            let selector_bytes = &hasher.finalize()[..4];
1020            let mut data = selector_bytes.to_vec();
1021            data.extend(args.abi_encode());
1022            data
1023        };
1024
1025        let usdt_address = Address::from_str("0xdAC17F958D2ee523a2206206994597C13D831ec7").unwrap();
1026        let _ = readonly_state
1027            .basic_ref(usdt_address)
1028            .unwrap()
1029            .unwrap();
1030
1031        // let deploy_bytecode = std::fs::read(
1032        //     "/home/mdank/repos/datarevenue/DEFI/defibot-solver/defibot/swaps/pool_state/dodo/
1033        // compiled/ERC20.bin-runtime" ).unwrap();
1034        // let deploy_bytecode = revm::precompile::Bytes::from(mocked_bytecode);
1035        hex::decode("608060405234801562000010575f80fd5b5060405162000a6b38038062000a6b83398101604081905262000033916200012c565b600362000041848262000237565b50600462000050838262000237565b506005805460ff191660ff9290921691909117905550620002ff9050565b634e487b7160e01b5f52604160045260245ffd5b5f82601f83011262000092575f80fd5b81516001600160401b0380821115620000af57620000af6200006e565b604051601f8301601f19908116603f01168101908282118183101715620000da57620000da6200006e565b81604052838152602092508683858801011115620000f6575f80fd5b5f91505b83821015620001195785820183015181830184015290820190620000fa565b5f93810190920192909252949350505050565b5f805f606084860312156200013f575f80fd5b83516001600160401b038082111562000156575f80fd5b620001648783880162000082565b945060208601519150808211156200017a575f80fd5b50620001898682870162000082565b925050604084015160ff81168114620001a0575f80fd5b809150509250925092565b600181811c90821680620001c057607f821691505b602082108103620001df57634e487b7160e01b5f52602260045260245ffd5b50919050565b601f82111562000232575f81815260208120601f850160051c810160208610156200020d5750805b601f850160051c820191505b818110156200022e5782815560010162000219565b5050505b505050565b81516001600160401b038111156200025357620002536200006e565b6200026b81620002648454620001ab565b84620001e5565b602080601f831160018114620002a1575f8415620002895750858301515b5f19600386901b1c1916600185901b1785556200022e565b5f85815260208120601f198616915b82811015620002d157888601518255948401946001909101908401620002b0565b5085821015620002ef57878501515f19600388901b60f8161c191681555b5050505050600190811b01905550565b61075e806200030d5f395ff3fe608060405234801561000f575f80fd5b50600436106100a6575f3560e01c8063395093511161006e578063395093511461011f57806370a082311461013257806395d89b411461015a578063a457c2d714610162578063a9059cbb14610175578063dd62ed3e14610188575f80fd5b806306fdde03146100aa578063095ea7b3146100c857806318160ddd146100eb57806323b872dd146100fd578063313ce56714610110575b5f80fd5b6100b261019b565b6040516100bf91906105b9565b60405180910390f35b6100db6100d636600461061f565b61022b565b60405190151581526020016100bf565b6002545b6040519081526020016100bf565b6100db61010b366004610647565b610244565b604051601281526020016100bf565b6100db61012d36600461061f565b610267565b6100ef610140366004610680565b6001600160a01b03165f9081526020819052604090205490565b6100b2610288565b6100db61017036600461061f565b610297565b6100db61018336600461061f565b6102f2565b6100ef6101963660046106a0565b6102ff565b6060600380546101aa906106d1565b80601f01602080910402602001604051908101604052809291908181526020018280546101d6906106d1565b80156102215780601f106101f857610100808354040283529160200191610221565b820191905f5260205f20905b81548152906001019060200180831161020457829003601f168201915b5050505050905090565b5f33610238818585610329565b60019150505b92915050565b5f336102518582856103dc565b61025c85858561043e565b506001949350505050565b5f3361023881858561027983836102ff565b6102839190610709565b610329565b6060600480546101aa906106d1565b5f33816102a482866102ff565b9050838110156102e557604051632983c0c360e21b81526001600160a01b038616600482015260248101829052604481018590526064015b60405180910390fd5b61025c8286868403610329565b5f3361023881858561043e565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b6001600160a01b0383166103525760405163e602df0560e01b81525f60048201526024016102dc565b6001600160a01b03821661037b57604051634a1406b160e11b81525f60048201526024016102dc565b6001600160a01b038381165f8181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b5f6103e784846102ff565b90505f198114610438578181101561042b57604051637dc7a0d960e11b81526001600160a01b038416600482015260248101829052604481018390526064016102dc565b6104388484848403610329565b50505050565b6001600160a01b03831661046757604051634b637e8f60e11b81525f60048201526024016102dc565b6001600160a01b0382166104905760405163ec442f0560e01b81525f60048201526024016102dc565b61049b8383836104a0565b505050565b6001600160a01b0383166104ca578060025f8282546104bf9190610709565b9091555061053a9050565b6001600160a01b0383165f908152602081905260409020548181101561051c5760405163391434e360e21b81526001600160a01b038516600482015260248101829052604481018390526064016102dc565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b03821661055657600280548290039055610574565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516103cf91815260200190565b5f6020808352835180828501525f5b818110156105e4578581018301518582016040015282016105c8565b505f604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b038116811461061a575f80fd5b919050565b5f8060408385031215610630575f80fd5b61063983610604565b946020939093013593505050565b5f805f60608486031215610659575f80fd5b61066284610604565b925061067060208501610604565b9150604084013590509250925092565b5f60208284031215610690575f80fd5b61069982610604565b9392505050565b5f80604083850312156106b1575f80fd5b6106ba83610604565b91506106c860208401610604565b90509250929050565b600181811c90821680620001c057607f821691505b602082108103620001df57634e487b7160e01b5f52602260045260245ffd5b50919050565b8082018082111561023e57634e487b7160e01b5f52601160045260245ffdfea2646970667358221220dfc123d5852c9246ea16b645b377b4436e2f778438195cc6d6c435e8c73a20e764736f6c63430008140033000000000000000000000000000000000000000000000000000000000000000000").expect("valid hex bytecode");
1036
1037        let onchain_bytecode = Bytes::from(hex::decode("608060405234801561000f575f80fd5b50600436106100a6575f3560e01c8063395093511161006e578063395093511461011f57806370a082311461013257806395d89b411461015a578063a457c2d714610162578063a9059cbb14610175578063dd62ed3e14610188575f80fd5b806306fdde03146100aa578063095ea7b3146100c857806318160ddd146100eb57806323b872dd146100fd578063313ce56714610110575b5f80fd5b6100b261019b565b6040516100bf91906105b9565b60405180910390f35b6100db6100d636600461061f565b61022b565b60405190151581526020016100bf565b6002545b6040519081526020016100bf565b6100db61010b366004610647565b610244565b604051601281526020016100bf565b6100db61012d36600461061f565b610267565b6100ef610140366004610680565b6001600160a01b03165f9081526020819052604090205490565b6100b2610288565b6100db61017036600461061f565b610297565b6100db61018336600461061f565b6102f2565b6100ef6101963660046106a0565b6102ff565b6060600380546101aa906106d1565b80601f01602080910402602001604051908101604052809291908181526020018280546101d6906106d1565b80156102215780601f106101f857610100808354040283529160200191610221565b820191905f5260205f20905b81548152906001019060200180831161020457829003601f168201915b5050505050905090565b5f33610238818585610329565b60019150505b92915050565b5f336102518582856103dc565b61025c85858561043e565b506001949350505050565b5f3361023881858561027983836102ff565b6102839190610709565b610329565b6060600480546101aa906106d1565b5f33816102a482866102ff565b9050838110156102e557604051632983c0c360e21b81526001600160a01b038616600482015260248101829052604481018590526064015b60405180910390fd5b61025c8286868403610329565b5f3361023881858561043e565b6001600160a01b039182165f90815260016020908152604080832093909416825291909152205490565b6001600160a01b0383166103525760405163e602df0560e01b81525f60048201526024016102dc565b6001600160a01b03821661037b57604051634a1406b160e11b81525f60048201526024016102dc565b6001600160a01b038381165f8181526001602090815260408083209487168084529482529182902085905590518481527f8c5be1e5ebec7d5bd14f71427d1e84f3dd0314c0f7b2291e5b200ac8c7c3b92591015b60405180910390a3505050565b5f6103e784846102ff565b90505f198114610438578181101561042b57604051637dc7a0d960e11b81526001600160a01b038416600482015260248101829052604481018390526064016102dc565b6104388484848403610329565b50505050565b6001600160a01b03831661046757604051634b637e8f60e11b81525f60048201526024016102dc565b6001600160a01b0382166104905760405163ec442f0560e01b81525f60048201526024016102dc565b61049b8383836104a0565b505050565b6001600160a01b0383166104ca578060025f8282546104bf9190610709565b9091555061053a9050565b6001600160a01b0383165f908152602081905260409020548181101561051c5760405163391434e360e21b81526001600160a01b038516600482015260248101829052604481018390526064016102dc565b6001600160a01b0384165f9081526020819052604090209082900390555b6001600160a01b03821661055657600280548290039055610574565b6001600160a01b0382165f9081526020819052604090208054820190555b816001600160a01b0316836001600160a01b03167fddf252ad1be2c89b69c2b068fc378daa952ba7f163c4a11628f55a4df523b3ef836040516103cf91815260200190565b5f6020808352835180828501525f5b818110156105e4578581018301518582016040015282016105c8565b505f604082860101526040601f19601f8301168501019250505092915050565b80356001600160a01b038116811461061a575f80fd5b919050565b5f8060408385031215610630575f80fd5b61063983610604565b946020939093013593505050565b5f805f60608486031215610659575f80fd5b61066284610604565b925061067060208501610604565b9150604084013590509250925092565b5f60208284031215610690575f80fd5b61069982610604565b9392505050565b5f80604083850312156106b1575f80fd5b6106ba83610604565b91506106c860208401610604565b90509250929050565b600181811c908216806106e557607f821691505b60208210810361070357634e487b7160e01b5f52602260045260245ffd5b50919050565b8082018082111561023e57634e487b7160e01b5f52601160045260245ffdfea2646970667358221220dfc123d5852c9246ea16b645b377b4436e2f778438195cc6d6c435e8c73a20e764736f6c63430008140033000000000000000000000000000000000000000000000000000000000000000000").expect("valid hex bytecode"));
1038        let code = Bytecode::new_raw(onchain_bytecode);
1039        let contract_acc_info = AccountInfo::new(
1040            U256::from(0),
1041            0,
1042            code.hash_slow(),
1043            code,
1044            // true_usdt.code.unwrap(),
1045        );
1046        // Adding permanent storage for balance
1047        let mut storage = HashMap::default();
1048        storage.insert(
1049            U256::from_str(
1050                "25842306973167774731510882590667189188844731550465818811072464953030320818263",
1051            )
1052            .unwrap(),
1053            U256::from_str("25").unwrap(),
1054        );
1055        // MOCK A BALANCE AND APPROVAL
1056        // let mut permanent_storage = HashMap::new();
1057        // permanent_storage.insert(s)
1058        state
1059            .init_account(usdt_address, contract_acc_info, Some(storage), true)
1060            .expect("Failed to init account");
1061
1062        // DEPLOY A CONTRACT TO GET ON-CHAIN BYTECODE
1063        // let deployment_account = B160::from_str("0x0000000000000000000000000000000000000123")?;
1064        // state.init_account(
1065        //     deployment_account,
1066        //     AccountInfo::new(U256::MAX, 0, Bytecode::default()),
1067        //     None,
1068        //     true,
1069        // );
1070        // let deployment_params = SimulationParameters {
1071        //     caller: Address::from(deployment_account),
1072        //     to: Address::zero(),
1073        //     data: Bytes::from(deploy_bytecode),
1074        //     value: U256::from(0u64),
1075        //     overrides: None,
1076        //     gas_limit: None,
1077        // };
1078
1079        // prepare balanceOf
1080        // let deployed_contract_address =
1081        // B160::from_str("0x5450b634edf901a95af959c99c058086a51836a8")?; Adding overwrite
1082        // for balance
1083        let mut overrides = HashMap::default();
1084        let mut storage_overwrite = HashMap::default();
1085        storage_overwrite.insert(
1086            U256::from_str(
1087                "25842306973167774731510882590667189188844731550465818811072464953030320818263",
1088            )
1089            .unwrap(),
1090            U256::from_str("80").unwrap(),
1091        );
1092        overrides.insert(usdt_address, storage_overwrite);
1093
1094        let sim_params = SimulationParameters {
1095            caller: Address::from_str("0x0000000000000000000000000000000000000000")
1096                .expect("valid caller address"),
1097            to: usdt_address,
1098            // to: Address::from(deployed_contract_address),
1099            data: calldata,
1100            overrides: Some(overrides),
1101            ..Default::default()
1102        };
1103
1104        let mut eng = SimulationEngine::new(state, false);
1105
1106        // Dummy block (irrelevant for this test)
1107        let block = BlockHeader {
1108            number: 1,
1109            hash: tycho_common::Bytes::from_str(
1110                "0x0000000000000000000000000000000000000000000000000000000000000000",
1111            )
1112            .unwrap(),
1113            timestamp: 1748397011,
1114            ..Default::default()
1115        };
1116        eng.state.set_block(Some(block));
1117
1118        // println!("Deploying a mocked contract!");
1119        // let deployment_result = eng.simulate(&deployment_params);
1120        // match deployment_result {
1121        //     Ok(SimulationResult { result, state_updates, gas_used }) => {
1122        //         println!("Deployment result: {:?}", result);
1123        //         println!("Used gas: {:?}", gas_used);
1124        //         println!("{:?}", state_updates);
1125        //     }
1126        //     Err(error) => panic!("{:?}", error),
1127        // };
1128
1129        println!("Executing balanceOf");
1130        let result = eng.simulate(&sim_params);
1131        let balance = match result {
1132            Ok(SimulationResult { result, .. }) => {
1133                U256::abi_decode(&result).expect("valid ABI-encoded balance")
1134            }
1135            Err(error) => panic!("{error:?}"),
1136        };
1137        println!("Balance: {balance}");
1138    }
1139}