reth_optimism_evm/
lib.rs

1//! EVM config for vanilla optimism.
2
3#![doc(
4    html_logo_url = "https://raw.githubusercontent.com/paradigmxyz/reth/main/assets/reth-docs.png",
5    html_favicon_url = "https://avatars0.githubusercontent.com/u/97369466?s=256",
6    issue_tracker_base_url = "https://github.com/paradigmxyz/reth/issues/"
7)]
8#![cfg_attr(docsrs, feature(doc_cfg))]
9#![cfg_attr(not(feature = "std"), no_std)]
10#![cfg_attr(not(test), warn(unused_crate_dependencies))]
11
12extern crate alloc;
13
14use alloc::sync::Arc;
15use alloy_consensus::{BlockHeader, Header};
16use alloy_evm::{EvmFactory, FromRecoveredTx, FromTxWithEncoded};
17use alloy_op_evm::block::{receipt_builder::OpReceiptBuilder, OpTxEnv};
18use core::fmt::Debug;
19use op_alloy_consensus::EIP1559ParamError;
20use op_revm::{OpSpecId, OpTransaction};
21use reth_chainspec::EthChainSpec;
22use reth_evm::{
23    eth::NextEvmEnvAttributes, precompiles::PrecompilesMap, ConfigureEvm, EvmEnv, TransactionEnv,
24};
25use reth_optimism_chainspec::OpChainSpec;
26use reth_optimism_forks::OpHardforks;
27use reth_optimism_primitives::{DepositReceipt, OpPrimitives};
28use reth_primitives_traits::{NodePrimitives, SealedBlock, SealedHeader, SignedTransaction};
29use revm::context::{BlockEnv, TxEnv};
30
31#[allow(unused_imports)]
32use {
33    alloy_eips::Decodable2718,
34    alloy_primitives::{Bytes, U256},
35    op_alloy_rpc_types_engine::OpExecutionData,
36    reth_evm::{EvmEnvFor, ExecutionCtxFor},
37    reth_primitives_traits::{TxTy, WithEncoded},
38    reth_storage_errors::any::AnyError,
39    revm::{
40        context::CfgEnv, context_interface::block::BlobExcessGasAndPrice,
41        primitives::hardfork::SpecId,
42    },
43};
44
45#[cfg(feature = "std")]
46use reth_evm::{ConfigureEngineEvm, ExecutableTxIterator};
47
48mod config;
49pub use config::{revm_spec, revm_spec_by_timestamp_after_bedrock, OpNextBlockEnvAttributes};
50mod execute;
51pub use execute::*;
52pub mod l1;
53pub use l1::*;
54mod receipts;
55pub use receipts::*;
56mod build;
57pub use build::OpBlockAssembler;
58
59mod error;
60pub use error::OpBlockExecutionError;
61
62pub use alloy_op_evm::{OpBlockExecutionCtx, OpBlockExecutorFactory, OpEvm, OpEvmFactory};
63
64/// Optimism-related EVM configuration.
65#[derive(Debug)]
66pub struct OpEvmConfig<
67    ChainSpec = OpChainSpec,
68    N: NodePrimitives = OpPrimitives,
69    R = OpRethReceiptBuilder,
70    EvmFactory = OpEvmFactory,
71> {
72    /// Inner [`OpBlockExecutorFactory`].
73    pub executor_factory: OpBlockExecutorFactory<R, Arc<ChainSpec>, EvmFactory>,
74    /// Optimism block assembler.
75    pub block_assembler: OpBlockAssembler<ChainSpec>,
76    #[doc(hidden)]
77    pub _pd: core::marker::PhantomData<N>,
78}
79
80impl<ChainSpec, N: NodePrimitives, R: Clone, EvmFactory: Clone> Clone
81    for OpEvmConfig<ChainSpec, N, R, EvmFactory>
82{
83    fn clone(&self) -> Self {
84        Self {
85            executor_factory: self.executor_factory.clone(),
86            block_assembler: self.block_assembler.clone(),
87            _pd: self._pd,
88        }
89    }
90}
91
92impl<ChainSpec: OpHardforks> OpEvmConfig<ChainSpec> {
93    /// Creates a new [`OpEvmConfig`] with the given chain spec for OP chains.
94    pub fn optimism(chain_spec: Arc<ChainSpec>) -> Self {
95        Self::new(chain_spec, OpRethReceiptBuilder::default())
96    }
97}
98
99impl<ChainSpec: OpHardforks, N: NodePrimitives, R> OpEvmConfig<ChainSpec, N, R> {
100    /// Creates a new [`OpEvmConfig`] with the given chain spec.
101    pub fn new(chain_spec: Arc<ChainSpec>, receipt_builder: R) -> Self {
102        Self {
103            block_assembler: OpBlockAssembler::new(chain_spec.clone()),
104            executor_factory: OpBlockExecutorFactory::new(
105                receipt_builder,
106                chain_spec,
107                OpEvmFactory::default(),
108            ),
109            _pd: core::marker::PhantomData,
110        }
111    }
112}
113
114impl<ChainSpec, N, R, EvmFactory> OpEvmConfig<ChainSpec, N, R, EvmFactory>
115where
116    ChainSpec: OpHardforks,
117    N: NodePrimitives,
118{
119    /// Returns the chain spec associated with this configuration.
120    pub const fn chain_spec(&self) -> &Arc<ChainSpec> {
121        self.executor_factory.spec()
122    }
123}
124
125impl<ChainSpec, N, R, EvmF> ConfigureEvm for OpEvmConfig<ChainSpec, N, R, EvmF>
126where
127    ChainSpec: EthChainSpec<Header = Header> + OpHardforks,
128    N: NodePrimitives<
129        Receipt = R::Receipt,
130        SignedTx = R::Transaction,
131        BlockHeader = Header,
132        BlockBody = alloy_consensus::BlockBody<R::Transaction>,
133        Block = alloy_consensus::Block<R::Transaction>,
134    >,
135    OpTransaction<TxEnv>: FromRecoveredTx<N::SignedTx> + FromTxWithEncoded<N::SignedTx>,
136    R: OpReceiptBuilder<Receipt: DepositReceipt, Transaction: SignedTransaction>,
137    EvmF: EvmFactory<
138            Tx: FromRecoveredTx<R::Transaction>
139                    + FromTxWithEncoded<R::Transaction>
140                    + TransactionEnv
141                    + OpTxEnv,
142            Precompiles = PrecompilesMap,
143            Spec = OpSpecId,
144            BlockEnv = BlockEnv,
145        > + Debug,
146    Self: Send + Sync + Unpin + Clone + 'static,
147{
148    type Primitives = N;
149    type Error = EIP1559ParamError;
150    type NextBlockEnvCtx = OpNextBlockEnvAttributes;
151    type BlockExecutorFactory = OpBlockExecutorFactory<R, Arc<ChainSpec>, EvmF>;
152    type BlockAssembler = OpBlockAssembler<ChainSpec>;
153
154    fn block_executor_factory(&self) -> &Self::BlockExecutorFactory {
155        &self.executor_factory
156    }
157
158    fn block_assembler(&self) -> &Self::BlockAssembler {
159        &self.block_assembler
160    }
161
162    fn evm_env(&self, header: &Header) -> Result<EvmEnv<OpSpecId>, Self::Error> {
163        Ok(EvmEnv::for_op_block(header, self.chain_spec(), self.chain_spec().chain().id()))
164    }
165
166    fn next_evm_env(
167        &self,
168        parent: &Header,
169        attributes: &Self::NextBlockEnvCtx,
170    ) -> Result<EvmEnv<OpSpecId>, Self::Error> {
171        Ok(EvmEnv::for_op_next_block(
172            parent,
173            NextEvmEnvAttributes {
174                timestamp: attributes.timestamp,
175                suggested_fee_recipient: attributes.suggested_fee_recipient,
176                prev_randao: attributes.prev_randao,
177                gas_limit: attributes.gas_limit,
178            },
179            self.chain_spec().next_block_base_fee(parent, attributes.timestamp).unwrap_or_default(),
180            self.chain_spec(),
181            self.chain_spec().chain().id(),
182        ))
183    }
184
185    fn context_for_block(
186        &self,
187        block: &'_ SealedBlock<N::Block>,
188    ) -> Result<OpBlockExecutionCtx, Self::Error> {
189        Ok(OpBlockExecutionCtx {
190            parent_hash: block.header().parent_hash(),
191            parent_beacon_block_root: block.header().parent_beacon_block_root(),
192            extra_data: block.header().extra_data().clone(),
193        })
194    }
195
196    fn context_for_next_block(
197        &self,
198        parent: &SealedHeader<N::BlockHeader>,
199        attributes: Self::NextBlockEnvCtx,
200    ) -> Result<OpBlockExecutionCtx, Self::Error> {
201        Ok(OpBlockExecutionCtx {
202            parent_hash: parent.hash(),
203            parent_beacon_block_root: attributes.parent_beacon_block_root,
204            extra_data: attributes.extra_data,
205        })
206    }
207}
208
209#[cfg(feature = "std")]
210impl<ChainSpec, N, R> ConfigureEngineEvm<OpExecutionData> for OpEvmConfig<ChainSpec, N, R>
211where
212    ChainSpec: EthChainSpec<Header = Header> + OpHardforks,
213    N: NodePrimitives<
214        Receipt = R::Receipt,
215        SignedTx = R::Transaction,
216        BlockHeader = Header,
217        BlockBody = alloy_consensus::BlockBody<R::Transaction>,
218        Block = alloy_consensus::Block<R::Transaction>,
219    >,
220    OpTransaction<TxEnv>: FromRecoveredTx<N::SignedTx> + FromTxWithEncoded<N::SignedTx>,
221    R: OpReceiptBuilder<Receipt: DepositReceipt, Transaction: SignedTransaction>,
222    Self: Send + Sync + Unpin + Clone + 'static,
223{
224    fn evm_env_for_payload(
225        &self,
226        payload: &OpExecutionData,
227    ) -> Result<EvmEnvFor<Self>, Self::Error> {
228        let timestamp = payload.payload.timestamp();
229        let block_number = payload.payload.block_number();
230
231        let spec = revm_spec_by_timestamp_after_bedrock(self.chain_spec(), timestamp);
232
233        let cfg_env = CfgEnv::new().with_chain_id(self.chain_spec().chain().id()).with_spec(spec);
234
235        let blob_excess_gas_and_price = spec
236            .into_eth_spec()
237            .is_enabled_in(SpecId::CANCUN)
238            .then_some(BlobExcessGasAndPrice { excess_blob_gas: 0, blob_gasprice: 1 });
239
240        let block_env = BlockEnv {
241            number: U256::from(block_number),
242            beneficiary: payload.payload.as_v1().fee_recipient,
243            timestamp: U256::from(timestamp),
244            difficulty: if spec.into_eth_spec() >= SpecId::MERGE {
245                U256::ZERO
246            } else {
247                payload.payload.as_v1().prev_randao.into()
248            },
249            prevrandao: (spec.into_eth_spec() >= SpecId::MERGE)
250                .then(|| payload.payload.as_v1().prev_randao),
251            gas_limit: payload.payload.as_v1().gas_limit,
252            basefee: payload.payload.as_v1().base_fee_per_gas.to(),
253            // EIP-4844 excess blob gas of this block, introduced in Cancun
254            blob_excess_gas_and_price,
255        };
256
257        Ok(EvmEnv { cfg_env, block_env })
258    }
259
260    fn context_for_payload<'a>(
261        &self,
262        payload: &'a OpExecutionData,
263    ) -> Result<ExecutionCtxFor<'a, Self>, Self::Error> {
264        Ok(OpBlockExecutionCtx {
265            parent_hash: payload.parent_hash(),
266            parent_beacon_block_root: payload.sidecar.parent_beacon_block_root(),
267            extra_data: payload.payload.as_v1().extra_data.clone(),
268        })
269    }
270
271    fn tx_iterator_for_payload(
272        &self,
273        payload: &OpExecutionData,
274    ) -> Result<impl ExecutableTxIterator<Self>, Self::Error> {
275        let transactions = payload.payload.transactions().clone();
276        let convert = |encoded: Bytes| {
277            let tx = TxTy::<Self::Primitives>::decode_2718_exact(encoded.as_ref())
278                .map_err(AnyError::new)?;
279            let signer = tx.try_recover().map_err(AnyError::new)?;
280            Ok::<_, AnyError>(WithEncoded::new(encoded, tx.with_signer(signer)))
281        };
282
283        Ok((transactions, convert))
284    }
285}
286
287#[cfg(test)]
288mod tests {
289    use super::*;
290    use alloy_consensus::{Header, Receipt};
291    use alloy_eips::eip7685::Requests;
292    use alloy_genesis::Genesis;
293    use alloy_primitives::{bytes, map::HashMap, Address, LogData, B256};
294    use op_revm::OpSpecId;
295    use reth_chainspec::ChainSpec;
296    use reth_evm::execute::ProviderError;
297    use reth_execution_types::{
298        AccountRevertInit, BundleStateInit, Chain, ExecutionOutcome, RevertsInit,
299    };
300    use reth_optimism_chainspec::{OpChainSpec, BASE_MAINNET};
301    use reth_optimism_primitives::{OpBlock, OpPrimitives, OpReceipt};
302    use reth_primitives_traits::{Account, RecoveredBlock};
303    use revm::{
304        database::{BundleState, CacheDB},
305        database_interface::EmptyDBTyped,
306        inspector::NoOpInspector,
307        primitives::Log,
308        state::AccountInfo,
309    };
310    use std::sync::Arc;
311
312    fn test_evm_config() -> OpEvmConfig {
313        OpEvmConfig::optimism(BASE_MAINNET.clone())
314    }
315
316    #[test]
317    fn test_fill_cfg_and_block_env() {
318        // Create a default header
319        let header = Header::default();
320
321        // Build the ChainSpec for Ethereum mainnet, activating London, Paris, and Shanghai
322        // hardforks
323        let chain_spec = ChainSpec::builder()
324            .chain(0.into())
325            .genesis(Genesis::default())
326            .london_activated()
327            .paris_activated()
328            .shanghai_activated()
329            .build();
330
331        // Use the `OpEvmConfig` to create the `cfg_env` and `block_env` based on the ChainSpec,
332        // Header, and total difficulty
333        let EvmEnv { cfg_env, .. } =
334            OpEvmConfig::optimism(Arc::new(OpChainSpec { inner: chain_spec.clone() }))
335                .evm_env(&header)
336                .unwrap();
337
338        // Assert that the chain ID in the `cfg_env` is correctly set to the chain ID of the
339        // ChainSpec
340        assert_eq!(cfg_env.chain_id, chain_spec.chain().id());
341    }
342
343    #[test]
344    fn test_evm_with_env_default_spec() {
345        let evm_config = test_evm_config();
346
347        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
348
349        let evm_env = EvmEnv::default();
350
351        let evm = evm_config.evm_with_env(db, evm_env.clone());
352
353        // Check that the EVM environment
354        assert_eq!(evm.cfg, evm_env.cfg_env);
355    }
356
357    #[test]
358    fn test_evm_with_env_custom_cfg() {
359        let evm_config = test_evm_config();
360
361        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
362
363        // Create a custom configuration environment with a chain ID of 111
364        let cfg = CfgEnv::new().with_chain_id(111).with_spec(OpSpecId::default());
365
366        let evm_env = EvmEnv { cfg_env: cfg.clone(), ..Default::default() };
367
368        let evm = evm_config.evm_with_env(db, evm_env);
369
370        // Check that the EVM environment is initialized with the custom environment
371        assert_eq!(evm.cfg, cfg);
372    }
373
374    #[test]
375    fn test_evm_with_env_custom_block_and_tx() {
376        let evm_config = test_evm_config();
377
378        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
379
380        // Create customs block and tx env
381        let block = BlockEnv {
382            basefee: 1000,
383            gas_limit: 10_000_000,
384            number: U256::from(42),
385            ..Default::default()
386        };
387
388        let evm_env = EvmEnv { block_env: block, ..Default::default() };
389
390        let evm = evm_config.evm_with_env(db, evm_env.clone());
391
392        // Verify that the block and transaction environments are set correctly
393        assert_eq!(evm.block, evm_env.block_env);
394    }
395
396    #[test]
397    fn test_evm_with_spec_id() {
398        let evm_config = test_evm_config();
399
400        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
401
402        let evm_env =
403            EvmEnv { cfg_env: CfgEnv::new().with_spec(OpSpecId::ECOTONE), ..Default::default() };
404
405        let evm = evm_config.evm_with_env(db, evm_env.clone());
406
407        assert_eq!(evm.cfg, evm_env.cfg_env);
408    }
409
410    #[test]
411    fn test_evm_with_env_and_default_inspector() {
412        let evm_config = test_evm_config();
413        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
414
415        let evm_env = EvmEnv { cfg_env: Default::default(), ..Default::default() };
416
417        let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
418
419        // Check that the EVM environment is set to default values
420        assert_eq!(evm.block, evm_env.block_env);
421        assert_eq!(evm.cfg, evm_env.cfg_env);
422    }
423
424    #[test]
425    fn test_evm_with_env_inspector_and_custom_cfg() {
426        let evm_config = test_evm_config();
427        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
428
429        let cfg = CfgEnv::new().with_chain_id(111).with_spec(OpSpecId::default());
430        let block = BlockEnv::default();
431        let evm_env = EvmEnv { block_env: block, cfg_env: cfg.clone() };
432
433        let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
434
435        // Check that the EVM environment is set with custom configuration
436        assert_eq!(evm.cfg, cfg);
437        assert_eq!(evm.block, evm_env.block_env);
438    }
439
440    #[test]
441    fn test_evm_with_env_inspector_and_custom_block_tx() {
442        let evm_config = test_evm_config();
443        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
444
445        // Create custom block and tx environment
446        let block = BlockEnv {
447            basefee: 1000,
448            gas_limit: 10_000_000,
449            number: U256::from(42),
450            ..Default::default()
451        };
452        let evm_env = EvmEnv { block_env: block, ..Default::default() };
453
454        let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
455
456        // Verify that the block and transaction environments are set correctly
457        assert_eq!(evm.block, evm_env.block_env);
458    }
459
460    #[test]
461    fn test_evm_with_env_inspector_and_spec_id() {
462        let evm_config = test_evm_config();
463        let db = CacheDB::<EmptyDBTyped<ProviderError>>::default();
464
465        let evm_env =
466            EvmEnv { cfg_env: CfgEnv::new().with_spec(OpSpecId::ECOTONE), ..Default::default() };
467
468        let evm = evm_config.evm_with_env_and_inspector(db, evm_env.clone(), NoOpInspector {});
469
470        // Check that the spec ID is set properly
471        assert_eq!(evm.cfg, evm_env.cfg_env);
472        assert_eq!(evm.block, evm_env.block_env);
473    }
474
475    #[test]
476    fn receipts_by_block_hash() {
477        // Create a default recovered block
478        let block: RecoveredBlock<OpBlock> = Default::default();
479
480        // Define block hashes for block1 and block2
481        let block1_hash = B256::new([0x01; 32]);
482        let block2_hash = B256::new([0x02; 32]);
483
484        // Clone the default block into block1 and block2
485        let mut block1 = block.clone();
486        let mut block2 = block;
487
488        // Set the hashes of block1 and block2
489        block1.set_block_number(10);
490        block1.set_hash(block1_hash);
491
492        block2.set_block_number(11);
493        block2.set_hash(block2_hash);
494
495        // Create a random receipt object, receipt1
496        let receipt1 = OpReceipt::Legacy(Receipt::<Log> {
497            cumulative_gas_used: 46913,
498            logs: vec![],
499            status: true.into(),
500        });
501
502        // Create another random receipt object, receipt2
503        let receipt2 = OpReceipt::Legacy(Receipt::<Log> {
504            cumulative_gas_used: 1325345,
505            logs: vec![],
506            status: true.into(),
507        });
508
509        // Create a Receipts object with a vector of receipt vectors
510        let receipts = vec![vec![receipt1.clone()], vec![receipt2]];
511
512        // Create an ExecutionOutcome object with the created bundle, receipts, an empty requests
513        // vector, and first_block set to 10
514        let execution_outcome = ExecutionOutcome::<OpReceipt> {
515            bundle: Default::default(),
516            receipts,
517            requests: vec![],
518            first_block: 10,
519        };
520
521        // Create a Chain object with a BTreeMap of blocks mapped to their block numbers,
522        // including block1_hash and block2_hash, and the execution_outcome
523        let chain: Chain<OpPrimitives> =
524            Chain::new([block1, block2], execution_outcome.clone(), None);
525
526        // Assert that the proper receipt vector is returned for block1_hash
527        assert_eq!(chain.receipts_by_block_hash(block1_hash), Some(vec![&receipt1]));
528
529        // Create an ExecutionOutcome object with a single receipt vector containing receipt1
530        let execution_outcome1 = ExecutionOutcome {
531            bundle: Default::default(),
532            receipts: vec![vec![receipt1]],
533            requests: vec![],
534            first_block: 10,
535        };
536
537        // Assert that the execution outcome at the first block contains only the first receipt
538        assert_eq!(chain.execution_outcome_at_block(10), Some(execution_outcome1));
539
540        // Assert that the execution outcome at the tip block contains the whole execution outcome
541        assert_eq!(chain.execution_outcome_at_block(11), Some(execution_outcome));
542    }
543
544    #[test]
545    fn test_initialization() {
546        // Create a new BundleState object with initial data
547        let bundle = BundleState::new(
548            vec![(Address::new([2; 20]), None, Some(AccountInfo::default()), HashMap::default())],
549            vec![vec![(Address::new([2; 20]), None, vec![])]],
550            vec![],
551        );
552
553        // Create a Receipts object with a vector of receipt vectors
554        let receipts = vec![vec![Some(OpReceipt::Legacy(Receipt::<Log> {
555            cumulative_gas_used: 46913,
556            logs: vec![],
557            status: true.into(),
558        }))]];
559
560        // Create a Requests object with a vector of requests
561        let requests = vec![Requests::new(vec![bytes!("dead"), bytes!("beef"), bytes!("beebee")])];
562
563        // Define the first block number
564        let first_block = 123;
565
566        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
567        // first_block
568        let exec_res = ExecutionOutcome {
569            bundle: bundle.clone(),
570            receipts: receipts.clone(),
571            requests: requests.clone(),
572            first_block,
573        };
574
575        // Assert that creating a new ExecutionOutcome using the constructor matches exec_res
576        assert_eq!(
577            ExecutionOutcome::new(bundle, receipts.clone(), first_block, requests.clone()),
578            exec_res
579        );
580
581        // Create a BundleStateInit object and insert initial data
582        let mut state_init: BundleStateInit = HashMap::default();
583        state_init
584            .insert(Address::new([2; 20]), (None, Some(Account::default()), HashMap::default()));
585
586        // Create a HashMap for account reverts and insert initial data
587        let mut revert_inner: HashMap<Address, AccountRevertInit> = HashMap::default();
588        revert_inner.insert(Address::new([2; 20]), (None, vec![]));
589
590        // Create a RevertsInit object and insert the revert_inner data
591        let mut revert_init: RevertsInit = HashMap::default();
592        revert_init.insert(123, revert_inner);
593
594        // Assert that creating a new ExecutionOutcome using the new_init method matches
595        // exec_res
596        assert_eq!(
597            ExecutionOutcome::new_init(
598                state_init,
599                revert_init,
600                vec![],
601                receipts,
602                first_block,
603                requests,
604            ),
605            exec_res
606        );
607    }
608
609    #[test]
610    fn test_block_number_to_index() {
611        // Create a Receipts object with a vector of receipt vectors
612        let receipts = vec![vec![Some(OpReceipt::Legacy(Receipt::<Log> {
613            cumulative_gas_used: 46913,
614            logs: vec![],
615            status: true.into(),
616        }))]];
617
618        // Define the first block number
619        let first_block = 123;
620
621        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
622        // first_block
623        let exec_res = ExecutionOutcome {
624            bundle: Default::default(),
625            receipts,
626            requests: vec![],
627            first_block,
628        };
629
630        // Test before the first block
631        assert_eq!(exec_res.block_number_to_index(12), None);
632
633        // Test after the first block but index larger than receipts length
634        assert_eq!(exec_res.block_number_to_index(133), None);
635
636        // Test after the first block
637        assert_eq!(exec_res.block_number_to_index(123), Some(0));
638    }
639
640    #[test]
641    fn test_get_logs() {
642        // Create a Receipts object with a vector of receipt vectors
643        let receipts = vec![vec![OpReceipt::Legacy(Receipt::<Log> {
644            cumulative_gas_used: 46913,
645            logs: vec![Log::<LogData>::default()],
646            status: true.into(),
647        })]];
648
649        // Define the first block number
650        let first_block = 123;
651
652        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
653        // first_block
654        let exec_res = ExecutionOutcome {
655            bundle: Default::default(),
656            receipts,
657            requests: vec![],
658            first_block,
659        };
660
661        // Get logs for block number 123
662        let logs: Vec<&Log> = exec_res.logs(123).unwrap().collect();
663
664        // Assert that the logs match the expected logs
665        assert_eq!(logs, vec![&Log::<LogData>::default()]);
666    }
667
668    #[test]
669    fn test_receipts_by_block() {
670        // Create a Receipts object with a vector of receipt vectors
671        let receipts = vec![vec![Some(OpReceipt::Legacy(Receipt::<Log> {
672            cumulative_gas_used: 46913,
673            logs: vec![Log::<LogData>::default()],
674            status: true.into(),
675        }))]];
676
677        // Define the first block number
678        let first_block = 123;
679
680        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
681        // first_block
682        let exec_res = ExecutionOutcome {
683            bundle: Default::default(), // Default value for bundle
684            receipts,                   // Include the created receipts
685            requests: vec![],           // Empty vector for requests
686            first_block,                // Set the first block number
687        };
688
689        // Get receipts for block number 123 and convert the result into a vector
690        let receipts_by_block: Vec<_> = exec_res.receipts_by_block(123).iter().collect();
691
692        // Assert that the receipts for block number 123 match the expected receipts
693        assert_eq!(
694            receipts_by_block,
695            vec![&Some(OpReceipt::Legacy(Receipt::<Log> {
696                cumulative_gas_used: 46913,
697                logs: vec![Log::<LogData>::default()],
698                status: true.into(),
699            }))]
700        );
701    }
702
703    #[test]
704    fn test_receipts_len() {
705        // Create a Receipts object with a vector of receipt vectors
706        let receipts = vec![vec![Some(OpReceipt::Legacy(Receipt::<Log> {
707            cumulative_gas_used: 46913,
708            logs: vec![Log::<LogData>::default()],
709            status: true.into(),
710        }))]];
711
712        // Create an empty Receipts object
713        let receipts_empty = vec![];
714
715        // Define the first block number
716        let first_block = 123;
717
718        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
719        // first_block
720        let exec_res = ExecutionOutcome {
721            bundle: Default::default(), // Default value for bundle
722            receipts,                   // Include the created receipts
723            requests: vec![],           // Empty vector for requests
724            first_block,                // Set the first block number
725        };
726
727        // Assert that the length of receipts in exec_res is 1
728        assert_eq!(exec_res.len(), 1);
729
730        // Assert that exec_res is not empty
731        assert!(!exec_res.is_empty());
732
733        // Create a ExecutionOutcome object with an empty Receipts object
734        let exec_res_empty_receipts: ExecutionOutcome<OpReceipt> = ExecutionOutcome {
735            bundle: Default::default(), // Default value for bundle
736            receipts: receipts_empty,   // Include the empty receipts
737            requests: vec![],           // Empty vector for requests
738            first_block,                // Set the first block number
739        };
740
741        // Assert that the length of receipts in exec_res_empty_receipts is 0
742        assert_eq!(exec_res_empty_receipts.len(), 0);
743
744        // Assert that exec_res_empty_receipts is empty
745        assert!(exec_res_empty_receipts.is_empty());
746    }
747
748    #[test]
749    fn test_revert_to() {
750        // Create a random receipt object
751        let receipt = OpReceipt::Legacy(Receipt::<Log> {
752            cumulative_gas_used: 46913,
753            logs: vec![],
754            status: true.into(),
755        });
756
757        // Create a Receipts object with a vector of receipt vectors
758        let receipts = vec![vec![Some(receipt.clone())], vec![Some(receipt.clone())]];
759
760        // Define the first block number
761        let first_block = 123;
762
763        // Create a request.
764        let request = bytes!("deadbeef");
765
766        // Create a vector of Requests containing the request.
767        let requests =
768            vec![Requests::new(vec![request.clone()]), Requests::new(vec![request.clone()])];
769
770        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
771        // first_block
772        let mut exec_res =
773            ExecutionOutcome { bundle: Default::default(), receipts, requests, first_block };
774
775        // Assert that the revert_to method returns true when reverting to the initial block number.
776        assert!(exec_res.revert_to(123));
777
778        // Assert that the receipts are properly cut after reverting to the initial block number.
779        assert_eq!(exec_res.receipts, vec![vec![Some(receipt)]]);
780
781        // Assert that the requests are properly cut after reverting to the initial block number.
782        assert_eq!(exec_res.requests, vec![Requests::new(vec![request])]);
783
784        // Assert that the revert_to method returns false when attempting to revert to a block
785        // number greater than the initial block number.
786        assert!(!exec_res.revert_to(133));
787
788        // Assert that the revert_to method returns false when attempting to revert to a block
789        // number less than the initial block number.
790        assert!(!exec_res.revert_to(10));
791    }
792
793    #[test]
794    fn test_extend_execution_outcome() {
795        // Create a Receipt object with specific attributes.
796        let receipt = OpReceipt::Legacy(Receipt::<Log> {
797            cumulative_gas_used: 46913,
798            logs: vec![],
799            status: true.into(),
800        });
801
802        // Create a Receipts object containing the receipt.
803        let receipts = vec![vec![Some(receipt.clone())]];
804
805        // Create a request.
806        let request = bytes!("deadbeef");
807
808        // Create a vector of Requests containing the request.
809        let requests = vec![Requests::new(vec![request.clone()])];
810
811        // Define the initial block number.
812        let first_block = 123;
813
814        // Create an ExecutionOutcome object.
815        let mut exec_res =
816            ExecutionOutcome { bundle: Default::default(), receipts, requests, first_block };
817
818        // Extend the ExecutionOutcome object by itself.
819        exec_res.extend(exec_res.clone());
820
821        // Assert the extended ExecutionOutcome matches the expected outcome.
822        assert_eq!(
823            exec_res,
824            ExecutionOutcome {
825                bundle: Default::default(),
826                receipts: vec![vec![Some(receipt.clone())], vec![Some(receipt)]],
827                requests: vec![Requests::new(vec![request.clone()]), Requests::new(vec![request])],
828                first_block: 123,
829            }
830        );
831    }
832
833    #[test]
834    fn test_split_at_execution_outcome() {
835        // Create a random receipt object
836        let receipt = OpReceipt::Legacy(Receipt::<Log> {
837            cumulative_gas_used: 46913,
838            logs: vec![],
839            status: true.into(),
840        });
841
842        // Create a Receipts object with a vector of receipt vectors
843        let receipts = vec![
844            vec![Some(receipt.clone())],
845            vec![Some(receipt.clone())],
846            vec![Some(receipt.clone())],
847        ];
848
849        // Define the first block number
850        let first_block = 123;
851
852        // Create a request.
853        let request = bytes!("deadbeef");
854
855        // Create a vector of Requests containing the request.
856        let requests = vec![
857            Requests::new(vec![request.clone()]),
858            Requests::new(vec![request.clone()]),
859            Requests::new(vec![request.clone()]),
860        ];
861
862        // Create a ExecutionOutcome object with the created bundle, receipts, requests, and
863        // first_block
864        let exec_res =
865            ExecutionOutcome { bundle: Default::default(), receipts, requests, first_block };
866
867        // Split the ExecutionOutcome at block number 124
868        let result = exec_res.clone().split_at(124);
869
870        // Define the expected lower ExecutionOutcome after splitting
871        let lower_execution_outcome = ExecutionOutcome {
872            bundle: Default::default(),
873            receipts: vec![vec![Some(receipt.clone())]],
874            requests: vec![Requests::new(vec![request.clone()])],
875            first_block,
876        };
877
878        // Define the expected higher ExecutionOutcome after splitting
879        let higher_execution_outcome = ExecutionOutcome {
880            bundle: Default::default(),
881            receipts: vec![vec![Some(receipt.clone())], vec![Some(receipt)]],
882            requests: vec![Requests::new(vec![request.clone()]), Requests::new(vec![request])],
883            first_block: 124,
884        };
885
886        // Assert that the split result matches the expected lower and higher outcomes
887        assert_eq!(result.0, Some(lower_execution_outcome));
888        assert_eq!(result.1, higher_execution_outcome);
889
890        // Assert that splitting at the first block number returns None for the lower outcome
891        assert_eq!(exec_res.clone().split_at(123), (None, exec_res));
892    }
893}