miden-client-cli 0.17.0-rc.1

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
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
use std::collections::BTreeMap;
use std::fmt::Write as _;
use std::path::PathBuf;
use std::slice;

use clap::Parser;
use miden_client::account::AccountId;
use miden_client::assembly::CodeBuilder;
use miden_client::keystore::Keystore;
use miden_client::rpc::domain::account::AccountStorageRequirements;
use miden_client::transaction::{
    AdviceInputs,
    ForeignAccount,
    TransactionRequestBuilder,
    TransactionRequestError,
    TransactionScript,
    build_fpi_script,
};
use miden_client::vm::typed::TypedProcInfo;
use miden_client::vm::{
    ExecutionError,
    MIN_STACK_DEPTH,
    OperationError,
    PackageExport,
    PackageManifest,
    ProcedureExport,
    error_code_from_msg,
};
use miden_client::{Client, ClientError, Felt, TransactionExecutorError, Word};

use crate::advice_inputs::load_advice_map_from_file;
use crate::codecs::with_cli_codecs;
use crate::commands::account::DEFAULT_ACCOUNT_ID_KEY;
use crate::commands::new_account::load_packages;
use crate::config::CliConfig;
use crate::errors::CliError;
use crate::utils::{
    parse_account_id,
    print_executed_program_stack,
    print_executed_transaction,
    split_procedure_target,
};

// CALL COMMAND
// ================================================================================================

/// The transaction kernel's assertion message for a transaction that changes nothing.
///
/// The message is hashed into the error code the assertion carries, and compared against it. It
/// only decides whether an explanatory line is printed: if the kernel ever rewords it, the line
/// stops appearing and nothing else changes.
const EMPTY_TRANSACTION_ASSERTION: &str =
    "executed transaction neither changed the account state, nor consumed any notes";

#[derive(Debug, Clone, Parser)]
#[command(
    about = "Call a procedure on an account and display the result and state delta. Accounts \
             that aren't tracked locally are read from the network and the call is read-only."
)]
pub struct CallCmd {
    /// Account and procedure in the form `<ACCOUNT_ID>:<PROCEDURE>`.
    #[arg(
        value_name = "ACCOUNT_ID:PROCEDURE",
        long_help = "Account and procedure in the form `<ACCOUNT_ID>:<PROCEDURE>`.\n\n\
                     The procedure name is matched against the package's exports with `_` and `-` \
                     treated as equivalent, so it can be written in either snake_case or \
                     kebab-case (e.g. `get_count` matches the WIT export `get-count`)."
    )]
    target: String,

    /// Positional arguments to push onto the stack before calling the procedure.
    #[arg(value_name = "args")]
    args: Vec<String>,

    /// Path to the package (.masp) file containing the procedure. If omitted, `<PROCEDURE>` must be
    /// a hex digest and the output stack is shown as raw felts.
    #[arg(long, short)]
    package: Option<PathBuf>,

    /// Path to a TOML file with advice map entries, in the same format as the `exec` command.
    #[arg(long, short, long_help = crate::advice_inputs::INPUTS_PATH_LONG_HELP)]
    inputs_path: Option<PathBuf>,
}

