Skip to main content

reth_rpc/eth/
bundle.rs

1//! `Eth` bundle implementation and helpers.
2
3use crate::eth::sim_bundle::{DEFAULT_SIM_TIMEOUT, MAX_SIM_TIMEOUT};
4use alloy_consensus::{transaction::TxHashRef, EnvKzgSettings, Transaction as _};
5use alloy_eips::eip7840::BlobParams;
6use alloy_primitives::{uint, Keccak256, U256};
7use alloy_rpc_types_mev::{EthCallBundle, EthCallBundleResponse, EthCallBundleTransactionResult};
8use evm2::evm::DynDatabase;
9use jsonrpsee::core::RpcResult;
10use reth_chainspec::{ChainSpecProvider, EthChainSpec};
11use reth_evm::{ConfigureEvm, Evm, EvmEnv};
12use reth_rpc_eth_api::{
13    helpers::{Call, EthTransactions},
14    EthCallBundleApiServer, FromEthApiError, FromEvmError,
15};
16use reth_rpc_eth_types::{
17    EthApiError, PendingBlockEnv, PendingBlockEnvOrigin, RpcInvalidTransactionError,
18};
19use reth_storage_api::BlockReaderIdExt;
20use reth_tasks::{cancel::is_cancelled, pool::BlockingTaskGuard};
21use reth_transaction_pool::{
22    EthBlobTransactionSidecar, EthPoolTransaction, PoolTransaction, TransactionPool,
23};
24use std::{
25    sync::Arc,
26    time::{Duration, Instant},
27};
28
29/// `Eth` bundle implementation.
30pub struct EthBundle<Eth> {
31    /// All nested fields bundled together.
32    inner: Arc<EthBundleInner<Eth>>,
33}
34
35impl<Eth> EthBundle<Eth> {
36    /// Create a new `EthBundle` instance.
37    pub fn new(eth_api: Eth, blocking_task_guard: BlockingTaskGuard) -> Self {
38        Self { inner: Arc::new(EthBundleInner { eth_api, blocking_task_guard }) }
39    }
40
41    /// Access the underlying `Eth` API.
42    pub fn eth_api(&self) -> &Eth {
43        &self.inner.eth_api
44    }
45}
46
47impl<Eth> EthBundle<Eth>
48where
49    Eth: EthTransactions + Call,
50{
51    /// Simulates a bundle of transactions at the top of a given block number with the state of
52    /// another (or the same) block. This can be used to simulate future blocks with the current
53    /// state, or it can be used to simulate a past block. The sender is responsible for signing the
54    /// transactions and using the correct nonce and ensuring validity
55    ///
56    /// The simulation is bounded by the request's `timeout` in milliseconds, capped at 30
57    /// seconds, or by 5 seconds if it is missing or zero. No transaction starts after it expires,
58    /// the request then fails with [`EthApiError::ExecutionTimedOut`].
59    pub async fn call_bundle(
60        &self,
61        bundle: EthCallBundle,
62    ) -> Result<EthCallBundleResponse, Eth::Error> {
63        let EthCallBundle {
64            txs,
65            block_number,
66            coinbase,
67            state_block_number,
68            timeout,
69            timestamp,
70            gas_limit,
71            difficulty,
72            base_fee,
73            ..
74        } = bundle;
75        if txs.is_empty() {
76            return Err(EthApiError::InvalidParams(
77                EthBundleError::EmptyBundleTransactions.to_string(),
78            )
79            .into())
80        }
81        if block_number == 0 {
82            return Err(EthApiError::InvalidParams(
83                EthBundleError::BundleMissingBlockNumber.to_string(),
84            )
85            .into())
86        }
87
88        // Validate gas limit against the configured call gas limit before any DB calls
89        let call_gas_limit = self.inner.eth_api.call_gas_limit();
90        if let Some(gas_limit) = gas_limit &&
91            gas_limit > call_gas_limit
92        {
93            return Err(
94                EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into()
95            )
96        }
97
98        // A zero timeout selects the default instead of expiring immediately.
99        let timeout = timeout
100            .filter(|timeout| *timeout > 0)
101            .map(Duration::from_millis)
102            .map_or(DEFAULT_SIM_TIMEOUT, |timeout| timeout.min(MAX_SIM_TIMEOUT));
103
104        let transactions = self.eth_api().recover_raw_pooled_transactions(txs)?;
105
106        let block_id: alloy_rpc_types_eth::BlockId = state_block_number.into();
107        // Note: the block number is considered the `parent` block: <https://github.com/flashbots/mev-geth/blob/fddf97beec5877483f879a77b7dea2e58a58d653/internal/ethapi/api.go#L2104>
108        let (mut evm_env, at, parent) = if block_id.is_pending() {
109            let PendingBlockEnv { evm_env, origin } = self.eth_api().pending_block_env_and_cfg()?;
110            let at = origin.state_block_id();
111            let parent = match origin {
112                PendingBlockEnvOrigin::ActualPending(block, _) => block.clone_sealed_header(),
113                PendingBlockEnvOrigin::DerivedFromLatest(header) => header,
114            };
115            (evm_env, at, parent)
116        } else {
117            let parent = self
118                .eth_api()
119                .provider()
120                .sealed_header_by_id(block_id)
121                .map_err(Eth::Error::from_eth_err)?
122                .ok_or(EthApiError::HeaderNotFound(block_id))?;
123            let evm_env = self.eth_api().evm_env_for_header(&parent)?;
124            (evm_env, parent.hash().into(), parent)
125        };
126
127        if let Some(coinbase) = coinbase {
128            evm_env.block_env_mut().beneficiary = coinbase;
129        }
130
131        // need to adjust the timestamp for the next block
132        if let Some(timestamp) = timestamp {
133            evm_env.block_env_mut().timestamp = U256::from(timestamp);
134        } else {
135            evm_env.block_env_mut().timestamp += uint!(12_U256);
136        }
137
138        if let Some(difficulty) = difficulty {
139            evm_env.block_env_mut().difficulty = difficulty;
140        }
141
142        // Validate that the bundle does not contain more than MAX_BLOB_NUMBER_PER_BLOCK blob
143        // transactions.
144        let blob_gas_used = transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::<u64>();
145        if blob_gas_used > 0 {
146            let blob_params = self
147                .eth_api()
148                .provider()
149                .chain_spec()
150                .blob_params_at_timestamp(evm_env.block_env().timestamp.saturating_to())
151                .unwrap_or_else(BlobParams::cancun);
152            if blob_gas_used > blob_params.max_blob_gas_per_block() {
153                return Err(EthApiError::InvalidParams(
154                    EthBundleError::Eip4844BlobGasExceeded(blob_params.max_blob_gas_per_block())
155                        .to_string(),
156                )
157                .into())
158            }
159        }
160
161        // Apply gas limit: default to call gas limit unless user requests a smaller limit
162        let block_gas_limit = gas_limit.unwrap_or(call_gas_limit);
163        evm_env.block_env_mut().gas_limit = U256::from(block_gas_limit);
164
165        // The bundle is simulated on top of the state block, so default to the next block's base
166        // fee. <https://github.com/flashbots/mev-geth/blob/fddf97beec5877483f879a77b7dea2e58a58d653/internal/ethapi/api.go#L2130>
167        if let Some(base_fee) = base_fee {
168            evm_env.block_env_mut().basefee = U256::from(base_fee.min(u64::MAX as u128));
169        } else if let Some(next_base_fee) = self
170            .eth_api()
171            .provider()
172            .chain_spec()
173            .next_block_base_fee(&parent, evm_env.block_env().timestamp.saturating_to())
174        {
175            evm_env.block_env_mut().basefee = U256::from(next_base_fee);
176        }
177
178        let state_block_number = evm_env.block_env().number;
179        // use the block number of the request
180        evm_env.block_env_mut().number = U256::from(block_number);
181
182        let permit = self
183            .eth_api()
184            .acquire_owned_blocking_io()
185            .await
186            .map_err(|_| EthApiError::InternalEthError)?;
187
188        self.eth_api()
189            .spawn_with_state_at_block(at, move |eth_api, mut db| {
190                let _permit = permit;
191                let coinbase = evm_env.block_env().beneficiary;
192                let basefee = evm_env.block_base_fee();
193
194                let initial_coinbase = db
195                    .get_account(&coinbase)
196                    .map_err(Eth::Error::from_eth_err)?
197                    .map(|acc| acc.balance)
198                    .unwrap_or_default();
199                let mut block_gas = BundleBlockGas::new(block_gas_limit, evm_env.version());
200                let mut evm = eth_api.evm_config().evm_with_env(&mut db, evm_env);
201                let mut coinbase_balance_before_tx = initial_coinbase;
202                let mut coinbase_balance_after_tx = initial_coinbase;
203                let mut total_gas_fees = U256::ZERO;
204                let mut hasher = Keccak256::new();
205
206                let mut results = Vec::with_capacity(transactions.len());
207                // Starts here, so waiting for the permit does not count.
208                let deadline = Instant::now() + timeout;
209                for tx in transactions {
210                    if is_cancelled() {
211                        return Err(EthApiError::InternalEthError.into())
212                    }
213
214                    if Instant::now() >= deadline {
215                        return Err(EthApiError::ExecutionTimedOut(timeout).into())
216                    }
217
218                    if !block_gas.admits(tx.gas_limit()) {
219                        return Err(EthApiError::InvalidParams(
220                            EthBundleError::BundleGasLimitExceeded(block_gas_limit).to_string(),
221                        )
222                        .into())
223                    }
224
225                    let signer = tx.signer();
226                    let tx = {
227                        let mut tx = <Eth::Pool as TransactionPool>::Transaction::from_pooled(tx);
228
229                        if let EthBlobTransactionSidecar::Present(sidecar) = tx.take_blob() {
230                            tx.validate_blob(&sidecar, EnvKzgSettings::Default.get()).map_err(
231                                |e| {
232                                    Eth::Error::from_eth_err(EthApiError::InvalidParams(
233                                        e.to_string(),
234                                    ))
235                                },
236                            )?;
237                        }
238
239                        tx.into_consensus()
240                    };
241
242                    let tx_hash = *tx.tx_hash();
243                    hasher.update(tx_hash);
244                    // Fee caps below the base fee are only rejected by the EVM from London on.
245                    let gas_price = tx.effective_tip_per_gas(basefee).ok_or_else(|| {
246                        Eth::Error::from_eth_err(EthApiError::InvalidTransaction(
247                            RpcInvalidTransactionError::FeeCapTooLow,
248                        ))
249                    })?;
250                    let to_address = tx.inner().to();
251                    let tx_env = eth_api.evm_config().tx_env(tx);
252                    let result = evm.transact_commit(&tx_env).map_err(Eth::Error::from_evm_err)?;
253
254                    let gas_used = result.tx_gas_used();
255                    block_gas.record(&result);
256
257                    let gas_fees = U256::from(gas_used) * U256::from(gas_price);
258                    total_gas_fees += gas_fees;
259
260                    coinbase_balance_after_tx = evm
261                        .account_info(&coinbase)
262                        .map_err(Eth::Error::from_evm_err)?
263                        .map(|acc| acc.balance)
264                        .unwrap_or_default();
265                    let coinbase_diff =
266                        coinbase_balance_after_tx.saturating_sub(coinbase_balance_before_tx);
267                    let eth_sent_to_coinbase = coinbase_diff.saturating_sub(gas_fees);
268
269                    // update the coinbase balance
270                    coinbase_balance_before_tx = coinbase_balance_after_tx;
271
272                    // set the return data for the response
273                    let (value, revert) = if result.status {
274                        let value = result.output;
275                        (Some(value), None)
276                    } else {
277                        let revert = result.output;
278                        (None, Some(revert))
279                    };
280
281                    let tx_res = EthCallBundleTransactionResult {
282                        coinbase_diff,
283                        eth_sent_to_coinbase,
284                        from_address: signer,
285                        gas_fees,
286                        gas_price: U256::from(gas_price),
287                        gas_used,
288                        to_address,
289                        tx_hash,
290                        value,
291                        revert,
292                    };
293                    results.push(tx_res);
294                }
295
296                // populate the response
297
298                let total_gas_used = block_gas.gas_used();
299                let coinbase_diff = coinbase_balance_after_tx.saturating_sub(initial_coinbase);
300                let eth_sent_to_coinbase = coinbase_diff.saturating_sub(total_gas_fees);
301                let bundle_gas_price =
302                    coinbase_diff.checked_div(U256::from(total_gas_used)).unwrap_or_default();
303                let res = EthCallBundleResponse {
304                    bundle_gas_price,
305                    bundle_hash: hasher.finalize(),
306                    coinbase_diff,
307                    eth_sent_to_coinbase,
308                    gas_fees: total_gas_fees,
309                    results,
310                    state_block_number: state_block_number.to(),
311                    total_gas_used,
312                };
313
314                Ok(res)
315            })
316            .await
317    }
318}
319
320impl<Eth> EthCallBundleApiServer for EthBundle<Eth>
321where
322    Eth: EthTransactions + Call,
323{
324    async fn call_bundle(&self, request: EthCallBundle) -> RpcResult<EthCallBundleResponse> {
325        Self::call_bundle(self, request).await.map_err(Into::into)
326    }
327}
328
329/// Container type for `EthBundle` internals
330#[derive(Debug)]
331struct EthBundleInner<Eth> {
332    /// Access to commonly used code of the `eth` namespace
333    eth_api: Eth,
334    // restrict the number of concurrent tracing calls.
335    #[expect(dead_code)]
336    blocking_task_guard: BlockingTaskGuard,
337}
338
339impl<Eth> std::fmt::Debug for EthBundle<Eth> {
340    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
341        f.debug_struct("EthBundle").finish_non_exhaustive()
342    }
343}
344
345impl<Eth> Clone for EthBundle<Eth> {
346    fn clone(&self) -> Self {
347        Self { inner: Arc::clone(&self.inner) }
348    }
349}
350
351/// [`EthBundle`] specific errors.
352#[derive(Debug, thiserror::Error)]
353pub enum EthBundleError {
354    /// Thrown if the bundle does not contain any transactions.
355    #[error("bundle missing txs")]
356    EmptyBundleTransactions,
357    /// Thrown if the bundle does not contain a block number, or block number is 0.
358    #[error("bundle missing blockNumber")]
359    BundleMissingBlockNumber,
360    /// Thrown when the blob gas usage of the blob transactions in a bundle exceed the maximum.
361    #[error("blob gas usage exceeds the limit of {0} gas per block.")]
362    Eip4844BlobGasExceeded(u64),
363    /// Thrown when the gas limits of the bundle's transactions exceed the block gas limit.
364    #[error("bundle gas exceeds the block gas limit of {0}")]
365    BundleGasLimitExceeded(u64),
366}
367
368/// Gas a simulated bundle uses from the block it is simulated in.
369///
370/// Transactions are admitted against the gas left in the block, like the block executor does:
371/// EIP-8037 keeps separate regular and state gas pools.
372#[derive(Debug)]
373pub(crate) struct BundleBlockGas {
374    limit: u64,
375    tx_gas_limit_cap: u64,
376    separate_pools: bool,
377    gas_used: u64,
378    regular_gas_used: u64,
379    state_gas_used: u64,
380}
381
382impl BundleBlockGas {
383    /// Creates an unused budget of `limit` gas for a block executed with `version`.
384    pub(crate) const fn new(limit: u64, version: &evm2::Version) -> Self {
385        Self {
386            limit,
387            tx_gas_limit_cap: version.tx_gas_limit_cap,
388            separate_pools: version.feature(evm2::EvmFeatures::EIP8037),
389            gas_used: 0,
390            regular_gas_used: 0,
391            state_gas_used: 0,
392        }
393    }
394
395    /// Returns the receipt gas used by the recorded transactions.
396    pub(crate) const fn gas_used(&self) -> u64 {
397        self.gas_used
398    }
399
400    /// Returns whether a transaction with `gas_limit` fits in the gas left in the block.
401    pub(crate) fn admits(&self, gas_limit: u64) -> bool {
402        let regular_limit = gas_limit.min(self.tx_gas_limit_cap);
403        if self.separate_pools {
404            regular_limit <= self.limit.saturating_sub(self.regular_gas_used) &&
405                gas_limit <= self.limit.saturating_sub(self.state_gas_used)
406        } else {
407            regular_limit <= self.limit.saturating_sub(self.gas_used)
408        }
409    }
410
411    /// Records the gas spent by an executed transaction.
412    pub(crate) const fn record<E>(&mut self, result: &evm2::TxResultExt<E>) {
413        self.gas_used += result.tx_gas_used();
414        self.regular_gas_used += result.execution_gas_spent();
415        self.state_gas_used += result.state_gas_spent();
416    }
417}
418
419#[cfg(test)]
420mod tests {
421    use super::*;
422    use crate::EthApiBuilder;
423    use alloy_consensus::{transaction::SignerRecoverable, TxEip1559};
424    use alloy_eips::{eip1559::INITIAL_BASE_FEE, eip2718::Encodable2718, BlockNumberOrTag};
425    use alloy_genesis::{Genesis, GenesisAccount};
426    use alloy_primitives::{Address, TxKind};
427    use reth_chain_state::{CanonicalInMemoryStateWriter, ExecutedBlock};
428    use reth_chainspec::ChainSpecBuilder;
429    use reth_db_common::init::init_genesis;
430    use reth_ethereum_primitives::Block as EthBlock;
431    use reth_evm_ethereum::EthEvmConfig;
432    use reth_network_api::noop::NoopNetwork;
433    use reth_primitives_traits::RecoveredBlock;
434    use reth_provider::{
435        providers::BlockchainProvider,
436        test_utils::{
437            create_test_provider_factory_with_chain_spec,
438            create_test_provider_factory_with_in_memory_state_writer,
439        },
440    };
441    use reth_rpc_eth_api::helpers::SpawnBlocking;
442    use reth_testing_utils::generators::{self, generate_key, sign_tx_with_key_pair};
443    use reth_transaction_pool::test_utils::testing_pool;
444
445    /// The bundle is simulated in the block after the state block, so a transaction that only
446    /// covers the next block's base fee, but not the state block's, must be accepted.
447    #[tokio::test(flavor = "multi_thread")]
448    async fn call_bundle_uses_next_block_base_fee() {
449        let mut rng = generators::rng();
450        let key = generate_key(&mut rng);
451        // genesis is empty, so the next base fee is 7/8 of the initial base fee
452        let next_base_fee = INITIAL_BASE_FEE - INITIAL_BASE_FEE / 8;
453        let tx = sign_tx_with_key_pair(
454            key,
455            reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
456                chain_id: 1,
457                nonce: 0,
458                gas_limit: 21_000,
459                max_fee_per_gas: (next_base_fee + 1) as u128,
460                max_priority_fee_per_gas: (next_base_fee + 1) as u128,
461                to: TxKind::Call(Address::random()),
462                ..Default::default()
463            }),
464        );
465        let sender = tx.recover_signer().unwrap();
466
467        let genesis = Genesis::default()
468            .with_gas_limit(30_000_000)
469            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
470            .extend_accounts([(
471                sender,
472                GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
473            )]);
474        let chain_spec =
475            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
476        let (factory, in_memory_state_writer) =
477            create_test_provider_factory_with_in_memory_state_writer(chain_spec);
478        init_genesis(&factory).unwrap();
479        let mut canonical_in_memory_state_writer = CanonicalInMemoryStateWriter::new(
480            factory.chain_info_headers().unwrap(),
481            in_memory_state_writer,
482        );
483        let provider = BlockchainProvider::with_canonical_in_memory_state(
484            factory,
485            canonical_in_memory_state_writer.canonical_in_memory_state().clone(),
486        );
487
488        let eth_api = EthApiBuilder::new(
489            provider.clone(),
490            testing_pool(),
491            NoopNetwork::default(),
492            EthEvmConfig::new(provider.chain_spec()),
493        )
494        .build();
495        let api = EthBundle::new(eth_api, BlockingTaskGuard::new(4));
496
497        let bundle = EthCallBundle {
498            txs: vec![tx.encoded_2718().into()],
499            block_number: 1,
500            state_block_number: BlockNumberOrTag::Number(0),
501            ..Default::default()
502        };
503        for state_block_number in
504            [BlockNumberOrTag::Number(0), BlockNumberOrTag::Latest, BlockNumberOrTag::Pending]
505        {
506            for base_fee in [None, Some((next_base_fee - 1) as u128)] {
507                let response = api
508                    .call_bundle(EthCallBundle { state_block_number, base_fee, ..bundle.clone() })
509                    .await
510                    .unwrap();
511                let expected_tip =
512                    (next_base_fee + 1) as u128 - base_fee.unwrap_or(next_base_fee as u128);
513                assert_bundle_fees(&response, expected_tip);
514            }
515        }
516
517        let error = api
518            .call_bundle(EthCallBundle { base_fee: Some(u128::MAX), ..bundle.clone() })
519            .await
520            .unwrap_err();
521        assert!(
522            matches!(
523                error.as_invalid_transaction(),
524                Some(reth_rpc_eth_types::RpcInvalidTransactionError::FeeCapTooLow)
525            ),
526            "{error:?}"
527        );
528
529        // An actual pending block is not canonical and has its own base fee.
530        let chain_spec = provider.chain_spec();
531        let mut header = chain_spec.genesis_header().clone();
532        header.parent_hash = chain_spec.genesis_hash();
533        header.number = 1;
534        header.timestamp = 12;
535        header.base_fee_per_gas = Some(next_base_fee);
536        let pending_block = ExecutedBlock {
537            recovered_block: Arc::new(RecoveredBlock::new_unhashed(
538                EthBlock { header, body: Default::default() },
539                vec![],
540            )),
541            ..Default::default()
542        };
543        canonical_in_memory_state_writer.set_pending_block(pending_block);
544        let pending_next_base_fee = next_base_fee - next_base_fee / 8;
545        for base_fee in [None, Some((pending_next_base_fee - 1) as u128)] {
546            let response = api
547                .call_bundle(EthCallBundle {
548                    block_number: 2,
549                    state_block_number: BlockNumberOrTag::Pending,
550                    base_fee,
551                    ..bundle.clone()
552                })
553                .await
554                .unwrap();
555            let expected_tip =
556                (next_base_fee + 1) as u128 - base_fee.unwrap_or(pending_next_base_fee as u128);
557            assert_bundle_fees(&response, expected_tip);
558        }
559    }
560
561    /// The bundle's transactions share the block gas limit, and the simulation waits for a
562    /// blocking IO permit.
563    #[tokio::test(flavor = "multi_thread")]
564    async fn call_bundle_shares_gas_limit_and_takes_blocking_io_permit() {
565        let mut rng = generators::rng();
566        let key = generate_key(&mut rng);
567        let txs: Vec<_> = (0..2)
568            .map(|nonce| {
569                sign_tx_with_key_pair(
570                    key,
571                    reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
572                        chain_id: 1,
573                        nonce,
574                        gas_limit: 21_000,
575                        max_fee_per_gas: INITIAL_BASE_FEE as u128,
576                        to: TxKind::Call(Address::random()),
577                        ..Default::default()
578                    }),
579                )
580            })
581            .collect();
582        let sender = txs[0].recover_signer().unwrap();
583
584        let genesis = Genesis::default()
585            .with_gas_limit(30_000_000)
586            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
587            .extend_accounts([(
588                sender,
589                GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
590            )]);
591        let chain_spec =
592            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
593        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
594        init_genesis(&factory).unwrap();
595        let provider = BlockchainProvider::new(factory).unwrap();
596
597        let eth_api = EthApiBuilder::new(
598            provider.clone(),
599            testing_pool(),
600            NoopNetwork::default(),
601            EthEvmConfig::new(provider.chain_spec()),
602        )
603        .max_blocking_io_requests(1)
604        .build();
605        let api = EthBundle::new(eth_api.clone(), BlockingTaskGuard::new(4));
606
607        let bundle = EthCallBundle {
608            txs: txs.iter().map(|tx| tx.encoded_2718().into()).collect(),
609            block_number: 1,
610            state_block_number: BlockNumberOrTag::Number(0),
611            ..Default::default()
612        };
613
614        let error = api
615            .call_bundle(EthCallBundle { gas_limit: Some(41_999), ..bundle.clone() })
616            .await
617            .unwrap_err();
618        assert_eq!(
619            error.to_string(),
620            EthApiError::InvalidParams(EthBundleError::BundleGasLimitExceeded(41_999).to_string())
621                .to_string()
622        );
623
624        let bundle = EthCallBundle { gas_limit: Some(42_000), ..bundle };
625        let permit = eth_api.acquire_owned_blocking_io().await.unwrap();
626        assert!(tokio::time::timeout(
627            std::time::Duration::from_millis(200),
628            api.call_bundle(bundle.clone())
629        )
630        .await
631        .is_err());
632
633        drop(permit);
634        let response = api.call_bundle(bundle).await.unwrap();
635        assert_eq!(response.total_gas_used, 42_000);
636    }
637
638    /// Under EIP-8037 the bundle admits transactions against separate regular and state gas
639    /// pools, so a bundle that fits a block is accepted even when its receipt gas does not fit
640    /// one pool.
641    #[tokio::test(flavor = "multi_thread")]
642    async fn call_bundle_uses_separate_gas_pools_after_amsterdam() {
643        const TX_GAS_LIMIT: u64 = 1_000_000;
644
645        let mut rng = generators::rng();
646        let key = generate_key(&mut rng);
647        // Value transfers to new accounts spend both regular and state gas.
648        let txs: Vec<_> = (0..2)
649            .map(|nonce| {
650                sign_tx_with_key_pair(
651                    key,
652                    reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
653                        chain_id: 1,
654                        nonce,
655                        gas_limit: TX_GAS_LIMIT,
656                        max_fee_per_gas: INITIAL_BASE_FEE as u128,
657                        to: TxKind::Call(Address::random()),
658                        value: U256::from(1),
659                        ..Default::default()
660                    }),
661                )
662            })
663            .collect();
664        let sender = txs[0].recover_signer().unwrap();
665
666        let genesis = Genesis::default()
667            .with_gas_limit(30_000_000)
668            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
669            .extend_accounts([(
670                sender,
671                GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
672            )]);
673        let chain_spec =
674            Arc::new(ChainSpecBuilder::mainnet().amsterdam_activated().genesis(genesis).build());
675        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
676        init_genesis(&factory).unwrap();
677        let provider = BlockchainProvider::new(factory).unwrap();
678
679        let eth_api = EthApiBuilder::new(
680            provider.clone(),
681            testing_pool(),
682            NoopNetwork::default(),
683            EthEvmConfig::new(provider.chain_spec()),
684        )
685        .build();
686        let api = EthBundle::new(eth_api, BlockingTaskGuard::new(4));
687
688        let bundle = EthCallBundle {
689            txs: txs.iter().map(|tx| tx.encoded_2718().into()).collect(),
690            block_number: 1,
691            state_block_number: BlockNumberOrTag::Number(0),
692            ..Default::default()
693        };
694        let first_gas_used = api.call_bundle(bundle.clone()).await.unwrap().results[0].gas_used;
695
696        // The second transaction fits both pools, but not one pool holding the first
697        // transaction's regular and state gas together.
698        let gas_limit = TX_GAS_LIMIT + first_gas_used - 1;
699        let response =
700            api.call_bundle(EthCallBundle { gas_limit: Some(gas_limit), ..bundle }).await.unwrap();
701        assert_eq!(response.results.len(), 2);
702    }
703
704    /// A pre-London state has no base fee check in the EVM, so the bundle must reject a fee cap
705    /// below the supplied base fee instead of panicking.
706    #[tokio::test(flavor = "multi_thread")]
707    async fn call_bundle_rejects_fee_cap_below_base_fee_before_london() {
708        let mut rng = generators::rng();
709        let key = generate_key(&mut rng);
710        let tx = sign_tx_with_key_pair(
711            key,
712            reth_ethereum_primitives::Transaction::Legacy(alloy_consensus::TxLegacy {
713                chain_id: Some(1),
714                nonce: 0,
715                gas_price: 1,
716                gas_limit: 21_000,
717                to: TxKind::Call(Address::random()),
718                ..Default::default()
719            }),
720        );
721        let sender = tx.recover_signer().unwrap();
722
723        let genesis = Genesis::default().with_gas_limit(30_000_000).extend_accounts([(
724            sender,
725            GenesisAccount::default().with_balance(U256::from(10u128.pow(18))),
726        )]);
727        let chain_spec =
728            Arc::new(ChainSpecBuilder::mainnet().berlin_activated().genesis(genesis).build());
729        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
730        init_genesis(&factory).unwrap();
731        let provider = BlockchainProvider::new(factory).unwrap();
732
733        let eth_api = EthApiBuilder::new(
734            provider.clone(),
735            testing_pool(),
736            NoopNetwork::default(),
737            EthEvmConfig::new(provider.chain_spec()),
738        )
739        .build();
740        let api = EthBundle::new(eth_api, BlockingTaskGuard::new(4));
741
742        let error = api
743            .call_bundle(EthCallBundle {
744                txs: vec![tx.encoded_2718().into()],
745                block_number: 1,
746                state_block_number: BlockNumberOrTag::Number(0),
747                base_fee: Some(100),
748                ..Default::default()
749            })
750            .await
751            .unwrap_err();
752        assert!(
753            matches!(
754                error.as_invalid_transaction(),
755                Some(RpcInvalidTransactionError::FeeCapTooLow)
756            ),
757            "{error:?}"
758        );
759    }
760
761    /// A pre-Cancun transaction can selfdestruct the coinbase; later fees must then be counted
762    /// from a zero balance.
763    #[tokio::test(flavor = "multi_thread")]
764    async fn call_bundle_counts_fees_after_coinbase_selfdestruct() {
765        let mut rng = generators::rng();
766        let key = generate_key(&mut rng);
767        let tip = INITIAL_BASE_FEE - INITIAL_BASE_FEE / 8 + 1;
768        let coinbase = Address::random();
769        let tx = |nonce, to| {
770            sign_tx_with_key_pair(
771                key,
772                reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
773                    chain_id: 1,
774                    nonce,
775                    gas_limit: 100_000,
776                    max_fee_per_gas: tip as u128 * 2,
777                    max_priority_fee_per_gas: tip as u128,
778                    to: TxKind::Call(to),
779                    ..Default::default()
780                }),
781            )
782        };
783        let txs = [tx(0, coinbase), tx(1, Address::random())];
784        let sender = txs[0].recover_signer().unwrap();
785
786        // `PUSH0 SELFDESTRUCT`
787        let selfdestruct_code = [0x5f, 0xff];
788        let genesis = Genesis::default()
789            .with_gas_limit(30_000_000)
790            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
791            .extend_accounts([
792                (sender, GenesisAccount::default().with_balance(U256::from(10u128.pow(18)))),
793                (
794                    coinbase,
795                    GenesisAccount::default()
796                        .with_balance(U256::from(10u128.pow(18)))
797                        .with_code(Some(selfdestruct_code.into())),
798                ),
799            ]);
800        let chain_spec =
801            Arc::new(ChainSpecBuilder::mainnet().shanghai_activated().genesis(genesis).build());
802        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
803        init_genesis(&factory).unwrap();
804        let provider = BlockchainProvider::new(factory).unwrap();
805
806        let eth_api = EthApiBuilder::new(
807            provider.clone(),
808            testing_pool(),
809            NoopNetwork::default(),
810            EthEvmConfig::new(provider.chain_spec()),
811        )
812        .build();
813        let api = EthBundle::new(eth_api, BlockingTaskGuard::new(4));
814
815        let response = api
816            .call_bundle(EthCallBundle {
817                txs: txs.iter().map(|tx| tx.encoded_2718().into()).collect(),
818                block_number: 1,
819                state_block_number: BlockNumberOrTag::Number(0),
820                coinbase: Some(coinbase),
821                ..Default::default()
822            })
823            .await
824            .unwrap();
825
826        assert_eq!(response.results[0].revert, None);
827        assert_eq!(response.results[1].coinbase_diff, response.results[1].gas_fees);
828    }
829
830    /// No transaction starts once the bundle's timeout has expired, and a zero timeout selects
831    /// the default instead of expiring immediately.
832    #[tokio::test(flavor = "multi_thread")]
833    async fn call_bundle_times_out() {
834        let mut rng = generators::rng();
835        let key = generate_key(&mut rng);
836        let looping = Address::random();
837        let tx = |nonce, to, gas_limit| {
838            sign_tx_with_key_pair(
839                key,
840                reth_ethereum_primitives::Transaction::Eip1559(TxEip1559 {
841                    chain_id: 1,
842                    nonce,
843                    gas_limit,
844                    max_fee_per_gas: INITIAL_BASE_FEE as u128,
845                    to: TxKind::Call(to),
846                    ..Default::default()
847                }),
848            )
849        };
850        // Burns its whole gas limit, which takes longer than 1ms.
851        let slow = tx(0, looping, 10_000_000);
852        let transfer = |nonce| tx(nonce, Address::random(), 21_000);
853        let sender = slow.recover_signer().unwrap();
854
855        // `JUMPDEST PUSH0 JUMP`
856        let looping_code = [0x5b, 0x5f, 0x56];
857        let genesis = Genesis::default()
858            .with_gas_limit(30_000_000)
859            .with_base_fee(Some(INITIAL_BASE_FEE as u128))
860            .extend_accounts([
861                (sender, GenesisAccount::default().with_balance(U256::from(10u128.pow(18)))),
862                (looping, GenesisAccount::default().with_code(Some(looping_code.into()))),
863            ]);
864        let chain_spec =
865            Arc::new(ChainSpecBuilder::mainnet().cancun_activated().genesis(genesis).build());
866        let factory = create_test_provider_factory_with_chain_spec(chain_spec);
867        init_genesis(&factory).unwrap();
868        let provider = BlockchainProvider::new(factory).unwrap();
869
870        let eth_api = EthApiBuilder::new(
871            provider.clone(),
872            testing_pool(),
873            NoopNetwork::default(),
874            EthEvmConfig::new(provider.chain_spec()),
875        )
876        .build();
877        let api = EthBundle::new(eth_api, BlockingTaskGuard::new(4));
878
879        let bundle = EthCallBundle {
880            block_number: 1,
881            state_block_number: BlockNumberOrTag::Number(0),
882            ..Default::default()
883        };
884
885        let error = api
886            .call_bundle(EthCallBundle {
887                txs: vec![slow.encoded_2718().into(), transfer(1).encoded_2718().into()],
888                timeout: Some(1),
889                ..bundle.clone()
890            })
891            .await
892            .unwrap_err();
893        assert!(
894            matches!(
895                error,
896                EthApiError::ExecutionTimedOut(timeout) if timeout == Duration::from_millis(1)
897            ),
898            "{error:?}"
899        );
900
901        let response = api
902            .call_bundle(EthCallBundle {
903                txs: vec![transfer(0).encoded_2718().into()],
904                timeout: Some(0),
905                ..bundle
906            })
907            .await
908            .unwrap();
909        assert_eq!(response.results.len(), 1);
910    }
911
912    fn assert_bundle_fees(response: &EthCallBundleResponse, expected_tip: u128) {
913        assert_eq!(response.results.len(), 1);
914        assert_eq!(response.total_gas_used, 21_000);
915        let gas_price = U256::from(expected_tip);
916        let gas_fees = gas_price * U256::from(21_000);
917        assert_eq!(response.results[0].gas_price, gas_price);
918        assert_eq!(response.results[0].gas_fees, gas_fees);
919        assert_eq!(response.gas_fees, gas_fees);
920        assert_eq!(response.bundle_gas_price, gas_price);
921        assert_eq!(response.coinbase_diff, gas_fees);
922    }
923}