soroban_cli/commands/
mod.rs

1use std::str::FromStr;
2
3use async_trait::async_trait;
4use clap::{command, error::ErrorKind, CommandFactory, FromArgMatches, Parser};
5
6use crate::config;
7
8pub mod cache;
9pub mod cfg;
10pub mod completion;
11pub mod container;
12pub mod contract;
13pub mod doctor;
14pub mod env;
15pub mod events;
16pub mod fee_stats;
17pub mod global;
18pub mod keys;
19pub mod ledger;
20pub mod network;
21pub mod plugin;
22pub mod snapshot;
23pub mod tx;
24pub mod version;
25
26pub mod txn_result;
27
28pub const HEADING_RPC: &str = "Options (RPC)";
29pub const HEADING_ARCHIVE: &str = "Options (Archive)";
30pub const HEADING_GLOBAL: &str = "Options (Global)";
31const ABOUT: &str =
32    "Work seamlessly with Stellar accounts, contracts, and assets from the command line.
33
34- Generate and manage keys and accounts
35- Build, deploy, and interact with contracts
36- Deploy asset contracts
37- Stream events
38- Start local testnets
39- Decode, encode XDR
40- More!
41
42For additional information see:
43
44- Stellar Docs: https://developers.stellar.org
45- Smart Contract Docs: https://developers.stellar.org/docs/build/smart-contracts/overview
46- CLI Docs: https://developers.stellar.org/docs/tools/developer-tools/cli/stellar-cli";
47
48// long_about is shown when someone uses `--help`; short help when using `-h`
49const LONG_ABOUT: &str = "
50
51To get started generate a new identity:
52
53    stellar keys generate alice
54
55Use keys with the `--source` flag in other commands.
56
57Commands that work with contracts are organized under the `contract` subcommand. List them:
58
59    stellar contract --help
60
61Use contracts like a CLI:
62
63    stellar contract invoke --id CCR6QKTWZQYW6YUJ7UP7XXZRLWQPFRV6SWBLQS4ZQOSAF4BOUD77OTE2 --source alice --network testnet -- --help
64
65Anything after the `--` double dash (the \"slop\") is parsed as arguments to the contract-specific CLI, generated on-the-fly from the contract schema. For the hello world example, with a function called `hello` that takes one string argument `to`, here's how you invoke it:
66
67    stellar contract invoke --id CCR6QKTWZQYW6YUJ7UP7XXZRLWQPFRV6SWBLQS4ZQOSAF4BOUD77OTE2 --source alice --network testnet -- hello --to world
68";
69
70#[derive(Parser, Debug)]
71#[command(
72    name = "stellar",
73    about = ABOUT,
74    version = version::long(),
75    long_about = ABOUT.to_string() + LONG_ABOUT,
76    disable_help_subcommand = true,
77)]
78pub struct Root {
79    #[clap(flatten)]
80    pub global_args: global::Args,
81
82    #[command(subcommand)]
83    pub cmd: Cmd,
84}
85
86impl Root {
87    pub fn new() -> Result<Self, Error> {
88        Self::try_parse().map_err(|e| {
89            if std::env::args().any(|s| s == "--list") {
90                let _ = plugin::ls::Cmd.run();
91                std::process::exit(0);
92            }
93
94            match e.kind() {
95                ErrorKind::InvalidSubcommand => match plugin::default::run() {
96                    Ok(()) => Error::Clap(e),
97                    Err(e) => Error::PluginDefault(e),
98                },
99                _ => Error::Clap(e),
100            }
101        })
102    }
103
104    pub fn from_arg_matches<I, T>(itr: I) -> Result<Self, clap::Error>
105    where
106        I: IntoIterator<Item = T>,
107        T: Into<std::ffi::OsString> + Clone,
108    {
109        Self::from_arg_matches_mut(&mut Self::command().get_matches_from(itr))
110    }
111
112    pub async fn run(&mut self) -> Result<(), Error> {
113        match &mut self.cmd {
114            Cmd::Completion(completion) => completion.run(),
115            Cmd::Plugin(plugin) => plugin.run(&self.global_args).await?,
116            Cmd::Contract(contract) => contract.run(&self.global_args).await?,
117            Cmd::Doctor(doctor) => doctor.run(&self.global_args).await?,
118            Cmd::Config(config) => config.run()?,
119            Cmd::Events(events) => events.run().await?,
120            Cmd::Xdr(xdr) => xdr.run()?,
121            Cmd::Network(network) => network.run(&self.global_args).await?,
122            Cmd::Container(container) => container.run(&self.global_args).await?,
123            Cmd::Snapshot(snapshot) => snapshot.run(&self.global_args).await?,
124            Cmd::Version(version) => version.run(),
125            Cmd::Keys(id) => id.run(&self.global_args).await?,
126            Cmd::Tx(tx) => tx.run(&self.global_args).await?,
127            Cmd::Cache(cache) => cache.run()?,
128            Cmd::Env(env) => env.run(&self.global_args)?,
129            Cmd::Ledger(env) => env.run(&self.global_args).await?,
130            Cmd::FeeStats(env) => env.run(&self.global_args).await?,
131        }
132        Ok(())
133    }
134}
135
136impl FromStr for Root {
137    type Err = clap::Error;
138
139    fn from_str(s: &str) -> Result<Self, Self::Err> {
140        Self::from_arg_matches(s.split_whitespace())
141    }
142}
143
144#[derive(Parser, Debug)]
145pub enum Cmd {
146    /// Tools for smart contract developers
147    #[command(subcommand)]
148    Contract(contract::Cmd),
149
150    /// Diagnose and troubleshoot CLI and network issues
151    Doctor(doctor::Cmd),
152
153    /// Watch the network for contract events
154    Events(events::Cmd),
155
156    /// Prints the environment variables
157    ///
158    /// Prints to stdout in a format that can be used as .env file. Environment
159    /// variables have precedence over defaults.
160    ///
161    /// Pass a name to get the value of a single environment variable.
162    ///
163    /// If there are no environment variables in use, prints the defaults.
164    Env(env::Cmd),
165
166    /// Create and manage identities including keys and addresses
167    #[command(subcommand)]
168    Keys(keys::Cmd),
169
170    /// Configure connection to networks
171    #[command(subcommand)]
172    Network(network::Cmd),
173
174    /// Start local networks in containers
175    #[command(subcommand)]
176    Container(container::Cmd),
177
178    /// Manage cli configuration
179    #[command(subcommand)]
180    Config(cfg::Cmd),
181
182    /// Download a snapshot of a ledger from an archive.
183    #[command(subcommand)]
184    Snapshot(snapshot::Cmd),
185
186    /// Sign, Simulate, and Send transactions
187    #[command(subcommand)]
188    Tx(tx::Cmd),
189
190    /// Decode and encode XDR
191    Xdr(stellar_xdr::cli::Root),
192
193    /// Print shell completion code for the specified shell.
194    #[command(long_about = completion::LONG_ABOUT)]
195    Completion(completion::Cmd),
196
197    /// Cache for transactions and contract specs
198    #[command(subcommand)]
199    Cache(cache::Cmd),
200
201    /// Print version information
202    Version(version::Cmd),
203
204    /// The subcommand for CLI plugins
205    #[command(subcommand)]
206    Plugin(plugin::Cmd),
207
208    /// Fetch ledger information
209    #[command(subcommand)]
210    Ledger(ledger::Cmd),
211
212    /// Fetch network feestats
213    FeeStats(fee_stats::Cmd),
214}
215
216#[derive(thiserror::Error, Debug)]
217pub enum Error {
218    // TODO: stop using Debug for displaying errors
219    #[error(transparent)]
220    Contract(#[from] contract::Error),
221
222    #[error(transparent)]
223    Doctor(#[from] doctor::Error),
224
225    #[error(transparent)]
226    Events(#[from] events::Error),
227
228    #[error(transparent)]
229    Keys(#[from] keys::Error),
230
231    #[error(transparent)]
232    Xdr(#[from] stellar_xdr::cli::Error),
233
234    #[error(transparent)]
235    Clap(#[from] clap::error::Error),
236
237    #[error(transparent)]
238    Plugin(#[from] plugin::Error),
239
240    #[error(transparent)]
241    PluginDefault(#[from] plugin::default::Error),
242
243    #[error(transparent)]
244    Network(#[from] network::Error),
245
246    #[error(transparent)]
247    Container(#[from] container::Error),
248
249    #[error(transparent)]
250    Config(#[from] cfg::Error),
251
252    #[error(transparent)]
253    Snapshot(#[from] snapshot::Error),
254
255    #[error(transparent)]
256    Tx(#[from] tx::Error),
257
258    #[error(transparent)]
259    Cache(#[from] cache::Error),
260
261    #[error(transparent)]
262    Env(#[from] env::Error),
263
264    #[error(transparent)]
265    Ledger(#[from] ledger::Error),
266
267    #[error(transparent)]
268    FeeStats(#[from] fee_stats::Error),
269}
270
271#[async_trait]
272pub trait NetworkRunnable {
273    type Error;
274    type Result;
275
276    async fn run_against_rpc_server(
277        &self,
278        global_args: Option<&global::Args>,
279        config: Option<&config::Args>,
280    ) -> Result<Self::Result, Self::Error>;
281}