snarkos-cli 4.6.4

Command-line interface for snarkOS
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
// Copyright (c) 2019-2026 Provable Inc.
// This file is part of the snarkOS library.

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at:

// http://www.apache.org/licenses/LICENSE-2.0

// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use super::{DEFAULT_ENDPOINT, Developer};
use crate::{
    commands::StoreFormat,
    helpers::args::{parse_private_key, prepare_endpoint},
};

use snarkvm::{
    console::network::Network,
    ledger::{query::QueryTrait, store::helpers::memory::BlockMemory},
    prelude::{
        Address,
        Identifier,
        Locator,
        Process,
        ProgramID,
        VM,
        Value,
        query::Query,
        store::{ConsensusStore, helpers::memory::ConsensusMemory},
    },
};

use aleo_std::StorageMode;
use anyhow::{Context, Result, anyhow, bail};
use clap::{Parser, builder::NonEmptyStringValueParser};
use colored::Colorize;
use std::str::FromStr;
use tracing::debug;
use ureq::http::Uri;
use zeroize::Zeroize;

/// Executes an Aleo program function.
#[derive(Debug, Parser)]
#[command(
    group(clap::ArgGroup::new("mode").required(true).multiple(false)),
    group(clap::ArgGroup::new("key").required(true).multiple(false))
)]
pub struct Execute {
    /// The program identifier.
    #[clap(value_parser=NonEmptyStringValueParser::default())]
    program_id: String,
    /// The function name.
    #[clap(value_parser=NonEmptyStringValueParser::default())]
    function: String,
    /// The function inputs.
    inputs: Vec<String>,
    /// The private key used to generate the execution.
    #[clap(short = 'p', long, group = "key", value_parser=NonEmptyStringValueParser::default())]
    private_key: Option<String>,
    /// Specify the path to a file containing the account private key of the node
    #[clap(long, group = "key", value_parser=NonEmptyStringValueParser::default())]
    private_key_file: Option<String>,
    /// Use a developer validator key to generate the execution
    #[clap(long, group = "key")]
    dev_key: Option<u16>,
    /// The endpoint to query node state from and broadcast to (if set to broadcast).
    ///
    /// The given value is expected to be the base URL, e.g., "https://mynode.com", and will be extended automatically
    /// to fit the network type and query.
    /// For example, the base URL may extend to "http://mynode.com/testnet/transaction/unconfirmed/ID" to retrieve
    /// an unconfirmed transaction on the test network.
    ///
    /// The given value may also be a JSON serialized `StaticQuery` struct.
    #[clap(short, long, alias="query", default_value=DEFAULT_ENDPOINT, verbatim_doc_comment)]
    endpoint: Uri,
    /// The priority fee in microcredits.
    #[clap(long, default_value_t = 0)]
    priority_fee: u64,
    /// The record to spend the fee from.
    #[clap(short, long)]
    record: Option<String>,
    /// Set the URL used to broadcast the transaction (if no value is given, the query endpoint is used).
    ///
    /// The given value is expected the full URL of the endpoint, not just the base URL, e.g., "http://mynode.com/testnet/transaction/broadcast".
    #[clap(short, long, group = "mode", verbatim_doc_comment)]
    broadcast: Option<Option<Uri>>,
    /// Performs a dry-run of transaction generation.
    #[clap(short, long, group = "mode")]
    dry_run: bool,
    /// Store generated deployment transaction to a local file.
    #[clap(long, group = "mode")]
    store: Option<String>,
    /// If --store is specified, the format in which the transaction should be stored : string or
    /// bytes, by default : bytes.
    #[clap(long, value_enum, default_value_t = StoreFormat::Bytes, requires="store")]
    store_format: StoreFormat,
    /// Wait for the transaction to be accepted by the network. Requires --broadcast.
    #[clap(long, requires = "broadcast")]
    wait: bool,
    /// Timeout in seconds when waiting for transaction confirmation. Default is 60 seconds.
    #[clap(long, default_value_t = 60, requires = "wait")]
    timeout: u64,
    /// Send the transaction without checking if sufficient funds are available (intended for testing purposes only).
    #[clap(long, hide = true)]
    skip_funds_check: bool,
}

impl Drop for Execute {
    /// Zeroize the private key when the `Execute` struct goes out of scope.
    fn drop(&mut self) {
        if let Some(mut pk) = self.private_key.take() {
            pk.zeroize()
        }
    }
}

