revm-handler 18.1.0

Revm handler crates
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
use context_interface::{
    result::{InvalidHeader, InvalidTransaction},
    transaction::{Transaction, TransactionType},
    Block, Cfg, ContextTr,
};
use core::cmp;
use interpreter::{instructions::calculate_initial_tx_gas_for_tx, InitialAndFloorGas};
use primitives::{eip4844, hardfork::SpecId, B256};

/// Validates the execution environment including block and transaction parameters.
pub fn validate_env<CTX: ContextTr, ERROR: From<InvalidHeader> + From<InvalidTransaction>>(
    context: CTX,
) -> Result<(), ERROR> {
    let spec = context.cfg().spec().into();
    // `prevrandao` is required for the merge
    if spec.is_enabled_in(SpecId::MERGE) && context.block().prevrandao().is_none() {
        return Err(InvalidHeader::PrevrandaoNotSet.into());
    }
    // `excess_blob_gas` is required for Cancun
    if spec.is_enabled_in(SpecId::CANCUN) && context.block().blob_excess_gas_and_price().is_none() {
        return Err(InvalidHeader::ExcessBlobGasNotSet.into());
    }
    validate_tx_env::<CTX>(context, spec).map_err(Into::into)
}

/// Validate legacy transaction gas price against basefee.
#[inline]
pub fn validate_legacy_gas_price(
    gas_price: u128,
    base_fee: Option<u128>,
) -> Result<(), InvalidTransaction> {
    // Gas price must be at least the basefee.
    if let Some(base_fee) = base_fee {
        if gas_price < base_fee {
            return Err(InvalidTransaction::GasPriceLessThanBasefee);
        }
    }
    Ok(())
}

/// Validate transaction that has EIP-1559 priority fee
pub fn validate_priority_fee_tx(
    max_fee: u128,
    max_priority_fee: u128,
    base_fee: Option<u128>,
    disable_priority_fee_check: bool,
) -> Result<(), InvalidTransaction> {
    if !disable_priority_fee_check && max_priority_fee > max_fee {
        // Or gas_max_fee for eip1559
        return Err(InvalidTransaction::PriorityFeeGreaterThanMaxFee);
    }

    // Check minimal cost against basefee
    if let Some(base_fee) = base_fee {
        let effective_gas_price = cmp::min(max_fee, base_fee.saturating_add(max_priority_fee));
        if effective_gas_price < base_fee {
            return Err(InvalidTransaction::GasPriceLessThanBasefee);
        }
    }

    Ok(())
}

/// Validate priority fee for transactions that support EIP-1559 (Eip1559, Eip4844, Eip7702).
#[inline]
fn validate_priority_fee_for_tx<TX: Transaction>(
    tx: TX,
    base_fee: Option<u128>,
    disable_priority_fee_check: bool,
) -> Result<(), InvalidTransaction> {
    validate_priority_fee_tx(
        tx.max_fee_per_gas(),
        tx.max_priority_fee_per_gas().unwrap_or_default(),
        base_fee,
        disable_priority_fee_check,
    )
}

/// Validate EIP-4844 transaction.
pub fn validate_eip4844_tx(
    blobs: &[B256],
    max_blob_fee: u128,
    block_blob_gas_price: u128,
    max_blobs: Option<u64>,
) -> Result<(), InvalidTransaction> {
    // Ensure that the user was willing to at least pay the current blob gasprice
    if block_blob_gas_price > max_blob_fee {
        return Err(InvalidTransaction::BlobGasPriceGreaterThanMax {
            block_blob_gas_price,
            tx_max_fee_per_blob_gas: max_blob_fee,
        });
    }

    // There must be at least one blob
    if blobs.is_empty() {
        return Err(InvalidTransaction::EmptyBlobs);
    }

    // All versioned blob hashes must start with VERSIONED_HASH_VERSION_KZG
    for blob in blobs {
        if blob[0] != eip4844::VERSIONED_HASH_VERSION_KZG {
            return Err(InvalidTransaction::BlobVersionNotSupported);
        }
    }

    // Ensure the total blob gas spent is at most equal to the limit
    // assert blob_gas_used <= MAX_BLOB_GAS_PER_BLOCK
    if let Some(max_blobs) = max_blobs {
        if blobs.len() > max_blobs as usize {
            return Err(InvalidTransaction::TooManyBlobs {
                have: blobs.len(),
                max: max_blobs as usize,
            });
        }
    }
    Ok(())
}

