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
use crate::{
    trevm_bail, trevm_ensure, unwrap_or_trevm_err, Block, BundleDriver, DriveBundleResult,
};
use alloy_consensus::{Transaction, TxEip4844Variant, TxEnvelope};
use alloy_eips::{eip2718::Decodable2718, BlockNumberOrTag};
use alloy_primitives::{bytes::Buf, keccak256, Address, Bytes, TxKind, U256};
use alloy_rpc_types_mev::{
    EthBundleHash, EthCallBundle, EthCallBundleResponse, EthCallBundleTransactionResult,
    EthSendBundle,
};
use revm::primitives::{EVMError, ExecutionResult, MAX_BLOB_GAS_PER_BLOCK};
use thiserror::Error;

/// Possible errors that can occur while driving a bundle.
#[derive(Error)]
pub enum BundleError<Db: revm::Database> {
    /// The block number of the bundle does not match the block number of the revm block configuration.
    #[error("revm block number must match the bundle block number")]
    BlockNumberMismatch,
    /// The timestamp of the bundle is out of range.
    #[error("timestamp out of range")]
    TimestampOutOfRange,
    /// The bundle was reverted (or halted).
    #[error("bundle reverted")]
    BundleReverted,
    /// The bundle has no transactions
    #[error("bundle has no transactions")]
    BundleEmpty,
    /// Too many blob transactions
    #[error("max blob gas limit exceeded")]
    Eip4844BlobGasExceeded,
    /// An unsupported transaction type was encountered.
    #[error("unsupported transaction type")]
    UnsupportedTransactionType,
    /// An error occurred while decoding a transaction contained in the bundle.
    #[error("transaction decoding error")]
    TransactionDecodingError(#[from] alloy_eips::eip2718::Eip2718Error),
    /// An error ocurred while recovering the sender of a transaction
    #[error("transaction sender recovery error")]
    TransactionSenderRecoveryError(#[from] alloy_primitives::SignatureError),
    /// An error occurred while running the EVM.
    #[error("internal EVM Error")]
    EVMError {
        /// The error that occurred while running the EVM.
        inner: EVMError<Db::Error>,
    },
}

impl<Db: revm::Database> From<EVMError<Db::Error>> for BundleError<Db> {
    fn from(inner: EVMError<Db::Error>) -> Self {
        Self::EVMError { inner }
    }
}

impl<Db: revm::Database> std::fmt::Debug for BundleError<Db> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::TimestampOutOfRange => write!(f, "TimestampOutOfRange"),
            Self::BlockNumberMismatch => write!(f, "BlockNumberMismatch"),
            Self::BundleEmpty => write!(f, "BundleEmpty"),
            Self::BundleReverted => write!(f, "BundleReverted"),
            Self::TransactionDecodingError(e) => write!(f, "TransactionDecodingError({:?})", e),
            Self::UnsupportedTransactionType => write!(f, "UnsupportedTransactionType"),
            Self::Eip4844BlobGasExceeded => write!(f, "Eip4844BlobGasExceeded"),
            Self::TransactionSenderRecoveryError(e) => {
                write!(f, "TransactionSenderRecoveryError({:?})", e)
            }
            Self::EVMError { .. } => write!(f, "EVMError"),
        }
    }
}

/// A bundle processor which can be used to drive a bundle with a [BundleDriver], accumulate the results of the bundle and dispatch
/// a response.
#[derive(Debug)]
pub struct BundleProcessor<B, R> {
    /// The bundle to process.
    pub bundle: B,
    /// The response for the processed bundle.
    pub response: R,
}

impl<B, R> BundleProcessor<B, R> {
    /// Create a new bundle simulator with the given bundle and response.
    pub const fn new(bundle: B, response: R) -> Self {
        Self { bundle, response }
    }
}