impl Execute {
    /// Executes an Aleo program function with the provided inputs.
    pub fn parse<N: Network>(self) -> Result<String> {
        let endpoint = prepare_endpoint(self.endpoint.clone())?;

        // Specify the query
        let query = Query::<N, BlockMemory<N>>::from(endpoint.clone());

        // Check if the query is a static query.
        let is_static_query = matches!(query, Query::STATIC(_));

        // Retrieve the private key.
        let private_key = parse_private_key(self.private_key.clone(), self.private_key_file.clone(), self.dev_key)?;

        // Retrieve the program ID.
        let program_id = ProgramID::from_str(&self.program_id).with_context(|| "Failed to parse program ID")?;

        // Retrieve the function.
        let function = Identifier::from_str(&self.function).with_context(|| "Failed to parse function ID")?;

        // Retrieve the inputs.
        let inputs = self.inputs.iter().map(|input| Value::from_str(input)).collect::<Result<Vec<Value<N>>>>()?;

        let locator = Locator::<N>::from_str(&format!("{program_id}/{function}"))?;
        println!("📦 Creating execution transaction for '{}'...\n", &locator.to_string().bold());

        // Generate the execution transaction.
        let transaction = {
            // Initialize an RNG.
            let rng = &mut rand::thread_rng();

            // Initialize the storage.
            let store = ConsensusStore::<N, ConsensusMemory<N>>::open(StorageMode::Production)?;

            // Initialize the VM.
            let vm = VM::from(store)?;

            if !is_static_query && program_id != ProgramID::from_str("credits.aleo")? {
                let height = query.current_block_height().with_context(|| "Failed to retrieve current block height")?;
                let version = N::CONSENSUS_VERSION(height)?;
                debug!("At block height {height} and consensus {version:?}");

                // Load the program and it's imports into the process.
                load_program(&query, &mut vm.process().write(), &program_id, &endpoint)?;
            }

            // Prepare the fee.
            let fee_record = match &self.record {
                Some(record_string) => Some(
                    Developer::parse_record(&private_key, record_string).with_context(|| "Failed to parse record")?,
                ),
                None => None,
            };

            // Create a new transaction.
            vm.execute(
                &private_key,
                (program_id, function),
                inputs.iter(),
                fee_record,
                self.priority_fee,
                Some(&query),
                rng,
            )
            .with_context(|| "VM failed to execute transaction locally")?
        };

        // Check if the public balance is sufficient.
        if self.record.is_none() && !is_static_query && !self.skip_funds_check {
            // Fetch the public balance.
            let address = Address::try_from(&private_key)?;
            let public_balance = Developer::get_public_balance::<N>(&endpoint, &address)
                .with_context(|| "Failed to check for sufficient funds to send transaction")?
                .ok_or_else(|| {
                    anyhow!(
                        "No public balance found for sending account `{}`. It may not exist.",
                        address.to_string().bold()
                    )
                })?;

            // Check if the public balance is sufficient.
            let storage_cost = transaction
                .execution()
                .with_context(|| "Failed to get execution cost of transaction")?
                .size_in_bytes()?;

            // Calculate the base fee.
            // This fee is the minimum fee required to pay for the transaction,
            // excluding any finalize fees that the execution may incur.
            let base_fee = storage_cost.saturating_add(self.priority_fee);

            // If the public balance is insufficient, return an error.
            if public_balance < base_fee {
                bail!(
                    "The public balance of {} is insufficient to pay the base fee for `{}`",
                    public_balance,
                    locator.to_string().bold()
                );
            }
        }

        println!("✅ Created execution transaction for '{}'", locator.to_string().bold());

        // Determine if the transaction should be broadcast, stored, or displayed to the user.
        Developer::handle_transaction(
            &endpoint,
            &self.broadcast,
            self.dry_run,
            &self.store,
            self.store_format,
            self.wait,
            self.timeout,
            transaction,
            locator.to_string(),
        )
    }
}

