Skip to main content

aleo_rust_sdk/
program.rs

1//! # Aleo Program — load and inspect Aleo programs.
2//!
3//! Wraps snarkVM [`Program<TestnetV0>`] with ergonomic constructors and queries.
4//!
5//! ## Usage
6//!
7//! ```no_run
8//! use aleo_rust_sdk::AleoProgram;
9//!
10//! // Load from source string
11//! let program = AleoProgram::from_source("program hello.aleo;\nfunction main:\n    input r0 as u32.public;\n    output r0 as u32.public;\n").unwrap();
12//! println!("Program ID: {}", program.id());
13//!
14//! // Load the built-in credits program
15//! let credits = AleoProgram::credits().unwrap();
16//! assert!(credits.id().to_string().contains("credits.aleo"));
17//! ```
18
19use anyhow::{Context, Result};
20use snarkvm::prelude::{Program, ProgramID, TestnetV0};
21use std::str::FromStr;
22
23/// A loaded Aleo program for TestnetV0.
24#[derive(Clone, Debug)]
25pub struct AleoProgram {
26    pub(crate) program: Program<TestnetV0>,
27}
28
29impl AleoProgram {
30    /// Load a program from a `.aleo` file on disk.
31    pub fn from_local_file(path: &str) -> Result<Self> {
32        let source = std::fs::read_to_string(path).context(format!("Failed to read {path}"))?;
33        let program = Program::<TestnetV0>::from_str(&source).context("Failed to parse program")?;
34        Ok(Self { program })
35    }
36
37    /// Parse a program from its source string.
38    pub fn from_source(source: &str) -> Result<Self> {
39        let program = Program::<TestnetV0>::from_str(source).context("Failed to parse program")?;
40        Ok(Self { program })
41    }
42
43    /// Load the credits program (built-in).
44    pub fn credits() -> Result<Self> {
45        let program = Program::<TestnetV0>::credits()?;
46        Ok(Self { program })
47    }
48
49    /// Return the program ID.
50    pub fn id(&self) -> &ProgramID<TestnetV0> {
51        self.program.id()
52    }
53
54    /// Return a reference to the inner snarkVM `Program`.
55    pub fn inner(&self) -> &Program<TestnetV0> {
56        &self.program
57    }
58
59    /// Consume self and return the inner `Program`.
60    pub fn into_inner(self) -> Program<TestnetV0> {
61        self.program
62    }
63}
64
65#[cfg(test)]
66mod tests {
67    use super::*;
68
69    #[test]
70    fn test_credits_program() {
71        let prog = AleoProgram::credits().unwrap();
72        assert!(prog.id().to_string().contains("credits.aleo"));
73    }
74
75    #[test]
76    fn test_parse_simple_program() {
77        let source = r#"
78program hello.aleo;
79
80function main:
81    input r0 as u32.public;
82    output r0 as u32.public;
83"#;
84        let prog = AleoProgram::from_source(source).unwrap();
85        assert_eq!(prog.id().to_string(), "hello.aleo");
86    }
87}