hylix 0.10.0

Build, test & deploy verifiable apps on Hyli
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
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
use anyhow::Context;
use serde::{Deserialize, Serialize};
use std::path::PathBuf;

use crate::logging::{log_error, log_info};

/// Default configuration version
fn default_config_version() -> String {
    "0.9.0".to_string()
}

/// Hylix configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct HylixConfig {
    /// Configuration schema version
    #[serde(default = "default_config_version")]
    pub version: String,
    /// Default backend type for new projects
    pub default_backend: BackendType,
    /// Default scaffold repository URL
    pub scaffold_repo: String,
    /// Local devnet configuration
    pub devnet: DevnetConfig,
    /// Build configuration
    pub build: BuildConfig,
    /// Bake profile configuration
    pub bake_profile: String,
    /// Testing configuration
    pub test: TestConfig,
    /// Run configuration
    pub run: RunConfig,
}

/// Testing configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct TestConfig {
    /// Print logs to console
    pub print_server_logs: bool,
    /// Clean data directory before running tests
    pub clean_server_data: bool,
}

/// Run configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct RunConfig {
    /// Clean data directory before running
    pub clean_server_data: bool,
    /// Server port
    pub server_port: u16,
}

/// Backend type enumeration
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, clap::ValueEnum)]
pub enum BackendType {
    Sp1,
    Risc0,
}

/// Devnet configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DevnetConfig {
    /// Custom image for the Hyli node and indexer
    pub node_image: String,
    /// Custom image for the wallet server
    pub wallet_server_image: String,
    /// Custom image for the wallet UI
    pub wallet_ui_image: String,
    /// Custom image for the registry server
    pub registry_server_image: String,
    /// Custom image for the registry UI
    pub registry_ui_image: String,
    /// Default port for the local node
    pub node_port: u16,
    /// Default port for the DA server
    pub da_port: u16,
    /// Default value for node'sRUST_LOG environment variable
    pub node_rust_log: String,
    /// Default port for the wallet app
    pub wallet_api_port: u16,
    /// Default port for the wallet WS
    pub wallet_ws_port: u16,
    /// Default port for the wallet UI
    pub wallet_ui_port: u16,
    /// Default port for the indexer
    pub indexer_port: u16,
    /// Default port for the postgres server
    pub postgres_port: u16,
    /// Default port for the registry server
    pub registry_server_port: u16,
    /// Default port for the registry UI
    pub registry_ui_port: u16,
    /// Auto-start devnet on test command
    pub auto_start: bool,
    /// Custom environment variables for containers
    pub container_env: ContainerEnvConfig,
}

/// Container environment variables configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ContainerEnvConfig {
    /// Custom environment variables for the node container
    pub node: Vec<String>,
    /// Custom environment variables for the indexer container
    pub indexer: Vec<String>,
    /// Custom environment variables for the wallet server container
    pub wallet_server: Vec<String>,
    /// Custom environment variables for the wallet UI container
    pub wallet_ui: Vec<String>,
    /// Custom environment variables for the postgres container
    pub postgres: Vec<String>,
    /// Custom environment variables for the registry server container
    pub registry_server: Vec<String>,
}

/// Build configuration
#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct BuildConfig {
    /// Build in release mode by default
    pub release: bool,
    /// Number of parallel build jobs
    pub jobs: Option<u32>,
    /// Additional cargo build flags
    pub extra_flags: Vec<String>,
}

/// Bake profile configuration
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct BakeProfile {
    /// Name of the profile
    pub name: String,
    /// Accounts to create
    pub accounts: Vec<AccountConfig>,
    /// Funds to send to accounts
    pub funds: Vec<FundConfig>,
}

/// Account configuration for baking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AccountConfig {
    /// Account name
    pub name: String,
    /// Account password
    pub password: String,
    /// Account type (e.g., "vip")
    pub invite_code: String,
}

/// Fund configuration for baking
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FundConfig {
    /// Source account name
    pub from: String,
    /// Source account password
    pub from_password: String,
    /// Amount to send
    pub amount: u64,
    /// Token type (e.g., "oranj", "oxygen")
    pub token: String,
    /// Destination account name
    pub to: String,
}

