leo_lang/cli/commands/
deploy.rs

1// Copyright (C) 2019-2025 Provable Inc.
2// This file is part of the Leo library.
3
4// The Leo 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 Leo 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 Leo library. If not, see <https://www.gnu.org/licenses/>.
16
17use super::*;
18
19use check_transaction::TransactionStatus;
20use leo_ast::NetworkName;
21use leo_package::{Package, ProgramData, fetch_program_from_network};
22
23use aleo_std::StorageMode;
24#[cfg(not(feature = "only_testnet"))]
25use snarkvm::prelude::{CanaryV0, MainnetV0};
26use snarkvm::{
27    ledger::{query::Query as SnarkVMQuery, store::helpers::memory::BlockMemory},
28    prelude::{
29        ConsensusVersion,
30        Deployment,
31        Program,
32        ProgramID,
33        TestnetV0,
34        VM,
35        deployment_cost,
36        store::{ConsensusStore, helpers::memory::ConsensusMemory},
37    },
38};
39
40use colored::*;
41use itertools::Itertools;
42use std::{collections::HashSet, fs, path::PathBuf};
43
44/// Deploys an Aleo program.
45#[derive(Parser, Debug)]
46pub struct LeoDeploy {
47    #[clap(flatten)]
48    pub(crate) fee_options: FeeOptions,
49    #[clap(flatten)]
50    pub(crate) action: TransactionAction,
51    #[clap(flatten)]
52    pub(crate) env_override: EnvOptions,
53    #[clap(flatten)]
54    pub(crate) extra: ExtraOptions,
55    #[clap(long, help = "Skips deployment of any program that contains one of the given substrings.", value_delimiter = ',', num_args = 1..)]
56    pub(crate) skip: Vec<String>,
57    #[clap(flatten)]
58    pub(crate) build_options: BuildOptions,
59}
60
61pub struct Task<N: Network> {
62    pub id: ProgramID<N>,
63    pub program: Program<N>,
64    pub edition: Option<u16>,
65    pub is_local: bool,
66    pub priority_fee: Option<u64>,
67    pub record: Option<Record<N, Plaintext<N>>>,
68}
69
70impl Command for LeoDeploy {
71    type Input = Package;
72    type Output = ();
73
74    fn log_span(&self) -> Span {
75        tracing::span!(tracing::Level::INFO, "Leo")
76    }
77
78    fn prelude(&self, context: Context) -> Result<Self::Input> {
79        LeoBuild {
80            env_override: self.env_override.clone(),
81            options: {
82                let mut options = self.build_options.clone();
83                options.no_cache = true;
84                options
85            },
86        }
87        .execute(context)
88    }
89
90    fn apply(self, context: Context, input: Self::Input) -> Result<Self::Output> {
91        // Get the network, accounting for overrides.
92        let network = get_network(&self.env_override.network)?;
93        // Handle each network with the appropriate parameterization.
94        match network {
95            NetworkName::TestnetV0 => handle_deploy::<TestnetV0>(&self, context, network, input),
96            NetworkName::MainnetV0 => {
97                #[cfg(feature = "only_testnet")]
98                panic!("Mainnet chosen with only_testnet feature");
99                #[cfg(not(feature = "only_testnet"))]
100                handle_deploy::<MainnetV0>(&self, context, network, input)
101            }
102            NetworkName::CanaryV0 => {
103                #[cfg(feature = "only_testnet")]
104                panic!("Canary chosen with only_testnet feature");
105                #[cfg(not(feature = "only_testnet"))]
106                handle_deploy::<CanaryV0>(&self, context, network, input)
107            }
108        }
109    }
110}
111
112// A helper function to handle deployment logic.
113fn handle_deploy<N: Network>(
114    command: &LeoDeploy,
115    context: Context,
116    network: NetworkName,
117    package: Package,
118) -> Result<<LeoDeploy as Command>::Output> {
119    // Get the private key and associated address, accounting for overrides.
120    let private_key = get_private_key(&command.env_override.private_key)?;
121    let address =
122        Address::try_from(&private_key).map_err(|e| CliError::custom(format!("Failed to parse address: {e}")))?;
123
124    // Get the endpoint, accounting for overrides.
125    let endpoint = get_endpoint(&command.env_override.endpoint)?;
126
127    // Get whether the network is a devnet, accounting for overrides.
128    let is_devnet = get_is_devnet(command.env_override.devnet);
129
130    // If the consensus heights are provided, use them; otherwise, use the default heights for the network.
131    let consensus_heights =
132        command.env_override.consensus_heights.clone().unwrap_or_else(|| get_consensus_heights(network, is_devnet));
133    // Validate the provided consensus heights.
134    validate_consensus_heights(&consensus_heights)
135        .map_err(|e| CliError::custom(format!("⚠️ Invalid consensus heights: {e}")))?;
136    // Print the consensus heights being used.
137    let consensus_heights_string = consensus_heights.iter().format(",").to_string();
138    println!(
139        "\nπŸ“’ Using the following consensus heights: {consensus_heights_string}\n  To override, pass in `--consensus-heights` or override the environment variable `CONSENSUS_VERSION_HEIGHTS`.\n"
140    );
141
142    // Set the consensus heights in the environment.
143    #[allow(unsafe_code)]
144    unsafe {
145        // SAFETY:
146        //  - `CONSENSUS_VERSION_HEIGHTS` is only set once and is only read in `snarkvm::prelude::load_consensus_heights`.
147        //  - There are no concurrent threads running at this point in the execution.
148        // WHY:
149        //  - This is needed because there is no way to set the desired consensus heights for a particular `VM` instance
150        //    without using the environment variable `CONSENSUS_VERSION_HEIGHTS`. Which is itself read once, and stored in a `OnceLock`.
151        std::env::set_var("CONSENSUS_VERSION_HEIGHTS", consensus_heights_string);
152    }
153
154    // Get all the programs but tests.
155    let programs = package.programs.iter().filter(|program| !program.is_test).cloned();
156
157    let programs_and_bytecode: Vec<(leo_package::Program, String)> = programs
158        .into_iter()
159        .map(|program| {
160            let bytecode = match &program.data {
161                ProgramData::Bytecode(s) => s.clone(),
162                ProgramData::SourcePath { .. } => {
163                    // We need to read the bytecode from the filesystem.
164                    let aleo_name = format!("{}.aleo", program.name);
165                    let aleo_path = if package.manifest.program == aleo_name {
166                        // The main program in the package, so its .aleo file
167                        // will be in the build directory.
168                        package.build_directory().join("main.aleo")
169                    } else {
170                        // Some other dependency, so look in `imports`.
171                        package.imports_directory().join(aleo_name)
172                    };
173                    fs::read_to_string(aleo_path.clone())
174                        .map_err(|e| CliError::custom(format!("Failed to read file {}: {e}", aleo_path.display())))?
175                }
176            };
177
178            Ok((program, bytecode))
179        })
180        .collect::<Result<_>>()?;
181
182    // Parse the fee options.
183    let fee_options = parse_fee_options(&private_key, &command.fee_options, programs_and_bytecode.len())?;
184
185    let tasks: Vec<Task<N>> = programs_and_bytecode
186        .into_iter()
187        .zip(fee_options)
188        .map(|((program, bytecode), (_base_fee, priority_fee, record))| {
189            let id_str = format!("{}.aleo", program.name);
190            let id =
191                id_str.parse().map_err(|e| CliError::custom(format!("Failed to parse program ID {id_str}: {e}")))?;
192            let bytecode = bytecode.parse().map_err(|e| CliError::custom(format!("Failed to parse program: {e}")))?;
193            Ok(Task {
194                id,
195                program: bytecode,
196                edition: program.edition,
197                is_local: program.is_local,
198                priority_fee,
199                record,
200            })
201        })
202        .collect::<Result<_>>()?;
203
204    // Split the tasks into local and remote dependencies.
205    let (local, remote) = tasks.into_iter().partition::<Vec<_>, _>(|task| task.is_local);
206
207    // Get the skipped programs.
208    let skipped: HashSet<ProgramID<N>> = local
209        .iter()
210        .filter_map(|task| {
211            let id_string = task.id.to_string();
212            command.skip.iter().any(|skip| id_string.contains(skip)).then_some(task.id)
213        })
214        .collect();
215
216    // Get the consensus version.
217    let consensus_version =
218        get_consensus_version(&command.extra.consensus_version, &endpoint, network, &consensus_heights, &context)?;
219
220    // Print a summary of the deployment plan.
221    print_deployment_plan(
222        &private_key,
223        &address,
224        &endpoint,
225        &network,
226        &local,
227        &skipped,
228        &remote,
229        &check_tasks_for_warnings(&endpoint, network, &local, consensus_version, command),
230        consensus_version,
231        command,
232    );
233
234    // Prompt the user to confirm the plan.
235    if !confirm("Do you want to proceed with deployment?", command.extra.yes)? {
236        println!("❌ Deployment aborted.");
237        return Ok(());
238    }
239
240    // Initialize an RNG.
241    let rng = &mut rand::thread_rng();
242
243    // Initialize a new VM.
244    let vm = VM::from(ConsensusStore::<N, ConsensusMemory<N>>::open(StorageMode::Production)?)?;
245
246    // Load the remote dependencies into the VM.
247    let programs_and_editions = remote
248        .into_iter()
249        .map(|task| {
250            // Note: We default to edition 1 since snarkVM execute may produce spurious errors if the program does not have a constructor but uses edition 0.
251            (task.program, task.edition.unwrap_or(1))
252        })
253        .collect::<Vec<_>>();
254    vm.process().write().add_programs_with_editions(&programs_and_editions)?;
255
256    // Specify the query
257    let query = SnarkVMQuery::<N, BlockMemory<N>>::from(
258        endpoint
259            .parse::<Uri>()
260            .map_err(|e| CliError::custom(format!("Failed to parse endpoint URI '{endpoint}': {e}")))?,
261    );
262
263    // For each of the programs, generate a deployment transaction.
264    let mut transactions = Vec::new();
265    for Task { id, program, priority_fee, record, .. } in local {
266        // If the program is a local dependency that is not skipped, generate a deployment transaction.
267        if !skipped.contains(&id) {
268            // If the program contains an upgrade config, confirm with the user that they want to proceed.
269            if let Some(constructor) = program.constructor() {
270                println!(
271                    r"
272πŸ”§ Your program '{}' has the following constructor.
273──────────────────────────────────────────────
274{constructor}
275──────────────────────────────────────────────
276Once it is deployed, it CANNOT be changed.
277",
278                    id.to_string().bold()
279                );
280                if !confirm("Would you like to proceed?", command.extra.yes)? {
281                    println!("❌ Deployment aborted.");
282                    return Ok(());
283                }
284            }
285            println!("πŸ“¦ Creating deployment transaction for '{}'...\n", id.to_string().bold());
286            // Generate the transaction.
287            let transaction =
288                vm.deploy(&private_key, &program, record, priority_fee.unwrap_or(0), Some(&query), rng)
289                    .map_err(|e| CliError::custom(format!("Failed to generate deployment transaction: {e}")))?;
290            // Get the deployment.
291            let deployment = transaction.deployment().expect("Expected a deployment in the transaction");
292            // Print the deployment stats.
293            print_deployment_stats(&vm, &id.to_string(), deployment, priority_fee, consensus_version)?;
294            // Save the transaction.
295            transactions.push((id, transaction));
296        }
297        // Add the program to the VM.
298        vm.process().write().add_program(&program)?;
299    }
300
301    for (program_id, transaction) in transactions.iter() {
302        // Validate the deployment limits.
303        let deployment = transaction.deployment().expect("Expected a deployment in the transaction");
304        validate_deployment_limits(deployment, program_id, &network)?;
305    }
306
307    // If the `print` option is set, print the deployment transaction to the console.
308    // The transaction is printed in JSON format.
309    if command.action.print {
310        for (program_name, transaction) in transactions.iter() {
311            // Pretty-print the transaction.
312            let transaction_json = serde_json::to_string_pretty(transaction)
313                .map_err(|e| CliError::custom(format!("Failed to serialize transaction: {e}")))?;
314            println!("πŸ–¨οΈ Printing deployment for {program_name}\n{transaction_json}")
315        }
316    }
317
318    // If the `save` option is set, save each deployment transaction to a file in the specified directory.
319    // The file format is `program_name.deployment.json`.
320    // The directory is created if it doesn't exist.
321    if let Some(path) = &command.action.save {
322        // Create the directory if it doesn't exist.
323        std::fs::create_dir_all(path).map_err(|e| CliError::custom(format!("Failed to create directory: {e}")))?;
324        for (program_name, transaction) in transactions.iter() {
325            // Save the transaction to a file.
326            let file_path = PathBuf::from(path).join(format!("{program_name}.deployment.json"));
327            println!("πŸ’Ύ Saving deployment for {program_name} at {}", file_path.display());
328            let transaction_json = serde_json::to_string_pretty(transaction)
329                .map_err(|e| CliError::custom(format!("Failed to serialize transaction: {e}")))?;
330            std::fs::write(file_path, transaction_json)
331                .map_err(|e| CliError::custom(format!("Failed to write transaction to file: {e}")))?;
332        }
333    }
334
335    // If the `broadcast` option is set, broadcast each deployment transaction to the network.
336    if command.action.broadcast {
337        for (i, (program_id, transaction)) in transactions.iter().enumerate() {
338            println!("\nπŸ“‘ Broadcasting deployment for {}...", program_id.to_string().bold());
339            // Get and confirm the fee with the user.
340            let fee = transaction.fee_transition().expect("Expected a fee in the transaction");
341            if !confirm_fee(&fee, &private_key, &address, &endpoint, network, &context, command.extra.yes)? {
342                println!("⏩ Deployment skipped.");
343                continue;
344            }
345            let fee_id = fee.id().to_string();
346            let id = transaction.id().to_string();
347            let height_before = check_transaction::current_height(&endpoint, network)?;
348            // Broadcast the transaction to the network.
349            let (message, status) = handle_broadcast(
350                &format!("{endpoint}/{network}/transaction/broadcast"),
351                transaction,
352                &program_id.to_string(),
353            )?;
354
355            let fail_and_prompt = |msg| {
356                println!("❌ Failed to deploy program {program_id}: {msg}.");
357                let count = transactions.len() - i - 1;
358                // Check if the user wants to continue with the next deployment.
359                if count > 0 {
360                    confirm("Do you want to continue with the next deployment?", command.extra.yes)
361                } else {
362                    Ok(false)
363                }
364            };
365
366            match status {
367                200..=299 => {
368                    let status = check_transaction::check_transaction_with_message(
369                        &id,
370                        Some(&fee_id),
371                        &endpoint,
372                        network,
373                        height_before + 1,
374                        command.extra.max_wait,
375                        command.extra.blocks_to_check,
376                    )?;
377                    if status == Some(TransactionStatus::Accepted) {
378                        println!("βœ… Deployment confirmed!");
379                    } else if fail_and_prompt("could not find the transaction on the network")? {
380                        continue;
381                    } else {
382                        return Ok(());
383                    }
384                }
385                _ => {
386                    if fail_and_prompt(&message)? {
387                        continue;
388                    } else {
389                        return Ok(());
390                    }
391                }
392            }
393        }
394    }
395
396    Ok(())
397}
398
399/// Check the tasks to warn the user about any potential issues.
400/// The following properties are checked:
401/// - If the transaction is to be broadcast:
402///     - The program does not exist on the network.
403///     - If the consensus version is less than V9, the program does not use V9 features.
404///     - If the consensus version is V9 or greater, the program contains a constructor.
405fn check_tasks_for_warnings<N: Network>(
406    endpoint: &str,
407    network: NetworkName,
408    tasks: &[Task<N>],
409    consensus_version: ConsensusVersion,
410    command: &LeoDeploy,
411) -> Vec<String> {
412    let mut warnings = Vec::new();
413    for Task { id, is_local, program, .. } in tasks {
414        if !is_local || !command.action.broadcast {
415            continue;
416        }
417        // Check if the program exists on the network.
418        if fetch_program_from_network(&id.to_string(), endpoint, network).is_ok() {
419            warnings
420                .push(format!("The program '{id}' already exists on the network. Please use `leo upgrade` instead.",));
421        }
422        // Check if the program has a valid naming scheme.
423        if consensus_version >= ConsensusVersion::V7 {
424            if let Err(e) = program.check_program_naming_structure() {
425                warnings.push(format!(
426                    "The program '{id}' has an invalid naming scheme: {e}. The deployment will likely fail."
427                ));
428            }
429        }
430
431        // Check if the program contains restricted keywords.
432        if let Err(e) = program.check_restricted_keywords_for_consensus_version(consensus_version) {
433            warnings.push(format!(
434                "The program '{id}' contains restricted keywords for consensus version {}: {e}. The deployment will likely fail.",
435                consensus_version as u8
436            ));
437        }
438        // Check if the program uses V9 features.
439        if consensus_version < ConsensusVersion::V9 && program.contains_v9_syntax() {
440            warnings.push(format!("The program '{id}' uses V9 features but the consensus version is less than V9. The deployment will likely fail"));
441        }
442        // Check if the program contains a constructor.
443        if consensus_version >= ConsensusVersion::V9 && !program.contains_constructor() {
444            warnings
445                .push(format!("The program '{id}' does not contain a constructor. The deployment will likely fail",));
446        }
447    }
448    // Check for a consensus version mismatch.
449    if let Err(e) = check_consensus_version_mismatch(consensus_version, endpoint, network) {
450        warnings.push(format!("{e}. In some cases, the deployment may fail"));
451    }
452    warnings
453}
454
455/// Check if the number of variables and constraints are within the limits.
456pub(crate) fn validate_deployment_limits<N: Network>(
457    deployment: &Deployment<N>,
458    program_id: &ProgramID<N>,
459    network: &NetworkName,
460) -> Result<()> {
461    // Check if the number of variables is within the limits.
462    let combined_variables = deployment.num_combined_variables()?;
463    if combined_variables > N::MAX_DEPLOYMENT_VARIABLES {
464        return Err(CliError::variable_limit_exceeded(
465            program_id,
466            combined_variables,
467            N::MAX_DEPLOYMENT_VARIABLES,
468            network,
469        )
470        .into());
471    }
472
473    // Check if the number of constraints is within the limits.
474    let constraints = deployment.num_combined_constraints()?;
475    if constraints > N::MAX_DEPLOYMENT_CONSTRAINTS {
476        return Err(CliError::constraint_limit_exceeded(
477            program_id,
478            constraints,
479            N::MAX_DEPLOYMENT_CONSTRAINTS,
480            network,
481        )
482        .into());
483    }
484
485    Ok(())
486}
487
488/// Pretty‑print the deployment plan without using a table.
489#[allow(clippy::too_many_arguments)]
490pub(crate) fn print_deployment_plan<N: Network>(
491    private_key: &PrivateKey<N>,
492    address: &Address<N>,
493    endpoint: &str,
494    network: &NetworkName,
495    local: &[Task<N>],
496    skipped: &HashSet<ProgramID<N>>,
497    remote: &[Task<N>],
498    warnings: &[String],
499    consensus_version: ConsensusVersion,
500    command: &LeoDeploy,
501) {
502    use colored::*;
503
504    println!("\n{}", "πŸ› οΈ  Deployment Plan Summary".bold());
505    println!("{}", "──────────────────────────────────────────────".dimmed());
506
507    // ── Configuration ────────────────────────────────────────────────────
508    println!("{}", "πŸ”§ Configuration:".bold());
509    println!("  {:20}{}", "Private Key:".cyan(), format!("{}...", &private_key.to_string()[..24]).yellow());
510    println!("  {:20}{}", "Address:".cyan(), format!("{}...", &address.to_string()[..24]).yellow());
511    println!("  {:20}{}", "Endpoint:".cyan(), endpoint.yellow());
512    println!("  {:20}{}", "Network:".cyan(), network.to_string().yellow());
513    println!("  {:20}{}", "Consensus Version:".cyan(), (consensus_version as u8).to_string().yellow());
514
515    // ── Deployment tasks (bullet list) ───────────────────────────────────
516    println!("\n{}", "πŸ“¦ Deployment Tasks:".bold());
517    if local.is_empty() {
518        println!("  (none)");
519    } else {
520        for Task { id, priority_fee, record, .. } in local.iter().filter(|task| !skipped.contains(&task.id)) {
521            let priority_fee_str = priority_fee.map_or("0".into(), |v| v.to_string());
522            let record_str = if record.is_some() { "yes" } else { "no (public fee)" };
523            println!(
524                "  β€’ {}  β”‚ priority fee: {}  β”‚ fee record: {}",
525                id.to_string().cyan(),
526                priority_fee_str,
527                record_str
528            );
529        }
530    }
531
532    // ── Skipped programs ─────────────────────────────────────────────────
533    if !skipped.is_empty() {
534        println!("\n{}", "🚫 Skipped Programs:".bold().red());
535        for symbol in skipped {
536            println!("  β€’ {}", symbol.to_string().dimmed());
537        }
538    }
539
540    // ── Remote dependencies ──────────────────────────────────────────────
541    if !remote.is_empty() {
542        println!("\n{}", "🌐 Remote Dependencies:".bold().red());
543        println!("{}", "(Leo will not generate transactions for these programs)".bold().red());
544        for Task { id, .. } in remote {
545            println!("  β€’ {}", id.to_string().dimmed());
546        }
547    }
548
549    // ── Actions ──────────────────────────────────────────────────────────
550    println!("\n{}", "βš™οΈ Actions:".bold());
551    if command.action.print {
552        println!("  β€’ Transaction(s) will be printed to the console.");
553    } else {
554        println!("  β€’ Transaction(s) will NOT be printed to the console.");
555    }
556    if let Some(path) = &command.action.save {
557        println!("  β€’ Transaction(s) will be saved to {}", path.bold());
558    } else {
559        println!("  β€’ Transaction(s) will NOT be saved to a file.");
560    }
561    if command.action.broadcast {
562        println!("  β€’ Transaction(s) will be broadcast to {}", endpoint.bold());
563    } else {
564        println!("  β€’ Transaction(s) will NOT be broadcast to the network.");
565    }
566
567    // ── Warnings ─────────────────────────────────────────────────────────
568    if !warnings.is_empty() {
569        println!("\n{}", "⚠️ Warnings:".bold().red());
570        for warning in warnings {
571            println!("  β€’ {}", warning.dimmed());
572        }
573    }
574
575    println!("{}", "──────────────────────────────────────────────\n".dimmed());
576}
577
578/// Pretty‑print deployment statistics without a table, using the same UI
579/// conventions as `print_deployment_plan`.
580pub(crate) fn print_deployment_stats<N: Network>(
581    vm: &VM<N, ConsensusMemory<N>>,
582    program_id: &str,
583    deployment: &Deployment<N>,
584    priority_fee: Option<u64>,
585    consensus_version: ConsensusVersion,
586) -> Result<()> {
587    use colored::*;
588    use num_format::{Locale, ToFormattedString};
589
590    // ── Collect statistics ────────────────────────────────────────────────
591    let variables = deployment.num_combined_variables()?;
592    let constraints = deployment.num_combined_constraints()?;
593    let (base_fee, (storage_cost, synthesis_cost, constructor_cost, namespace_cost)) =
594        deployment_cost(&vm.process().read(), deployment, consensus_version)?;
595
596    let base_fee_cr = base_fee as f64 / 1_000_000.0;
597    let prio_fee_cr = priority_fee.unwrap_or(0) as f64 / 1_000_000.0;
598    let total_fee_cr = base_fee_cr + prio_fee_cr;
599
600    // ── Header ────────────────────────────────────────────────────────────
601    println!("\n{} {}", "πŸ“Š Deployment Summary for".bold(), program_id.bold());
602    println!("{}", "──────────────────────────────────────────────".dimmed());
603
604    // ── High‑level metrics ────────────────────────────────────────────────
605    println!("  {:22}{}", "Total Variables:".cyan(), variables.to_formatted_string(&Locale::en).yellow());
606    println!("  {:22}{}", "Total Constraints:".cyan(), constraints.to_formatted_string(&Locale::en).yellow());
607    println!(
608        "  {:22}{}",
609        "Max Variables:".cyan(),
610        N::MAX_DEPLOYMENT_VARIABLES.to_formatted_string(&Locale::en).green()
611    );
612    println!(
613        "  {:22}{}",
614        "Max Constraints:".cyan(),
615        N::MAX_DEPLOYMENT_CONSTRAINTS.to_formatted_string(&Locale::en).green()
616    );
617
618    // ── Cost breakdown ────────────────────────────────────────────────────
619    println!("\n{}", "πŸ’° Cost Breakdown (credits)".bold());
620    println!(
621        "  {:22}{}{:.6}",
622        "Transaction Storage:".cyan(),
623        "".yellow(), // spacer for alignment
624        storage_cost as f64 / 1_000_000.0
625    );
626    println!("  {:22}{}{:.6}", "Program Synthesis:".cyan(), "".yellow(), synthesis_cost as f64 / 1_000_000.0);
627    println!("  {:22}{}{:.6}", "Namespace:".cyan(), "".yellow(), namespace_cost as f64 / 1_000_000.0);
628    println!("  {:22}{}{:.6}", "Constructor:".cyan(), "".yellow(), constructor_cost as f64 / 1_000_000.0);
629    println!("  {:22}{}{:.6}", "Priority Fee:".cyan(), "".yellow(), prio_fee_cr);
630    println!("  {:22}{}{:.6}", "Total Fee:".cyan(), "".yellow(), total_fee_cr);
631
632    // ── Footer rule ───────────────────────────────────────────────────────
633    println!("{}", "──────────────────────────────────────────────".dimmed());
634    Ok(())
635}