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        if let Some(account) = {
401            self.read_account_storage()?
402                .get_account_info(&address)
403                .cloned()
404        } {
405            return Ok(Some(account));
406        }
407        let account_info = self.query_account_info(address)?;
408        self.init_account(address, account_info.clone(), None, false)?;
409        Ok(Some(account_info))
410    }
411
412    fn code_by_hash_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> {
413        Err(SimulationDBError::NotImplementedError(
414            "Code by hash is not implemented in SimulationDB".to_string(),
415        ))
416    }
417
418    /// Retrieves the storage value at the specified address and index.
419    ///
420    /// If we don't know the value, and the accessed contract is mocked, the function returns
421    /// an empty slot instead of querying a node, to avoid potentially returning garbage values.
422    ///
423    /// # Arguments
424    ///
425    /// * `address`: The address of the contract to retrieve the storage value from.
426    /// * `index`: The index of the storage value to retrieve.
427    ///
428    /// # Returns
429    ///
430    /// Returns a `Result` containing the storage value if it exists. If the contract is mocked
431    /// and the storage value is not found locally, an empty slot is returned as `U256::ZERO`.
432    ///
433    /// # Errors
434    ///
435    /// Returns an error if there was an issue querying the storage value from the contract or
436    /// accessing the storage.
437    ///
438    /// # Notes
439    ///
440    /// * If the contract is present locally and is mocked, the function first checks if the storage
441    ///   value exists locally. If found, it returns the stored value. If not found, it returns an
442    ///   empty slot. Mocked contracts are not expected to have valid storage values, so the
443    ///   function does not query a node in this case.
444    ///
445    /// * If the contract is present locally and is not mocked, the function checks if the storage
446    ///   value exists locally. If found, it returns the stored value. If not found, it queries the
447    ///   storage value from a node, stores it locally, and returns it.
448    ///
449    /// * If the contract is not present locally, the function queries the account info and storage
450    ///   value from a node, initializes the account locally with the retrieved information, and
451    ///   returns the storage value.
452    fn storage_ref(&self, address: Address, index: U256) -> Result<U256, Self::Error> {
453        debug!("Requested storage of account {:x?} slot {}", address, index);
454        let (is_mocked, local_value) = {
455            let account_storage = self.read_account_storage()?;
456            (
457                account_storage.is_mocked_account(&address),
458                account_storage.get_storage(&address, &index),
459            )
460        };
461
462        if let Some(storage_value) = local_value {
463            debug!(
464                "Got value locally. This is a {} account. Value: {}",
465                if is_mocked.unwrap_or(false) { "mocked" } else { "non-mocked" },
466                storage_value
467            );
468            return Ok(storage_value);
469        }
470
471        // At this point we know we don't have data for this storage slot.
472        match is_mocked {
473            Some(true) => {
474                debug!("This is a mocked account for which we don't have data. Returning zero.");
475                Ok(U256::ZERO)
476            }
477            Some(false) => {
478                let storage_value = self.query_storage(address, index)?;
479                self.write_account_storage()?
480                    .set_temp_storage(address, index, storage_value);
481                debug!(
482                    "This is a non-mocked account for which we didn't have data. Fetched value: {}",
483                    storage_value
484                );
485                Ok(storage_value)
486            }
487            None => {
488                let account_info = self.query_account_info(address)?;
489                let storage_value = self.query_storage(address, index)?;
490                self.init_account(address, account_info, None, false)?;
491                self.write_account_storage()?
492                    .set_temp_storage(address, index, storage_value);
493                debug!("This is non-initialised account. Fetched value: {}", storage_value);
494                Ok(storage_value)
495            }
496        }
497    }
498
499    /// If block header is set, returns the hash. Otherwise returns a zero hash
500    /// instead of querying a node.
501    fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
502        match &self.block {
503            Some(header) => Ok(B256::from_slice(&header.hash)),
504            None => Ok(B256::ZERO),
505        }
506    }
507}
508
509#[cfg(test)]
510mod tests {
511    use std::str::FromStr;
512
513    use alloy::primitives::U160;
514    use rstest::rstest;
515    use tycho_common::Bytes;
516
517    use super::*;
518    use crate::evm::engine_db::utils::{get_client, get_runtime};
519
520    #[rstest]
521    fn test_query_storage_latest_block() {
522        let db = SimulationDB::new(
523            get_client(None).expect("Failed to create test client"),
524            get_runtime().expect("Failed to create test runtime"),
525            None,
526        );
527        let address =
528            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").expect("valid address");
529        let index = U256::from_limbs_slice(&[8]);
530        db.init_account(address, AccountInfo::default(), None, false)
531            .expect("Failed to init account");
532
533        db.query_storage(address, index)
534            .unwrap();
535
536        // There is no assertion, but has the querying failed, we would have panicked by now.
537        // This test is not deterministic as it depends on the current state of the blockchain.
538        // See the next test where we do this for a specific block.
539    }
540
541    #[rstest]
542    fn test_query_account_info() {
543        let mut db = SimulationDB::new(
544            get_client(None).expect("Failed to create test client"),
545            get_runtime().expect("Failed to create test runtime"),
546            None,
547        );
548        let block = BlockHeader {
549            number: 20308186,
550            hash: Bytes::from_str(
551                "0x61c51e3640b02ae58a03201be0271e84e02dac8a4826501995cbe4da24174b52",
552            )
553            .unwrap(),
554            timestamp: 234,
555            ..Default::default()
556        };
557        db.set_block(Some(block));
558        let address = Address::from_str("0x168b93113fe5902c87afaecE348581A1481d0f93").unwrap();
559        db.init_account(address, AccountInfo::default(), None, false)
560            .expect("Failed to init account");
561
562        let account_info = db.query_account_info(address).unwrap();
563
564        assert_eq!(account_info.balance, U256::from_str("6246978663692389").unwrap());
565        assert_eq!(account_info.nonce, 17);
566    }
567
568    #[rstest]
569    fn test_mock_account_get_acc_info() {
570        let db = SimulationDB::new(
571            get_client(None).expect("Failed to create test client"),
572            get_runtime().expect("Failed to create test runtime"),
573            None,
574        );
575        let mock_acc_address =
576            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
577        db.init_account(mock_acc_address, AccountInfo::default(), None, true)
578            .expect("Failed to init account");
579
580        let acc_info = db
581            .basic_ref(mock_acc_address)
582            .unwrap()
583            .unwrap();
584
585        assert_eq!(
586            db.account_storage
587                .read()
588                .unwrap()
589                .get_account_info(&mock_acc_address)
590                .unwrap(),
591            &acc_info
592        );
593    }
594
595    #[rstest]
596    fn test_mock_account_get_storage() {
597        let db = SimulationDB::new(
598            get_client(None).expect("Failed to create test client"),
599            get_runtime().expect("Failed to create test runtime"),
600            None,
601        );
602        let mock_acc_address =
603            Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
604        let storage_address = U256::ZERO;
605        db.init_account(mock_acc_address, AccountInfo::default(), None, true)
606            .expect("Failed to init account");
607
608        let storage = db
609            .storage_ref(mock_acc_address, storage_address)
610            .unwrap();
611
612        assert_eq!(storage, U256::ZERO);
613    }
614
615    #[rstest]
616    fn test_update_state() {
617        let mut db = SimulationDB::new(
618            get_client(None).expect("Failed to create test client"),
619            get_runtime().expect("Failed to create test runtime"),
620            None,
621        );
622        let address = Address::from_str("0xb4e16d0168e52d35cacd2c6185b44281ec28c9dc").unwrap();
623        db.init_account(address, AccountInfo::default(), None, false)
624            .expect("Failed to init account");
625
626        let mut new_storage = HashMap::default();
627        let new_storage_value_index = U256::from_limbs_slice(&[123]);
628        new_storage.insert(new_storage_value_index, new_storage_value_index);
629        let new_balance = U256::from_limbs_slice(&[500]);
630        let update = StateUpdate { storage: Some(new_storage), balance: Some(new_balance) };
631        let mut updates = HashMap::default();
632        updates.insert(address, update);
633        let new_block = BlockHeader { number: 1, timestamp: 234, ..Default::default() };
634
635        let reverse_update = db
636            .update_state(&updates, new_block)
637            .expect("State update should succeed");
638
639        assert_eq!(
640            db.account_storage
641                .read()
642                .expect("Storage entry should exist")
643                .get_storage(&address, &new_storage_value_index)
644                .unwrap(),
645            new_storage_value_index
646        );
647        assert_eq!(
648            db.account_storage
649                .read()
650                .unwrap()
651                .get_account_info(&address)
652                .unwrap()
653                .balance,
654            new_balance
655        );
656        assert_eq!(db.block.unwrap().number, 1);
657
658        assert_eq!(
659            reverse_update
660                .get(&address)
661                .unwrap()
662                .balance
663                .unwrap(),
664            AccountInfo::default().balance
665        );
666        assert_eq!(
667            reverse_update
668                .get(&address)
669                .unwrap()
670                .storage,
671            Some(HashMap::default())
672        );
673    }
674
675    #[rstest]
676    fn test_overridden_db() {
677        let db = SimulationDB::new(
678            get_client(None).expect("Failed to create test client"),
679            get_runtime().expect("Failed to create test runtime"),
680            None,
681        );
682        let slot1 = U256::from_limbs_slice(&[1]);
683        let slot2 = U256::from_limbs_slice(&[2]);
684        let orig_value1 = U256::from_limbs_slice(&[100]);
685        let orig_value2 = U256::from_limbs_slice(&[200]);
686        let original_storage: HashMap<U256, U256> = [(slot1, orig_value1), (slot2, orig_value2)]
687            .iter()
688            .cloned()
689            .collect();
690
691        let address1 = Address::from(U160::from(1));
692        let address2 = Address::from(U160::from(2));
693        let address3 = Address::from(U160::from(3));
694
695        // override slot 1 of address 2
696        // and slot 1 of address 3 which doesn't exist in the original DB
697        db.init_account(address1, AccountInfo::default(), Some(original_storage.clone()), false)
698            .expect("Failed to init account");
699        db.init_account(address2, AccountInfo::default(), Some(original_storage), false)
700            .expect("Failed to init account");
701
702        let overridden_value1 = U256::from_limbs_slice(&[101]);
703        let mut overrides: HashMap<Address, HashMap<U256, U256>> = HashMap::new();
704        overrides.insert(
705            address2,
706            [(slot1, overridden_value1)]
707                .iter()
708                .cloned()
709                .collect(),
710        );
711        overrides.insert(
712            address3,
713            [(slot1, overridden_value1)]
714                .iter()
715                .cloned()
716                .collect(),
717        );
718
719        let native_balance_overrides = HashMap::new();
720        let overriden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
721
722        assert_eq!(
723            overriden_db
724                .storage_ref(address1, slot1)
725                .expect("Value should be available"),
726            orig_value1,
727            "Slots of non-overridden account should hold original values."
728        );
729
730        assert_eq!(
731            overriden_db
732                .storage_ref(address1, slot2)
733                .expect("Value should be available"),
734            orig_value2,
735            "Slots of non-overridden account should hold original values."
736        );
737
738        assert_eq!(
739            overriden_db
740                .storage_ref(address2, slot1)
741                .expect("Value should be available"),
742            overridden_value1,
743            "Overridden slot of overridden account should hold an overridden value."
744        );
745
746        assert_eq!(
747            overriden_db
748                .storage_ref(address2, slot2)
749                .expect("Value should be available"),
750            orig_value2,
751            "Non-overridden slot of an account with other slots overridden \
752            should hold an original value."
753        );
754
755        assert_eq!(
756            overriden_db
757                .storage_ref(address3, slot1)
758                .expect("Value should be available"),
759            overridden_value1,
760            "Overridden slot of an overridden non-existent account should hold an overriden value."
761        );
762    }
763
764    #[derive(Debug, Default)]
765    struct StaticDB {
766        accounts: HashMap<Address, AccountInfo>,
767        fail_basic_ref: bool,
768    }
769
770    impl DatabaseRef for StaticDB {
771        type Error = SimulationDBError;
772
773        fn basic_ref(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
774            if self.fail_basic_ref {
775                return Err(SimulationDBError::Internal("account unavailable".to_string()));
776            }
777            Ok(self.accounts.get(&address).cloned())
778        }
779
780        fn code_by_hash_ref(&self, _code_hash: B256) -> Result<Bytecode, Self::Error> {
781            Ok(Bytecode::default())
782        }
783
784        fn storage_ref(&self, _address: Address, _index: U256) -> Result<U256, Self::Error> {
785            Ok(U256::ZERO)
786        }
787
788        fn block_hash_ref(&self, _number: u64) -> Result<B256, Self::Error> {
789            Ok(B256::ZERO)
790        }
791    }
792
793    #[rstest]
794    fn test_balance_override_known_account() {
795        let address = Address::from(U160::from(1));
796        let bytecode = Bytecode::new_raw(AlloyBytes::from_static(&[0x00]));
797        let account = AccountInfo::new(U256::from(100), 7, bytecode.hash_slow(), bytecode.clone());
798        let db = StaticDB { accounts: HashMap::from([(address, account)]), ..Default::default() };
799        let overrides = HashMap::new();
800        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
801        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
802
803        let info = overridden_db
804            .basic_ref(address)
805            .expect("basic_ref should succeed")
806            .expect("account should exist");
807
808        assert_eq!(info.balance, U256::from(999), "Overridden balance should be returned.");
809        assert_eq!(info.nonce, 7, "Other account fields should be preserved.");
810        assert_eq!(info.code, Some(bytecode), "Contract code should be preserved.");
811    }
812
813    #[rstest]
814    fn test_balance_override_unknown_account() {
815        let address = Address::from(U160::from(1));
816        let db = StaticDB::default();
817        let overrides = HashMap::new();
818        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
819        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
820
821        let info = overridden_db
822            .basic_ref(address)
823            .expect("basic_ref should succeed")
824            .expect("overridden unknown account should be synthesized");
825
826        assert_eq!(
827            info,
828            AccountInfo { balance: U256::from(999), ..Default::default() },
829            "Unknown account should be synthesized as an EOA with the overridden balance."
830        );
831    }
832
833    #[rstest]
834    fn test_balance_override_materializes_account_when_inner_db_errors() {
835        let address = Address::from(U160::from(1));
836        let db = StaticDB { fail_basic_ref: true, ..Default::default() };
837        let overrides = HashMap::new();
838        let native_balance_overrides = HashMap::from([(address, U256::from(999))]);
839        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
840
841        let info = overridden_db
842            .basic_ref(address)
843            .expect("balance override should shield an inner account miss")
844            .expect("overridden account should be synthesized");
845
846        assert_eq!(info, AccountInfo { balance: U256::from(999), ..Default::default() });
847    }
848
849    #[rstest]
850    fn test_missing_balance_override_propagates_inner_error() {
851        let address = Address::from(U160::from(1));
852        let db = StaticDB { fail_basic_ref: true, ..Default::default() };
853        let overrides = HashMap::new();
854        let native_balance_overrides = HashMap::new();
855        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
856
857        let result = overridden_db.basic_ref(address);
858
859        match result {
860            Err(SimulationDBError::Internal(message)) => {
861                assert_eq!(message, "account unavailable")
862            }
863            other => panic!("expected inner database error, got {other:?}"),
864        }
865    }
866
867    #[rstest]
868    fn test_balance_override_absent_passthrough() {
869        let address = Address::from(U160::from(1));
870        let unknown_address = Address::from(U160::from(2));
871        let account = AccountInfo { balance: U256::from(100), nonce: 7, ..Default::default() };
872        let db = StaticDB {
873            accounts: HashMap::from([(address, account.clone())]),
874            ..Default::default()
875        };
876        let overrides = HashMap::new();
877        let native_balance_overrides = HashMap::new();
878        let overridden_db = OverriddenSimulationDB::new(&db, &overrides, &native_balance_overrides);
879
880        assert_eq!(
881            overridden_db
882                .basic_ref(address)
883                .expect("basic_ref should succeed"),
884            Some(account),
885            "Known account without override should pass through unchanged."
886        );
887        assert_eq!(
888            overridden_db
889                .basic_ref(unknown_address)
890                .expect("basic_ref should succeed"),
891            None,
892            "Unknown account without override should stay absent."
893        );
894    }
895}