/// Validate transaction against block and configuration for mainnet.
pub fn validate_tx_env<CTX: ContextTr>(
    context: CTX,
    spec_id: SpecId,
) -> Result<(), InvalidTransaction> {
    // Check if the transaction's chain id is correct
    let tx = context.tx();
    let tx_type = tx.tx_type();

    let base_fee = if context.cfg().is_base_fee_check_disabled() {
        None
    } else {
        Some(context.block().basefee() as u128)
    };

    let tx_type = TransactionType::from(tx_type);

    // Check chain_id if config is enabled.
    // EIP-155: Simple replay attack protection
    if context.cfg().tx_chain_id_check() {
        if let Some(chain_id) = tx.chain_id() {
            if chain_id != context.cfg().chain_id() {
                return Err(InvalidTransaction::InvalidChainId);
            }
        } else if !tx_type.is_legacy() && !tx_type.is_custom() {
            // Legacy transaction are the only one that can omit chain_id.
            return Err(InvalidTransaction::MissingChainId);
        }
    }

    // tx gas cap is not enforced if state gas is enabled.
    if !context.cfg().is_amsterdam_eip8037_enabled() {
        // EIP-7825: Transaction Gas Limit Cap
        let cap = context.cfg().tx_gas_limit_cap();
        if tx.gas_limit() > cap {
            return Err(InvalidTransaction::TxGasLimitGreaterThanCap {
                gas_limit: tx.gas_limit(),
                cap,
            });
        }
    }

    let disable_priority_fee_check = context.cfg().is_priority_fee_check_disabled();

    match tx_type {
        TransactionType::Legacy => {
            validate_legacy_gas_price(tx.gas_price(), base_fee)?;
        }
        TransactionType::Eip2930 => {
            // Enabled in BERLIN hardfork
            if !spec_id.is_enabled_in(SpecId::BERLIN) {
                return Err(InvalidTransaction::Eip2930NotSupported);
            }
            validate_legacy_gas_price(tx.gas_price(), base_fee)?;
        }
        TransactionType::Eip1559 => {
            if !spec_id.is_enabled_in(SpecId::LONDON) {
                return Err(InvalidTransaction::Eip1559NotSupported);
            }
            validate_priority_fee_for_tx(tx, base_fee, disable_priority_fee_check)?;
        }
        TransactionType::Eip4844 => {
            if !spec_id.is_enabled_in(SpecId::CANCUN) {
                return Err(InvalidTransaction::Eip4844NotSupported);
            }

            validate_priority_fee_for_tx(tx, base_fee, disable_priority_fee_check)?;

            validate_eip4844_tx(
                tx.blob_versioned_hashes(),
                tx.max_fee_per_blob_gas(),
                context.block().blob_gasprice().unwrap_or_default(),
                context.cfg().max_blobs_per_tx(),
            )?;
        }
        TransactionType::Eip7702 => {
            // Check if EIP-7702 transaction is enabled.
            if !spec_id.is_enabled_in(SpecId::PRAGUE) {
                return Err(InvalidTransaction::Eip7702NotSupported);
            }

            validate_priority_fee_for_tx(tx, base_fee, disable_priority_fee_check)?;

            let auth_list_len = tx.authorization_list_len();
            // The transaction is considered invalid if the length of authorization_list is zero.
            if auth_list_len == 0 {
                return Err(InvalidTransaction::EmptyAuthorizationList);
            }
        }
        TransactionType::Custom => {
            // Custom transaction type check is not done here.
        }
    };

    // Check if gas_limit is more than block_gas_limit
    // TODO(eip8037) should we enforce to `min(tx.gas_limit(), 16M) < block.gas_limit`?
    // This would enforce that regular gas is constrained.
    if !context.cfg().is_block_gas_limit_disabled() && tx.gas_limit() > context.block().gas_limit()
    {
        return Err(InvalidTransaction::CallerGasLimitMoreThanBlock);
    }

    // EIP-3860: Limit and meter initcode. Still valid with EIP-7907 and increase of initcode size.
    if spec_id.is_enabled_in(SpecId::SHANGHAI)
        && tx.kind().is_create()
        && tx.input().len() > context.cfg().max_initcode_size()
    {
        return Err(InvalidTransaction::CreateInitCodeSizeLimit);
    }

    // Check that the transaction's nonce is not at the maximum value.
    // Incrementing the nonce would overflow. Can't happen in the real world.
    if tx.nonce() == u64::MAX {
        return Err(InvalidTransaction::NonceOverflowInTransaction);
    }

    Ok(())
}

