miden-client-cli 0.14.4

The official command line client for interacting with the Miden network
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
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
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fs::{self, File};
use std::io::{Read, Write};
use std::path::PathBuf;

use clap::{Parser, ValueEnum};
use miden_client::Client;
use miden_client::account::component::{
    AccountComponent,
    AccountComponentMetadata,
    AuthControlled,
    BasicFungibleFaucet,
    InitStorageData,
    MIDEN_PACKAGE_EXTENSION,
    StorageSlotSchema,
};
use miden_client::account::{Account, AccountBuilder, AccountStorageMode, AccountType};
use miden_client::auth::{AuthSchemeId, AuthSecretKey, AuthSingleSig};
use miden_client::keystore::Keystore;
use miden_client::transaction::TransactionRequestBuilder;
use miden_client::utils::Deserializable;
use miden_client::vm::{Package, SectionId};
use rand::RngCore;
use tracing::debug;

use crate::commands::account::set_default_account_if_unset;
use crate::config::CliConfig;
use crate::errors::CliError;
use crate::{CliKeyStore, client_binary_name};

// CLI TYPES
// ================================================================================================

/// Mirror enum for [`AccountStorageMode`] that enables parsing for CLI commands.
#[derive(Debug, Clone, Copy, ValueEnum)]
pub enum CliAccountStorageMode {
    Private,
    Public,
}

impl From<CliAccountStorageMode> for AccountStorageMode {
    fn from(cli_mode: CliAccountStorageMode) -> Self {
        match cli_mode {
            CliAccountStorageMode::Private => AccountStorageMode::Private,
            CliAccountStorageMode::Public => AccountStorageMode::Public,
        }
    }
}

/// Mirror enum for [`AccountType`] that enables parsing for CLI commands.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, ValueEnum)]
pub enum CliAccountType {
    FungibleFaucet,
    NonFungibleFaucet,
    RegularAccountImmutableCode,
    RegularAccountUpdatableCode,
}

impl From<CliAccountType> for AccountType {
    fn from(cli_type: CliAccountType) -> Self {
        match cli_type {
            CliAccountType::FungibleFaucet => AccountType::FungibleFaucet,
            CliAccountType::NonFungibleFaucet => AccountType::NonFungibleFaucet,
            CliAccountType::RegularAccountImmutableCode => AccountType::RegularAccountImmutableCode,
            CliAccountType::RegularAccountUpdatableCode => AccountType::RegularAccountUpdatableCode,
        }
    }
}

// NEW WALLET
// ================================================================================================

/// Creates a new wallet account and store it locally.
///
/// A wallet account exposes functionality to sign transactions and
/// manage asset transfers. Additionally, more component templates can be added by specifying
/// a list of component template files.
#[derive(Debug, Parser, Clone)]
pub struct NewWalletCmd {
    /// Storage mode of the account.
    #[arg(value_enum, short, long, default_value_t = CliAccountStorageMode::Private)]
    pub storage_mode: CliAccountStorageMode,
    /// Defines if the account code is mutable (by default it isn't mutable).
    #[arg(short, long)]
    pub mutable: bool,
    /// Optional list of paths specifying additional components in the form of
    /// packages to add to the account.
    #[arg(short, long)]
    pub extra_packages: Vec<PathBuf>,
    /// Optional file path to a TOML file containing a list of key/values used for initializing
    /// storage. Each of these keys should map to the templated storage values within the passed
    /// list of component templates. The user will be prompted to provide values for any keys not
    /// present in the init storage data file.
    #[arg(short, long)]
    pub init_storage_data_path: Option<PathBuf>,
    /// If set, the newly created wallet will be deployed to the network by submitting an
    /// authentication transaction.
    #[arg(long, default_value_t = false)]
    pub deploy: bool,
    /// Seed local-only state so the wallet can be created and used for execution without a node.
    /// Only available when built with the `testing` feature.
    #[cfg_attr(
        feature = "testing",
        arg(long, default_value_t = false, conflicts_with = "deploy")
    )]
    #[cfg_attr(not(feature = "testing"), arg(skip = false))]
    pub offline: bool,
}

