leo-lang 4.4.1

The Leo programming language
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
// Copyright (C) 2019-2026 Provable Inc.
// This file is part of the Leo library.

// The Leo library is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.

// The Leo library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.

// You should have received a copy of the GNU General Public License
// along with the Leo library. If not, see <https://www.gnu.org/licenses/>.

use super::*;

use leo_ast::{AleoProgram, DiGraph, DiGraphError, NetworkName};
use leo_errors::LeoError;

use snarkvm::{
    prelude::{CanaryV0, MainnetV0, Network, Process as SvmProcess, TestnetV0},
    synthesizer::program::Program as SvmProgram,
};

use indexmap::IndexMap;
use std::{
    collections::HashMap,
    path::{Path, PathBuf},
    str::FromStr,
};

/// Generate ABI from an Aleo bytecode file.
#[derive(Parser, Debug)]
pub struct LeoAbi {
    /// Path to the .aleo file.
    #[clap(value_name = "FILE")]
    file: PathBuf,

    /// Network for parsing (mainnet, testnet, canary).
    #[clap(long, short, default_value = "testnet")]
    network: NetworkName,

    /// Without `--satisfies`, the output directory: writes `<PATH>/<program>.abi.json` for the input and for each
    /// declared dependency (created if missing; existing files overwritten); when omitted, every ABI is printed to
    /// stdout, separated by `=== <name> ===` headers. With `--satisfies`, the file path to write the JSON
    /// compatibility report to instead of printing a human-readable one.
    #[clap(long, short, value_name = "PATH")]
    output: Option<PathBuf>,

    /// Directory containing the program's `.aleo` imports. Two layouts are supported:
    /// per-unit (`<DIR>/<name>/<name>.aleo`) and legacy flat (`<DIR>/<name>.aleo`).
    /// Defaults to the parent's parent when the input is at `<root>/<unit>/<unit>.aleo`,
    /// otherwise a sibling `imports/` directory next to the input.
    #[clap(long, value_name = "DIR")]
    imports_dir: Option<PathBuf>,

    /// Check whether the input program satisfies an interface standard, instead of printing its
    /// ABI. The standard is a JSON file containing an ABI. The input satisfies the standard when
    /// the standard's public interface is a subset of the input's. Exits non-zero when it does
    /// not. With `--output`, the report is written there as JSON.
    #[clap(long, value_name = "FILE")]
    satisfies: Option<PathBuf>,
}

impl Command for LeoAbi {
    type Input = ();
    type Output = ();

    fn log_span(&self) -> Span {
        tracing::span!(tracing::Level::INFO, "Leo")
    }

    fn prelude(&self, _: Context) -> Result<Self::Input> {
        Ok(())
    }

    fn apply(self, _context: Context, _: Self::Input) -> Result<Self::Output> {
        if !self.file.exists() {
            return Err(crate::errors::cli_invalid_input(format!("File not found: {}", self.file.display())).into());
        }

        match self.file.extension().and_then(|s| s.to_str()) {
            Some("aleo") => {}
            _ => {
                return Err(crate::errors::cli_invalid_input(format!(
                    "Expected a .aleo file, got: {}",
                    self.file.display()
                ))
                .into());
            }
        }

        let content = std::fs::read_to_string(&self.file).map_err(crate::errors::cli_io_error)?;
        let file_name = self.file.file_name().and_then(|s| s.to_str()).unwrap_or("unknown");

        let imports_dir = self.imports_dir.clone().or_else(|| {
            let parent = self.file.parent()?;
            // Per-unit layout: file at `<root>/<unit>/<unit>.aleo` — use `<root>`.
            if parent.file_name() == self.file.file_stem() {
                return parent.parent().map(Path::to_path_buf);
            }
            // Legacy: sibling `imports/`.
            let legacy = parent.join("imports");
            legacy.is_dir().then_some(legacy)
        });

        // `Process::add_program` is contextual, so dependencies must be loaded in topological order before the main
        // program.
        let (main_aleo, dep_aleos) = match &imports_dir {
            Some(dir) => disassemble_with_imports(file_name, &content, self.network, dir)?,
            None => (
                leo_disassembler::disassemble_from_str_for_network(file_name, &content, self.network)
                    .map_err(|e| crate::errors::failed_to_parse_aleo_file(file_name, e))?,
                Vec::new(),
            ),
        };

        let main_abi = leo_abi::aleo::generate(&main_aleo);

        // Satisfies mode: check the input's interface against a JSON ABI standard rather than printing its ABI.
        if let Some(standard) = &self.satisfies {
            let standard_abi = load_standard_abi(standard)?;
            let problems = leo_abi::compatibility::check_compatibility(&main_abi, &standard_abi);
            return report_compatibility(&problems, &main_abi.program, &standard_abi.program, self.output.as_deref());
        }

        let dep_abis: IndexMap<String, _> =
            dep_aleos.into_iter().map(|(name, aleo)| (name, leo_abi::aleo::generate(&aleo))).collect();

        match self.output {
            Some(dir) => write_abis_to_directory(&dir, &main_abi, &dep_abis)?,
            None => print_abis_to_stdout(&main_abi, &dep_abis)?,
        }

        Ok(())
    }
}

