evm_fork_cache/cache/overlay.rs
1//! Per-simulation state overlays layered over a snapshot or the live cache.
2//!
3//! An [`EvmOverlay`] wraps a read-only base (an
4//! [`EvmSnapshot`] or the cache itself) with
5//! a scratch write layer, so a simulation can mutate balances, storage, and code
6//! and run calls without disturbing the base or other overlays. Overlays are the
7//! `Send` unit of parallel fan-out: snapshot once, clone cheaply, overlay per
8//! candidate. Reads fall through the write layer to the base; writes and reverts
9//! stay local to the overlay.
10
11use std::cell::RefCell;
12use std::collections::HashMap;
13use std::rc::Rc;
14use std::sync::Arc;
15
16use alloy_eips::eip2930::{AccessList, AccessListItem};
17use alloy_primitives::{Address, B256, Bytes, TxKind, U256};
18use foundry_fork_db::{DatabaseError, SharedBackend};
19use revm::{
20 Context, ExecuteCommitEvm, ExecuteEvm, InspectEvm, MainBuilder, MainContext,
21 context::{BlockEnv, CfgEnv, Journal, LocalContext, TxEnv, result::ExecutionResult},
22 database_interface::{Database, DatabaseRef},
23 state::{AccountInfo, Bytecode},
24};
25
26use super::snapshot::EvmSnapshot;
27use super::{CallSimulationResult, IERC20, SimStatus, TxConfig, unix_timestamp_secs_saturating};
28use crate::access_set::StorageAccessList;
29use crate::bundle::{BundleOptions, BundleResult, BundleTx, RevertPolicy, TxOutcome};
30use crate::errors::{
31 OverlayError, OverlayResult as Result, SimError, SimHostError, SimulationError,
32 SimulationResult,
33};
34use crate::inspector::TransferInspector;
35use crate::mapping_probe::HashStorageProbe;
36use alloy_sol_types::SolCall;
37
38type OverlayEvm<'a> = revm::MainnetEvm<
39 Context<BlockEnv, TxEnv, CfgEnv, &'a mut EvmOverlay, Journal<&'a mut EvmOverlay>, ()>,
40>;
41
42type InspectorOverlayEvm<'a, INSP> = revm::MainnetEvm<
43 Context<BlockEnv, TxEnv, CfgEnv, &'a mut EvmOverlay, Journal<&'a mut EvmOverlay>, ()>,
44 INSP,
45>;
46
47/// Per-simulation mutable overlay on an immutable snapshot.
48///
49/// Lookup order: dirty layer → snapshot → ext_db (optional RPC fallback).
50///
51/// This type is `Send` (unlike `EvmCache`) because it uses no `Rc`/`RefCell`.
52/// Each simulation task gets its own `EvmOverlay` with a cheap `Arc::clone`
53/// of the shared `EvmSnapshot`.
54///
55/// # Reuse across simulations (Pillar A.2)
56///
57/// A worker doing many sims against the same snapshot can call [`Self::new`]
58/// once and [`Self::reset`] between sims instead of allocating a fresh overlay
59/// each time. The reusable shared-memory buffer is also recycled across calls —
60/// see [`Self::call_raw`] — without making the overlay `!Send`.
61pub struct EvmOverlay {
62 snapshot: Arc<EvmSnapshot>,
63 /// Per-simulation mutations (accounts fetched from ext_db, committed changes).
64 dirty_accounts: HashMap<Address, AccountInfo>,
65 /// Per-simulation storage mutations.
66 dirty_storage: HashMap<Address, HashMap<U256, U256>>,
67 /// Optional RPC fallback for data not in snapshot.
68 ext_db: Option<SharedBackend>,
69 /// Reusable shared-memory buffer, recycled across the build→transact→revert
70 /// call methods to avoid reallocating a 64 KB `Vec` per call.
71 ///
72 /// Stored as a plain `Vec<u8>` (not an `Rc`) so the overlay stays `Send`. A
73 /// call method `mem::take`s it, wraps it in a method-local `Rc<RefCell<_>>`
74 /// for revm's [`LocalContext`], runs, then reclaims and clears it after the
75 /// EVM is dropped (see [`Self::build_evm_with_local`]).
76 reusable_buffer: Vec<u8>,
77 /// Target pre-allocation (bytes) for [`Self::reusable_buffer`] and each
78 /// per-call buffer, taken from the snapshot's configured
79 /// [`SharedMemoryCapacity`](super::SharedMemoryCapacity) so overlays honor the
80 /// capacity set on the originating [`EvmCache`].
81 buffer_capacity: usize,
82 /// Set when a `BLOCKHASH` read fell through to the ZERO fallback (no
83 /// snapshot-provided hash and no `ext_db`). The freshness validator reads
84 /// this via [`Self::blockhash_zero_fallback`] to fail closed instead of
85 /// confirming a sim whose control flow may rest on a hash its overlays
86 /// cannot resolve. Cleared by [`Self::reset`].
87 blockhash_zero_fallback: bool,
88}
89
90impl EvmOverlay {
91 /// Create a new overlay on the given snapshot.
92 ///
93 /// The reusable shared-memory buffer is pre-allocated to the snapshot's
94 /// configured shared-memory capacity (see
95 /// [`SharedMemoryCapacity`](super::SharedMemoryCapacity)).
96 pub fn new(snapshot: Arc<EvmSnapshot>, ext_db: Option<SharedBackend>) -> Self {
97 let buffer_capacity = snapshot.shared_memory_capacity;
98 Self {
99 snapshot,
100 dirty_accounts: HashMap::new(),
101 dirty_storage: HashMap::new(),
102 ext_db,
103 reusable_buffer: Vec::with_capacity(buffer_capacity),
104 buffer_capacity,
105 blockhash_zero_fallback: false,
106 }
107 }
108
109 /// Clear the per-simulation dirty layer so this overlay can be reused for the
110 /// next simulation against the same snapshot, without reallocating (Pillar
111 /// A.2).
112 ///
113 /// A worker doing K sims calls [`Self::new`] once and `reset()` between sims
114 /// instead of allocating a fresh overlay (plus dirty maps plus an `Arc`
115 /// clone) each time. After `reset()` the overlay reads the pristine snapshot
116 /// again — it is exactly equivalent to a freshly-built overlay on the same
117 /// snapshot. The snapshot `Arc`, the optional `ext_db`, and the reusable
118 /// shared-memory buffer (kept at capacity) are retained.
119 pub fn reset(&mut self) {
120 self.dirty_accounts.clear();
121 self.dirty_storage.clear();
122 self.blockhash_zero_fallback = false;
123 // Keep: snapshot Arc, ext_db, and the reusable buffer. The buffer is
124 // already cleared after each call, so nothing to do for it here.
125 }
126
127 /// `true` if any `BLOCKHASH` read on this overlay fell through to the ZERO
128 /// fallback (no snapshot-provided hash for that number and no `ext_db`)
129 /// since construction or the last [`reset`](Self::reset).
130 ///
131 /// The freshness validator uses this to **fail closed**: a sim that read a
132 /// hash its ext-db-less overlays cannot resolve is reported
133 /// [`Unverified`](crate::freshness::Validation::Unverified) rather than
134 /// silently confirmed against a ZERO stand-in.
135 ///
136 /// Only reads revm actually routes to the database can set this: requests
137 /// outside the EVM's valid lookback window (`[current − 256, current)`)
138 /// return spec-mandated ZERO without a database call — that value is
139 /// correct on-chain too, so such reads are deliberately not flagged.
140 pub fn blockhash_zero_fallback(&self) -> bool {
141 self.blockhash_zero_fallback
142 }
143
144 /// Chain ID of the block context captured by the underlying snapshot.
145 ///
146 /// This is the value installed into `cfg.chain_id` by [`Self::build_evm`].
147 pub fn chain_id(&self) -> u64 {
148 self.snapshot.chain_id
149 }
150
151 /// Block number of the snapshot's block context, or `None` if it was not
152 /// captured.
153 ///
154 /// When present this is the `block.number` simulations run against; when
155 /// `None`, [`Self::build_evm`] leaves revm's default block number in place.
156 pub fn block_number(&self) -> Option<u64> {
157 self.snapshot.block_number
158 }
159
160 /// Base fee of the snapshot's block context, or `None` if it was not
161 /// captured.
162 ///
163 /// Note that base-fee checks are disabled in the simulation EVM, so this is
164 /// informational rather than enforced against the transaction.
165 pub fn basefee(&self) -> Option<u64> {
166 self.snapshot.basefee
167 }
168
169 /// Timestamp of the snapshot's block context, or `None` if it was not
170 /// captured.
171 ///
172 /// When `None`, [`Self::build_evm`] substitutes the current wall-clock time
173 /// for `block.timestamp`.
174 pub fn timestamp(&self) -> Option<u64> {
175 self.snapshot.timestamp
176 }
177
178 /// A fresh [`LocalContext`] with a newly-allocated 64 KB shared-memory buffer.
179 ///
180 /// Used by the public [`Self::build_evm`], which hands out the EVM and cannot
181 /// reclaim its buffer afterwards. The internal call methods instead recycle
182 /// [`Self::reusable_buffer`] via [`Self::build_evm_with_local`].
183 fn fresh_local(&self) -> LocalContext {
184 LocalContext {
185 shared_memory_buffer: Rc::new(RefCell::new(Vec::with_capacity(self.buffer_capacity))),
186 precompile_error_message: None,
187 }
188 }
189
190 /// Build a revm EVM instance backed by this overlay, using a caller-supplied
191 /// [`LocalContext`].
192 ///
193 /// This is the shared body behind [`Self::build_evm`] and the internal call
194 /// methods. The call methods pass a `local` wrapping the recycled
195 /// [`Self::reusable_buffer`] (Pillar A.2) and reclaim it after the EVM is
196 /// dropped; [`Self::build_evm`] passes a fresh one.
197 ///
198 /// Note: the returned EVM is `!Send` (due to `LocalContext`'s `Rc<RefCell>`),
199 /// but this is fine because it's created and used within a single task.
200 fn build_evm_with_local(&mut self, local: LocalContext) -> OverlayEvm<'_> {
201 // Read snapshot values before the mutable borrow of self
202 let chain_id = self.snapshot.chain_id;
203 let spec_id = self.snapshot.spec_id;
204 let timestamp = self
205 .snapshot
206 .timestamp
207 .unwrap_or_else(|| unix_timestamp_secs_saturating(std::time::SystemTime::now()));
208 let block_number = self.snapshot.block_number;
209 let basefee = self.snapshot.basefee;
210 let coinbase = self.snapshot.coinbase;
211 let prevrandao = self.snapshot.prevrandao;
212 let gas_limit = self.snapshot.gas_limit;
213
214 let mut evm = Context::mainnet()
215 .with_db(&mut *self)
216 .with_local(local)
217 .modify_cfg_chained(|cfg| {
218 cfg.disable_nonce_check = true;
219 cfg.disable_eip3607 = true;
220 cfg.disable_base_fee = true;
221 cfg.disable_balance_check = true;
222 cfg.chain_id = chain_id;
223 cfg.limit_contract_code_size = None;
224 cfg.tx_chain_id_check = false;
225 cfg.spec = spec_id;
226 })
227 .build_mainnet();
228
229 evm.block.timestamp = U256::from(timestamp);
230 if let Some(number) = block_number {
231 evm.block.number = U256::from(number);
232 }
233 if let Some(basefee) = basefee {
234 evm.block.basefee = basefee;
235 }
236 if let Some(coinbase) = coinbase {
237 evm.block.beneficiary = coinbase;
238 }
239 if let Some(prevrandao) = prevrandao {
240 evm.block.prevrandao = Some(prevrandao);
241 }
242 if let Some(gas_limit) = gas_limit {
243 evm.block.gas_limit = gas_limit;
244 }
245 evm
246 }
247
248 /// Build a revm EVM instance backed by this overlay.
249 ///
250 /// This allocates a fresh 64 KB shared-memory buffer each call: it hands the
251 /// EVM out to the caller and cannot reclaim the buffer afterwards, so it
252 /// cannot recycle the overlay's reusable buffer. The internal call methods
253 /// ([`Self::call_raw`], etc.) recycle the buffer instead (Pillar A.2).
254 ///
255 /// Note: The returned EVM is `!Send` (due to `LocalContext`'s `Rc<RefCell>`),
256 /// but this is fine because it's created and used within a single task.
257 pub fn build_evm(&mut self) -> OverlayEvm<'_> {
258 let local = self.fresh_local();
259 self.build_evm_with_local(local)
260 }
261
262 /// Execute a non-committing call and return the raw [`ExecutionResult`].
263 ///
264 /// The EVM state is reverted to a checkpoint after execution on *both*
265 /// success and failure, so the call never mutates this overlay's dirty
266 /// layer. Each overlay simulation is therefore isolated: repeated calls all
267 /// observe the same base state.
268 ///
269 /// A revert or halt is *not* an error here — it is reported through the
270 /// returned [`ExecutionResult`] variant. Only failure to build or transact
271 /// the call yields `Err`.
272 ///
273 /// # Errors
274 ///
275 /// Returns an error if the [`TxEnv`] cannot be built from the given inputs,
276 /// or if revm fails to transact the call (for example a database error
277 /// while loading state from the RPC fallback).
278 ///
279 /// # Examples
280 ///
281 /// ```no_run
282 /// # use std::sync::Arc;
283 /// # use alloy_primitives::{Address, Bytes};
284 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
285 /// # fn run(snapshot: Arc<EvmSnapshot>) -> Result<(), Box<dyn std::error::Error>> {
286 /// let mut overlay = EvmOverlay::new(snapshot, None);
287 /// let result = overlay.call_raw(Address::ZERO, Address::ZERO, Bytes::new())?;
288 /// // State is reverted; a second call sees the same base state.
289 /// let _again = overlay.call_raw(Address::ZERO, Address::ZERO, Bytes::new())?;
290 /// # let _ = result;
291 /// # Ok(())
292 /// # }
293 /// ```
294 pub fn call_raw(
295 &mut self,
296 from: Address,
297 to: Address,
298 calldata: Bytes,
299 ) -> Result<ExecutionResult> {
300 let tx = TxEnv::builder()
301 .caller(from)
302 .kind(TxKind::Call(to))
303 .data(calldata)
304 .value(U256::ZERO)
305 .build()
306 .map_err(OverlayError::tx_env)?;
307
308 // Recycle the reusable buffer (Pillar A.2): take it out as a plain Vec
309 // (keeping the overlay Send), lend it to a method-local Rc<RefCell> for
310 // revm's LocalContext, then reclaim and clear it after the EVM is dropped.
311 let buffer = Rc::new(RefCell::new(std::mem::take(&mut self.reusable_buffer)));
312 let local = LocalContext {
313 shared_memory_buffer: Rc::clone(&buffer),
314 precompile_error_message: None,
315 };
316
317 let result = {
318 let mut evm = self.build_evm_with_local(local);
319 use revm::context_interface::JournalTr;
320 let checkpoint = evm.journaled_state.checkpoint();
321 let result = evm.transact_one(tx).map_err(OverlayError::transact);
322 evm.journaled_state.checkpoint_revert(checkpoint);
323 result
324 };
325
326 self.reclaim_buffer(buffer);
327 result
328 }
329
330 /// Reclaim the recycled shared-memory buffer after the EVM (and its
331 /// `LocalContext` clone of the `Rc`) has been dropped, clearing it for the
332 /// next call.
333 ///
334 /// The `Rc` was only ever held by the dropped EVM and this method's local, so
335 /// `try_unwrap` succeeds in the normal path. If a panic somewhere left an
336 /// extra strong reference the buffer is simply re-allocated next call — no
337 /// correctness impact.
338 fn reclaim_buffer(&mut self, buffer: Rc<RefCell<Vec<u8>>>) {
339 if let Ok(cell) = Rc::try_unwrap(buffer) {
340 let mut buf = cell.into_inner();
341 buf.clear();
342 self.reusable_buffer = buf;
343 } else {
344 self.reusable_buffer = Vec::with_capacity(self.buffer_capacity);
345 }
346 }
347
348 /// Build a revm EVM instance with an inspector, backed by this overlay, using
349 /// a caller-supplied [`LocalContext`].
350 ///
351 /// Like [`Self::build_evm_with_local`] but attaches `inspector`. The call
352 /// methods pass a `local` wrapping the recycled [`Self::reusable_buffer`]
353 /// (Pillar A.2) and reclaim it after the EVM is dropped.
354 fn build_evm_with_inspector_local<INSP>(
355 &mut self,
356 inspector: INSP,
357 local: LocalContext,
358 ) -> InspectorOverlayEvm<'_, INSP> {
359 let chain_id = self.snapshot.chain_id;
360 let spec_id = self.snapshot.spec_id;
361 let timestamp = self
362 .snapshot
363 .timestamp
364 .unwrap_or_else(|| unix_timestamp_secs_saturating(std::time::SystemTime::now()));
365 let block_number = self.snapshot.block_number;
366 let basefee = self.snapshot.basefee;
367 let coinbase = self.snapshot.coinbase;
368 let prevrandao = self.snapshot.prevrandao;
369 let gas_limit = self.snapshot.gas_limit;
370
371 let mut evm = Context::mainnet()
372 .with_db(&mut *self)
373 .with_local(local)
374 .modify_cfg_chained(|cfg| {
375 cfg.disable_nonce_check = true;
376 cfg.disable_eip3607 = true;
377 cfg.disable_base_fee = true;
378 cfg.disable_balance_check = true;
379 cfg.chain_id = chain_id;
380 cfg.limit_contract_code_size = None;
381 cfg.tx_chain_id_check = false;
382 cfg.spec = spec_id;
383 })
384 .build_mainnet_with_inspector(inspector);
385
386 evm.block.timestamp = U256::from(timestamp);
387 if let Some(number) = block_number {
388 evm.block.number = U256::from(number);
389 }
390 if let Some(basefee) = basefee {
391 evm.block.basefee = basefee;
392 }
393 if let Some(coinbase) = coinbase {
394 evm.block.beneficiary = coinbase;
395 }
396 if let Some(prevrandao) = prevrandao {
397 evm.block.prevrandao = Some(prevrandao);
398 }
399 if let Some(gas_limit) = gas_limit {
400 evm.block.gas_limit = gas_limit;
401 }
402 evm
403 }
404
405 /// Simulate a call with transfer tracking via the `TransferInspector`.
406 ///
407 /// This is the overlay-compatible equivalent of
408 /// [`super::EvmCache::simulate_with_transfer_tracking`]. It captures ERC20
409 /// Transfer events during execution to compute balance deltas for `owner`
410 /// (restricted to `tokens` when provided) without relying on pre/post
411 /// balance queries.
412 ///
413 /// On a reverting or halting call the EVM state is reverted to a checkpoint
414 /// before returning, so a failed simulation never mutates this overlay. On
415 /// success the call either commits the journaled changes into the overlay's
416 /// dirty layer (`commit == true`) or reverts them (`commit == false`); a
417 /// non-committing run leaves each overlay simulation isolated from the next.
418 ///
419 /// # Errors
420 ///
421 /// Returns an error if the [`TxEnv`] cannot be built, if revm fails to
422 /// transact the call, if the call reverts (mapped from the revert payload),
423 /// or if the call halts. In every error case the EVM state is reverted
424 /// first, regardless of `commit`.
425 ///
426 /// # Examples
427 ///
428 /// ```no_run
429 /// # use std::sync::Arc;
430 /// # use alloy_primitives::{Address, Bytes};
431 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
432 /// # fn run(snapshot: Arc<EvmSnapshot>, token: Address, owner: Address) -> Result<(), Box<dyn std::error::Error>> {
433 /// let mut overlay = EvmOverlay::new(snapshot, None);
434 /// let sim = overlay.simulate_with_transfer_tracking(
435 /// owner,
436 /// token,
437 /// Bytes::new(),
438 /// owner,
439 /// Some([token]),
440 /// false, // non-committing: state is reverted afterwards
441 /// )?;
442 /// let _delta = sim.token_deltas.get(&token);
443 /// # Ok(())
444 /// # }
445 /// ```
446 pub fn simulate_with_transfer_tracking(
447 &mut self,
448 from: Address,
449 to: Address,
450 calldata: Bytes,
451 owner: Address,
452 tokens: Option<impl IntoIterator<Item = Address>>,
453 commit: bool,
454 ) -> SimulationResult<CallSimulationResult> {
455 let tx = TxEnv::builder()
456 .caller(from)
457 .kind(TxKind::Call(to))
458 .data(calldata)
459 .value(U256::ZERO)
460 .build()
461 .map_err(|e| SimError::Other(SimHostError::tx_env(e)))?;
462
463 let inspector = TransferInspector::new();
464
465 // Recycle the reusable buffer (Pillar A.2); reclaimed after the EVM drops.
466 let buffer = Rc::new(RefCell::new(std::mem::take(&mut self.reusable_buffer)));
467 let local = LocalContext {
468 shared_memory_buffer: Rc::clone(&buffer),
469 precompile_error_message: None,
470 };
471
472 let outcome = {
473 let mut evm = self.build_evm_with_inspector_local(inspector, local);
474
475 use revm::context_interface::JournalTr;
476 let checkpoint = evm.journaled_state.checkpoint();
477
478 let result = evm
479 .inspect_one_tx(tx)
480 .map_err(|e| SimError::Other(SimHostError::transact(e)));
481
482 match result {
483 Ok(ExecutionResult::Success {
484 logs,
485 gas_used,
486 output,
487 ..
488 }) => {
489 let token_deltas = if let Some(token_list) = tokens {
490 evm.inspector.balance_deltas_for_tokens(owner, token_list)
491 } else {
492 evm.inspector.balance_deltas(owner)
493 };
494
495 // Extract EIP-2930 access list from journaled state
496 let access_list = extract_access_list(&evm.journaled_state.state);
497
498 if commit {
499 evm.commit_inner();
500 } else {
501 evm.journaled_state.checkpoint_revert(checkpoint);
502 }
503
504 Ok(CallSimulationResult {
505 status: SimStatus::Success,
506 gas_used,
507 token_deltas,
508 logs,
509 access_list,
510 output: output.into_data(),
511 })
512 }
513 Ok(ExecutionResult::Revert { gas_used, output }) => {
514 evm.journaled_state.checkpoint_revert(checkpoint);
515 Err(SimulationError::from_revert(gas_used, output).into())
516 }
517 Ok(ExecutionResult::Halt { reason, gas_used }) => {
518 evm.journaled_state.checkpoint_revert(checkpoint);
519 Err(SimError::Halt {
520 reason: format!("{reason:?}"),
521 gas_used,
522 })
523 }
524 Err(err) => {
525 evm.journaled_state.checkpoint_revert(checkpoint);
526 Err(err)
527 }
528 }
529 };
530
531 self.reclaim_buffer(buffer);
532 outcome
533 }
534
535 /// Run a single call with a caller-supplied [`Inspector`](revm::Inspector),
536 /// returning the raw [`ExecutionResult`] and handing the inspector back for the
537 /// caller to read.
538 ///
539 /// This is the inspector-generic public seam: where
540 /// [`Self::simulate_with_transfer_tracking`] hard-wires the
541 /// [`TransferInspector`], this accepts any
542 /// [`revm::Inspector`] — a [`CallTracer`](crate::tracing::CallTracer), an
543 /// [`InspectorStack`](crate::tracing::InspectorStack) composing several, or a
544 /// caller-defined one. It honors a full [`TxConfig`] (value/gas/nonce/access
545 /// list) exactly like [`Self::call_raw_with_access_list_with`] and recycles the
546 /// reusable shared-memory buffer like the other call methods.
547 ///
548 /// Unlike `simulate_with_transfer_tracking`, a revert or halt is **not** an
549 /// error: the raw [`ExecutionResult`] variant
550 /// ([`Success`](ExecutionResult::Success) /
551 /// [`Revert`](ExecutionResult::Revert) / [`Halt`](ExecutionResult::Halt)) is
552 /// returned as `Ok` so the inspector's captured frames (e.g. a reverted call
553 /// tree) remain observable. Only a tx-env build failure or a transact/database
554 /// error yields `Err`.
555 ///
556 /// On a successful transact the journaled changes are either committed into the
557 /// overlay's dirty layer (`commit == true`) or reverted (`commit == false`),
558 /// matching [`Self::simulate_with_transfer_tracking`]. On a revert/halt the
559 /// checkpoint is always reverted regardless of `commit`, so a failed call never
560 /// mutates this overlay. On a transact error the checkpoint is reverted too.
561 ///
562 /// # Errors
563 ///
564 /// Returns an error if the [`TxEnv`] cannot be built from `from`/`to`/`tx`, or
565 /// if revm fails to transact the call (e.g. a database error while loading
566 /// state).
567 ///
568 /// # Examples
569 ///
570 /// ```no_run
571 /// # use std::sync::Arc;
572 /// # use alloy_primitives::{Address, Bytes};
573 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot, TxConfig};
574 /// # use evm_fork_cache::CallTracer;
575 /// # fn run(snapshot: Arc<EvmSnapshot>, to: Address) -> Result<(), Box<dyn std::error::Error>> {
576 /// let mut overlay = EvmOverlay::new(snapshot, None);
577 /// let (result, tracer) = overlay.call_raw_with_inspector(
578 /// Address::ZERO,
579 /// to,
580 /// Bytes::new(),
581 /// &TxConfig::default(),
582 /// CallTracer::new(),
583 /// false,
584 /// )?;
585 /// let _ = result;
586 /// let _trace = tracer.into_trace();
587 /// # Ok(())
588 /// # }
589 /// ```
590 pub fn call_raw_with_inspector<I>(
591 &mut self,
592 from: Address,
593 to: Address,
594 calldata: Bytes,
595 tx: &TxConfig,
596 inspector: I,
597 commit: bool,
598 ) -> SimulationResult<(ExecutionResult, I)>
599 where
600 I: for<'a> revm::Inspector<
601 Context<
602 BlockEnv,
603 TxEnv,
604 CfgEnv,
605 &'a mut EvmOverlay,
606 Journal<&'a mut EvmOverlay>,
607 (),
608 >,
609 >,
610 {
611 let mut builder = TxEnv::builder()
612 .caller(from)
613 .kind(TxKind::Call(to))
614 .data(calldata)
615 .value(tx.value);
616 if let Some(gas_limit) = tx.gas_limit {
617 builder = builder.gas_limit(gas_limit);
618 }
619 if let Some(gas_price) = tx.gas_price {
620 builder = builder.gas_price(gas_price);
621 }
622 if let Some(nonce) = tx.nonce {
623 builder = builder.nonce(nonce);
624 }
625 if let Some(access_list) = &tx.access_list {
626 builder = builder.access_list(access_list.clone());
627 }
628 let tx_env = builder
629 .build()
630 .map_err(|e| SimError::Other(SimHostError::tx_env(e)))?;
631
632 // Recycle the reusable buffer (Pillar A.2); reclaimed after the EVM drops.
633 let buffer = Rc::new(RefCell::new(std::mem::take(&mut self.reusable_buffer)));
634 let local = LocalContext {
635 shared_memory_buffer: Rc::clone(&buffer),
636 precompile_error_message: None,
637 };
638
639 let outcome = {
640 let mut evm = self.build_evm_with_inspector_local(inspector, local);
641
642 use revm::context_interface::JournalTr;
643 let checkpoint = evm.journaled_state.checkpoint();
644
645 match evm.inspect_one_tx(tx_env) {
646 Ok(result) => {
647 if commit && matches!(result, ExecutionResult::Success { .. }) {
648 evm.commit_inner();
649 } else {
650 evm.journaled_state.checkpoint_revert(checkpoint);
651 }
652 // Hand the inspector back to the caller.
653 Ok((result, evm.inspector))
654 }
655 Err(e) => {
656 evm.journaled_state.checkpoint_revert(checkpoint);
657 Err(SimError::Other(SimHostError::transact(e)))
658 }
659 }
660 };
661
662 self.reclaim_buffer(buffer);
663 outcome
664 }
665
666 /// Apply `txs` in order against this overlay over **cumulative** block state,
667 /// with a revert policy and coinbase/miner-payment accounting (Phase 6
668 /// Track A+B).
669 ///
670 /// Each transaction observes the committed writes of the ones before it:
671 /// the bundle runs on a single overlay/EVM with one outer checkpoint plus a
672 /// per-transaction inner checkpoint, so it does **not** rebuild a fresh
673 /// overlay per transaction. See the [`bundle`](crate::bundle) module for the
674 /// public vocabulary ([`BundleTx`], [`BundleOptions`], [`RevertPolicy`],
675 /// [`TxOutcome`], [`BundleResult`]).
676 ///
677 /// # Revert policy
678 ///
679 /// - [`RevertPolicy::Atomic`]: the first transaction that reverts/halts
680 /// rolls the whole bundle back to the outer checkpoint, sets
681 /// `succeeded = false`, and stops (`per_tx` ends at the failing
682 /// transaction). `coinbase_payment` is `0` and the overlay is unchanged.
683 /// - [`RevertPolicy::AllowReverts`]: a revert at a whitelisted index rolls
684 /// back only that transaction (inner checkpoint) and execution continues;
685 /// a revert at a non-whitelisted index behaves like `Atomic`.
686 ///
687 /// # Coinbase accounting
688 ///
689 /// `coinbase_payment` is the block beneficiary's balance delta across the kept
690 /// transactions. Under EIP-1559 revm credits the beneficiary only the priority
691 /// fee (`(effective_gas_price − basefee) × gas_used`) and burns the base fee
692 /// in-EVM, so the delta is the honest miner payment (plus any direct coinbase
693 /// tips). Saturating.
694 ///
695 /// # Commit semantics
696 ///
697 /// `opts.commit == true` folds the bundle's cumulative state into this
698 /// overlay's dirty layer (observable by subsequent overlay calls);
699 /// `false` reverts the outer checkpoint so the overlay is unchanged. A
700 /// failed atomic bundle never leaves partial state regardless of `commit`.
701 ///
702 /// # Errors
703 ///
704 /// Returns [`SimError`] if a transaction environment cannot be built or revm
705 /// fails to transact (e.g. a database error). A transaction *reverting* is
706 /// not an error — it is reported through the per-transaction
707 /// [`TxOutcome`] and the revert policy.
708 pub fn simulate_bundle(
709 &mut self,
710 txs: &[BundleTx],
711 opts: &BundleOptions,
712 ) -> SimulationResult<BundleResult> {
713 // Build every TxEnv up front so a build failure surfaces as an error
714 // before we touch the EVM/journal (and the borrow of `self` is clean).
715 let tx_envs: Vec<TxEnv> = txs
716 .iter()
717 .map(|bt| {
718 let mut builder = TxEnv::builder()
719 .caller(bt.from)
720 .kind(TxKind::Call(bt.to))
721 .data(bt.calldata.clone())
722 .value(bt.tx.value);
723 if let Some(gas_limit) = bt.tx.gas_limit {
724 builder = builder.gas_limit(gas_limit);
725 }
726 if let Some(gas_price) = bt.tx.gas_price {
727 builder = builder.gas_price(gas_price);
728 }
729 if let Some(nonce) = bt.tx.nonce {
730 builder = builder.nonce(nonce);
731 }
732 if let Some(access_list) = &bt.tx.access_list {
733 builder = builder.access_list(access_list.clone());
734 }
735 builder
736 .build()
737 .map_err(|e| SimError::Other(SimHostError::tx_env(e)))
738 })
739 .collect::<std::result::Result<_, _>>()?;
740
741 // Resolve the beneficiary and read its pre-bundle balance before the
742 // mutable borrow of `self` by the EVM (the post-bundle delta is the miner
743 // payment; revm already burns the base fee per EIP-1559).
744 let beneficiary = self
745 .snapshot
746 .coinbase
747 .unwrap_or_else(|| revm::context::BlockEnv::default().beneficiary);
748 let pre_beneficiary_balance = self
749 .basic(beneficiary)
750 .map_err(|e| SimError::Other(SimHostError::database(e)))?
751 .map(|info| info.balance)
752 .unwrap_or(U256::ZERO);
753
754 // Recycle the reusable buffer (Pillar A.2); reclaimed after the EVM drops.
755 let buffer = Rc::new(RefCell::new(std::mem::take(&mut self.reusable_buffer)));
756 let local = LocalContext {
757 shared_memory_buffer: Rc::clone(&buffer),
758 precompile_error_message: None,
759 };
760
761 let outcome = {
762 use revm::context_interface::JournalTr;
763 let mut evm = self.build_evm_with_local(local);
764
765 // Outer checkpoint: the whole-bundle savepoint.
766 let outer = evm.journaled_state.checkpoint();
767
768 let mut per_tx: Vec<TxOutcome> = Vec::with_capacity(tx_envs.len());
769 let mut total_gas: u64 = 0;
770 let mut aborted = false;
771
772 'bundle: for (idx, tx_env) in tx_envs.into_iter().enumerate() {
773 // Inner checkpoint: this transaction's savepoint.
774 let inner = evm.journaled_state.checkpoint();
775 let result = match evm.transact_one(tx_env) {
776 Ok(result) => result,
777 Err(e) => {
778 // Host/transact error: undo this tx and the whole bundle,
779 // reclaim the buffer, and surface as SimError.
780 evm.journaled_state.checkpoint_revert(inner);
781 evm.journaled_state.checkpoint_revert(outer);
782 drop(evm);
783 self.reclaim_buffer(buffer);
784 return Err(SimError::Other(SimHostError::transact(e)));
785 }
786 };
787
788 let gas_used = result.gas_used();
789 let reverted = !result.is_success();
790 let logs = result.logs().to_vec();
791 total_gas = total_gas.saturating_add(gas_used);
792
793 per_tx.push(TxOutcome {
794 result,
795 gas_used,
796 reverted,
797 logs,
798 });
799
800 if reverted {
801 let allowed = match &opts.revert_policy {
802 RevertPolicy::Atomic => false,
803 RevertPolicy::AllowReverts(idxs) => idxs.contains(&idx),
804 };
805 if allowed {
806 // Roll back only this transaction; later txs still run.
807 evm.journaled_state.checkpoint_revert(inner);
808 continue 'bundle;
809 } else {
810 // Atomic abort: roll the whole bundle back and stop.
811 evm.journaled_state.checkpoint_revert(outer);
812 aborted = true;
813 break 'bundle;
814 }
815 }
816 // Successful tx: its effects stay journaled for the next tx.
817 }
818
819 // Partition total gas into successful/reverted buckets in a single
820 // pass. Saturating (consistent with `total_gas`); the invariant
821 // `successful_tx_gas + reverted_tx_gas == total_gas` holds by
822 // construction since every executed tx lands in exactly one bucket.
823 let (successful_tx_gas, reverted_tx_gas) =
824 per_tx.iter().fold((0u64, 0u64), |(succ, rev), tx| {
825 if tx.reverted {
826 (succ, rev.saturating_add(tx.gas_used))
827 } else {
828 (succ.saturating_add(tx.gas_used), rev)
829 }
830 });
831
832 if aborted {
833 // State is reverted to the pre-bundle outer checkpoint regardless
834 // of `commit`; no payment.
835 BundleResult {
836 per_tx,
837 coinbase_payment: U256::ZERO,
838 gas_used: total_gas,
839 successful_tx_gas,
840 reverted_tx_gas,
841 succeeded: false,
842 }
843 } else {
844 // Read the beneficiary's post-bundle balance from the journaled
845 // state (present iff it was touched) BEFORE commit/revert, since
846 // `commit_inner` finalizes (drains) the journal and an outer
847 // revert would undo the credit.
848 let post_beneficiary_balance = evm
849 .journaled_state
850 .state
851 .get(&beneficiary)
852 .map(|acct| acct.info.balance)
853 .unwrap_or(pre_beneficiary_balance);
854 // revm already excludes the base fee from the beneficiary credit
855 // (EIP-1559), so the delta is the honest miner payment.
856 let coinbase_payment =
857 post_beneficiary_balance.saturating_sub(pre_beneficiary_balance);
858
859 if opts.commit {
860 evm.commit_inner();
861 } else {
862 evm.journaled_state.checkpoint_revert(outer);
863 }
864
865 BundleResult {
866 per_tx,
867 coinbase_payment,
868 gas_used: total_gas,
869 successful_tx_gas,
870 reverted_tx_gas,
871 succeeded: true,
872 }
873 }
874 };
875
876 self.reclaim_buffer(buffer);
877 Ok(outcome)
878 }
879
880 /// Execute a non-committing call and return the result plus the touched
881 /// [`StorageAccessList`].
882 ///
883 /// The access list is collected from every account marked touched in the
884 /// journaled state after execution, recording both the touched accounts and
885 /// the storage slots accessed under each.
886 ///
887 /// The EVM state is reverted to a checkpoint after a successful transact on
888 /// both success and revert/halt outcomes, so the call never mutates this
889 /// overlay's dirty layer and each overlay simulation stays isolated. As with
890 /// [`Self::call_raw`], a revert or halt is reported through the returned
891 /// [`ExecutionResult`] rather than as an error.
892 ///
893 /// # Errors
894 ///
895 /// Returns an error if the [`TxEnv`] cannot be built, or if revm fails to
896 /// transact the call (for example a database error while loading state).
897 ///
898 /// # Examples
899 ///
900 /// ```no_run
901 /// # use std::sync::Arc;
902 /// # use alloy_primitives::{Address, Bytes};
903 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
904 /// # fn run(snapshot: Arc<EvmSnapshot>) -> Result<(), Box<dyn std::error::Error>> {
905 /// let mut overlay = EvmOverlay::new(snapshot, None);
906 /// let (result, access_list) =
907 /// overlay.call_raw_with_access_list(Address::ZERO, Address::ZERO, Bytes::new())?;
908 /// # let _ = (result, access_list);
909 /// # Ok(())
910 /// # }
911 /// ```
912 pub fn call_raw_with_access_list(
913 &mut self,
914 from: Address,
915 to: Address,
916 calldata: Bytes,
917 ) -> Result<(ExecutionResult, StorageAccessList)> {
918 self.call_raw_with_access_list_with(from, to, calldata, &TxConfig::default())
919 }
920
921 /// Like [`call_raw_with_access_list`](Self::call_raw_with_access_list) but
922 /// honors a full [`TxConfig`]: native `value`, `gas_limit`, `gas_price`,
923 /// `nonce`, and a pre-warming EIP-2930 `access_list`.
924 ///
925 /// This is what the freshness optimistic loop uses so a [`SimRequest`]'s tx
926 /// environment — e.g. a payable call carrying `value`, or a gas-bounded call
927 /// — is reproduced faithfully instead of silently running as a zero-value,
928 /// default-gas call. Like the shorthand it is non-committing (the checkpoint
929 /// is reverted) and returns the captured storage access list.
930 ///
931 /// [`SimRequest`]: crate::freshness::SimRequest
932 pub fn call_raw_with_access_list_with(
933 &mut self,
934 from: Address,
935 to: Address,
936 calldata: Bytes,
937 tx: &TxConfig,
938 ) -> Result<(ExecutionResult, StorageAccessList)> {
939 let mut builder = TxEnv::builder()
940 .caller(from)
941 .kind(TxKind::Call(to))
942 .data(calldata)
943 .value(tx.value);
944 if let Some(gas_limit) = tx.gas_limit {
945 builder = builder.gas_limit(gas_limit);
946 }
947 if let Some(gas_price) = tx.gas_price {
948 builder = builder.gas_price(gas_price);
949 }
950 if let Some(nonce) = tx.nonce {
951 builder = builder.nonce(nonce);
952 }
953 if let Some(access_list) = &tx.access_list {
954 builder = builder.access_list(access_list.clone());
955 }
956 let tx_env = builder.build().map_err(OverlayError::tx_env)?;
957
958 // Recycle the reusable buffer (Pillar A.2); reclaimed after the EVM drops.
959 let buffer = Rc::new(RefCell::new(std::mem::take(&mut self.reusable_buffer)));
960 let local = LocalContext {
961 shared_memory_buffer: Rc::clone(&buffer),
962 precompile_error_message: None,
963 };
964
965 let outcome = {
966 let mut evm = self.build_evm_with_local(local);
967 use revm::context_interface::JournalTr;
968 let checkpoint = evm.journaled_state.checkpoint();
969 match evm.transact_one(tx_env) {
970 Ok(result) => {
971 let mut access_list = StorageAccessList::default();
972 for (address, account) in evm.journaled_state.state.iter() {
973 if account.is_touched() {
974 access_list.accounts.insert(*address);
975 for (slot_key, _) in account.storage.iter() {
976 access_list.slots.insert((*address, *slot_key));
977 }
978 }
979 }
980 evm.journaled_state.checkpoint_revert(checkpoint);
981 Ok((result, access_list))
982 }
983 Err(e) => {
984 // Revert the checkpoint even on a host/transact error so the EVM
985 // journal is not left dirty (mirrors `call_raw`).
986 evm.journaled_state.checkpoint_revert(checkpoint);
987 Err(OverlayError::transact(e))
988 }
989 }
990 };
991
992 self.reclaim_buffer(buffer);
993 outcome
994 }
995
996 /// Write a storage value into this overlay's dirty layer.
997 ///
998 /// The dirty layer takes precedence over the snapshot on subsequent reads
999 /// (see the lookup order on [`EvmOverlay`]), so this injects a value into a
1000 /// snapshot-backed overlay without mutating the shared snapshot.
1001 ///
1002 /// # Freshness validation
1003 ///
1004 /// This is the freshness validator's correction step. When a slot the
1005 /// snapshot captured is found to be stale, the validator writes the
1006 /// freshly-fetched value here and then re-runs the simulation (e.g. via
1007 /// [`Self::call_raw`]): the re-run reads the corrected slot out of the dirty
1008 /// layer instead of the stale snapshot value, so the corrected result
1009 /// becomes observable. Because the override lives only in this overlay,
1010 /// other overlays sharing the same `Arc<EvmSnapshot>` are unaffected.
1011 ///
1012 /// # Examples
1013 ///
1014 /// ```no_run
1015 /// # use std::sync::Arc;
1016 /// # use alloy_primitives::{Address, Bytes, U256};
1017 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
1018 /// # fn run(snapshot: Arc<EvmSnapshot>, token: Address, slot: U256) -> Result<(), Box<dyn std::error::Error>> {
1019 /// let mut overlay = EvmOverlay::new(snapshot, None);
1020 /// // Inject the fresh value, then re-run to observe the corrected result.
1021 /// overlay.override_slot(token, slot, U256::from(42u64));
1022 /// let corrected = overlay.call_raw(Address::ZERO, token, Bytes::new())?;
1023 /// # let _ = corrected;
1024 /// # Ok(())
1025 /// # }
1026 /// ```
1027 pub fn override_slot(&mut self, address: Address, slot: U256, value: U256) {
1028 self.dirty_storage
1029 .entry(address)
1030 .or_default()
1031 .insert(slot, value);
1032 }
1033
1034 /// Execute a non-committing typed Solidity call from [`Address::ZERO`],
1035 /// decoding the return — the overlay counterpart to
1036 /// [`EvmCache::call_sol`](super::EvmCache::call_sol).
1037 ///
1038 /// ```no_run
1039 /// # use std::sync::Arc;
1040 /// # use alloy_primitives::Address;
1041 /// # use alloy_sol_types::sol;
1042 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
1043 /// # sol! { interface IErc20 { function balanceOf(address account) returns (uint256); } }
1044 /// # fn run(mut overlay: EvmOverlay, token: Address, alice: Address) -> Result<(), Box<dyn std::error::Error>> {
1045 /// let bal = overlay.call_sol(token, IErc20::balanceOfCall { account: alice })?;
1046 /// # let _ = bal; Ok(()) }
1047 /// ```
1048 pub fn call_sol<C: SolCall>(&mut self, to: Address, call: C) -> Result<C::Return> {
1049 self.call_sol_from(Address::ZERO, to, call)
1050 }
1051
1052 /// Execute a non-committing typed Solidity call from an explicit sender,
1053 /// decoding the return.
1054 pub fn call_sol_from<C: SolCall>(
1055 &mut self,
1056 from: Address,
1057 to: Address,
1058 call: C,
1059 ) -> Result<C::Return> {
1060 let result = self.call_raw(from, to, Bytes::from(call.abi_encode()))?;
1061 match result {
1062 ExecutionResult::Success { output, .. } => {
1063 let output = output.into_data();
1064 C::abi_decode_returns(&output).map_err(|error| OverlayError::SolCallDecode {
1065 signature: C::SIGNATURE,
1066 from,
1067 to,
1068 output_len: output.len(),
1069 details: format!("{error:?}"),
1070 })
1071 }
1072 other => Err(OverlayError::SolCallFailed {
1073 signature: C::SIGNATURE,
1074 from,
1075 to,
1076 result: format!("{other:?}"),
1077 }),
1078 }
1079 }
1080
1081 /// Mock `holder`'s ERC-20 balance of `token` to `amount` — **overlay-local**.
1082 ///
1083 /// Discovers the balance mapping slot and layout (Solidity / Vyper / Solady)
1084 /// from a single `balanceOf(holder)` simulation, writes `amount` to that slot
1085 /// in this overlay's dirty layer via [`override_slot`](Self::override_slot),
1086 /// and verifies. The cache and snapshot are never mutated; the mock is
1087 /// dropped with the overlay.
1088 ///
1089 /// Returns `Ok(true)` if set and verified, `Ok(false)` if no balance slot was
1090 /// discoverable or the write did not drive the return (e.g. a rebasing token,
1091 /// or `holder == Address::ZERO`, which is refused). A failed attempt leaves no
1092 /// stray write.
1093 pub fn mock_balance(
1094 &mut self,
1095 token: Address,
1096 holder: Address,
1097 amount: U256,
1098 ) -> SimulationResult<bool> {
1099 if holder == Address::ZERO {
1100 return Ok(false);
1101 }
1102 let calldata = Bytes::from(IERC20::balanceOfCall { target: holder }.abi_encode());
1103 let holder_word = holder.into_word();
1104 self.mock_slot_driving(token, calldata, amount, move |probe, ret| {
1105 probe
1106 .accesses(&[holder_word])
1107 .into_iter()
1108 .filter(|a| a.keyed_by(holder_word))
1109 .max_by_key(|a| (a.value == ret, a.confidence))
1110 .map(|a| (a.slot, a.value))
1111 })
1112 }
1113
1114 /// Mock `owner`'s ERC-20 allowance to `spender` on `token` — overlay-local.
1115 ///
1116 /// Discovers the (nested) `allowance` mapping entry keyed by both addresses,
1117 /// writes `amount` (pass `U256::MAX` for "unlimited"), and verifies. Refuses
1118 /// `owner == Address::ZERO`. Same isolation and failure semantics as
1119 /// [`mock_balance`](Self::mock_balance).
1120 pub fn mock_allowance(
1121 &mut self,
1122 token: Address,
1123 owner: Address,
1124 spender: Address,
1125 amount: U256,
1126 ) -> SimulationResult<bool> {
1127 if owner == Address::ZERO {
1128 return Ok(false);
1129 }
1130 let calldata = Bytes::from(IERC20::allowanceCall { owner, spender }.abi_encode());
1131 let (owner_word, spender_word) = (owner.into_word(), spender.into_word());
1132 self.mock_slot_driving(token, calldata, amount, move |probe, _ret| {
1133 probe
1134 .accesses(&[owner_word, spender_word])
1135 .into_iter()
1136 .filter(|a| a.keyed_by(owner_word) && a.keyed_by(spender_word))
1137 .max_by_key(|a| (a.depth, a.confidence))
1138 .map(|a| (a.slot, a.value))
1139 })
1140 }
1141
1142 /// Mock the return value of a single-word view call by finding the storage
1143 /// slot that drives it and overriding that slot — overlay-local.
1144 ///
1145 /// Runs `to.calldata`, identifies the `SLOAD` whose loaded value equals the
1146 /// call's returned word (see
1147 /// [`HashStorageProbe::slots_returning`](crate::mapping_probe::HashStorageProbe::slots_returning)),
1148 /// writes `desired` there, and verifies the call now returns `desired`. Works
1149 /// for balances, allowances, `totalSupply`, and any getter that returns a
1150 /// single stored word. Returns `Ok(false)` (leaving no stray write) when the
1151 /// return is computed from more than one slot, so it can't be set by a single
1152 /// override.
1153 pub fn mock_view(
1154 &mut self,
1155 to: Address,
1156 calldata: Bytes,
1157 desired: U256,
1158 ) -> SimulationResult<bool> {
1159 self.mock_slot_driving(to, calldata, desired, |probe, ret| {
1160 probe
1161 .slots_returning(ret)
1162 .into_iter()
1163 .next()
1164 .map(|slot| (slot, ret))
1165 })
1166 }
1167
1168 /// Typed [`mock_view`](Self::mock_view): mock the `desired` return of a
1169 /// [`SolCall`] getter that returns a single word.
1170 ///
1171 /// ```no_run
1172 /// # use std::sync::Arc;
1173 /// # use alloy_primitives::{Address, U256};
1174 /// # use alloy_sol_types::sol;
1175 /// # use evm_fork_cache::cache::{EvmOverlay, EvmSnapshot};
1176 /// # sol! { interface IErc20 { function totalSupply() returns (uint256); } }
1177 /// # fn run(mut overlay: EvmOverlay, token: Address) -> Result<(), Box<dyn std::error::Error>> {
1178 /// overlay.mock_call(token, IErc20::totalSupplyCall {}, U256::from(1_000u64))?;
1179 /// # Ok(()) }
1180 /// ```
1181 pub fn mock_call<C: SolCall>(
1182 &mut self,
1183 to: Address,
1184 call: C,
1185 desired: U256,
1186 ) -> SimulationResult<bool> {
1187 self.mock_view(to, Bytes::from(call.abi_encode()), desired)
1188 }
1189
1190 /// Extract the leading 32-byte word of a successful call's return data.
1191 fn success_word(result: &ExecutionResult) -> Option<U256> {
1192 match result {
1193 ExecutionResult::Success { output, .. } => {
1194 let data = output.data();
1195 (data.len() >= 32).then(|| U256::from_be_slice(&data[..32]))
1196 }
1197 _ => None,
1198 }
1199 }
1200
1201 /// Shared core for the `mock_*` methods: discover the slot driving
1202 /// `to.calldata`'s return via `choose`, override it to `desired`, verify, and
1203 /// restore the slot on a failed verify so a mis-pick leaves no stray write.
1204 fn mock_slot_driving<F>(
1205 &mut self,
1206 to: Address,
1207 calldata: Bytes,
1208 desired: U256,
1209 choose: F,
1210 ) -> SimulationResult<bool>
1211 where
1212 F: FnOnce(&HashStorageProbe, U256) -> Option<(B256, U256)>,
1213 {
1214 let (result, probe) = self.call_raw_with_inspector(
1215 Address::ZERO,
1216 to,
1217 calldata.clone(),
1218 &TxConfig::default(),
1219 HashStorageProbe::new(),
1220 false,
1221 )?;
1222 let Some(ret) = Self::success_word(&result) else {
1223 return Ok(false);
1224 };
1225 let Some((slot, prev)) = choose(&probe, ret) else {
1226 return Ok(false);
1227 };
1228 let slot_u = U256::from_be_bytes(slot.0);
1229 self.override_slot(to, slot_u, desired);
1230
1231 let (verify, _) = self.call_raw_with_inspector(
1232 Address::ZERO,
1233 to,
1234 calldata,
1235 &TxConfig::default(),
1236 HashStorageProbe::new(),
1237 false,
1238 )?;
1239 if Self::success_word(&verify) == Some(desired) {
1240 Ok(true)
1241 } else {
1242 self.override_slot(to, slot_u, prev); // undo the mis-pick
1243 Ok(false)
1244 }
1245 }
1246}
1247
1248impl revm::database_interface::DatabaseCommit for EvmOverlay {
1249 fn commit(&mut self, changes: alloy_primitives::map::HashMap<Address, revm::state::Account>) {
1250 for (address, account) in changes {
1251 self.dirty_accounts.insert(address, account.info);
1252 let storage = self.dirty_storage.entry(address).or_default();
1253 for (slot, value) in account.storage {
1254 storage.insert(slot, value.present_value);
1255 }
1256 }
1257 }
1258}
1259
1260impl Database for EvmOverlay {
1261 type Error = DatabaseError;
1262
1263 fn basic(&mut self, address: Address) -> Result<Option<AccountInfo>, Self::Error> {
1264 // 1. Check dirty layer
1265 if let Some(info) = self.dirty_accounts.get(&address) {
1266 return Ok(Some(info.clone()));
1267 }
1268 // 2. Check snapshot (O(1) HashMap lookup, no locks). `account_info` folds
1269 // the two snapshot tiers (overlay ▸ base) and already short-circuits a
1270 // NotExisting account to None — it must NOT fall through to the ext_db,
1271 // mirroring revm `DbAccount::info()` and the live `EvmCache` read.
1272 if self.snapshot.accounts_not_existing.contains(&address) {
1273 return Ok(None);
1274 }
1275 if let Some(info) = self.snapshot.account_info(address) {
1276 return Ok(Some(info.clone()));
1277 }
1278 // 3. RPC fallback
1279 if let Some(ref ext_db) = self.ext_db {
1280 let info = ext_db.basic_ref(address)?;
1281 if let Some(ref info) = info {
1282 self.dirty_accounts.insert(address, info.clone());
1283 }
1284 return Ok(info);
1285 }
1286 Ok(None)
1287 }
1288
1289 fn code_by_hash(&mut self, code_hash: B256) -> Result<Bytecode, Self::Error> {
1290 // Check dirty accounts first
1291 for info in self.dirty_accounts.values() {
1292 if info.code_hash == code_hash
1293 && let Some(code) = &info.code
1294 {
1295 return Ok(code.clone());
1296 }
1297 }
1298 // Check the snapshot's code index (overlay ▸ base).
1299 if let Some(code) = self.snapshot.code(code_hash) {
1300 return Ok(code.clone());
1301 }
1302 // RPC fallback
1303 if let Some(ref ext_db) = self.ext_db {
1304 return ext_db.code_by_hash_ref(code_hash);
1305 }
1306 Ok(Bytecode::default())
1307 }
1308
1309 fn storage(&mut self, address: Address, index: U256) -> Result<U256, Self::Error> {
1310 // 1. Check dirty layer
1311 if let Some(account_storage) = self.dirty_storage.get(&address)
1312 && let Some(value) = account_storage.get(&index)
1313 {
1314 return Ok(*value);
1315 }
1316 // 2. Check snapshot (O(1)). `storage_value` folds the two tiers (overlay ▸
1317 // cleared-as-ZERO ▸ base); a cleared account's absent slot reads ZERO
1318 // and must NOT fall through to the ext_db, mirroring the live EVM SLOAD
1319 // for a StorageCleared/NotExisting account.
1320 if let Some(value) = self.snapshot.storage_value(address, index) {
1321 return Ok(value);
1322 }
1323 // 3. RPC fallback
1324 if let Some(ref ext_db) = self.ext_db {
1325 let value = ext_db.storage_ref(address, index)?;
1326 self.dirty_storage
1327 .entry(address)
1328 .or_default()
1329 .insert(index, value);
1330 return Ok(value);
1331 }
1332 Ok(U256::ZERO)
1333 }
1334
1335 fn block_hash(&mut self, number: u64) -> Result<B256, Self::Error> {
1336 if let Some(hash) = self.snapshot.block_hashes.get(&number) {
1337 return Ok(*hash);
1338 }
1339 if let Some(ref ext_db) = self.ext_db {
1340 return ext_db.block_hash_ref(number);
1341 }
1342 // Snapshots never populate `block_hashes` (the live cache does not track
1343 // block hashes), so without an `ext_db` the `BLOCKHASH` opcode resolves to
1344 // ZERO. Overlays built internally (e.g. the freshness validator) pass
1345 // `ext_db = None`; the fallback is recorded so the validator can fail
1346 // closed (`Unverified`) instead of confirming a sim whose control flow
1347 // may depend on the real hash. See `blockhash_zero_fallback()`.
1348 self.blockhash_zero_fallback = true;
1349 Ok(B256::ZERO)
1350 }
1351}
1352
1353fn extract_access_list(state: &revm::state::EvmState) -> AccessList {
1354 let items: Vec<AccessListItem> = state
1355 .iter()
1356 .filter(|(_, account)| account.is_touched())
1357 .map(|(address, account)| AccessListItem {
1358 address: *address,
1359 storage_keys: account
1360 .storage
1361 .keys()
1362 .map(|slot| B256::from(*slot))
1363 .collect(),
1364 })
1365 .collect();
1366 AccessList(items)
1367}
1368
1369#[cfg(test)]
1370mod tests {
1371 use super::*;
1372 use crate::cache::snapshot::BaseState;
1373 use revm::primitives::hardfork::SpecId;
1374 use std::collections::HashSet;
1375
1376 /// Build a two-tier `EvmSnapshot` whose cold base holds the given accounts,
1377 /// storage, and code, with an empty hot overlay — the shape
1378 /// `snapshot_deep_clone` produces. The `Arc`-per-account storage of the
1379 /// base is built from the plain per-account maps.
1380 fn snap(
1381 accounts: HashMap<Address, AccountInfo>,
1382 storage: HashMap<Address, HashMap<U256, U256>>,
1383 code_by_hash: HashMap<B256, Bytecode>,
1384 block_hashes: HashMap<u64, B256>,
1385 ) -> Arc<EvmSnapshot> {
1386 let base = BaseState {
1387 accounts,
1388 storage: storage
1389 .into_iter()
1390 .map(|(addr, slots)| (addr, Arc::new(slots)))
1391 .collect(),
1392 code_by_hash,
1393 };
1394 Arc::new(EvmSnapshot {
1395 base: Arc::new(base),
1396 overlay_accounts: HashMap::new(),
1397 overlay_storage: HashMap::new(),
1398 overlay_code_by_hash: HashMap::new(),
1399 storage_cleared: HashSet::new(),
1400 accounts_not_existing: HashSet::new(),
1401 block_hashes,
1402 block_number: None,
1403 basefee: None,
1404 coinbase: None,
1405 prevrandao: None,
1406 gas_limit: None,
1407 chain_id: 42161,
1408 timestamp: None,
1409 spec_id: SpecId::CANCUN,
1410 shared_memory_capacity: 64_000,
1411 })
1412 }
1413
1414 #[test]
1415 fn test_overlay_is_send() {
1416 fn assert_send<T: Send>() {}
1417 assert_send::<EvmOverlay>();
1418 }
1419
1420 #[test]
1421 fn blockhash_zero_fallback_flags_only_unresolved_reads() {
1422 let known = B256::repeat_byte(0xAB);
1423 let snapshot = snap(
1424 HashMap::new(),
1425 HashMap::new(),
1426 HashMap::new(),
1427 HashMap::from([(5u64, known)]),
1428 );
1429 let mut overlay = EvmOverlay::new(snapshot, None);
1430
1431 // A snapshot-provided hash resolves for real: no flag.
1432 assert_eq!(overlay.block_hash(5).unwrap(), known);
1433 assert!(!overlay.blockhash_zero_fallback());
1434
1435 // An untracked number falls back to ZERO and is flagged so the
1436 // freshness validator can fail closed.
1437 assert_eq!(overlay.block_hash(6).unwrap(), B256::ZERO);
1438 assert!(overlay.blockhash_zero_fallback());
1439
1440 // The flag is per-simulation state: reset clears it.
1441 overlay.reset();
1442 assert!(!overlay.blockhash_zero_fallback());
1443 }
1444
1445 #[test]
1446 fn test_overlay_basic_from_snapshot() {
1447 let mut accounts = HashMap::new();
1448 let info = AccountInfo {
1449 balance: U256::from(1000),
1450 nonce: 1,
1451 code_hash: B256::ZERO,
1452 code: None,
1453 account_id: None,
1454 };
1455 let addr = Address::repeat_byte(0x01);
1456 accounts.insert(addr, info);
1457
1458 let snapshot = snap(accounts, HashMap::new(), HashMap::new(), HashMap::new());
1459
1460 let mut overlay = EvmOverlay::new(snapshot, None);
1461 let result = overlay.basic(addr).unwrap();
1462 assert!(result.is_some());
1463 assert_eq!(result.unwrap().balance, U256::from(1000));
1464 }
1465
1466 #[test]
1467 fn test_overlay_storage_from_snapshot() {
1468 let addr = Address::repeat_byte(0x01);
1469 let slot = U256::from(42);
1470 let value = U256::from(999);
1471
1472 let mut storage = HashMap::new();
1473 let mut account_storage = HashMap::new();
1474 account_storage.insert(slot, value);
1475 storage.insert(addr, account_storage);
1476
1477 let snapshot = snap(HashMap::new(), storage, HashMap::new(), HashMap::new());
1478
1479 let mut overlay = EvmOverlay::new(snapshot, None);
1480 let result = overlay.storage(addr, slot).unwrap();
1481 assert_eq!(result, value);
1482 }
1483
1484 #[test]
1485 fn test_overlay_dirty_overrides_snapshot() {
1486 let addr = Address::repeat_byte(0x01);
1487 let slot = U256::from(42);
1488
1489 let mut storage = HashMap::new();
1490 let mut account_storage = HashMap::new();
1491 account_storage.insert(slot, U256::from(100));
1492 storage.insert(addr, account_storage);
1493
1494 let snapshot = snap(HashMap::new(), storage, HashMap::new(), HashMap::new());
1495
1496 let mut overlay = EvmOverlay::new(snapshot, None);
1497
1498 // Write to dirty layer
1499 overlay
1500 .dirty_storage
1501 .entry(addr)
1502 .or_default()
1503 .insert(slot, U256::from(200));
1504
1505 // Should read dirty value, not snapshot
1506 let result = overlay.storage(addr, slot).unwrap();
1507 assert_eq!(result, U256::from(200));
1508 }
1509
1510 #[test]
1511 fn test_overlay_missing_returns_zero() {
1512 let snapshot = snap(
1513 HashMap::new(),
1514 HashMap::new(),
1515 HashMap::new(),
1516 HashMap::new(),
1517 );
1518
1519 let mut overlay = EvmOverlay::new(snapshot, None);
1520 let addr = Address::repeat_byte(0x99);
1521 let result = overlay.storage(addr, U256::from(1)).unwrap();
1522 assert_eq!(result, U256::ZERO);
1523
1524 let account = overlay.basic(addr).unwrap();
1525 assert!(account.is_none());
1526 }
1527
1528 #[test]
1529 fn test_overlay_code_by_hash_from_snapshot() {
1530 let code = Bytecode::new_raw(Bytes::from(vec![0x60, 0x00, 0x60, 0x00]));
1531 let hash = code.hash_slow();
1532
1533 let mut code_by_hash = HashMap::new();
1534 code_by_hash.insert(hash, code.clone());
1535
1536 let snapshot = snap(HashMap::new(), HashMap::new(), code_by_hash, HashMap::new());
1537
1538 let mut overlay = EvmOverlay::new(snapshot, None);
1539 let result = overlay.code_by_hash(hash).unwrap();
1540 assert_eq!(result.len(), 4);
1541 }
1542
1543 #[test]
1544 fn test_overlay_block_hash() {
1545 let mut block_hashes = HashMap::new();
1546 let hash = B256::repeat_byte(0xAB);
1547 block_hashes.insert(42u64, hash);
1548
1549 let snapshot = snap(HashMap::new(), HashMap::new(), HashMap::new(), block_hashes);
1550
1551 let mut overlay = EvmOverlay::new(snapshot, None);
1552 assert_eq!(overlay.block_hash(42).unwrap(), hash);
1553 assert_eq!(overlay.block_hash(99).unwrap(), B256::ZERO);
1554 }
1555}