impl CallCmd {
    pub async fn execute<AUTH: Keystore + Sync + 'static>(
        &self,
        client: Client<AUTH>,
    ) -> Result<(), CliError> {
        if client.get_sync_height().await? == 0.into() {
            return Err(CliError::NotSynced);
        }

        let cli_config = CliConfig::load()?;
        let (account_str, procedure) = split_procedure_target(&self.target);
        let procedure = procedure.ok_or_else(|| {
            CliError::InvalidArgument(format!(
                "Expected `<ACCOUNT_ID>:<PROCEDURE>`, got '{}'.",
                self.target
            ))
        })?;

        let target_id = parse_account_id(&client, account_str).await?;
        let call_code = self.resolve_call_code(&client, &cli_config, procedure)?;

        let advice_entries = match &self.inputs_path {
            Some(path) => load_advice_map_from_file(path)?,
            None => vec![],
        };

        let call_target = resolve_call_target(&client, target_id).await?;

        match call_target {
            CallTarget::Local(account_id) => {
                run_local_call(&client, account_id, call_code, advice_entries).await
            },
            CallTarget::Remote { target_id, executor_id, foreign_account } => {
                run_remote_call(
                    &client,
                    target_id,
                    executor_id,
                    foreign_account,
                    call_code,
                    advice_entries,
                )
                .await
            },
        }
    }

    /// Resolves the procedure digest, code builder and encoded arguments either from `--package`
    /// (calling by name) or from a hex digest when no package is given.
    fn resolve_call_code<AUTH: Keystore + Sync + 'static>(
        &self,
        client: &Client<AUTH>,
        cli_config: &CliConfig,
        procedure: &str,
    ) -> Result<CallCode, CliError> {
        let call_code = match &self.package {
            Some(pkg_path) => self.resolve_from_package(client, cli_config, pkg_path, procedure)?,
            None => self.resolve_from_digest(client, procedure)?,
        };

        // A procedure only sees the top MIN_STACK_DEPTH felts of the stack. An argument below that
        // reaches it as a zero and the call still succeeds, so without this check a procedure with
        // wide arguments would run on the wrong values.
        if call_code.args.len() > MIN_STACK_DEPTH {
            return Err(CliError::InvalidArgument(format!(
                "A procedure takes at most {MIN_STACK_DEPTH} input values; got {}.",
                call_code.args.len()
            )));
        }

        // The output stack only holds MIN_STACK_DEPTH felts.
        if let Some(n) = call_code.typed.as_ref().and_then(TypedProcInfo::output_felt_count)
            && n > MIN_STACK_DEPTH
        {
            return Err(CliError::InvalidArgument(format!(
                "Procedure '{procedure}' returns {n} values; only up to {MIN_STACK_DEPTH} \
                 can be read from the output stack."
            )));
        }

        Ok(call_code)
    }

    /// Resolves the call from the package's manifest, which names the procedure and, when it was
    /// built from a WIT interface, describes the types its arguments and results are encoded as.
    fn resolve_from_package<AUTH: Keystore + Sync + 'static>(
        &self,
        client: &Client<AUTH>,
        cli_config: &CliConfig,
        pkg_path: &PathBuf,
        procedure: &str,
    ) -> Result<CallCode, CliError> {
        let package = load_packages(cli_config, slice::from_ref(pkg_path))?
            .pop()
            .expect("load_packages returns one package per path");

        let export = resolve_procedure_export(&package.manifest, procedure)?;
        let digest = export.digest;
        // The signature prints under the name the package carries, not the one the user typed, so
        // `call increment_by` shows `increment-by(felt) -> felt`.
        let name = export.path.last().ok_or_else(|| {
            CliError::InvalidArgument(format!(
                "The export matching '{procedure}' has an empty path, so it names no procedure."
            ))
        })?;

        // Only a Component Model signature describes the values the user passes and reads; a
        // `C`-ABI or `Fast` one describes the lowering instead, which would encode the wrong thing.
        let typed = match export.signature.clone() {
            Some(signature) if signature.abi.is_wasm_canonical_abi() => {
                Some(with_cli_codecs(TypedProcInfo::new(name, signature)?))
            },
            _ => None,
        };

        let args = if let Some(typed) = &typed {
            println!("Signature: {typed}\n");
            // Checks the argument count as well, and names the procedure and both counts when it is
            // wrong, so there is nothing to check here first.
            typed.encode_args(&self.args)?
        } else {
            println!("Signature: {name}(...) [no type info]\n");
            println!(
                "Warning: the package does not describe the types of '{procedure}', so each \
                 argument is passed as one field element, the argument count is not checked, and \
                 the result is printed as a stack dump."
            );
            encode_raw_args(&self.args)?
        };

        // The account's code is loaded from the client's store at VM runtime, so the library
        // doesn't need to be embedded in the script. The assembler still needs it at compile time
        // to resolve `call.<digest>` to a known procedure — otherwise it emits a "phantom target"
        // warning. Dynamic linking provides that resolution without embedding the library bytes.
        let builder = client.code_builder().with_dynamically_linked_package(&package)?;
        Ok(CallCode { builder, digest, args, typed })
    }

    /// Resolves the call from a hex digest. Nothing describes the procedure, so each argument is
    /// one field element and the results are read back as raw stack felts.
    fn resolve_from_digest<AUTH: Keystore + Sync + 'static>(
        &self,
        client: &Client<AUTH>,
        procedure: &str,
    ) -> Result<CallCode, CliError> {
        let digest = Word::try_from(procedure).map_err(|_| {
            CliError::InvalidArgument(format!(
                "'{procedure}' is not a hex digest. Pass `--package <FILE>.masp` to \
                 call a procedure by name, or give its hex digest to call without a \
                 package."
            ))
        })?;
        println!(
            "No `--package` provided; output will be raw felts. Pass \
             `--package <FILE>.masp` for typed output."
        );

        Ok(CallCode {
            builder: client.code_builder(),
            digest,
            args: encode_raw_args(&self.args)?,
            typed: None,
        })
    }
}

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

