op-config 0.1.0

An extensible OP Stack configuration file
Documentation
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
use std::fmt::Display;
use std::marker::PhantomData;
use std::path::PathBuf;

use eyre::Result;
use figment::{
    providers::{Env, Serialized},
    value::{Dict, Map, Value},
    Figment, Metadata, Profile, Provider,
};
use serde::{Deserialize, Serialize};
use strum::IntoEnumIterator;
use tracing::trace;

use op_primitives::{ChallengerAgent, L1Client, L2Client, MonorepoConfig, RollupClient};

use crate::providers::{
    error::ExtractConfigError, optional::OptionalStrictProfileProvider,
    rename::RenameProfileProvider, toml::TomlFileProvider, wraps::WrapProfileProvider,
};
use crate::root::RootPath;

/// L1 node url.
pub const L1_URL: &str = "http://localhost:8545";

/// L1 node port.
pub const L1_PORT: u16 = 8545;

/// L2 node url.
pub const L2_URL: &str = "http://localhost:9545";

/// L2 node port.
pub const L2_PORT: u16 = 9545;

/// Rollup node url.
pub const ROLLUP_URL: &str = "http://localhost:7545";

/// Rollup node port.
pub const ROLLUP_PORT: u16 = 7545;

/// Testing deployer private key.
pub const DEPLOYER_PRIVATE_KEY: &str =
    "ac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80";

/// OP Stack Configuration
///
/// # Defaults
///
/// All configuration values have a default, documented in the [fields](#fields)
/// section below. [`Config::default()`] returns the default values for
/// the default profile while [`Config::with_root()`] returns the values based on the given
/// directory. [`Config::load()`] starts with the default profile and merges various providers into
/// the config, same for [`Config::load_with_root()`], but there the default values are determined
/// by [`Config::with_root()`]
///
/// # Provider Details
///
/// `Config` is a Figment [`Provider`] with the following characteristics:
///
///   * **Profile**
///
///     The profile is set to the value of the `profile` field.
///
///   * **Metadata**
///
///     This provider is named `OP Stack Config`. It does not specify a
///     [`Source`](figment::Source) and uses default interpolation.
///
///   * **Data**
///
///     The data emitted by this provider are the keys and values corresponding
///     to the fields and values of the structure. The dictionary is emitted to
///     the "default" meta-profile.
///
/// Note that these behaviors differ from those of [`Config::figment()`].
#[derive(Debug, Clone, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "kebab-case")]
pub struct Config<'a> {
    /// Phantom data to ensure that the lifetime `'a` is used.
    #[serde(skip)]
    _phantom: std::marker::PhantomData<&'a ()>,

    /// The selected profile. **(default: _default_ `default`)**
    ///
    /// **Note:** This field is never serialized nor deserialized. When a
    /// `Config` is merged into a `Figment` as a `Provider`, this profile is
    /// selected on the `Figment`. When a `Config` is extracted, this field is
    /// set to the extracting Figment's selected `Profile`.
    #[serde(skip)]
    pub profile: Profile,

    /// The path to the op stack artifact directory. **(default: _default_ `.stack`)**
    pub artifacts: PathBuf,

    /// The Optimism Monorepo configuration options.
    pub monorepo: MonorepoConfig,

    /// The type of L1 Client to use. **(default: _default_ `L1Client::Geth`)**
    pub l1_client: L1Client,
    /// The type of L2 Client to use. **(default: _default_ `L2Client::OpGeth`)**
    pub l2_client: L2Client,
    /// The type of Rollup Client to use. **(default: _default_ `RollupClient::OpNode`)**
    pub rollup_client: RollupClient,

    // todo: parse the urls properly as opposed to using strings
    /// The L1 Client base URL.
    pub l1_client_url: Option<String>,
    /// The L1 Client port.
    pub l1_client_port: Option<u16>,
    /// The L2 Client URL.
    pub l2_client_url: Option<String>,
    /// The L2 Client port.
    pub l2_client_port: Option<u16>,
    /// The rollup client URL.
    pub rollup_client_url: Option<String>,
    /// The rollup client port.
    pub rollup_client_port: Option<u16>,

    /// Deployer is the contract deployer.
    /// By default, this is a hardhat test account.
    pub deployer: Option<String>,

    /// The challenger agent to use. **(default: _default_ `ChallengerAgent::OpChallengerGo`)**
    pub challenger: ChallengerAgent,

    /// Enable Sequencing. **(default: _default_ `false`)**
    pub enable_sequencing: bool,
    /// Enable Fault Proofs. **(default: _default_ `false`)**
    pub enable_fault_proofs: bool,

    /// Stack Stage Components
    ///
    /// This is a table array of [StageConfig]s, each of which
    /// represents a stage in the stack and is orchestrated by the
    /// [StageManager].
    ///
    /// The parsing of [StageConfig]s is done by the [StageConfig::from_toml]
    /// function. This allows for different configuration formats to be used
    /// for each stage.
    // pub stages: Vec<StageProvider<'a>>,

    /// JWT secret that should be used for any rpc calls
    pub eth_rpc_jwt: Option<String>,

    /// The root path where the config detection started from, `Config::with_root`
    #[doc(hidden)]
    // Skip serialization here, so it won't be included in the [`Config::to_string()`]
    // representation, but will be deserialized from `Figment` so that commands can
    // override it.
    #[serde(rename = "root", default, skip_serializing)]
    pub __root: RootPath,
}