impl Default for HylixConfig {
    fn default() -> Self {
        Self {
            version: default_config_version(),
            default_backend: BackendType::Risc0,
            scaffold_repo: "https://github.com/hyli-org/app-scaffold".to_string(),
            devnet: DevnetConfig::default(),
            build: BuildConfig::default(),
            bake_profile: "bobalice".to_string(),
            test: TestConfig::default(),
            run: RunConfig::default(),
        }
    }
}

impl Default for DevnetConfig {
    fn default() -> Self {
        Self {
            node_image: "ghcr.io/hyli-org/hyli:latest".to_string(),
            wallet_server_image: "ghcr.io/hyli-org/wallet/wallet-server:main".to_string(),
            wallet_ui_image: "ghcr.io/hyli-org/wallet/wallet-ui:main".to_string(),
            registry_server_image: "ghcr.io/hyli-org/hyli-registry/zkvm-registry-server:latest"
                .to_string(),
            registry_ui_image: "ghcr.io/hyli-org/hyli-registry/zkvm-registry-ui:latest".to_string(),
            da_port: 4141,
            node_rust_log: "info".to_string(),
            node_port: 4321,
            indexer_port: 4322,
            postgres_port: 5432,
            wallet_ui_port: 8080,
            wallet_api_port: 4000,
            wallet_ws_port: 8081,
            registry_server_port: 9003,
            registry_ui_port: 8082,
            auto_start: true,
            container_env: ContainerEnvConfig::default(),
        }
    }
}

impl Default for TestConfig {
    fn default() -> Self {
        Self {
            print_server_logs: false,
            clean_server_data: true,
        }
    }
}

impl Default for RunConfig {
    fn default() -> Self {
        Self {
            clean_server_data: false,
            server_port: 9002,
        }
    }
}

impl HylixConfig {
    /// Load configuration from file or create default
    pub fn load() -> crate::error::HylixResult<Self> {
        let config_path = Self::config_path()?;

        if config_path.exists() {
            let content = std::fs::read_to_string(&config_path)?;

            // Parse as TOML value to check version
            let mut toml_value: toml::Value = toml::from_str(&content)
                .map_err(crate::error::HylixError::Toml)
                .with_context(|| {
                    format!("Failed to parse TOML from file {}", config_path.display())
                })?;

            // Check version and migrate if needed
            let file_version = toml_value
                .get("version")
                .and_then(|v| v.as_str())
                .unwrap_or("legacy")
                .to_string();

            let current_version = default_config_version();

            if file_version != current_version {
                log_info(&format!(
                    "Upgrading configuration from version '{file_version}' to '{current_version}'"
                ));

                // Backup the old config before migration
                Self::backup()?;

                // Migrate the TOML value
                toml_value = Self::migrate_toml(toml_value, file_version)?;

                // Write the migrated config back to file
                let migrated_content = toml::to_string_pretty(&toml_value)?;
                std::fs::write(&config_path, migrated_content)?;

                log_info("Configuration successfully upgraded and saved");
            }

            // Now parse the (possibly migrated) config
            let config: Self = toml::from_str(&toml::to_string(&toml_value)?)
                .map_err(crate::error::HylixError::Toml)
                .with_context(|| {
                    format!(
                        "Failed to load configuration from file {}",
                        config_path.display()
                    )
                })?;

            Ok(config)
        } else {
            let config = Self::default();
            config.save()?;
            log_info(&format!(
                "Created default configuration in file {}",
                config_path.display()
            ));
            Ok(config)
        }
    }

    /// Migrate TOML configuration from previous versions
    fn migrate_toml(
        toml_value: toml::Value,
        file_version: String,
    ) -> crate::error::HylixResult<toml::Value> {
        let migrations: Vec<Box<dyn ConfigMigration>> =
            vec![Box::new(LegacyMigration), Box::new(Migration0_6_0)];

        for migration in migrations {
            if migration.version() == file_version.as_str() {
                return migration.migrate(toml_value);
            }
        }

        log_error(&format!(
            "Unsupported configuration version: {file_version}"
        ));
        log_info("Failed to migrate configuration. Please check your configuration file.");
        log_info(&format!(
            "You can reset to default configuration by running `{}`",
            console::style("hy config reset").bold().green()
        ));
        Err(crate::error::HylixError::config(
            "Unsupported configuration version".to_string(),
        ))
    }
}