/// Validate initial transaction gas.
pub fn validate_initial_tx_gas(
    tx: impl Transaction,
    spec: SpecId,
    is_eip7623_disabled: bool,
    is_amsterdam_eip8037_enabled: bool,
    tx_gas_limit_cap: u64,
) -> Result<InitialAndFloorGas, InvalidTransaction> {
    let mut gas = calculate_initial_tx_gas_for_tx(&tx, spec);

    if is_eip7623_disabled {
        gas.floor_gas = 0
    }

    // Additional check to see if limit is big enough to cover initial gas.
    if gas.initial_total_gas > tx.gas_limit() {
        return Err(InvalidTransaction::CallGasCostMoreThanGasLimit {
            gas_limit: tx.gas_limit(),
            initial_gas: gas.initial_total_gas,
        });
    }

    // EIP-7623: Increase calldata cost
    // floor gas should be less than gas limit.
    if spec.is_enabled_in(SpecId::PRAGUE) && gas.floor_gas > tx.gas_limit() {
        return Err(InvalidTransaction::GasFloorMoreThanGasLimit {
            gas_floor: gas.floor_gas,
            gas_limit: tx.gas_limit(),
        });
    };

    // EIP-8037: Regular gas is capped at TX_MAX_GAS_LIMIT.
    // Validate that both intrinsic regular gas and floor gas fit within the cap.
    // State gas is excluded — it uses its own reservoir.
    if is_amsterdam_eip8037_enabled && tx.gas_limit() > tx_gas_limit_cap {
        let min_regular_gas = gas.initial_regular_gas().max(gas.floor_gas);
        if min_regular_gas > tx_gas_limit_cap {
            return Err(InvalidTransaction::GasFloorMoreThanGasLimit {
                gas_floor: min_regular_gas,
                gas_limit: tx_gas_limit_cap,
            });
        }
    }

    Ok(gas)
}

#[cfg(test)]
mod tests {
    use crate::{api::ExecuteEvm, ExecuteCommitEvm, MainBuilder, MainContext};
    use bytecode::opcode;
    use context::{
        result::{EVMError, ExecutionResult, HaltReason, InvalidTransaction, Output},
        Context, ContextTr, TxEnv,
    };
    use database::{CacheDB, EmptyDB};
    use primitives::{address, eip3860, eip7954, hardfork::SpecId, Bytes, TxKind, B256};
    use state::{AccountInfo, Bytecode};

    fn deploy_contract(
        bytecode: Bytes,
        spec_id: Option<SpecId>,
    ) -> Result<ExecutionResult, EVMError<core::convert::Infallible>> {
        let ctx = Context::mainnet()
            .modify_cfg_chained(|c| {
                if let Some(spec_id) = spec_id {
                    c.set_spec_and_mainnet_gas_params(spec_id);
                }
            })
            .with_db(CacheDB::<EmptyDB>::default());

        let mut evm = ctx.build_mainnet();
        evm.transact_commit(
            TxEnv::builder()
                .kind(TxKind::Create)
                .data(bytecode.clone())
                .build()
                .unwrap(),
        )
    }

