Skip to main content

forge_script/simulate/
monad.rs

1//! Sequential Monad simulation owns its block cursor independently of local script execution.
2
3use super::{PreSimulationState, RpcSimulationContext, SimulatedTransaction, SimulationOutcome};
4use crate::{
5    ScriptResult,
6    runner::{GasSearch, ScriptRunner, needs_more_gas},
7    simulate::FilledTransactionsState,
8    transaction::ScriptTransactionBuilder,
9};
10use alloy_consensus::transaction::Recovered;
11use alloy_eips::eip7702::SignedAuthorization;
12use alloy_network::{AnyNetwork, Ethereum, TransactionBuilder};
13use alloy_primitives::{Address, Bytes, TxKind, U256, map::HashMap};
14use alloy_provider::Provider;
15use alloy_rpc_types::TransactionRequest;
16use evm2::interpreter::InstrStop;
17use eyre::{Result, WrapErr};
18use foundry_common::{FoundryTransactionBuilder, TransactionMaybeSigned};
19use foundry_evm::{
20    core::evm::{
21        BlockContext, ChainFor, EvmEnvFor, EvmFactoryFor, FoundryEvmFactory, FoundryTxConversion,
22        MonadEvmNetwork, TxFor, TypesFor,
23    },
24    executors::{EvmError, RawCallResult},
25};
26
27struct MonadSimulation {
28    runner: ScriptRunner<MonadEvmNetwork>,
29    cursor: Option<BlockContext<MonadEvmNetwork>>,
30}
31
32impl MonadSimulation {
33    /// Creates a simulation whose cursor starts in the block after the runner's fork block, if
34    /// forked.
35    async fn new(runner: ScriptRunner<MonadEvmNetwork>) -> Result<Self> {
36        let backend = runner.executor.backend();
37        let cursor = match (backend.fork(), backend.active_fork_url()) {
38            (Some(fork), Some(url)) => {
39                let provider = runner.evm_opts.fork_provider_with_url::<AnyNetwork>(&url)?;
40                let block = provider
41                    .get_block_by_hash(fork.hash())
42                    .full()
43                    .await?
44                    .ok_or_else(|| eyre::eyre!("fork block {} not found", fork.hash()))?;
45                let mut cursor = BlockContext::fetch(&provider, &block).await?;
46                cursor.advance_block();
47                Some(cursor)
48            }
49            _ => None,
50        };
51        Ok(Self { runner, cursor })
52    }
53
54    /// Returns the extension state for `tx` at the cursor's next position, if positioned.
55    fn ext(
56        &self,
57        env: &EvmEnvFor<MonadEvmNetwork>,
58        tx: &Recovered<TxFor<MonadEvmNetwork>>,
59    ) -> Option<ChainFor<MonadEvmNetwork>> {
60        self.cursor.as_ref().map(|cursor| {
61            let mut ext = EvmFactoryFor::<MonadEvmNetwork>::default().evm_ext(env);
62            cursor.prepare_next(&mut ext, tx);
63            ext
64        })
65    }
66
67    /// Executes `tx` without committing it.
68    fn call(
69        &self,
70        env: EvmEnvFor<MonadEvmNetwork>,
71        tx: TransactionRequest,
72    ) -> Result<RawCallResult<MonadEvmNetwork>> {
73        let tx = TypesFor::<MonadEvmNetwork>::tx_from_request(tx)?;
74        self.runner.executor.call_tx(env, &tx, self.ext(&env, &tx))
75    }
76
77    /// Executes and commits `tx`, and records it at the cursor's position.
78    ///
79    /// Reverted transactions are committed and recorded too; transactions failing validation are
80    /// neither.
81    fn transact(
82        &mut self,
83        env: EvmEnvFor<MonadEvmNetwork>,
84        tx: TransactionRequest,
85    ) -> Result<RawCallResult<MonadEvmNetwork>> {
86        let tx = TypesFor::<MonadEvmNetwork>::tx_from_request(tx)?;
87        let result = self.runner.executor.transact_tx(env, &tx, self.ext(&env, &tx))?;
88        if let Some(cursor) = &mut self.cursor {
89            cursor.record_transaction(tx);
90        }
91        Ok(result)
92    }
93
94    fn prepare_call(
95        &self,
96        from: Address,
97        to: Address,
98        calldata: Bytes,
99        value: U256,
100        authorization_list: Option<Vec<SignedAuthorization>>,
101    ) -> (EvmEnvFor<MonadEvmNetwork>, TransactionRequest) {
102        let (env, mut tx) = self.runner.executor.prepare_call_env(from, to.into(), calldata, value);
103        if let Some(authorization_list) = authorization_list {
104            tx.set_authorization_list(authorization_list);
105            tx.set_max_fee_per_gas(0);
106            tx.set_max_priority_fee_per_gas(0);
107        }
108        (env, tx)
109    }
110
111    fn simulate(
112        &mut self,
113        transaction: &TransactionMaybeSigned<Ethereum>,
114        is_fixed_gas_limit: bool,
115    ) -> Result<ScriptResult<Ethereum>> {
116        let from = transaction.from().expect("transaction sender missing");
117        let calldata = transaction.input().cloned();
118        let value = transaction.value().unwrap_or_default();
119        let authorization_list = transaction.authorization_list();
120        let Some(to) = transaction.to() else {
121            let (env, tx) = if is_fixed_gas_limit {
122                self.runner.prepare_fixed_gas_env(transaction)
123            } else {
124                self.runner.executor.prepare_call_env(
125                    from,
126                    TxKind::Create,
127                    calldata.expect("No data for create transaction"),
128                    value,
129                )
130            };
131            let result = self
132                .transact(env, tx)
133                .map_err(EvmError::from)
134                .and_then(|raw| self.runner.executor.persist_deployment(raw, None));
135            return self.runner.deployment_result(result);
136        };
137
138        if is_fixed_gas_limit {
139            let (env, tx) = self.runner.prepare_fixed_gas_env(transaction);
140            let result = self.transact(env, tx)?;
141            let gas_used = result.gas_used;
142            return Ok(self.runner.call_result(result, gas_used));
143        }
144
145        let calldata = calldata.unwrap_or_default();
146        let (env, tx) =
147            self.prepare_call(from, to, calldata.clone(), value, authorization_list.clone());
148        let result = self.call(env, tx)?;
149        let mut gas_used = result.gas_used;
150        if result.exit_reason.is_some_and(InstrStop::is_success) {
151            let initial_limit = self.runner.executor.tx().gas_limit();
152            let mut search = GasSearch::new(gas_used);
153            while let Some(limit) = search.next_limit() {
154                // Keep the existing gas-probe preparation and authorization behavior unchanged.
155                self.runner.executor.tx_mut().set_gas_limit(limit);
156                let (env, tx) = self.prepare_call(from, to, calldata.clone(), value, None);
157                let result = self.call(env, tx)?;
158                search.record(limit, needs_more_gas(result.exit_reason));
159            }
160            gas_used = search.gas_used();
161            match initial_limit {
162                Some(gas_limit) => self.runner.executor.tx_mut().set_gas_limit(gas_limit),
163                None => self.runner.executor.tx_mut().reset_gas_limit(),
164            }
165        }
166
167        let (env, tx) = self.prepare_call(from, to, calldata, value, authorization_list);
168        let result = self.transact(env, tx)?;
169        Ok(self.runner.call_result(result, gas_used))
170    }
171
172    fn advance_block(&mut self) {
173        if let Some(cursor) = &mut self.cursor {
174            cursor.advance_block();
175        }
176        self.runner.executor.evm_env_mut().block.number += U256::ONE;
177    }
178}
179
180impl PreSimulationState<MonadEvmNetwork> {
181    pub(crate) async fn fill_monad_metadata(
182        self,
183    ) -> Result<FilledTransactionsState<MonadEvmNetwork>> {
184        if self.args.skip_simulation {
185            return self.fill_without_simulation().await;
186        }
187
188        let mut contexts = HashMap::default();
189        for (rpc, context) in self.build_runners().await? {
190            contexts.insert(
191                rpc,
192                RpcSimulationContext {
193                    runner: MonadSimulation::new(context.runner).await?,
194                    decoder: context.decoder,
195                },
196            );
197        }
198        let transactions =
199            self.transaction_metadata(|rpc| &contexts.get(rpc).expect("invalid rpc url").decoder)?;
200        self.show_simulation_header()?;
201        let results = transactions
202            .into_iter()
203            .map(|transaction| {
204                let rpc = transaction.rpc.clone();
205                let simulation = &mut contexts.get_mut(&rpc).expect("invalid rpc url").runner;
206
207                let tx = transaction.tx();
208                let to = tx.to();
209                let result = simulation
210                    .simulate(tx, transaction.is_fixed_gas_limit)
211                    .wrap_err("Internal EVM error during simulation")?;
212                if !result.success {
213                    return Ok(SimulationOutcome {
214                        rpc,
215                        transaction: SimulatedTransaction::Failed,
216                        traces: result.traces,
217                    });
218                }
219                if self.args.slow {
220                    simulation.advance_block();
221                }
222                let is_noop = if let Some(to) = to {
223                    simulation.runner.executor.is_empty_code(to)?
224                        && tx.value().unwrap_or_default().is_zero()
225                } else {
226                    false
227                };
228                let transaction = ScriptTransactionBuilder::from(transaction)
229                    .with_execution_result(
230                        &result,
231                        self.args.gas_estimate_multiplier,
232                        &self.build_data,
233                    )?
234                    .build();
235                eyre::Ok(SimulationOutcome {
236                    rpc,
237                    transaction: SimulatedTransaction::succeeded(transaction, is_noop),
238                    traces: result.traces,
239                })
240            })
241            .collect::<Vec<_>>();
242        let transactions = self.collect_simulation_results(results, &contexts).await?;
243        Ok(self.into_filled(transactions))
244    }
245}
246
247#[cfg(test)]
248mod tests {
249    use super::*;
250    use alloy_eips::eip2930::{AccessList, AccessListItem};
251    use alloy_primitives::{B256, bytes};
252    use evm2::bytecode::Bytecode;
253    use foundry_evm::{
254        backend::Backend, executors::ExecutorBuilder, hardforks::MonadHardfork, opts::EvmOpts,
255    };
256    use foundry_evm_networks::NetworkConfigs;
257
258    fn simulation() -> MonadSimulation {
259        // Match the simulation environment produced by EvmOpts.
260        let opts = EvmOpts { memory_limit: 1 << 25, ..Default::default() };
261        let mut env = opts.local_evm_env::<MonadEvmNetwork>();
262        env.block.gas_limit = U256::from(30_000_000);
263        let executor = ExecutorBuilder::<MonadEvmNetwork>::new().gas_limit(1 << 20).build(
264            env,
265            Default::default(),
266            Backend::spawn(None, env).unwrap(),
267            NetworkConfigs::with_monad(),
268        );
269        let runner = ScriptRunner::new(executor, EvmOpts::default());
270        let mut simulation = futures::executor::block_on(MonadSimulation::new(runner)).unwrap();
271        assert!(simulation.cursor.is_none());
272        simulation.cursor = Some(BlockContext::new(Vec::new(), Vec::new(), Vec::new()));
273        simulation
274    }
275
276    fn assert_transaction_count(simulation: &MonadSimulation, count: usize) {
277        let cursor = simulation.cursor.as_ref().unwrap();
278        assert!(cursor.clone().before_transaction(count).is_ok());
279        assert!(cursor.clone().before_transaction(count + 1).is_err());
280    }
281
282    #[test]
283    fn calls_and_gas_probes_record_only_committed_transactions() {
284        let other = simulation();
285        let mut simulation = simulation();
286        let sender = Address::with_last_byte(0x42);
287        let recipient = Address::with_last_byte(0x43);
288        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
289        let result =
290            simulation.simulate(&transaction(sender, Some(recipient), None), false).unwrap();
291        assert!(result.success);
292        assert_transaction_count(&simulation, 1);
293        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 1);
294
295        simulation.advance_block();
296        assert_transaction_count(&simulation, 0);
297        assert_eq!(simulation.runner.executor.evm_env().block.number, U256::ONE);
298        assert_transaction_count(&other, 0);
299    }
300
301    #[test]
302    fn deployment_and_reverted_call_both_advance_the_cursor() {
303        let mut simulation = simulation();
304        let sender = Address::with_last_byte(0x42);
305        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
306        // Deploy runtime code that always reverts.
307        let initcode = bytes!("6005600c60003960056000f360006000fd");
308        let deployment =
309            simulation.simulate(&transaction(sender, None, Some(initcode)), false).unwrap();
310        assert!(deployment.success);
311        assert_transaction_count(&simulation, 1);
312        let address = deployment.address.unwrap();
313        assert!(!simulation.runner.executor.is_empty_code(address).unwrap());
314        let result = simulation.simulate(&transaction(sender, Some(address), None), false).unwrap();
315        assert!(!result.success);
316        assert_transaction_count(&simulation, 2);
317        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 2);
318    }
319
320    #[test]
321    fn validation_failure_does_not_advance_the_cursor() {
322        let mut simulation = simulation();
323        simulation.runner.executor.set_gas_limit(1);
324        let sender = Address::with_last_byte(0x42);
325        let result = simulation
326            .simulate(&transaction(sender, Some(Address::with_last_byte(0x43)), None), false);
327        assert!(result.is_err());
328        assert_transaction_count(&simulation, 0);
329        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 0);
330    }
331
332    #[test]
333    fn authorization_preparation_preserves_explicit_empty_list() {
334        let simulation = simulation();
335        let (_, tx) = simulation.prepare_call(
336            Address::with_last_byte(0x42),
337            Address::with_last_byte(0x43),
338            Bytes::new(),
339            U256::ZERO,
340            Some(Vec::new()),
341        );
342        assert_eq!(tx.authorization_list(), Some(&Vec::new()));
343        assert_transaction_count(&simulation, 0);
344    }
345
346    fn transaction(
347        from: Address,
348        to: Option<Address>,
349        input: Option<Bytes>,
350    ) -> TransactionMaybeSigned<Ethereum> {
351        TransactionMaybeSigned::new(
352            TransactionRequest::default()
353                .with_from(from)
354                .with_kind(to.map_or(TxKind::Create, TxKind::Call))
355                .with_input(input.unwrap_or_default()),
356        )
357    }
358
359    #[test]
360    fn fixed_gas_calls_and_deployments_preserve_block_gas_limit() {
361        let mut simulation = simulation();
362        let sender = Address::with_last_byte(0x42);
363        let block_gas_limit = 30_000_000;
364        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
365        simulation.runner.executor.evm_env_mut().block.gas_limit = U256::from(block_gas_limit);
366        let executor_gas_limit = simulation.runner.executor.gas_limit();
367
368        // The constructor stores GASLIMIT in slot zero; the runtime returns GASLIMIT.
369        let initcode = bytes!("456000556009601060003960096000f34560005260206000f3");
370        let deployment = simulation
371            .simulate(&fixed_transaction(sender, None, Some(initcode), 100_000), true)
372            .unwrap();
373        assert!(deployment.success);
374        let address = deployment.address.unwrap();
375        assert_eq!(
376            simulation.runner.executor.backend().storage(address, U256::ZERO).unwrap(),
377            U256::from(block_gas_limit),
378        );
379        assert_transaction_count(&simulation, 1);
380        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 1);
381
382        let result = simulation
383            .simulate(&fixed_transaction(sender, Some(address), None, 50_000), true)
384            .unwrap();
385        assert!(result.success);
386        assert_eq!(U256::from_be_slice(&result.returned), U256::from(block_gas_limit));
387        assert_transaction_count(&simulation, 2);
388        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 2);
389        assert_eq!(simulation.runner.executor.gas_limit(), executor_gas_limit);
390        assert_eq!(
391            simulation.runner.executor.evm_env().block.gas_limit,
392            U256::from(block_gas_limit)
393        );
394    }
395
396    #[test]
397    fn fixed_gas_access_lists_do_not_leak_to_following_transactions() {
398        let mut simulation = simulation();
399        simulation.runner.executor.set_spec_id(MonadHardfork::MonadTen);
400        let sender = Address::with_last_byte(0x42);
401        let recipient = Address::with_last_byte(0x43);
402        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
403        let executor_gas_limit = simulation.runner.executor.gas_limit();
404
405        // Read 32 distinct storage pages: warm reads fit the cap, while cold reads do not.
406        // MonadTen warms all 128 slots in a page together.
407        let mut code = Vec::new();
408        for page in 0..32u16 {
409            code.push(0x61);
410            code.extend_from_slice(&(page * 128).to_be_bytes());
411            code.extend_from_slice(&[0x54, 0x50]);
412        }
413        code.push(0x00);
414        simulation.runner.executor.set_code(recipient, Bytecode::new_raw(code.into())).unwrap();
415        let access_list = AccessList(vec![AccessListItem {
416            address: recipient,
417            storage_keys: (0..32).map(|page| B256::from(U256::from(page * 128))).collect(),
418        }]);
419        let mut transaction = TransactionMaybeSigned::new(
420            TransactionRequest::default()
421                .with_from(sender)
422                .with_to(recipient)
423                .with_gas_price(0)
424                .with_gas_limit(100_000)
425                .with_access_list(access_list),
426        );
427        let result = simulation.simulate(&transaction, true).unwrap();
428        assert!(result.success);
429        assert_transaction_count(&simulation, 1);
430        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 1);
431
432        transaction.as_unsigned_mut().unwrap().access_list = None;
433        let result = simulation.simulate(&transaction, true).unwrap();
434        assert!(!result.success);
435        assert_eq!(result.exit_reason, Some(InstrStop::OutOfGas));
436        assert_transaction_count(&simulation, 2);
437        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 2);
438
439        let result = simulation.simulate(&transaction, false).unwrap();
440        assert!(result.success);
441        assert_transaction_count(&simulation, 3);
442        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 3);
443        assert_eq!(simulation.runner.executor.gas_limit(), executor_gas_limit);
444    }
445
446    #[test]
447    fn fixed_gas_validation_failure_does_not_advance_the_cursor() {
448        let mut simulation = simulation();
449        let sender = Address::with_last_byte(0x42);
450        let recipient = Address::with_last_byte(0x43);
451        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
452        let result =
453            simulation.simulate(&fixed_transaction(sender, Some(recipient), None, 1), true);
454        assert!(result.is_err());
455        assert_transaction_count(&simulation, 0);
456        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 0);
457
458        let result = simulation
459            .simulate(&fixed_transaction(sender, Some(recipient), None, 21_000), true)
460            .unwrap();
461        assert!(result.success);
462        assert_transaction_count(&simulation, 1);
463        assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), 1);
464    }
465
466    fn fixed_transaction(
467        from: Address,
468        to: Option<Address>,
469        input: Option<Bytes>,
470        gas_limit: u64,
471    ) -> TransactionMaybeSigned<Ethereum> {
472        let mut transaction = transaction(from, to, input);
473        transaction.as_unsigned_mut().unwrap().set_gas_limit(gas_limit);
474        transaction
475    }
476
477    #[test]
478    fn fixed_gas_failed_deployments_advance_the_cursor() {
479        let mut simulation = simulation();
480        let sender = Address::with_last_byte(0x42);
481        simulation.runner.executor.set_balance(sender, U256::MAX).unwrap();
482
483        for (index, (initcode, exit_reason)) in
484            [(bytes!("60006000fd"), InstrStop::Revert), (bytes!("5b600056"), InstrStop::OutOfGas)]
485                .into_iter()
486                .enumerate()
487        {
488            let result = simulation
489                .simulate(&fixed_transaction(sender, None, Some(initcode), 60_000), true)
490                .unwrap();
491            assert!(!result.success);
492            assert_eq!(result.exit_reason, Some(exit_reason));
493            assert_eq!(result.address, Some(Address::ZERO));
494            assert_transaction_count(&simulation, index + 1);
495            assert_eq!(simulation.runner.executor.get_nonce(sender).unwrap(), index as u64 + 1);
496        }
497    }
498}