foundry_evm_core/
env.rs

1pub use alloy_evm::EvmEnv;
2use revm::{
3    context::{BlockEnv, CfgEnv, JournalInner, JournalTr, TxEnv},
4    primitives::hardfork::SpecId,
5    Context, Database, Journal, JournalEntry,
6};
7
8/// Helper container type for [`EvmEnv`] and [`TxEnv`].
9#[derive(Clone, Debug, Default)]
10pub struct Env {
11    pub evm_env: EvmEnv,
12    pub tx: TxEnv,
13}
14
15/// Helper container type for [`EvmEnv`] and [`TxEnv`].
16impl Env {
17    pub fn default_with_spec_id(spec_id: SpecId) -> Self {
18        let mut cfg = CfgEnv::default();
19        cfg.spec = spec_id;
20
21        Self::from(cfg, BlockEnv::default(), TxEnv::default())
22    }
23
24    pub fn from(cfg: CfgEnv, block: BlockEnv, tx: TxEnv) -> Self {
25        Self { evm_env: EvmEnv { cfg_env: cfg, block_env: block }, tx }
26    }
27
28    pub fn new_with_spec_id(cfg: CfgEnv, block: BlockEnv, tx: TxEnv, spec_id: SpecId) -> Self {
29        let mut cfg = cfg;
30        cfg.spec = spec_id;
31
32        Self::from(cfg, block, tx)
33    }
34}
35
36/// Helper struct with mutable references to the block and cfg environments.
37pub struct EnvMut<'a> {
38    pub block: &'a mut BlockEnv,
39    pub cfg: &'a mut CfgEnv,
40    pub tx: &'a mut TxEnv,
41}
42
43impl EnvMut<'_> {
44    /// Returns a copy of the environment.
45    pub fn to_owned(&self) -> Env {
46        Env {
47            evm_env: EvmEnv { cfg_env: self.cfg.to_owned(), block_env: self.block.to_owned() },
48            tx: self.tx.to_owned(),
49        }
50    }
51}
52
53pub trait AsEnvMut {
54    fn as_env_mut(&mut self) -> EnvMut<'_>;
55}
56
57impl AsEnvMut for EnvMut<'_> {
58    fn as_env_mut(&mut self) -> EnvMut<'_> {
59        EnvMut { block: self.block, cfg: self.cfg, tx: self.tx }
60    }
61}
62
63impl AsEnvMut for Env {
64    fn as_env_mut(&mut self) -> EnvMut<'_> {
65        EnvMut {
66            block: &mut self.evm_env.block_env,
67            cfg: &mut self.evm_env.cfg_env,
68            tx: &mut self.tx,
69        }
70    }
71}
72
73impl<DB: Database, J: JournalTr<Database = DB>, C> AsEnvMut
74    for Context<BlockEnv, TxEnv, CfgEnv, DB, J, C>
75{
76    fn as_env_mut(&mut self) -> EnvMut<'_> {
77        EnvMut { block: &mut self.block, cfg: &mut self.cfg, tx: &mut self.tx }
78    }
79}
80
81pub trait ContextExt {
82    type DB: Database;
83
84    fn as_db_env_and_journal(
85        &mut self,
86    ) -> (&mut Self::DB, &mut JournalInner<JournalEntry>, EnvMut<'_>);
87}
88
89impl<DB: Database, C> ContextExt
90    for Context<BlockEnv, TxEnv, CfgEnv, DB, Journal<DB, JournalEntry>, C>
91{
92    type DB = DB;
93
94    fn as_db_env_and_journal(
95        &mut self,
96    ) -> (&mut Self::DB, &mut JournalInner<JournalEntry>, EnvMut<'_>) {
97        (
98            &mut self.journaled_state.database,
99            &mut self.journaled_state.inner,
100            EnvMut { block: &mut self.block, cfg: &mut self.cfg, tx: &mut self.tx },
101        )
102    }
103}