Skip to main content

reth_rpc_eth_types/
simulate.rs

1//! Utilities for serving `eth_simulateV1`
2
3use crate::{
4    error::{api::FromEthApiError, FromEvmError, ToRpcError},
5    EthApiError,
6};
7use alloy_chains::Chain;
8use alloy_consensus::{transaction::TxHashRef, BlockHeader, Transaction as _};
9use alloy_eips::eip2718::WithEncoded;
10use alloy_evm::{block::TxResult, precompiles::PrecompilesMap};
11use alloy_network::{NetworkTransactionBuilder, TransactionBuilder};
12use alloy_rpc_types_eth::{
13    simulate::{SimBlock, SimCallResult, SimulateError, SimulatedBlock},
14    state::StateOverride,
15    BlockId, BlockOverrides, BlockTransactionsKind,
16};
17use jsonrpsee_types::{error::INTERNAL_ERROR_CODE, ErrorObject};
18use reth_evm::{
19    execute::{BlockBuilder, BlockBuilderOutcome, BlockExecutor},
20    Evm, HaltReasonFor,
21};
22use reth_primitives_traits::{
23    BlockBody as _, BlockTy, NodePrimitives, Recovered, RecoveredBlock, SealedHeader,
24};
25use reth_rpc_convert::{RpcBlock, RpcConvert, RpcTxReq};
26use reth_rpc_server_types::result::{block_id_to_str, rpc_err};
27use reth_storage_api::{noop::NoopProvider, StateProvider};
28use revm::{
29    context::Block,
30    context_interface::result::ExecutionResult,
31    primitives::{Address, Bytes, TxKind, U256},
32    Database,
33};
34
35/// Fallback seconds added between simulated block timestamps when neither the user nor the chain
36/// hint provides a value.
37const SIMULATE_FALLBACK_TIMESTAMP_INCREMENT: u64 = 12;
38
39/// Error code for execution reverted in `eth_simulateV1`.
40///
41/// Consistent with `eth_call` revert error code.
42///
43/// <https://github.com/ethereum/execution-apis/pull/748>
44pub const SIMULATE_REVERT_CODE: i32 = 3;
45
46/// Error code for VM execution errors (e.g., out of gas) in `eth_simulateV1`.
47///
48/// <https://github.com/ethereum/execution-apis>
49pub const SIMULATE_VM_ERROR_CODE: i32 = -32015;
50
51/// Errors which may occur during `eth_simulateV1` execution.
52#[derive(Debug, thiserror::Error)]
53pub enum EthSimulateError {
54    /// Total gas limit of transactions for the block exceeds the block gas limit.
55    #[error("Block gas limit exceeded by the block's transactions")]
56    BlockGasLimitExceeded,
57    /// Number of simulated blocks exceeds the configured client limit.
58    #[error("too many blocks")]
59    TooManyBlocks,
60    /// Max gas limit for entire operation exceeded.
61    #[error("Client adjustable limit reached")]
62    GasLimitReached,
63    /// Base block for the simulation was not found.
64    #[error("block not found: {}", block_id_to_str(*block))]
65    BlockNotFound {
66        /// The block id that was requested.
67        block: BlockId,
68    },
69    /// Block number in sequence did not increase.
70    #[error("block numbers must be in order: {got} <= {parent}")]
71    BlockNumberInvalid {
72        /// The block number that was provided.
73        got: u64,
74        /// The parent block number.
75        parent: u64,
76    },
77    /// Block timestamp in sequence did not increase.
78    #[error("block timestamps must be in order: {got} <= {parent}")]
79    BlockTimestampInvalid {
80        /// The block timestamp that was provided.
81        got: u64,
82        /// The parent block timestamp.
83        parent: u64,
84    },
85    /// Transaction nonce is too low.
86    #[error("nonce too low: next nonce {state}, tx nonce {tx}")]
87    NonceTooLow {
88        /// Transaction nonce.
89        tx: u64,
90        /// Current state nonce.
91        state: u64,
92    },
93    /// Transaction nonce is too high.
94    #[error("nonce too high")]
95    NonceTooHigh,
96    /// Transaction nonce cannot be incremented.
97    #[error("nonce has max value")]
98    NonceMaxValue,
99    /// Transaction's baseFeePerGas is too low.
100    #[error("max fee per gas less than block base fee")]
101    BaseFeePerGasTooLow,
102    /// Not enough gas provided to pay for intrinsic gas.
103    #[error("intrinsic gas too low")]
104    IntrinsicGasTooLow,
105    /// Insufficient funds to pay for gas fees and value.
106    #[error("insufficient funds for gas * price + value: have {balance} want {cost}")]
107    InsufficientFunds {
108        /// Transaction cost.
109        cost: U256,
110        /// Sender balance.
111        balance: U256,
112    },
113    /// Sender is not an EOA.
114    #[error("sender is not an EOA")]
115    SenderNotEOA,
116    /// Max init code size exceeded.
117    #[error("max initcode size exceeded")]
118    MaxInitCodeSizeExceeded,
119    /// Attempted to move a non-precompile address.
120    #[error("account {0} is not a precompile")]
121    NotAPrecompile(Address),
122    /// Attempted to move a precompile to its own address.
123    #[error("cannot move precompile {0} to itself")]
124    MovePrecompileToSelf(Address),
125}
126
127impl EthSimulateError {
128    /// Returns the JSON-RPC error code for a `eth_simulateV1` error.
129    pub const fn error_code(&self) -> i32 {
130        match self {
131            Self::NonceTooLow { .. } => -38010,
132            Self::NonceTooHigh => -38011,
133            Self::NonceMaxValue => INTERNAL_ERROR_CODE,
134            Self::BaseFeePerGasTooLow => -38012,
135            Self::IntrinsicGasTooLow => -38013,
136            Self::InsufficientFunds { .. } => -38014,
137            Self::BlockGasLimitExceeded => -38015,
138            Self::BlockNumberInvalid { .. } => -38020,
139            Self::BlockTimestampInvalid { .. } => -38021,
140            Self::SenderNotEOA => -38024,
141            Self::MaxInitCodeSizeExceeded => -38025,
142            Self::TooManyBlocks | Self::GasLimitReached => -38026,
143            Self::MovePrecompileToSelf(_) => -38022,
144            Self::BlockNotFound { .. } | Self::NotAPrecompile(_) => -32000,
145        }
146    }
147}
148
149impl ToRpcError for EthSimulateError {
150    fn to_rpc_error(&self) -> ErrorObject<'static> {
151        rpc_err(self.error_code(), self.to_string(), None)
152    }
153}
154
155/// Sanitizes and gap-fills the chain of [`SimBlock`]s for `eth_simulateV1`.
156///
157/// Walks the provided block-state calls in order and:
158/// - validates that each block number and timestamp strictly increases relative to the parent and
159///   prior simulated block;
160/// - inserts empty filler blocks for every gap in block numbers, so a request like `[block at
161///   number N + k]` over a parent at `N` expands to `k - 1` empty blocks followed by the requested
162///   one (per the execution-apis spec: "If the block number is increased more than `1` compared to
163///   the previous block, new empty blocks are generated in between.");
164/// - assigns default block numbers (`prev_number + 1`) and timestamps (`prev_timestamp + chain
165///   block time`) when missing, so every returned entry has explicit `number` and `time` overrides.
166///   The block time defaults to [`Chain::average_blocktime_hint`] for the chain id, falling back to
167///   `SIMULATE_FALLBACK_TIMESTAMP_INCREMENT` when no hint is registered. Sub-second chain hints are
168///   rounded up because block timestamps are second-granular;
169/// - enforces the global `max_simulate_blocks` cap on the total number of blocks (including
170///   generated fillers).
171pub fn sanitize_chain<TxReq, H>(
172    blocks: Vec<SimBlock<TxReq>>,
173    parent: &SealedHeader<H>,
174    chain_id: u64,
175    max_simulate_blocks: u64,
176) -> Result<Vec<SimBlock<TxReq>>, EthApiError>
177where
178    H: BlockHeader,
179{
180    let timestamp_increment = Chain::from(chain_id)
181        .average_blocktime_hint()
182        .map(|d| d.as_secs().saturating_add(u64::from(d.subsec_nanos() > 0)))
183        .filter(|&s| s > 0)
184        .unwrap_or(SIMULATE_FALLBACK_TIMESTAMP_INCREMENT);
185
186    let mut out = Vec::with_capacity(blocks.len());
187    let base_number = parent.number();
188    let mut prev_number = base_number;
189    let mut prev_timestamp = parent.timestamp();
190
191    for mut block in blocks {
192        let overrides = block.block_overrides.get_or_insert_with(BlockOverrides::default);
193
194        // Default block number to prev + 1 if not specified.
195        let target_number = if let Some(n) = overrides.number {
196            u64::try_from(n).unwrap_or(u64::MAX)
197        } else {
198            let n = prev_number.saturating_add(1);
199            overrides.number = Some(U256::from(n));
200            n
201        };
202
203        if target_number <= prev_number {
204            return Err(EthApiError::other(EthSimulateError::BlockNumberInvalid {
205                got: target_number,
206                parent: prev_number,
207            }));
208        }
209
210        if target_number.saturating_sub(base_number) > max_simulate_blocks {
211            return Err(EthApiError::other(EthSimulateError::TooManyBlocks));
212        }
213
214        // Insert empty filler blocks for any gap between prev_number and target_number.
215        let gap = target_number - prev_number;
216        if gap > 1 {
217            for i in 1..gap {
218                let filler_number = prev_number + i;
219                let filler_time =
220                    prev_timestamp.checked_add(timestamp_increment).ok_or_else(|| {
221                        EthApiError::other(EthSimulateError::BlockTimestampInvalid {
222                            got: prev_timestamp,
223                            parent: prev_timestamp,
224                        })
225                    })?;
226                out.push(SimBlock {
227                    block_overrides: Some(BlockOverrides {
228                        number: Some(U256::from(filler_number)),
229                        time: Some(filler_time),
230                        ..Default::default()
231                    }),
232                    state_overrides: None,
233                    calls: Vec::new(),
234                });
235                prev_timestamp = filler_time;
236            }
237        }
238
239        prev_number = target_number;
240        // Default timestamp to prev + increment if not specified, otherwise validate ordering.
241        let block_time = if let Some(t) = overrides.time {
242            if t <= prev_timestamp {
243                return Err(EthApiError::other(EthSimulateError::BlockTimestampInvalid {
244                    got: t,
245                    parent: prev_timestamp,
246                }));
247            }
248            t
249        } else {
250            let t = prev_timestamp.checked_add(timestamp_increment).ok_or_else(|| {
251                EthApiError::other(EthSimulateError::BlockTimestampInvalid {
252                    got: prev_timestamp,
253                    parent: prev_timestamp,
254                })
255            })?;
256            overrides.time = Some(t);
257            t
258        };
259        prev_timestamp = block_time;
260
261        out.push(block);
262    }
263
264    Ok(out)
265}
266
267/// Applies precompile move overrides from state overrides to the EVM's precompiles map.
268///
269/// This function processes `movePrecompileToAddress` entries from the state overrides and
270/// moves precompiles from their original addresses to new addresses. The original address
271/// is cleared (precompile removed) and the precompile is installed at the destination address.
272pub fn apply_precompile_overrides(
273    state_overrides: &StateOverride,
274    precompiles: &mut PrecompilesMap,
275) -> Result<(), EthSimulateError> {
276    let moves: Vec<_> = state_overrides
277        .iter()
278        .filter_map(|(source, account_override)| {
279            account_override.move_precompile_to.map(|dest| (*source, dest))
280        })
281        .collect();
282
283    for (source, dest) in &moves {
284        if source == dest {
285            if precompiles.get(source).is_none() {
286                return Err(EthSimulateError::NotAPrecompile(*source))
287            }
288            return Err(EthSimulateError::MovePrecompileToSelf(*source))
289        }
290    }
291
292    precompiles.move_precompiles(moves).map_err(
293        |alloy_evm::precompiles::MovePrecompileError::NotAPrecompile(addr)| {
294            EthSimulateError::NotAPrecompile(addr)
295        },
296    )?;
297
298    Ok(())
299}
300
301/// Converts all [`TransactionRequest`]s into [`Recovered`] transactions and applies them to the
302/// given [`BlockExecutor`].
303///
304/// Returns all executed transactions and the result of the execution.
305///
306/// For each call without an explicit `gas` field, the remaining block gas is used as the default.
307/// The RPC gas cap is tracked as a request-wide remaining budget and caps each call before
308/// execution. This matches the spec rule `"gasLimit: blockGasLimit - soFarUsedGasInBlock"` and
309/// geth's per-call `sanitizeCall` behavior.
310///
311/// [`TransactionRequest`]: alloy_rpc_types_eth::TransactionRequest
312#[expect(clippy::type_complexity)]
313pub fn execute_transactions<S, T>(
314    mut builder: S,
315    state_provider: impl StateProvider,
316    calls: Vec<RpcTxReq<T::Network>>,
317    remaining_call_gas_limit: &mut Option<u64>,
318    chain_id: u64,
319    compute_state_root: bool,
320    converter: &T,
321) -> Result<
322    (
323        BlockBuilderOutcome<S::Primitives>,
324        Vec<ExecutionResult<<<S::Executor as BlockExecutor>::Evm as Evm>::HaltReason>>,
325    ),
326    EthApiError,
327>
328where
329    S: BlockBuilder<Executor: BlockExecutor<Evm: Evm<DB: Database<Error: Into<EthApiError>>>>>,
330    T: RpcConvert<Primitives = S::Primitives>,
331{
332    builder.apply_pre_execution_changes()?;
333
334    let mut results = Vec::with_capacity(calls.len());
335    let mut cumulative_tx_gas_used: u64 = 0;
336    let mut block_regular_gas_used: u64 = 0;
337    let mut block_state_gas_used: u64 = 0;
338    let block_gas_limit = builder.evm().block().gas_limit();
339    let is_amsterdam = builder.evm().cfg_env().enable_amsterdam_eip8037;
340    let tx_gas_limit_cap = builder.evm().cfg_env().tx_gas_limit_cap.unwrap_or(u64::MAX);
341    for mut call in calls {
342        let block_gas_remaining = if is_amsterdam {
343            block_gas_limit
344                .saturating_sub(block_regular_gas_used)
345                .min(block_gas_limit.saturating_sub(block_state_gas_used))
346        } else {
347            block_gas_limit.saturating_sub(cumulative_tx_gas_used)
348        };
349        let mut default_gas_limit = block_gas_remaining;
350
351        if let Some(gas_limit) = call.as_ref().gas_limit() {
352            let exceeds_gas_limit = if is_amsterdam {
353                let regular_available_gas = block_gas_limit.saturating_sub(block_regular_gas_used);
354                let state_available_gas = block_gas_limit.saturating_sub(block_state_gas_used);
355                let regular_tx_gas_limit = gas_limit.min(tx_gas_limit_cap);
356
357                regular_tx_gas_limit > regular_available_gas || gas_limit > state_available_gas
358            } else {
359                gas_limit > block_gas_remaining
360            };
361
362            if exceeds_gas_limit {
363                return Err(EthApiError::other(EthSimulateError::BlockGasLimitExceeded))
364            }
365        }
366
367        if let Some(remaining_call_gas_limit) = *remaining_call_gas_limit {
368            if let Some(gas_limit) = call.as_ref().gas_limit() {
369                if gas_limit > remaining_call_gas_limit {
370                    call.as_mut().set_gas_limit(remaining_call_gas_limit);
371                }
372            } else {
373                default_gas_limit = default_gas_limit.min(remaining_call_gas_limit);
374            }
375        }
376
377        // Resolve transaction, populate missing fields and enforce calls
378        // correctness.
379        let tx = resolve_transaction(
380            call,
381            default_gas_limit,
382            builder.evm().block().basefee(),
383            chain_id,
384            builder.evm().cfg_env().disable_nonce_check,
385            builder.evm_mut().db_mut(),
386            converter,
387        )?;
388        // Create transaction with an empty envelope.
389        // The effect for a layer-2 execution client is that it does not charge L1 cost.
390        let tx = WithEncoded::new(Default::default(), tx);
391
392        let mut tx_regular_gas_used = 0;
393        let gas_output = builder.execute_transaction_with_result_closure(tx, |result| {
394            tx_regular_gas_used = result.result().result.gas().block_regular_gas_used();
395            results.push(result.result().result.clone())
396        })?;
397
398        let gas_used = gas_output.tx_gas_used();
399        if let Some(remaining_call_gas_limit) = remaining_call_gas_limit.as_mut() {
400            if gas_used > *remaining_call_gas_limit {
401                return Err(EthApiError::other(EthSimulateError::GasLimitReached))
402            }
403            *remaining_call_gas_limit -= gas_used;
404        }
405
406        cumulative_tx_gas_used = cumulative_tx_gas_used.saturating_add(gas_used);
407        block_regular_gas_used = block_regular_gas_used.saturating_add(tx_regular_gas_used);
408        block_state_gas_used = block_state_gas_used.saturating_add(gas_output.state_gas_used());
409    }
410
411    let result = if compute_state_root {
412        builder.finish(state_provider, None)?
413    } else {
414        builder.finish(NoopProvider::default(), None)?
415    };
416
417    Ok((result, results))
418}
419
420/// Goes over the list of [`TransactionRequest`]s and populates missing fields trying to resolve
421/// them into primitive transactions.
422///
423/// This will set the defaults as defined in <https://github.com/ethereum/execution-apis/blob/e56d3208789259d0b09fa68e9d8594aa4d73c725/docs/ethsimulatev1-notes.md#default-values-for-transactions>
424///
425/// [`TransactionRequest`]: alloy_rpc_types_eth::TransactionRequest
426pub fn resolve_transaction<DB: Database, Tx, T>(
427    mut tx: RpcTxReq<T::Network>,
428    default_gas_limit: u64,
429    block_base_fee_per_gas: u64,
430    chain_id: u64,
431    disable_nonce_check: bool,
432    db: &mut DB,
433    converter: &T,
434) -> Result<Recovered<Tx>, EthApiError>
435where
436    DB::Error: Into<EthApiError>,
437    T: RpcConvert<Primitives: NodePrimitives<SignedTx = Tx>>,
438{
439    // If we're missing any fields we try to fill nonce, gas and
440    // gas price.
441    let tx_type = tx.as_ref().output_tx_type();
442
443    let from = if let Some(from) = tx.as_ref().from() {
444        from
445    } else {
446        tx.as_mut().set_from(Address::ZERO);
447        Address::ZERO
448    };
449
450    if tx.as_ref().nonce().is_none() {
451        tx.as_mut().set_nonce(
452            db.basic(from).map_err(Into::into)?.map(|acc| acc.nonce).unwrap_or_default(),
453        );
454    }
455    // eth_simulateV1 validation-off mode behaves like eth_call; avoid revm's max-nonce guard.
456    if disable_nonce_check && tx.as_ref().nonce() == Some(u64::MAX) {
457        tx.as_mut().set_nonce(0);
458    }
459
460    if tx.as_ref().gas_limit().is_none() {
461        tx.as_mut().set_gas_limit(default_gas_limit);
462    }
463
464    if tx.as_ref().chain_id().is_none() {
465        tx.as_mut().set_chain_id(chain_id);
466    }
467
468    if tx.as_ref().kind().is_none() {
469        tx.as_mut().set_kind(TxKind::Create);
470    }
471
472    // if we can't build the _entire_ transaction yet, fill the fee fields.
473    //
474    // Per the eth_simulateV1 spec, unspecified fee fields default to 0 (not the block base fee),
475    // matching geth's `CallDefaults` behavior. This lets simulation behave like a free-gas
476    // `eth_call` when validation is off, and surfaces "max fee per gas less than block base fee"
477    // errors when validation is on with a real base fee.
478    let _ = block_base_fee_per_gas;
479    if tx.as_ref().output_tx_type_checked().is_none() {
480        if tx_type.is_legacy() || tx_type.is_eip2930() {
481            if tx.as_ref().gas_price().is_none() {
482                tx.as_mut().set_gas_price(0);
483            }
484        } else {
485            if tx.as_ref().max_fee_per_gas().is_none() {
486                tx.as_mut().set_max_fee_per_gas(0);
487            }
488            if tx.as_ref().max_priority_fee_per_gas().is_none() {
489                tx.as_mut().set_max_priority_fee_per_gas(0);
490            }
491        }
492    }
493
494    let tx =
495        converter.build_simulate_v1_transaction(tx).map_err(|e| EthApiError::other(e.into()))?;
496
497    Ok(Recovered::new_unchecked(tx, from))
498}
499
500/// Handles outputs of the calls execution and builds a [`SimulatedBlock`].
501pub fn build_simulated_block<Err, T>(
502    block: RecoveredBlock<BlockTy<T::Primitives>>,
503    results: Vec<ExecutionResult<HaltReasonFor<T::Evm>>>,
504    txs_kind: BlockTransactionsKind,
505    converter: &T,
506) -> Result<SimulatedBlock<RpcBlock<T::Network>>, Err>
507where
508    Err: std::error::Error
509        + FromEthApiError
510        + FromEvmError<T::Evm>
511        + From<T::Error>
512        + Into<jsonrpsee_types::ErrorObject<'static>>,
513    T: RpcConvert,
514{
515    let mut calls: Vec<SimCallResult> = Vec::with_capacity(results.len());
516
517    let mut log_index = 0;
518    for (index, (result, tx)) in results.into_iter().zip(block.body().transactions()).enumerate() {
519        let call = match result {
520            ExecutionResult::Halt { reason, gas, .. } => {
521                let error = Err::from_evm_halt(reason, tx.gas_limit());
522                SimCallResult {
523                    return_data: Bytes::new(),
524                    error: Some(SimulateError {
525                        message: error.to_string(),
526                        code: SIMULATE_VM_ERROR_CODE,
527                        ..SimulateError::invalid_params()
528                    }),
529                    gas_used: gas.tx_gas_used(),
530                    max_used_gas: Some(gas.total_gas_spent().max(gas.floor_gas())),
531                    logs: Vec::new(),
532                    status: false,
533                }
534            }
535            ExecutionResult::Revert { output, gas, .. } => {
536                let error = Err::from_revert(output.clone());
537                SimCallResult {
538                    return_data: Bytes::new(),
539                    error: Some(SimulateError {
540                        message: error.to_string(),
541                        code: SIMULATE_REVERT_CODE,
542                        data: Some(output),
543                    }),
544                    gas_used: gas.tx_gas_used(),
545                    max_used_gas: Some(gas.total_gas_spent().max(gas.floor_gas())),
546                    status: false,
547                    logs: Vec::new(),
548                }
549            }
550            ExecutionResult::Success { output, gas, logs, .. } => SimCallResult {
551                return_data: output.into_data(),
552                error: None,
553                gas_used: gas.tx_gas_used(),
554                max_used_gas: Some(gas.total_gas_spent().max(gas.floor_gas())),
555                logs: logs
556                    .into_iter()
557                    .map(|log| {
558                        log_index += 1;
559                        alloy_rpc_types_eth::Log {
560                            inner: log,
561                            log_index: Some(log_index - 1),
562                            transaction_index: Some(index as u64),
563                            transaction_hash: Some(*tx.tx_hash()),
564                            block_hash: Some(block.hash()),
565                            block_number: Some(block.header().number()),
566                            block_timestamp: Some(block.header().timestamp()),
567                            ..Default::default()
568                        }
569                    })
570                    .collect(),
571                status: true,
572            },
573        };
574
575        calls.push(call);
576    }
577
578    let block = block.into_rpc_block(
579        txs_kind,
580        |tx, tx_info| converter.fill(tx, tx_info),
581        |header, size| converter.convert_header(header, size),
582    )?;
583    Ok(SimulatedBlock { inner: block, calls })
584}
585
586#[cfg(test)]
587mod tests {
588    use super::{
589        apply_precompile_overrides, sanitize_chain, EthSimulateError, INTERNAL_ERROR_CODE,
590    };
591    use crate::{error::ToRpcError, EthApiError};
592    use alloy_chains::Chain;
593    use alloy_consensus::Header;
594    use alloy_evm::precompiles::PrecompilesMap;
595    use alloy_primitives::{address, U256};
596    use alloy_rpc_types_eth::{
597        simulate::SimBlock,
598        state::{AccountOverride, StateOverride},
599        BlockOverrides, TransactionRequest,
600    };
601    use reth_primitives_traits::SealedHeader;
602    use revm::precompile::Precompiles;
603
604    #[test]
605    fn nonce_max_value_error_uses_internal_error_code() {
606        let err = EthSimulateError::NonceMaxValue.to_rpc_error();
607
608        assert_eq!(err.code(), INTERNAL_ERROR_CODE);
609        assert_eq!(err.message(), "nonce has max value");
610    }
611
612    #[test]
613    fn block_not_found_error_uses_simulate_code() {
614        let err = EthSimulateError::BlockNotFound { block: 100000.into() }.to_rpc_error();
615
616        assert_eq!(err.code(), -32000);
617        assert_eq!(err.message(), "block not found: 0x186a0");
618    }
619
620    fn parent_at(number: u64, timestamp: u64) -> SealedHeader<Header> {
621        SealedHeader::seal_slow(Header { number, timestamp, ..Default::default() })
622    }
623
624    fn block_with_number(number: u64) -> SimBlock<TransactionRequest> {
625        SimBlock {
626            block_overrides: Some(BlockOverrides {
627                number: Some(U256::from(number)),
628                ..Default::default()
629            }),
630            ..Default::default()
631        }
632    }
633
634    #[test]
635    fn precompile_self_move_requires_existing_precompile() {
636        let address = address!("c100000000000000000000000000000000000000");
637        let mut state_overrides = StateOverride::default();
638        state_overrides.insert(
639            address,
640            AccountOverride { move_precompile_to: Some(address), ..Default::default() },
641        );
642        let mut precompiles = PrecompilesMap::from_static(Precompiles::prague());
643
644        let err = apply_precompile_overrides(&state_overrides, &mut precompiles).unwrap_err();
645
646        assert!(matches!(err, EthSimulateError::NotAPrecompile(addr) if addr == address));
647    }
648
649    #[test]
650    fn precompile_self_move_errors_for_existing_precompile() {
651        let address = address!("0000000000000000000000000000000000000001");
652        let mut state_overrides = StateOverride::default();
653        state_overrides.insert(
654            address,
655            AccountOverride { move_precompile_to: Some(address), ..Default::default() },
656        );
657        let mut precompiles = PrecompilesMap::from_static(Precompiles::prague());
658
659        let err = apply_precompile_overrides(&state_overrides, &mut precompiles).unwrap_err();
660
661        assert!(matches!(err, EthSimulateError::MovePrecompileToSelf(addr) if addr == address));
662    }
663
664    #[test]
665    fn moved_precompile_is_callable() {
666        let source = address!("0000000000000000000000000000000000000001");
667        let dest = address!("0000000000000000000000000000000000123456");
668        let mut state_overrides = StateOverride::default();
669        state_overrides.insert(
670            source,
671            AccountOverride { move_precompile_to: Some(dest), ..Default::default() },
672        );
673        let mut precompiles = PrecompilesMap::from_static(Precompiles::prague());
674
675        apply_precompile_overrides(&state_overrides, &mut precompiles).unwrap();
676
677        assert!(precompiles.get(&source).is_none());
678        assert!(precompiles.get(&dest).is_some());
679    }
680
681    #[test]
682    fn sanitize_chain_fills_gaps_with_empty_blocks() {
683        // parent at block 5; user requests one block at 8 — sanitize should insert fillers at 6
684        // and 7 before the requested block.
685        let parent = parent_at(5, 100);
686        let blocks = vec![block_with_number(8)];
687
688        let out = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap();
689        assert_eq!(out.len(), 3);
690
691        let numbers: Vec<u64> = out
692            .iter()
693            .map(|b| b.block_overrides.as_ref().unwrap().number.unwrap().try_into().unwrap())
694            .collect();
695        assert_eq!(numbers, vec![6, 7, 8]);
696
697        assert!(out[0].calls.is_empty());
698        assert!(out[1].calls.is_empty());
699
700        // Mainnet hint is 12s, so timestamps should auto-increment from 100 by 12.
701        let times: Vec<u64> =
702            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
703        assert_eq!(times, vec![112, 124, 136]);
704    }
705
706    #[test]
707    fn sanitize_chain_defaults_missing_number_and_time() {
708        let parent = parent_at(10, 1000);
709        let blocks: Vec<SimBlock<TransactionRequest>> =
710            vec![SimBlock::default(), SimBlock::default()];
711
712        let out = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap();
713        assert_eq!(out.len(), 2);
714
715        let overrides = out[0].block_overrides.as_ref().unwrap();
716        assert_eq!(overrides.number.unwrap(), U256::from(11));
717        assert_eq!(overrides.time, Some(1012));
718
719        let overrides = out[1].block_overrides.as_ref().unwrap();
720        assert_eq!(overrides.number.unwrap(), U256::from(12));
721        assert_eq!(overrides.time, Some(1024));
722    }
723
724    #[test]
725    fn sanitize_chain_uses_chain_blocktime_hint() {
726        // Optimism has a 2s blocktime hint; filler/auto timestamps should reflect that.
727        let parent = parent_at(0, 0);
728        let blocks = vec![block_with_number(3)];
729
730        let out = sanitize_chain(blocks, &parent, Chain::optimism_mainnet().id(), 256).unwrap();
731        let times: Vec<u64> =
732            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
733        assert_eq!(times, vec![2, 4, 6]);
734    }
735
736    #[test]
737    fn sanitize_chain_rounds_subsecond_blocktime_hint_up() {
738        // Arbitrum has a 260ms blocktime hint. Simulated timestamps are second-granular, so this
739        // rounds up to a 1s increment instead of falling back to the default.
740        let parent = parent_at(0, 0);
741        let blocks = vec![block_with_number(3)];
742
743        let out = sanitize_chain(blocks, &parent, Chain::arbitrum_mainnet().id(), 256).unwrap();
744        let times: Vec<u64> =
745            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
746        assert_eq!(times, vec![1, 2, 3]);
747    }
748
749    #[test]
750    fn sanitize_chain_falls_back_when_chain_has_no_hint() {
751        // An unknown chain id has no blocktime hint — fall back to the 12s default.
752        let parent = parent_at(0, 0);
753        let blocks = vec![block_with_number(2)];
754
755        let out = sanitize_chain(blocks, &parent, Chain::from_id(123_456_789).id(), 256).unwrap();
756        let times: Vec<u64> =
757            out.iter().map(|b| b.block_overrides.as_ref().unwrap().time.unwrap()).collect();
758        assert_eq!(times, vec![12, 24]);
759    }
760
761    #[test]
762    fn sanitize_chain_rejects_non_increasing_number() {
763        let parent = parent_at(10, 100);
764        let err = sanitize_chain(vec![block_with_number(10)], &parent, Chain::mainnet().id(), 256)
765            .unwrap_err();
766        assert!(matches!(err, EthApiError::Other(_)));
767    }
768
769    #[test]
770    fn sanitize_chain_rejects_timestamp_overflow() {
771        // A block may set any timestamp above its parent's, including `u64::MAX`. The following
772        // block then defaults to `prev + increment`, which must not wrap.
773        let parent = parent_at(0, 0);
774        let blocks: Vec<SimBlock<TransactionRequest>> = vec![
775            SimBlock {
776                block_overrides: Some(BlockOverrides {
777                    time: Some(u64::MAX),
778                    ..Default::default()
779                }),
780                ..Default::default()
781            },
782            SimBlock::default(),
783        ];
784
785        let err = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap_err();
786        assert!(matches!(err, EthApiError::Other(_)));
787    }
788
789    #[test]
790    fn sanitize_chain_rejects_filler_timestamp_overflow() {
791        // Same, but the wrap would happen while generating filler blocks for a number gap.
792        let parent = parent_at(0, 0);
793        let blocks = vec![
794            SimBlock {
795                block_overrides: Some(BlockOverrides {
796                    number: Some(U256::from(1)),
797                    time: Some(u64::MAX),
798                    ..Default::default()
799                }),
800                ..Default::default()
801            },
802            block_with_number(4),
803        ];
804
805        let err = sanitize_chain(blocks, &parent, Chain::mainnet().id(), 256).unwrap_err();
806        assert!(matches!(err, EthApiError::Other(_)));
807    }
808
809    #[test]
810    fn sanitize_chain_enforces_max_blocks() {
811        let parent = parent_at(0, 0);
812        let err = sanitize_chain(vec![block_with_number(257)], &parent, Chain::mainnet().id(), 256)
813            .unwrap_err();
814        assert!(matches!(err, EthApiError::Other(_)));
815    }
816}