impl<B, R> BundleProcessor<B, R> {
    /// Decode and validate the transactions in the bundle, performing EIP4844 gas checks.
    pub fn decode_and_validate_txs<Db: revm::Database>(
        txs: &[Bytes],
    ) -> Result<Vec<TxEnvelope>, BundleError<Db>> {
        let txs = txs
            .iter()
            .map(|tx| TxEnvelope::decode_2718(&mut tx.chunk()))
            .collect::<Result<Vec<_>, _>>()?;

        if txs
            .iter()
            .filter_map(|tx| tx.as_eip4844())
            .map(|tx| tx.tx().tx().blob_gas())
            .sum::<u64>()
            > MAX_BLOB_GAS_PER_BLOCK
        {
            Err(BundleError::Eip4844BlobGasExceeded)
        } else {
            Ok(txs)
        }
    }
}

impl BundleProcessor<EthCallBundle, EthCallBundleResponse> {
    /// Create a new bundle simulator with the given bundle.
    pub fn new_call(bundle: EthCallBundle) -> Self {
        Self::new(bundle, EthCallBundleResponse::default())
    }

    /// Process a bundle transaction and accumulate the results into a [EthCallBundleTransactionResult].
    pub fn process_call_bundle_tx<Db: revm::Database>(
        tx: &TxEnvelope,
        pre_sim_coinbase_balance: U256,
        post_sim_coinbase_balance: U256,
        basefee: U256,
        execution_result: ExecutionResult,
    ) -> Result<(EthCallBundleTransactionResult, U256), BundleError<Db>> {
        let gas_used = execution_result.gas_used();

        // Calculate the gas price
        let gas_price = match tx {
            TxEnvelope::Legacy(tx) => U256::from(tx.tx().gas_price),
            TxEnvelope::Eip2930(tx) => U256::from(tx.tx().gas_price),
            TxEnvelope::Eip1559(tx) => {
                U256::from(tx.tx().effective_gas_price(Some(basefee.to::<u64>())))
            }
            TxEnvelope::Eip4844(tx) => match tx.tx() {
                TxEip4844Variant::TxEip4844(tx) => {
                    U256::from(tx.effective_gas_price(Some(basefee.to::<u64>())))
                }
                TxEip4844Variant::TxEip4844WithSidecar(tx) => {
                    U256::from(tx.tx.effective_gas_price(Some(basefee.to::<u64>())))
                }
            },
            _ => return Err(BundleError::UnsupportedTransactionType),
        };

        // Calculate the gas fees paid
        let gas_fees = match tx {
            TxEnvelope::Legacy(tx) => U256::from(tx.tx().gas_price) * U256::from(gas_used),
            TxEnvelope::Eip2930(tx) => U256::from(tx.tx().gas_price) * U256::from(gas_used),
            TxEnvelope::Eip1559(tx) => {
                U256::from(tx.tx().effective_gas_price(Some(basefee.to::<u64>())))
                    * U256::from(gas_used)
            }
            TxEnvelope::Eip4844(tx) => match tx.tx() {
                TxEip4844Variant::TxEip4844(tx) => {
                    U256::from(tx.effective_gas_price(Some(basefee.to::<u64>())))
                        * U256::from(gas_used)
                }
                TxEip4844Variant::TxEip4844WithSidecar(tx) => {
                    U256::from(tx.tx.effective_gas_price(Some(basefee.to::<u64>())))
                        * U256::from(gas_used)
                }
            },
            _ => return Err(BundleError::UnsupportedTransactionType),
        };

        // set the return data for the response
        let (value, revert) = if execution_result.is_success() {
            let value = execution_result.into_output().unwrap_or_default();
            (Some(value), None)
        } else {
            let revert = execution_result.into_output().unwrap_or_default();
            (None, Some(revert))
        };

        let coinbase_diff = post_sim_coinbase_balance.saturating_sub(pre_sim_coinbase_balance);
        let eth_sent_to_coinbase = coinbase_diff.saturating_sub(gas_fees);

        Ok((
            EthCallBundleTransactionResult {
                tx_hash: *tx.tx_hash(),
                coinbase_diff,
                eth_sent_to_coinbase,
                from_address: tx.recover_signer()?,
                to_address: match tx.to() {
                    TxKind::Call(to) => Some(to),
                    _ => Some(Address::ZERO),
                },
                value,
                revert,
                gas_used,
                gas_price,
                gas_fees,
            },
            post_sim_coinbase_balance,
        ))
    }
}

