forked from foundry-rs/foundry
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathevm.rs
More file actions
1941 lines (1734 loc) · 68.9 KB
/
evm.rs
File metadata and controls
1941 lines (1734 loc) · 68.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! Implementations of [`Evm`](spec::Group::Evm) cheatcodes.
use crate::{
BroadcastableTransaction, Cheatcode, Cheatcodes, CheatcodesExecutor, CheatsCtxExt, CheatsCtxt,
Error, Result, Vm::*, inspector::RecordDebugStepInfo,
};
use alloy_consensus::TxEnvelope;
use alloy_evm::{EvmEnv, FromRecoveredTx};
use alloy_genesis::{Genesis, GenesisAccount};
use alloy_network::eip2718::EIP4844_TX_TYPE_ID;
use alloy_primitives::{
Address, B256, U256, hex, keccak256,
map::{B256Map, HashMap},
};
use alloy_rlp::Decodable;
use alloy_sol_types::SolValue;
use foundry_common::{
fs::{read_json_file, write_json_file},
slot_identifier::{
ENCODING_BYTES, ENCODING_DYN_ARRAY, ENCODING_INPLACE, ENCODING_MAPPING, SlotIdentifier,
SlotInfo,
},
};
use foundry_compilers::artifacts::EvmVersion;
use foundry_evm_core::{
Env, FoundryBlock, FoundryCfg, FoundryTransaction,
backend::{DatabaseExt, FoundryJournalExt, RevertStateSnapshotAction},
constants::{CALLER, CHEATCODE_ADDRESS, HARDHAT_CONSOLE_ADDRESS, TEST_CONTRACT_ADDRESS},
env::FoundryContextExt,
utils::get_blob_base_fee_update_fraction_by_spec_id,
};
use foundry_evm_traces::TraceMode;
use foundry_primitives::FoundryTxEnvelope;
use itertools::Itertools;
use rand::Rng;
use revm::{
bytecode::Bytecode,
context::{Block, Cfg, ContextTr, JournalTr, Transaction, TxEnv, result::ExecutionResult},
inspector::JournalExt,
primitives::{KECCAK_EMPTY, hardfork::SpecId},
state::{Account, AccountStatus},
};
use std::{
collections::{BTreeMap, HashSet, btree_map::Entry},
fmt::Display,
path::Path,
str::FromStr,
};
mod record_debug_step;
use foundry_common::fmt::format_token_raw;
use foundry_config::evm_spec_id;
use record_debug_step::{convert_call_trace_ctx_to_debug_step, flatten_call_trace};
use serde::Serialize;
mod fork;
pub(crate) mod mapping;
pub(crate) mod mock;
pub(crate) mod prank;
/// JSON-serializable log entry for `getRecordedLogsJson`.
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct LogJson {
/// The topics of the log, including the signature, if any.
topics: Vec<String>,
/// The raw data of the log, hex-encoded with 0x prefix.
data: String,
/// The address of the log's emitter.
emitter: String,
}
/// Records storage slots reads and writes.
#[derive(Clone, Debug, Default)]
pub struct RecordAccess {
/// Storage slots reads.
pub reads: HashMap<Address, Vec<U256>>,
/// Storage slots writes.
pub writes: HashMap<Address, Vec<U256>>,
}
impl RecordAccess {
/// Records a read access to a storage slot.
pub fn record_read(&mut self, target: Address, slot: U256) {
self.reads.entry(target).or_default().push(slot);
}
/// Records a write access to a storage slot.
///
/// This also records a read internally as `SSTORE` does an implicit `SLOAD`.
pub fn record_write(&mut self, target: Address, slot: U256) {
self.record_read(target, slot);
self.writes.entry(target).or_default().push(slot);
}
/// Clears the recorded reads and writes.
pub fn clear(&mut self) {
// Also frees memory.
*self = Default::default();
}
}
/// Records the `snapshotGas*` cheatcodes.
#[derive(Clone, Debug)]
pub struct GasRecord {
/// The group name of the gas snapshot.
pub group: String,
/// The name of the gas snapshot.
pub name: String,
/// The total gas used in the gas snapshot.
pub gas_used: u64,
/// Depth at which the gas snapshot was taken.
pub depth: usize,
}
/// Records `deal` cheatcodes
#[derive(Clone, Debug)]
pub struct DealRecord {
/// Target of the deal.
pub address: Address,
/// The balance of the address before deal was applied
pub old_balance: U256,
/// Balance after deal was applied
pub new_balance: U256,
}
/// Storage slot diff info.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct SlotStateDiff {
/// Initial storage value.
previous_value: B256,
/// Current storage value.
new_value: B256,
/// Storage layout metadata (variable name, type, offset).
/// Only present when contract has storage layout output.
/// This includes decoded values when available.
#[serde(skip_serializing_if = "Option::is_none", flatten)]
slot_info: Option<SlotInfo>,
}
/// Balance diff info.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct BalanceDiff {
/// Initial storage value.
previous_value: U256,
/// Current storage value.
new_value: U256,
}
/// Nonce diff info.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct NonceDiff {
/// Initial nonce value.
previous_value: u64,
/// Current nonce value.
new_value: u64,
}
/// Account state diff info.
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct AccountStateDiffs {
/// Address label, if any set.
label: Option<String>,
/// Contract identifier from artifact. e.g "src/Counter.sol:Counter"
contract: Option<String>,
/// Account balance changes.
balance_diff: Option<BalanceDiff>,
/// Account nonce changes.
nonce_diff: Option<NonceDiff>,
/// State changes, per slot.
state_diff: BTreeMap<B256, SlotStateDiff>,
}
impl Display for AccountStateDiffs {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> eyre::Result<(), std::fmt::Error> {
// Print changed account.
if let Some(label) = &self.label {
writeln!(f, "label: {label}")?;
}
if let Some(contract) = &self.contract {
writeln!(f, "contract: {contract}")?;
}
// Print balance diff if changed.
if let Some(balance_diff) = &self.balance_diff
&& balance_diff.previous_value != balance_diff.new_value
{
writeln!(
f,
"- balance diff: {} → {}",
balance_diff.previous_value, balance_diff.new_value
)?;
}
// Print nonce diff if changed.
if let Some(nonce_diff) = &self.nonce_diff
&& nonce_diff.previous_value != nonce_diff.new_value
{
writeln!(f, "- nonce diff: {} → {}", nonce_diff.previous_value, nonce_diff.new_value)?;
}
// Print state diff if any.
if !&self.state_diff.is_empty() {
writeln!(f, "- state diff:")?;
for (slot, slot_changes) in &self.state_diff {
match &slot_changes.slot_info {
Some(slot_info) => {
if let Some(decoded) = &slot_info.decoded {
// Have slot info with decoded values - show decoded values
writeln!(
f,
"@ {slot} ({}, {}): {} → {}",
slot_info.label,
slot_info.slot_type.dyn_sol_type,
format_token_raw(&decoded.previous_value),
format_token_raw(&decoded.new_value)
)?;
} else {
// Have slot info but no decoded values - show raw hex values
writeln!(
f,
"@ {slot} ({}, {}): {} → {}",
slot_info.label,
slot_info.slot_type.dyn_sol_type,
slot_changes.previous_value,
slot_changes.new_value
)?;
}
}
None => {
// No slot info - show raw hex values
writeln!(
f,
"@ {slot}: {} → {}",
slot_changes.previous_value, slot_changes.new_value
)?;
}
}
}
}
Ok(())
}
}
impl Cheatcode for addrCall {
fn apply(&self, _state: &mut Cheatcodes) -> Result {
let Self { privateKey } = self;
let wallet = super::crypto::parse_wallet(privateKey)?;
Ok(wallet.address().abi_encode())
}
}
impl Cheatcode for getNonce_0Call {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { account } = self;
get_nonce(ccx, account)
}
}
impl Cheatcode for getNonce_1Call {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { wallet } = self;
get_nonce(ccx, &wallet.addr)
}
}
impl Cheatcode for loadCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target, slot } = *self;
ccx.ensure_not_precompile(&target)?;
ccx.ecx.journal_mut().load_account(target)?;
let mut val = ccx
.ecx
.journal_mut()
.sload(target, slot.into())
.map_err(|e| fmt_err!("failed to load storage slot: {:?}", e))?;
if val.is_cold && val.data.is_zero() {
if ccx.state.has_arbitrary_storage(&target) {
// If storage slot is untouched and load from a target with arbitrary storage,
// then set random value for current slot.
let rand_value = ccx.state.rng().random();
ccx.state.arbitrary_storage.as_mut().unwrap().save(
ccx.ecx,
target,
slot.into(),
rand_value,
);
val.data = rand_value;
} else if ccx.state.is_arbitrary_storage_copy(&target) {
// If storage slot is untouched and load from a target that copies storage from
// a source address with arbitrary storage, then copy existing arbitrary value.
// If no arbitrary value generated yet, then the random one is saved and set.
let rand_value = ccx.state.rng().random();
val.data = ccx.state.arbitrary_storage.as_mut().unwrap().copy(
ccx.ecx,
target,
slot.into(),
rand_value,
);
}
}
Ok(val.abi_encode())
}
}
impl Cheatcode for loadAllocsCall {
fn apply_stateful<CTX: ContextTr<Journal: FoundryJournalExt, Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { pathToAllocsJson } = self;
let path = Path::new(pathToAllocsJson);
ensure!(path.exists(), "allocs file does not exist: {pathToAllocsJson}");
// Let's first assume we're reading a file with only the allocs.
let allocs: BTreeMap<Address, GenesisAccount> = match read_json_file(path) {
Ok(allocs) => allocs,
Err(_) => {
// Let's try and read from a genesis file, and extract allocs.
let genesis = read_json_file::<Genesis>(path)?;
genesis.alloc
}
};
// Then, load the allocs into the database.
let (db, inner) = ccx.ecx.journal_mut().as_db_and_inner();
db.load_allocs(&allocs, inner)
.map(|()| Vec::default())
.map_err(|e| fmt_err!("failed to load allocs: {e}"))
}
}
impl Cheatcode for cloneAccountCall {
fn apply_stateful<CTX: ContextTr<Journal: FoundryJournalExt, Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { source, target } = self;
let account = ccx.ecx.journal_mut().load_account(*source)?;
let genesis = genesis_account(account.data);
let (db, inner) = ccx.ecx.journal_mut().as_db_and_inner();
db.clone_account(&genesis, target, inner)?;
// Cloned account should persist in forked envs.
ccx.ecx.db_mut().add_persistent_account(*target);
Ok(Default::default())
}
}
impl Cheatcode for dumpStateCall {
fn apply_stateful<CTX: ContextTr<Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { pathToStateJson } = self;
let path = Path::new(pathToStateJson);
// Do not include system account or empty accounts in the dump.
let skip = |key: &Address, val: &Account| {
key == &CHEATCODE_ADDRESS
|| key == &CALLER
|| key == &HARDHAT_CONSOLE_ADDRESS
|| key == &TEST_CONTRACT_ADDRESS
|| key == &ccx.caller
|| key == &ccx.state.config.evm_opts.sender
|| val.is_empty()
};
let alloc = ccx
.ecx
.journal_mut()
.evm_state_mut()
.iter_mut()
.filter(|(key, val)| !skip(key, val))
.map(|(key, val)| (key, genesis_account(val)))
.collect::<BTreeMap<_, _>>();
write_json_file(path, &alloc)?;
Ok(Default::default())
}
}
impl Cheatcode for recordCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.recording_accesses = true;
state.accesses.clear();
Ok(Default::default())
}
}
impl Cheatcode for stopRecordCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
state.recording_accesses = false;
Ok(Default::default())
}
}
impl Cheatcode for accessesCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { target } = *self;
let result = (
state.accesses.reads.entry(target).or_default().as_slice(),
state.accesses.writes.entry(target).or_default().as_slice(),
);
Ok(result.abi_encode_params())
}
}
impl Cheatcode for recordLogsCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.recorded_logs = Some(Default::default());
Ok(Default::default())
}
}
impl Cheatcode for getRecordedLogsCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
Ok(state.recorded_logs.replace(Default::default()).unwrap_or_default().abi_encode())
}
}
impl Cheatcode for getRecordedLogsJsonCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
let logs = state.recorded_logs.replace(Default::default()).unwrap_or_default();
let json_logs: Vec<_> = logs
.into_iter()
.map(|log| LogJson {
topics: log.topics.iter().map(|t| format!("{t}")).collect(),
data: hex::encode_prefixed(&log.data),
emitter: format!("{}", log.emitter),
})
.collect();
Ok(serde_json::to_string(&json_logs)?.abi_encode())
}
}
impl Cheatcode for pauseGasMeteringCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.gas_metering.paused = true;
Ok(Default::default())
}
}
impl Cheatcode for resumeGasMeteringCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.gas_metering.resume();
Ok(Default::default())
}
}
impl Cheatcode for resetGasMeteringCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.gas_metering.reset();
Ok(Default::default())
}
}
impl Cheatcode for lastCallGasCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
let Some(last_call_gas) = &state.gas_metering.last_call_gas else {
bail!("no external call was made yet");
};
Ok(last_call_gas.abi_encode())
}
}
impl Cheatcode for getChainIdCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
Ok(U256::from(ccx.ecx.cfg().chain_id()).abi_encode())
}
}
impl Cheatcode for chainIdCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newChainId } = self;
ensure!(*newChainId <= U256::from(u64::MAX), "chain ID must be less than 2^64");
ccx.ecx.cfg_mut().set_chain_id(newChainId.to());
Ok(Default::default())
}
}
impl Cheatcode for coinbaseCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newCoinbase } = self;
ccx.ecx.block_mut().set_beneficiary(*newCoinbase);
Ok(Default::default())
}
}
impl Cheatcode for difficultyCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newDifficulty } = self;
ensure!(
ccx.ecx.cfg().spec().into() < SpecId::MERGE,
"`difficulty` is not supported after the Paris hard fork, use `prevrandao` instead; \
see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
);
ccx.ecx.block_mut().set_difficulty(*newDifficulty);
Ok(Default::default())
}
}
impl Cheatcode for feeCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newBasefee } = self;
ensure!(*newBasefee <= U256::from(u64::MAX), "base fee must be less than 2^64");
ccx.ecx.block_mut().set_basefee(newBasefee.saturating_to());
Ok(Default::default())
}
}
impl Cheatcode for prevrandao_0Call {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newPrevrandao } = self;
ensure!(
ccx.ecx.cfg().spec().into() >= SpecId::MERGE,
"`prevrandao` is not supported before the Paris hard fork, use `difficulty` instead; \
see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
);
ccx.ecx.block_mut().set_prevrandao(Some(*newPrevrandao));
Ok(Default::default())
}
}
impl Cheatcode for prevrandao_1Call {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newPrevrandao } = self;
ensure!(
ccx.ecx.cfg().spec().into() >= SpecId::MERGE,
"`prevrandao` is not supported before the Paris hard fork, use `difficulty` instead; \
see EIP-4399: https://eips.ethereum.org/EIPS/eip-4399"
);
ccx.ecx.block_mut().set_prevrandao(Some((*newPrevrandao).into()));
Ok(Default::default())
}
}
impl Cheatcode for blobhashesCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { hashes } = self;
ensure!(
ccx.ecx.cfg().spec().into() >= SpecId::CANCUN,
"`blobhashes` is not supported before the Cancun hard fork; \
see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
);
ccx.ecx.tx_mut().set_blob_hashes(hashes.clone());
// force this as 4844 txtype
ccx.ecx.tx_mut().set_tx_type(EIP4844_TX_TYPE_ID);
Ok(Default::default())
}
}
impl Cheatcode for getBlobhashesCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
ensure!(
ccx.ecx.cfg().spec().into() >= SpecId::CANCUN,
"`getBlobhashes` is not supported before the Cancun hard fork; \
see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
);
Ok(ccx.ecx.tx().blob_versioned_hashes().to_vec().abi_encode())
}
}
impl Cheatcode for rollCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newHeight } = self;
ccx.ecx.block_mut().set_number(*newHeight);
Ok(Default::default())
}
}
impl Cheatcode for getBlockNumberCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
Ok(ccx.ecx.block().number().abi_encode())
}
}
impl Cheatcode for txGasPriceCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newGasPrice } = self;
ensure!(*newGasPrice <= U256::from(u64::MAX), "gas price must be less than 2^64");
ccx.ecx.tx_mut().set_gas_price(newGasPrice.saturating_to());
Ok(Default::default())
}
}
impl Cheatcode for warpCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newTimestamp } = self;
ccx.ecx.block_mut().set_timestamp(*newTimestamp);
Ok(Default::default())
}
}
impl Cheatcode for getBlockTimestampCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
Ok(ccx.ecx.block().timestamp().abi_encode())
}
}
impl Cheatcode for blobBaseFeeCall {
fn apply_stateful<CTX: FoundryContextExt>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { newBlobBaseFee } = self;
ensure!(
ccx.ecx.cfg().spec().into() >= SpecId::CANCUN,
"`blobBaseFee` is not supported before the Cancun hard fork; \
see EIP-4844: https://eips.ethereum.org/EIPS/eip-4844"
);
let spec: SpecId = ccx.ecx.cfg().spec().into();
ccx.ecx.block_mut().set_blob_excess_gas_and_price(
(*newBlobBaseFee).to(),
get_blob_base_fee_update_fraction_by_spec_id(spec),
);
Ok(Default::default())
}
}
impl Cheatcode for getBlobBaseFeeCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
Ok(ccx.ecx.block().blob_excess_gas().unwrap_or(0).abi_encode())
}
}
impl Cheatcode for dealCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt, Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { account: address, newBalance: new_balance } = *self;
let account = journaled_account(ccx.ecx, address)?;
let old_balance = std::mem::replace(&mut account.info.balance, new_balance);
let record = DealRecord { address, old_balance, new_balance };
ccx.state.eth_deals.push(record);
Ok(Default::default())
}
}
impl Cheatcode for etchCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target, newRuntimeBytecode } = self;
ccx.ensure_not_precompile(target)?;
ccx.ecx.journal_mut().load_account(*target)?;
let bytecode = Bytecode::new_raw_checked(newRuntimeBytecode.clone())
.map_err(|e| fmt_err!("failed to create bytecode: {e}"))?;
ccx.ecx.journal_mut().set_code(*target, bytecode);
Ok(Default::default())
}
}
impl Cheatcode for resetNonceCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt, Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { account } = self;
let account = journaled_account(ccx.ecx, *account)?;
// Per EIP-161, EOA nonces start at 0, but contract nonces
// start at 1. Comparing by code_hash instead of code
// to avoid hitting the case where account's code is None.
let empty = account.info.code_hash == KECCAK_EMPTY;
let nonce = if empty { 0 } else { 1 };
account.info.nonce = nonce;
debug!(target: "cheatcodes", nonce, "reset");
Ok(Default::default())
}
}
impl Cheatcode for setNonceCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt, Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { account, newNonce } = *self;
let account = journaled_account(ccx.ecx, account)?;
// nonce must increment only
let current = account.info.nonce;
ensure!(
newNonce >= current,
"new nonce ({newNonce}) must be strictly equal to or higher than the \
account's current nonce ({current})"
);
account.info.nonce = newNonce;
Ok(Default::default())
}
}
impl Cheatcode for setNonceUnsafeCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt, Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { account, newNonce } = *self;
let account = journaled_account(ccx.ecx, account)?;
account.info.nonce = newNonce;
Ok(Default::default())
}
}
impl Cheatcode for storeCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target, slot, value } = *self;
ccx.ensure_not_precompile(&target)?;
ensure_loaded_account(ccx.ecx, target)?;
ccx.ecx
.journal_mut()
.sstore(target, slot.into(), value.into())
.map_err(|e| fmt_err!("failed to store storage slot: {:?}", e))?;
Ok(Default::default())
}
}
impl Cheatcode for coolCall {
fn apply_stateful<CTX: ContextTr<Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target } = self;
if let Some(account) = ccx.ecx.journal_mut().evm_state_mut().get_mut(target) {
account.unmark_touch();
account.storage.values_mut().for_each(|slot| slot.mark_cold());
}
Ok(Default::default())
}
}
impl Cheatcode for accessListCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self { access } = self;
let access_list = access
.iter()
.map(|item| {
let keys = item.storageKeys.iter().map(|key| B256::from(*key)).collect_vec();
alloy_rpc_types::AccessListItem { address: item.target, storage_keys: keys }
})
.collect_vec();
state.access_list = Some(alloy_rpc_types::AccessList::from(access_list));
Ok(Default::default())
}
}
impl Cheatcode for noAccessListCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
// Set to empty option in order to override previous applied access list.
if state.access_list.is_some() {
state.access_list = Some(alloy_rpc_types::AccessList::default());
}
Ok(Default::default())
}
}
impl Cheatcode for warmSlotCall {
fn apply_stateful<CTX: ContextTr<Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target, slot } = *self;
set_cold_slot(ccx, target, slot.into(), false);
Ok(Default::default())
}
}
impl Cheatcode for coolSlotCall {
fn apply_stateful<CTX: ContextTr<Journal: JournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { target, slot } = *self;
set_cold_slot(ccx, target, slot.into(), true);
Ok(Default::default())
}
}
impl Cheatcode for readCallersCall {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
read_callers(ccx.state, &ccx.ecx.tx().caller(), ccx.ecx.journal().depth())
}
}
impl Cheatcode for snapshotValue_0Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { name, value } = self;
inner_value_snapshot(ccx, None, Some(name.clone()), value.to_string())
}
}
impl Cheatcode for snapshotValue_1Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { group, name, value } = self;
inner_value_snapshot(ccx, Some(group.clone()), Some(name.clone()), value.to_string())
}
}
impl Cheatcode for snapshotGasLastCall_0Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { name } = self;
let Some(last_call_gas) = &ccx.state.gas_metering.last_call_gas else {
bail!("no external call was made yet");
};
inner_last_gas_snapshot(ccx, None, Some(name.clone()), last_call_gas.gasTotalUsed)
}
}
impl Cheatcode for snapshotGasLastCall_1Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { name, group } = self;
let Some(last_call_gas) = &ccx.state.gas_metering.last_call_gas else {
bail!("no external call was made yet");
};
inner_last_gas_snapshot(
ccx,
Some(group.clone()),
Some(name.clone()),
last_call_gas.gasTotalUsed,
)
}
}
impl Cheatcode for startSnapshotGas_0Call {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { name } = self;
inner_start_gas_snapshot(ccx, None, Some(name.clone()))
}
}
impl Cheatcode for startSnapshotGas_1Call {
fn apply_stateful<CTX: ContextTr>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { group, name } = self;
inner_start_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()))
}
}
impl Cheatcode for stopSnapshotGas_0Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self {} = self;
inner_stop_gas_snapshot(ccx, None, None)
}
}
impl Cheatcode for stopSnapshotGas_1Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { name } = self;
inner_stop_gas_snapshot(ccx, None, Some(name.clone()))
}
}
impl Cheatcode for stopSnapshotGas_2Call {
fn apply_stateful<CTX>(&self, ccx: &mut CheatsCtxt<'_, CTX>) -> Result {
let Self { group, name } = self;
inner_stop_gas_snapshot(ccx, Some(group.clone()), Some(name.clone()))
}
}
// Deprecated in favor of `snapshotStateCall`
impl Cheatcode for snapshotCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self {} = self;
inner_snapshot_state(ccx)
}
}
impl Cheatcode for snapshotStateCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self {} = self;
inner_snapshot_state(ccx)
}
}
// Deprecated in favor of `revertToStateCall`
impl Cheatcode for revertToCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_revert_to_state(ccx, *snapshotId)
}
}
impl Cheatcode for revertToStateCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_revert_to_state(ccx, *snapshotId)
}
}
// Deprecated in favor of `revertToStateAndDeleteCall`
impl Cheatcode for revertToAndDeleteCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_revert_to_state_and_delete(ccx, *snapshotId)
}
}
impl Cheatcode for revertToStateAndDeleteCall {
fn apply_stateful<CTX: FoundryContextExt<Journal: FoundryJournalExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_revert_to_state_and_delete(ccx, *snapshotId)
}
}
// Deprecated in favor of `deleteStateSnapshotCall`
impl Cheatcode for deleteSnapshotCall {
fn apply_stateful<CTX: FoundryContextExt<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_delete_state_snapshot(ccx, *snapshotId)
}
}
impl Cheatcode for deleteStateSnapshotCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self { snapshotId } = self;
inner_delete_state_snapshot(ccx, *snapshotId)
}
}
// Deprecated in favor of `deleteStateSnapshotsCall`
impl Cheatcode for deleteSnapshotsCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self {} = self;
inner_delete_state_snapshots(ccx)
}
}
impl Cheatcode for deleteStateSnapshotsCall {
fn apply_stateful<CTX: ContextTr<Db: DatabaseExt>>(
&self,
ccx: &mut CheatsCtxt<'_, CTX>,
) -> Result {
let Self {} = self;
inner_delete_state_snapshots(ccx)
}
}
impl Cheatcode for startStateDiffRecordingCall {
fn apply(&self, state: &mut Cheatcodes) -> Result {
let Self {} = self;
state.recorded_account_diffs_stack = Some(Default::default());
// Enable mapping recording to track mapping slot accesses
state.mapping_slots.get_or_insert_default();