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
use std::{env, fs::read_to_string, path::PathBuf};

use cache::CacheConfig;
use cli::{CacheType, Cli, DevSystemContracts};
use gas::GasConfig;
use log::LogConfig;
use node::{InMemoryNodeConfig, ShowCalls, ShowGasDetails};
use serde::Deserialize;

use crate::system_contracts;

pub mod cli;

pub const CONFIG_DIR: &str = ".era_test_node";
pub const CONFIG_FILE_NAME: &str = "config.toml";

/// Defines the configuration parameters for the [InMemoryNode].
#[derive(Deserialize, Default, Debug, Clone)]
pub struct TestNodeConfig {
    pub node: InMemoryNodeConfig,
    // The values to be used when calculating gas.
    pub gas: Option<GasConfig>,
    // Logging configuration.
    pub log: LogConfig,
    // Caching configuration.
    pub cache: CacheConfig,
}

impl TestNodeConfig {
    /// Try to load a configuration file from either a provided path or the `$HOME` directory.
    pub fn try_load(file_path: &Option<String>) -> eyre::Result<TestNodeConfig> {
        let path = if let Some(path) = file_path {
            PathBuf::from(path)
        } else {
            // NOTE: `env::home_dir` is not compatible with Windows.
            #[allow(deprecated)]
            let mut path = env::home_dir().expect("failed to get home directory");

            path.push(CONFIG_DIR);
            path.push(CONFIG_FILE_NAME);
            path
        };

        let toml = read_to_string(path)?;
        let config = toml::from_str(&toml)?;

        Ok(config)
    }

    /// Override the config with values provided by [`Cli`].
    pub fn override_with_opts(&mut self, opt: &Cli) {
        // [`NodeConfig`].
        if let Some(port) = &opt.port {
            self.node.port = *port;
        }

        if opt.debug_mode {
            self.node.show_calls = ShowCalls::All;
            self.node.show_outputs = true;
            self.node.show_gas_details = ShowGasDetails::All;
            self.node.resolve_hashes = true;
        }
        if let Some(show_calls) = &opt.show_calls {
            self.node.show_calls = *show_calls;
        }
        if let Some(show_outputs) = &opt.show_outputs {
            self.node.show_outputs = *show_outputs;
        }
        if let Some(show_storage_logs) = &opt.show_storage_logs {
            self.node.show_storage_logs = *show_storage_logs;
        }
        if let Some(show_vm_details) = &opt.show_vm_details {
            self.node.show_vm_details = *show_vm_details;
        }
        if let Some(show_gas_details) = &opt.show_gas_details {
            self.node.show_gas_details = *show_gas_details;
        }
        if let Some(resolve_hashes) = &opt.resolve_hashes {
            self.node.resolve_hashes = *resolve_hashes;
        }

        if let Some(contract_options) = &opt.dev_system_contracts {
            self.node.system_contracts_options = match contract_options {
                DevSystemContracts::BuiltIn => system_contracts::Options::BuiltIn,
                DevSystemContracts::BuiltInNoVerify => {
                    system_contracts::Options::BuiltInWithoutSecurity
                }
                DevSystemContracts::Local => system_contracts::Options::Local,
            };
        }

        // [`GasConfig`]
        if let Some(l1_gas_price) = &opt.l1_gas_price {
            let mut gas = self.gas.unwrap_or_default();
            gas.l1_gas_price = Some(*l1_gas_price);
            self.gas = Some(gas);
        }
        if let Some(l2_gas_price) = &opt.l2_gas_price {
            let mut gas = self.gas.unwrap_or_default();
            gas.l2_gas_price = Some(*l2_gas_price);
            self.gas = Some(gas);
        }

        // [`LogConfig`].
        if let Some(log_level) = &opt.log {
            self.log.level = *log_level;
        }
        if let Some(file_path) = &opt.log_file_path {
            self.log.file_path = file_path.to_string();
        }

        // [`CacheConfig`].
        if let Some(cache_type) = &opt.cache {
            self.cache = match cache_type {
                CacheType::None => CacheConfig::None,
                CacheType::Memory => CacheConfig::Memory,
                CacheType::Disk => CacheConfig::Disk {
                    dir: opt.cache_dir.clone().expect("missing --cache-dir argument"),
                    reset: opt.reset_cache.unwrap_or_default(),
                },
            };
        }
    }
}

pub mod node {
    use clap::Parser;
    use serde::Deserialize;
    use std::{fmt::Display, str::FromStr};

    use crate::system_contracts;

    #[derive(Deserialize, Debug, Copy, Clone)]
    pub struct InMemoryNodeConfig {
        pub port: u16,
        pub show_calls: ShowCalls,
        pub show_outputs: bool,
        pub show_storage_logs: ShowStorageLogs,
        pub show_vm_details: ShowVMDetails,
        pub show_gas_details: ShowGasDetails,
        pub resolve_hashes: bool,
        pub system_contracts_options: system_contracts::Options,
    }

    impl Default for InMemoryNodeConfig {
        fn default() -> Self {
            Self {
                port: 8011,
                show_calls: Default::default(),
                show_outputs: Default::default(),
                show_storage_logs: Default::default(),
                show_vm_details: Default::default(),
                show_gas_details: Default::default(),
                resolve_hashes: Default::default(),
                system_contracts_options: Default::default(),
            }
        }
    }

