reth_rpc/eth/
bundle.rs

1//! `Eth` bundle implementation and helpers.
2
3use alloy_consensus::{transaction::TxHashRef, EnvKzgSettings, Transaction as _};
4use alloy_eips::eip7840::BlobParams;
5use alloy_evm::env::BlockEnvironment;
6use alloy_primitives::{uint, Keccak256, U256};
7use alloy_rpc_types_mev::{EthCallBundle, EthCallBundleResponse, EthCallBundleTransactionResult};
8use jsonrpsee::core::RpcResult;
9use reth_chainspec::{ChainSpecProvider, EthChainSpec};
10use reth_evm::{ConfigureEvm, Evm};
11use reth_rpc_eth_api::{
12    helpers::{Call, EthTransactions, LoadPendingBlock},
13    EthCallBundleApiServer, FromEthApiError, FromEvmError,
14};
15use reth_rpc_eth_types::{utils::recover_raw_transaction, EthApiError, RpcInvalidTransactionError};
16use reth_tasks::pool::BlockingTaskGuard;
17use reth_transaction_pool::{
18    EthBlobTransactionSidecar, EthPoolTransaction, PoolPooledTx, PoolTransaction, TransactionPool,
19};
20use revm::{
21    context::Block, context_interface::result::ResultAndState, DatabaseCommit, DatabaseRef,
22};
23use std::sync::Arc;
24
25/// `Eth` bundle implementation.
26pub struct EthBundle<Eth> {
27    /// All nested fields bundled together.
28    inner: Arc<EthBundleInner<Eth>>,
29}
30
31impl<Eth> EthBundle<Eth> {
32    /// Create a new `EthBundle` instance.
33    pub fn new(eth_api: Eth, blocking_task_guard: BlockingTaskGuard) -> Self {
34        Self { inner: Arc::new(EthBundleInner { eth_api, blocking_task_guard }) }
35    }
36
37    /// Access the underlying `Eth` API.
38    pub fn eth_api(&self) -> &Eth {
39        &self.inner.eth_api
40    }
41}
42
43impl<Eth> EthBundle<Eth>
44where
45    Eth: EthTransactions + LoadPendingBlock + Call + 'static,
46{
47    /// Simulates a bundle of transactions at the top of a given block number with the state of
48    /// another (or the same) block. This can be used to simulate future blocks with the current
49    /// state, or it can be used to simulate a past block. The sender is responsible for signing the
50    /// transactions and using the correct nonce and ensuring validity
51    pub async fn call_bundle(
52        &self,
53        bundle: EthCallBundle,
54    ) -> Result<EthCallBundleResponse, Eth::Error> {
55        let EthCallBundle {
56            txs,
57            block_number,
58            coinbase,
59            state_block_number,
60            timeout: _,
61            timestamp,
62            gas_limit,
63            difficulty,
64            base_fee,
65            ..
66        } = bundle;
67        if txs.is_empty() {
68            return Err(EthApiError::InvalidParams(
69                EthBundleError::EmptyBundleTransactions.to_string(),
70            )
71            .into())
72        }
73        if block_number == 0 {
74            return Err(EthApiError::InvalidParams(
75                EthBundleError::BundleMissingBlockNumber.to_string(),
76            )
77            .into())
78        }
79
80        let transactions = txs
81            .into_iter()
82            .map(|tx| recover_raw_transaction::<PoolPooledTx<Eth::Pool>>(&tx))
83            .collect::<Result<Vec<_>, _>>()?
84            .into_iter()
85            .collect::<Vec<_>>();
86
87        let block_id: alloy_rpc_types_eth::BlockId = state_block_number.into();
88        // Note: the block number is considered the `parent` block: <https://github.com/flashbots/mev-geth/blob/fddf97beec5877483f879a77b7dea2e58a58d653/internal/ethapi/api.go#L2104>
89        let (mut evm_env, at) = self.eth_api().evm_env_at(block_id).await?;
90
91        if let Some(coinbase) = coinbase {
92            evm_env.block_env.inner_mut().beneficiary = coinbase;
93        }
94
95        // need to adjust the timestamp for the next block
96        if let Some(timestamp) = timestamp {
97            evm_env.block_env.inner_mut().timestamp = U256::from(timestamp);
98        } else {
99            evm_env.block_env.inner_mut().timestamp += uint!(12_U256);
100        }
101
102        if let Some(difficulty) = difficulty {
103            evm_env.block_env.inner_mut().difficulty = U256::from(difficulty);
104        }
105
106        // Validate that the bundle does not contain more than MAX_BLOB_NUMBER_PER_BLOCK blob
107        // transactions.
108        let blob_gas_used = transactions.iter().filter_map(|tx| tx.blob_gas_used()).sum::<u64>();
109        if blob_gas_used > 0 {
110            let blob_params = self
111                .eth_api()
112                .provider()
113                .chain_spec()
114                .blob_params_at_timestamp(evm_env.block_env.timestamp().saturating_to())
115                .unwrap_or_else(BlobParams::cancun);
116            if blob_gas_used > blob_params.max_blob_gas_per_block() {
117                return Err(EthApiError::InvalidParams(
118                    EthBundleError::Eip4844BlobGasExceeded(blob_params.max_blob_gas_per_block())
119                        .to_string(),
120                )
121                .into())
122            }
123        }
124
125        // default to call gas limit unless user requests a smaller limit
126        evm_env.block_env.inner_mut().gas_limit = self.inner.eth_api.call_gas_limit();
127        if let Some(gas_limit) = gas_limit {
128            if gas_limit > evm_env.block_env.gas_limit() {
129                return Err(
130                    EthApiError::InvalidTransaction(RpcInvalidTransactionError::GasTooHigh).into()
131                )
132            }
133            evm_env.block_env.inner_mut().gas_limit = gas_limit;
134        }
135
136        if let Some(base_fee) = base_fee {
137            evm_env.block_env.inner_mut().basefee = base_fee.try_into().unwrap_or(u64::MAX);
138        }
139
140        let state_block_number = evm_env.block_env.number();
141        // use the block number of the request
142        evm_env.block_env.inner_mut().number = U256::from(block_number);
143
144        self.eth_api()
145            .spawn_with_state_at_block(at, move |eth_api, db| {
146                let coinbase = evm_env.block_env.beneficiary();
147                let basefee = evm_env.block_env.basefee();
148
149                let initial_coinbase = db
150                    .basic_ref(coinbase)
151                    .map_err(Eth::Error::from_eth_err)?
152                    .map(|acc| acc.balance)
153                    .unwrap_or_default();
154                let mut coinbase_balance_before_tx = initial_coinbase;
155                let mut coinbase_balance_after_tx = initial_coinbase;
156                let mut total_gas_used = 0u64;
157                let mut total_gas_fees = U256::ZERO;
158                let mut hasher = Keccak256::new();
159
160                let mut evm = eth_api.evm_config().evm_with_env(db, evm_env);
161
162                let mut results = Vec::with_capacity(transactions.len());
163                let mut transactions = transactions.into_iter().peekable();
164
165                while let Some(tx) = transactions.next() {
166                    let signer = tx.signer();
167                    let tx = {
168                        let mut tx = <Eth::Pool as TransactionPool>::Transaction::from_pooled(tx);
169
170                        if let EthBlobTransactionSidecar::Present(sidecar) = tx.take_blob() {
171                            tx.validate_blob(&sidecar, EnvKzgSettings::Default.get()).map_err(
172                                |e| {
173                                    Eth::Error::from_eth_err(EthApiError::InvalidParams(
174                                        e.to_string(),
175                                    ))
176                                },
177                            )?;
178                        }
179
180                        tx.into_consensus()
181                    };
182
183                    hasher.update(*tx.tx_hash());
184                    let ResultAndState { result, state } = evm
185                        .transact(eth_api.evm_config().tx_env(&tx))
186                        .map_err(Eth::Error::from_evm_err)?;
187
188                    let gas_price = tx
189                        .effective_tip_per_gas(basefee)
190                        .expect("fee is always valid; execution succeeded");
191                    let gas_used = result.gas_used();
192                    total_gas_used += gas_used;
193
194                    let gas_fees = U256::from(gas_used) * U256::from(gas_price);
195                    total_gas_fees += gas_fees;
196
197                    // coinbase is always present in the result state
198                    coinbase_balance_after_tx =
199                        state.get(&coinbase).map(|acc| acc.info.balance).unwrap_or_default();
200                    let coinbase_diff =
201                        coinbase_balance_after_tx.saturating_sub(coinbase_balance_before_tx);
202                    let eth_sent_to_coinbase = coinbase_diff.saturating_sub(gas_fees);
203
204                    // update the coinbase balance
205                    coinbase_balance_before_tx = coinbase_balance_after_tx;
206
207                    // set the return data for the response
208                    let (value, revert) = if result.is_success() {
209                        let value = result.into_output().unwrap_or_default();
210                        (Some(value), None)
211                    } else {
212                        let revert = result.into_output().unwrap_or_default();
213                        (None, Some(revert))
214                    };
215
216                    let tx_res = EthCallBundleTransactionResult {
217                        coinbase_diff,
218                        eth_sent_to_coinbase,
219                        from_address: signer,
220                        gas_fees,
221                        gas_price: U256::from(gas_price),
222                        gas_used,
223                        to_address: tx.to(),
224                        tx_hash: *tx.tx_hash(),
225                        value,
226                        revert,
227                    };
228                    results.push(tx_res);
229
230                    // need to apply the state changes of this call before executing the
231                    // next call
232                    if transactions.peek().is_some() {
233                        // need to apply the state changes of this call before executing
234                        // the next call
235                        evm.db_mut().commit(state)
236                    }
237                }
238
239                // populate the response
240
241                let coinbase_diff = coinbase_balance_after_tx.saturating_sub(initial_coinbase);
242                let eth_sent_to_coinbase = coinbase_diff.saturating_sub(total_gas_fees);
243                let bundle_gas_price =
244                    coinbase_diff.checked_div(U256::from(total_gas_used)).unwrap_or_default();
245                let res = EthCallBundleResponse {
246                    bundle_gas_price,
247                    bundle_hash: hasher.finalize(),
248                    coinbase_diff,
249                    eth_sent_to_coinbase,
250                    gas_fees: total_gas_fees,
251                    results,
252                    state_block_number: state_block_number.to(),
253                    total_gas_used,
254                };
255
256                Ok(res)
257            })
258            .await
259    }
260}
261
262#[async_trait::async_trait]
263impl<Eth> EthCallBundleApiServer for EthBundle<Eth>
264where
265    Eth: EthTransactions + LoadPendingBlock + Call + 'static,
266{
267    async fn call_bundle(&self, request: EthCallBundle) -> RpcResult<EthCallBundleResponse> {
268        Self::call_bundle(self, request).await.map_err(Into::into)
269    }
270}
271
272/// Container type for `EthBundle` internals
273#[derive(Debug)]
274struct EthBundleInner<Eth> {
275    /// Access to commonly used code of the `eth` namespace
276    eth_api: Eth,
277    // restrict the number of concurrent tracing calls.
278    #[expect(dead_code)]
279    blocking_task_guard: BlockingTaskGuard,
280}
281
282impl<Eth> std::fmt::Debug for EthBundle<Eth> {
283    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
284        f.debug_struct("EthBundle").finish_non_exhaustive()
285    }
286}
287
288impl<Eth> Clone for EthBundle<Eth> {
289    fn clone(&self) -> Self {
290        Self { inner: Arc::clone(&self.inner) }
291    }
292}
293
294/// [`EthBundle`] specific errors.
295#[derive(Debug, thiserror::Error)]
296pub enum EthBundleError {
297    /// Thrown if the bundle does not contain any transactions.
298    #[error("bundle missing txs")]
299    EmptyBundleTransactions,
300    /// Thrown if the bundle does not contain a block number, or block number is 0.
301    #[error("bundle missing blockNumber")]
302    BundleMissingBlockNumber,
303    /// Thrown when the blob gas usage of the blob transactions in a bundle exceed the maximum.
304    #[error("blob gas usage exceeds the limit of {0} gas per block.")]
305    Eip4844BlobGasExceeded(u64),
306}