Skip to main content

reth_rpc/eth/
sim_bundle.rs

1//! `Eth` Sim bundle implementation and helpers.
2
3use crate::eth::bundle::{BundleBlockGas, EthBundleError};
4use alloy_consensus::{transaction::TxHashRef, BlockHeader, Transaction as _};
5use alloy_primitives::U256;
6use alloy_rpc_types_eth::{BlockId, Log};
7use alloy_rpc_types_mev::{
8    BundleItem, Inclusion, MevSendBundle, SimBundleLogs, SimBundleOverrides, SimBundleResponse,
9};
10use evm2::evm::DynDatabase;
11use jsonrpsee::core::RpcResult;
12use reth_errors::RethError;
13use reth_evm::{ConfigureEvm, Evm, EvmEnv};
14use reth_primitives_traits::Recovered;
15use reth_rpc_api::MevSimApiServer;
16use reth_rpc_eth_api::{
17    helpers::{block::LoadBlock, Call, EthTransactions},
18    FromEthApiError, FromEvmError,
19};
20use reth_rpc_eth_types::{
21    cache::db::apply_block_overrides, EthApiError, RpcInvalidTransactionError,
22};
23use reth_storage_api::ProviderTx;
24use reth_tasks::{cancel::is_cancelled, pool::BlockingTaskGuard};
25use reth_transaction_pool::{PoolTransaction, TransactionPool};
26use std::{sync::Arc, time::Duration};
27use tracing::trace;
28
29/// Maximum bundle depth
30const MAX_NESTED_BUNDLE_DEPTH: usize = 5;
31
32/// Maximum body size
33const MAX_BUNDLE_BODY_SIZE: usize = 50;
34
35/// Default simulation timeout
36pub(crate) const DEFAULT_SIM_TIMEOUT: Duration = Duration::from_secs(5);
37
38/// Maximum simulation timeout
39pub(crate) const MAX_SIM_TIMEOUT: Duration = Duration::from_secs(30);
40
41/// Maximum payout cost
42const SBUNDLE_PAYOUT_MAX_COST: u64 = 30_000;
43
44/// A flattened representation of a bundle item containing transaction and associated metadata.
45#[derive(Clone, Debug)]
46pub struct FlattenedBundleItem<T> {
47    /// The signed transaction
48    pub tx: Recovered<T>,
49    /// Whether the transaction is allowed to revert
50    pub can_revert: bool,
51    /// Item-level inclusion constraints
52    pub inclusion: Inclusion,
53    /// Optional refund percent for the bundle item
54    pub refund_percent: Option<u64>,
55    /// Number of refund payouts for the bundle item, used when `refund_percent` is set.
56    ///
57    /// Without refund configs the refund is a single payout to the transaction signer.
58    pub refund_payouts: usize,
59}
60
61/// `Eth` sim bundle implementation.
62pub struct EthSimBundle<Eth> {
63    /// All nested fields bundled together.
64    inner: Arc<EthSimBundleInner<Eth>>,
65}
66
67impl<Eth> EthSimBundle<Eth> {
68    /// Create a new `EthSimBundle` instance.
69    pub fn new(eth_api: Eth, blocking_task_guard: BlockingTaskGuard) -> Self {
70        Self { inner: Arc::new(EthSimBundleInner { eth_api, blocking_task_guard }) }
71    }
72
73    /// Access the underlying `Eth` API.
74    pub fn eth_api(&self) -> &Eth {
75        &self.inner.eth_api
76    }
77
78    /// Builds a hierarchical `SimBundleLogs` structure from flattened transaction logs.
79    fn build_bundle_logs(
80        bundle: &MevSendBundle,
81        flat_logs: &[Vec<Log>],
82    ) -> Result<Vec<SimBundleLogs>, EthApiError> {
83        struct BundleFrame<'a> {
84            bundle: &'a MevSendBundle,
85            next_idx: usize,
86            logs: Vec<SimBundleLogs>,
87        }
88
89        let mut stack = vec![BundleFrame { bundle, next_idx: 0, logs: Vec::new() }];
90        let mut flat_log_idx = 0;
91        let mut root_logs = None;
92
93        while let Some(mut frame) = stack.pop() {
94            if frame.next_idx == frame.bundle.bundle_body.len() {
95                if let Some(parent) = stack.last_mut() {
96                    parent
97                        .logs
98                        .push(SimBundleLogs { tx_logs: None, bundle_logs: Some(frame.logs) });
99                } else {
100                    root_logs = Some(frame.logs);
101                }
102
103                continue;
104            }
105
106            match &frame.bundle.bundle_body[frame.next_idx] {
107                BundleItem::Tx { .. } => {
108                    let tx_logs = flat_logs.get(flat_log_idx).cloned().ok_or_else(|| {
109                        EthApiError::InvalidParams(EthSimBundleError::UnmatchedBundle.to_string())
110                    })?;
111
112                    frame.logs.push(SimBundleLogs { tx_logs: Some(tx_logs), bundle_logs: None });
113                    frame.next_idx += 1;
114                    flat_log_idx += 1;
115                    stack.push(frame);
116                }
117                BundleItem::Bundle { bundle } => {
118                    frame.next_idx += 1;
119                    stack.push(frame);
120                    stack.push(BundleFrame { bundle, next_idx: 0, logs: Vec::new() });
121                }
122                BundleItem::Hash { .. } => {
123                    return Err(EthApiError::InvalidParams(
124                        EthSimBundleError::InvalidBundle.to_string(),
125                    ));
126                }
127            }
128        }
129
130        if flat_log_idx != flat_logs.len() {
131            return Err(EthApiError::InvalidParams(EthSimBundleError::UnmatchedBundle.to_string()));
132        }
133
134        root_logs.ok_or_else(|| {
135            EthApiError::InvalidParams(EthSimBundleError::UnmatchedBundle.to_string())
136        })
137    }
138}
139
140impl<Eth> EthSimBundle<Eth>
141where
142    Eth: EthTransactions + LoadBlock + Call,
143{
144    /// Flattens a potentially nested bundle into a list of individual transactions in a
145    /// `FlattenedBundleItem` with their associated metadata. This handles recursive bundle
146    /// processing up to `MAX_NESTED_BUNDLE_DEPTH` and `MAX_BUNDLE_BODY_SIZE`, preserving
147    /// inclusion and refund settings from parent bundles.
148    fn parse_and_flatten_bundle(
149        &self,
150        request: &MevSendBundle,
151    ) -> Result<Vec<FlattenedBundleItem<ProviderTx<Eth::Provider>>>, EthApiError> {
152        let mut items = Vec::new();
153
154        // Stack for processing bundles
155        let mut stack = Vec::new();
156
157        // Start with initial bundle, index 0, and depth 1
158        stack.push((request, 0, 1));
159
160        while let Some((current_bundle, mut idx, depth)) = stack.pop() {
161            // Check max depth
162            if depth > MAX_NESTED_BUNDLE_DEPTH {
163                return Err(EthApiError::InvalidParams(EthSimBundleError::MaxDepth.to_string()));
164            }
165
166            // Determine inclusion and validity
167            let inclusion = &current_bundle.inclusion;
168            let validity = &current_bundle.validity;
169            let refund_payouts =
170                validity.as_ref().and_then(|v| v.refund_config.as_ref()).map_or(1, Vec::len);
171
172            // Validate inclusion parameters
173            let block_number = inclusion.block_number();
174            let max_block_number = inclusion.max_block_number().unwrap_or(block_number);
175
176            if max_block_number < block_number || block_number == 0 {
177                return Err(EthApiError::InvalidParams(
178                    EthSimBundleError::InvalidInclusion.to_string(),
179                ));
180            }
181
182            // Validate bundle body size
183            if current_bundle.bundle_body.len() > MAX_BUNDLE_BODY_SIZE {
184                return Err(EthApiError::InvalidParams(
185                    EthSimBundleError::BundleTooLarge.to_string(),
186                ));
187            }
188
189            // Validate validity and refund config
190            if let Some(validity) = &current_bundle.validity {
191                // Validate refund entries
192                if let Some(refunds) = &validity.refund {
193                    let mut total_percent = 0;
194                    for refund in refunds {
195                        if refund.body_idx as usize >= current_bundle.bundle_body.len() {
196                            return Err(EthApiError::InvalidParams(
197                                EthSimBundleError::InvalidValidity.to_string(),
198                            ));
199                        }
200                        if 100 - total_percent < refund.percent {
201                            return Err(EthApiError::InvalidParams(
202                                EthSimBundleError::InvalidValidity.to_string(),
203                            ));
204                        }
205                        total_percent += refund.percent;
206                    }
207                }
208
209                // Validate refund configs
210                if let Some(refund_configs) = &validity.refund_config {
211                    let mut total_percent = 0;
212                    for refund_config in refund_configs {
213                        if 100 - total_percent < refund_config.percent {
214                            return Err(EthApiError::InvalidParams(
215                                EthSimBundleError::InvalidValidity.to_string(),
216                            ));
217                        }
218                        total_percent += refund_config.percent;
219                    }
220                }
221            }
222
223            let body = &current_bundle.bundle_body;
224
225            // Process items in the current bundle
226            while idx < body.len() {
227                match &body[idx] {
228                    BundleItem::Tx { tx, can_revert } => {
229                        let recovered_tx = self.eth_api().recover_raw_pooled_transaction(tx)?;
230                        let tx = recovered_tx.map(
231                            <Eth::Pool as TransactionPool>::Transaction::pooled_into_consensus,
232                        );
233
234                        let refund_percent =
235                            validity.as_ref().and_then(|v| v.refund.as_ref()).and_then(|refunds| {
236                                refunds.iter().find_map(|refund| {
237                                    (refund.body_idx as usize == idx).then_some(refund.percent)
238                                })
239                            });
240
241                        // Create FlattenedBundleItem with current inclusion and refund settings
242                        let flattened_item = FlattenedBundleItem {
243                            tx,
244                            can_revert: *can_revert,
245                            inclusion: inclusion.clone(),
246                            refund_percent,
247                            refund_payouts,
248                        };
249
250                        items.push(flattened_item);
251                        idx += 1;
252                    }
253                    BundleItem::Bundle { bundle } => {
254                        // Push the current bundle and next index onto the stack to resume later
255                        stack.push((current_bundle, idx + 1, depth));
256
257                        // process the nested bundle next
258                        stack.push((bundle, 0, depth + 1));
259                        break;
260                    }
261                    BundleItem::Hash { hash: _ } => {
262                        // Hash-only items are not allowed
263                        return Err(EthApiError::InvalidParams(
264                            EthSimBundleError::InvalidBundle.to_string(),
265                        ));
266                    }
267                }
268            }
269        }
270
271        Ok(items)
272    }
273
274    async fn sim_bundle_inner(
275        &self,
276        request: MevSendBundle,
277        overrides: SimBundleOverrides,
278        logs: bool,
279    ) -> Result<SimBundleResponse, Eth::Error> {
280        let SimBundleOverrides { parent_block, block_overrides, .. } = overrides;
281
282        // A call gas limit of 0 disables the cap.
283        let call_gas_limit = self.eth_api().call_gas_limit();
284        if let Some(gas_limit) = block_overrides.gas_limit &&
285            call_gas_limit != 0 &&
286            gas_limit > call_gas_limit
287        {
288            return Err(
289                EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into()
290            )
291        }
292
293        // Parse and validate bundle
294        // Also, flatten the bundle here so that its easier to process
295        let flattened_bundle = self.parse_and_flatten_bundle(&request)?;
296
297        let block_id = parent_block.unwrap_or(BlockId::latest());
298        let (parent, _, parent_block_id) =
299            self.eth_api().evm_env_and_recovered_block_at(block_id).await?;
300
301        // The bundle is simulated in the block that builds on the parent, so derive the
302        // environment of the next block, see
303        // <https://github.com/flashbots/builder/blob/main/internal/ethapi/sbundle_api.go>
304        let parent_header = parent.clone_sealed_header();
305        let mut evm_env = {
306            let attributes = self
307                .eth_api()
308                .pending_env_builder()
309                .pending_env_attributes(&parent_header, Some(&block_overrides))?;
310            self.eth_api()
311                .evm_config()
312                .next_evm_env(&parent_header, &attributes)
313                .map_err(RethError::other)
314                .map_err(EthApiError::from_eth_err)?
315        };
316
317        let permit = self
318            .eth_api()
319            .acquire_owned_blocking_io()
320            .await
321            .map_err(|_| EthApiError::InternalEthError)?;
322
323        let eth_api = self.inner.eth_api.clone();
324
325        let sim_response = self
326            .inner
327            .eth_api
328            .spawn_with_state_at_block(parent_block_id, move |_, mut db| {
329                let _permit = permit;
330                // apply overrides before reading the block values they may change
331                apply_block_overrides(block_overrides, &mut db, &mut evm_env);
332
333                let state_block = parent.number();
334                let simulated_block_number = evm_env.block_env().number.saturating_to::<u64>();
335                let simulated_block_timestamp =
336                    evm_env.block_env().timestamp.saturating_to::<u64>();
337                let coinbase = evm_env.block_env().beneficiary;
338                let basefee = evm_env.block_env().basefee;
339
340                let initial_coinbase_balance = db
341                    .get_account(&coinbase)
342                    .map_err(Eth::Error::from_eth_err)?
343                    .map(|acc| acc.balance)
344                    .unwrap_or_default();
345
346                let mut block_gas_limit = evm_env.block_env().gas_limit.saturating_to::<u64>();
347                if call_gas_limit != 0 {
348                    block_gas_limit = block_gas_limit.min(call_gas_limit);
349                }
350                let mut block_gas = BundleBlockGas::new(block_gas_limit, evm_env.version());
351                let mut evm = eth_api.evm_config().evm_with_env(&mut db, evm_env);
352                let mut coinbase_balance_before_tx = initial_coinbase_balance;
353                let mut total_profit = U256::ZERO;
354                let mut refundable_value = U256::ZERO;
355                let mut flat_logs: Vec<Vec<Log>> = Vec::new();
356
357                let mut log_index = 0;
358
359                for (tx_index, item) in flattened_bundle.iter().enumerate() {
360                    if is_cancelled() {
361                        return Err(EthApiError::InternalEthError.into())
362                    }
363
364                    // Check inclusion constraints
365                    let block_number = item.inclusion.block_number();
366                    let max_block_number =
367                        item.inclusion.max_block_number().unwrap_or(block_number);
368
369                    if simulated_block_number < block_number ||
370                        simulated_block_number > max_block_number
371                    {
372                        return Err(EthApiError::InvalidParams(
373                            EthSimBundleError::InvalidInclusion.to_string(),
374                        )
375                        .into());
376                    }
377
378                    if !block_gas.admits(item.tx.gas_limit()) {
379                        return Err(EthApiError::InvalidParams(
380                            EthBundleError::BundleGasLimitExceeded(block_gas_limit).to_string(),
381                        )
382                        .into())
383                    }
384
385                    let tx_env = eth_api.evm_config().tx_env(item.tx.clone());
386                    let result = evm.transact_commit(&tx_env).map_err(Eth::Error::from_evm_err)?;
387
388                    if !result.status && !item.can_revert {
389                        return Err(EthApiError::InvalidParams(
390                            EthSimBundleError::BundleTransactionFailed.to_string(),
391                        )
392                        .into());
393                    }
394
395                    block_gas.record(&result);
396
397                    let coinbase_balance_after_tx = evm
398                        .account_info(&coinbase)
399                        .map_err(Eth::Error::from_evm_err)?
400                        .map(|acc| acc.balance)
401                        .unwrap_or_default();
402
403                    let coinbase_diff =
404                        coinbase_balance_after_tx.saturating_sub(coinbase_balance_before_tx);
405                    total_profit += coinbase_diff;
406
407                    // Add to refundable value if this tx does not have a refund percent
408                    if item.refund_percent.is_none() {
409                        refundable_value += coinbase_diff;
410                    }
411
412                    // Update coinbase balance before next tx
413                    coinbase_balance_before_tx = coinbase_balance_after_tx;
414
415                    // Keep one log entry per executed transaction so we can rebuild the bundle
416                    // tree in execution order after simulation.
417                    if logs {
418                        let tx_logs: Vec<Log> = result
419                            .logs
420                            .into_iter()
421                            .map(|inner| {
422                                let full_log = Log {
423                                    inner,
424                                    // the simulated block has no hash yet
425                                    block_hash: None,
426                                    block_number: Some(simulated_block_number),
427                                    block_timestamp: Some(simulated_block_timestamp),
428                                    transaction_hash: Some(*item.tx.tx_hash()),
429                                    transaction_index: Some(tx_index as u64),
430                                    log_index: Some(log_index),
431                                    removed: false,
432                                };
433                                log_index += 1;
434                                full_log
435                            })
436                            .collect();
437                        flat_logs.push(tx_logs);
438                    }
439                }
440
441                let body_logs =
442                    if logs { Self::build_bundle_logs(&request, &flat_logs)? } else { vec![] };
443
444                let mut total_gas_used = block_gas.gas_used();
445
446                // After processing all transactions, process refunds
447                for item in &flattened_bundle {
448                    if let Some(refund_percent) = item.refund_percent {
449                        // Saturates so a huge base fee override fails the profit check instead
450                        // of wrapping.
451                        let payout_tx_fee = basefee
452                            .saturating_mul(U256::from(SBUNDLE_PAYOUT_MAX_COST))
453                            .saturating_mul(U256::from(item.refund_payouts));
454
455                        // Add gas used for payout transactions
456                        total_gas_used += SBUNDLE_PAYOUT_MAX_COST * item.refund_payouts as u64;
457
458                        // Calculate allocated refundable value (payout value)
459                        let payout_value =
460                            refundable_value * U256::from(refund_percent) / U256::from(100);
461
462                        if payout_tx_fee > payout_value {
463                            return Err(EthApiError::InvalidParams(
464                                EthSimBundleError::NegativeProfit.to_string(),
465                            )
466                            .into());
467                        }
468
469                        // Subtract payout value from total profit
470                        total_profit = total_profit.checked_sub(payout_value).ok_or(
471                            EthApiError::InvalidParams(
472                                EthSimBundleError::NegativeProfit.to_string(),
473                            ),
474                        )?;
475                    }
476                }
477
478                // Calculate mev gas price
479                let mev_gas_price = if total_gas_used != 0 {
480                    total_profit / U256::from(total_gas_used)
481                } else {
482                    U256::ZERO
483                };
484
485                Ok(SimBundleResponse {
486                    success: true,
487                    state_block,
488                    error: None,
489                    logs: Some(body_logs),
490                    gas_used: total_gas_used,
491                    mev_gas_price,
492                    profit: total_profit,
493                    refundable_value,
494                    exec_error: None,
495                    revert: None,
496                })
497            })
498            .await?;
499
500        Ok(sim_response)
501    }
502}
503
504impl<Eth> MevSimApiServer for EthSimBundle<Eth>
505where
506    Eth: EthTransactions + LoadBlock + Call,
507{
508    async fn sim_bundle(
509        &self,
510        request: MevSendBundle,
511        overrides: SimBundleOverrides,
512    ) -> RpcResult<SimBundleResponse> {
513        trace!("mev_simBundle called, request: {:?}, overrides: {:?}", request, overrides);
514
515        let override_timeout = overrides.timeout;
516
517        let timeout = override_timeout
518            .map(Duration::from_secs)
519            .map(|d| d.min(MAX_SIM_TIMEOUT))
520            .unwrap_or(DEFAULT_SIM_TIMEOUT);
521
522        let bundle_res =
523            tokio::time::timeout(timeout, Self::sim_bundle_inner(self, request, overrides, true))
524                .await
525                .map_err(|_| {
526                    EthApiError::InvalidParams(EthSimBundleError::BundleTimeout.to_string())
527                })?;
528
529        bundle_res.map_err(Into::into)
530    }
531}
532
533/// Container type for `EthSimBundle` internals
534#[derive(Debug)]
535struct EthSimBundleInner<Eth> {
536    /// Access to commonly used code of the `eth` namespace
537    eth_api: Eth,
538    // restrict the number of concurrent tracing calls.
539    #[expect(dead_code)]
540    blocking_task_guard: BlockingTaskGuard,
541}
542
543impl<Eth> std::fmt::Debug for EthSimBundle<Eth> {
544    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
545        f.debug_struct("EthSimBundle").finish_non_exhaustive()
546    }
547}
548
549impl<Eth> Clone for EthSimBundle<Eth> {
550    fn clone(&self) -> Self {
551        Self { inner: Arc::clone(&self.inner) }
552    }
553}
554
555/// [`EthSimBundle`] specific errors.
556#[derive(Debug, thiserror::Error)]
557pub enum EthSimBundleError {
558    /// Thrown when max depth is reached
559    #[error("max depth reached")]
560    MaxDepth,
561    /// Thrown when a bundle is unmatched
562    #[error("unmatched bundle")]
563    UnmatchedBundle,
564    /// Thrown when a bundle is too large
565    #[error("bundle too large")]
566    BundleTooLarge,
567    /// Thrown when validity is invalid
568    #[error("invalid validity")]
569    InvalidValidity,
570    /// Thrown when inclusion is invalid
571    #[error("invalid inclusion")]
572    InvalidInclusion,
573    /// Thrown when a bundle is invalid
574    #[error("invalid bundle")]
575    InvalidBundle,
576    /// Thrown when a bundle simulation times out
577    #[error("bundle simulation timed out")]
578    BundleTimeout,
579    /// Thrown when a transaction is reverted in a bundle
580    #[error("bundle transaction failed")]
581    BundleTransactionFailed,
582    /// Thrown when a bundle simulation returns negative profit
583    #[error("bundle simulation returned negative profit")]
584    NegativeProfit,
585}
586
587#[cfg(test)]
588mod tests {
589    use super::*;
590    use crate::EthApiBuilder;
591    use alloy_consensus::{transaction::SignerRecoverable, TxEip1559};
592    use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip2718::Encodable2718};
593    use alloy_genesis::{Genesis, GenesisAccount};
594    use alloy_primitives::{Address, Bytes, TxKind, B256};
595    use alloy_rpc_types_eth::BlockOverrides;
596    use alloy_rpc_types_mev::{Inclusion, ProtocolVersion, Refund, RefundConfig, Validity};
597    use jsonrpsee::types::ErrorObjectOwned;
598    use reth_chainspec::{ChainSpecBuilder, ChainSpecProvider};
599    use reth_db_common::init::init_genesis;
600    use reth_evm_ethereum::EthEvmConfig;
601    use reth_network_api::noop::NoopNetwork;
602    use reth_provider::{
603        providers::BlockchainProvider, test_utils::create_test_provider_factory_with_chain_spec,
604    };
605    use reth_testing_utils::{
606        generators,
607        generators::{generate_key, sign_tx_with_key_pair},
608    };
609    use reth_transaction_pool::test_utils::testing_pool;
610
611    #[tokio::test(flavor = "multi_thread")]
612    async fn sim_bundle_uses_next_block_env_and_overrides() {
613        let contract = Address::repeat_byte(0xaa);
614        let coinbase = Address::repeat_byte(0x11);
615        let overridden_coinbase = Address::repeat_byte(0x22);
616        let mut rng = generators::rng();
617        let tx = sign_tx_with_key_pair(
618            generate_key(&mut rng),
619            reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
620                chain_id: 1,
621                nonce: 0,
622                gas_limit: 100_000,
623                max_fee_per_gas: 2_000_000_000,
624                max_priority_fee_per_gas: 1_000_000_000,
625                to: TxKind::Call(contract),
626                ..Default::default()
627            }),
628        );
629        let sender = tx.recover_signer().unwrap();
630
631        // Log NUMBER, TIMESTAMP, BASEFEE and COINBASE as topics, in that order.
632        let code = Bytes::from_static(&[0x41, 0x48, 0x42, 0x43, 0x5f, 0x5f, 0xa4, 0x00]);
633        let genesis = Genesis::default()
634            .with_gas_limit(30_000_000)
635            .with_timestamp(100)
636            .with_base_fee(Some(1_000_000_000))
637            .with_coinbase(coinbase)
638            .extend_accounts([
639                (sender, GenesisAccount::default().with_balance(U256::from(10u128.pow(18)))),
640                (contract, GenesisAccount::default().with_code(Some(code))),
641                (
642                    overridden_coinbase,
643                    GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
644                ),
645            ]);
646        let chain_spec =
647            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
648        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
649        init_genesis(&factory).unwrap();
650        let provider = BlockchainProvider::new(factory).unwrap();
651
652        let eth_api = EthApiBuilder::new(
653            provider.clone(),
654            testing_pool(),
655            NoopNetwork::default(),
656            EthEvmConfig::new(provider.chain_spec()),
657        )
658        .build();
659        let api = EthSimBundle::new(eth_api, BlockingTaskGuard::new(4));
660
661        let bundle = |block| MevSendBundle {
662            protocol_version: ProtocolVersion::V0_1,
663            inclusion: Inclusion::at_block(block),
664            bundle_body: vec![BundleItem::Tx { tx: tx.encoded_2718().into(), can_revert: false }],
665            validity: None,
666            privacy: None,
667        };
668
669        for (overrides, number, timestamp, base_fee, beneficiary) in [
670            (SimBundleOverrides::default(), 1, 112, 875_000_000, coinbase),
671            (
672                SimBundleOverrides {
673                    parent_block: Some(BlockId::number(0)),
674                    block_overrides: BlockOverrides {
675                        number: Some(U256::from(2)),
676                        time: Some(200),
677                        base_fee: Some(U256::from(1_500_000_000)),
678                        coinbase: Some(overridden_coinbase),
679                        ..Default::default()
680                    },
681                    ..Default::default()
682                },
683                2,
684                200,
685                1_500_000_000,
686                overridden_coinbase,
687            ),
688        ] {
689            let response = api.sim_bundle(bundle(number), overrides.clone()).await.unwrap();
690            assert!(response.success);
691            assert_eq!(response.state_block, 0);
692            let tip = (2_000_000_000u64 - base_fee).min(1_000_000_000);
693            assert_eq!(response.profit, U256::from(response.gas_used) * U256::from(tip));
694            assert_eq!(response.refundable_value, response.profit);
695            assert_eq!(response.mev_gas_price, U256::from(tip));
696
697            let logs = response.logs.unwrap();
698            assert_eq!(logs.len(), 1);
699            let tx_logs = logs[0].tx_logs.as_ref().unwrap();
700            assert_eq!(tx_logs.len(), 1);
701            let log = &tx_logs[0];
702            assert_eq!(
703                log.inner.topics(),
704                &[
705                    B256::from(U256::from(number)),
706                    B256::from(U256::from(timestamp)),
707                    B256::from(U256::from(base_fee)),
708                    beneficiary.into_word(),
709                ]
710            );
711            assert_eq!(log.block_hash, None);
712            assert_eq!(log.block_number, Some(number));
713            assert_eq!(log.block_timestamp, Some(timestamp));
714            assert_eq!(log.transaction_hash, Some(*tx.tx_hash()));
715            assert_eq!(log.transaction_index, Some(0));
716            assert_eq!(log.log_index, Some(0));
717
718            // Nonzero inclusion bounds reach the simulation check instead of failing parsing.
719            let err = api.sim_bundle(bundle(number + 1), overrides.clone()).await.unwrap_err();
720            assert!(err.message().contains("invalid inclusion"), "{err}");
721            if number > 1 {
722                let err = api.sim_bundle(bundle(number - 1), overrides).await.unwrap_err();
723                assert!(err.message().contains("invalid inclusion"), "{err}");
724            }
725        }
726    }
727
728    fn create_test_bundle(tx_bytes: Vec<Bytes>) -> MevSendBundle {
729        let body: Vec<BundleItem> =
730            tx_bytes.into_iter().map(|tx| BundleItem::Tx { tx, can_revert: false }).collect();
731        MevSendBundle {
732            bundle_body: body,
733            inclusion: Inclusion { block: 1, max_block: None },
734            validity: None,
735            privacy: None,
736            protocol_version: ProtocolVersion::V0_1,
737        }
738    }
739
740    fn create_nested_bundle(outer_tx: Bytes, inner_txs: Vec<Bytes>) -> MevSendBundle {
741        let inner_bundle = create_test_bundle(inner_txs);
742        MevSendBundle {
743            bundle_body: vec![
744                BundleItem::Tx { tx: outer_tx, can_revert: false },
745                BundleItem::Bundle { bundle: inner_bundle },
746            ],
747            inclusion: Inclusion { block: 1, max_block: None },
748            validity: None,
749            privacy: None,
750            protocol_version: ProtocolVersion::V0_1,
751        }
752    }
753
754    fn create_bundle_with_body(bundle_body: Vec<BundleItem>) -> MevSendBundle {
755        MevSendBundle {
756            bundle_body,
757            inclusion: Inclusion { block: 1, max_block: None },
758            validity: None,
759            privacy: None,
760            protocol_version: ProtocolVersion::V0_1,
761        }
762    }
763
764    fn create_bundle_logs(log_counts: &[usize]) -> Vec<Vec<Log>> {
765        log_counts.iter().map(|count| vec![Log::default(); *count]).collect()
766    }
767
768    fn assert_unmatched_bundle(result: Result<Vec<SimBundleLogs>, EthApiError>) {
769        assert!(matches!(
770            result,
771            Err(EthApiError::InvalidParams(ref message))
772                if message == &EthSimBundleError::UnmatchedBundle.to_string()
773        ));
774    }
775
776    #[test]
777    fn test_build_bundle_logs_single_tx() {
778        let bundle = create_test_bundle(vec![Bytes::from(vec![0x01, 0x02, 0x03])]);
779        let result =
780            EthSimBundle::<()>::build_bundle_logs(&bundle, &create_bundle_logs(&[1])).unwrap();
781
782        assert_eq!(result.len(), 1);
783        assert!(result[0].tx_logs.is_some());
784        assert!(result[0].bundle_logs.is_none());
785        assert_eq!(result[0].tx_logs.as_ref().unwrap().len(), 1);
786    }
787
788    #[test]
789    fn test_build_bundle_logs_empty_bundle() {
790        let bundle = create_test_bundle(vec![]);
791        let result = EthSimBundle::<()>::build_bundle_logs(&bundle, &[]).unwrap();
792
793        assert!(result.is_empty());
794    }
795
796    #[test]
797    fn test_build_bundle_logs_nested_bundle() {
798        let outer_tx = Bytes::from(vec![0x01, 0x02, 0x03]);
799        let inner_tx1 = Bytes::from(vec![0x04, 0x05, 0x06]);
800        let inner_tx2 = Bytes::from(vec![0x07, 0x08, 0x09]);
801        let bundle = create_nested_bundle(outer_tx, vec![inner_tx1, inner_tx2]);
802        let result =
803            EthSimBundle::<()>::build_bundle_logs(&bundle, &create_bundle_logs(&[1, 1, 2]))
804                .unwrap();
805
806        assert_eq!(result.len(), 2);
807        assert!(result[0].tx_logs.is_some());
808        assert!(result[0].bundle_logs.is_none());
809        assert_eq!(result[0].tx_logs.as_ref().unwrap().len(), 1);
810
811        assert!(result[1].tx_logs.is_none());
812        assert!(result[1].bundle_logs.is_some());
813
814        let nested_logs = result[1].bundle_logs.as_ref().unwrap();
815        assert_eq!(nested_logs.len(), 2);
816        assert!(nested_logs[0].tx_logs.is_some());
817        assert_eq!(nested_logs[0].tx_logs.as_ref().unwrap().len(), 1);
818        assert!(nested_logs[1].tx_logs.is_some());
819        assert_eq!(nested_logs[1].tx_logs.as_ref().unwrap().len(), 2);
820    }
821
822    #[test]
823    fn test_build_bundle_logs_duplicate_transactions_same_level() {
824        let duplicate_tx = Bytes::from(vec![0x01, 0x02, 0x03]);
825        let bundle = create_test_bundle(vec![duplicate_tx.clone(), duplicate_tx]);
826        let result =
827            EthSimBundle::<()>::build_bundle_logs(&bundle, &create_bundle_logs(&[1, 2])).unwrap();
828
829        assert_eq!(result.len(), 2);
830        assert_eq!(result[0].tx_logs.as_ref().unwrap().len(), 1);
831        assert_eq!(result[1].tx_logs.as_ref().unwrap().len(), 2);
832    }
833
834    #[test]
835    fn test_build_bundle_logs_duplicate_transactions_across_nested_bundles() {
836        let duplicate_tx = Bytes::from(vec![0x01, 0x02, 0x03]);
837        let bundle = create_nested_bundle(duplicate_tx.clone(), vec![duplicate_tx]);
838        let result =
839            EthSimBundle::<()>::build_bundle_logs(&bundle, &create_bundle_logs(&[1, 2])).unwrap();
840
841        assert_eq!(result.len(), 2);
842        assert!(result[1].bundle_logs.is_some());
843        assert_eq!(result[0].tx_logs.as_ref().unwrap().len(), 1);
844
845        let nested_logs = result[1].bundle_logs.as_ref().unwrap();
846        assert_eq!(nested_logs.len(), 1);
847        assert_eq!(nested_logs[0].tx_logs.as_ref().unwrap().len(), 2);
848    }
849
850    #[test]
851    fn test_build_bundle_logs_root_with_only_nested_bundles() {
852        let first_nested = create_test_bundle(vec![Bytes::from(vec![0x01])]);
853        let second_nested =
854            create_test_bundle(vec![Bytes::from(vec![0x02]), Bytes::from(vec![0x03])]);
855        let bundle = create_bundle_with_body(vec![
856            BundleItem::Bundle { bundle: first_nested },
857            BundleItem::Bundle { bundle: second_nested },
858        ]);
859        let result =
860            EthSimBundle::<()>::build_bundle_logs(&bundle, &create_bundle_logs(&[1, 1, 2]))
861                .unwrap();
862
863        assert_eq!(result.len(), 2);
864        assert!(result[0].tx_logs.is_none());
865        assert!(result[1].tx_logs.is_none());
866
867        let first_nested_logs = result[0].bundle_logs.as_ref().unwrap();
868        assert_eq!(first_nested_logs.len(), 1);
869        assert_eq!(first_nested_logs[0].tx_logs.as_ref().unwrap().len(), 1);
870
871        let second_nested_logs = result[1].bundle_logs.as_ref().unwrap();
872        assert_eq!(second_nested_logs.len(), 2);
873        assert_eq!(second_nested_logs[0].tx_logs.as_ref().unwrap().len(), 1);
874        assert_eq!(second_nested_logs[1].tx_logs.as_ref().unwrap().len(), 2);
875    }
876
877    #[test]
878    fn test_build_bundle_logs_deeply_nested_bundle() {
879        let leaf_bundle = create_test_bundle(vec![Bytes::from(vec![0x03])]);
880        let middle_bundle = create_bundle_with_body(vec![
881            BundleItem::Tx { tx: Bytes::from(vec![0x02]), can_revert: false },
882            BundleItem::Bundle { bundle: leaf_bundle },
883        ]);
884        let root_bundle = create_bundle_with_body(vec![
885            BundleItem::Tx { tx: Bytes::from(vec![0x01]), can_revert: false },
886            BundleItem::Bundle { bundle: middle_bundle },
887        ]);
888        let result =
889            EthSimBundle::<()>::build_bundle_logs(&root_bundle, &create_bundle_logs(&[1, 2, 3]))
890                .unwrap();
891
892        assert_eq!(result.len(), 2);
893        assert_eq!(result[0].tx_logs.as_ref().unwrap().len(), 1);
894
895        let middle_logs = result[1].bundle_logs.as_ref().unwrap();
896        assert_eq!(middle_logs.len(), 2);
897        assert_eq!(middle_logs[0].tx_logs.as_ref().unwrap().len(), 2);
898
899        let leaf_logs = middle_logs[1].bundle_logs.as_ref().unwrap();
900        assert_eq!(leaf_logs.len(), 1);
901        assert_eq!(leaf_logs[0].tx_logs.as_ref().unwrap().len(), 3);
902    }
903
904    #[test]
905    fn test_build_bundle_logs_mismatched_flat_logs() {
906        let bundle = create_test_bundle(vec![Bytes::from(vec![0x01, 0x02, 0x03])]);
907
908        assert_unmatched_bundle(EthSimBundle::<()>::build_bundle_logs(&bundle, &[]));
909        assert_unmatched_bundle(EthSimBundle::<()>::build_bundle_logs(
910            &bundle,
911            &create_bundle_logs(&[1, 2]),
912        ));
913    }
914
915    /// The bundle's gas budget is capped at the RPC call gas limit, and a limit of 0 disables the
916    /// cap.
917    #[tokio::test(flavor = "multi_thread")]
918    async fn sim_bundle_caps_gas_at_call_gas_limit() {
919        let mut rng = generators::rng();
920        let key = generate_key(&mut rng);
921        let txs: Vec<_> = (0..2)
922            .map(|nonce| {
923                sign_tx_with_key_pair(
924                    key,
925                    reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
926                        chain_id: 1,
927                        nonce,
928                        gas_limit: 21_000,
929                        max_fee_per_gas: INITIAL_BASE_FEE as u128,
930                        to: TxKind::Call(Address::random()),
931                        ..Default::default()
932                    }),
933                )
934            })
935            .collect();
936        let sender = txs[0].recover_signer().unwrap();
937
938        let genesis = Genesis::default()
939            .with_gas_limit(30_000_000)
940            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
941            .extend_accounts([(
942                sender,
943                GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
944            )]);
945        let chain_spec =
946            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
947        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
948        init_genesis(&factory).unwrap();
949        let provider = BlockchainProvider::new(factory).unwrap();
950        let api = |gas_cap: u64| {
951            let eth_api = EthApiBuilder::new(
952                provider.clone(),
953                testing_pool(),
954                NoopNetwork::default(),
955                EthEvmConfig::new(provider.chain_spec()),
956            )
957            .gas_cap(gas_cap.into())
958            .build();
959            EthSimBundle::new(eth_api, BlockingTaskGuard::new(4))
960        };
961        let bundle = create_test_bundle(txs.iter().map(|tx| tx.encoded_2718().into()).collect());
962        let overrides = SimBundleOverrides {
963            block_overrides: BlockOverrides { gas_limit: Some(21_001), ..Default::default() },
964            ..Default::default()
965        };
966
967        let capped = api(21_000);
968        assert_eq!(
969            capped.sim_bundle(bundle.clone(), overrides).await.unwrap_err(),
970            ErrorObjectOwned::from(EthApiError::InvalidTransaction(
971                RpcInvalidTransactionError::GasTooHigh
972            ))
973        );
974        assert_eq!(
975            capped.sim_bundle(bundle.clone(), SimBundleOverrides::default()).await.unwrap_err(),
976            ErrorObjectOwned::from(EthApiError::InvalidParams(
977                EthBundleError::BundleGasLimitExceeded(21_000).to_string()
978            ))
979        );
980        let response = api(0).sim_bundle(bundle, SimBundleOverrides::default()).await.unwrap();
981        assert_eq!(response.gas_used, 42_000);
982    }
983
984    /// Refunds charge one payout per refund config, or a single payout to the signer without one.
985    #[tokio::test(flavor = "multi_thread")]
986    async fn sim_bundle_charges_payout_per_refund_config() {
987        let coinbase = Address::repeat_byte(0x11);
988        let mut rng = generators::rng();
989        let key = generate_key(&mut rng);
990        // Pays `value` to the coinbase, then sends a plain transfer.
991        let txs = |value: U256, max_fee_per_gas: u128| -> Vec<_> {
992            [(0, coinbase, value), (1, Address::random(), U256::ZERO)]
993                .into_iter()
994                .map(|(nonce, to, value)| {
995                    sign_tx_with_key_pair(
996                        key,
997                        reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
998                            chain_id: 1,
999                            nonce,
1000                            gas_limit: 21_000,
1001                            max_fee_per_gas,
1002                            to: TxKind::Call(to),
1003                            value,
1004                            ..Default::default()
1005                        }),
1006                    )
1007                })
1008                .collect()
1009        };
1010        let coinbase_payment = U256::from(10u128.pow(17));
1011        let bundle_txs = txs(coinbase_payment, INITIAL_BASE_FEE as u128);
1012        let sender = bundle_txs[0].recover_signer().unwrap();
1013
1014        let genesis = Genesis::default()
1015            .with_gas_limit(30_000_000)
1016            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
1017            .with_coinbase(coinbase)
1018            .extend_accounts([(
1019                sender,
1020                GenesisAccount::default().with_balance(U256::from(u128::MAX)),
1021            )]);
1022        let chain_spec =
1023            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
1024        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
1025        init_genesis(&factory).unwrap();
1026        let provider = BlockchainProvider::new(factory).unwrap();
1027        let eth_api = EthApiBuilder::new(
1028            provider.clone(),
1029            testing_pool(),
1030            NoopNetwork::default(),
1031            EthEvmConfig::new(provider.chain_spec()),
1032        )
1033        .build();
1034        let api = EthSimBundle::new(eth_api, BlockingTaskGuard::new(4));
1035
1036        for (refund_config, payouts) in [
1037            (None, 1),
1038            (
1039                Some(vec![
1040                    RefundConfig { address: Address::random(), percent: 50 },
1041                    RefundConfig { address: Address::random(), percent: 50 },
1042                ]),
1043                2,
1044            ),
1045        ] {
1046            let mut bundle =
1047                create_test_bundle(bundle_txs.iter().map(|tx| tx.encoded_2718().into()).collect());
1048            bundle.validity = Some(Validity {
1049                refund: Some(vec![Refund { body_idx: 1, percent: 50 }]),
1050                refund_config,
1051            });
1052
1053            let response = api.sim_bundle(bundle, SimBundleOverrides::default()).await.unwrap();
1054            assert_eq!(response.gas_used, 42_000 + SBUNDLE_PAYOUT_MAX_COST * payouts);
1055            assert_eq!(response.refundable_value, coinbase_payment);
1056        }
1057
1058        // The payout is charged at the base fee override as given: the refund covers it at
1059        // `u64::MAX`, but not at this base fee.
1060        let base_fee = U256::from(1u128 << 100);
1061        let override_txs = txs(U256::from(10u128.pow(30)), base_fee.to::<u128>() * 2);
1062        let mut bundle =
1063            create_test_bundle(override_txs.iter().map(|tx| tx.encoded_2718().into()).collect());
1064        bundle.validity = Some(Validity {
1065            refund: Some(vec![Refund { body_idx: 1, percent: 50 }]),
1066            refund_config: None,
1067        });
1068        let overrides = SimBundleOverrides {
1069            block_overrides: BlockOverrides { base_fee: Some(base_fee), ..Default::default() },
1070            ..Default::default()
1071        };
1072        assert_eq!(
1073            api.sim_bundle(bundle, overrides).await.unwrap_err(),
1074            ErrorObjectOwned::from(EthApiError::InvalidParams(
1075                EthSimBundleError::NegativeProfit.to_string()
1076            ))
1077        );
1078    }
1079}