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