    #[test]
    fn test_eip3860_initcode_size_limit_failure() {
        let large_bytecode = vec![opcode::STOP; eip3860::MAX_INITCODE_SIZE + 1];
        let bytecode: Bytes = large_bytecode.into();
        let result = deploy_contract(bytecode, Some(SpecId::PRAGUE));
        assert!(matches!(
            result,
            Err(EVMError::Transaction(
                InvalidTransaction::CreateInitCodeSizeLimit
            ))
        ));
    }

    #[test]
    fn test_eip3860_initcode_size_limit_success_prague() {
        let large_bytecode = vec![opcode::STOP; eip3860::MAX_INITCODE_SIZE];
        let bytecode: Bytes = large_bytecode.into();
        let result = deploy_contract(bytecode, Some(SpecId::PRAGUE));
        assert!(matches!(result, Ok(ExecutionResult::Success { .. })));
    }

    #[test]
    fn test_eip7954_initcode_size_limit_failure_amsterdam() {
        let large_bytecode = vec![opcode::STOP; eip7954::MAX_INITCODE_SIZE + 1];
        let bytecode: Bytes = large_bytecode.into();
        let result = deploy_contract(bytecode, Some(SpecId::AMSTERDAM));
        assert!(matches!(
            result,
            Err(EVMError::Transaction(
                InvalidTransaction::CreateInitCodeSizeLimit
            ))
        ));
    }

    #[test]
    fn test_eip7954_initcode_size_limit_success_amsterdam() {
        let large_bytecode = vec![opcode::STOP; eip7954::MAX_INITCODE_SIZE];
        let bytecode: Bytes = large_bytecode.into();
        let result = deploy_contract(bytecode, Some(SpecId::AMSTERDAM));
        assert!(matches!(result, Ok(ExecutionResult::Success { .. })));
    }

    #[test]
    fn test_eip7954_initcode_between_old_and_new_limit() {
        // Size between old limit (0xC000) and new limit (0x10000):
        // should fail pre-Amsterdam, succeed at Amsterdam
        let size = eip3860::MAX_INITCODE_SIZE + 1; // 0xC001
        let large_bytecode = vec![opcode::STOP; size];

        // Pre-Amsterdam (Prague): should fail
        let bytecode: Bytes = large_bytecode.clone().into();
        let result = deploy_contract(bytecode, Some(SpecId::PRAGUE));
        assert!(matches!(
            result,
            Err(EVMError::Transaction(
                InvalidTransaction::CreateInitCodeSizeLimit
            ))
        ));

        // Amsterdam: should succeed
        let bytecode: Bytes = large_bytecode.into();
        let result = deploy_contract(bytecode, Some(SpecId::AMSTERDAM));
        assert!(matches!(result, Ok(ExecutionResult::Success { .. })));
    }

    #[test]
    fn test_eip7954_code_size_limit_failure() {
        // EIP-7954: MAX_CODE_SIZE = 0x8000
        // use the simplest method to return a contract code size greater than 0x8000
        // PUSH3 0x8001 (greater than 0x8000) - return size
        // PUSH1 0x00 - memory position 0
        // RETURN - return uninitialized memory, will be filled with 0
        let init_code = vec![
            0x62, 0x00, 0x80, 0x01, // PUSH3 0x8001 (greater than 0x8000)
            0x60, 0x00, // PUSH1 0
            0xf3, // RETURN
        ];
        let bytecode: Bytes = init_code.into();
        let result = deploy_contract(bytecode, Some(SpecId::AMSTERDAM));
        assert!(
            matches!(
                result,
                Ok(ExecutionResult::Halt {
                    reason: HaltReason::CreateContractSizeLimit,
                    ..
                },)
            ),
            "{result:?}"
        );
    }

