-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
config.rs
1433 lines (1276 loc) · 48.9 KB
/
config.rs
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
use crate::{
cmd::StateFile,
eth::{
backend::{
db::{Db, SerializableState},
fork::{ClientFork, ClientForkConfig},
genesis::GenesisConfig,
mem::fork_db::ForkedDatabase,
time::duration_since_unix_epoch,
},
fees::{INITIAL_BASE_FEE, INITIAL_GAS_PRICE},
pool::transactions::{PoolTransaction, TransactionOrder},
},
mem::{self, in_memory_db::MemDb},
FeeManager, Hardfork, PrecompileFactory,
};
use alloy_genesis::Genesis;
use alloy_network::AnyNetwork;
use alloy_primitives::{hex, utils::Unit, BlockNumber, TxHash, U256};
use alloy_provider::Provider;
use alloy_rpc_types::{BlockNumberOrTag, Transaction};
use alloy_signer::Signer;
use alloy_signer_local::{
coins_bip39::{English, Mnemonic},
MnemonicBuilder, PrivateKeySigner,
};
use alloy_transport::{Transport, TransportError};
use anvil_server::ServerConfig;
use eyre::Result;
use foundry_common::{
provider::{ProviderBuilder, RetryProvider},
ALCHEMY_FREE_TIER_CUPS, NON_ARCHIVE_NODE_WARNING, REQUEST_TIMEOUT,
};
use foundry_config::Config;
use foundry_evm::{
backend::{BlockchainDb, BlockchainDbMeta, SharedBackend},
constants::DEFAULT_CREATE2_DEPLOYER,
revm::primitives::{BlockEnv, CfgEnv, CfgEnvWithHandlerCfg, EnvWithHandlerCfg, SpecId, TxEnv},
utils::apply_chain_and_block_specific_env_changes,
};
use itertools::Itertools;
use parking_lot::RwLock;
use rand::thread_rng;
use revm::primitives::BlobExcessGasAndPrice;
use serde_json::{json, to_writer, Value};
use std::{
collections::HashMap,
fmt::Write as FmtWrite,
fs::File,
net::{IpAddr, Ipv4Addr},
path::{Path, PathBuf},
sync::Arc,
time::Duration,
};
use yansi::Paint;
/// Default port the rpc will open
pub const NODE_PORT: u16 = 8545;
/// Default chain id of the node
pub const CHAIN_ID: u64 = 31337;
/// Default mnemonic for dev accounts
pub const DEFAULT_MNEMONIC: &str = "test test test test test test test test test test test junk";
/// The default IPC endpoint
pub const DEFAULT_IPC_ENDPOINT: &str =
if cfg!(unix) { "/tmp/anvil.ipc" } else { r"\\.\pipe\anvil.ipc" };
/// `anvil 0.1.0 (f01b232bc 2022-04-13T23:28:39.493201+00:00)`
pub const VERSION_MESSAGE: &str = concat!(
env!("CARGO_PKG_VERSION"),
" (",
env!("VERGEN_GIT_SHA"),
" ",
env!("VERGEN_BUILD_TIMESTAMP"),
")"
);
const BANNER: &str = r"
_ _
(_) | |
__ _ _ __ __ __ _ | |
/ _` | | '_ \ \ \ / / | | | |
| (_| | | | | | \ V / | | | |
\__,_| |_| |_| \_/ |_| |_|
";
/// Configurations of the EVM node
#[derive(Clone, Debug)]
pub struct NodeConfig {
/// Chain ID of the EVM chain
pub chain_id: Option<u64>,
/// Default gas limit for all txs
pub gas_limit: u128,
/// If set to `true`, disables the block gas limit
pub disable_block_gas_limit: bool,
/// Default gas price for all txs
pub gas_price: Option<u128>,
/// Default base fee
pub base_fee: Option<u128>,
/// Default blob excess gas and price
pub blob_excess_gas_and_price: Option<BlobExcessGasAndPrice>,
/// The hardfork to use
pub hardfork: Option<Hardfork>,
/// Signer accounts that will be initialised with `genesis_balance` in the genesis block
pub genesis_accounts: Vec<PrivateKeySigner>,
/// Native token balance of every genesis account in the genesis block
pub genesis_balance: U256,
/// Genesis block timestamp
pub genesis_timestamp: Option<u64>,
/// Signer accounts that can sign messages/transactions from the EVM node
pub signer_accounts: Vec<PrivateKeySigner>,
/// Configured block time for the EVM chain. Use `None` to mine a new block for every tx
pub block_time: Option<Duration>,
/// Disable auto, interval mining mode uns use `MiningMode::None` instead
pub no_mining: bool,
/// port to use for the server
pub port: u16,
/// maximum number of transactions in a block
pub max_transactions: usize,
/// don't print anything on startup
pub silent: bool,
/// url of the rpc server that should be used for any rpc calls
pub eth_rpc_url: Option<String>,
/// pins the block number or transaction hash for the state fork
pub fork_choice: Option<ForkChoice>,
/// headers to use with `eth_rpc_url`
pub fork_headers: Vec<String>,
/// specifies chain id for cache to skip fetching from remote in offline-start mode
pub fork_chain_id: Option<U256>,
/// The generator used to generate the dev accounts
pub account_generator: Option<AccountGenerator>,
/// whether to enable tracing
pub enable_tracing: bool,
/// Explicitly disables the use of RPC caching.
pub no_storage_caching: bool,
/// How to configure the server
pub server_config: ServerConfig,
/// The host the server will listen on
pub host: Vec<IpAddr>,
/// How transactions are sorted in the mempool
pub transaction_order: TransactionOrder,
/// Filename to write anvil output as json
pub config_out: Option<String>,
/// The genesis to use to initialize the node
pub genesis: Option<Genesis>,
/// Timeout in for requests sent to remote JSON-RPC server in forking mode
pub fork_request_timeout: Duration,
/// Number of request retries for spurious networks
pub fork_request_retries: u32,
/// The initial retry backoff
pub fork_retry_backoff: Duration,
/// available CUPS
pub compute_units_per_second: u64,
/// The ipc path
pub ipc_path: Option<Option<String>>,
/// Enable transaction/call steps tracing for debug calls returning geth-style traces
pub enable_steps_tracing: bool,
/// Enable printing of `console.log` invocations.
pub print_logs: bool,
/// Enable auto impersonation of accounts on startup
pub enable_auto_impersonate: bool,
/// Configure the code size limit
pub code_size_limit: Option<usize>,
/// Configures how to remove historic state.
///
/// If set to `Some(num)` keep latest num state in memory only.
pub prune_history: PruneStateHistoryConfig,
/// The file where to load the state from
pub init_state: Option<SerializableState>,
/// max number of blocks with transactions in memory
pub transaction_block_keeper: Option<usize>,
/// Disable the default CREATE2 deployer
pub disable_default_create2_deployer: bool,
/// Enable Optimism deposit transaction
pub enable_optimism: bool,
/// Slots in an epoch
pub slots_in_an_epoch: u64,
/// The memory limit per EVM execution in bytes.
pub memory_limit: Option<u64>,
/// Factory used by `anvil` to extend the EVM's precompiles.
pub precompile_factory: Option<Arc<dyn PrecompileFactory>>,
}
impl NodeConfig {
fn as_string(&self, fork: Option<&ClientFork>) -> String {
let mut config_string: String = String::new();
let _ = write!(config_string, "\n{}", BANNER.green());
let _ = write!(config_string, "\n {VERSION_MESSAGE}");
let _ = write!(config_string, "\n {}", "https://github.com/foundry-rs/foundry".green());
let _ = write!(
config_string,
r#"
Available Accounts
==================
"#
);
let balance = alloy_primitives::utils::format_ether(self.genesis_balance);
for (idx, wallet) in self.genesis_accounts.iter().enumerate() {
write!(config_string, "\n({idx}) {} ({balance} ETH)", wallet.address()).unwrap();
}
let _ = write!(
config_string,
r#"
Private Keys
==================
"#
);
for (idx, wallet) in self.genesis_accounts.iter().enumerate() {
let hex = hex::encode(wallet.credential().to_bytes());
let _ = write!(config_string, "\n({idx}) 0x{hex}");
}
if let Some(ref gen) = self.account_generator {
let _ = write!(
config_string,
r#"
Wallet
==================
Mnemonic: {}
Derivation path: {}
"#,
gen.phrase,
gen.get_derivation_path()
);
}
if let Some(fork) = fork {
let _ = write!(
config_string,
r#"
Fork
==================
Endpoint: {}
Block number: {}
Block hash: {:?}
Chain ID: {}
"#,
fork.eth_rpc_url(),
fork.block_number(),
fork.block_hash(),
fork.chain_id()
);
if let Some(tx_hash) = fork.transaction_hash() {
let _ = writeln!(config_string, "Transaction hash: {tx_hash}");
}
} else {
let _ = write!(
config_string,
r#"
Chain ID
==================
{}
"#,
self.get_chain_id().green()
);
}
if (SpecId::from(self.get_hardfork()) as u8) < (SpecId::LONDON as u8) {
let _ = write!(
config_string,
r#"
Gas Price
==================
{}
"#,
self.get_gas_price().green()
);
} else {
let _ = write!(
config_string,
r#"
Base Fee
==================
{}
"#,
self.get_base_fee().green()
);
}
let _ = write!(
config_string,
r#"
Gas Limit
==================
{}
"#,
self.gas_limit.green()
);
let _ = write!(
config_string,
r#"
Genesis Timestamp
==================
{}
"#,
self.get_genesis_timestamp().green()
);
config_string
}
fn as_json(&self, fork: Option<&ClientFork>) -> Value {
let mut wallet_description = HashMap::new();
let mut available_accounts = Vec::with_capacity(self.genesis_accounts.len());
let mut private_keys = Vec::with_capacity(self.genesis_accounts.len());
for wallet in &self.genesis_accounts {
available_accounts.push(format!("{:?}", wallet.address()));
private_keys.push(format!("0x{}", hex::encode(wallet.credential().to_bytes())));
}
if let Some(ref gen) = self.account_generator {
let phrase = gen.get_phrase().to_string();
let derivation_path = gen.get_derivation_path().to_string();
wallet_description.insert("derivation_path".to_string(), derivation_path);
wallet_description.insert("mnemonic".to_string(), phrase);
};
if let Some(fork) = fork {
json!({
"available_accounts": available_accounts,
"private_keys": private_keys,
"endpoint": fork.eth_rpc_url(),
"block_number": fork.block_number(),
"block_hash": fork.block_hash(),
"chain_id": fork.chain_id(),
"wallet": wallet_description,
"base_fee": format!("{}", self.get_base_fee()),
"gas_price": format!("{}", self.get_gas_price()),
"gas_limit": format!("{}", self.gas_limit),
})
} else {
json!({
"available_accounts": available_accounts,
"private_keys": private_keys,
"wallet": wallet_description,
"base_fee": format!("{}", self.get_base_fee()),
"gas_price": format!("{}", self.get_gas_price()),
"gas_limit": format!("{}", self.gas_limit),
"genesis_timestamp": format!("{}", self.get_genesis_timestamp()),
})
}
}
}
impl NodeConfig {
/// Returns a new config intended to be used in tests, which does not print and binds to a
/// random, free port by setting it to `0`
#[doc(hidden)]
pub fn test() -> Self {
Self { enable_tracing: true, silent: true, port: 0, ..Default::default() }
}
/// Returns a new config which does not initialize any accounts on node startup.
pub fn empty_state() -> Self {
Self {
genesis_accounts: vec![],
signer_accounts: vec![],
disable_default_create2_deployer: true,
..Default::default()
}
}
}
impl Default for NodeConfig {
fn default() -> Self {
// generate some random wallets
let genesis_accounts = AccountGenerator::new(10).phrase(DEFAULT_MNEMONIC).gen();
Self {
chain_id: None,
gas_limit: 30_000_000,
disable_block_gas_limit: false,
gas_price: None,
hardfork: None,
signer_accounts: genesis_accounts.clone(),
genesis_timestamp: None,
genesis_accounts,
// 100ETH default balance
genesis_balance: Unit::ETHER.wei().saturating_mul(U256::from(100u64)),
block_time: None,
no_mining: false,
port: NODE_PORT,
// TODO make this something dependent on block capacity
max_transactions: 1_000,
silent: false,
eth_rpc_url: None,
fork_choice: None,
account_generator: None,
base_fee: None,
blob_excess_gas_and_price: None,
enable_tracing: true,
enable_steps_tracing: false,
print_logs: true,
enable_auto_impersonate: false,
no_storage_caching: false,
server_config: Default::default(),
host: vec![IpAddr::V4(Ipv4Addr::LOCALHOST)],
transaction_order: Default::default(),
config_out: None,
genesis: None,
fork_request_timeout: REQUEST_TIMEOUT,
fork_headers: vec![],
fork_request_retries: 5,
fork_retry_backoff: Duration::from_millis(1_000),
fork_chain_id: None,
// alchemy max cpus <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
compute_units_per_second: ALCHEMY_FREE_TIER_CUPS,
ipc_path: None,
code_size_limit: None,
prune_history: Default::default(),
init_state: None,
transaction_block_keeper: None,
disable_default_create2_deployer: false,
enable_optimism: false,
slots_in_an_epoch: 32,
memory_limit: None,
precompile_factory: None,
}
}
}
impl NodeConfig {
/// Returns the memory limit of the node
#[must_use]
pub fn with_memory_limit(mut self, mems_value: Option<u64>) -> Self {
self.memory_limit = mems_value;
self
}
/// Returns the base fee to use
pub fn get_base_fee(&self) -> u128 {
self.base_fee
.or_else(|| self.genesis.as_ref().and_then(|g| g.base_fee_per_gas))
.unwrap_or(INITIAL_BASE_FEE)
}
/// Returns the base fee to use
pub fn get_gas_price(&self) -> u128 {
self.gas_price.unwrap_or(INITIAL_GAS_PRICE)
}
pub fn get_blob_excess_gas_and_price(&self) -> BlobExcessGasAndPrice {
if let Some(blob_excess_gas_and_price) = &self.blob_excess_gas_and_price {
blob_excess_gas_and_price.clone()
} else if let Some(excess_blob_gas) = self.genesis.as_ref().and_then(|g| g.excess_blob_gas)
{
BlobExcessGasAndPrice::new(excess_blob_gas as u64)
} else {
BlobExcessGasAndPrice { blob_gasprice: 0, excess_blob_gas: 0 }
}
}
/// Returns the base fee to use
pub fn get_hardfork(&self) -> Hardfork {
self.hardfork.unwrap_or_default()
}
/// Sets a custom code size limit
#[must_use]
pub fn with_code_size_limit(mut self, code_size_limit: Option<usize>) -> Self {
self.code_size_limit = code_size_limit;
self
}
/// Sets the init state if any
#[must_use]
pub fn with_init_state(mut self, init_state: Option<SerializableState>) -> Self {
self.init_state = init_state;
self
}
/// Loads the init state from a file if it exists
#[must_use]
pub fn with_init_state_path(mut self, path: impl AsRef<Path>) -> Self {
self.init_state = StateFile::parse_path(path).ok().and_then(|file| file.state);
self
}
/// Sets the chain ID
#[must_use]
pub fn with_chain_id<U: Into<u64>>(mut self, chain_id: Option<U>) -> Self {
self.set_chain_id(chain_id);
self
}
/// Returns the chain ID to use
pub fn get_chain_id(&self) -> u64 {
self.chain_id
.or_else(|| self.genesis.as_ref().map(|g| g.config.chain_id))
.unwrap_or(CHAIN_ID)
}
/// Sets the chain id and updates all wallets
pub fn set_chain_id(&mut self, chain_id: Option<impl Into<u64>>) {
self.chain_id = chain_id.map(Into::into);
let chain_id = self.get_chain_id();
self.genesis_accounts.iter_mut().for_each(|wallet| {
*wallet = wallet.clone().with_chain_id(Some(chain_id));
});
self.signer_accounts.iter_mut().for_each(|wallet| {
*wallet = wallet.clone().with_chain_id(Some(chain_id));
})
}
/// Sets the gas limit
#[must_use]
pub fn with_gas_limit(mut self, gas_limit: Option<u128>) -> Self {
if let Some(gas_limit) = gas_limit {
self.gas_limit = gas_limit;
}
self
}
/// Disable block gas limit check
///
/// If set to `true` block gas limit will not be enforced
#[must_use]
pub fn disable_block_gas_limit(mut self, disable_block_gas_limit: bool) -> Self {
self.disable_block_gas_limit = disable_block_gas_limit;
self
}
/// Sets the gas price
#[must_use]
pub fn with_gas_price(mut self, gas_price: Option<u128>) -> Self {
self.gas_price = gas_price;
self
}
/// Sets prune history status.
#[must_use]
pub fn set_pruned_history(mut self, prune_history: Option<Option<usize>>) -> Self {
self.prune_history = PruneStateHistoryConfig::from_args(prune_history);
self
}
/// Sets max number of blocks with transactions to keep in memory
#[must_use]
pub fn with_transaction_block_keeper<U: Into<usize>>(
mut self,
transaction_block_keeper: Option<U>,
) -> Self {
self.transaction_block_keeper = transaction_block_keeper.map(Into::into);
self
}
/// Sets the base fee
#[must_use]
pub fn with_base_fee(mut self, base_fee: Option<u128>) -> Self {
self.base_fee = base_fee;
self
}
/// Sets the init genesis (genesis.json)
#[must_use]
pub fn with_genesis(mut self, genesis: Option<Genesis>) -> Self {
self.genesis = genesis;
self
}
/// Returns the genesis timestamp to use
pub fn get_genesis_timestamp(&self) -> u64 {
self.genesis_timestamp
.or_else(|| self.genesis.as_ref().map(|g| g.timestamp))
.unwrap_or_else(|| duration_since_unix_epoch().as_secs())
}
/// Sets the genesis timestamp
#[must_use]
pub fn with_genesis_timestamp<U: Into<u64>>(mut self, timestamp: Option<U>) -> Self {
if let Some(timestamp) = timestamp {
self.genesis_timestamp = Some(timestamp.into());
}
self
}
/// Sets the hardfork
#[must_use]
pub fn with_hardfork(mut self, hardfork: Option<Hardfork>) -> Self {
self.hardfork = hardfork;
self
}
/// Sets the genesis accounts
#[must_use]
pub fn with_genesis_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
self.genesis_accounts = accounts;
self
}
/// Sets the signer accounts
#[must_use]
pub fn with_signer_accounts(mut self, accounts: Vec<PrivateKeySigner>) -> Self {
self.signer_accounts = accounts;
self
}
/// Sets both the genesis accounts and the signer accounts
/// so that `genesis_accounts == accounts`
#[must_use]
pub fn with_account_generator(mut self, generator: AccountGenerator) -> Self {
let accounts = generator.gen();
self.account_generator = Some(generator);
self.with_signer_accounts(accounts.clone()).with_genesis_accounts(accounts)
}
/// Sets the balance of the genesis accounts in the genesis block
#[must_use]
pub fn with_genesis_balance<U: Into<U256>>(mut self, balance: U) -> Self {
self.genesis_balance = balance.into();
self
}
/// Sets the block time to automine blocks
#[must_use]
pub fn with_blocktime<D: Into<Duration>>(mut self, block_time: Option<D>) -> Self {
self.block_time = block_time.map(Into::into);
self
}
/// If set to `true` auto mining will be disabled
#[must_use]
pub fn with_no_mining(mut self, no_mining: bool) -> Self {
self.no_mining = no_mining;
self
}
/// Sets the slots in an epoch
#[must_use]
pub fn with_slots_in_an_epoch(mut self, slots_in_an_epoch: u64) -> Self {
self.slots_in_an_epoch = slots_in_an_epoch;
self
}
/// Sets the port to use
#[must_use]
pub fn with_port(mut self, port: u16) -> Self {
self.port = port;
self
}
/// Makes the node silent to not emit anything on stdout
#[must_use]
pub fn silent(self) -> Self {
self.set_silent(true)
}
#[must_use]
pub fn set_silent(mut self, silent: bool) -> Self {
self.silent = silent;
self
}
/// Sets the ipc path to use
///
/// Note: this is a double Option for
/// - `None` -> no ipc
/// - `Some(None)` -> use default path
/// - `Some(Some(path))` -> use custom path
#[must_use]
pub fn with_ipc(mut self, ipc_path: Option<Option<String>>) -> Self {
self.ipc_path = ipc_path;
self
}
/// Sets the file path to write the Anvil node's config info to.
#[must_use]
pub fn set_config_out(mut self, config_out: Option<String>) -> Self {
self.config_out = config_out;
self
}
/// Makes the node silent to not emit anything on stdout
#[must_use]
pub fn no_storage_caching(self) -> Self {
self.with_storage_caching(true)
}
#[must_use]
pub fn with_storage_caching(mut self, storage_caching: bool) -> Self {
self.no_storage_caching = storage_caching;
self
}
/// Sets the `eth_rpc_url` to use when forking
#[must_use]
pub fn with_eth_rpc_url<U: Into<String>>(mut self, eth_rpc_url: Option<U>) -> Self {
self.eth_rpc_url = eth_rpc_url.map(Into::into);
self
}
/// Sets the `fork_choice` to use to fork off from based on a block number
#[must_use]
pub fn with_fork_block_number<U: Into<u64>>(self, fork_block_number: Option<U>) -> Self {
self.with_fork_choice(fork_block_number.map(Into::into))
}
/// Sets the `fork_choice` to use to fork off from based on a transaction hash
#[must_use]
pub fn with_fork_transaction_hash<U: Into<TxHash>>(
self,
fork_transaction_hash: Option<U>,
) -> Self {
self.with_fork_choice(fork_transaction_hash.map(Into::into))
}
/// Sets the `fork_choice` to use to fork off from
#[must_use]
pub fn with_fork_choice<U: Into<ForkChoice>>(mut self, fork_choice: Option<U>) -> Self {
self.fork_choice = fork_choice.map(Into::into);
self
}
/// Sets the `fork_chain_id` to use to fork off local cache from
#[must_use]
pub fn with_fork_chain_id(mut self, fork_chain_id: Option<U256>) -> Self {
self.fork_chain_id = fork_chain_id.map(Into::into);
self
}
/// Sets the `fork_headers` to use with `eth_rpc_url`
#[must_use]
pub fn with_fork_headers(mut self, headers: Vec<String>) -> Self {
self.fork_headers = headers;
self
}
/// Sets the `fork_request_timeout` to use for requests
#[must_use]
pub fn fork_request_timeout(mut self, fork_request_timeout: Option<Duration>) -> Self {
if let Some(fork_request_timeout) = fork_request_timeout {
self.fork_request_timeout = fork_request_timeout;
}
self
}
/// Sets the `fork_request_retries` to use for spurious networks
#[must_use]
pub fn fork_request_retries(mut self, fork_request_retries: Option<u32>) -> Self {
if let Some(fork_request_retries) = fork_request_retries {
self.fork_request_retries = fork_request_retries;
}
self
}
/// Sets the initial `fork_retry_backoff` for rate limits
#[must_use]
pub fn fork_retry_backoff(mut self, fork_retry_backoff: Option<Duration>) -> Self {
if let Some(fork_retry_backoff) = fork_retry_backoff {
self.fork_retry_backoff = fork_retry_backoff;
}
self
}
/// Sets the number of assumed available compute units per second
///
/// See also, <https://docs.alchemy.com/reference/compute-units#what-are-cups-compute-units-per-second>
#[must_use]
pub fn fork_compute_units_per_second(mut self, compute_units_per_second: Option<u64>) -> Self {
if let Some(compute_units_per_second) = compute_units_per_second {
self.compute_units_per_second = compute_units_per_second;
}
self
}
/// Sets whether to enable tracing
#[must_use]
pub fn with_tracing(mut self, enable_tracing: bool) -> Self {
self.enable_tracing = enable_tracing;
self
}
/// Sets whether to enable steps tracing
#[must_use]
pub fn with_steps_tracing(mut self, enable_steps_tracing: bool) -> Self {
self.enable_steps_tracing = enable_steps_tracing;
self
}
/// Sets whether to print `console.log` invocations to stdout.
#[must_use]
pub fn with_print_logs(mut self, print_logs: bool) -> Self {
self.print_logs = print_logs;
self
}
/// Sets whether to enable autoImpersonate
#[must_use]
pub fn with_auto_impersonate(mut self, enable_auto_impersonate: bool) -> Self {
self.enable_auto_impersonate = enable_auto_impersonate;
self
}
#[must_use]
pub fn with_server_config(mut self, config: ServerConfig) -> Self {
self.server_config = config;
self
}
/// Sets the host the server will listen on
#[must_use]
pub fn with_host(mut self, host: Vec<IpAddr>) -> Self {
self.host = if host.is_empty() { vec![IpAddr::V4(Ipv4Addr::LOCALHOST)] } else { host };
self
}
#[must_use]
pub fn with_transaction_order(mut self, transaction_order: TransactionOrder) -> Self {
self.transaction_order = transaction_order;
self
}
/// Returns the ipc path for the ipc endpoint if any
pub fn get_ipc_path(&self) -> Option<String> {
match &self.ipc_path {
Some(path) => path.clone().or_else(|| Some(DEFAULT_IPC_ENDPOINT.to_string())),
None => None,
}
}
/// Prints the config info
pub fn print(&self, fork: Option<&ClientFork>) {
if self.config_out.is_some() {
let config_out = self.config_out.as_deref().unwrap();
to_writer(
&File::create(config_out).expect("Unable to create anvil config description file"),
&self.as_json(fork),
)
.expect("Failed writing json");
}
if self.silent {
return;
}
println!("{}", self.as_string(fork))
}
/// Returns the path where the cache file should be stored
///
/// See also [ Config::foundry_block_cache_file()]
pub fn block_cache_path(&self, block: u64) -> Option<PathBuf> {
if self.no_storage_caching || self.eth_rpc_url.is_none() {
return None;
}
let chain_id = self.get_chain_id();
Config::foundry_block_cache_file(chain_id, block)
}
/// Sets whether to enable optimism support
#[must_use]
pub fn with_optimism(mut self, enable_optimism: bool) -> Self {
self.enable_optimism = enable_optimism;
self
}
/// Sets whether to disable the default create2 deployer
#[must_use]
pub fn with_disable_default_create2_deployer(mut self, yes: bool) -> Self {
self.disable_default_create2_deployer = yes;
self
}
/// Injects precompiles to `anvil`'s EVM.
#[must_use]
pub fn with_precompile_factory(mut self, factory: impl PrecompileFactory + 'static) -> Self {
self.precompile_factory = Some(Arc::new(factory));
self
}
/// Configures everything related to env, backend and database and returns the
/// [Backend](mem::Backend)
///
/// *Note*: only memory based backend for now
pub(crate) async fn setup(&mut self) -> mem::Backend {
// configure the revm environment
let mut cfg =
CfgEnvWithHandlerCfg::new_with_spec_id(CfgEnv::default(), self.get_hardfork().into());
cfg.chain_id = self.get_chain_id();
cfg.limit_contract_code_size = self.code_size_limit;
// EIP-3607 rejects transactions from senders with deployed code.
// If EIP-3607 is enabled it can cause issues during fuzz/invariant tests if the
// caller is a contract. So we disable the check by default.
cfg.disable_eip3607 = true;
cfg.disable_block_gas_limit = self.disable_block_gas_limit;
cfg.handler_cfg.is_optimism = self.enable_optimism;
if let Some(value) = self.memory_limit {
cfg.memory_limit = value;
}
let env = revm::primitives::Env {
cfg: cfg.cfg_env,
block: BlockEnv {
gas_limit: U256::from(self.gas_limit),
basefee: U256::from(self.get_base_fee()),
..Default::default()
},
tx: TxEnv { chain_id: self.get_chain_id().into(), ..Default::default() },
};
let mut env = EnvWithHandlerCfg::new(Box::new(env), cfg.handler_cfg);
let fees = FeeManager::new(
cfg.handler_cfg.spec_id,
self.get_base_fee(),
self.get_gas_price(),
self.get_blob_excess_gas_and_price(),
);
let (db, fork): (Arc<tokio::sync::RwLock<Box<dyn Db>>>, Option<ClientFork>) =
if let Some(eth_rpc_url) = self.eth_rpc_url.clone() {
self.setup_fork_db(eth_rpc_url, &mut env, &fees).await
} else {
(Arc::new(tokio::sync::RwLock::new(Box::<MemDb>::default())), None)
};
// if provided use all settings of `genesis.json`
if let Some(ref genesis) = self.genesis {
env.cfg.chain_id = genesis.config.chain_id;
env.block.timestamp = U256::from(genesis.timestamp);
if let Some(base_fee) = genesis.base_fee_per_gas {
env.block.basefee = U256::from(base_fee);
}
if let Some(number) = genesis.number {
env.block.number = U256::from(number);
}
env.block.coinbase = genesis.coinbase;
}
let genesis = GenesisConfig {
timestamp: self.get_genesis_timestamp(),
balance: self.genesis_balance,
accounts: self.genesis_accounts.iter().map(|acc| acc.address()).collect(),
fork_genesis_account_infos: Arc::new(Default::default()),
genesis_init: self.genesis.clone(),
};
// only memory based backend for now
let backend = mem::Backend::with_genesis(
db,
Arc::new(RwLock::new(env)),
genesis,
fees,
Arc::new(RwLock::new(fork)),
self.enable_steps_tracing,
self.print_logs,
self.prune_history,
self.transaction_block_keeper,
self.block_time,
Arc::new(tokio::sync::RwLock::new(self.clone())),
)
.await;
// Writes the default create2 deployer to the backend,
// if the option is not disabled and we are not forking.
if !self.disable_default_create2_deployer && self.eth_rpc_url.is_none() {
backend
.set_create2_deployer(DEFAULT_CREATE2_DEPLOYER)
.await
.expect("Failed to create default create2 deployer");
}
if let Some(state) = self.init_state.clone() {
backend.load_state(state).await.expect("Failed to load init state");
}
backend
}
/// Configures everything related to forking based on the passed `eth_rpc_url`:
/// - returning a tuple of a [ForkedDatabase] wrapped in an [Arc] [RwLock](tokio::sync::RwLock)
/// and [ClientFork] wrapped in an [Option] which can be used in a [Backend](mem::Backend) to
/// fork from.
/// - modifying some parameters of the passed `env`
/// - mutating some members of `self`
pub async fn setup_fork_db(
&mut self,
eth_rpc_url: String,
env: &mut EnvWithHandlerCfg,
fees: &FeeManager,
) -> (Arc<tokio::sync::RwLock<Box<dyn Db>>>, Option<ClientFork>) {
let (db, config) = self.setup_fork_db_config(eth_rpc_url, env, fees).await;
let db: Arc<tokio::sync::RwLock<Box<dyn Db>>> =