impl<Ext> BundleDriver<Ext> for BundleProcessor<EthCallBundle, EthCallBundleResponse> {
    type Error<Db: revm::Database> = BundleError<Db>;

    fn run_bundle<'a, Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        trevm: crate::EvmNeedsTx<'a, Ext, Db>,
    ) -> DriveBundleResult<'a, Ext, Db, Self> {
        // Check if the block we're in is valid for this bundle. Both must match
        trevm_ensure!(
            trevm.inner().block().number.to::<u64>() == self.bundle.block_number,
            trevm,
            BundleError::BlockNumberMismatch
        );

        // Check if the bundle has any transactions
        trevm_ensure!(!self.bundle.txs.is_empty(), trevm, BundleError::BundleEmpty);

        // Check if the state block number is valid (not 0, and not a tag)
        trevm_ensure!(
            self.bundle.state_block_number.is_number()
                && self.bundle.state_block_number.as_number().unwrap_or(0) != 0,
            trevm,
            BundleError::BlockNumberMismatch
        );

        // Set the state block number this simulation was based on
        self.response.state_block_number = self
            .bundle
            .state_block_number
            .as_number()
            .unwrap_or(trevm.inner().block().number.to::<u64>());

        let bundle_filler = BundleBlockFiller::from(&self.bundle);

        let run_result = trevm.try_with_block(&bundle_filler, |trevm| {
            // We need to keep track of the state of the EVM as we run the transactions, so we can accumulate the results.
            // Therefore we keep this mutable trevm instance, and set it to the new one after we're done simulating.
            let mut trevm = trevm;

            // Decode and validate the transactions in the bundle
            let txs = unwrap_or_trevm_err!(Self::decode_and_validate_txs(&self.bundle.txs), trevm);

            // Cache the pre simulation coinbase balance, so we can use it to calculate the coinbase diff after every tx simulated.
            let initial_coinbase_balance = unwrap_or_trevm_err!(
                trevm.try_read_balance(trevm.inner().block().coinbase).map_err(|e| {
                    BundleError::EVMError { inner: revm::primitives::EVMError::Database(e) }
                }),
                trevm
            );
            let mut pre_sim_coinbase_balance = initial_coinbase_balance;
            let post_sim_coinbase_balance = pre_sim_coinbase_balance;
            let mut total_gas_fees = U256::ZERO;
            let mut total_gas_used = 0;

            let mut hash_bytes = Vec::with_capacity(32 * txs.len());

            for tx in txs.iter() {
                let run_result = trevm.run_tx(tx);

                match run_result {
                    // return immediately if errored
                    Err(e) => {
                        return Err(e.map_err(|e| BundleError::EVMError { inner: e }));
                    }
                    // Accept + accumulate state
                    Ok(res) => {
                        let (execution_result, mut committed_trevm) = res.accept();

                        // Get the coinbase and basefee from the block
                        let coinbase = committed_trevm.inner().block().coinbase;
                        let basefee = committed_trevm.inner().block().basefee;

                        // Get the post simulation coinbase balance
                        let post_sim_coinbase_balance = unwrap_or_trevm_err!(
                            committed_trevm.try_read_balance(coinbase).map_err(|e| {
                                BundleError::EVMError {
                                    inner: revm::primitives::EVMError::Database(e),
                                }
                            }),
                            committed_trevm
                        );

                        // Process the transaction and accumulate the results
                        let (response, post_sim_coinbase_balance) = unwrap_or_trevm_err!(
                            Self::process_call_bundle_tx(
                                tx,
                                pre_sim_coinbase_balance,
                                post_sim_coinbase_balance,
                                basefee,
                                execution_result
                            ),
                            committed_trevm
                        );

                        // Accumulate overall results from response
                        total_gas_used += response.gas_used;
                        total_gas_fees += response.gas_fees;
                        self.response.results.push(response);
                        hash_bytes.extend_from_slice(tx.tx_hash().as_slice());

                        // update the coinbase balance
                        pre_sim_coinbase_balance = post_sim_coinbase_balance;

                        // Set the trevm instance to the committed one
                        trevm = committed_trevm;
                    }
                }
            }

            // Accumulate the total results
            self.response.total_gas_used = total_gas_used;
            self.response.coinbase_diff =
                post_sim_coinbase_balance.saturating_sub(initial_coinbase_balance);
            self.response.eth_sent_to_coinbase =
                self.response.coinbase_diff.saturating_sub(total_gas_fees);
            self.response.bundle_gas_price = self
                .response
                .coinbase_diff
                .checked_div(U256::from(total_gas_used))
                .unwrap_or_default();
            self.response.gas_fees = total_gas_fees;
            self.response.bundle_hash = keccak256(hash_bytes);

            // return the final state
            Ok(trevm)
        });

        match run_result {
            Ok(trevm) => Ok(trevm),
            Err(e) => Err(e),
        }
    }

    fn post_bundle<Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        _trevm: &crate::EvmNeedsTx<'_, Ext, Db>,
    ) -> Result<(), Self::Error<Db>> {
        Ok(())
    }
}

