soroban_cli/config/
mod.rs

1use clap::{arg, command};
2use serde::{Deserialize, Serialize};
3use std::{
4    fs::{self, File},
5    io::Write,
6};
7
8use crate::{
9    print::Print,
10    signer,
11    xdr::{self, SequenceNumber, Transaction, TransactionEnvelope},
12    Pwd,
13};
14use network::Network;
15
16pub mod address;
17pub mod alias;
18pub mod data;
19pub mod key;
20pub mod locator;
21pub mod network;
22pub mod sc_address;
23pub mod secret;
24pub mod sign_with;
25pub mod upgrade_check;
26
27pub use address::UnresolvedMuxedAccount;
28pub use alias::UnresolvedContract;
29pub use sc_address::UnresolvedScAddress;
30
31#[derive(thiserror::Error, Debug)]
32pub enum Error {
33    #[error(transparent)]
34    Network(#[from] network::Error),
35    #[error(transparent)]
36    Secret(#[from] secret::Error),
37    #[error(transparent)]
38    Config(#[from] locator::Error),
39    #[error(transparent)]
40    Rpc(#[from] soroban_rpc::Error),
41    #[error(transparent)]
42    Signer(#[from] signer::Error),
43    #[error(transparent)]
44    StellarStrkey(#[from] stellar_strkey::DecodeError),
45    #[error(transparent)]
46    Address(#[from] address::Error),
47}
48
49#[derive(Debug, clap::Args, Clone, Default)]
50#[group(skip)]
51pub struct Args {
52    #[command(flatten)]
53    pub network: network::Args,
54
55    #[arg(long, short = 's', visible_alias = "source", env = "STELLAR_ACCOUNT")]
56    /// Account that where transaction originates from. Alias `source`.
57    /// Can be an identity (--source alice), a public key (--source GDKW...),
58    /// a muxed account (--source MDA…), a secret key (--source SC36…),
59    /// or a seed phrase (--source "kite urban…").
60    /// If `--build-only` or `--sim-only` flags were NOT provided, this key will also be used to
61    /// sign the final transaction. In that case, trying to sign with public key will fail.
62    pub source_account: UnresolvedMuxedAccount,
63
64    #[arg(long)]
65    /// If using a seed phrase, which hierarchical deterministic path to use, e.g. `m/44'/148'/{hd_path}`. Example: `--hd-path 1`. Default: `0`
66    pub hd_path: Option<usize>,
67
68    #[command(flatten)]
69    pub locator: locator::Args,
70}
71
72impl Args {
73    // TODO: Replace PublicKey with MuxedAccount once https://github.com/stellar/rs-stellar-xdr/pull/396 is merged.
74    pub async fn source_account(&self) -> Result<xdr::MuxedAccount, Error> {
75        Ok(self
76            .source_account
77            .resolve_muxed_account(&self.locator, self.hd_path)
78            .await?)
79    }
80
81    pub fn key_pair(&self) -> Result<ed25519_dalek::SigningKey, Error> {
82        let key = &self.source_account.resolve_secret(&self.locator)?;
83        Ok(key.key_pair(self.hd_path)?)
84    }
85
86    pub async fn sign_with_local_key(&self, tx: Transaction) -> Result<TransactionEnvelope, Error> {
87        self.sign(tx).await
88    }
89
90    #[allow(clippy::unused_async)]
91    pub async fn sign(&self, tx: Transaction) -> Result<TransactionEnvelope, Error> {
92        let key = &self.source_account.resolve_secret(&self.locator)?;
93        let signer = key.signer(self.hd_path, Print::new(false)).await?;
94        let network = &self.get_network()?;
95
96        Ok(signer.sign_tx(tx, network).await?)
97    }
98
99    pub async fn sign_soroban_authorizations(
100        &self,
101        tx: &Transaction,
102        signers: &[ed25519_dalek::SigningKey],
103    ) -> Result<Option<Transaction>, Error> {
104        let network = self.get_network()?;
105        let source_key = self.key_pair()?;
106        let client = network.rpc_client()?;
107        let latest_ledger = client.get_latest_ledger().await?.sequence;
108        let seq_num = latest_ledger + 60; // ~ 5 min
109        Ok(signer::sign_soroban_authorizations(
110            tx,
111            &source_key,
112            signers,
113            seq_num,
114            &network.network_passphrase,
115        )?)
116    }
117
118    pub fn get_network(&self) -> Result<Network, Error> {
119        Ok(self.network.get(&self.locator)?)
120    }
121
122    pub async fn next_sequence_number(
123        &self,
124        account: impl Into<xdr::AccountId>,
125    ) -> Result<SequenceNumber, Error> {
126        let network = self.get_network()?;
127        let client = network.rpc_client()?;
128        Ok((client
129            .get_account(&account.into().to_string())
130            .await?
131            .seq_num
132            .0
133            + 1)
134        .into())
135    }
136}
137
138impl Pwd for Args {
139    fn set_pwd(&mut self, pwd: &std::path::Path) {
140        self.locator.set_pwd(pwd);
141    }
142}
143
144#[derive(Debug, clap::Args, Clone, Default)]
145#[group(skip)]
146pub struct ArgsLocatorAndNetwork {
147    #[command(flatten)]
148    pub network: network::Args,
149
150    #[command(flatten)]
151    pub locator: locator::Args,
152}
153
154impl ArgsLocatorAndNetwork {
155    pub fn get_network(&self) -> Result<Network, Error> {
156        Ok(self.network.get(&self.locator)?)
157    }
158}
159
160#[derive(Serialize, Deserialize, Debug, Default)]
161pub struct Config {
162    pub defaults: Defaults,
163}
164
165#[derive(Serialize, Deserialize, Debug, Default)]
166pub struct Defaults {
167    pub network: Option<String>,
168    pub identity: Option<String>,
169}
170
171impl Config {
172    pub fn new() -> Result<Config, locator::Error> {
173        let path = locator::config_file()?;
174
175        if path.exists() {
176            let data = fs::read_to_string(&path).map_err(|_| locator::Error::FileRead { path })?;
177            Ok(toml::from_str(&data)?)
178        } else {
179            Ok(Config::default())
180        }
181    }
182
183    #[must_use]
184    pub fn set_network(mut self, s: &str) -> Self {
185        self.defaults.network = Some(s.to_string());
186        self
187    }
188
189    #[must_use]
190    pub fn set_identity(mut self, s: &str) -> Self {
191        self.defaults.identity = Some(s.to_string());
192        self
193    }
194
195    pub fn save(&self) -> Result<(), locator::Error> {
196        let toml_string = toml::to_string(&self)?;
197        let path = locator::config_file()?;
198        // Depending on the platform, this function may fail if the full directory path does not exist
199        let mut file = File::create(locator::ensure_directory(path)?)?;
200        file.write_all(toml_string.as_bytes())?;
201
202        Ok(())
203    }
204}