    #[test]
    fn test_eip170_code_size_limit_failure() {
        // use the simplest method to return a contract code size greater than 0x6000
        // PUSH3 0x6001 (greater than 0x6000) - return size
        // PUSH1 0x00 - memory position 0
        // RETURN - return uninitialized memory, will be filled with 0
        let init_code = vec![
            0x62, 0x00, 0x60, 0x01, // PUSH3 0x6001 (greater than 0x6000)
            0x60, 0x00, // PUSH1 0
            0xf3, // RETURN
        ];
        let bytecode: Bytes = init_code.into();
        let result = deploy_contract(bytecode, Some(SpecId::PRAGUE));
        assert!(
            matches!(
                result,
                Ok(ExecutionResult::Halt {
                    reason: HaltReason::CreateContractSizeLimit,
                    ..
                },)
            ),
            "{result:?}"
        );
    }

    #[test]
    fn test_eip170_code_size_limit_success() {
        // use the  simplest method to return a contract code size equal to 0x6000
        // PUSH3 0x6000 - return size
        // PUSH1 0x00 - memory position 0
        // RETURN - return uninitialized memory, will be filled with 0
        let init_code = vec![
            0x62, 0x00, 0x60, 0x00, // PUSH3 0x6000
            0x60, 0x00, // PUSH1 0
            0xf3, // RETURN
        ];
        let bytecode: Bytes = init_code.into();
        let result = deploy_contract(bytecode, None);
        assert!(matches!(result, Ok(ExecutionResult::Success { .. },)));
    }

    #[test]
    fn test_eip170_create_opcode_size_limit_failure() {
        // 1. create a "factory" contract, which will use the CREATE opcode to create another large contract
        // 2. because the sub contract exceeds the EIP-170 limit, the CREATE operation should fail

        // the bytecode of the factory contract:
        // PUSH1 0x01      - the value for MSTORE
        // PUSH1 0x00      - the memory position
        // MSTORE          - store a non-zero value at the beginning of memory

        // PUSH3 0x6001    - the return size (exceeds 0x6000)
        // PUSH1 0x00      - the memory offset
        // PUSH1 0x00      - the amount of ETH sent
        // CREATE          - create contract instruction (create contract from current memory)

        // PUSH1 0x00      - the return value storage position
        // MSTORE          - store the address returned by CREATE to the memory position 0
        // PUSH1 0x20      - the return size (32 bytes)
        // PUSH1 0x00      - the return offset
        // RETURN          - return the result

        let factory_code = vec![
            // 1. store a non-zero value at the beginning of memory
            0x60, 0x01, // PUSH1 0x01
            0x60, 0x00, // PUSH1 0x00
            0x52, // MSTORE
            // 2. prepare to create a large contract
            0x62, 0x00, 0x60, 0x01, // PUSH3 0x6001 (exceeds 0x6000)
            0x60, 0x00, // PUSH1 0x00 (the memory offset)
            0x60, 0x00, // PUSH1 0x00 (the amount of ETH sent)
            0xf0, // CREATE
            // 3. store the address returned by CREATE to the memory position 0
            0x60, 0x00, // PUSH1 0x00
            0x52, // MSTORE (store the address returned by CREATE to the memory position 0)
            // 4. return the result
            0x60, 0x20, // PUSH1 0x20 (32 bytes)
            0x60, 0x00, // PUSH1 0x00
            0xf3, // RETURN
        ];

        // deploy factory contract
        let factory_bytecode: Bytes = factory_code.into();
        let factory_result = deploy_contract(factory_bytecode, Some(SpecId::PRAGUE))
            .expect("factory contract deployment failed");

        // get factory contract address
        let factory_address = match &factory_result {
            ExecutionResult::Success {
                output: Output::Create(_, Some(addr)),
                ..
            } => *addr,
            _ => panic!("factory contract deployment failed: {factory_result:?}"),
        };

        // call factory contract to create sub contract
        let tx_caller = address!("0x0000000000000000000000000000000000100000");
        let call_result = Context::mainnet()
            .with_db(CacheDB::<EmptyDB>::default())
            .build_mainnet()
            .transact_commit(
                TxEnv::builder()
                    .caller(tx_caller)
                    .kind(TxKind::Call(factory_address))
                    .data(Bytes::new())
                    .build()
                    .unwrap(),
            )
            .expect("call factory contract failed");

        match &call_result {
            ExecutionResult::Success { output, .. } => match output {
                Output::Call(bytes) => {
                    if !bytes.is_empty() {
                        assert!(
                            bytes.iter().all(|&b| b == 0),
                            "When CREATE operation failed, it should return all zero address"
                        );
                    }
                }
                _ => panic!("unexpected output type"),
            },
            _ => panic!("execution result is not Success"),
        }
    }

