1use 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
30const MAX_NESTED_BUNDLE_DEPTH: usize = 5;
32
33const MAX_BUNDLE_BODY_SIZE: usize = 50;
35
36const DEFAULT_SIM_TIMEOUT: Duration = Duration::from_secs(5);
38
39const MAX_SIM_TIMEOUT: Duration = Duration::from_secs(30);
41
42const SBUNDLE_PAYOUT_MAX_COST: u64 = 30_000;
44
45#[derive(Clone, Debug)]
47pub struct FlattenedBundleItem<T> {
48 pub tx: Recovered<T>,
50 pub can_revert: bool,
52 pub inclusion: Inclusion,
54 pub validity: Option<Validity>,
56 pub privacy: Option<Privacy>,
58 pub refund_percent: Option<u64>,
60 pub refund_configs: Option<Vec<RefundConfig>>,
62}
63
64pub struct EthSimBundle<Eth> {
66 inner: Arc<EthSimBundleInner<Eth>>,
68}
69
70impl<Eth> EthSimBundle<Eth> {
71 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 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 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 let mut stack = Vec::new();
98
99 stack.push((request, 0, 1));
101
102 while let Some((current_bundle, mut idx, depth)) = stack.pop() {
103 if depth > MAX_NESTED_BUNDLE_DEPTH {
105 return Err(EthApiError::InvalidParams(EthSimBundleError::MaxDepth.to_string()));
106 }
107
108 let inclusion = ¤t_bundle.inclusion;
110 let validity = ¤t_bundle.validity;
111 let privacy = ¤t_bundle.privacy;
112
113 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 if current_bundle.bundle_body.len() > MAX_BUNDLE_BODY_SIZE {
125 return Err(EthApiError::InvalidParams(
126 EthSimBundleError::BundleTooLarge.to_string(),
127 ));
128 }
129
130 if let Some(validity) = ¤t_bundle.validity {
132 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 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 = ¤t_bundle.bundle_body;
165
166 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 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 items.push(flattened_item);
197
198 idx += 1;
199 }
200 BundleItem::Bundle { bundle } => {
201 stack.push((current_bundle, idx + 1, depth));
203
204 stack.push((bundle, 0, depth + 1));
206 break;
207 }
208 BundleItem::Hash { hash: _ } => {
209 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 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 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_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 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 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 if item.refund_percent.is_none() {
305 refundable_value += coinbase_diff;
306 }
307
308 coinbase_balance_before_tx = coinbase_balance_after_tx;
310
311 if logs {
315 let tx_logs = result
316 .into_logs()
317 .into_iter()
318 .map(|inner| {
319 let full_log = alloy_rpc_types_eth::Log {
320 inner,
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 evm.db_mut().commit(state);
340 }
341
342 let original_refundable_value = refundable_value;
345 for item in &flattened_bundle {
346 if let Some(refund_percent) = item.refund_percent {
347 let refund_configs = item.refund_configs.clone().unwrap_or_else(|| {
349 vec![RefundConfig { address: item.tx.signer(), percent: 100 }]
350 });
351
352 let payout_tx_fee = U256::from(basefee) *
354 U256::from(SBUNDLE_PAYOUT_MAX_COST) *
355 U256::from(refund_configs.len() as u64);
356
357 total_gas_used += SBUNDLE_PAYOUT_MAX_COST * refund_configs.len() as u64;
359
360 let payout_value = original_refundable_value * U256::from(refund_percent) /
364 U256::from(100);
365
366 if payout_tx_fee > payout_value {
367 return Err(EthApiError::InvalidParams(
368 EthSimBundleError::NegativeProfit.to_string(),
369 )
370 .into());
371 }
372
373 total_profit = total_profit.checked_sub(payout_value).ok_or(
375 EthApiError::InvalidParams(
376 EthSimBundleError::NegativeProfit.to_string(),
377 ),
378 )?;
379
380 refundable_value = refundable_value.checked_sub(payout_value).ok_or(
382 EthApiError::InvalidParams(
383 EthSimBundleError::NegativeProfit.to_string(),
384 ),
385 )?;
386 }
387 }
388
389 let mev_gas_price = if total_gas_used != 0 {
391 total_profit / U256::from(total_gas_used)
392 } else {
393 U256::ZERO
394 };
395
396 Ok(SimBundleResponse {
397 success: true,
398 state_block: current_block_number,
399 error: None,
400 logs: Some(body_logs),
401 gas_used: total_gas_used,
402 mev_gas_price,
403 profit: total_profit,
404 refundable_value,
405 exec_error: None,
406 revert: None,
407 })
408 })
409 .await?;
410
411 Ok(sim_response)
412 }
413}
414
415#[async_trait::async_trait]
416impl<Eth> MevSimApiServer for EthSimBundle<Eth>
417where
418 Eth: EthTransactions + LoadBlock + Call + 'static,
419{
420 async fn sim_bundle(
421 &self,
422 request: MevSendBundle,
423 overrides: SimBundleOverrides,
424 ) -> RpcResult<SimBundleResponse> {
425 trace!("mev_simBundle called, request: {:?}, overrides: {:?}", request, overrides);
426
427 let override_timeout = overrides.timeout;
428
429 let timeout = override_timeout
430 .map(Duration::from_secs)
431 .map(|d| d.min(MAX_SIM_TIMEOUT))
432 .unwrap_or(DEFAULT_SIM_TIMEOUT);
433
434 let bundle_res =
435 tokio::time::timeout(timeout, Self::sim_bundle_inner(self, request, overrides, true))
436 .await
437 .map_err(|_| {
438 EthApiError::InvalidParams(EthSimBundleError::BundleTimeout.to_string())
439 })?;
440
441 bundle_res.map_err(Into::into)
442 }
443}
444
445#[derive(Debug)]
447struct EthSimBundleInner<Eth> {
448 eth_api: Eth,
450 #[expect(dead_code)]
452 blocking_task_guard: BlockingTaskGuard,
453}
454
455impl<Eth> std::fmt::Debug for EthSimBundle<Eth> {
456 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
457 f.debug_struct("EthSimBundle").finish_non_exhaustive()
458 }
459}
460
461impl<Eth> Clone for EthSimBundle<Eth> {
462 fn clone(&self) -> Self {
463 Self { inner: Arc::clone(&self.inner) }
464 }
465}
466
467#[derive(Debug, thiserror::Error)]
469pub enum EthSimBundleError {
470 #[error("max depth reached")]
472 MaxDepth,
473 #[error("unmatched bundle")]
475 UnmatchedBundle,
476 #[error("bundle too large")]
478 BundleTooLarge,
479 #[error("invalid validity")]
481 InvalidValidity,
482 #[error("invalid inclusion")]
484 InvalidInclusion,
485 #[error("invalid bundle")]
487 InvalidBundle,
488 #[error("bundle simulation timed out")]
490 BundleTimeout,
491 #[error("bundle transaction failed")]
493 BundleTransactionFailed,
494 #[error("bundle simulation returned negative profit")]
496 NegativeProfit,
497}