/// A helper function to recursively load the program and all of its imports into the process.
fn load_program<N: Network>(
    query: &Query<N, BlockMemory<N>>,
    process: &mut Process<N>,
    program_id: &ProgramID<N>,
    endpoint: &Uri,
) -> Result<()> {
    // Fetch the program.
    let program = query.get_program(program_id).with_context(|| "Failed to fetch program")?;
    // Fetch the latest edition of the program.
    let edition = Developer::get_latest_edition(endpoint, program_id)
        .with_context(|| format!("Failed to get latest edition for program {program_id}"))?;

    // Return early if the program is already loaded.
    if process.contains_program(program.id()) {
        return Ok(());
    }

    // Iterate through the program imports.
    for import_program_id in program.imports().keys() {
        // Add the imports to the process if does not exist yet.
        if !process.contains_program(import_program_id) {
            // Recursively load the program and its imports.
            load_program(query, process, import_program_id, endpoint)
                .with_context(|| format!("Failed to load imported program {import_program_id}"))?;
        }
    }

    // Add the program to the process if it does not already exist.
    if !process.contains_program(program.id()) {
        debug!("Adding program {program_id} with edition {edition}");
        process
            .add_programs_with_editions(&[(program, edition)])
            .with_context(|| format!("Failed to add program {program_id}"))?;
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::commands::{CLI, Command, DeveloperCommand};

    #[test]
    fn clap_snarkos_execute() -> Result<()> {
        let arg_vec = &[
            "snarkos",
            "developer",
            "execute",
            "--private-key",
            "PRIVATE_KEY",
            "--endpoint=ENDPOINT",
            "--priority-fee",
            "77",
            "--record",
            "RECORD",
            "--dry-run",
            "hello.aleo",
            "hello",
            "1u32",
            "2u32",
        ];
        let cli = CLI::try_parse_from(arg_vec)?;

        let Command::Developer(developer) = cli.command else {
            bail!("Unexpected result of clap parsing!");
        };
        let DeveloperCommand::Execute(execute) = developer.command else {
            bail!("Unexpected result of clap parsing!");
        };

        assert_eq!(developer.network, 0);
        assert_eq!(execute.private_key, Some("PRIVATE_KEY".to_string()));
        assert_eq!(execute.endpoint, "ENDPOINT");
        assert_eq!(execute.priority_fee, 77);
        assert_eq!(execute.record, Some("RECORD".into()));
        assert_eq!(execute.program_id, "hello.aleo".to_string());
        assert_eq!(execute.function, "hello".to_string());
        assert_eq!(execute.inputs, vec!["1u32".to_string(), "2u32".to_string()]);

        Ok(())
    }

    #[test]
    fn clap_snarkos_execute_pk_file() -> Result<()> {
        let arg_vec = &[
            "snarkos",
            "developer",
            "execute",
            "--private-key-file",
            "PRIVATE_KEY_FILE",
            "--endpoint=ENDPOINT",
            "--record",
            "RECORD",
            "--dry-run",
            "hello.aleo",
            "hello",
            "1u32",
            "2u32",
        ];
        let cli = CLI::try_parse_from(arg_vec)?;

        let Command::Developer(developer) = cli.command else {
            bail!("Unexpected result of clap parsing!");
        };
        let DeveloperCommand::Execute(execute) = developer.command else {
            bail!("Unexpected result of clap parsing!");
        };

        assert_eq!(developer.network, 0);
        assert_eq!(execute.private_key_file, Some("PRIVATE_KEY_FILE".to_string()));
        assert_eq!(execute.endpoint, "ENDPOINT");
        assert_eq!(execute.priority_fee, 0); // Default value.
        assert_eq!(execute.record, Some("RECORD".into()));
        assert_eq!(execute.program_id, "hello.aleo".to_string());
        assert_eq!(execute.function, "hello".to_string());
        assert_eq!(execute.inputs, vec!["1u32".to_string(), "2u32".to_string()]);

        Ok(())
    }

    #[test]
    fn clap_snarkos_execute_two_private_keys() {
        let arg_vec = &[
            "snarkos",
            "developer",
            "execute",
            "--private-key",
            "PRIVATE_KEY",
            "--private-key-file",
            "PRIVATE_KEY_FILE",
            "--endpoint=ENDPOINT",
            "--priority-fee",
            "77",
            "--record",
            "RECORD",
            "--dry-run",
            "hello.aleo",
            "hello",
            "1u32",
            "2u32",
        ];

        let err = CLI::try_parse_from(arg_vec).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::ArgumentConflict);
    }

    #[test]
    fn clap_snarkos_execute_no_private_keys() {
        let arg_vec = &[
            "snarkos",
            "developer",
            "execute",
            "--endpoint=ENDPOINT",
            "--priority-fee",
            "77",
            "--record",
            "RECORD",
            "--dry-run",
            "hello.aleo",
            "hello",
            "1u32",
            "2u32",
        ];

        let err = CLI::try_parse_from(arg_vec).unwrap_err();
        assert_eq!(err.kind(), clap::error::ErrorKind::MissingRequiredArgument);
    }
}