aleo_rust/
lib.rs

1// Copyright (C) 2019-2023 Aleo Systems Inc.
2// This file is part of the Aleo SDK library.
3
4// The Aleo SDK library is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8
9// The Aleo SDK library is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13
14// You should have received a copy of the GNU General Public License
15// along with the Aleo SDK library. If not, see <https://www.gnu.org/licenses/>.
16
17//! [![github]](https://github.com/AleoHQ/sdk)&ensp;[![crates-io]](https://crates.io/crates/aleo-rust)&ensp;[![docs-rs]](https://docs.rs/aleo-rust/latest/aleo_rust/)
18//!
19//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
20//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
21//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
22//!
23//! <br/>
24//! The Aleo Rust SDK provides a set of tools for deploying and executing programs as well as
25//! tools for communicating with the Aleo Network.
26//!
27//! # Aleo Network Interaction
28//!
29//! Users of the SDK can interact with the Aleo network via the [AleoAPIClient] struct.
30//!
31//! The Aleo Network has nodes within the network which provide a REST API for interacting with
32//! the network. The AleoAPIClient struct provides a 1:1 mapping of those REST API endpoints as well
33//! as several convenience methods for interacting with the network.
34//!
35//! Some key usages of the Aleo API client are:
36//! * Finding records to spend in value transfers, program executions and program deployments
37//! * Locating programs deployed on the network
38//! * Sending transactions to the network
39//! * Inspecting chain data such as block content, transaction content, etc.
40//!
41//! ### Example Usage
42//! ```no_run
43//!   use aleo_rust::AleoAPIClient;
44//!   use snarkvm_console::{
45//!       account::PrivateKey,
46//!       network::Testnet3,
47//!   };
48//!   use rand::thread_rng;
49//!
50//!   // Create a client that interacts with the testnet3 program
51//!   let api_client = AleoAPIClient::<Testnet3>::testnet3();
52//!
53//!   // FIND A PROGRAM ON THE ALEO NETWORK
54//!   let hello = api_client.get_program("hello.aleo").unwrap();
55//!   println!("Hello program: {hello:?}");
56//!
57//!   // FIND RECORDS THAT BELONG TO A PRIVATE KEY
58//!   let mut rng = thread_rng();
59//!   // Create a private key (in practice, this would be an existing user's private key)
60//!   let private_key = PrivateKey::new(&mut rng).unwrap();
61//!   // Get the latest block height
62//!   let end_height = api_client.latest_height().unwrap();
63//!   // Look back 1000 blocks
64//!   let start_height = end_height - 1000u32;
65//!   // Find records with these gate amounts (requires an account with a balance)
66//!   let amounts_to_find = vec![100u64, 200u64];
67//!   let records = api_client.get_unspent_records(&private_key, (start_height..end_height), None, Some(&amounts_to_find)).unwrap();
68//!
69//!   ```
70//! # Program Execution and Deployment
71//!
72//! The Aleo [ProgramManager] provides a set of tools for deploying and executing programs locally
73//! and on the Aleo Network.
74//!
75//! The [RecordFinder] struct is used in conjunction with the ProgramManager to find records to
76//! spend in value transfers and program execution/deployments fees.
77//!
78//! The program deployment and execution flow are shown in the example below.
79//!
80//! ### Example Usage
81//! ```no_run
82//!   use aleo_rust::{
83//!     AleoAPIClient, Encryptor, ProgramManager, RecordFinder,
84//!     snarkvm_types::{Address, PrivateKey, Testnet3, Program},
85//!     TransferType
86//!   };
87//!   use rand::thread_rng;
88//!   use std::str::FromStr;
89//!
90//!   // Create the necessary components to create the program manager
91//!   let mut rng = thread_rng();
92//!   // Create an api client to query the network state
93//!   let api_client = AleoAPIClient::<Testnet3>::testnet3();
94//!   // Create a private key (in practice, this would be a user's private key)
95//!   let private_key = PrivateKey::<Testnet3>::new(&mut rng).unwrap();
96//!   // Encrypt the private key with a password
97//!   let private_key_ciphertext = Encryptor::<Testnet3>::encrypt_private_key_with_secret(&private_key, "password").unwrap();
98//!
99//!   // Create the program manager
100//!   // (Note: An optional local directory can be provided to manage local program data)
101//!   let mut program_manager = ProgramManager::<Testnet3>::new(None, Some(private_key_ciphertext), Some(api_client), None, false).unwrap();
102//!
103//!   // ------------------
104//!   // EXECUTE PROGRAM STEPS
105//!   // ------------------
106//!
107//!   let record_finder = RecordFinder::<Testnet3>::new(AleoAPIClient::testnet3());
108//!   // Set the fee for the deployment transaction (in units of microcredits)
109//!   let fee_microcredits = 300000;
110//!   // Find a record to fund the deployment fee (requires an account with a balance)
111//!   let fee_record = record_finder.find_one_record(&private_key, fee_microcredits, None).unwrap();
112//!
113//!   // Execute the function `hello` of the hello.aleo program with the arguments 5u32 and 3u32.
114//!   // Specify 0 for the fee and provide a password to decrypt the private key stored in the program manager
115//!   program_manager.execute_program("hello.aleo", "hello", ["5u32", "3u32"].into_iter(), 0, Some(fee_record), Some("password"), None).unwrap();
116//!
117//!   // ------------------
118//!   // DEPLOY PROGRAM STEPS
119//!   // ------------------
120//!
121//!   // Note - Deployment requires a mandatory deployment fee, so an account with an existing
122//!   // balance is required to deploy a program
123//!
124//!   // Create a program name (note: change this to something unique)
125//!   let program_name = "yourownprogram.aleo";
126//!   // Create a test program
127//!   let test_program = format!("program {};\n\nfunction hello:\n    input r0 as u32.public;\n    input r1 as u32.private;\n    add r0 r1 into r2;\n    output r2 as u32.private;\n", program_name);
128//!   // Create a program object from the program string
129//!   let program = Program::from_str(&test_program).unwrap();
130//!   // Add the program to the program manager (this can also be done by providing a path to
131//!   // the program on disk when the program manager is created)
132//!   program_manager.add_program(&program).unwrap();
133//!   // Create a record finder to find records to fund the deployment fee
134//!   let record_finder = RecordFinder::<Testnet3>::new(AleoAPIClient::testnet3());
135//!   // Set the fee for the deployment transaction (in units of microcredits)
136//!   let fee_microcredits = 300000;
137//!   // Find a record to fund the deployment fee (requires an account with a balance)
138//!   let fee_record = record_finder.find_one_record(&private_key, fee_microcredits, None).unwrap();
139//!   // Deploy the program to the network
140//!   program_manager.deploy_program(program_name, fee_microcredits, Some(fee_record), Some("password")).unwrap();
141//!
142//!   // Wait several minutes.. then check the program exists on the network
143//!   let api_client = AleoAPIClient::<Testnet3>::testnet3();
144//!   let program_on_chain = api_client.get_program(program_name).unwrap();
145//!   let program_on_chain_name = program_on_chain.id().to_string();
146//!   assert_eq!(&program_on_chain_name, program_name);
147//!
148//!   // ------------------
149//!   // TRANSFER STEPS
150//!   // ------------------
151//!
152//!   // Create a recipient (in practice, the recipient would send their address to the sender)
153//!   let recipient_key = PrivateKey::<Testnet3>::new(&mut rng).unwrap();
154//!   let recipient_address = Address::try_from(recipient_key).unwrap();
155//!   // Create amount and fee (both in units of microcredits)
156//!   let amount = 30000;
157//!   let fee = 100;
158//!   // Find records to fund the transfer
159//!   let (amount_record, fee_record) = record_finder.find_amount_and_fee_records(amount, fee, &private_key).unwrap();
160//!   // Create a transfer
161//!   program_manager.transfer(amount, fee, recipient_address, TransferType::Private, Some("password"), Some(amount_record), Some(fee_record)).unwrap();
162//!
163//!   ```
164//! This API is currently under active development and is expected to change in the future in order
165//! to provide a more streamlined experience for program execution and deployment.
166//!
167
168pub mod account;
169#[doc(inline)]
170pub use account::Encryptor;
171
172#[cfg(feature = "full")]
173pub mod api;
174#[cfg(feature = "full")]
175#[doc(inline)]
176pub use api::AleoAPIClient;
177
178#[cfg(feature = "full")]
179pub mod program;
180#[cfg(feature = "full")]
181#[doc(inline)]
182pub use program::{OnChainProgramState, ProgramManager, RecordFinder, TransferType};
183
184#[cfg(test)]
185#[cfg(feature = "full")]
186pub mod test_utils;
187#[cfg(test)]
188#[cfg(feature = "full")]
189pub use test_utils::*;
190
191pub mod snarkvm_types {
192    //! Re-export of crucial types from the snarkVM crate
193    #[cfg(feature = "full")]
194    pub use snarkvm::{file::Manifest, package::Package};
195    pub use snarkvm_circuit_network::{Aleo, AleoV0};
196    pub use snarkvm_console::{
197        account::{Address, PrivateKey, Signature, ViewKey},
198        network::Testnet3,
199        prelude::{ToBytes, Uniform},
200        program::{
201            Ciphertext,
202            Entry,
203            EntryType,
204            Identifier,
205            Literal,
206            Locator,
207            Network,
208            OutputID,
209            Plaintext,
210            PlaintextType,
211            ProgramID,
212            ProgramOwner,
213            Record,
214            Response,
215            Value,
216            ValueType,
217        },
218        types::Field,
219    };
220    pub use snarkvm_ledger_block::{Block, Deployment, Execution, Transaction};
221    pub use snarkvm_ledger_query::Query;
222    pub use snarkvm_ledger_store::{
223        helpers::memory::{BlockMemory, ConsensusMemory},
224        BlockStore,
225        ConsensusStore,
226    };
227    pub use snarkvm_synthesizer::{
228        cost_in_microcredits,
229        deployment_cost,
230        execution_cost,
231        snark::{Proof, ProvingKey, VerifyingKey},
232        Process,
233        Program,
234        Trace,
235        VM,
236    };
237}
238
239pub use snarkvm_types::*;
240
241use anyhow::{anyhow, bail, ensure, Error, Result};
242use indexmap::IndexMap;
243use once_cell::sync::OnceCell;
244#[cfg(feature = "full")]
245use std::{convert::TryInto, fs::File, io::Read, ops::Range, path::PathBuf};
246use std::{iter::FromIterator, marker::PhantomData, str::FromStr};
247
248/// A trait providing convenient methods for accessing the amount of Aleo present in a record
249pub trait Credits {
250    /// Get the amount of credits in the record if the record possesses Aleo credits
251    fn credits(&self) -> Result<f64> {
252        Ok(self.microcredits()? as f64 / 1_000_000.0)
253    }
254
255    /// Get the amount of microcredits in the record if the record possesses Aleo credits
256    fn microcredits(&self) -> Result<u64>;
257}
258
259impl<N: Network> Credits for Record<N, Plaintext<N>> {
260    fn microcredits(&self) -> Result<u64> {
261        let amount = match self.find(&[Identifier::from_str("microcredits")?])? {
262            Entry::Private(Plaintext::Literal(Literal::<N>::U64(amount), _)) => amount,
263            _ => bail!("The record provided does not contain a microcredits field"),
264        };
265        Ok(*amount)
266    }
267}