Skip to main content

tycho_simulation/evm/engine_db/
simulation_db.rs

1use std::{
2    collections::HashMap,
3    fmt::Debug,
4    sync::{Arc, RwLock, RwLockReadGuard, RwLockWriteGuard},
5};
6
7use alloy::{
8    primitives::{Address, Bytes as AlloyBytes, StorageValue, B256, U256},
9    providers::{
10        fillers::{BlobGasFiller, ChainIdFiller, FillProvider, GasFiller, JoinFill, NonceFiller},
11        Provider, RootProvider,
12    },
13    transports::{RpcError, TransportErrorKind},
14};
15use revm::{
16    context::DBErrorMarker,
17    state::{AccountInfo, Bytecode},
18    DatabaseRef,
19};
20use thiserror::Error;
21use tracing::{debug, info};
22use tycho_client::feed::BlockHeader;
23
24use super::{
25    super::account_storage::{AccountStorage, StateUpdate},
26    engine_db_interface::EngineDatabaseInterface,
27};
28
29/// A wrapper over an actual SimulationDB that allows overriding specific storage slots
30/// and native balances
31pub struct OverriddenSimulationDB<'a, DB: DatabaseRef> {
32    /// Wrapped database. Will be queried if a requested item is not found in the overrides.
33    pub inner_db: &'a DB,
34    /// A mapping from account address to storage.
35    /// Storage is a mapping from slot index to slot value.
36    pub overrides: &'a HashMap<Address, HashMap<U256, U256>>,
37    /// A mapping from account address to its overridden native balance.
38    /// An override for an account absent from the inner database materializes it as an
39    /// empty account holding that balance.
40    pub native_balance_overrides: &'a HashMap<Address, U256>,
41}
42
43impl<'a, DB: DatabaseRef> OverriddenSimulationDB<'a, DB> {
44    /// Creates a new OverriddenSimulationDB.
45    pub fn new(
46        inner_db: &'a DB,
47        overrides: &'a HashMap<Address, HashMap<U256, U256>>,
48        native_balance_overrides: &'a HashMap<Address, U256>,
49    ) -> Self {
50        OverriddenSimulationDB { inner_db, overrides, native_balance_overrides }
51    }
52}
53
54impl<DB: DatabaseRef> DatabaseRef for OverriddenSimulationDB<'_, DB> {
55    type Error = DB::Error;
56
57    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
58        let Some(balance) = self
59            .native_balance_overrides
60            .get(&address)
61        else {
62            return self.inner_db.basic_ref(address);
63        };
64        let info = self
65            .inner_db
66            .basic_ref(address)
67            .ok()
68            .flatten();
69        Ok(Some(AccountInfo { balance: *balance, ..info.unwrap_or_default() }))
70    }
71
72    fn code_by_hash_ref(&self, code_hash: B256) -> Result<Bytecode, Self::Error> {
73        self.inner_db
74            .code_by_hash_ref(code_hash)
75    }
76
77    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
78        match self.overrides.get(&address) {
79            None => self
80                .inner_db
81                .storage_ref(address, index),
82            Some(slot_overrides) => match slot_overrides.get(&index) {
83                Some(value) => {
84                    debug!(%address, %index, %value, "Requested storage of account {:x?} slot {}", address, index);
85                    Ok(*value)
86                }
87                None => self
88                    .inner_db
89                    .storage_ref(address, index),
90            },
91        }
92    }
93
94    fn block_hash_ref(&self, number: u64) -> Result<B256, Self::Error> {
95        self.inner_db.block_hash_ref(number)
96    }
97}
98
99/// A wrapper over an Alloy Provider with local storage cache and overrides.
100#[derive(Clone, Debug)]
101#[expect(
102    clippy::partial_pub_fields,
103    reason = "public API; making every field public or private is a breaking change"
104)]
105pub struct SimulationDB<P: Provider + Debug> {
106    /// Client to connect to the RPC
107    client: Arc<P>,
108    /// Cached data
109    account_storage: Arc<RwLock<AccountStorage>>,
110    /// Current block
111    block: Option<BlockHeader>,
112    /// Tokio runtime to execute async code
113    pub runtime: Option<Arc<tokio::runtime::Runtime>>,
114}
115
116pub type EVMProvider = FillProvider<
117    JoinFill<
118        alloy::providers::Identity,
119        JoinFill<GasFiller, JoinFill<BlobGasFiller, JoinFill<NonceFiller, ChainIdFiller>>>,
120    >,
121    RootProvider,
122>;
123
124impl<P: Provider + Debug + 'static> SimulationDB<P> {
125    pub fn new(
126        client: Arc<P>,
127        runtime: Option<Arc<tokio::runtime::Runtime>>,
128        block: Option<BlockHeader>,
129    ) -> Self {
130        Self {
131            client,
132            account_storage: Arc::new(RwLock::new(AccountStorage::new())),
133            block,
134            runtime,
135        }
136    }
137
138    /// Set the block that will be used when querying a node
139    pub fn set_block(&mut self, block: Option<BlockHeader>) {
140        self.block = block;
141    }
142
143    /// Update the simulation state.
144    ///
145    /// Updates the underlying smart contract storage. Any previously missed account,
146    /// which was queried and whose state now is in the account_storage will be cleared.
147    ///
148    /// # Arguments
149    ///
150    /// * `updates` - Values for the updates that should be applied to the accounts
151    /// * `block` - The newest block
152    ///
153    /// Returns a state update struct to revert this update.
154    pub fn update_state(
155        &mut self,
156        updates: &HashMap<Address, StateUpdate>,
157        block: BlockHeader,
158    ) -> Result<HashMap<Address, StateUpdate>, SimulationDBError> {
159        info!("Received account state update.");
160        let mut revert_updates = HashMap::new();
161        self.block = Some(block);
162        for (address, update_info) in updates.iter() {
163            let mut revert_entry = StateUpdate::default();
164            let current_balance = self
165                .read_account_storage()?
166                .get_account_info(address)
167                .map(|account| account.balance);
168            if let Some(balance) = current_balance {
169                revert_entry.balance = Some(balance);
170            }
171            if let Some(storage_updates) = update_info.storage.as_ref() {
172                let mut revert_storage = HashMap::default();
173                for index in storage_updates.keys() {
174                    let stored = self
175                        .read_account_storage()?
176                        .get_permanent_storage(address, index);
177                    if let Some(s) = stored {
178                        revert_storage.insert(*index, s);
179                    }
180                }
181                revert_entry.storage = Some(revert_storage);
182            }
183            revert_updates.insert(*address, revert_entry);
184
185            self.write_account_storage()?
186                .update_account(address, update_info);
187        }
188        Ok(revert_updates)
189    }
190
191    /// Query information about an Ethereum account.
192    /// Gets account information not including storage.
193    ///
194    /// # Arguments
195    ///
196    /// * `address` - The Ethereum address to query.
197    ///
198    /// # Returns
199    ///
200    /// Returns a `Result` containing either an `AccountInfo` object with balance, nonce, and code
201    /// information, or an error of type `SimulationDB<M>::Error` if the query fails.
202    fn query_account_info(
203        &self,
204        address: Address,
205    ) -> Result<AccountInfo, <SimulationDB<P> as DatabaseRef>::Error> {
206        debug!("Querying account info of {:x?} at block {:?}", address, self.block);
207
208        let (balance, nonce, code) = self.block_on(async {
209            let mut balance_request = self.client.get_balance(address);
210            let mut nonce_request = self
211                .client
212                .get_transaction_count(address);
213            let mut code_request = self.client.get_code_at(address);
214
215            if let Some(block) = &self.block {
216                balance_request = balance_request.number(block.number);
217                nonce_request = nonce_request.number(block.number);
218                code_request = code_request.number(block.number);
219            }
220
221            tokio::join!(balance_request, nonce_request, code_request,)
222        });
223        let code = Bytecode::new_raw(AlloyBytes::copy_from_slice(&code?));
224
225        Ok(AccountInfo::new(balance?, nonce?, code.hash_slow(), code))
226    }
227
228    /// Queries a value from storage at the specified index for a given Ethereum account.
229    ///
230    /// # Arguments
231    ///
232    /// * `address` - The Ethereum address of the account.
233    /// * `index` - The index of the storage value to query.
234    ///
235    /// # Returns
236    ///
237    /// Returns a `Result` containing the value from storage at the specified index as an `U256`,
238    /// or an error of type `SimulationDB<M>::Error` if the query fails.
239    pub fn query_storage(
240        &self,
241        address: Address,
242        index: U256,
243    ) -> Result<StorageValue, <SimulationDB<P> as DatabaseRef>::Error> {
244        let mut request = self
245            .client
246            .get_storage_at(address, index);
247        if let Some(block) = &self.block {
248            request = request.number(block.number);
249        }
250
251        let storage_future = async move {
252            request.await.map_err(|err| {
253                SimulationDBError::SimulationError(format!(
254                    "Failed to fetch storage for {address:?} slot {index}: {err}"
255                ))
256            })
257        };
258
259        self.block_on(storage_future)
260    }
261
262    fn read_account_storage(
263        &self,
264    ) -> Result<RwLockReadGuard<'_, AccountStorage>, SimulationDBError> {
265        self.account_storage
266            .read()
267            .map_err(|_poisoned| {
268                SimulationDBError::Internal("Account storage read lock poisoned".to_string())
269            })
270    }
271
272    fn write_account_storage(
273        &self,
274    ) -> Result<RwLockWriteGuard<'_, AccountStorage>, SimulationDBError> {
275        self.account_storage
276            .write()
277            .map_err(|_poisoned| {
278                SimulationDBError::Internal("Account storage write lock poisoned".to_string())
279            })
280    }
281
282    fn block_on<F: core::future::Future>(&self, f: F) -> F::Output {
283        // If we get here and have to block the current thread, we really
284        // messed up indexing / filling the storage. In that case this will save us
285        // at the price of a very high time penalty.
286        match &self.runtime {
287            Some(runtime) => runtime.block_on(f),
288            None => futures::executor::block_on(f),
289        }
290    }
291}
292
293impl<P: Provider + Debug> EngineDatabaseInterface for SimulationDB<P>
294where
295    P: Provider + Send + Sync + 'static,
296{
297    type Error = SimulationDBError;
298
299    /// Sets up a single account
300    ///
301    /// Full control over setting up an accounts. Allows to set up EOAs as
302    /// well as smart contracts.
303    ///
304    /// # Arguments
305    ///
306    /// * `address` - Address of the account
307    /// * `account` - The account information
308    /// * `permanent_storage` - Storage to init the account with this storage can only be updated
309    ///   manually.
310    /// * `mocked` - Whether this account should be considered mocked. For mocked accounts, nothing
311    ///   is downloaded from a node; all data must be inserted manually.
312    fn init_account(
313        &self,
314        address: Address,
315        mut account: AccountInfo,
316        permanent_storage: Option<HashMap<U256, U256>>,
317        mocked: bool,
318    ) -> Result<(), <Self as EngineDatabaseInterface>::Error> {
319        if let Some(code) = account.code.clone() {
320            account.code = Some(code);
321        }
322
323        self.write_account_storage()?
324            .init_account(address, account, permanent_storage, mocked);
325
326        Ok(())
327    }
328
329    /// Clears temp storage
330    ///
331    /// It is recommended to call this after a new block is received,
332    /// to avoid stored state leading to wrong results.
333    fn clear_temp_storage(&mut self) -> Result<(), <Self as EngineDatabaseInterface>::Error> {
334        self.write_account_storage()?
335            .clear_temp_storage();
336
337        Ok(())
338    }
339
340    fn get_current_block(&self) -> Option<BlockHeader> {
341        self.block.clone()
342    }
343}
344
345#[derive(Error, Debug)]
346pub enum SimulationDBError {
347    #[error("Simulation error: {0} ")]
348    SimulationError(String),
349    #[error("Not implemented error: {0}")]
350    NotImplementedError(String),
351    #[error("Simulation DB internal error: {0}")]
352    Internal(String),
353}
354
355impl DBErrorMarker for SimulationDBError {}
356
357impl From<RpcError<TransportErrorKind>> for SimulationDBError {
358    fn from(err: RpcError<TransportErrorKind>) -> Self {
359        SimulationDBError::SimulationError(err.to_string())
360    }
361}
362
363impl<P: Provider> DatabaseRef for SimulationDB<P>
364where
365    P: Provider + Debug + Send + Sync + 'static,
366{
367    type Error = SimulationDBError;
368
369    /// Retrieves basic information about an account.
370    ///
371    /// This function retrieves the basic account information for the specified address.
372    /// If the account is present in the storage, the stored account information is returned.
373    /// If the account is not present in the storage, the function queries the account information
374    /// from the contract and initializes the account in the storage with the retrieved
375    /// information.
376    ///
377    /// # Arguments
378    ///
379    /// * `address`: The address of the account to retrieve the information for.
380    ///
381    /// # Returns
382    ///
383    /// Returns a `Result` containing an `Option` that holds the account information if it exists.
384    /// If the account is not found, `None` is returned.
385    ///
386    /// # Errors
387    ///
388    /// Returns an error if there was an issue querying the account information from the contract or
389    /// accessing the storage.
390    ///
391    /// # Notes
392    ///
393    /// * If the account is present in the storage, the function returns a clone of the stored
394    ///   account information.
395    ///
396    /// * If the account is not present in the storage, the function queries the account information
397    ///   from the contract, initializes the account in the storage with the retrieved information,
398    ///   and returns a clone of the account information.
399    fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
400        // A separate statement, so the read lock is released before `init_account` writes.
401        let stored = self
402            .read_account_storage()?
403            .get_account_info(&address)
404            .cloned();
405        if let Some(account) = stored {
406            return Ok(Some(account));
407        }
408        let account_info = self.query_account_info(address)?;
409        self.init_account(address, account_info.clone(), None, false)?;
410        Ok(Some(account_info))
411    }
412
413    fn code_by_hash_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> {
414        Err(SimulationDBError::NotImplementedError(
415            "Code by hash is not implemented in SimulationDB".to_string(),
416        ))
417    }
418
419    /// Retrieves the storage value at the specified address and index.
420    ///
421    /// If we don't know the value, and the accessed contract is mocked, the function returns
422    /// an empty slot instead of querying a node, to avoid potentially returning garbage values.
423    ///
424    /// # Arguments
425    ///
426    /// * `address`: The address of the contract to retrieve the storage value from.
427    /// * `index`: The index of the storage value to retrieve.
428    ///
429    /// # Returns
430    ///
431    /// Returns a `Result` containing the storage value if it exists. If the contract is mocked
432    /// and the storage value is not found locally, an empty slot is returned as `U256::ZERO`.
433    ///
434    /// # Errors
435    ///
436    /// Returns an error if there was an issue querying the storage value from the contract or
437    /// accessing the storage.
438    ///
439    /// # Notes
440    ///
441    /// * If the contract is present locally and is mocked, the function first checks if the storage
442    ///   value exists locally. If found, it returns the stored value. If not found, it returns an
443    ///   empty slot. Mocked contracts are not expected to have valid storage values, so the
444    ///   function does not query a node in this case.
445    ///
446    /// * If the contract is present locally and is not mocked, the function checks if the storage
447    ///   value exists locally. If found, it returns the stored value. If not found, it queries the
448    ///   storage value from a node, stores it locally, and returns it.
449    ///
450    /// * If the contract is not present locally, the function queries the account info and storage
451    ///   value from a node, initializes the account locally with the retrieved information, and
452    ///   returns the storage value.
453    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
454        debug!("Requested storage of account {:x?} slot {}", address, index);
455        let (is_mocked, local_value) = {
456            let account_storage = self.read_account_storage()?;
457            (
458                account_storage.is_mocked_account(&address),
459                account_storage.get_storage(&address, &index),
460            )
461        };
462
463        if let Some(storage_value) = local_value {
464            debug!(
465                "Got value locally. This is a {} account. Value: {}",
466                if is_mocked.unwrap_or(false) { "mocked" } else { "non-mocked" },
467                storage_value
468            );
469            return Ok(storage_value);
470        }
471
472        // At this point we know we don't have data for this storage slot.
473        match is_mocked {
474            Some(true) => {
475                debug!("This is a mocked account for which we don't have data. Returning zero.");
476                Ok(U256::ZERO)
477            }
478            Some(false) => {
479                let storage_value = self.query_storage(address, index)?;
480                self.write_account_storage()?
481                    .set_temp_storage(address, index, storage_value);
482                debug!(
483                    "This is a non-mocked account for which we didn't have data. Fetched value: {}",
484                    storage_value
485                );
486                Ok(storage_value)
487            }
488            None => {
489                let account_info = self.query_account_info(address)?;
490                let storage_value = self.query_storage(address, index)?;
491                self.init_account(address, account_info, None, false)?;
492                self.write_account_storage()?
493                    .set_temp_storage(address, index, storage_value);
494                debug!("This is non-initialised account. Fetched value: {}", storage_value);
495                Ok(storage_value)
496            }
497        }
498    }
499
500    /// If block header is set, returns the hash. Otherwise returns a zero hash
501    /// instead of querying a node.
502    fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
503        match &self.block {
504            Some(header) => Ok(B256::from_slice(&header.hash)),
505            None => Ok(B256::ZERO),
506        }
507    }
508}
509
510#[cfg(test)]
511mod tests {
512    use std::str::FromStr;
513
514    use alloy::primitives::U160;
515    use rstest::rstest;
516    use tycho_common::Bytes;
517
518    use super::*;
519    use crate::evm::engine_db::utils::{get_client, get_runtime};
520
521    #[rstest]
522    fn test_query_storage_latest_block() {
523        let db = SimulationDB::new(
524            get_client(None).expect("Failed to create test client"),
525            get_runtime().expect("Failed to create test runtime"),
526            None,
527        );
528        let address =
529            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").expect("valid address");
530        let index = U256::from_limbs_slice(&[8]);
531        db.init_account(address, AccountInfo::default(), None, false)
532            .expect("Failed to init account");
533
534        db.query_storage(address, index)
535            .unwrap();
536
537        // There is no assertion, but has the querying failed, we would have panicked by now.
538        // This test is not deterministic as it depends on the current state of the blockchain.
539        // See the next test where we do this for a specific block.
540    }
541
542    #[rstest]
543    fn test_query_account_info() {
544        let mut db = SimulationDB::new(
545            get_client(None).expect("Failed to create test client"),
546            get_runtime().expect("Failed to create test runtime"),
547            None,
548        );
549        let block = BlockHeader {
550            number: 20308186,
551            hash: Bytes::from_str(
552                "0x61c51e3640b02ae58a03201be0271e84e02dac8a4826501995cbe4da24174b52",
553            )
554            .unwrap(),
555            timestamp: 234,
556            ..Default::default()
557        };
558        db.set_block(Some(block));
559        let address = Address::from_str("0x168b93113fe5902c87afaecE348581A1481d0f93").unwrap();
560        db.init_account(address, AccountInfo::default(), None, false)
561            .expect("Failed to init account");
562
563        let account_info = db.query_account_info(address).unwrap();
564
565        assert_eq!(account_info.balance, U256::from_str("6246978663692389").unwrap());
566        assert_eq!(account_info.nonce, 17);
567    }
568
569    #[rstest]
570    fn test_mock_account_get_acc_info() {
571        let db = SimulationDB::new(
572            get_client(None).expect("Failed to create test client"),
573            get_runtime().expect("Failed to create test runtime"),
574            None,
575        );
576        let mock_acc_address =
577            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
578        db.init_account(mock_acc_address, AccountInfo::default(), None, true)
579            .expect("Failed to init account");
580
581        let acc_info = db
582            .basic_ref(mock_acc_address)
583            .unwrap()
584            .unwrap();
585
586        assert_eq!(
587            db.account_storage
588                .read()
589                .unwrap()
590                .get_account_info(&mock_acc_address)
591                .unwrap(),
592            &acc_info
593        );
594    }
595
596    #[rstest]
597    fn test_mock_account_get_storage() {
598        let db = SimulationDB::new(
599            get_client(None).expect("Failed to create test client"),
600            get_runtime().expect("Failed to create test runtime"),
601            None,
602        );
603        let mock_acc_address =
604            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
605        let storage_address = U256::ZERO;
606        db.init_account(mock_acc_address, AccountInfo::default(), None, true)
607            .expect("Failed to init account");
608
609        let storage = db
610            .storage_ref(mock_acc_address, storage_address)
611            .unwrap();
612
613        assert_eq!(storage, U256::ZERO);
614    }
615
616    #[rstest]
617    fn test_update_state() {
618        let mut db = SimulationDB::new(
619            get_client(None).expect("Failed to create test client"),
620            get_runtime().expect("Failed to create test runtime"),
621            None,
622        );
623        let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
624        db.init_account(address, AccountInfo::default(), None, false)
625            .expect("Failed to init account");
626
627        let mut new_storage = HashMap::default();
628        let new_storage_value_index = U256::from_limbs_slice(&[123]);
629        new_storage.insert(new_storage_value_index, new_storage_value_index);
630        let new_balance = U256::from_limbs_slice(&[500]);
631        let update = StateUpdate { storage: Some(new_storage), balance: Some(new_balance) };
632        let mut updates = HashMap::default();
633        updates.insert(address, update);
634        let new_block = BlockHeader { number: 1, timestamp: 234, ..Default::default() };
635
636        let reverse_update = db
637            .update_state(&updates, new_block)
638            .expect("State update should succeed");
639
640        assert_eq!(
641            db.account_storage
642                .read()
643                .expect("Storage entry should exist")
644                .get_storage(&address, &new_storage_value_index)
645                .unwrap(),
646            new_storage_value_index
647        );
648        assert_eq!(
649            db.account_storage
650                .read()
651                .unwrap()
652                .get_account_info(&address)
653                .unwrap()
654                .balance,
655            new_balance
656        );
657        assert_eq!(db.block.unwrap().number, 1);
658
659        assert_eq!(
660            reverse_update
661                .get(&address)
662                .unwrap()
663                .balance
664                .unwrap(),
665            AccountInfo::default().balance
666        );
667        assert_eq!(
668            reverse_update
669                .get(&address)
670                .unwrap()
671                .storage,
672            Some(HashMap::default())
673        );
674    }
675
676    #[rstest]
677    fn test_overridden_db() {
678        let db = SimulationDB::new(
679            get_client(None).expect("Failed to create test client"),
680            get_runtime().expect("Failed to create test runtime"),
681            None,
682        );
683        let slot1 = U256::from_limbs_slice(&[1]);
684        let slot2 = U256::from_limbs_slice(&[2]);
685        let orig_value1 = U256::from_limbs_slice(&[100]);
686        let orig_value2 = U256::from_limbs_slice(&[200]);
687        let original_storage: HashMap<U256, U256> = [(slot1, orig_value1), (slot2, orig_value2)]
688            .iter()
689            .cloned()
690            .collect();
691
692        let address1 = Address::from(U160::from(1));
693        let address2 = Address::from(U160::from(2));
694        let address3 = Address::from(U160::from(3));
695
696        // override slot 1 of address 2
697        // and slot 1 of address 3 which doesn't exist in the original DB
698        db.init_account(address1, AccountInfo::default(), Some(original_storage.clone()), false)
699            .expect("Failed to init account");
700        db.init_account(address2, AccountInfo::default(), Some(original_storage), false)
701            .expect("Failed to init account");
702
703        let overridden_value1 = U256::from_limbs_slice(&[101]);
704        let mut overrides: HashMap<Address, HashMap<U256, U256>> = HashMap::new();
705        overrides.insert(
706            address2,
707            [(slot1, overridden_value1)]
708                .iter()
709                .cloned()
710                .collect(),
711        );
712        overrides.insert(
713            address3,
714            [(slot1, overridden_value1)]
715                .iter()
716                .cloned()
717                .collect(),
718        );
719
720        let native_balance_overrides = HashMap::new();
721        let overriden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
722
723        assert_eq!(
724            overriden_db
725                .storage_ref(address1, slot1)
726                .expect("Value should be available"),
727            orig_value1,
728            "Slots of non-overridden account should hold original values."
729        );
730
731        assert_eq!(
732            overriden_db
733                .storage_ref(address1, slot2)
734                .expect("Value should be available"),
735            orig_value2,
736            "Slots of non-overridden account should hold original values."
737        );
738
739        assert_eq!(
740            overriden_db
741                .storage_ref(address2, slot1)
742                .expect("Value should be available"),
743            overridden_value1,
744            "Overridden slot of overridden account should hold an overridden value."
745        );
746
747        assert_eq!(
748            overriden_db
749                .storage_ref(address2, slot2)
750                .expect("Value should be available"),
751            orig_value2,
752            "Non-overridden slot of an account with other slots overridden \
753            should hold an original value."
754        );
755
756        assert_eq!(
757            overriden_db
758                .storage_ref(address3, slot1)
759                .expect("Value should be available"),
760            overridden_value1,
761            "Overridden slot of an overridden non-existent account should hold an overriden value."
762        );
763    }
764
765    #[derive(Debug, Default)]
766    struct StaticDB {
767        accounts: HashMap<Address, AccountInfo>,
768        fail_basic_ref: bool,
769    }
770
771    impl DatabaseRef for StaticDB {
772        type Error = SimulationDBError;
773
774        fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
775            if self.fail_basic_ref {
776                return Err(SimulationDBError::Internal("account unavailable".to_string()));
777            }
778            Ok(self.accounts.get(&address).cloned())
779        }
780
781        fn code_by_hash_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> {
782            Ok(Bytecode::default())
783        }
784
785        fn storage_ref(&self, _address: Address, _index: U256) -> Result<U256, Self::Error> {
786            Ok(U256::ZERO)
787        }
788
789        fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
790            Ok(B256::ZERO)
791        }
792    }
793
794    #[rstest]
795    fn test_balance_override_known_account() {
796        let address = Address::from(U160::from(1));
797        let bytecode = Bytecode::new_raw(AlloyBytes::from_static(&[0x00]));
798        let account = AccountInfo::new(U256::from(100), 7, bytecode.hash_slow(), bytecode.clone());
799        let db = StaticDB { accounts: HashMap::from([(address, account)]), ..Default::default() };
800        let overrides = HashMap::new();
801        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
802        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
803
804        let info = overridden_db
805            .basic_ref(address)
806            .expect("basic_ref should succeed")
807            .expect("account should exist");
808
809        assert_eq!(info.balance, U256::from(999), "Overridden balance should be returned.");
810        assert_eq!(info.nonce, 7, "Other account fields should be preserved.");
811        assert_eq!(info.code, Some(bytecode), "Contract code should be preserved.");
812    }
813
814    #[rstest]
815    fn test_balance_override_unknown_account() {
816        let address = Address::from(U160::from(1));
817        let db = StaticDB::default();
818        let overrides = HashMap::new();
819        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
820        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
821
822        let info = overridden_db
823            .basic_ref(address)
824            .expect("basic_ref should succeed")
825            .expect("overridden unknown account should be synthesized");
826
827        assert_eq!(
828            info,
829            AccountInfo { balance: U256::from(999), ..Default::default() },
830            "Unknown account should be synthesized as an EOA with the overridden balance."
831        );
832    }
833
834    #[rstest]
835    fn test_balance_override_materializes_account_when_inner_db_errors() {
836        let address = Address::from(U160::from(1));
837        let db = StaticDB { fail_basic_ref: true, ..Default::default() };
838        let overrides = HashMap::new();
839        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
840        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
841
842        let info = overridden_db
843            .basic_ref(address)
844            .expect("balance override should shield an inner account miss")
845            .expect("overridden account should be synthesized");
846
847        assert_eq!(info, AccountInfo { balance: U256::from(999), ..Default::default() });
848    }
849
850    #[rstest]
851    fn test_missing_balance_override_propagates_inner_error() {
852        let address = Address::from(U160::from(1));
853        let db = StaticDB { fail_basic_ref: true, ..Default::default() };
854        let overrides = HashMap::new();
855        let native_balance_overrides = HashMap::new();
856        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
857
858        let result = overridden_db.basic_ref(address);
859
860        match result {
861            Err(SimulationDBError::Internal(message)) => {
862                assert_eq!(message, "account unavailable")
863            }
864            other => panic!("expected inner database error, got {other:?}"),
865        }
866    }
867
868    #[rstest]
869    fn test_balance_override_absent_passthrough() {
870        let address = Address::from(U160::from(1));
871        let unknown_address = Address::from(U160::from(2));
872        let account = AccountInfo { balance: U256::from(100), nonce: 7, ..Default::default() };
873        let db = StaticDB {
874            accounts: HashMap::from([(address, account.clone())]),
875            ..Default::default()
876        };
877        let overrides = HashMap::new();
878        let native_balance_overrides = HashMap::new();
879        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
880
881        assert_eq!(
882            overridden_db
883                .basic_ref(address)
884                .expect("basic_ref should succeed"),
885            Some(account),
886            "Known account without override should pass through unchanged."
887        );
888        assert_eq!(
889            overridden_db
890                .basic_ref(unknown_address)
891                .expect("basic_ref should succeed"),
892            None,
893            "Unknown account without override should stay absent."
894        );
895    }
896}