impl NewWalletCmd {
    pub async fn execute<AUTH: Keystore + Sync + 'static>(
        &self,
        mut client: Client<AUTH>,
        keystore: CliKeyStore,
    ) -> Result<(), CliError> {
        let package_paths: Vec<PathBuf> = [PathBuf::from("basic-wallet")]
            .into_iter()
            .chain(self.extra_packages.clone())
            .collect();

        // Choose account type based on mutability.
        let account_type = if self.mutable {
            AccountType::RegularAccountUpdatableCode
        } else {
            AccountType::RegularAccountImmutableCode
        };

        let new_account = create_client_account(
            &mut client,
            &keystore,
            account_type,
            self.storage_mode.into(),
            &package_paths,
            self.init_storage_data_path.clone(),
            self.deploy,
            self.offline,
        )
        .await?;

        println!("Successfully created new wallet.");
        println!(
            "To view account details execute {} account -s {}",
            client_binary_name().display(),
            new_account.id().to_hex()
        );

        set_default_account_if_unset(&mut client, new_account.id()).await?;

        Ok(())
    }
}

// NEW ACCOUNT
// ================================================================================================

/// Creates a new account and saves it locally.
///
/// An account may comprise one or more components, each with its own storage and distinct
/// functionality.
///
/// # Authentication Components
///
/// If a package with an authentication component is provided via `-p`, it will be used for
/// the account. Otherwise, a default `RpoFalcon512` authentication component will be added
/// automatically.
///
/// Each account can only have one authentication component. If multiple packages contain
/// authentication components, an error will be returned. By default, authentication-related
/// packages are located in the `auth` subdir in your packages directory.
///
/// # Examples
///
/// Create an account with default Falcon auth:
/// ```bash
/// miden-client new-account --account-type regular-account-immutable-code -p basic-wallet
/// ```
///
/// Create an account with a custom auth component (e.g., NoAuth):
/// ```bash
/// miden-client new-account --account-type regular-account-immutable-code -p auth/no-auth -p basic-wallet
/// ```
#[derive(Debug, Parser, Clone)]
pub struct NewAccountCmd {
    /// Storage mode of the account.
    #[arg(value_enum, short, long, default_value_t = CliAccountStorageMode::Private)]
    pub storage_mode: CliAccountStorageMode,
    /// Account type to create.
    #[arg(long, value_enum)]
    pub account_type: CliAccountType,
    /// List of files specifying package files used to create account components for the
    /// account.
    #[arg(short, long)]
    pub packages: Vec<PathBuf>,
    /// Optional file path to a TOML file containing a list of key/values used for initializing
    /// storage. Each of these keys should map to the templated storage values within the passed
    /// list of component templates. The user will be prompted to provide values for any keys not
    /// present in the init storage data file.
    #[arg(short, long)]
    pub init_storage_data_path: Option<PathBuf>,
    /// If set, the newly created account will be deployed to the network by submitting an
    /// authentication transaction.
    #[arg(long, default_value_t = false)]
    pub deploy: bool,
    /// Seed local-only state so the account can be created and used for execution without a node.
    /// Only available when built with the `testing` feature.
    #[cfg_attr(
        feature = "testing",
        arg(long, default_value_t = false, conflicts_with = "deploy")
    )]
    #[cfg_attr(not(feature = "testing"), arg(skip = false))]
    pub offline: bool,
}

impl NewAccountCmd {
    pub async fn execute<AUTH: Keystore + Sync + 'static>(
        &self,
        mut client: Client<AUTH>,
        keystore: CliKeyStore,
    ) -> Result<(), CliError> {
        let new_account = create_client_account(
            &mut client,
            &keystore,
            self.account_type.into(),
            self.storage_mode.into(),
            &self.packages,
            self.init_storage_data_path.clone(),
            self.deploy,
            self.offline,
        )
        .await?;

        println!("Successfully created new account.");
        println!(
            "To view account details execute {} account -s {}",
            client_binary_name().display(),
            new_account.id().to_hex()
        );

        Ok(())
    }
}

// HELPERS
// ================================================================================================

