soroban_cli/commands/contract/alias/
add.rs1use std::fmt::Debug;
2
3use clap::{command, Parser};
4
5use crate::commands::{config::network, global};
6use crate::config::locator;
7use crate::print::Print;
8
9#[derive(Parser, Debug, Clone)]
10#[group(skip)]
11pub struct Cmd {
12 #[command(flatten)]
13 pub config_locator: locator::Args,
14
15 #[command(flatten)]
16 pub network: network::Args,
17
18 pub alias: String,
20
21 #[arg(long)]
23 pub overwrite: bool,
24
25 #[arg(long = "id")]
27 pub contract_id: stellar_strkey::Contract,
28}
29
30#[derive(thiserror::Error, Debug)]
31pub enum Error {
32 #[error(transparent)]
33 Locator(#[from] locator::Error),
34
35 #[error(transparent)]
36 Network(#[from] network::Error),
37
38 #[error(
39 "alias '{alias}' is already referencing contract '{contract}' on network '{network_passphrase}'"
40 )]
41 AlreadyExist {
42 alias: String,
43 network_passphrase: String,
44 contract: stellar_strkey::Contract,
45 },
46}
47
48impl Cmd {
49 pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
50 let print = Print::new(global_args.quiet);
51 let alias = &self.alias;
52 let network = self.network.get(&self.config_locator)?;
53 let network_passphrase = &network.network_passphrase;
54
55 let contract = self
56 .config_locator
57 .get_contract_id(&self.alias, network_passphrase)?;
58
59 if let Some(contract) = contract {
60 if contract != self.contract_id && !self.overwrite {
61 return Err(Error::AlreadyExist {
62 alias: alias.clone(),
63 network_passphrase: network_passphrase.clone(),
64 contract,
65 });
66 }
67 }
68
69 print.infoln(format!(
70 "Contract alias '{alias}' will reference {contract} on network '{network_passphrase}'",
71 contract = self.contract_id
72 ));
73
74 self.config_locator.save_contract_id(
75 &network.network_passphrase,
76 &self.contract_id,
77 alias,
78 )?;
79
80 print.checkln(format!("Contract alias '{alias}' has been added"));
81
82 Ok(())
83 }
84}