/// Resolved call code: the linked builder, the procedure digest, the encoded arguments, and the
/// type information the arguments were encoded against, which the result is rendered with as well.
struct CallCode {
    builder: CodeBuilder,
    digest: Word,
    args: Vec<Felt>,
    typed: Option<TypedProcInfo>,
}

/// Prints the values the procedure returned, rendered as their declared types when the package
/// describes them and as raw stack felts otherwise.
fn print_call_result(output_stack: &[Felt; MIN_STACK_DEPTH], typed: Option<&TypedProcInfo>) {
    let Some(typed) = typed else {
        // Nothing says where the results end, so the dump runs to the last non-zero value.
        print_executed_program_stack(output_stack, None);
        return;
    };

    match typed.decode_result(output_stack.as_slice()) {
        // A procedure that returns nothing has no result to show.
        Ok(None) => {},
        Ok(Some(rendered)) => println!("Result: {rendered}"),
        Err(err) => {
            println!("The result is not a valid value of the procedure's return type: {err}");
            print_executed_program_stack(output_stack, typed.output_felt_count());
        },
    }
}

/// Runs a remote call via FPI. FPI cannot mutate the foreign account, so there is no state delta to
/// compute — only the read phase runs.
async fn run_remote_call<AUTH: Keystore + Sync + 'static>(
    client: &Client<AUTH>,
    target_id: AccountId,
    executor_id: AccountId,
    foreign_account: Box<ForeignAccount>,
    call_code: CallCode,
    advice_entries: Vec<(Word, Vec<Felt>)>,
) -> Result<(), CliError> {
    let CallCode { builder, digest, args, typed } = call_code;
    let tx_script =
        build_fpi_script(builder, target_id, digest, &args).map_err(|err| match err {
            TransactionRequestError::ForeignProcedureInputsTooLong { max, actual } => {
                CliError::InvalidArgument(format!(
                    "A call on an account read from the network takes at most {max} input felts; \
                     got {actual}"
                ))
            },
            other => {
                CliError::Transaction(other.into(), "Failed to build the call script".to_string())
            },
        })?;

    let output_stack = client
        .execute_program(
            executor_id,
            tx_script,
            AdviceInputs::default().with_map(advice_entries),
            BTreeMap::from([(target_id, *foreign_account)]),
        )
        .await?;

    print_call_result(&output_stack, typed.as_ref());

    println!("\nA call on an account read from the network can only read it; no state delta.");
    Ok(())
}