/// Reads [[`miden_core::vm::Package`]]s from the given file paths.
fn load_packages(
    cli_config: &CliConfig,
    package_paths: &[PathBuf],
) -> Result<Vec<Package>, CliError> {
    let mut packages = Vec::with_capacity(package_paths.len());

    let packages_dir = &cli_config.package_directory;
    for path in package_paths {
        // If a user passes in a file with the `.masp` file extension, then we
        // leave the path as is; since it probably is a full path (this is the
        // case with cargo-miden for instance).
        let path = match path.extension() {
            None => {
                let path = path.with_extension(MIDEN_PACKAGE_EXTENSION);
                Ok(packages_dir.join(path))
            },
            Some(extension) => {
                if extension == OsStr::new(MIDEN_PACKAGE_EXTENSION) {
                    Ok(path.clone())
                } else {
                    let error = std::io::Error::new(
                        std::io::ErrorKind::InvalidFilename,
                        format!(
                            "{} has an invalid file extension: '{}'. \
                            Expected: {MIDEN_PACKAGE_EXTENSION}",
                            path.display(),
                            extension.display()
                        ),
                    );
                    Err(CliError::AccountComponentError(
                        Box::new(error),
                        format!("refuesed to read {}", path.display()),
                    ))
                }
            },
        }?;

        let bytes = fs::read(&path).map_err(|e| {
            CliError::AccountComponentError(
                Box::new(e),
                format!("failed to read Package file from {}", path.display()),
            )
        })?;

        let package = Package::read_from_bytes(&bytes).map_err(|e| {
            CliError::AccountComponentError(
                Box::new(e),
                format!("failed to deserialize Package in {}", path.display()),
            )
        })?;

        packages.push(package);
    }

    Ok(packages)
}

/// Loads the initialization storage data from an optional TOML file.
/// If None is passed, an empty object is returned.
fn load_init_storage_data(path: Option<&PathBuf>) -> Result<InitStorageData, CliError> {
    if let Some(path) = &path {
        let mut contents = String::new();
        File::open(path)
            .and_then(|mut f| f.read_to_string(&mut contents))
            .map_err(|err| {
                CliError::InitDataError(
                    Box::new(err),
                    format!("Failed to open init data  file {}", path.display()),
                )
            })?;

        InitStorageData::from_toml(&contents).map_err(|err| {
            CliError::InitDataError(
                Box::new(err),
                format!("Failed to deserialize init data from file {}", path.display()),
            )
        })
    } else {
        Ok(InitStorageData::default())
    }
}

/// Separates account components into auth and regular components.
///
/// Returns a tuple of (`auth_component`, `regular_components`).
/// Returns an error if multiple auth components are found.
fn separate_auth_components(
    components: Vec<AccountComponent>,
) -> Result<(Option<AccountComponent>, Vec<AccountComponent>), CliError> {
    let mut auth_component: Option<AccountComponent> = None;
    let mut regular_components = Vec::new();

    for component in components {
        let auth_proc_count = component.procedures().filter(|(_, is_auth)| *is_auth).count();

        match auth_proc_count {
            0 => regular_components.push(component),
            1 => {
                if auth_component.is_some() {
                    return Err(CliError::InvalidArgument(
                        "Multiple auth components found in packages. Only one auth component is allowed per account.".to_string()
                    ));
                }
                auth_component = Some(component);
            },
            _ => {
                return Err(CliError::InvalidArgument(
                    "Component has multiple auth procedures. Only one auth procedure is allowed per component.".to_string()
                ));
            },
        }
    }

    Ok((auth_component, regular_components))
}

/// Returns `true` when the CLI should inject `AuthControlled::allow_all()` for a
/// fungible faucet account built from package components.
///
/// Why this exists:
/// - RC fungible faucets require a mint policy manager component in addition to
///   `BasicFungibleFaucet`.
/// - The CLI's built-in `basic-fungible-faucet` package only contributes the faucet component
///   itself; it does not include `AuthControlled`.
/// - Other faucet creation paths in this repo add `AuthControlled::allow_all()` explicitly, so the
///   CLI adds it implicitly here to preserve the same behavior and keep the old UX working.
///
/// What it does:
/// - only applies to `AccountType::FungibleFaucet`,
/// - only triggers when `BasicFungibleFaucet` is present,
/// - and skips injection if an `AuthControlled` component is already present so user-provided mint
///   policy components are not duplicated or overridden.
fn should_add_implicit_auth_controlled(
    account_type: AccountType,
    regular_components: &[AccountComponent],
) -> bool {
    let has_basic_fungible_faucet = regular_components
        .iter()
        .any(|component| component.metadata().name() == BasicFungibleFaucet::NAME);
    let has_auth_controlled = regular_components
        .iter()
        .any(|component| component.metadata().name() == AuthControlled::NAME);

    account_type == AccountType::FungibleFaucet && has_basic_fungible_faucet && !has_auth_controlled
}