impl<Ext> BundleDriver<Ext> for BundleProcessor<EthSendBundle, EthBundleHash> {
    type Error<Db: revm::Database> = BundleError<Db>;

    fn run_bundle<'a, Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        trevm: crate::EvmNeedsTx<'a, Ext, Db>,
    ) -> DriveBundleResult<'a, Ext, Db, Self> {
        {
            // Check if the block we're in is valid for this bundle. Both must match
            trevm_ensure!(
                trevm.inner().block().number.to::<u64>() == self.bundle.block_number,
                trevm,
                BundleError::BlockNumberMismatch
            );

            // Check for start timestamp range validity
            if let Some(min_timestamp) = self.bundle.min_timestamp {
                trevm_ensure!(
                    trevm.inner().block().timestamp.to::<u64>() >= min_timestamp,
                    trevm,
                    BundleError::TimestampOutOfRange
                );
            }

            // Check for end timestamp range validity
            if let Some(max_timestamp) = self.bundle.max_timestamp {
                trevm_ensure!(
                    trevm.inner().block().timestamp.to::<u64>() <= max_timestamp,
                    trevm,
                    BundleError::TimestampOutOfRange
                );
            }

            // Check if the bundle has any transactions
            trevm_ensure!(!self.bundle.txs.is_empty(), trevm, BundleError::BundleEmpty);

            // Decode and validate the transactions in the bundle
            let txs = unwrap_or_trevm_err!(Self::decode_and_validate_txs(&self.bundle.txs), trevm);

            // Store the current evm state in this mutable variable, so we can continually use the freshest state for each simulation
            let mut t = trevm;

            let mut hash_bytes = Vec::with_capacity(32 * txs.len());

            for tx in txs.iter() {
                hash_bytes.extend_from_slice(tx.tx_hash().as_slice());
                // Run the transaction
                let run_result = match t.run_tx(tx) {
                    Ok(res) => res,
                    Err(e) => return Err(e.map_err(|e| BundleError::EVMError { inner: e })),
                };

                // Accept the state if the transaction was successful and the bundle did not revert or halt AND
                // the tx that reverted is NOT in the set of transactions allowed to revert
                let trevm = match run_result.result() {
                    ExecutionResult::Success { .. } => run_result.accept_state(),
                    ExecutionResult::Revert { .. } | ExecutionResult::Halt { .. } => {
                        // If the transaction reverted but it is contained in the set of transactions allowed to revert,
                        // then we _accept_ the state and move on.
                        // See https://github.com/flashbots/rbuilder/blob/52fea312e5d8be1f1405c52d1fd207ecee2d14b1/crates/rbuilder/src/building/order_commit.rs#L546-L558
                        if self.bundle.reverting_tx_hashes.contains(tx.tx_hash()) {
                            run_result.accept_state()
                        } else {
                            trevm_bail!(run_result, BundleError::BundleReverted);
                        }
                    }
                };

                // Make sure to update the trevm instance we're using to simulate with the latest one
                t = trevm;
            }

            // Populate the response, which in this case just means setting the bundle hash
            self.response.bundle_hash = keccak256(hash_bytes);

            Ok(t)
        }
    }

    fn post_bundle<Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        _trevm: &crate::EvmNeedsTx<'_, Ext, Db>,
    ) -> Result<(), Self::Error<Db>> {
        Ok(())
    }
}

