snarkos_cli/commands/developer/
transfer_private.rs

1// Copyright (c) 2019-2025 Provable Inc.
2// This file is part of the snarkOS library.
3
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at:
7
8// http://www.apache.org/licenses/LICENSE-2.0
9
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16use super::Developer;
17use snarkvm::{
18    console::network::{CanaryV0, MainnetV0, Network, TestnetV0},
19    prelude::{
20        Address,
21        Locator,
22        PrivateKey,
23        VM,
24        Value,
25        query::Query,
26        store::{ConsensusStore, helpers::memory::ConsensusMemory},
27    },
28};
29
30use aleo_std::StorageMode;
31use anyhow::{Result, bail};
32use clap::Parser;
33use std::{path::PathBuf, str::FromStr};
34use zeroize::Zeroize;
35
36/// Executes the `transfer_private` function in the `credits.aleo` program.
37#[derive(Debug, Parser)]
38pub struct TransferPrivate {
39    /// Specify the network to create a `transfer_private` for.
40    #[clap(default_value = "0", long = "network")]
41    pub network: u16,
42    /// The input record used to craft the transfer.
43    #[clap(long)]
44    input_record: String,
45    /// The recipient address.
46    #[clap(long)]
47    recipient: String,
48    /// The number of microcredits to transfer.
49    #[clap(long)]
50    amount: u64,
51    /// The private key used to generate the execution.
52    #[clap(short, long)]
53    private_key: String,
54    /// The endpoint to query node state from.
55    #[clap(short, long)]
56    query: String,
57    /// The priority fee in microcredits.
58    #[clap(long)]
59    priority_fee: u64,
60    /// The record to spend the fee from.
61    #[clap(long)]
62    fee_record: String,
63    /// The endpoint used to broadcast the generated transaction.
64    #[clap(short, long, conflicts_with = "dry_run")]
65    broadcast: Option<String>,
66    /// Performs a dry-run of transaction generation.
67    #[clap(short, long, conflicts_with = "broadcast")]
68    dry_run: bool,
69    /// Store generated deployment transaction to a local file.
70    #[clap(long)]
71    store: Option<String>,
72    /// Specify the path to a directory containing the ledger. Overrides the default path (also for
73    /// dev).
74    #[clap(long = "storage_path")]
75    pub storage_path: Option<PathBuf>,
76}
77
78impl Drop for TransferPrivate {
79    /// Zeroize the private key when the `TransferPrivate` struct goes out of scope.
80    fn drop(&mut self) {
81        self.private_key.zeroize();
82    }
83}
84
85impl TransferPrivate {
86    /// Creates an Aleo transfer with the provided inputs.
87    #[allow(clippy::format_in_format_args)]
88    pub fn parse(self) -> Result<String> {
89        // Ensure that the user has specified an action.
90        if !self.dry_run && self.broadcast.is_none() && self.store.is_none() {
91            bail!("❌ Please specify one of the following actions: --broadcast, --dry-run, --store");
92        }
93
94        // Construct the transfer for the specified network.
95        match self.network {
96            MainnetV0::ID => self.construct_transfer_private::<MainnetV0>(),
97            TestnetV0::ID => self.construct_transfer_private::<TestnetV0>(),
98            CanaryV0::ID => self.construct_transfer_private::<CanaryV0>(),
99            unknown_id => bail!("Unknown network ID ({unknown_id})"),
100        }
101    }
102
103    /// Construct and process the `transfer_private` transaction.
104    fn construct_transfer_private<N: Network>(&self) -> Result<String> {
105        // Specify the query
106        let query = Query::from(&self.query);
107
108        // Retrieve the recipient.
109        let recipient = Address::<N>::from_str(&self.recipient)?;
110
111        // Retrieve the private key.
112        let private_key = PrivateKey::from_str(&self.private_key)?;
113
114        println!("📦 Creating private transfer of {} microcredits to {}...\n", self.amount, recipient);
115
116        // Generate the transfer_private transaction.
117        let transaction = {
118            // Initialize an RNG.
119            let rng = &mut rand::thread_rng();
120
121            // Initialize the storage.
122            let storage_mode = match &self.storage_path {
123                Some(path) => StorageMode::Custom(path.clone()),
124                None => StorageMode::Production,
125            };
126            let store = ConsensusStore::<N, ConsensusMemory<N>>::open(storage_mode)?;
127
128            // Initialize the VM.
129            let vm = VM::from(store)?;
130
131            // Prepare the fee.
132            let fee_record = Developer::parse_record(&private_key, &self.fee_record)?;
133            let priority_fee = self.priority_fee;
134
135            // Prepare the inputs for a transfer.
136            let input_record = Developer::parse_record(&private_key, &self.input_record)?;
137            let inputs = [
138                Value::Record(input_record),
139                Value::from_str(&format!("{}", recipient))?,
140                Value::from_str(&format!("{}u64", self.amount))?,
141            ];
142
143            // Create a new transaction.
144            vm.execute(
145                &private_key,
146                ("credits.aleo", "transfer_private"),
147                inputs.iter(),
148                Some(fee_record),
149                priority_fee,
150                Some(query),
151                rng,
152            )?
153        };
154        let locator = Locator::<N>::from_str("credits.aleo/transfer_private")?;
155        println!("✅ Created private transfer of {} microcredits to {}\n", &self.amount, recipient);
156
157        // Determine if the transaction should be broadcast, stored, or displayed to the user.
158        Developer::handle_transaction(&self.broadcast, self.dry_run, &self.store, transaction, locator.to_string())
159    }
160}