/// Loads the ABI of an interface standard for the satisfies check from a JSON file (any `.json`
/// file), parsed directly as a serialized [`leo_abi::Program`].
fn load_standard_abi(path: &Path) -> Result<leo_abi::Program> {
    if !path.exists() {
        return Err(crate::errors::cli_invalid_input(format!("File not found: {}", path.display())).into());
    }
    match path.extension().and_then(|s| s.to_str()) {
        Some("json") => {
            let text = std::fs::read_to_string(path).map_err(crate::errors::cli_io_error)?;
            serde_json::from_str(&text).map_err(|e| {
                crate::errors::cli_invalid_input(format!("could not parse ABI JSON `{}`: {e}", path.display())).into()
            })
        }
        _ => Err(crate::errors::cli_invalid_input(format!(
            "Expected a JSON file containing an ABI for `--satisfies`, got: {}",
            path.display()
        ))
        .into()),
    }
}

/// Reports the satisfies `problems` (empty means satisfied) and returns a `not_compatible` error
/// when there are any, so the command exits non-zero. With `output`, writes a JSON report to that
/// file; otherwise prints a human-readable report to stdout.
fn report_compatibility(problems: &[String], program: &str, standard: &str, output: Option<&Path>) -> Result<()> {
    if let Some(path) = output {
        let value = serde_json::json!({ "satisfied": problems.is_empty(), "problems": problems });
        let text =
            serde_json::to_string_pretty(&value).map_err(|e| crate::errors::failed_to_serialize_abi(e.to_string()))?;
        std::fs::write(path, text).map_err(crate::errors::failed_to_write_abi)?;
        tracing::info!("Compatibility report written to '{}'.", path.display());
    } else if problems.is_empty() {
        eprintln!("`{program}` satisfies `{standard}`");
    } else {
        eprintln!("`{program}` does not satisfy `{standard}`:");
        for problem in problems {
            eprintln!("  - {problem}");
        }
    }

    if problems.is_empty() {
        Ok(())
    } else {
        Err(crate::errors::not_compatible(program, standard, problems.len()).into())
    }
}

/// Pretty-prints `abi` as JSON.
fn abi_to_json(abi: &leo_abi::Program) -> Result<String> {
    serde_json::to_string_pretty(abi).map_err(|e| crate::errors::failed_to_serialize_abi(e.to_string()).into())
}

/// Prints the main ABI followed by each dependency under a `=== <name> ===` header. The main entry is a bare JSON
/// document so callers that only need the no-imports case keep working unchanged.
fn print_abis_to_stdout(main: &leo_abi::Program, deps: &IndexMap<String, leo_abi::Program>) -> Result<()> {
    println!("{}", abi_to_json(main)?);
    for (name, abi) in deps {
        println!();
        println!("=== {name} ===");
        println!("{}", abi_to_json(abi)?);
    }
    Ok(())
}

/// Writes the main ABI and each dependency ABI to `<dir>/<name>.abi.json`. `dir` is created if missing; existing
/// files are overwritten.
fn write_abis_to_directory(
    dir: &Path,
    main: &leo_abi::Program,
    deps: &IndexMap<String, leo_abi::Program>,
) -> Result<()> {
    std::fs::create_dir_all(dir).map_err(crate::errors::failed_to_write_abi)?;
    let write = |name: &str, abi: &leo_abi::Program| -> Result<()> {
        let path = dir.join(format!("{name}.abi.json"));
        std::fs::write(&path, abi_to_json(abi)?).map_err(crate::errors::failed_to_write_abi)?;
        tracing::info!("ABI written to '{}'.", path.display());
        Ok(())
    };
    write(&main.program, main)?;
    for (name, abi) in deps {
        write(name, abi)?;
    }
    Ok(())
}