/// Helper function to create the seed, initialize the account builder, add the given components,
/// and build the account.
///
/// If no auth component is detected in the packages, a Falcon-based auth component will be added.
async fn create_client_account<AUTH: Keystore + Sync + 'static>(
    client: &mut Client<AUTH>,
    keystore: &CliKeyStore,
    account_type: AccountType,
    storage_mode: AccountStorageMode,
    package_paths: &[PathBuf],
    init_storage_data_path: Option<PathBuf>,
    deploy: bool,
    offline: bool,
) -> Result<Account, CliError> {
    if package_paths.is_empty() {
        return Err(CliError::InvalidArgument(format!(
            "Account must contain at least one component. To provide one, pass a package with the -p flag, like so:
{} -p <package_name>
            ", client_binary_name().display())));
    }

    // Load the component templates and initialization storage data.

    let cli_config = CliConfig::load()?;
    debug!("Loading packages...");
    let packages = load_packages(&cli_config, package_paths)?;
    debug!("Loaded {} packages", packages.len());
    debug!("Loading initialization storage data...");
    let init_storage_data = load_init_storage_data(init_storage_data_path.as_ref())?;
    debug!("Loaded initialization storage data");

    let mut init_seed = [0u8; 32];
    client.rng().fill_bytes(&mut init_seed);

    let mut builder = AccountBuilder::new(init_seed)
        .account_type(account_type)
        .storage_mode(storage_mode);

    // Process packages and separate auth components from regular components
    let account_components = process_packages(packages, &init_storage_data)?;
    let (auth_component, mut regular_components) = separate_auth_components(account_components)?;

    // Faucet accounts require a mint policy manager component. The CLI's standard
    // `basic-fungible-faucet` package only provides the faucet component itself, so add the
    // default `allow_all` policy manager implicitly.
    if should_add_implicit_auth_controlled(account_type, &regular_components) {
        debug!("Adding implicit AuthControlled mint policy component for fungible faucet");
        regular_components.push(AuthControlled::allow_all().into());
    }

    // Add the auth component (either from packages or default Falcon)
    let key_pair = if let Some(auth_component) = auth_component {
        debug!("Adding auth component from package");
        builder = builder.with_auth_component(auth_component);
        None
    } else {
        debug!("Adding default Falcon auth component");
        let kp = AuthSecretKey::new_falcon512_poseidon2_with_rng(client.rng());
        builder = builder.with_auth_component(AuthSingleSig::new(
            kp.public_key().to_commitment(),
            AuthSchemeId::Falcon512Poseidon2,
        ));
        Some(kp)
    };

    // Add all regular (non-auth) components
    for component in regular_components {
        builder = builder.with_component(component);
    }

    let account = builder
        .build()
        .map_err(|err| CliError::Account(err, "failed to build account".into()))?;

    // Only add the key to the keystore if we generated a default key type (Falcon)
    if let Some(key_pair) = key_pair {
        // Use the Keystore trait method which handles both key storage and account association
        keystore.add_key(&key_pair, account.id()).await.map_err(CliError::KeyStore)?;
        println!("Generated and stored Falcon512 authentication key in keystore.");
    } else {
        println!("Using custom authentication component from package (no key generated).");
    }

    let _ = offline;

    #[cfg(feature = "testing")]
    if offline {
        client.prepare_offline_bootstrap().await?;
        println!("Offline mode seeded default RPC limits and a synthetic genesis header.");
    }

    client.add_account(&account, false).await?;

    if deploy {
        deploy_account(client, &account).await?;
    }

    Ok(account)
}

/// Submits a deploy transaction to the node for the specified account.
async fn deploy_account<AUTH: Keystore + Sync + 'static>(
    client: &mut Client<AUTH>,
    account: &Account,
) -> Result<(), CliError> {
    // Build a minimal transaction request. The transaction execution will naturally increment
    // the account nonce from 0 to 1, which deploys the account on-chain.
    // We don't need to call auth procedures directly as that must be done in the epilogue.
    let tx_request = TransactionRequestBuilder::new().build().map_err(|err| {
        CliError::Transaction(err.into(), "Failed to build deploy transaction".to_string())
    })?;

    client.submit_new_transaction(account.id(), tx_request).await?;
    Ok(())
}

fn process_packages(
    packages: Vec<Package>,
    init_storage_data: &InitStorageData,
) -> Result<Vec<AccountComponent>, CliError> {
    let mut account_components = Vec::with_capacity(packages.len());

    for package in packages {
        let mut value_entries = init_storage_data.values().clone();
        let mut map_entries = BTreeMap::new();

        let Some(component_metadata_section) = package.sections.iter().find(|section| {
            section.id.as_str() == (SectionId::ACCOUNT_COMPONENT_METADATA).as_str()
        }) else {
            continue;
        };

        let component_metadata = AccountComponentMetadata::read_from_bytes(
            &component_metadata_section.data,
        )
        .map_err(|err| {
            CliError::AccountComponentError(
                Box::new(err),
                format!(
                    "Failed to deserialize Account Component Metadata from package {}",
                    package.name
                ),
            )
        })?;

        // Preserve any provided map entries for map slots.
        for (slot_name, schema) in component_metadata.storage_schema().iter() {
            if matches!(schema, StorageSlotSchema::Map(_))
                && let Some(entries) = init_storage_data.map_entries(slot_name)
            {
                map_entries.insert(slot_name.clone(), entries.clone());
            }
        }

        for (value_name, requirement) in component_metadata.schema_requirements() {
            if value_entries.contains_key(&value_name) {
                // The user provided it through the TOML file, so we can skip it
                continue;
            }

            if let Some(default_value) = &requirement.default_value {
                // Use the schema's default value without prompting the user
                value_entries.insert(value_name, default_value.clone().into());
                continue;
            }

            let description = requirement.description.unwrap_or("[No description]".into());
            println!(
                "Enter value for '{value_name}' - {description} (type: {}): ",
                requirement.r#type
            );
            std::io::stdout().flush()?;

            let mut input_value = String::new();
            std::io::stdin().read_line(&mut input_value)?;
            let input_value = input_value.trim();
            value_entries.insert(value_name, input_value.to_string().into());
        }

        let init_data = InitStorageData::new(value_entries, map_entries).map_err(|e| {
            CliError::AccountComponentError(
                Box::new(e),
                format!("error creating InitStorageData for Package {}", package.name),
            )
        })?;
        let account_component =
            AccountComponent::from_package(&package, &init_data).map_err(|e| {
                CliError::Account(
                    e,
                    format!("error instantiating component from Package {}", package.name),
                )
            })?;

        account_components.push(account_component);
    }

    Ok(account_components)
}

#[cfg(test)]
mod tests {
    use miden_client::Felt;
    use miden_client::account::component::BasicWallet;
    use miden_client::asset::TokenSymbol;

    use super::*;

    #[test]
    fn implicit_auth_controlled_is_added_for_basic_faucet_accounts() {
        let regular_components = vec![
            BasicFungibleFaucet::new(TokenSymbol::new("BTC").unwrap(), 10, Felt::new(1_000_000))
                .unwrap()
                .into(),
        ];

        assert!(should_add_implicit_auth_controlled(
            AccountType::FungibleFaucet,
            &regular_components
        ));
    }

    #[test]
    fn implicit_auth_controlled_is_skipped_when_component_already_present() {
        let regular_components = vec![
            BasicFungibleFaucet::new(TokenSymbol::new("BTC").unwrap(), 10, Felt::new(1_000_000))
                .unwrap()
                .into(),
            AuthControlled::allow_all().into(),
        ];

        assert!(!should_add_implicit_auth_controlled(
            AccountType::FungibleFaucet,
            &regular_components
        ));
    }

    #[test]
    fn implicit_auth_controlled_is_not_added_for_non_faucet_accounts() {
        let regular_components = vec![AccountComponent::from(BasicWallet)];

        assert!(!should_add_implicit_auth_controlled(
            AccountType::RegularAccountImmutableCode,
            &regular_components
        ));
    }
}