/// A block filler for the bundle, used to fill in the block data specified for the bundle.
#[derive(Clone, Debug)]
struct BundleBlockFiller {
    pub block_number: BlockNumberOrTag,
    pub timestamp: Option<u64>,
    pub gas_limit: Option<u64>,
    pub difficulty: Option<U256>,
    pub base_fee: Option<u128>,
}

impl Block for BundleBlockFiller {
    fn fill_block_env(&self, block_env: &mut revm::primitives::BlockEnv) {
        if let Some(timestamp) = self.timestamp {
            block_env.timestamp = U256::from(timestamp);
        } else {
            block_env.timestamp += U256::from(12);
        }
        if let Some(gas_limit) = self.gas_limit {
            block_env.gas_limit = U256::from(gas_limit);
        }
        if let Some(difficulty) = self.difficulty {
            block_env.difficulty = difficulty;
        }
        if let Some(base_fee) = self.base_fee {
            block_env.basefee = U256::from(base_fee);
        }
        if let Some(block_number) = self.block_number.as_number() {
            block_env.number = U256::from(block_number);
        }
    }
}

impl From<&EthCallBundle> for BundleBlockFiller {
    fn from(bundle: &EthCallBundle) -> Self {
        Self {
            block_number: bundle.state_block_number,
            timestamp: bundle.timestamp,
            gas_limit: bundle.gas_limit,
            difficulty: bundle.difficulty,
            base_fee: bundle.base_fee,
        }
    }
}

impl From<EthCallBundle> for BundleBlockFiller {
    fn from(bundle: EthCallBundle) -> Self {
        Self {
            block_number: bundle.state_block_number,
            timestamp: bundle.timestamp,
            gas_limit: bundle.gas_limit,
            difficulty: bundle.difficulty,
            base_fee: bundle.base_fee,
        }
    }
}

impl<Ext> BundleDriver<Ext> for EthCallBundle {
    type Error<Db: revm::Database> = BundleError<Db>;

    fn run_bundle<'a, Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        trevm: crate::EvmNeedsTx<'a, Ext, Db>,
    ) -> DriveBundleResult<'a, Ext, Db, Self> {
        // Check if the block we're in is valid for this bundle. Both must match
        trevm_ensure!(
            trevm.inner().block().number.to::<u64>() == self.block_number,
            trevm,
            BundleError::BlockNumberMismatch
        );

        // Check if the bundle has any transactions
        trevm_ensure!(!self.txs.is_empty(), trevm, BundleError::BundleEmpty);

        // Check if the state block number is valid (not 0, and not a tag)
        trevm_ensure!(
            self.state_block_number.is_number()
                && self.state_block_number.as_number().unwrap_or(0) != 0,
            trevm,
            BundleError::BlockNumberMismatch
        );

        let bundle_filler = BundleBlockFiller::from(self.clone());

        let run_result = trevm.try_with_block(&bundle_filler, |trevm| {
            let mut trevm = trevm;

            let txs = unwrap_or_trevm_err!(
                self.txs
                    .iter()
                    .map(|tx| TxEnvelope::decode_2718(&mut tx.chunk()))
                    .collect::<Result<Vec<_>, _>>(),
                trevm
            );

            // Check that the bundle does not exceed the maximum gas limit for blob transactions
            trevm_ensure!(
                txs.iter()
                    .filter_map(|tx| tx.as_eip4844())
                    .map(|tx| tx.tx().tx().blob_gas())
                    .sum::<u64>()
                    <= MAX_BLOB_GAS_PER_BLOCK,
                trevm,
                BundleError::Eip4844BlobGasExceeded
            );

            for tx in txs.iter() {
                let run_result = trevm.run_tx(tx);

                match run_result {
                    // return immediately if errored
                    Err(e) => {
                        return Err(e.map_err(|e| BundleError::EVMError { inner: e }));
                    }
                    // Accept the state, and move on
                    Ok(res) => {
                        trevm = res.accept_state();
                    }
                }
            }

            // return the final state
            Ok(trevm)
        });

        match run_result {
            Ok(trevm) => Ok(trevm),
            Err(e) => Err(e),
        }
    }

    fn post_bundle<Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        _trevm: &crate::EvmNeedsTx<'_, Ext, Db>,
    ) -> Result<(), Self::Error<Db>> {
        Ok(())
    }
}