// impl<'a> Deserialize<'a> for Config<'a> {
//     fn deserialize<D: serde::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
//         let mut config: Config<'a> = serde::Deserialize::deserialize(deserializer)?;
//         config.__root = RootPath::default();
//         Ok(config)
//     }
// }

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

/// Macro to create a selection prompt.
#[macro_export]
macro_rules! make_selection {
    ($name:ident, $prompt:expr, $options:expr) => {
        let $name = inquire::Select::new($prompt, $options)
            .without_help_message()
            .prompt()?
            .to_string();
    };
}

impl Config<'_> {
    /// The default profile: "default"
    pub const DEFAULT_PROFILE: Profile = Profile::const_new("default");

    /// TOML section for profiles
    pub const PROFILE_SECTION: &'static str = "profile";

    /// File name of config toml file
    pub const FILE_NAME: &'static str = "stack.toml";

    /// The name of the directory rollup reserves for itself under the user's home directory: `~`
    pub const STACK_DIR_NAME: &'static str = ".stack";

    /// Standalone sections in the config which get integrated into the selected profile
    pub const STANDALONE_SECTIONS: &'static [&'static str] = &[];

    /// Returns the current `Config`
    ///
    /// See `Config::figment`
    #[track_caller]
    pub fn load() -> Self {
        Config::from_provider(Config::figment())
    }

    /// Returns the current `Config`
    ///
    /// See `Config::figment_with_root`
    #[track_caller]
    pub fn load_with_root(root: impl Into<PathBuf>) -> Self {
        Config::from_provider(Config::figment_with_root(root))
    }

    /// Extract a `Config` from `provider`, panicking if extraction fails.
    ///
    /// # Panics
    ///
    /// If extraction fails, prints an error message indicating the failure and
    /// panics. For a version that doesn't panic, use [`Config::try_from()`].
    ///
    /// # Example
    ///
    /// ```no_run
    /// use op_config::Config;
    /// use figment::providers::{Toml, Format, Env};
    ///
    /// // Use default `Figment`, but allow values from `other.toml`
    /// // to supersede its values.
    /// let figment = Config::figment()
    ///     .merge(Toml::file("other.toml").nested());
    ///
    /// let config = Config::from_provider(figment);
    /// ```
    #[track_caller]
    pub fn from_provider<T: Provider>(provider: T) -> Self {
        trace!("load config with provider: {:?}", provider.metadata());
        Self::try_from(provider).unwrap_or_else(|err| panic!("{}", err))
    }

    /// Attempts to build a `Config` using a [PathBuf] toml file.
    /// If the file does not exist, it will be created with default values.
    pub fn from_toml(path: impl Into<PathBuf>) -> Result<Self, ExtractConfigError> {
        let figment = Config::figment().merge(TomlFileProvider::new(None, path));
        Self::try_from(figment)
    }

    /// Attempts to extract a `Config` from `provider`, returning the result.
    ///
    /// # Example
    ///
    /// ```rust
    /// use op_config::Config;
    /// use figment::providers::{Toml, Format, Env};
    ///
    /// // Use default `Figment`, but allow values from `other.toml`
    /// // to supersede its values.
    /// let figment = Config::figment()
    ///     .merge(Toml::file("other.toml").nested());
    ///
    /// let config = Config::try_from(figment);
    /// ```
    pub fn try_from<T: Provider>(provider: T) -> Result<Self, ExtractConfigError> {
        let figment = Figment::from(provider);
        let mut config = figment.extract::<Self>().map_err(ExtractConfigError::new)?;
        config.profile = figment.profile().clone();
        Ok(config)
    }

    /// Returns the default figment
    ///
    /// The default figment reads from the following sources, in ascending
    /// priority order:
    ///
    ///   1. [`Config::default()`] (see [defaults](#defaults))
    ///   2. `stack.toml` _or_ filename in `OP_STACK_CONFIG` environment variable
    ///   3. `OP_STACK_` prefixed environment variables
    ///
    /// The profile selected is the value set in the `OP_STACK_PROFILE`
    /// environment variable. If it is not set, it defaults to `default`.
    ///
    /// # Example
    ///
    /// ```rust
    /// use op_config::Config;
    /// use serde::Deserialize;
    ///
    /// let my_config = Config::figment().extract::<Config>();
    /// ```
    pub fn figment() -> Figment {
        Config::default().into()
    }

    /// Returns the default figment enhanced with additional context extracted from the provided
    /// root, like remappings and directories.
    ///
    /// # Example
    ///
    /// ```rust
    /// use op_config::Config;
    /// use serde::Deserialize;
    ///
    /// let my_config = Config::figment_with_root(".").extract::<Config>();
    /// ```
    pub fn figment_with_root(root: impl Into<PathBuf>) -> Figment {
        Self::with_root(root).into()
    }

    /// Creates a new Config that adds additional context extracted from the provided root.
    ///
    /// # Example
    ///
    /// ```rust
    /// use op_config::Config;
    /// let my_config = Config::with_root(".");
    /// ```
    pub fn with_root(root: impl Into<PathBuf>) -> Self {
        Config {
            __root: RootPath(root.into()),
            ..Config::default()
        }
    }

    /// Creates the artifacts directory if it doesn't exist.
    pub fn create_artifacts_dir(&self) -> Result<()> {
        if !self.artifacts.exists() {
            std::fs::create_dir_all(&self.artifacts)?;
        }
        Ok(())
    }

    /// Returns the selected profile
    ///
    /// If the `STACK_PROFILE` env variable is not set, this returns the `DEFAULT_PROFILE`
    pub fn selected_profile() -> Profile {
        Profile::from_env_or("STACK_PROFILE", Config::DEFAULT_PROFILE)
    }

    /// Returns the path to the global toml file that's stored at `~/.stack/stack.toml`
    pub fn stack_dir_toml() -> Option<PathBuf> {
        Self::stack_dir().map(|p| p.join(Config::FILE_NAME))
    }

    /// Returns the path to the config dir `~/.stack/`
    pub fn stack_dir() -> Option<PathBuf> {
        dirs_next::home_dir().map(|p| p.join(Config::STACK_DIR_NAME))
    }

    /// Force monorepo artifact overwrites.
    pub fn force_overwrites(mut self, force: bool) -> Self {
        self.monorepo.force = force;
        self
    }

    /// Sets the l1 client to use via a cli prompt.
    pub fn set_l1_client(&mut self) -> Result<()> {
        make_selection!(
            l1_client,
            "Which L1 execution client would you like to use?",
            L1Client::iter().collect::<Vec<_>>()
        );
        self.l1_client = l1_client.parse()?;
        tracing::debug!(target: "stack", "Nice l1 client choice! You've got great taste ✨");
        Ok(())
    }

    /// Sets the l2 client to use via a cli prompt.
    pub fn set_l2_client(&mut self) -> Result<()> {
        make_selection!(
            l2_client,
            "Which L2 execution client would you like to use?",
            L2Client::iter().collect::<Vec<_>>()
        );
        self.l2_client = l2_client.parse()?;
        tracing::debug!(target: "stack", "Nice l2 client choice! You've got great taste ✨");
        Ok(())
    }

    /// Sets the rollup client to use via a cli prompt.
    pub fn set_rollup_client(&mut self) -> Result<()> {
        make_selection!(
            rollup_client,
            "Which rollup client would you like to use?",
            RollupClient::iter().collect::<Vec<_>>()
        );
        self.rollup_client = rollup_client.parse()?;
        tracing::debug!(target: "stack", "Nice rollup choice! You've got great taste ✨");
        Ok(())
    }

    /// Sets the challenger agent to use via a cli prompt.
    pub fn set_challenger(&mut self) -> Result<()> {
        make_selection!(
            challenger,
            "Which challenger agent would you like to use?",
            ChallengerAgent::iter().collect::<Vec<_>>()
        );
        self.challenger = challenger.parse()?;
        tracing::debug!(target: "stack", "Nice challenger choice! You've got great taste ✨");
        Ok(())
    }

    fn merge_toml_provider(
        mut figment: Figment,
        toml_provider: impl Provider,
        profile: Profile,
    ) -> Figment {
        figment = figment.select(profile.clone());

        // use [profile.<profile>] as [<profile>]
        let mut profiles = vec![Config::DEFAULT_PROFILE];
        if profile != Config::DEFAULT_PROFILE {
            profiles.push(profile.clone());
        }
        let provider = toml_provider; // toml_provider.strict_select(profiles);

        // merge the default profile as a base
        if profile != Config::DEFAULT_PROFILE {
            figment = figment.merge(provider.rename(Config::DEFAULT_PROFILE, profile.clone()));
        }

        // merge the profile
        figment = figment.merge(provider);
        figment
    }
}