/// Disassembles `bytecode` and its declared transitive imports, resolving each dependency from `imports_dir`.
/// Returns the main program plus an ordered list of `(name, AleoProgram)` pairs where dependencies precede their
/// dependents (post-order). Names already loaded as network builtins (e.g. `credits.aleo`) are skipped silently.
fn disassemble_with_imports(
    name: &str,
    bytecode: &str,
    network: NetworkName,
    imports_dir: &Path,
) -> Result<(AleoProgram, Vec<(String, AleoProgram)>), LeoError> {
    match network {
        NetworkName::MainnetV0 => disassemble_with_imports_typed::<MainnetV0>(name, bytecode, imports_dir),
        NetworkName::TestnetV0 => disassemble_with_imports_typed::<TestnetV0>(name, bytecode, imports_dir),
        NetworkName::CanaryV0 => disassemble_with_imports_typed::<CanaryV0>(name, bytecode, imports_dir),
    }
}

/// Typed implementation of [`disassemble_with_imports`] specialised to a concrete `Network`. Parses the main
/// program once, walks its transitive imports from `imports_dir`, hands each parsed program to
/// `leo_disassembler::validate_and_disassemble` in topological order, and finally does the same for the main
/// program once all dependencies are loaded.
fn disassemble_with_imports_typed<N: Network>(
    name: &str,
    bytecode: &str,
    imports_dir: &Path,
) -> Result<(AleoProgram, Vec<(String, AleoProgram)>), LeoError> {
    let mut process = SvmProcess::<N>::load().map_err(crate::errors::failed_to_load_process)?;
    let main = SvmProgram::<N>::from_str(bytecode)
        .map_err(|_| crate::errors::failed_to_parse_aleo_file(name, "invalid Aleo bytecode"))?;
    let deps = load_and_disassemble_imports(&main, imports_dir, &mut process)?;
    let main_aleo = leo_disassembler::validate_and_disassemble(name, main, &mut process)?;
    Ok((main_aleo, deps))
}

/// Walks `program`'s transitive imports from `imports_dir`, hands each parsed program to
/// `leo_disassembler::validate_and_disassemble` in topological order, and returns the disassembled programs in
/// the same order. Names already loaded in `process` are skipped, so network builtins don't need to be on disk.
fn load_and_disassemble_imports<N: Network>(
    program: &SvmProgram<N>,
    imports_dir: &Path,
    process: &mut SvmProcess<N>,
) -> Result<Vec<(String, AleoProgram)>, LeoError> {
    let mut parsed: HashMap<String, SvmProgram<N>> = HashMap::new();
    let mut graph: DiGraph<String> = DiGraph::default();
    let mut worklist: Vec<String> = program
        .imports()
        .iter()
        .filter(|(id, _)| !process.contains_program(id))
        .map(|(id, _)| id.to_string())
        .collect();

    while let Some(name) = worklist.pop() {
        if parsed.contains_key(&name) {
            continue;
        }
        // Try the per-unit layout (`<dir>/<bare>/<name>.aleo`) first, falling back to flat.
        let bare = name.strip_suffix(".aleo").unwrap_or(&name);
        let per_unit = imports_dir.join(bare).join(&name);
        let path = if per_unit.exists() { per_unit } else { imports_dir.join(&name) };
        let text =
            std::fs::read_to_string(&path).map_err(|e| crate::errors::failed_to_read_import(path.display(), e))?;
        let imported = SvmProgram::<N>::from_str(&text)
            .map_err(|_| crate::errors::failed_to_parse_aleo_file(name.clone(), "invalid Aleo bytecode"))?;
        graph.add_node(name.clone());
        for (nested_id, _) in imported.imports() {
            if process.contains_program(nested_id) {
                continue;
            }
            let nested_name = nested_id.to_string();
            graph.add_edge(name.clone(), nested_name.clone());
            worklist.push(nested_name);
        }
        parsed.insert(name, imported);
    }

    let ordered = graph.post_order().map_err(|DiGraphError::CycleDetected(cycle)| {
        let path = cycle.iter().map(|n| format!("`{n}`")).collect::<Vec<_>>().join(" -> ");
        crate::errors::circular_import(path)
    })?;
    let mut disassembled: Vec<(String, AleoProgram)> = Vec::with_capacity(ordered.len());
    for name in ordered {
        // `post_order` returns only names inserted into `graph`, and every such name was inserted into `parsed` on
        // the same loop iteration, so `remove` cannot fail.
        let svm = parsed.remove(&name).expect("post_order yielded a name absent from `parsed`");
        let aleo = leo_disassembler::validate_and_disassemble(&name, svm, process)?;
        disassembled.push((name, aleo));
    }
    Ok(disassembled)
}