    #[test]
    fn test_eip170_create_opcode_size_limit_success() {
        // 1. create a "factory" contract, which will use the CREATE opcode to create another contract
        // 2. the sub contract generated by the factory contract does not exceed the EIP-170 limit, so it should be created successfully

        // the bytecode of the factory contract:
        // PUSH1 0x01      - the value for MSTORE
        // PUSH1 0x00      - the memory position
        // MSTORE          - store a non-zero value at the beginning of memory

        // PUSH3 0x6000    - the return size (0x6000)
        // PUSH1 0x00      - the memory offset
        // PUSH1 0x00      - the amount of ETH sent
        // CREATE          - create contract instruction (create contract from current memory)

        // PUSH1 0x00      - the return value storage position
        // MSTORE          - store the address returned by CREATE to the memory position 0
        // PUSH1 0x20      - the return size (32 bytes)
        // PUSH1 0x00      - the return offset
        // RETURN          - return the result

        let factory_code = vec![
            // 1. store a non-zero value at the beginning of memory
            0x60, 0x01, // PUSH1 0x01
            0x60, 0x00, // PUSH1 0x00
            0x52, // MSTORE
            // 2. prepare to create a contract
            0x62, 0x00, 0x60, 0x00, // PUSH3 0x6000 (0x6000)
            0x60, 0x00, // PUSH1 0x00 (the memory offset)
            0x60, 0x00, // PUSH1 0x00 (the amount of ETH sent)
            0xf0, // CREATE
            // 3. store the address returned by CREATE to the memory position 0
            0x60, 0x00, // PUSH1 0x00
            0x52, // MSTORE (store the address returned by CREATE to the memory position 0)
            // 4. return the result
            0x60, 0x20, // PUSH1 0x20 (32 bytes)
            0x60, 0x00, // PUSH1 0x00
            0xf3, // RETURN
        ];

        // deploy factory contract
        let factory_bytecode: Bytes = factory_code.into();
        let factory_result = deploy_contract(factory_bytecode, Some(SpecId::PRAGUE))
            .expect("factory contract deployment failed");
        // get factory contract address
        let factory_address = match &factory_result {
            ExecutionResult::Success {
                output: Output::Create(_, Some(addr)),
                ..
            } => *addr,
            _ => panic!("factory contract deployment failed: {factory_result:?}"),
        };

        // call factory contract to create sub contract
        let tx_caller = address!("0x0000000000000000000000000000000000100000");
        let call_result = Context::mainnet()
            .with_db(CacheDB::<EmptyDB>::default())
            .build_mainnet()
            .transact_commit(
                TxEnv::builder()
                    .caller(tx_caller)
                    .kind(TxKind::Call(factory_address))
                    .data(Bytes::new())
                    .build()
                    .unwrap(),
            )
            .expect("call factory contract failed");

        match &call_result {
            ExecutionResult::Success { output, .. } => {
                match output {
                    Output::Call(bytes) => {
                        // check if CREATE operation is successful (return non-zero address)
                        if !bytes.is_empty() {
                            assert!(bytes.iter().any(|&b| b != 0), "create sub contract failed");
                        }
                    }
                    _ => panic!("unexpected output type"),
                }
            }
            _ => panic!("execution result is not Success"),
        }
    }