/// Strategy pattern for config migrations
trait ConfigMigration {
    fn version(&self) -> &str;
    fn migrate(&self, toml_value: toml::Value) -> crate::error::HylixResult<toml::Value>;
}

/// Migration from legacy configuration (no version field)
struct LegacyMigration;

impl ConfigMigration for LegacyMigration {
    fn version(&self) -> &str {
        "legacy"
    }

    fn migrate(&self, mut toml_value: toml::Value) -> crate::error::HylixResult<toml::Value> {
        log_info("Migrating from legacy configuration");
        let current_version = default_config_version();

        if let Some(table) = toml_value.as_table_mut() {
            // Add version field
            table.insert(
                "version".to_string(),
                toml::Value::String(current_version.clone()),
            );

            // Add node_rust_log field if devnet section exists
            if let Some(devnet) = table.get_mut("devnet") {
                if let Some(devnet_table) = devnet.as_table_mut() {
                    if !devnet_table.contains_key("node_rust_log") {
                        devnet_table.insert(
                            "node_rust_log".to_string(),
                            toml::Value::String("info".to_string()),
                        );
                    }
                }
            } else {
                log_error("Devnet section not found in configuration");
                log_info("Failed to migrate configuration. Please check your configuration file.");
                log_info(&format!(
                    "You can reset to default configuration by running `{}`",
                    console::style("hy config reset").bold().green()
                ));
                return Err(crate::error::HylixError::config(
                    "Devnet section not found in configuration".to_string(),
                ));
            }
        }

        Ok(toml_value)
    }
}

/// Migration from version 0.6.0 to 0.9.0
struct Migration0_6_0;

impl ConfigMigration for Migration0_6_0 {
    fn version(&self) -> &str {
        "0.6.0"
    }

    fn migrate(&self, mut toml_value: toml::Value) -> crate::error::HylixResult<toml::Value> {
        log_info("Migrating from configuration version 0.6.0 to 0.9.0");
        let current_version = default_config_version();

        if let Some(table) = toml_value.as_table_mut() {
            // Update version field
            table.insert(
                "version".to_string(),
                toml::Value::String(current_version.clone()),
            );

            // Add registry fields to devnet section
            if let Some(devnet) = table.get_mut("devnet") {
                if let Some(devnet_table) = devnet.as_table_mut() {
                    // Add registry_server_image if missing
                    if !devnet_table.contains_key("registry_server_image") {
                        devnet_table.insert(
                            "registry_server_image".to_string(),
                            toml::Value::String(
                                "ghcr.io/hyli-org/hyli-registry/zkvm-registry-server:latest"
                                    .to_string(),
                            ),
                        );
                    }
                    // Add registry_ui_image if missing
                    if !devnet_table.contains_key("registry_ui_image") {
                        devnet_table.insert(
                            "registry_ui_image".to_string(),
                            toml::Value::String(
                                "ghcr.io/hyli-org/hyli-registry/zkvm-registry-ui:latest"
                                    .to_string(),
                            ),
                        );
                    }
                    // Add registry_server_port if missing
                    if !devnet_table.contains_key("registry_server_port") {
                        devnet_table.insert(
                            "registry_server_port".to_string(),
                            toml::Value::Integer(9003),
                        );
                    }
                    // Add registry_ui_port if missing
                    if !devnet_table.contains_key("registry_ui_port") {
                        devnet_table
                            .insert("registry_ui_port".to_string(), toml::Value::Integer(8082));
                    }
                }
            }

            // Add registry_server to container_env if it exists
            if let Some(devnet) = table.get_mut("devnet") {
                if let Some(devnet_table) = devnet.as_table_mut() {
                    if let Some(container_env) = devnet_table.get_mut("container_env") {
                        if let Some(container_env_table) = container_env.as_table_mut() {
                            if !container_env_table.contains_key("registry_server") {
                                container_env_table.insert(
                                    "registry_server".to_string(),
                                    toml::Value::Array(vec![]),
                                );
                            }
                        }
                    }
                }
            }
        }

        Ok(toml_value)
    }
}

