1use 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
25pub struct EthBundle<Eth> {
27 inner: Arc<EthBundleInner<Eth>>,
29}
30
31impl<Eth> EthBundle<Eth> {
32 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 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 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 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 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 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 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 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_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 coinbase_balance_before_tx = coinbase_balance_after_tx;
206
207 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 if transactions.peek().is_some() {
233 evm.db_mut().commit(state)
236 }
237 }
238
239 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#[derive(Debug)]
274struct EthBundleInner<Eth> {
275 eth_api: Eth,
277 #[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#[derive(Debug, thiserror::Error)]
296pub enum EthBundleError {
297 #[error("bundle missing txs")]
299 EmptyBundleTransactions,
300 #[error("bundle missing blockNumber")]
302 BundleMissingBlockNumber,
303 #[error("blob gas usage exceeds the limit of {0} gas per block.")]
305 Eip4844BlobGasExceeded(u64),
306}