    #[test]
    fn test_transact_many_with_transaction_index_error() {
        use context::result::TransactionIndexedError;

        let ctx = Context::mainnet().with_db(CacheDB::<EmptyDB>::default());
        let mut evm = ctx.build_mainnet();

        // Create a transaction that will fail (invalid gas limit)
        let invalid_tx = TxEnv::builder()
            .gas_limit(0) // This will cause a validation error
            .build()
            .unwrap();

        // Create a valid transaction
        let valid_tx = TxEnv::builder().gas_limit(100000).build().unwrap();

        // Test that the first transaction fails with index 0
        let result = evm.transact_many([invalid_tx.clone()].into_iter());
        assert!(matches!(
            result,
            Err(TransactionIndexedError {
                transaction_index: 0,
                ..
            })
        ));

        // Test that the second transaction fails with index 1
        let result = evm.transact_many([valid_tx, invalid_tx].into_iter());
        assert!(matches!(
            result,
            Err(TransactionIndexedError {
                transaction_index: 1,
                ..
            })
        ));
    }

    #[test]
    fn test_transact_many_success() {
        use primitives::{address, U256};

        let ctx = Context::mainnet().with_db(CacheDB::<EmptyDB>::default());
        let mut evm = ctx.build_mainnet();

        // Add balance to the caller account
        let caller = address!("0x0000000000000000000000000000000000000001");
        evm.db_mut().insert_account_info(
            caller,
            AccountInfo::new(
                U256::from(1000000000000000000u64),
                0,
                B256::ZERO,
                Bytecode::new(),
            ),
        );

        // Create valid transactions with proper data
        let tx1 = TxEnv::builder()
            .caller(caller)
            .gas_limit(100000)
            .gas_price(20_000_000_000u128)
            .nonce(0)
            .build()
            .unwrap();

        let tx2 = TxEnv::builder()
            .caller(caller)
            .gas_limit(100000)
            .gas_price(20_000_000_000u128)
            .nonce(1)
            .build()
            .unwrap();

        // Test that all transactions succeed
        let result = evm.transact_many([tx1, tx2].into_iter());
        if let Err(e) = &result {
            println!("Error: {e:?}");
        }
        let outputs = result.expect("All transactions should succeed");
        assert_eq!(outputs.len(), 2);
    }

    #[test]
    fn test_transact_many_finalize_with_error() {
        use context::result::TransactionIndexedError;

        let ctx = Context::mainnet().with_db(CacheDB::<EmptyDB>::default());
        let mut evm = ctx.build_mainnet();

        // Create transactions where the second one fails
        let valid_tx = TxEnv::builder().gas_limit(100000).build().unwrap();

        let invalid_tx = TxEnv::builder()
            .gas_limit(0) // This will cause a validation error
            .build()
            .unwrap();

        // Test that transact_many_finalize returns the error with correct index
        let result = evm.transact_many_finalize([valid_tx, invalid_tx].into_iter());
        assert!(matches!(
            result,
            Err(TransactionIndexedError {
                transaction_index: 1,
                ..
            })
        ));
    }

    #[test]
    fn test_transact_many_commit_with_error() {
        use context::result::TransactionIndexedError;

        let ctx = Context::mainnet().with_db(CacheDB::<EmptyDB>::default());
        let mut evm = ctx.build_mainnet();

        // Create transactions where the first one fails
        let invalid_tx = TxEnv::builder()
            .gas_limit(0) // This will cause a validation error
            .build()
            .unwrap();

        let valid_tx = TxEnv::builder().gas_limit(100000).build().unwrap();

        // Test that transact_many_commit returns the error with correct index
        let result = evm.transact_many_commit([invalid_tx, valid_tx].into_iter());
        assert!(matches!(
            result,
            Err(TransactionIndexedError {
                transaction_index: 0,
                ..
            })
        ));
    }
}