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