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 .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 evm.db_mut().commit(state);
340 }
341
342 for item in &flattened_bundle {
344 if let Some(refund_percent) = item.refund_percent {
345 let refund_configs = item.refund_configs.clone().unwrap_or_else(|| {
347 vec![RefundConfig { address: item.tx.signer(), percent: 100 }]
348 });
349
350 let payout_tx_fee = U256::from(basefee) *
352 U256::from(SBUNDLE_PAYOUT_MAX_COST) *
353 U256::from(refund_configs.len() as u64);
354
355 total_gas_used += SBUNDLE_PAYOUT_MAX_COST * refund_configs.len() as u64;
357
358 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 total_profit = total_profit.checked_sub(payout_value).ok_or(
371 EthApiError::InvalidParams(
372 EthSimBundleError::NegativeProfit.to_string(),
373 ),
374 )?;
375
376 refundable_value = refundable_value.checked_sub(payout_value).ok_or(
378 EthApiError::InvalidParams(
379 EthSimBundleError::NegativeProfit.to_string(),
380 ),
381 )?;
382 }
383 }
384
385 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#[derive(Debug)]
443struct EthSimBundleInner<Eth> {
444 eth_api: Eth,
446 #[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#[derive(Debug, thiserror::Error)]
465pub enum EthSimBundleError {
466 #[error("max depth reached")]
468 MaxDepth,
469 #[error("unmatched bundle")]
471 UnmatchedBundle,
472 #[error("bundle too large")]
474 BundleTooLarge,
475 #[error("invalid validity")]
477 InvalidValidity,
478 #[error("invalid inclusion")]
480 InvalidInclusion,
481 #[error("invalid bundle")]
483 InvalidBundle,
484 #[error("bundle simulation timed out")]
486 BundleTimeout,
487 #[error("bundle transaction failed")]
489 BundleTransactionFailed,
490 #[error("bundle simulation returned negative profit")]
492 NegativeProfit,
493}