    #[derive(
        Deserialize, Debug, Default, clap::Parser, Copy, Clone, clap::ValueEnum, PartialEq, Eq,
    )]
    pub enum ShowCalls {
        #[default]
        None,
        User,
        System,
        All,
    }

    impl FromStr for ShowCalls {
        type Err = String;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s.to_lowercase().as_ref() {
                "none" => Ok(ShowCalls::None),
                "user" => Ok(ShowCalls::User),
                "system" => Ok(ShowCalls::System),
                "all" => Ok(ShowCalls::All),
                _ => Err(format!(
                    "Unknown ShowCalls value {} - expected one of none|user|system|all.",
                    s
                )),
            }
        }
    }

    impl Display for ShowCalls {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{:?}", self)
        }
    }

    #[derive(Deserialize, Debug, Default, Parser, Copy, Clone, clap::ValueEnum, PartialEq, Eq)]
    pub enum ShowStorageLogs {
        #[default]
        None,
        Read,
        Write,
        Paid,
        All,
    }

    impl FromStr for ShowStorageLogs {
        type Err = String;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s.to_lowercase().as_ref() {
                "none" => Ok(ShowStorageLogs::None),
                "read" => Ok(ShowStorageLogs::Read),
                "write" => Ok(ShowStorageLogs::Write),
                "paid" => Ok(ShowStorageLogs::Paid),
                "all" => Ok(ShowStorageLogs::All),
                _ => Err(format!(
                    "Unknown ShowStorageLogs value {} - expected one of none|read|write|paid|all.",
                    s
                )),
            }
        }
    }

    impl Display for ShowStorageLogs {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{:?}", self)
        }
    }

    #[derive(Deserialize, Debug, Default, Parser, Copy, Clone, clap::ValueEnum, PartialEq, Eq)]
    pub enum ShowVMDetails {
        #[default]
        None,
        All,
    }

    impl FromStr for ShowVMDetails {
        type Err = String;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s.to_lowercase().as_ref() {
                "none" => Ok(ShowVMDetails::None),
                "all" => Ok(ShowVMDetails::All),
                _ => Err(format!(
                    "Unknown ShowVMDetails value {} - expected one of none|all.",
                    s
                )),
            }
        }
    }

    impl Display for ShowVMDetails {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{:?}", self)
        }
    }

    #[derive(Deserialize, Debug, Default, Parser, Copy, Clone, clap::ValueEnum, PartialEq, Eq)]
    pub enum ShowGasDetails {
        #[default]
        None,
        All,
    }

    impl FromStr for ShowGasDetails {
        type Err = String;

        fn from_str(s: &str) -> Result<Self, Self::Err> {
            match s.to_lowercase().as_ref() {
                "none" => Ok(ShowGasDetails::None),
                "all" => Ok(ShowGasDetails::All),
                _ => Err(format!(
                    "Unknown ShowGasDetails value {} - expected one of none|all.",
                    s
                )),
            }
        }
    }

    impl Display for ShowGasDetails {
        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
            write!(f, "{:?}", self)
        }
    }
}

pub mod gas {
    use serde::Deserialize;

    /// L1 Gas Price.
    pub const DEFAULT_L1_GAS_PRICE: u64 = 50_000_000_000;
    // TODO: for now, that's fine, as computation overhead is set to zero, but we may consider using calculated fee input everywhere.
    /// The default L2 Gas Price to be used if not supplied via the CLI argument.
    pub const DEFAULT_L2_GAS_PRICE: u64 = 25_000_000;
    // Default fair pubdata price based on an average from Sepolia Testnet blocks
    pub const DEFAULT_FAIR_PUBDATA_PRICE: u64 = 450_000_000_000;
    /// L1 Gas Price Scale Factor for gas estimation.
    pub const DEFAULT_ESTIMATE_GAS_PRICE_SCALE_FACTOR: f64 = 1.5;
    /// The factor by which to scale the gasLimit.
    pub const DEFAULT_ESTIMATE_GAS_SCALE_FACTOR: f32 = 1.3;

    #[derive(Deserialize, Debug, Default, Copy, Clone)]
    pub struct GasConfig {
        /// L1 gas price.
        pub l1_gas_price: Option<u64>,
        /// L2 gas price.
        pub l2_gas_price: Option<u64>,
        /// Factors used in estimating gas.
        pub estimation: Option<Estimation>,
    }

    #[derive(Deserialize, Debug, Default, Copy, Clone)]
    pub struct Estimation {
        /// L1 gas price scale factor for gas estimation.
        pub price_scale_factor: Option<f64>,
        /// The factor by which to scale the gasLimit.
        pub limit_scale_factor: Option<f32>,
    }
}

pub mod log {
    use serde::Deserialize;

    use crate::observability::LogLevel;

    pub const DEFAULT_LOG_FILE_PATH: &str = "era_test_node.log";

    #[derive(Deserialize, Debug, Clone)]
    pub struct LogConfig {
        pub level: LogLevel,
        pub file_path: String,
    }

    impl Default for LogConfig {
        fn default() -> Self {
            Self {
                level: Default::default(),
                file_path: String::from(DEFAULT_LOG_FILE_PATH),
            }
        }
    }
}

pub mod cache {
    use serde::Deserialize;

    pub const DEFAULT_DISK_CACHE_DIR: &str = ".cache";

    /// Cache configuration. Can be one of:
    ///
    /// None    : Caching is disabled
    /// Memory  : Caching is provided in-memory and not persisted across runs
    /// Disk    : Caching is persisted on disk in the provided directory and can be reset
    #[derive(Deserialize, Debug, Clone)]
    pub enum CacheConfig {
        #[serde(rename = "none")]
        None,
        #[serde(rename = "memory")]
        Memory,
        #[serde(rename = "disk")]
        Disk { dir: String, reset: bool },
    }

    impl Default for CacheConfig {
        fn default() -> Self {
            Self::Disk {
                dir: String::from(DEFAULT_DISK_CACHE_DIR),
                reset: false,
            }
        }
    }
}