/// Runs a local call: a read phase for the return values, then a transaction for the state delta.
/// The account runs the call itself, so the procedure may mutate it.
async fn run_local_call<AUTH: Keystore + Sync + 'static>(
    client: &Client<AUTH>,
    account_id: AccountId,
    call_code: CallCode,
    advice_entries: Vec<(Word, Vec<Felt>)>,
) -> Result<(), CliError> {
    let CallCode { builder, digest, args, typed } = call_code;
    let tx_script = generate_tx_script(builder, &digest, &args)?;

    // 1) Read-only execution to get return values.
    let output_stack = client
        .execute_program(
            account_id,
            tx_script.clone(),
            AdviceInputs::default().with_map(advice_entries.clone()),
            BTreeMap::new(),
        )
        .await?;
    print_call_result(&output_stack, typed.as_ref());

    // 2) Transaction execution to get the state delta.
    let tx_request = TransactionRequestBuilder::new()
        .custom_script(tx_script)
        .extend_advice_map(advice_entries)
        .build()
        .map_err(|err| {
            CliError::Transaction(err.into(), "Failed to build transaction".to_string())
        })?;

    match client.execute_transaction(account_id, tx_request).await {
        Ok(tx_result) => {
            print_executed_transaction(client, tx_result.executed_transaction()).await?;
        },
        Err(e) => report_failed_delta(&e),
    }
    Ok(())
}

/// Resolved call target.
enum CallTarget {
    /// The account is tracked locally, so it runs the call itself and may be mutated by it.
    Local(AccountId),
    /// The account is read from the network and the call runs from a local account.
    Remote {
        target_id: AccountId,
        executor_id: AccountId,
        foreign_account: Box<ForeignAccount>,
    },
}

async fn resolve_call_target<AUTH: Keystore + Sync + 'static>(
    client: &Client<AUTH>,
    target_id: AccountId,
) -> Result<CallTarget, CliError> {
    if let Some((_, status)) = client.get_account_header(target_id).await? {
        // A locked account holds outdated state and is always private, so it can't be read from the
        // network either.
        if status.is_locked() {
            return Err(CliError::InvalidArgument(format!(
                "Account {target_id} is locked: its local state doesn't match the network's, so \
                 the call can't run on it."
            )));
        }

        return Ok(CallTarget::Local(target_id));
    }

    let foreign_account = ForeignAccount::public(target_id, AccountStorageRequirements::default())
        .map_err(|err| match err {
            TransactionRequestError::InvalidForeignAccountId(_) => {
                CliError::InvalidArgument(format!(
                    "Account {target_id} isn't tracked locally and its state isn't public, so it \
                     can't be read from the network."
                ))
            },
            other => CliError::InvalidArgument(format!(
                "Account {target_id} can't be read from the network: {other}"
            )),
        })?;

    let executor_id = pick_local_executor(client).await?;

    println!(
        "Account {target_id} isn't tracked locally; reading its state from the network and \
         running the call from your account {executor_id}."
    );

    Ok(CallTarget::Remote {
        target_id,
        executor_id,
        foreign_account: Box::new(foreign_account),
    })
}

/// Picks the local account the FPI call runs from, preferring the default account.
///
/// Any account works: the script calls the foreign procedure, not the native account's code. Locked
/// accounts are skipped because their local state doesn't match the node's.
async fn pick_local_executor<AUTH: Keystore + Sync + 'static>(
    client: &Client<AUTH>,
) -> Result<AccountId, CliError> {
    let default_id: Option<AccountId> =
        client.get_setting(DEFAULT_ACCOUNT_ID_KEY.to_string()).await?;
    if let Some(default_id) = default_id
        && let Some((_, status)) = client.get_account_header(default_id).await?
        && !status.is_locked()
    {
        return Ok(default_id);
    }

    let local_accounts = client.get_account_headers().await?;
    local_accounts
        .iter()
        .find(|(_, status)| !status.is_locked())
        .map(|(header, _)| header.id())
        .ok_or_else(|| {
            CliError::InvalidArgument(
                "Calling an account that isn't tracked locally needs one of your own accounts to \
                 run the call from, and none is usable. Create one with `miden-client new-wallet` \
                 and re-run."
                    .to_string(),
            )
        })
}

