Skip to main content

foundry_evm_core/evm/
monad.rs

1//! Monad on evm2, using `monad-evm2`.
2//!
3//! Ordinary transactions charge the full gas limit, including on revert. The runtime
4//! keeps that charge in `MonadTxResultExt::charged_gas`; evm2's gas consumption and
5//! calldata floor retain their ordinary meanings for simulations and isolated frames.
6//! Native reserve-balance enforcement remains opt-in, while tracking stays active.
7//! MIP-8 page warmth derives from native slot warmth, including cheatcode accesses.
8
9use super::{
10    EvmEnv, FoundryEvmExt, FoundryEvmFactory, FoundryEvmNetwork, FoundryExecutionHooks,
11    FoundryTxConversion, FoundryTxResultExt, SendableExt, TxPayload, eth_envelope_from_any_rpc,
12    eth_tx, eth_tx_from_request, with_eip7702_delegations,
13};
14use alloy_consensus::{TxLegacy, transaction::Recovered};
15use alloy_network::{AnyRpcTransaction, Ethereum};
16use alloy_primitives::{
17    Address,
18    map::{AddressMap, HashSet},
19};
20use alloy_rpc_types::TransactionRequest;
21use evm2::{
22    Evm, ExecutionConfig, TxResult, Version,
23    ethereum::TxEnvelope,
24    evm::{AccountInfo, precompile::PrecompileProvider},
25    registry::TxRegistry,
26};
27use monad_evm2::{
28    MonadChainContext, MonadEvmExt, MonadEvmFactory, MonadEvmTypes, MonadHardfork,
29    MonadPrecompiles, MonadTxResultExt, monad_memory_limit, monad_tx_registry, monad_version,
30    protocol_system_call,
31    reserve_balance::{rebase_reserve_balance_with_originals, sync_reserve_balance},
32    staking::constants::SYSTEM_ADDRESS,
33};
34
35/// Monad EVM network.
36#[derive(Clone, Copy, Debug, Default)]
37pub struct MonadEvmNetwork;
38
39// SAFETY: `MonadEvmExt` is `Send + Sync`, as asserted below, so clones share only thread-safe
40// state.
41unsafe impl SendableExt for MonadEvmExt {}
42
43const _: fn() = || {
44    const fn assert_send_sync<T: Send + Sync>() {}
45    assert_send_sync::<MonadEvmExt>();
46};
47
48impl FoundryEvmExt<TxEnvelope> for MonadEvmExt {
49    fn for_transaction(&mut self, tx: &Recovered<TxEnvelope>) {
50        // A synthetic transaction is alone in its block: its sender and EIP-7702 authorities are
51        // the only ones the reserve-balance rules may see.
52        self.for_block(&[], &[], std::slice::from_ref(tx), 0);
53    }
54
55    fn for_block(
56        &mut self,
57        grandparent: &[Recovered<TxEnvelope>],
58        parent: &[Recovered<TxEnvelope>],
59        current: &[Recovered<TxEnvelope>],
60        index: usize,
61    ) {
62        self.chain = MonadChainContext {
63            grandparent_senders_and_authorities: block_participants(grandparent),
64            parent_senders_and_authorities: block_participants(parent),
65            current_block_senders: current.iter().map(|tx| tx.signer()).collect(),
66            current_block_authorities: current.iter().map(authorities).collect(),
67            current_tx_index: index,
68            ..Default::default()
69        };
70        // Protocol replay is opted into per trusted transaction.
71        self.protocol_replay = false;
72    }
73
74    fn replace_while_executing(&mut self, ext: Self) {
75        // The pooled memory offset counts the memory of the suspended frames, which each release
76        // their share when they return.
77        let memory_pool_offset = self.memory_pool_offset;
78        *self = ext;
79        self.memory_pool_offset = memory_pool_offset;
80    }
81
82    fn is_protocol_transaction(tx: &Recovered<TxEnvelope>) -> bool {
83        matches!(protocol_system_call(tx), Ok(Some(_)))
84    }
85
86    fn set_protocol_replay(&mut self, enabled: bool) {
87        self.protocol_replay = enabled;
88    }
89
90    fn set_preserve_transaction_state(&mut self, preserve: bool) {
91        self.set_preserve_reserve_balance_tracker(preserve);
92    }
93
94    fn for_next_transaction(&mut self, tx: &Recovered<TxEnvelope>) {
95        // The retained cursor is the current block's prefix before `current_tx_index`; anything
96        // after it is a previous synthetic transaction's own entry, never canonical history.
97        let chain = &mut self.chain;
98        truncate_to_cursor(chain);
99        chain.current_block_senders.push(tx.signer());
100        chain.current_block_authorities.push(authorities(tx));
101        // Protocol replay is opted into per trusted transaction.
102        self.protocol_replay = false;
103    }
104
105    fn adopt_cursor(&mut self, cursor: &Self) {
106        let running = running_entry(&self.chain);
107        let mut chain = cursor.chain.clone();
108        truncate_to_cursor(&mut chain);
109        if let Some((sender, authorities)) = running {
110            chain.current_block_senders.push(sender);
111            chain.current_block_authorities.push(authorities);
112        }
113        self.chain = chain;
114    }
115
116    fn resume_context(&mut self, ext: Self) {
117        // A context only contributes its block cursor; the reserve-balance tracker, journal sync
118        // and memory pool belong to the running transaction.
119        self.adopt_cursor(&ext);
120    }
121}
122
123/// Drops entries after the retained cursor of the current block.
124fn truncate_to_cursor(chain: &mut MonadChainContext) {
125    chain.current_block_senders.truncate(chain.current_tx_index);
126    chain.current_block_authorities.truncate(chain.current_tx_index);
127}
128
129/// Returns the running transaction's own sender and authorities, if it is positioned.
130fn running_entry(chain: &MonadChainContext) -> Option<(Address, Vec<Address>)> {
131    let sender = *chain.current_block_senders.get(chain.current_tx_index)?;
132    let authorities =
133        chain.current_block_authorities.get(chain.current_tx_index).cloned().unwrap_or_default();
134    Some((sender, authorities))
135}
136
137/// Returns whether `tx`, attributed to the Monad system sender, is a canonical protocol system
138/// transaction, whatever its signature recovers to.
139pub fn is_protocol_system_legacy(tx: &TxLegacy) -> bool {
140    let tx = Recovered::new_unchecked(TxEnvelope::Legacy(tx.clone()), SYSTEM_ADDRESS);
141    matches!(protocol_system_call(&tx), Ok(Some(_)))
142}
143
144/// Returns the EIP-7702 authorities of `tx`.
145fn authorities(tx: &Recovered<TxEnvelope>) -> Vec<Address> {
146    tx.as_eip7702()
147        .map(|tx| tx.authorizations().filter_map(|auth| auth.authority()).collect())
148        .unwrap_or_default()
149}
150
151/// Returns every sender and EIP-7702 authority of a block's transactions.
152fn block_participants(transactions: &[Recovered<TxEnvelope>]) -> HashSet<Address> {
153    transactions.iter().flat_map(|tx| std::iter::once(tx.signer()).chain(authorities(tx))).collect()
154}
155
156impl FoundryTxResultExt for MonadTxResultExt {}
157
158impl FoundryEvmNetwork for MonadEvmNetwork {
159    type Network = Ethereum;
160    type EvmFactory = MonadEvmFactory;
161}
162
163impl FoundryTxConversion<Ethereum> for MonadEvmTypes {
164    fn evm_tx(
165        envelope: alloy_consensus::TxEnvelope,
166        sender: Address,
167        _payload: TxPayload,
168    ) -> eyre::Result<Recovered<TxEnvelope>> {
169        Ok(Recovered::new_unchecked(eth_tx(envelope), sender))
170    }
171
172    fn tx_from_request(request: TransactionRequest) -> eyre::Result<Recovered<TxEnvelope>> {
173        eth_tx_from_request(request)
174    }
175
176    fn envelope_from_any_rpc(tx: &AnyRpcTransaction) -> eyre::Result<alloy_consensus::TxEnvelope> {
177        eth_envelope_from_any_rpc(tx, "Monad")
178    }
179}
180
181impl FoundryEvmFactory for MonadEvmFactory {
182    type Types = MonadEvmTypes;
183
184    fn version(&self, spec: MonadHardfork, chain_id: u64) -> Version {
185        with_eip7702_delegations(monad_version(spec, chain_id))
186    }
187
188    fn execution_config(
189        &self,
190        spec: MonadHardfork,
191        mut version: Version,
192    ) -> ExecutionConfig<MonadEvmTypes> {
193        // MIP-3 caps the pooled memory limit from MonadNine on, including a larger configured one.
194        version.memory_limit = monad_memory_limit(spec, version.memory_limit);
195        ExecutionConfig::for_spec_and_version(spec, version)
196    }
197
198    fn tx_registry(
199        &self,
200        spec: MonadHardfork,
201    ) -> TxRegistry<MonadEvmTypes, TxResult<MonadEvmTypes>> {
202        monad_tx_registry(spec)
203    }
204
205    fn precompiles(
206        &self,
207        env: &EvmEnv<MonadEvmTypes>,
208        _ext: &MonadEvmExt,
209    ) -> Box<dyn PrecompileProvider<MonadEvmTypes>> {
210        Box::new(MonadPrecompiles::new(env.spec))
211    }
212}
213
214impl FoundryExecutionHooks for MonadEvmTypes {
215    fn sync_transaction(evm: &mut Evm<'_, Self>) {
216        // A database error surfaces again when execution next reads the account.
217        let _ = sync_reserve_balance(evm);
218    }
219
220    fn refresh_transaction(evm: &mut Evm<'_, Self>) {
221        Self::refresh_switched_transaction(evm, &AddressMap::default());
222    }
223
224    fn refresh_switched_transaction(
225        evm: &mut Evm<'_, Self>,
226        original: &AddressMap<Option<AccountInfo>>,
227    ) {
228        // Preserve persistent accounts' transaction-start fields for every later reserve read,
229        // including accounts first debited after the switch. Accepted writes are not new debits.
230        // A database error surfaces again when execution next reads the account.
231        let _ = rebase_reserve_balance_with_originals(evm, original);
232    }
233}