reth_rpc/eth/
sim_bundle.rs

1//! `Eth` Sim bundle implementation and helpers.
2
3use alloy_consensus::{transaction::TxHashRef, BlockHeader};
4use alloy_eips::BlockNumberOrTag;
5use alloy_evm::{env::BlockEnvironment, overrides::apply_block_overrides};
6use alloy_primitives::U256;
7use alloy_rpc_types_eth::BlockId;
8use alloy_rpc_types_mev::{
9    BundleItem, Inclusion, MevSendBundle, Privacy, RefundConfig, SimBundleLogs, SimBundleOverrides,
10    SimBundleResponse, Validity,
11};
12use jsonrpsee::core::RpcResult;
13use reth_evm::{ConfigureEvm, Evm};
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::{utils::recover_raw_transaction, EthApiError};
21use reth_storage_api::ProviderTx;
22use reth_tasks::pool::BlockingTaskGuard;
23use reth_transaction_pool::{PoolPooledTx, PoolTransaction, TransactionPool};
24use revm::{
25    context::Block, context_interface::result::ResultAndState, DatabaseCommit, DatabaseRef,
26};
27use std::{sync::Arc, time::Duration};
28use tracing::trace;
29
30/// Maximum bundle depth
31const MAX_NESTED_BUNDLE_DEPTH: usize = 5;
32
33/// Maximum body size
34const MAX_BUNDLE_BODY_SIZE: usize = 50;
35
36/// Default simulation timeout
37const DEFAULT_SIM_TIMEOUT: Duration = Duration::from_secs(5);
38
39/// Maximum simulation timeout
40const MAX_SIM_TIMEOUT: Duration = Duration::from_secs(30);
41
42/// Maximum payout cost
43const SBUNDLE_PAYOUT_MAX_COST: u64 = 30_000;
44
45/// A flattened representation of a bundle item containing transaction and associated metadata.
46#[derive(Clone, Debug)]
47pub struct FlattenedBundleItem<T> {
48    /// The signed transaction
49    pub tx: Recovered<T>,
50    /// Whether the transaction is allowed to revert
51    pub can_revert: bool,
52    /// Item-level inclusion constraints
53    pub inclusion: Inclusion,
54    /// Optional validity constraints for the bundle item
55    pub validity: Option<Validity>,
56    /// Optional privacy settings for the bundle item
57    pub privacy: Option<Privacy>,
58    /// Optional refund percent for the bundle item
59    pub refund_percent: Option<u64>,
60    /// Optional refund configs for the bundle item
61    pub refund_configs: Option<Vec<RefundConfig>>,
62}
63
64/// `Eth` sim bundle implementation.
65pub struct EthSimBundle<Eth> {
66    /// All nested fields bundled together.
67    inner: Arc<EthSimBundleInner<Eth>>,
68}
69
70impl<Eth> EthSimBundle<Eth> {
71    /// Create a new `EthSimBundle` instance.
72    pub fn new(eth_api: Eth, blocking_task_guard: BlockingTaskGuard) -> Self {
73        Self { inner: Arc::new(EthSimBundleInner { eth_api, blocking_task_guard }) }
74    }
75
76    /// Access the underlying `Eth` API.
77    pub fn eth_api(&self) -> &Eth {
78        &self.inner.eth_api
79    }
80}
81
82impl<Eth> EthSimBundle<Eth>
83where
84    Eth: EthTransactions + LoadBlock + Call + 'static,
85{
86    /// Flattens a potentially nested bundle into a list of individual transactions in a
87    /// `FlattenedBundleItem` with their associated metadata. This handles recursive bundle
88    /// processing up to `MAX_NESTED_BUNDLE_DEPTH` and `MAX_BUNDLE_BODY_SIZE`, preserving
89    /// inclusion, validity and privacy settings from parent bundles.
90    fn parse_and_flatten_bundle(
91        &self,
92        request: &MevSendBundle,
93    ) -> Result<Vec<FlattenedBundleItem<ProviderTx<Eth::Provider>>>, EthApiError> {
94        let mut items = Vec::new();
95
96        // Stack for processing bundles
97        let mut stack = Vec::new();
98
99        // Start with initial bundle, index 0, and depth 1
100        stack.push((request, 0, 1));
101
102        while let Some((current_bundle, mut idx, depth)) = stack.pop() {
103            // Check max depth
104            if depth > MAX_NESTED_BUNDLE_DEPTH {
105                return Err(EthApiError::InvalidParams(EthSimBundleError::MaxDepth.to_string()));
106            }
107
108            // Determine inclusion, validity, and privacy
109            let inclusion = &current_bundle.inclusion;
110            let validity = &current_bundle.validity;
111            let privacy = &current_bundle.privacy;
112
113            // Validate inclusion parameters
114            let block_number = inclusion.block_number();
115            let max_block_number = inclusion.max_block_number().unwrap_or(block_number);
116
117            if max_block_number < block_number || block_number == 0 {
118                return Err(EthApiError::InvalidParams(
119                    EthSimBundleError::InvalidInclusion.to_string(),
120                ));
121            }
122
123            // Validate bundle body size
124            if current_bundle.bundle_body.len() > MAX_BUNDLE_BODY_SIZE {
125                return Err(EthApiError::InvalidParams(
126                    EthSimBundleError::BundleTooLarge.to_string(),
127                ));
128            }
129
130            // Validate validity and refund config
131            if let Some(validity) = &current_bundle.validity {
132                // Validate refund entries
133                if let Some(refunds) = &validity.refund {
134                    let mut total_percent = 0;
135                    for refund in refunds {
136                        if refund.body_idx as usize >= current_bundle.bundle_body.len() {
137                            return Err(EthApiError::InvalidParams(
138                                EthSimBundleError::InvalidValidity.to_string(),
139                            ));
140                        }
141                        if 100 - total_percent < refund.percent {
142                            return Err(EthApiError::InvalidParams(
143                                EthSimBundleError::InvalidValidity.to_string(),
144                            ));
145                        }
146                        total_percent += refund.percent;
147                    }
148                }
149
150                // Validate refund configs
151                if let Some(refund_configs) = &validity.refund_config {
152                    let mut total_percent = 0;
153                    for refund_config in refund_configs {
154                        if 100 - total_percent < refund_config.percent {
155                            return Err(EthApiError::InvalidParams(
156                                EthSimBundleError::InvalidValidity.to_string(),
157                            ));
158                        }
159                        total_percent += refund_config.percent;
160                    }
161                }
162            }
163
164            let body = &current_bundle.bundle_body;
165
166            // Process items in the current bundle
167            while idx < body.len() {
168                match &body[idx] {
169                    BundleItem::Tx { tx, can_revert } => {
170                        let tx = recover_raw_transaction::<PoolPooledTx<Eth::Pool>>(tx)?;
171                        let tx = tx.map(
172                            <Eth::Pool as TransactionPool>::Transaction::pooled_into_consensus,
173                        );
174
175                        let refund_percent =
176                            validity.as_ref().and_then(|v| v.refund.as_ref()).and_then(|refunds| {
177                                refunds.iter().find_map(|refund| {
178                                    (refund.body_idx as usize == idx).then_some(refund.percent)
179                                })
180                            });
181                        let refund_configs =
182                            validity.as_ref().and_then(|v| v.refund_config.clone());
183
184                        // Create FlattenedBundleItem with current inclusion, validity, and privacy
185                        let flattened_item = FlattenedBundleItem {
186                            tx,
187                            can_revert: *can_revert,
188                            inclusion: inclusion.clone(),
189                            validity: validity.clone(),
190                            privacy: privacy.clone(),
191                            refund_percent,
192                            refund_configs,
193                        };
194
195                        // Add to items
196                        items.push(flattened_item);
197
198                        idx += 1;
199                    }
200                    BundleItem::Bundle { bundle } => {
201                        // Push the current bundle and next index onto the stack to resume later
202                        stack.push((current_bundle, idx + 1, depth));
203
204                        // process the nested bundle next
205                        stack.push((bundle, 0, depth + 1));
206                        break;
207                    }
208                    BundleItem::Hash { hash: _ } => {
209                        // Hash-only items are not allowed
210                        return Err(EthApiError::InvalidParams(
211                            EthSimBundleError::InvalidBundle.to_string(),
212                        ));
213                    }
214                }
215            }
216        }
217
218        Ok(items)
219    }
220
221    async fn sim_bundle_inner(
222        &self,
223        request: MevSendBundle,
224        overrides: SimBundleOverrides,
225        logs: bool,
226    ) -> Result<SimBundleResponse, Eth::Error> {
227        let SimBundleOverrides { parent_block, block_overrides, .. } = overrides;
228
229        // Parse and validate bundle
230        // Also, flatten the bundle here so that its easier to process
231        let flattened_bundle = self.parse_and_flatten_bundle(&request)?;
232
233        let block_id = parent_block.unwrap_or(BlockId::Number(BlockNumberOrTag::Latest));
234        let (mut evm_env, current_block_id) = self.eth_api().evm_env_at(block_id).await?;
235        let current_block = self.eth_api().recovered_block(current_block_id).await?;
236        let current_block = current_block.ok_or(EthApiError::HeaderNotFound(block_id))?;
237
238        let eth_api = self.inner.eth_api.clone();
239
240        let sim_response = self
241            .inner
242            .eth_api
243            .spawn_with_state_at_block(current_block_id, move |_, mut db| {
244                // Setup environment
245                let current_block_number = current_block.number();
246                let coinbase = evm_env.block_env.beneficiary();
247                let basefee = evm_env.block_env.basefee();
248
249                // apply overrides
250                apply_block_overrides(block_overrides, &mut db, evm_env.block_env.inner_mut());
251
252                let initial_coinbase_balance = DatabaseRef::basic_ref(&db, coinbase)
253                    .map_err(EthApiError::from_eth_err)?
254                    .map(|acc| acc.balance)
255                    .unwrap_or_default();
256
257                let mut coinbase_balance_before_tx = initial_coinbase_balance;
258                let mut total_gas_used = 0;
259                let mut total_profit = U256::ZERO;
260                let mut refundable_value = U256::ZERO;
261                let mut body_logs: Vec<SimBundleLogs> = Vec::new();
262
263                let mut evm = eth_api.evm_config().evm_with_env(db, evm_env);
264                let mut log_index = 0;
265
266                for (tx_index, item) in flattened_bundle.iter().enumerate() {
267                    // Check inclusion constraints
268                    let block_number = item.inclusion.block_number();
269                    let max_block_number =
270                        item.inclusion.max_block_number().unwrap_or(block_number);
271
272                    if current_block_number < block_number ||
273                        current_block_number > max_block_number
274                    {
275                        return Err(EthApiError::InvalidParams(
276                            EthSimBundleError::InvalidInclusion.to_string(),
277                        )
278                        .into());
279                    }
280
281                    let ResultAndState { result, state } = evm
282                        .transact(eth_api.evm_config().tx_env(&item.tx))
283                        .map_err(Eth::Error::from_evm_err)?;
284
285                    if !result.is_success() && !item.can_revert {
286                        return Err(EthApiError::InvalidParams(
287                            EthSimBundleError::BundleTransactionFailed.to_string(),
288                        )
289                        .into());
290                    }
291
292                    let gas_used = result.gas_used();
293                    total_gas_used += gas_used;
294
295                    // coinbase is always present in the result state
296                    let coinbase_balance_after_tx =
297                        state.get(&coinbase).map(|acc| acc.info.balance).unwrap_or_default();
298
299                    let coinbase_diff =
300                        coinbase_balance_after_tx.saturating_sub(coinbase_balance_before_tx);
301                    total_profit += coinbase_diff;
302
303                    // Add to refundable value if this tx does not have a refund percent
304                    if item.refund_percent.is_none() {
305                        refundable_value += coinbase_diff;
306                    }
307
308                    // Update coinbase balance before next tx
309                    coinbase_balance_before_tx = coinbase_balance_after_tx;
310
311                    // Collect logs if requested
312                    // TODO: since we are looping over iteratively, we are not collecting bundle
313                    // logs. We should collect bundle logs when we are processing the bundle items.
314                    if logs {
315                        let tx_logs = result
316                            .logs()
317                            .iter()
318                            .map(|log| {
319                                let full_log = alloy_rpc_types_eth::Log {
320                                    inner: log.clone(),
321                                    block_hash: None,
322                                    block_number: None,
323                                    block_timestamp: None,
324                                    transaction_hash: Some(*item.tx.tx_hash()),
325                                    transaction_index: Some(tx_index as u64),
326                                    log_index: Some(log_index),
327                                    removed: false,
328                                };
329                                log_index += 1;
330                                full_log
331                            })
332                            .collect();
333                        let sim_bundle_logs =
334                            SimBundleLogs { tx_logs: Some(tx_logs), bundle_logs: None };
335                        body_logs.push(sim_bundle_logs);
336                    }
337
338                    // Apply state changes
339                    evm.db_mut().commit(state);
340                }
341
342                // After processing all transactions, process refunds
343                for item in &flattened_bundle {
344                    if let Some(refund_percent) = item.refund_percent {
345                        // Get refund configurations
346                        let refund_configs = item.refund_configs.clone().unwrap_or_else(|| {
347                            vec![RefundConfig { address: item.tx.signer(), percent: 100 }]
348                        });
349
350                        // Calculate payout transaction fee
351                        let payout_tx_fee = U256::from(basefee) *
352                            U256::from(SBUNDLE_PAYOUT_MAX_COST) *
353                            U256::from(refund_configs.len() as u64);
354
355                        // Add gas used for payout transactions
356                        total_gas_used += SBUNDLE_PAYOUT_MAX_COST * refund_configs.len() as u64;
357
358                        // Calculate allocated refundable value (payout value)
359                        let payout_value =
360                            refundable_value * U256::from(refund_percent) / U256::from(100);
361
362                        if payout_tx_fee > payout_value {
363                            return Err(EthApiError::InvalidParams(
364                                EthSimBundleError::NegativeProfit.to_string(),
365                            )
366                            .into());
367                        }
368
369                        // Subtract payout value from total profit
370                        total_profit = total_profit.checked_sub(payout_value).ok_or(
371                            EthApiError::InvalidParams(
372                                EthSimBundleError::NegativeProfit.to_string(),
373                            ),
374                        )?;
375
376                        // Adjust refundable value
377                        refundable_value = refundable_value.checked_sub(payout_value).ok_or(
378                            EthApiError::InvalidParams(
379                                EthSimBundleError::NegativeProfit.to_string(),
380                            ),
381                        )?;
382                    }
383                }
384
385                // Calculate mev gas price
386                let mev_gas_price = if total_gas_used != 0 {
387                    total_profit / U256::from(total_gas_used)
388                } else {
389                    U256::ZERO
390                };
391
392                Ok(SimBundleResponse {
393                    success: true,
394                    state_block: current_block_number,
395                    error: None,
396                    logs: Some(body_logs),
397                    gas_used: total_gas_used,
398                    mev_gas_price,
399                    profit: total_profit,
400                    refundable_value,
401                    exec_error: None,
402                    revert: None,
403                })
404            })
405            .await?;
406
407        Ok(sim_response)
408    }
409}
410
411#[async_trait::async_trait]
412impl<Eth> MevSimApiServer for EthSimBundle<Eth>
413where
414    Eth: EthTransactions + LoadBlock + Call + 'static,
415{
416    async fn sim_bundle(
417        &self,
418        request: MevSendBundle,
419        overrides: SimBundleOverrides,
420    ) -> RpcResult<SimBundleResponse> {
421        trace!("mev_simBundle called, request: {:?}, overrides: {:?}", request, overrides);
422
423        let override_timeout = overrides.timeout;
424
425        let timeout = override_timeout
426            .map(Duration::from_secs)
427            .map(|d| d.min(MAX_SIM_TIMEOUT))
428            .unwrap_or(DEFAULT_SIM_TIMEOUT);
429
430        let bundle_res =
431            tokio::time::timeout(timeout, Self::sim_bundle_inner(self, request, overrides, true))
432                .await
433                .map_err(|_| {
434                    EthApiError::InvalidParams(EthSimBundleError::BundleTimeout.to_string())
435                })?;
436
437        bundle_res.map_err(Into::into)
438    }
439}
440
441/// Container type for `EthSimBundle` internals
442#[derive(Debug)]
443struct EthSimBundleInner<Eth> {
444    /// Access to commonly used code of the `eth` namespace
445    eth_api: Eth,
446    // restrict the number of concurrent tracing calls.
447    #[expect(dead_code)]
448    blocking_task_guard: BlockingTaskGuard,
449}
450
451impl<Eth> std::fmt::Debug for EthSimBundle<Eth> {
452    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
453        f.debug_struct("EthSimBundle").finish_non_exhaustive()
454    }
455}
456
457impl<Eth> Clone for EthSimBundle<Eth> {
458    fn clone(&self) -> Self {
459        Self { inner: Arc::clone(&self.inner) }
460    }
461}
462
463/// [`EthSimBundle`] specific errors.
464#[derive(Debug, thiserror::Error)]
465pub enum EthSimBundleError {
466    /// Thrown when max depth is reached
467    #[error("max depth reached")]
468    MaxDepth,
469    /// Thrown when a bundle is unmatched
470    #[error("unmatched bundle")]
471    UnmatchedBundle,
472    /// Thrown when a bundle is too large
473    #[error("bundle too large")]
474    BundleTooLarge,
475    /// Thrown when validity is invalid
476    #[error("invalid validity")]
477    InvalidValidity,
478    /// Thrown when inclusion is invalid
479    #[error("invalid inclusion")]
480    InvalidInclusion,
481    /// Thrown when a bundle is invalid
482    #[error("invalid bundle")]
483    InvalidBundle,
484    /// Thrown when a bundle simulation times out
485    #[error("bundle simulation timed out")]
486    BundleTimeout,
487    /// Thrown when a transaction is reverted in a bundle
488    #[error("bundle transaction failed")]
489    BundleTransactionFailed,
490    /// Thrown when a bundle simulation returns negative profit
491    #[error("bundle simulation returned negative profit")]
492    NegativeProfit,
493}