/// Finds the export `procedure_name` names, which carries both the digest to call and the signature
/// the arguments are encoded against.
///
/// The compiler writes two exports for the same Component Model procedure: one with its WIT
/// signature, `add-points(point, point) -> point`, and one lowered to the C ABI, `fn(felt, felt,
/// felt, felt) -> i32`. Arguments are encoded and results are rendered from the signature this
/// picks, so it has to be the WIT one. The lowered signature describes the ABI plumbing instead:
/// its parameters are the flattened felts, and its `i32` result is a pointer to the value rather
/// than the value.
fn resolve_procedure_export<'a>(
    manifest: &'a PackageManifest,
    procedure_name: &str,
) -> Result<&'a ProcedureExport, CliError> {
    // The user passes a bare name (e.g. `get_count`); match it against each export's name without
    // the module path. Export names may be kebab (Rust/WIT) or snake (hand-written MASM bare
    // identifiers), so compare with `_` and `-` treated as equal.
    let target = procedure_name.replace('_', "-");

    let mut available = Vec::new();
    let mut untyped = None;

    for export in manifest.exports() {
        let PackageExport::Procedure(proc) = export else {
            continue;
        };
        // Every procedure goes on the list, so a "not found" error shows the whole surface.
        available.push(format!("  {}", proc.path));

        if export.name().replace('_', "-") != target {
            continue;
        }
        // The same leaf name is exported both as a `C`-ABI lowering (for `exec`) and as the
        // `ComponentModel` export (the cross-context `call` target); pick the latter.
        if proc.signature.as_ref().is_some_and(|sig| sig.abi.is_wasm_canonical_abi()) {
            return Ok(proc);
        }
        // Any other match is the fallback: an export carrying no signature at all (hand-written
        // MASM), or one that describes a lowering rather than the values the caller passes (`Fast`,
        // `C`). Each of those is still callable with raw field elements. Keep the first one and go
        // on looking: the manifest is free to write the Component Model export after it, and that
        // one is worth more.
        untyped.get_or_insert(proc);
    }

    untyped.ok_or_else(|| {
        CliError::InvalidArgument(format!(
            "Procedure '{procedure_name}' not found. Available:\n{}",
            available.join("\n")
        ))
    })
}

/// Reports a transaction that did not execute, in place of the state delta it would have shown.
///
/// The read-only execution has already printed the result by this point, so this never fails the
/// command: the call itself succeeded, only its effects could not be reported.
fn report_failed_delta(error: &ClientError) {
    let is_empty_transaction = matches!(
        error,
        ClientError::TransactionExecutorError(
            TransactionExecutorError::TransactionProgramExecutionFailed(
                ExecutionError::OperationError {
                    err: OperationError::FailedAssertion { err_code, .. },
                    ..
                },
            ),
        ) if *err_code == error_code_from_msg(EMPTY_TRANSACTION_ASSERTION)
    );

    if is_empty_transaction {
        // A procedure that only reads, on an account whose components write nothing, leaves the
        // transaction with no effects at all, and the kernel refuses those. For a read-only call
        // that is the expected outcome rather than a fault, so it is reported instead of dumping
        // the assertion chain. The kernel rejects only when the account was left unchanged and
        // nothing was consumed, so that is all this can report; it says nothing about created
        // notes.
        println!();
        println!("The transaction was rejected because it had no effects:\n");
        println!("No notes were consumed.");
        println!();
        println!("Account Storage was not changed.");
        println!("Account Vault was not changed.");
        println!("Account nonce was not changed.");
        return;
    }

    let mut report = String::new();
    let mut cause = std::error::Error::source(error);
    while let Some(err) = cause {
        writeln!(report, "  caused by: {err}").unwrap();
        cause = err.source();
    }

    println!("\n(Could not compute state delta: {error})");
    print!("{report}");
}

