Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions FULL_HELP_DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,6 +266,18 @@ List all aliases

- `--config-dir <CONFIG_DIR>` — Location of config directory. By default, it uses `$XDG_CONFIG_HOME/stellar` if set, falling back to `~/.config/stellar` otherwise. Contains configuration files, aliases, and other persistent settings

###### **Options:**

- `--network <NETWORK>` — Name of the configured network to list
- `--output <OUTPUT>` — Format of the output

Default value: `text`

Possible values:
- `text`: Human-readable alias listing
- `json`: Compact JSON grouped by network passphrase
- `json-formatted`: Indented JSON grouped by network passphrase

## `stellar contract bindings`

Generate code client bindings for a contract
Expand Down
49 changes: 49 additions & 0 deletions cmd/crates/soroban-test/tests/it/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1121,6 +1121,55 @@ fn alias_ls_always_shows_builtin_native() {
});
}

#[test]
fn alias_ls_json_is_sorted_and_can_filter_by_network() {
TestEnv::with_default(|sandbox| {
let contract = "CA3D5KRYM6CB7OWQ6TWYRR3Z4T7GNZLKERYNZGGA5SOAOPIFY6YQGAXE";
for alias in ["z-token", "a-token"] {
sandbox
.new_assert_cmd("contract")
.args(["alias", "add", alias, "--id", contract])
.assert()
.success();
}
let list = |args: &[&str]| {
sandbox
.new_assert_cmd("contract")
.args(["alias", "ls", "--output", "json"])
.args(args)
.assert()
.success()
.stdout_as_str()
};

let all = list(&[]);
assert_eq!(all, list(&[]));
let all: serde_json::Value = serde_json::from_str(&all).unwrap();
let filtered = list(&["--network", "local"]);
let filtered: serde_json::Value = serde_json::from_str(&filtered).unwrap();
assert!(all.get(MAINNET).is_some());
assert_eq!(
filtered,
serde_json::json!({ (LOCAL_NETWORK_PASSPHRASE): all[LOCAL_NETWORK_PASSPHRASE] })
);

let aliases = filtered[LOCAL_NETWORK_PASSPHRASE].as_array().unwrap();
assert_eq!(aliases.len(), 3);
assert_eq!(
aliases[0],
serde_json::json!({
"alias": "a-token",
"contract": contract,
"builtin": false,
"disabled": false
})
);
assert_eq!(aliases[1]["alias"], "native");
assert_eq!(aliases[1]["builtin"], true);
assert_eq!(aliases[2]["alias"], "z-token");
});
}