#[cfg(test)]
mod tests {
    use super::*;

    use leo_span::create_session_if_not_set_then;

    /// `leo abi` on a `.aleo` file that declares imports must load each dependency from an imports directory before
    /// disassembling.
    #[test]
    fn disassemble_with_imports_loads_dependencies() {
        create_session_if_not_set_then(|_| {
            let dep_src = "\
program dep.aleo;

function id:
    input r0 as u32.private;
    output r0 as u32.private;
";
            let main_src = "\
import dep.aleo;

program importer.aleo;

function call_id:
    input r0 as u32.private;
    call dep.aleo/id r0 into r1;
    output r1 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("dep.aleo"), dep_src).unwrap();

            let (main, deps) = disassemble_with_imports("importer.aleo", main_src, NetworkName::TestnetV0, dir.path())
                .expect("expected disassembly with imports to succeed");
            assert_eq!(main.stub_id.to_string(), "importer.aleo");
            assert_eq!(main.imports.iter().map(|i| i.to_string()).collect::<Vec<_>>(), vec!["dep.aleo".to_string()]);
            assert_eq!(deps.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), vec!["dep.aleo"]);
            assert_eq!(deps[0].1.stub_id.to_string(), "dep.aleo");
        });
    }

    /// Transitive imports must load in dependency order: a leaf appears before any program that imports it.
    #[test]
    fn disassemble_with_imports_orders_transitive_dependencies() {
        create_session_if_not_set_then(|_| {
            let c_src = "\
program c.aleo;

function id_c:
    input r0 as u32.private;
    output r0 as u32.private;
";
            let b_src = "\
import c.aleo;

program b.aleo;

function id_b:
    input r0 as u32.private;
    call c.aleo/id_c r0 into r1;
    output r1 as u32.private;
";
            let a_src = "\
import b.aleo;

program a.aleo;

function id_a:
    input r0 as u32.private;
    call b.aleo/id_b r0 into r1;
    output r1 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("b.aleo"), b_src).unwrap();
            std::fs::write(dir.path().join("c.aleo"), c_src).unwrap();

            let (main, deps) = disassemble_with_imports("a.aleo", a_src, NetworkName::TestnetV0, dir.path())
                .expect("expected transitive disassembly to succeed");
            assert_eq!(main.stub_id.to_string(), "a.aleo");
            assert_eq!(deps.iter().map(|(n, _)| n.as_str()).collect::<Vec<_>>(), vec!["c.aleo", "b.aleo"]);
        });
    }

    /// Network builtins like `credits.aleo` are already in the `Process`, so they must be skipped silently — the
    /// command must not require them to be present in the imports directory.
    #[test]
    fn disassemble_with_imports_handles_network_builtin() {
        create_session_if_not_set_then(|_| {
            let main_src = "\
import credits.aleo;

program network_user.aleo;

function noop:
    input r0 as u32.private;
    output r0 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            let (main, deps) =
                disassemble_with_imports("network_user.aleo", main_src, NetworkName::TestnetV0, dir.path())
                    .expect("expected disassembly to succeed without credits.aleo on disk");
            assert_eq!(main.stub_id.to_string(), "network_user.aleo");
            assert!(deps.is_empty(), "network builtins must not appear in the dependency list");
        });
    }

    /// A cycle in the declared imports must surface a descriptive error (with the offending names) rather than a
    /// generic message or a panic.
    #[test]
    fn disassemble_with_imports_reports_circular_dependency() {
        create_session_if_not_set_then(|_| {
            let a_src = "\
import b.aleo;

program a.aleo;

function id_a:
    input r0 as u32.private;
    call b.aleo/id_b r0 into r1;
    output r1 as u32.private;
";
            let b_src = "\
import a.aleo;

program b.aleo;

function id_b:
    input r0 as u32.private;
    call a.aleo/id_a r0 into r1;
    output r1 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("a.aleo"), a_src).unwrap();
            std::fs::write(dir.path().join("b.aleo"), b_src).unwrap();

            let err = disassemble_with_imports("a.aleo", a_src, NetworkName::TestnetV0, dir.path())
                .expect_err("expected disassembly to fail on a circular import");
            let msg = err.to_string();
            assert!(msg.contains("circular import"), "unexpected error: {msg}");
            assert!(msg.contains("a.aleo") && msg.contains("b.aleo"), "cycle path not surfaced: {msg}");
        });
    }

    /// A program that lists an import not present in the imports directory must surface a clear error rather than
    /// panicking.
    #[test]
    fn disassemble_with_imports_reports_missing_dependency() {
        create_session_if_not_set_then(|_| {
            let main_src = "\
import dep.aleo;

program importer.aleo;

function call_id:
    input r0 as u32.private;
    call dep.aleo/id r0 into r1;
    output r1 as u32.private;
";
            let dir = tempfile::tempdir().unwrap();
            let err = disassemble_with_imports("importer.aleo", main_src, NetworkName::TestnetV0, dir.path())
                .expect_err("expected disassembly to fail when an import is missing");
            assert!(err.to_string().contains("dep.aleo"), "unexpected error: {err}");
        });
    }

    /// Main bytecode that fails grammatical parsing must surface a clear error naming the main program.
    #[test]
    fn disassemble_with_imports_rejects_malformed_main() {
        create_session_if_not_set_then(|_| {
            let dir = tempfile::tempdir().unwrap();
            let err = disassemble_with_imports(
                "importer.aleo",
                "this is not valid Aleo bytecode",
                NetworkName::TestnetV0,
                dir.path(),
            )
            .expect_err("expected disassembly to fail on malformed main bytecode");
            assert!(err.to_string().contains("importer.aleo"), "unexpected error: {err}");
        });
    }

    /// A dependency file whose contents are not valid Aleo bytecode must surface a clear error naming the dep.
    #[test]
    fn disassemble_with_imports_rejects_malformed_dependency() {
        create_session_if_not_set_then(|_| {
            let main_src = "\
import dep.aleo;

program importer.aleo;

function call_id:
    input r0 as u32.private;
    call dep.aleo/id r0 into r1;
    output r1 as u32.private;
";
            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("dep.aleo"), "this is not valid Aleo bytecode").unwrap();
            let err = disassemble_with_imports("importer.aleo", main_src, NetworkName::TestnetV0, dir.path())
                .expect_err("expected disassembly to fail on malformed dependency bytecode");
            assert!(err.to_string().contains("dep.aleo"), "unexpected error: {err}");
        });
    }

    /// A diamond-shaped import graph (`a → {b, c}`, `b → d`, `c → d`) must yield `d` exactly once, before both
    /// `b` and `c`. Exercises the worklist's already-parsed short-circuit.
    #[test]
    fn disassemble_with_imports_dedups_diamond_imports() {
        create_session_if_not_set_then(|_| {
            let d_src = "\
program d.aleo;

function id_d:
    input r0 as u32.private;
    output r0 as u32.private;
";
            let b_src = "\
import d.aleo;

program b.aleo;

function id_b:
    input r0 as u32.private;
    call d.aleo/id_d r0 into r1;
    output r1 as u32.private;
";
            let c_src = "\
import d.aleo;

program c.aleo;

function id_c:
    input r0 as u32.private;
    call d.aleo/id_d r0 into r1;
    output r1 as u32.private;
";
            let a_src = "\
import b.aleo;
import c.aleo;

program a.aleo;

function combine:
    input r0 as u32.private;
    call b.aleo/id_b r0 into r1;
    call c.aleo/id_c r1 into r2;
    output r2 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("d.aleo"), d_src).unwrap();
            std::fs::write(dir.path().join("b.aleo"), b_src).unwrap();
            std::fs::write(dir.path().join("c.aleo"), c_src).unwrap();

            let (main, deps) = disassemble_with_imports("a.aleo", a_src, NetworkName::TestnetV0, dir.path())
                .expect("expected diamond-imports disassembly to succeed");
            assert_eq!(main.stub_id.to_string(), "a.aleo");

            let names: Vec<&str> = deps.iter().map(|(n, _)| n.as_str()).collect();
            assert_eq!(names.iter().filter(|&&n| n == "d.aleo").count(), 1, "d.aleo not deduped: {names:?}");
            assert_eq!(names.len(), 3, "expected exactly 3 deps, got: {names:?}");
            let pos = |needle: &str| {
                names.iter().position(|&n| n == needle).unwrap_or_else(|| panic!("{needle} missing from {names:?}"))
            };
            assert!(pos("d.aleo") < pos("b.aleo"), "topo order violated: {names:?}");
            assert!(pos("d.aleo") < pos("c.aleo"), "topo order violated: {names:?}");
        });
    }

    /// A network builtin reached transitively (`a → b`, `b → credits`) must be filtered out of the dependency
    /// walk too, not just at the top level. Exercises the nested-import builtin filter.
    #[test]
    fn disassemble_with_imports_skips_nested_network_builtin() {
        create_session_if_not_set_then(|_| {
            let b_src = "\
import credits.aleo;

program b.aleo;

function id_b:
    input r0 as u32.private;
    output r0 as u32.private;
";
            let a_src = "\
import b.aleo;

program a.aleo;

function id_a:
    input r0 as u32.private;
    call b.aleo/id_b r0 into r1;
    output r1 as u32.private;
";

            let dir = tempfile::tempdir().unwrap();
            std::fs::write(dir.path().join("b.aleo"), b_src).unwrap();

            let (main, deps) = disassemble_with_imports("a.aleo", a_src, NetworkName::TestnetV0, dir.path())
                .expect("expected disassembly with transitive credits.aleo import to succeed");
            assert_eq!(main.stub_id.to_string(), "a.aleo");
            let names: Vec<&str> = deps.iter().map(|(n, _)| n.as_str()).collect();
            assert_eq!(names, vec!["b.aleo"], "credits.aleo must be skipped silently, got: {names:?}");
        });
    }

    /// A minimal but well-formed ABI JSON document (no items), enough to exercise the parser.
    const SAMPLE_ABI_JSON: &str = r#"{
  "program": "token.aleo",
  "structs": [],
  "records": [],
  "mappings": [],
  "storage_variables": [],
  "functions": [],
  "views": []
}"#;

    #[test]
    fn load_standard_abi_reads_json() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("token.abi.json");
        std::fs::write(&path, SAMPLE_ABI_JSON).unwrap();

        let loaded = load_standard_abi(&path).expect("expected JSON ABI to load");
        assert_eq!(loaded.program, "token.aleo");
    }

    #[test]
    fn load_standard_abi_rejects_aleo() {
        // The standard must be a JSON file; a `.aleo` bytecode file is rejected.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("token.aleo");
        std::fs::write(&path, "irrelevant").unwrap();

        let err = load_standard_abi(&path).expect_err("expected a .aleo standard to be rejected");
        assert!(err.to_string().contains("JSON file containing an ABI"), "unexpected error: {err}");
    }

    #[test]
    fn load_standard_abi_rejects_invalid_json() {
        // A `.json` file that is not valid JSON at all.
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("broken.json");
        std::fs::write(&path, "{ not valid json").unwrap();

        let err = load_standard_abi(&path).expect_err("expected invalid JSON to be rejected");
        assert!(err.to_string().contains("could not parse ABI JSON"), "unexpected error: {err}");
    }

    #[test]
    fn load_standard_abi_rejects_non_abi_json() {
        // Valid JSON, but not an ABI: it lacks the required fields (e.g. `program`).
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("notabi.json");
        std::fs::write(&path, r#"{ "hello": "world" }"#).unwrap();

        let err = load_standard_abi(&path).expect_err("expected non-ABI JSON to be rejected");
        assert!(err.to_string().contains("could not parse ABI JSON"), "unexpected error: {err}");
    }
}