/// Parses `args` as one field element each, for a procedure whose types the package does not
/// describe.
///
/// A value is written the way a `felt` is written on the typed path: in decimal. The untyped path
/// is the fallback, so accepting more than the typed one would teach a syntax that stops working as
/// soon as the procedure gains a signature.
fn encode_raw_args(args: &[String]) -> Result<Vec<Felt>, CliError> {
    args.iter()
        .map(|arg| {
            let value: u64 = arg.parse().map_err(|_| {
                CliError::InvalidArgument(format!("Invalid argument '{arg}'. Expected a felt."))
            })?;
            Felt::try_from(value).map_err(|_| {
                CliError::InvalidArgument(format!("Argument '{arg}' is too large for a felt."))
            })
        })
        .collect()
}

/// Builds a transaction script that pushes `args` and calls the procedure at `digest`.
///
/// Only the top results are read back, and `truncate_stack` restores the 16-element exit invariant,
/// so anything left below the results can stay there.
fn generate_tx_script(
    code_builder: CodeBuilder,
    digest: &Word,
    args: &[Felt],
) -> Result<TransactionScript, CliError> {
    let mut script = String::from("use miden::core::sys\n\n@transaction_script\npub proc main\n");

    // Push args in reverse so the first arg ends up on top.
    for arg in args.iter().rev() {
        writeln!(script, "    push.{arg}").unwrap();
    }

    writeln!(script, "    call.{}", digest.to_hex()).unwrap();

    script.push_str("    exec.sys::truncate_stack\n");
    script.push_str("end\n");
    Ok(code_builder.compile_tx_script(&script)?)
}

// TESTS
// ================================================================================================

#[cfg(test)]
mod tests {
    use std::sync::Arc;

    use miden_mast_package::PathBuf;
    use midenc_hir_type::{CallConv, FunctionType, Type};

    use super::*;

    /// A manifest exporting every `(path, signature)` pair. Resolution matches on the path and
    /// reads the signature, so the digest is left zero.
    fn manifest_with_exports(exports: &[(&str, Option<FunctionType>)]) -> PackageManifest {
        let exports = exports.iter().map(|(path, signature)| {
            let path: Arc<_> = path.parse::<PathBuf>().expect("path should parse").into();
            PackageExport::Procedure(ProcedureExport::new(
                path,
                None,
                Word::default(),
                signature.clone(),
            ))
        });

        PackageManifest::new(exports).expect("manifest should be valid")
    }

    /// The interface form of a Component Model export. It keeps the WIT types.
    fn interface_form() -> (&'static str, Option<FunctionType>) {
        (
            "::\"miden:counter/counter@0.1.0\"::\"increment-by\"",
            Some(FunctionType::new(CallConv::ComponentModel, [Type::Felt], [Type::Felt])),
        )
    }

    /// The lowered form of the same export. The C ABI flattens the types and returns the big value
    /// by reference: an `i32` pointer, not the value.
    fn lowered_form() -> (&'static str, Option<FunctionType>) {
        (
            "::\"miden:counter/counter@0.1.0\"::cc::\"miden:counter/counter@0.1.0#increment-by\"",
            Some(FunctionType::new(CallConv::C, [Type::Felt], [Type::I32])),
        )
    }

    #[test]
    fn the_interface_form_wins_over_the_lowered_one() {
        // The compiler is free to write the two exports in either order, so neither may decide it.
        for exports in [[interface_form(), lowered_form()], [lowered_form(), interface_form()]] {
            let manifest = manifest_with_exports(&exports);

            let export = resolve_procedure_export(&manifest, "increment-by").unwrap();
            assert_eq!(export.signature, interface_form().1);
        }
    }