#[test]
fn alias_ls_marks_preexisting_native_alias_disabled() {
TestEnv::with_default(|sandbox| {
Expand Down
2 changes: 1 addition & 1 deletion cmd/soroban-cli/src/commands/contract/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ impl Cmd {
Cmd::Rm(rm) => rm.run(global_args)?,
Cmd::Add(add) => add.run(global_args)?,
Cmd::Show(show) => show.run(global_args)?,
Cmd::Ls(ls) => ls.run()?,
Cmd::Ls(ls) => ls.run(global_args)?,
}
Ok(())
}
Expand Down
102 changes: 73 additions & 29 deletions cmd/soroban-cli/src/commands/contract/alias/ls.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,50 @@
use clap::Parser;
use std::collections::HashMap;
use clap::{Parser, ValueEnum};
use serde::Serialize;
use std::collections::BTreeMap;
use std::ffi::OsStr;
use std::fmt::Debug;
use std::fs;
use std::path::Path;

use crate::commands::config::network;
use crate::commands::global;
use crate::config::locator::{print_deprecation_warning, Location};
use crate::config::{alias, locator};
use crate::output::{Format, Output};

#[derive(Debug, Clone, Copy, ValueEnum)]
enum OutputFormat {
/// Human-readable alias listing
Text,
/// Compact JSON grouped by network passphrase
Json,
/// Indented JSON grouped by network passphrase
JsonFormatted,
}

impl From<OutputFormat> for Format {
fn from(format: OutputFormat) -> Self {
match format {
OutputFormat::Text => Self::Readable,
OutputFormat::Json => Self::Json,
OutputFormat::JsonFormatted => Self::JsonFormatted,
}
}
}

#[derive(Parser, Debug, Clone)]
#[group(skip)]
pub struct Cmd {
#[command(flatten)]
pub config_locator: locator::Args,

/// Name of the configured network to list
#[arg(long)]
network: Option<String>,

/// Format of the output
#[arg(long, value_enum, default_value = "text")]
output: OutputFormat,
}

#[derive(thiserror::Error, Debug)]
Expand All @@ -26,18 +57,23 @@ pub enum Error {

#[error(transparent)]
IoError(#[from] std::io::Error),

#[error(transparent)]
Json(#[from] serde_json::Error),
}

#[derive(Debug, Clone)]
#[derive(Debug, Clone, Serialize)]
struct AliasEntry {
alias: String,
contract: String,
builtin: bool,
disabled: bool,
}

impl Cmd {
pub fn run(&self) -> Result<(), Error> {
pub fn run(&self, global_args: &global::Args) -> Result<(), Error> {
let config_dirs = self.config_locator.local_and_global()?;
let output = Output::new(self.output.into(), global_args.quiet);

for cfg in config_dirs {
match cfg {
Expand All @@ -46,16 +82,16 @@ impl Cmd {
print_deprecation_warning(&config_dir);
}
}
Location::Global(config_dir) => self.read_from_config_dir(&config_dir)?,
Location::Global(config_dir) => self.read_from_config_dir(&config_dir, &output)?,
}
}

Ok(())
}

fn collect_aliases(config_dir: &Path) -> Result<HashMap<String, Vec<AliasEntry>>, Error> {
fn collect_aliases(config_dir: &Path) -> Result<BTreeMap<String, Vec<AliasEntry>>, Error> {
let contract_ids_dir = config_dir.join("contract-ids");
let mut map: HashMap<String, Vec<AliasEntry>> = HashMap::new();
let mut map: BTreeMap<String, Vec<AliasEntry>> = BTreeMap::new();

if !contract_ids_dir.is_dir() {
return Ok(map);
Expand All @@ -78,6 +114,7 @@ impl Cmd {
alias: alias.clone(),
contract: contract_id.clone(),
builtin: false,
disabled: alias::is_reserved(&alias),
};

map.entry(network_passphrase.clone())
Expand All @@ -90,14 +127,18 @@ impl Cmd {
Ok(map)
}

fn read_from_config_dir(&self, config_dir: &Path) -> Result<(), Error> {
fn read_from_config_dir(&self, config_dir: &Path, output: &Output) -> Result<(), Error> {
let mut map = Self::collect_aliases(config_dir)?;

// The built-in `native` alias resolves to the native asset contract for
// a network, so make sure every known network is listed even when it has
// no stored aliases of its own.
for (_, network, _) in self.config_locator.list_networks_long()? {
map.entry(network.network_passphrase).or_default();
if let Some(name) = &self.network {
let passphrase = self.config_locator.read_network(name)?.network_passphrase;
map.retain(|network, _| *network == passphrase);
map.entry(passphrase).or_default();
} else {
// Include known networks even when they only have the built-in native alias.
for (_, network, _) in self.config_locator.list_networks_long()? {
map.entry(network.network_passphrase).or_default();
}
}

for (network_passphrase, list) in &mut map {
Expand All @@ -108,28 +149,31 @@ impl Cmd {
alias: alias::NATIVE.to_string(),
contract: format!("{contract}"),
builtin: true,
disabled: false,
});
}

println!("ℹ️ Aliases available for network '{network_passphrase}'");

list.sort_by(|a, b| a.alias.cmp(&b.alias));
}

for entry in list.iter() {
let note = if entry.builtin {
" (built-in)"
} else if alias::is_reserved(&entry.alias) {
// A user alias whose name is now reserved is shadowed by the
// built-in alias of the same name, so it no longer resolves.
" (disabled)"
} else {
""
};
println!("{}: {}{note}", entry.alias, entry.contract);
}
output.readable(|_| {
for (network_passphrase, list) in &map {
println!("ℹ️ Aliases available for network '{network_passphrase}'");
for entry in list {
let note = if entry.builtin {
" (built-in)"
} else if entry.disabled {
" (disabled)"
} else {
""
};
println!("{}: {}{note}", entry.alias, entry.contract);
}

println!();
}
println!();
}
});
output.json_value(&map)?;

Ok(())
}
Expand Down