impl Provider for Config<'_> {
    fn metadata(&self) -> Metadata {
        Metadata::named("OP Stack Config")
    }

    #[track_caller]
    fn data(&self) -> Result<Map<Profile, Dict>, figment::Error> {
        let mut data = Serialized::defaults(self).data()?;
        if let Some(entry) = data.get_mut(&self.profile) {
            entry.insert("root".to_string(), Value::serialize(self.__root.clone())?);
        }
        Ok(data)
    }

    fn profile(&self) -> Option<Profile> {
        Some(self.profile.clone())
    }
}

impl From<Config<'_>> for Figment {
    fn from(c: Config<'_>) -> Figment {
        let profile = Config::selected_profile();
        let mut figment = Figment::default();

        // merge global toml file
        if let Some(global_toml) = Config::stack_dir_toml().filter(|p| p.exists()) {
            figment = Config::merge_toml_provider(
                figment,
                TomlFileProvider::new(None, global_toml).cached(),
                profile.clone(),
            );
        }
        // merge local toml file
        figment = Config::merge_toml_provider(
            figment,
            TomlFileProvider::new(Some("OP_STACK_CONFIG"), c.__root.0.join(Config::FILE_NAME))
                .cached(),
            profile.clone(),
        );

        // merge environment variables
        figment = figment
            .merge(
                Env::prefixed("OP_STACK_")
                    .ignore(&[
                        "PROFILE",
                        "L1_CLIENT",
                        "L2_CLIENT",
                        "ROLLUP_CLIENT",
                        "CHALLENGER",
                    ])
                    .map(|key| {
                        let key = key.as_str();
                        if Config::STANDALONE_SECTIONS.iter().any(|section| {
                            key.starts_with(&format!("{}_", section.to_ascii_uppercase()))
                        }) {
                            key.replacen('_', ".", 1).into()
                        } else {
                            key.into()
                        }
                    })
                    .global(),
            )
            .select(profile.clone());

        Figment::from(c).merge(figment).select(profile)
    }
}