/// An implementation of [BundleDriver] for [EthSendBundle].
/// This allows us to drive a bundle of transactions and accumulate the resulting state in the EVM.
/// Allows to simply take an [EthSendBundle] and get the resulting EVM state.
impl<Ext> BundleDriver<Ext> for EthSendBundle {
    type Error<Db: revm::Database> = BundleError<Db>;

    fn run_bundle<'a, Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        trevm: crate::EvmNeedsTx<'a, Ext, Db>,
    ) -> DriveBundleResult<'a, Ext, Db, Self> {
        // Check if the block we're in is valid for this bundle. Both must match
        trevm_ensure!(
            trevm.inner().block().number.to::<u64>() == self.block_number,
            trevm,
            BundleError::BlockNumberMismatch
        );

        // Check for start timestamp range validity

        if let Some(min_timestamp) = self.min_timestamp {
            trevm_ensure!(
                trevm.inner().block().timestamp.to::<u64>() >= min_timestamp,
                trevm,
                BundleError::TimestampOutOfRange
            );
        }

        // Check for end timestamp range validity
        if let Some(max_timestamp) = self.max_timestamp {
            trevm_ensure!(
                trevm.inner().block().timestamp.to::<u64>() <= max_timestamp,
                trevm,
                BundleError::TimestampOutOfRange
            );
        }

        // Check if the bundle has any transactions
        trevm_ensure!(!self.txs.is_empty(), trevm, BundleError::BundleEmpty);

        let txs = unwrap_or_trevm_err!(
            self.txs
                .iter()
                .map(|tx| TxEnvelope::decode_2718(&mut tx.chunk()))
                .collect::<Result<Vec<_>, _>>(),
            trevm
        );

        // Check that the bundle does not exceed the maximum gas limit for blob transactions
        trevm_ensure!(
            txs.iter()
                .filter_map(|tx| tx.as_eip4844())
                .map(|tx| tx.tx().tx().blob_gas())
                .sum::<u64>()
                <= MAX_BLOB_GAS_PER_BLOCK,
            trevm,
            BundleError::Eip4844BlobGasExceeded
        );

        // Store the current evm state in this mutable variable, so we can continually use the freshest state for each simulation
        let mut t = trevm;

        for tx in txs.iter() {
            // Run the transaction
            let run_result = match t.run_tx(tx) {
                Ok(res) => res,
                Err(e) => return Err(e.map_err(|e| BundleError::EVMError { inner: e })),
            };

            // Accept the state if the transaction was successful and the bundle did not revert or halt AND
            // the tx that reverted is NOT in the set of transactions allowed to revert
            let trevm = match run_result.result() {
                ExecutionResult::Success { .. } => run_result.accept_state(),
                ExecutionResult::Revert { .. } | ExecutionResult::Halt { .. } => {
                    // If the transaction reverted but it is contained in the set of transactions allowed to revert,
                    // then we _accept_ the state and move on.
                    // See https://github.com/flashbots/rbuilder/blob/52fea312e5d8be1f1405c52d1fd207ecee2d14b1/crates/rbuilder/src/building/order_commit.rs#L546-L558
                    if self.reverting_tx_hashes.contains(tx.tx_hash()) {
                        run_result.accept_state()
                    } else {
                        trevm_bail!(run_result, BundleError::BundleReverted)
                    }
                }
            };

            // Make sure to update the trevm instance we're using to simulate with the latest one
            t = trevm;
        }

        Ok(t)
    }

    fn post_bundle<Db: revm::Database + revm::DatabaseCommit>(
        &mut self,
        _trevm: &crate::EvmNeedsTx<'_, Ext, Db>,
    ) -> Result<(), Self::Error<Db>> {
        Ok(())
    }
}