example_database_components/
state.rs

1//! State database component from [`crate::Database`]
2
3use auto_impl::auto_impl;
4use core::ops::Deref;
5use revm::{
6    primitives::{Address, StorageKey, StorageValue, B256},
7    state::{AccountInfo, Bytecode},
8};
9use std::{error::Error as StdError, sync::Arc};
10
11#[auto_impl(&mut, Box)]
12pub trait State {
13    type Error: StdError;
14
15    /// Gets basic account information.
16    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;
17
18    /// Gets account code by its hash.
19    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error>;
20
21    /// Gets storage value of address at index.
22    fn storage(&mut self, address: Address, index: StorageKey)
23        -> Result<StorageValue, Self::Error>;
24}
25
26#[auto_impl(&, &mut, Box, Rc, Arc)]
27pub trait StateRef {
28    type Error: StdError;
29
30    /// Gets basic account information.
31    fn basic(&self, address: Address) -> Result<Option<AccountInfo>, Self::Error>;
32
33    /// Gets account code by its hash.
34    fn code_by_hash(&self, code_hash: B256) -> Result<Bytecode, Self::Error>;
35
36    /// Gets storage value of address at index.
37    fn storage(&self, address: Address, index: StorageKey) -> Result<StorageValue, Self::Error>;
38}
39
40impl<T> State for &T
41where
42    T: StateRef,
43{
44    type Error = <T as StateRef>::Error;
45
46    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
47        StateRef::basic(*self, address)
48    }
49
50    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
51        StateRef::code_by_hash(*self, code_hash)
52    }
53
54    fn storage(
55        &mut self,
56        address: Address,
57        index: StorageKey,
58    ) -> Result<StorageValue, Self::Error> {
59        StateRef::storage(*self, address, index)
60    }
61}
62
63impl<T> State for Arc<T>
64where
65    T: StateRef,
66{
67    type Error = <T as StateRef>::Error;
68
69    fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
70        self.deref().basic(address)
71    }
72
73    fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
74        self.deref().code_by_hash(code_hash)
75    }
76
77    fn storage(
78        &mut self,
79        address: Address,
80        index: StorageKey,
81    ) -> Result<StorageValue, Self::Error> {
82        self.deref().storage(address, index)
83    }
84}