impl HylixConfig {
    /// Save configuration to file
    pub fn save(&self) -> crate::error::HylixResult<()> {
        let config_path = Self::config_path()?;
        let config_dir = config_path.parent().unwrap();

        std::fs::create_dir_all(config_dir)?;

        let content = toml::to_string_pretty(self)?;
        std::fs::write(&config_path, content)?;

        Ok(())
    }

    /// Backup configuration to file
    pub fn backup() -> crate::error::HylixResult<()> {
        let config_path = Self::config_path()?;
        let config_dir = config_path.parent().unwrap();
        let backup_path = config_dir.join(format!(
            "config.toml.{}.backup",
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_secs()
        ));
        std::fs::copy(&config_path, &backup_path)?;
        log_info(&format!(
            "Backed up configuration to {}",
            backup_path.display()
        ));
        Ok(())
    }

    /// Get the configuration file path
    fn config_path() -> crate::error::HylixResult<PathBuf> {
        let config_dir = dirs::config_dir()
            .ok_or_else(|| crate::error::HylixError::config("Could not find config directory"))?;

        Ok(config_dir.join("hylix").join("config.toml"))
    }

    /// Get the profiles directory path
    fn profiles_dir() -> crate::error::HylixResult<PathBuf> {
        let config_dir = dirs::config_dir()
            .ok_or_else(|| crate::error::HylixError::config("Could not find config directory"))?;

        Ok(config_dir.join("hylix").join("profiles"))
    }

    /// Load a bake profile by name
    pub fn load_bake_profile(&self, profile_name: &str) -> crate::error::HylixResult<BakeProfile> {
        let profiles_dir = Self::profiles_dir()?;
        let profile_path = profiles_dir.join(format!("{profile_name}.toml"));

        if !profile_path.exists() {
            return Err(crate::error::HylixError::config(format!(
                "Profile '{}' not found at {}",
                profile_name,
                profile_path.display()
            )));
        }

        let content = std::fs::read_to_string(&profile_path)?;
        let profile: BakeProfile = toml::from_str(&content)
            .map_err(crate::error::HylixError::Toml)
            .with_context(|| {
                format!(
                    "Failed to load profile from file {}",
                    profile_path.display()
                )
            })?;

        log_info(&format!(
            "Loaded profile '{}' from {}",
            profile_name,
            profile_path.display()
        ));

        Ok(profile)
    }

    /// Create default bobalice profile if it doesn't exist
    pub fn create_default_profile(&self) -> crate::error::HylixResult<()> {
        let profiles_dir = Self::profiles_dir()?;
        std::fs::create_dir_all(&profiles_dir)?;

        let profile_path = profiles_dir.join("bobalice.toml");

        if !profile_path.exists() {
            let default_profile = BakeProfile {
                name: "bobalice".to_string(),
                accounts: vec![
                    AccountConfig {
                        name: "bob".to_string(),
                        password: crate::constants::passwords::DEFAULT.to_string(),
                        invite_code: "vip".to_string(),
                    },
                    AccountConfig {
                        name: "alice".to_string(),
                        password: crate::constants::passwords::DEFAULT.to_string(),
                        invite_code: "vip".to_string(),
                    },
                ],
                funds: vec![
                    FundConfig {
                        from: "hyli".to_string(),
                        from_password: crate::constants::passwords::DEFAULT.to_string(),
                        amount: 1000,
                        token: "oranj".to_string(),
                        to: "bob".to_string(),
                    },
                    FundConfig {
                        from: "hyli".to_string(),
                        from_password: crate::constants::passwords::DEFAULT.to_string(),
                        amount: 1000,
                        token: "oranj".to_string(),
                        to: "alice".to_string(),
                    },
                    FundConfig {
                        from: "hyli".to_string(),
                        from_password: crate::constants::passwords::DEFAULT.to_string(),
                        amount: 500,
                        token: "oxygen".to_string(),
                        to: "bob".to_string(),
                    },
                    FundConfig {
                        from: "bob".to_string(),
                        from_password: crate::constants::passwords::DEFAULT.to_string(),
                        amount: 50,
                        token: "oxygen".to_string(),
                        to: "alice".to_string(),
                    },
                ],
            };

            let content = toml::to_string_pretty(&default_profile)?;
            std::fs::write(&profile_path, content)?;

            log_info(&format!(
                "Created default bobalice profile at {}",
                profile_path.display()
            ));
        }

        Ok(())
    }
}