Skip to main content

foundry_cheatcodes/evm/
fork.rs

1use crate::{
2    Cheatcode, Cheatcodes, CheatcodesCore, CheatcodesExecutor, CheatsCtxt, Result, Vm::*,
3    json::json_value_to_token,
4};
5use alloy_dyn_abi::DynSolValue;
6use alloy_network::AnyNetwork;
7use alloy_primitives::{Address, B256, U256, map::AddressHashMap};
8use alloy_provider::{Provider, RootProvider};
9use alloy_rpc_types::Filter;
10use alloy_sol_types::SolValue;
11use foundry_common::provider::ProviderBuilder;
12use foundry_evm_core::{
13    backend::{Backend, ForkAccountField, LocalForkId},
14    evm::{ExecutionPhase, FoundryEvmFor, FoundryEvmNetwork},
15    fork::CreateFork,
16};
17
18impl Cheatcode for activeForkCall {
19    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
20        let Self {} = self;
21        ccx.active_fork_id().map(|id| id.abi_encode()).ok_or_else(|| fmt_err!("no active fork"))
22    }
23}
24
25impl Cheatcode for createFork_0Call {
26    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
27        let Self { urlOrAlias } = self;
28        create_fork(ccx, urlOrAlias, None)
29    }
30}
31
32impl Cheatcode for createFork_1Call {
33    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
34        let Self { urlOrAlias, blockNumber } = self;
35        create_fork(ccx, urlOrAlias, Some(blockNumber.saturating_to()))
36    }
37}
38
39impl Cheatcode for createFork_2Call {
40    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
41        let Self { urlOrAlias, txHash } = self;
42        create_fork_at_transaction(ccx, urlOrAlias, txHash)
43    }
44}
45
46impl Cheatcode for createSelectFork_0Call {
47    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
48        let Self { urlOrAlias } = self;
49        create_select_fork(ccx, urlOrAlias, None)
50    }
51}
52
53impl Cheatcode for createSelectFork_1Call {
54    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
55        let Self { urlOrAlias, blockNumber } = self;
56        create_select_fork(ccx, urlOrAlias, Some(blockNumber.saturating_to()))
57    }
58}
59
60impl Cheatcode for createSelectFork_2Call {
61    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
62        let Self { urlOrAlias, txHash } = self;
63        create_select_fork_at_transaction(ccx, urlOrAlias, txHash)
64    }
65}
66
67impl Cheatcode for rollFork_0Call {
68    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
69        let Self { blockNumber } = self;
70        persist_caller(ccx);
71        let result = fork_op(ccx, |db, evm| {
72            db.roll_fork(None, (*blockNumber).to(), evm, ExecutionPhase::InFlight)
73        })?;
74        record_fork_roll(ccx, None);
75        Ok(result)
76    }
77}
78
79impl Cheatcode for rollFork_1Call {
80    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
81        let Self { txHash } = self;
82        persist_caller(ccx);
83        let result = fork_op(ccx, |db, evm| {
84            db.roll_fork_to_transaction(None, *txHash, evm, ExecutionPhase::InFlight)
85        })?;
86        record_fork_roll(ccx, None);
87        Ok(result)
88    }
89}
90
91impl Cheatcode for rollFork_2Call {
92    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
93        let Self { forkId, blockNumber } = self;
94        persist_caller(ccx);
95        let result = fork_op(ccx, |db, evm| {
96            db.roll_fork(Some(*forkId), (*blockNumber).to(), evm, ExecutionPhase::InFlight)
97        })?;
98        record_fork_roll(ccx, Some(*forkId));
99        Ok(result)
100    }
101}
102
103impl Cheatcode for rollFork_3Call {
104    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
105        let Self { forkId, txHash } = self;
106        persist_caller(ccx);
107        let result = fork_op(ccx, |db, evm| {
108            db.roll_fork_to_transaction(Some(*forkId), *txHash, evm, ExecutionPhase::InFlight)
109        })?;
110        record_fork_roll(ccx, Some(*forkId));
111        Ok(result)
112    }
113}
114
115impl Cheatcode for selectForkCall {
116    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
117        let Self { forkId } = self;
118        persist_caller(ccx);
119        check_broadcast(ccx.state)?;
120        let source_fork_id = ccx.active_fork_id();
121        let initial = ccx.state.created_account_bindings(None);
122        let propagated = persistent_created_accounts(ccx);
123        let result =
124            fork_op(ccx, |db, evm| db.select_fork(*forkId, evm, ExecutionPhase::InFlight))?;
125        record_fork_switch(ccx, source_fork_id, initial, propagated);
126        Ok(result)
127    }
128}
129
130impl Cheatcode for transact_0Call {
131    fn apply_full<FEN: FoundryEvmNetwork>(
132        &self,
133        ccx: &mut CheatsCtxt<'_, '_, FEN>,
134        executor: &mut dyn CheatcodesExecutor<FEN>,
135    ) -> Result {
136        let Self { txHash } = *self;
137        transact(ccx, executor, txHash, None)
138    }
139}
140
141impl Cheatcode for transact_1Call {
142    fn apply_full<FEN: FoundryEvmNetwork>(
143        &self,
144        ccx: &mut CheatsCtxt<'_, '_, FEN>,
145        executor: &mut dyn CheatcodesExecutor<FEN>,
146    ) -> Result {
147        let Self { forkId, txHash } = *self;
148        transact(ccx, executor, txHash, Some(forkId))
149    }
150}
151
152impl Cheatcode for allowCheatcodesCall {
153    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
154        let Self { account } = self;
155        ccx.db_mut().allow_cheatcode_access(*account);
156        Ok(Default::default())
157    }
158}
159
160impl Cheatcode for makePersistent_0Call {
161    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
162        let Self { account } = self;
163        ccx.db_mut().add_persistent_account(*account);
164        Ok(Default::default())
165    }
166}
167
168impl Cheatcode for makePersistent_1Call {
169    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
170        let Self { account0, account1 } = self;
171        ccx.db_mut().add_persistent_account(*account0);
172        ccx.db_mut().add_persistent_account(*account1);
173        Ok(Default::default())
174    }
175}
176
177impl Cheatcode for makePersistent_2Call {
178    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
179        let Self { account0, account1, account2 } = self;
180        ccx.db_mut().add_persistent_account(*account0);
181        ccx.db_mut().add_persistent_account(*account1);
182        ccx.db_mut().add_persistent_account(*account2);
183        Ok(Default::default())
184    }
185}
186
187impl Cheatcode for makePersistent_3Call {
188    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
189        let Self { accounts } = self;
190        for account in accounts {
191            ccx.db_mut().add_persistent_account(*account);
192        }
193        Ok(Default::default())
194    }
195}
196
197impl Cheatcode for revokePersistent_0Call {
198    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
199        let Self { account } = self;
200        ccx.db_mut().remove_persistent_account(account);
201        Ok(Default::default())
202    }
203}
204
205impl Cheatcode for revokePersistent_1Call {
206    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
207        let Self { accounts } = self;
208        for account in accounts {
209            ccx.db_mut().remove_persistent_account(account);
210        }
211        Ok(Default::default())
212    }
213}
214
215impl Cheatcode for isPersistentCall {
216    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
217        let Self { account } = self;
218        Ok(ccx.is_persistent(account).abi_encode())
219    }
220}
221
222impl Cheatcode for rpc_0Call {
223    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
224        let Self { method, params } = self;
225        let url = ccx.active_fork_url().ok_or_else(|| fmt_err!("no active fork URL found"))?;
226        let result = rpc_call(&url, method, params)?;
227        refresh_active_fork_state(ccx, method, params)?;
228        Ok(result)
229    }
230}
231
232impl Cheatcode for rpc_1Call {
233    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
234        let Self { urlOrAlias, method, params } = self;
235        let url = state.config.rpc_endpoint(urlOrAlias)?.url()?;
236        rpc_call(&url, method, params)
237    }
238}
239
240impl Cheatcode for rpcJson_0Call {
241    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
242        let Self { method, params } = self;
243        let url = ccx.active_fork_url().ok_or_else(|| fmt_err!("no active fork URL found"))?;
244        let result = rpc_json_call(&url, method, params)?;
245        refresh_active_fork_state(ccx, method, params)?;
246        Ok(result)
247    }
248}
249
250impl Cheatcode for rpcJson_1Call {
251    fn apply_context(&self, state: &mut CheatcodesCore) -> Result {
252        let Self { urlOrAlias, method, params } = self;
253        let url = state.config.rpc_endpoint(urlOrAlias)?.url()?;
254        rpc_json_call(&url, method, params)
255    }
256}
257
258impl Cheatcode for eth_getLogsCall {
259    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
260        let Self { fromBlock, toBlock, target, topics } = self;
261        let (Ok(from_block), Ok(to_block)) = (u64::try_from(fromBlock), u64::try_from(toBlock))
262        else {
263            bail!("blocks in block range must be less than 2^64")
264        };
265
266        if topics.len() > 4 {
267            bail!("topics array must contain at most 4 elements")
268        }
269
270        let provider = active_fork_provider(ccx)?;
271        let mut filter = Filter::new().address(*target).from_block(from_block).to_block(to_block);
272        for (i, &topic) in topics.iter().enumerate() {
273            filter.topics[i] = topic.into();
274        }
275
276        let logs = foundry_common::block_on(provider.get_logs(&filter))
277            .map_err(|e| fmt_err!("failed to get logs: {e}"))?;
278
279        let eth_logs = logs
280            .into_iter()
281            .map(|log| EthGetLogs {
282                emitter: log.address(),
283                topics: log.topics().to_vec(),
284                data: log.inner.data.data,
285                blockHash: log.block_hash.unwrap_or_default(),
286                blockNumber: log.block_number.unwrap_or_default(),
287                transactionHash: log.transaction_hash.unwrap_or_default(),
288                transactionIndex: log.transaction_index.unwrap_or_default(),
289                logIndex: U256::from(log.log_index.unwrap_or_default()),
290                removed: log.removed,
291            })
292            .collect::<Vec<_>>();
293
294        Ok(eth_logs.abi_encode())
295    }
296}
297
298impl Cheatcode for eth_getProofCall {
299    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
300        let Self { target, slots, blockNumber } = self;
301        let block_number = u64::try_from(blockNumber)
302            .map_err(|_| fmt_err!("block number must be less than 2^64"))?;
303
304        let provider = active_fork_provider(ccx)?;
305        let proof = foundry_common::block_on(async move {
306            provider.get_proof(*target, slots.clone()).number(block_number).await
307        })
308        .map_err(|e| fmt_err!("failed to get proof: {e}"))?;
309
310        let storage_proof = proof
311            .storage_proof
312            .into_iter()
313            .map(|p| EthStorageProof { key: p.key.as_b256(), value: p.value, proof: p.proof })
314            .collect();
315
316        Ok(EthGetProof {
317            account: proof.address,
318            balance: proof.balance,
319            codeHash: proof.code_hash,
320            nonce: proof.nonce,
321            storageHash: proof.storage_hash,
322            accountProof: proof.account_proof,
323            storageProof: storage_proof,
324        }
325        .abi_encode())
326    }
327}
328
329impl Cheatcode for getRawBlockHeaderCall {
330    fn apply_stateful<FEN: FoundryEvmNetwork>(&self, ccx: &mut CheatsCtxt<'_, '_, FEN>) -> Result {
331        let Self { blockNumber } = self;
332        let provider = active_fork_provider(ccx)?;
333        let block_number = u64::try_from(blockNumber)
334            .map_err(|_| fmt_err!("block number must be less than 2^64"))?;
335        let block =
336            foundry_common::block_on(async move { provider.get_block(block_number.into()).await })
337                .map_err(|e| fmt_err!("failed to get block: {e}"))?
338                .ok_or_else(|| fmt_err!("block {block_number} not found"))?;
339
340        let header: alloy_consensus::Header = block
341            .into_inner()
342            .header
343            .inner
344            .try_into_header()
345            .map_err(|e| fmt_err!("failed to convert to header: {e}"))?;
346        Ok(alloy_rlp::encode(&header).abi_encode())
347    }
348}
349
350/// Creates and then also selects the new fork
351fn create_select_fork<FEN: FoundryEvmNetwork>(
352    ccx: &mut CheatsCtxt<'_, '_, FEN>,
353    url_or_alias: &str,
354    block: Option<u64>,
355) -> Result {
356    check_broadcast(ccx.state)?;
357
358    let fork = create_fork_request(ccx, url_or_alias, block)?;
359    let source_fork_id = ccx.active_fork_id();
360    let initial = ccx.state.created_account_bindings(None);
361    let propagated = persistent_created_accounts(ccx);
362    let result =
363        fork_op(ccx, |db, evm| db.create_select_fork(fork, evm, ExecutionPhase::InFlight))?;
364    record_fork_switch(ccx, source_fork_id, initial, propagated);
365    Ok(result)
366}
367
368/// Creates a new fork
369fn create_fork<FEN: FoundryEvmNetwork>(
370    ccx: &mut CheatsCtxt<'_, '_, FEN>,
371    url_or_alias: &str,
372    block: Option<u64>,
373) -> Result {
374    let fork = create_fork_request(ccx, url_or_alias, block)?;
375    let id = ccx.db_mut().create_fork(fork)?;
376    Ok(id.abi_encode())
377}
378
379/// Creates and then also selects the new fork at the given transaction
380fn create_select_fork_at_transaction<FEN: FoundryEvmNetwork>(
381    ccx: &mut CheatsCtxt<'_, '_, FEN>,
382    url_or_alias: &str,
383    transaction: &B256,
384) -> Result {
385    check_broadcast(ccx.state)?;
386
387    let fork = create_fork_request(ccx, url_or_alias, None)?;
388    let source_fork_id = ccx.active_fork_id();
389    let initial = ccx.state.created_account_bindings(None);
390    let propagated = persistent_created_accounts(ccx);
391    let result = fork_op(ccx, |db, evm| {
392        db.create_select_fork_at_transaction(fork, evm, ExecutionPhase::InFlight, *transaction)
393    })?;
394    record_fork_switch(ccx, source_fork_id, initial, propagated);
395    Ok(result)
396}
397
398/// Creates a new fork at the given transaction
399fn create_fork_at_transaction<FEN: FoundryEvmNetwork>(
400    ccx: &mut CheatsCtxt<'_, '_, FEN>,
401    url_or_alias: &str,
402    transaction: &B256,
403) -> Result {
404    let fork = create_fork_request(ccx, url_or_alias, None)?;
405    let id = ccx.db_mut().create_fork_at_transaction(fork, *transaction)?;
406    Ok(id.abi_encode())
407}
408
409/// Creates the request object for a new fork request
410fn create_fork_request<FEN: FoundryEvmNetwork>(
411    ccx: &mut CheatsCtxt<'_, '_, FEN>,
412    url_or_alias: &str,
413    block: Option<u64>,
414) -> Result<CreateFork> {
415    persist_caller(ccx);
416
417    let rpc_endpoint = ccx.state.core.config.rpc_endpoint(url_or_alias)?;
418    let url = rpc_endpoint.url()?;
419    let mut evm_opts = ccx.state.core.config.evm_opts.clone();
420    evm_opts.fork_block_number = block;
421    evm_opts.fork_block_number_is_inferred = false;
422    // The endpoint's retry settings override the run's only where the endpoint sets them. Its
423    // compute units apply only where the run sets none, as `--no-rpc-rate-limit` also wins.
424    let config = &rpc_endpoint.config;
425    evm_opts.fork_retries = config.retries.or(evm_opts.fork_retries);
426    evm_opts.fork_retry_backoff = config.retry_backoff.or(evm_opts.fork_retry_backoff);
427    evm_opts.compute_units_per_second =
428        evm_opts.compute_units_per_second.or(config.compute_units_per_second);
429    if let Some(Ok(auth)) = rpc_endpoint.auth {
430        let fork_headers = Some(vec![format!("Authorization: {auth}")]);
431        // The cached identity was discovered with other credentials, which may reach another
432        // backend behind the same URL.
433        if evm_opts.fork_headers != fork_headers {
434            evm_opts.fork_endpoint = None;
435        }
436        evm_opts.fork_headers = fork_headers;
437    }
438    let fork = CreateFork {
439        enable_caching: !ccx.state.core.config.no_storage_caching
440            && ccx.state.core.config.rpc_storage_caching.enable_for_endpoint(&url),
441        url,
442        evm_opts,
443    };
444    Ok(fork)
445}
446
447/// Runs a fork operation that switches or replaces the running context, such as `rollFork`,
448/// `selectFork` or `createSelectFork`.
449fn fork_op<FEN: FoundryEvmNetwork, T: SolValue>(
450    ccx: &mut CheatsCtxt<'_, '_, FEN>,
451    f: impl FnOnce(&mut Backend<FEN>, &mut FoundryEvmFor<'_, FEN>) -> eyre::Result<T>,
452) -> Result {
453    ensure!(!ccx.state.in_replay, "cannot select or roll forks in a replayed transaction");
454    let (evm, db) = ccx.evm_db_mut();
455    let result = f(db, evm)?;
456    ccx.state.state_epoch += 1;
457    ccx.state.fork_epoch += 1;
458    Ok(result.abi_encode())
459}
460
461fn persistent_created_accounts<FEN: FoundryEvmNetwork>(
462    ccx: &CheatsCtxt<'_, '_, FEN>,
463) -> Vec<(Address, usize)> {
464    let fork_id = ccx.active_fork_id();
465    ccx.state
466        .created_account_bindings(fork_id)
467        .into_iter()
468        .filter(|(address, _)| ccx.is_persistent(address))
469        .collect()
470}
471
472fn record_fork_switch<FEN: FoundryEvmNetwork>(
473    ccx: &mut CheatsCtxt<'_, '_, FEN>,
474    source_fork_id: Option<LocalForkId>,
475    initial: AddressHashMap<usize>,
476    propagated: Vec<(Address, usize)>,
477) {
478    let target_fork_id = ccx.active_fork_id();
479    ccx.state.fork_block_number_override = ccx.active_fork_block_number();
480    if source_fork_id != target_fork_id {
481        ccx.state.commit_created_account_changes(source_fork_id);
482        // The switch accepted the running state, so reverts no longer undo its persistent writes.
483        ccx.state.persistent_writes.clear();
484        ccx.state.snapshot_restores.accept_writes();
485    }
486    ccx.state.record_initial_created_accounts(target_fork_id, initial);
487    ccx.state.record_propagated_accounts(target_fork_id, propagated);
488    sync_chain_id_override(ccx, target_fork_id);
489}
490
491fn record_fork_roll<FEN: FoundryEvmNetwork>(
492    ccx: &mut CheatsCtxt<'_, '_, FEN>,
493    target_fork_id: Option<LocalForkId>,
494) {
495    let active_fork_id = ccx.active_fork_id();
496    let rolled_fork_id = target_fork_id.or(active_fork_id);
497    ccx.state.env_overrides.clear_implicit_basefee(rolled_fork_id);
498    if target_fork_id.is_none() || target_fork_id == active_fork_id {
499        ccx.state.fork_block_number_override = ccx.active_fork_block_number();
500        ccx.state.commit_created_account_changes(active_fork_id);
501        // The roll accepted the running state, so reverts no longer undo its persistent writes.
502        ccx.state.persistent_writes.clear();
503        ccx.state.snapshot_restores.accept_writes();
504        sync_chain_id_override(ccx, active_fork_id);
505    }
506}
507
508/// Makes `CHAINID` on the fork `fork_id` just switched to or rolled read the fork's chain ID at
509/// once, replacing an earlier `vm.chainId`.
510///
511/// The switch or roll defers the chain ID to the next transaction, and `CHAINID` reads the
512/// transaction's until then. `ccx.evm` can be a frame EVM that already runs the pending chain ID,
513/// so the pending chain ID is recorded whenever there is one.
514fn sync_chain_id_override<FEN: FoundryEvmNetwork>(
515    ccx: &mut CheatsCtxt<'_, '_, FEN>,
516    fork_id: Option<LocalForkId>,
517) {
518    let pending = ccx.db().lifecycle().pending_env().map(|env| env.chain_id());
519    if pending.is_none()
520        && !ccx.state.env_overrides.get(fork_id).is_some_and(|o| o.chain_id.is_some())
521    {
522        return;
523    }
524    let chain_id = pending.unwrap_or_else(|| ccx.evm.version().chain_id);
525    ccx.state.env_overrides.update(fork_id, |o| o.chain_id = Some(chain_id));
526}
527
528fn check_broadcast<FEN: FoundryEvmNetwork>(state: &Cheatcodes<FEN>) -> Result<()> {
529    if state.broadcast.is_none() {
530        Ok(())
531    } else {
532        Err(fmt_err!("cannot select forks during a broadcast"))
533    }
534}
535
536fn transact<FEN: FoundryEvmNetwork>(
537    ccx: &mut CheatsCtxt<'_, '_, FEN>,
538    executor: &mut dyn CheatcodesExecutor<FEN>,
539    transaction: B256,
540    fork_id: Option<U256>,
541) -> Result {
542    let _ = executor.transact(
543        ccx.state,
544        ccx.backend,
545        ccx.evm,
546        ccx.depth as u16,
547        fork_id,
548        transaction,
549    )?;
550    ccx.state.state_epoch += 1;
551    Ok(Default::default())
552}
553
554// Helper to add the caller of fork cheat code as persistent account (in order to make sure that the
555// state of caller contract is not lost when fork changes).
556// Applies to create, select and roll forks actions.
557// https://github.com/foundry-rs/foundry/issues/8004
558fn persist_caller<FEN: FoundryEvmNetwork>(ccx: &mut CheatsCtxt<'_, '_, FEN>) {
559    let caller = ccx.caller;
560    ccx.db_mut().add_persistent_account(caller);
561}
562
563/// Returns a provider for the active fork, configured with the RPC options the fork was created
564/// with (e.g. auth headers, retries and timeouts).
565fn active_fork_provider<FEN: FoundryEvmNetwork>(
566    ccx: &CheatsCtxt<'_, '_, FEN>,
567) -> Result<RootProvider<AnyNetwork>> {
568    let fork = ccx.active_fork_options().ok_or_else(|| fmt_err!("no active fork URL found"))?;
569    Ok(fork.evm_opts.fork_provider_with_url(&fork.url)?)
570}
571
572/// Performs an Ethereum JSON-RPC request to the given endpoint.
573fn rpc_call(url: &str, method: &str, params: &str) -> Result {
574    let result = rpc_result(url, method, params)?;
575    let result_as_tokens = convert_to_bytes(
576        &json_value_to_token(&result, None)
577            .map_err(|err| fmt_err!("failed to parse result: {err}"))?,
578    );
579
580    let payload = match &result_as_tokens {
581        DynSolValue::Bytes(b) => b.clone(),
582        _ => result_as_tokens.abi_encode(),
583    };
584    Ok(DynSolValue::Bytes(payload).abi_encode())
585}
586
587/// Performs an Ethereum JSON-RPC request to the given endpoint and returns the JSON result.
588fn rpc_json_call(url: &str, method: &str, params: &str) -> Result {
589    let result = rpc_result(url, method, params)?;
590    Ok(serde_json::to_string(&result)?.abi_encode())
591}
592
593/// Refreshes cached fork and journal state after a `vm.rpc` call on the active fork that mutates
594/// the node directly. Only well-known Anvil/Hardhat account/storage setters are handled;
595/// chain-advancing methods (e.g. `eth_sendTransaction`) need re-forking, not synchronization.
596fn refresh_active_fork_state<FEN: FoundryEvmNetwork>(
597    ccx: &mut CheatsCtxt<'_, '_, FEN>,
598    method: &str,
599    params: &str,
600) -> Result<()> {
601    let account_field = match method {
602        "anvil_setBalance"
603        | "hardhat_setBalance"
604        | "tenderly_setBalance"
605        | "anvil_addBalance"
606        | "hardhat_addBalance"
607        | "tenderly_addBalance" => Some(ForkAccountField::Balance),
608        "anvil_setNonce" | "hardhat_setNonce" | "evm_setAccountNonce" => {
609            Some(ForkAccountField::Nonce)
610        }
611        "anvil_setCode" | "hardhat_setCode" => Some(ForkAccountField::Code),
612        "anvil_setStorageAt" | "hardhat_setStorageAt" => None,
613        _ => return Ok(()),
614    };
615
616    let Ok(params) = serde_json::from_str::<serde_json::Value>(params) else { return Ok(()) };
617    let Some(address) =
618        params.get(0).and_then(|v| v.as_str()).and_then(|s| s.parse::<Address>().ok())
619    else {
620        return Ok(());
621    };
622
623    let (evm, db) = ccx.evm_db_mut();
624    if let Some(field) = account_field {
625        db.refresh_fork_account(address, field, evm)?;
626    } else {
627        let Some(slot) =
628            params.get(1).and_then(|v| v.as_str()).and_then(|s| s.parse::<U256>().ok())
629        else {
630            return Ok(());
631        };
632        if let Some(write) = db.refresh_fork_storage(address, slot, evm)? {
633            ccx.state.record_persistent(ccx.caller_depth(), ccx.evm.state(), [write]);
634        }
635    }
636    Ok(())
637}
638
639fn rpc_result(url: &str, method: &str, params: &str) -> Result<serde_json::Value> {
640    let provider = ProviderBuilder::<AnyNetwork>::new(url).build()?;
641    let params_json: serde_json::Value = serde_json::from_str(params)?;
642    foundry_common::block_on(provider.raw_request(method.to_string().into(), params_json))
643        .map_err(|err| fmt_err!("{method:?}: {err}"))
644}
645
646/// Convert fixed bytes and address values to bytes in order to prevent encoding issues.
647fn convert_to_bytes(token: &DynSolValue) -> DynSolValue {
648    match token {
649        // Convert fixed bytes to prevent encoding issues.
650        // See: <https://github.com/foundry-rs/foundry/issues/8287>
651        DynSolValue::FixedBytes(bytes, size) => {
652            DynSolValue::Bytes(bytes.as_slice()[..*size].to_vec())
653        }
654        DynSolValue::Address(addr) => DynSolValue::Bytes(addr.to_vec()),
655        val => val.clone(),
656    }
657}