    #[test]
    fn a_lowered_name_is_not_reachable_by_the_bare_procedure_name() {
        // The last part of the lowered path holds the whole interface, so it never equals the plain
        // name. Were it found, its `i32` return would be printed as a value.
        let manifest = manifest_with_exports(&[lowered_form()]);

        // The message itself is pinned by `an_unknown_procedure_lists_the_whole_export_surface`.
        assert!(resolve_procedure_export(&manifest, "increment-by").is_err());
    }

    #[test]
    fn an_underscore_query_finds_a_kebab_export() {
        let manifest = manifest_with_exports(&[interface_form(), lowered_form()]);

        let export = resolve_procedure_export(&manifest, "increment_by").unwrap();
        assert_eq!(export.signature, interface_form().1);
    }

    #[test]
    fn an_unknown_procedure_lists_the_whole_export_surface() {
        let manifest = manifest_with_exports(&[interface_form(), lowered_form()]);

        let err = resolve_procedure_export(&manifest, "no-such-proc").unwrap_err();
        assert_eq!(
            err.to_string(),
            "invalid argument: Procedure 'no-such-proc' not found. Available:\n  \
             ::\"miden:counter/counter@0.1.0\"::\"increment-by\"\n  \
             ::\"miden:counter/counter@0.1.0\"::cc::\"miden:counter/counter@0.1.0#increment-by\""
        );
    }

    #[test]
    fn an_untyped_export_is_resolved_but_never_shadows_the_component_model_one() {
        // Every export that is not the Component Model one takes the fallback path, whether it
        // carries no signature at all (hand-written MASM) or one describing a lowering. Each is
        // still callable with raw field elements, so it resolves on its own, and each must lose to
        // the Component Model export in whichever order the manifest writes the two.
        let untyped_forms = [
            ("::mix::\"increment-by\"", None),
            ("::mix::increment_by", Some(FunctionType::new(CallConv::Fast, [], [Type::U32]))),
        ];

        for untyped in untyped_forms {
            let manifest = manifest_with_exports(slice::from_ref(&untyped));
            let export = resolve_procedure_export(&manifest, "increment-by").unwrap();
            assert_eq!(export.signature, untyped.1, "{} did not resolve alone", untyped.0);

            for exports in
                [[untyped.clone(), interface_form()], [interface_form(), untyped.clone()]]
            {
                let manifest = manifest_with_exports(&exports);
                let export = resolve_procedure_export(&manifest, "increment-by").unwrap();
                assert_eq!(export.signature, interface_form().1, "{} won", untyped.0);
            }
        }
    }

    /// The Goldilocks field modulus, `2^64 - 2^32 + 1`. The first value with no felt of its own.
    const FIELD_MODULUS: u64 = 18_446_744_069_414_584_321;

    #[test]
    fn raw_arguments_are_read_as_decimal_felts() {
        let args = ["0", "10", (FIELD_MODULUS - 1).to_string().as_str()].map(String::from);

        let encoded = encode_raw_args(&args).unwrap();

        let expected = [0, 10, FIELD_MODULUS - 1].map(|v| Felt::new(v).unwrap());
        assert_eq!(encoded, expected);
    }

    #[test]
    fn a_raw_argument_that_is_not_a_decimal_felt_is_rejected() {
        let cases = [
            // What an unchecked `u64` argument would silently wrap around to.
            (
                FIELD_MODULUS.to_string(),
                format!("invalid argument: Argument '{FIELD_MODULUS}' is too large for a felt."),
            ),
            // The typed path writes a `felt` in decimal and reserves `0x` for wider values, so the
            // untyped path cannot take hex either: it would work only until the procedure is given
            // a signature.
            (
                "0xff".to_string(),
                "invalid argument: Invalid argument '0xff'. Expected a felt.".to_string(),
            ),
        ];

        for (arg, expected) in cases {
            let err = encode_raw_args(slice::from_ref(&arg)).unwrap_err();

            assert_eq!(err.to_string(), expected, "argument '{arg}'");
        }
    }
}