Skip to main content

forge_script/
runner.rs

1use super::{ScriptConfig, ScriptResult};
2use crate::build::ScriptPredeployLibraries;
3use alloy_eips::eip7702::SignedAuthorization;
4use alloy_network::TransactionBuilder;
5use alloy_primitives::{Address, Bytes, TxKind, U256, map::AddressHashMap};
6use evm2::interpreter::InstrStop;
7use eyre::Result;
8use foundry_cheatcodes::BroadcastableTransaction;
9use foundry_common::{FoundryTransactionBuilder, LIBRARY_DEPLOYER, TransactionMaybeSigned};
10use foundry_config::Config;
11use foundry_evm::{
12    constants::CALLER,
13    core::evm::{EvmEnvFor, FoundryEvmNetwork, TransactionRequestFor},
14    executors::{DeployResult, EvmError, ExecutionErr, Executor, RawCallResult},
15    opts::EvmOpts,
16    traces::{TraceKind, Traces},
17};
18use std::collections::VecDeque;
19
20/// Drives script execution
21#[derive(Debug)]
22pub struct ScriptRunner<FEN: FoundryEvmNetwork> {
23    pub executor: Executor<FEN>,
24    pub evm_opts: EvmOpts,
25    collect_debug_bytecodes: bool,
26}
27
28impl<FEN: FoundryEvmNetwork> ScriptRunner<FEN> {
29    pub const fn new(executor: Executor<FEN>, evm_opts: EvmOpts) -> Self {
30        Self { executor, evm_opts, collect_debug_bytecodes: false }
31    }
32
33    pub const fn with_debug_bytecodes(mut self, collect_debug_bytecodes: bool) -> Self {
34        self.collect_debug_bytecodes = collect_debug_bytecodes;
35        self
36    }
37
38    fn maybe_debug_bytecodes(
39        &self,
40        debug_bytecodes: AddressHashMap<Bytes>,
41    ) -> AddressHashMap<Bytes> {
42        if self.collect_debug_bytecodes { debug_bytecodes } else { Default::default() }
43    }
44
45    fn extend_debug_bytecodes(
46        &self,
47        target: &mut AddressHashMap<Bytes>,
48        debug_bytecodes: AddressHashMap<Bytes>,
49    ) {
50        if self.collect_debug_bytecodes {
51            target.extend(debug_bytecodes);
52        }
53    }
54
55    fn deploy_local_libraries(
56        &mut self,
57        libraries: &[foundry_linking::LinkedLibrary],
58        debug_bytecodes: &mut AddressHashMap<Bytes>,
59    ) -> Result<()> {
60        if libraries.is_empty() {
61            return Ok(());
62        }
63        let balance = self.executor.get_balance(LIBRARY_DEPLOYER)?;
64        let nonce = self.executor.get_nonce(LIBRARY_DEPLOYER)?;
65        self.executor.set_balance(LIBRARY_DEPLOYER, U256::MAX)?;
66        self.executor.set_nonce(LIBRARY_DEPLOYER, 0)?;
67        for library in libraries {
68            let DeployResult { address, raw } = self
69                .executor
70                .deploy(LIBRARY_DEPLOYER, library.bytecode.clone(), U256::ZERO, None)
71                .map_err(|err| eyre::eyre!("couldn't deploy local library: {err}"))?;
72            eyre::ensure!(
73                library.address == address,
74                "local library deployed at an unexpected address"
75            );
76            self.extend_debug_bytecodes(debug_bytecodes, raw.debug_bytecodes);
77        }
78        self.executor.set_balance(LIBRARY_DEPLOYER, balance)?;
79        self.executor.set_nonce(LIBRARY_DEPLOYER, nonce)?;
80        Ok(())
81    }
82
83    /// Deploys the libraries and broadcast contract. Calls setUp method if requested.
84    pub fn setup(
85        &mut self,
86        libraries: &ScriptPredeployLibraries,
87        code: Bytes,
88        setup: bool,
89        script_config: &ScriptConfig<FEN>,
90        is_broadcast: bool,
91    ) -> Result<(Address, ScriptResult<FEN::Network>)> {
92        trace!(target: "script", "executing setUP()");
93
94        if !is_broadcast {
95            if self.evm_opts.sender == Config::DEFAULT_SENDER {
96                // We max out their balance so that they can deploy and make calls.
97                self.executor.set_balance(self.evm_opts.sender, U256::MAX)?;
98            }
99
100            if script_config.evm_opts.fork_url.is_none()
101                && !script_config.evm_opts.networks.is_tempo()
102            {
103                self.executor.deploy_create2_deployer()?;
104            }
105        }
106
107        let sender_nonce = script_config.sender_nonce;
108        self.executor.set_nonce(self.evm_opts.sender, sender_nonce)?;
109
110        // We max out their balance so that they can deploy and make calls.
111        self.executor.set_balance(CALLER, U256::MAX)?;
112
113        let mut library_transactions = VecDeque::new();
114        let mut traces = Traces::default();
115        let mut debug_bytecodes: AddressHashMap<Bytes> = Default::default();
116
117        // Deploy libraries
118        match libraries {
119            ScriptPredeployLibraries::Default { onchain, local } => {
120                self.deploy_local_libraries(local, &mut debug_bytecodes)?;
121                for library in onchain {
122                    let code = &library.bytecode;
123                    let RawCallResult {
124                        traces: deploy_traces,
125                        debug_bytecodes: deploy_debug_bytecodes,
126                        ..
127                    } = self
128                        .executor
129                        .deploy(self.evm_opts.sender, code.clone(), U256::ZERO, None)
130                        .map_err(|err| eyre::eyre!("couldn't deploy library: {err}"))?
131                        .raw;
132
133                    self.extend_debug_bytecodes(&mut debug_bytecodes, deploy_debug_bytecodes);
134
135                    if let Some(deploy_traces) = deploy_traces {
136                        traces.push((TraceKind::Deployment, deploy_traces));
137                    }
138
139                    let mut tx_req = TransactionRequestFor::<FEN>::default()
140                        .with_from(self.evm_opts.sender)
141                        .with_input(code.clone())
142                        .with_nonce(sender_nonce + library_transactions.len() as u64);
143
144                    script_config.tempo.apply::<FEN::Network>(&mut tx_req, None);
145
146                    library_transactions.push_back(BroadcastableTransaction {
147                        rpc: self.evm_opts.fork_url.clone(),
148                        transaction: TransactionMaybeSigned::new(tx_req),
149                        contract_address: None,
150                    })
151                }
152            }
153            ScriptPredeployLibraries::Create2 { onchain, salt, local } => {
154                self.deploy_local_libraries(local, &mut debug_bytecodes)?;
155                let create2_deployer = self.executor.create2_deployer();
156                for library in onchain {
157                    let address =
158                        create2_deployer.create2_from_code(salt, library.bytecode.as_ref());
159                    // Skip if already deployed
160                    if !self.executor.is_empty_code(address)? {
161                        continue;
162                    }
163                    let calldata = [salt.as_ref(), library.bytecode.as_ref()].concat();
164                    let RawCallResult {
165                        traces: deploy_traces,
166                        debug_bytecodes: deploy_debug_bytecodes,
167                        ..
168                    } = self
169                        .executor
170                        .transact_raw(
171                            self.evm_opts.sender,
172                            create2_deployer,
173                            calldata.clone().into(),
174                            U256::ZERO,
175                        )
176                        .map_err(|err| eyre::eyre!("couldn't deploy library: {err}"))?;
177
178                    self.extend_debug_bytecodes(&mut debug_bytecodes, deploy_debug_bytecodes);
179
180                    if let Some(deploy_traces) = deploy_traces {
181                        traces.push((TraceKind::Deployment, deploy_traces));
182                    }
183
184                    let mut tx_req = TransactionRequestFor::<FEN>::default()
185                        .with_from(self.evm_opts.sender)
186                        .with_input(calldata)
187                        .with_nonce(sender_nonce + library_transactions.len() as u64)
188                        .with_to(create2_deployer);
189
190                    script_config.tempo.apply::<FEN::Network>(&mut tx_req, None);
191
192                    library_transactions.push_back(BroadcastableTransaction {
193                        rpc: self.evm_opts.fork_url.clone(),
194                        transaction: TransactionMaybeSigned::new(tx_req),
195                        contract_address: None,
196                    });
197                }
198
199                // Sender nonce is not incremented when performing CALLs. We need to manually
200                // increase it.
201                self.executor.set_nonce(
202                    self.evm_opts.sender,
203                    sender_nonce + library_transactions.len() as u64,
204                )?;
205            }
206        };
207
208        let address = CALLER.create(self.executor.get_nonce(CALLER)?);
209
210        // Set the contracts initial balance before deployment, so it is available during the
211        // construction
212        self.executor.set_balance(address, self.evm_opts.initial_balance)?;
213
214        // HACK: if the current sender is the default script sender (which is a default value), we
215        // set its nonce to a very large value before deploying the script contract. This
216        // ensures that the nonce increase during this CREATE does not affect deployment
217        // addresses of contracts that are deployed in the script, Otherwise, we'd have a
218        // nonce mismatch during script execution and onchain simulation, potentially
219        // resulting in weird errors like <https://github.com/foundry-rs/foundry/issues/8960>.
220        let prev_sender_nonce = self.executor.get_nonce(self.evm_opts.sender)?;
221        if self.evm_opts.sender == CALLER {
222            self.executor.set_nonce(self.evm_opts.sender, u64::MAX / 2)?;
223        }
224
225        // Deploy an instance of the contract
226        let DeployResult {
227            address,
228            raw:
229                RawCallResult {
230                    mut logs,
231                    traces: constructor_traces,
232                    debug_bytecodes: constructor_debug_bytecodes,
233                    ..
234                },
235        } = self
236            .executor
237            .deploy(CALLER, code, U256::ZERO, None)
238            .map_err(|err| eyre::eyre!("Failed to deploy script:\n{}", err))?;
239
240        if self.evm_opts.sender == CALLER {
241            self.executor.set_nonce(self.evm_opts.sender, prev_sender_nonce)?;
242        }
243
244        // set script address to be used by execution inspector
245        if script_config.config.script_execution_protection {
246            self.executor.set_script_execution(address);
247        }
248
249        traces.extend(constructor_traces.map(|traces| (TraceKind::Deployment, traces)));
250        self.extend_debug_bytecodes(&mut debug_bytecodes, constructor_debug_bytecodes);
251
252        // Optionally call the `setUp` function
253        let (success, returned, exit_reason, gas_used, labeled_addresses, transactions) = if setup {
254            let result = match self.executor.setup(Some(self.evm_opts.sender), address, None) {
255                Ok(result) => result,
256                Err(EvmError::Execution(err)) => err.raw,
257                Err(err) => return Err(err.into()),
258            };
259            let RawCallResult {
260                reverted,
261                result,
262                exit_reason,
263                traces: setup_traces,
264                labels,
265                logs: setup_logs,
266                gas_used,
267                debug_bytecodes: setup_debug_bytecodes,
268                transactions: setup_transactions,
269                ..
270            } = result;
271            traces.extend(setup_traces.map(|traces| (TraceKind::Setup, traces)));
272            logs.extend_from_slice(&setup_logs);
273            self.extend_debug_bytecodes(&mut debug_bytecodes, setup_debug_bytecodes);
274            if let Some(txs) = setup_transactions {
275                library_transactions.extend(txs);
276            }
277            (!reverted, result, exit_reason, gas_used, labels, Some(library_transactions))
278        } else {
279            self.executor.backend_mut().set_test_contract(address);
280            (true, Bytes::new(), None, 0, Default::default(), Some(library_transactions))
281        };
282
283        Ok((
284            address,
285            ScriptResult {
286                returned,
287                exit_reason,
288                success,
289                gas_used,
290                labeled_addresses,
291                debug_bytecodes: self.maybe_debug_bytecodes(debug_bytecodes),
292                transactions,
293                logs,
294                traces,
295                address: None,
296                ..Default::default()
297            },
298        ))
299    }
300
301    /// Executes the method that will collect all broadcastable transactions.
302    pub fn script(
303        &mut self,
304        address: Address,
305        calldata: Bytes,
306    ) -> Result<ScriptResult<FEN::Network>> {
307        self.call(self.evm_opts.sender, address, calldata, U256::ZERO, None, false)
308    }
309
310    /// Runs a broadcastable transaction locally and persists its state.
311    pub fn simulate(
312        &mut self,
313        transaction: &TransactionMaybeSigned<FEN::Network>,
314        is_fixed_gas_limit: bool,
315    ) -> Result<ScriptResult<FEN::Network>> {
316        let Some(blob_hashes) = transaction.blob_versioned_hashes() else {
317            return self.simulate_with_tx_env(transaction, is_fixed_gas_limit);
318        };
319
320        // Every simulated call starts from the executor's transaction defaults, so a blob
321        // transaction is run as one there, making `BLOBHASH` match the published transaction.
322        let original_tx = self.executor.tx().clone();
323        let blob_basefee = self.executor.evm_env().block.blob_basefee.saturating_to();
324        let tx = self.executor.tx_mut();
325        tx.set_blob_versioned_hashes(blob_hashes.to_vec());
326        tx.set_max_fee_per_blob_gas(blob_basefee);
327        // evm2 executes complete EIP-4844 requests, which carry 1559 fees and the sidecar.
328        tx.set_max_fee_per_gas(0);
329        tx.set_max_priority_fee_per_gas(0);
330        if let TransactionMaybeSigned::Unsigned(request) = transaction
331            && let Some(sidecar) = request.blob_sidecar()
332        {
333            tx.set_blob_sidecar(sidecar.clone());
334        }
335        let result = self.simulate_with_tx_env(transaction, is_fixed_gas_limit);
336        *self.executor.tx_mut() = original_tx;
337        result
338    }
339
340    fn simulate_with_tx_env(
341        &mut self,
342        transaction: &TransactionMaybeSigned<FEN::Network>,
343        is_fixed_gas_limit: bool,
344    ) -> Result<ScriptResult<FEN::Network>> {
345        if is_fixed_gas_limit {
346            let (env, tx) = self.prepare_fixed_gas_env(transaction);
347            return if is_single_create(&tx) {
348                // Tempo AA requests keep their creation in the call list, so they have no
349                // top-level kind for `deploy_with_env`.
350                let result = self
351                    .executor
352                    .transact_with_env(env, tx)
353                    .map_err(EvmError::from)
354                    .and_then(|raw| raw.into_result(None))
355                    .map(|raw| DeployResult {
356                        address: raw.created_address.unwrap_or_default(),
357                        raw,
358                    });
359                if let Ok(DeployResult { address, .. }) = &result {
360                    self.executor.backend_mut().add_persistent_account(*address);
361                }
362                self.deployment_result(result)
363            } else {
364                let result = self.executor.transact_with_env(env, tx)?;
365                let gas_used = result.gas_used;
366                Ok(self.call_result(result, gas_used))
367            };
368        }
369
370        let from = transaction.from().expect("transaction sender missing");
371        if let Some(to) = transaction.to() {
372            self.call(
373                from,
374                to,
375                transaction.input().cloned().unwrap_or_default(),
376                transaction.value().unwrap_or_default(),
377                transaction.authorization_list(),
378                true,
379            )
380        } else {
381            let res = self.executor.deploy(
382                from,
383                transaction.input().cloned().expect("No data for create transaction"),
384                transaction.value().unwrap_or_default(),
385                None,
386            );
387            self.deployment_result(res)
388        }
389    }
390
391    pub(crate) fn deployment_result(
392        &self,
393        res: Result<DeployResult<FEN>, EvmError<FEN>>,
394    ) -> Result<ScriptResult<FEN::Network>> {
395        let (address, RawCallResult { gas_used, logs, traces, debug_bytecodes, exit_reason, .. }) =
396            match res {
397                Ok(DeployResult { address, raw }) => (address, raw),
398                Err(EvmError::Execution(err)) => {
399                    let ExecutionErr { raw, reason } = *err;
400                    sh_err!("Failed with `{reason}`:\n")?;
401                    (Address::ZERO, raw)
402                }
403                Err(e) => {
404                    eyre::bail!("Failed deploying contract: {e:?}");
405                }
406            };
407
408        Ok(ScriptResult {
409            returned: Bytes::new(),
410            success: !address.is_zero(),
411            gas_used,
412            logs,
413            debug_bytecodes: self.maybe_debug_bytecodes(debug_bytecodes),
414            // Manually adjust gas for the trace to add back the stipend/real used gas
415            traces: traces.map(|traces| vec![(TraceKind::Execution, traces)]).unwrap_or_default(),
416            exit_reason,
417            address: Some(address),
418            ..Default::default()
419        })
420    }
421
422    /// Executes the call
423    ///
424    /// This will commit the changes if `commit` is true.
425    ///
426    /// This will return _estimated_ gas instead of the precise gas the call would consume, so it
427    /// can be used as `gas_limit`.
428    fn call(
429        &mut self,
430        from: Address,
431        to: Address,
432        calldata: Bytes,
433        value: U256,
434        authorization_list: Option<Vec<SignedAuthorization>>,
435        commit: bool,
436    ) -> Result<ScriptResult<FEN::Network>> {
437        let mut res = if let Some(authorization_list) = &authorization_list {
438            self.executor.call_raw_with_authorization(
439                from,
440                to,
441                calldata.clone(),
442                value,
443                authorization_list.clone(),
444            )?
445        } else {
446            self.executor.call_raw(from, to, calldata.clone(), value)?
447        };
448        let mut gas_used = res.gas_used;
449
450        // We should only need to calculate realistic gas costs when preparing to broadcast
451        // something. This happens during the onchain simulation stage, where we commit each
452        // collected transactions.
453        //
454        // Otherwise don't re-execute, or some usecases might be broken: https://github.com/foundry-rs/foundry/issues/3921
455        if commit {
456            gas_used = self.search_optimal_gas_usage(&res, from, to, &calldata, value)?;
457            res = if let Some(authorization_list) = authorization_list {
458                self.executor.transact_raw_with_authorization(
459                    from,
460                    to,
461                    calldata,
462                    value,
463                    authorization_list,
464                )?
465            } else {
466                self.executor.transact_raw(from, to, calldata, value)?
467            }
468        }
469
470        Ok(self.call_result(res, gas_used))
471    }
472
473    pub(crate) fn call_result(
474        &self,
475        res: RawCallResult<FEN>,
476        gas_used: u64,
477    ) -> ScriptResult<FEN::Network> {
478        let RawCallResult {
479            result,
480            reverted,
481            logs,
482            traces,
483            labels,
484            transactions,
485            debug_bytecodes,
486            exit_reason,
487            cheatcodes,
488            ..
489        } = res;
490        let breakpoints = cheatcodes.map(|cheats| cheats.breakpoints).unwrap_or_default();
491
492        ScriptResult {
493            returned: result,
494            success: !reverted,
495            gas_used,
496            logs,
497            debug_bytecodes: self.maybe_debug_bytecodes(debug_bytecodes),
498            traces: traces
499                .map(|traces| {
500                    // Manually adjust gas for the trace to add back the stipend/real used gas
501
502                    vec![(TraceKind::Execution, traces)]
503                })
504                .unwrap_or_default(),
505            labeled_addresses: labels,
506            transactions,
507            exit_reason,
508            address: None,
509            breakpoints,
510        }
511    }
512
513    /// The executor will return the _exact_ gas value this transaction consumed, setting this value
514    /// as gas limit will result in `OutOfGas` so to come up with a better estimate we search over a
515    /// possible range we pick a higher gas limit 3x of a succeeded call should be safe.
516    ///
517    /// This might result in executing the same script multiple times. Depending on the user's goal,
518    /// it might be problematic when using `ffi`.
519    fn search_optimal_gas_usage(
520        &mut self,
521        res: &RawCallResult<FEN>,
522        from: Address,
523        to: Address,
524        calldata: &Bytes,
525        value: U256,
526    ) -> Result<u64> {
527        let mut gas_used = res.gas_used;
528        if res.exit_reason.is_some_and(InstrStop::is_success) {
529            // Store the current gas limit and reset it later.
530            let init_gas_limit = self.executor.tx().gas_limit();
531
532            let mut search = GasSearch::new(gas_used);
533            while let Some(limit) = search.next_limit() {
534                self.executor.tx_mut().set_gas_limit(limit);
535                let res = self.executor.call_raw(from, to, calldata.0.clone().into(), value)?;
536                search.record(limit, needs_more_gas(res.exit_reason));
537            }
538            gas_used = search.gas_used();
539            // Reset gas limit in the executor.
540            match init_gas_limit {
541                Some(gas_limit) => self.executor.tx_mut().set_gas_limit(gas_limit),
542                None => self.executor.tx_mut().reset_gas_limit(),
543            }
544        }
545        Ok(gas_used)
546    }
547
548    /// Prepares a fixed-limit transaction without changing the block or executor gas limit.
549    ///
550    /// The transaction keeps its complete network-native payload, including access lists,
551    /// authorizations and network fields; only the sender, chain ID, gas limit and fees are
552    /// normalized as for synthetic calls.
553    pub(crate) fn prepare_fixed_gas_env(
554        &self,
555        transaction: &TransactionMaybeSigned<FEN::Network>,
556    ) -> (EvmEnvFor<FEN>, TransactionRequestFor<FEN>) {
557        let from = transaction.from().expect("transaction sender missing");
558        let kind = transaction.to().map_or(TxKind::Create, TxKind::Call);
559        let (mut env, defaults) = self.executor.prepare_call_env(
560            from,
561            kind,
562            transaction.input().cloned().unwrap_or_default(),
563            transaction.value().unwrap_or_default(),
564        );
565        env.block.gas_limit = self.executor.evm_env().block.gas_limit;
566        let mut tx: TransactionRequestFor<FEN> = match transaction {
567            TransactionMaybeSigned::Signed { tx: signed, .. } => signed.clone().into(),
568            TransactionMaybeSigned::Unsigned(request) => request.clone(),
569        };
570        tx.set_from(from);
571        // Requests and envelopes of creations can leave the kind unset.
572        if tx.kind().is_none() && !tx.has_tempo_call_list() {
573            tx.set_kind(kind);
574        }
575        if tx.nonce().is_none() {
576            tx.set_nonce(defaults.nonce().unwrap_or_default());
577        }
578        // Retain the synthetic call's fee and chain normalization.
579        if tx.max_fee_per_gas().is_some() || tx.authorization_list().is_some() || tx.is_tempo_aa() {
580            tx.set_max_fee_per_gas(0);
581            tx.set_max_priority_fee_per_gas(0);
582        } else {
583            tx.set_gas_price(0);
584        }
585        tx.set_chain_id(env.chain_id());
586        tx.set_gas_limit(transaction.gas().expect("fixed gas limit missing") as u64);
587        (env, tx)
588    }
589}
590
591/// Returns whether `tx` executes a single contract creation.
592fn is_single_create<N, T: FoundryTransactionBuilder<N>>(tx: &T) -> bool
593where
594    N: alloy_network::Network<TransactionRequest = T>,
595{
596    if tx.has_tempo_call_list() {
597        matches!(tx.tempo_calls().as_slice(), [(TxKind::Create, _)])
598    } else {
599        tx.kind().is_some_and(|kind| kind.is_create())
600    }
601}
602
603/// Gas-search arithmetic shared by ordinary and Monad simulation.
604pub(crate) struct GasSearch {
605    gas_used: u64,
606    highest: u64,
607    lowest: u64,
608    last_highest: u64,
609    done: bool,
610}
611
612impl GasSearch {
613    pub(crate) const fn new(gas_used: u64) -> Self {
614        Self {
615            gas_used,
616            highest: gas_used * 3,
617            lowest: gas_used,
618            last_highest: gas_used * 3,
619            done: false,
620        }
621    }
622
623    pub(crate) const fn next_limit(&self) -> Option<u64> {
624        if !self.done && self.highest - self.lowest > 1 {
625            Some((self.highest + self.lowest) / 2)
626        } else {
627            None
628        }
629    }
630
631    /// Records the outcome of a probe at `limit`, where `needs_more_gas` means the limit was not
632    /// enough.
633    pub(crate) const fn record(&mut self, limit: u64, needs_more_gas: bool) {
634        if needs_more_gas {
635            self.lowest = limit;
636        } else {
637            self.highest = limit;
638            // Stop when successive successful estimates differ by less than ten percent.
639            if (self.last_highest - self.highest) * 10 / self.last_highest < 1 {
640                self.gas_used = self.highest;
641                self.done = true;
642            } else {
643                self.last_highest = self.highest;
644            }
645        }
646    }
647
648    pub(crate) const fn gas_used(&self) -> u64 {
649        self.gas_used
650    }
651}
652
653/// Returns whether the gas search treats `exit_reason` as needing more gas.
654pub(crate) const fn needs_more_gas(exit_reason: Option<InstrStop>) -> bool {
655    matches!(exit_reason, Some(InstrStop::Revert | InstrStop::OutOfGas | InstrStop::OutOfFunds))
656}
657
658#[cfg(test)]
659mod tests {
660    use super::*;
661    use alloy_primitives::bytes;
662    use alloy_signer::SignerSync;
663    use alloy_signer_local::PrivateKeySigner;
664    use foundry_evm::{backend::Backend, core::evm::TempoEvmNetwork, executors::ExecutorBuilder};
665    use foundry_evm_networks::NetworkConfigs;
666    use tempo_alloy::primitives::{TempoTransaction, TempoTxEnvelope, transaction::Call};
667
668    #[test]
669    fn successful_probes_keep_existing_ten_percent_stop() {
670        let mut search = GasSearch::new(100);
671        for expected in [200, 150, 125, 112, 106] {
672            assert_eq!(search.next_limit(), Some(expected));
673            search.record(expected, false);
674        }
675        assert_eq!(search.next_limit(), None);
676        assert_eq!(search.gas_used(), 106);
677    }
678
679    #[test]
680    fn unsuccessful_probes_keep_original_estimate() {
681        let mut search = GasSearch::new(100);
682        while let Some(limit) = search.next_limit() {
683            search.record(limit, true);
684        }
685        assert_eq!(search.gas_used(), 100);
686        assert_eq!(GasSearch::new(0).next_limit(), None);
687    }
688
689    #[test]
690    fn only_revert_and_running_out_mean_too_little_gas() {
691        for reason in [InstrStop::Revert, InstrStop::OutOfGas, InstrStop::OutOfFunds] {
692            assert!(needs_more_gas(Some(reason)));
693        }
694        for reason in
695            [Some(InstrStop::Return), Some(InstrStop::Stop), Some(InstrStop::InvalidFEOpcode), None]
696        {
697            assert!(!needs_more_gas(reason));
698        }
699    }
700
701    #[test]
702    fn fixed_gas_tempo_create_first_batch() {
703        let signer = PrivateKeySigner::random();
704        let sender = signer.address();
705        let target = sender.create(0);
706        // The constructor stores seven; the runtime increments that slot when called.
707        let initcode = bytes!("60075f556008600e5f3960085ff35f546001015f5500");
708        for batch in [false, true] {
709            let opts = EvmOpts { memory_limit: 1 << 25, ..Default::default() };
710            let mut env = opts.local_evm_env::<TempoEvmNetwork>();
711            env.set_chain_id(31337);
712            env.block.gas_limit = U256::from(30_000_000);
713            let executor = ExecutorBuilder::<TempoEvmNetwork>::new().gas_limit(30_000_000).build(
714                env,
715                Default::default(),
716                Backend::spawn(None, env).unwrap(),
717                NetworkConfigs::with_tempo(),
718            );
719            let mut runner = ScriptRunner::new(executor, EvmOpts::default());
720            let mut calls =
721                vec![Call { to: TxKind::Create, value: U256::ZERO, input: initcode.clone() }];
722            if batch {
723                calls.push(Call {
724                    to: TxKind::Call(target),
725                    value: U256::ZERO,
726                    input: Bytes::new(),
727                });
728            }
729            let transaction = TempoTransaction {
730                chain_id: 31337,
731                gas_limit: 2_000_000,
732                calls,
733                ..Default::default()
734            };
735            let signature = signer.sign_hash_sync(&transaction.signature_hash()).unwrap();
736            let transaction = TransactionMaybeSigned::Signed {
737                tx: TempoTxEnvelope::AA(transaction.into_signed(signature.into())),
738                from: sender,
739            };
740            let result = runner.simulate(&transaction, true).unwrap();
741            assert!(result.success);
742            assert_eq!(
743                runner.executor.backend().storage(target, U256::ZERO).unwrap(),
744                U256::from(if batch { 8 } else { 7 }),
745            );
746            assert!(!runner.executor.is_empty_code(target).unwrap());
747            assert_eq!(transaction.gas(), Some(2_000_000));
748            assert_eq!(runner.executor.gas_limit(), 30_000_000);
749        }
750    }
751}