impl Default for Config<'_> {
    fn default() -> Self {
        Self {
            _phantom: PhantomData,
            profile: Self::DEFAULT_PROFILE,
            artifacts: PathBuf::from(Self::STACK_DIR_NAME),
            monorepo: MonorepoConfig::default(),
            l1_client: L1Client::default(),
            l2_client: L2Client::default(),
            l1_client_url: Some(L1_URL.to_string()),
            l1_client_port: Some(L1_PORT),
            l2_client_url: Some(L2_URL.to_string()),
            l2_client_port: Some(L2_PORT),
            deployer: Some(DEPLOYER_PRIVATE_KEY.to_string()),
            rollup_client_url: Some(ROLLUP_URL.to_string()),
            rollup_client_port: Some(ROLLUP_PORT),
            rollup_client: RollupClient::default(),
            challenger: ChallengerAgent::default(),
            enable_sequencing: false,
            enable_fault_proofs: false,
            // stages: vec![],
            eth_rpc_jwt: None,
            __root: RootPath::default(),
        }
    }
}

trait ProviderExt: Provider {
    fn rename(
        &self,
        from: impl Into<Profile>,
        to: impl Into<Profile>,
    ) -> RenameProfileProvider<&Self> {
        RenameProfileProvider::new(self, from, to)
    }

    fn wrap(
        &self,
        wrapping_key: impl Into<Profile>,
        profile: impl Into<Profile>,
    ) -> WrapProfileProvider<&Self> {
        WrapProfileProvider::new(self, wrapping_key, profile)
    }

    fn strict_select(
        &self,
        profiles: impl IntoIterator<Item = impl Into<Profile>>,
    ) -> OptionalStrictProfileProvider<&Self> {
        OptionalStrictProfileProvider::new(self, profiles)
    }
}
impl<P: Provider> ProviderExt for P {}