GeezerVison is showing github.com — Centralize asset/token resolution behind a single resolver by fnando · Pull Request #2654 · stellar/stellar-cli
Centralize asset/token resolution behind a single resolver
#2654
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement . We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Uh oh!
There was an error while loading. Please reload this page.
Show file tree
Hide file tree
Changes from all commits
Commits
File filter
Filter by extension
.rs
(12)
All 1 file type selected
Viewed files
Conversations
Failed to load comments.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Jump to
Jump to file
Failed to load files.
Loading
Uh oh!
There was an error while loading. Please reload this page.
Diff view
Hide whitespace
Diff view
Hide whitespace
There are no files selected for viewing
Original file line number
Diff line number
Diff line change
Expand Up
@@ -109,3 +109,37 @@ async fn balance_fails_when_sac_not_deployed() {
"expected an error message, got: {stdout}"
);
}
#[tokio::test]
async fn balance_fails_when_contract_not_found() {
let sandbox = &TestEnv::new();
// A well-formed contract id that resolves to a plain contract (not a SAC)
// and was never deployed → the missing-contract branch, distinct from the
// SAC deploy pointer above.
let id = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4";
// In JSON mode the error carries a machine-readable `type` discriminator.
let stdout = sandbox
.new_assert_cmd("token")
.args([
"balance",
"--id",
id,
"--account",
"test",
"--output",
"json",
])
.assert()
.failure()
.stdout_as_str();
let value: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(
value["error"]["type"], "contract_not_found",
"expected a typed error, got: {stdout}"
);
assert!(
value["error"]["message"].as_str().is_some(),
"expected an error message, got: {stdout}"
);
}
Original file line number
Diff line number
Diff line change
Expand Up
@@ -139,6 +139,36 @@ async fn transfer_fails_when_sac_not_deployed() {
.stderr(predicates::str::contains("contract asset deploy"));
}
#[tokio::test]
async fn transfer_fails_when_contract_not_found() {
let sandbox = &TestEnv::new();
let recipient = new_account(sandbox, "recipient");
// A well-formed contract id that resolves to a plain contract (not a SAC)
// and was never deployed → the missing-contract branch, distinct from the
// SAC deploy pointer above.
let id = "CAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFCT4";
// In JSON mode the error carries a machine-readable `type` discriminator.
let stdout = sandbox
.new_assert_cmd("token")
.args([
"transfer", "--id", id, "--to", &recipient, "--amount", "1", "--from", "test",
"--output", "json",
])
.assert()
.failure()
.stdout_as_str();
let value: Value = serde_json::from_str(&stdout).unwrap();
assert_eq!(
value["error"]["type"], "contract_not_found",
"expected a typed error, got: {stdout}"
);
assert!(
value["error"]["message"].as_str().is_some(),
"expected an error message, got: {stdout}"
);
}
#[tokio::test]
async fn transfer_fails_when_recipient_trustline_missing() {
let sandbox = &TestEnv::new();
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -101,7 +101,9 @@ impl Cmd {
}
for (network_passphrase, list) in &mut map {
if let Some(contract) = alias::resolve_reserved(alias::NATIVE, network_passphrase) {
if let Some(contract) =
alias::resolve_reserved(alias::NATIVE, &self.config_locator, network_passphrase)
{
list.push(AliasEntry {
alias: alias::NATIVE.to_string(),
contract: format!("{contract}"),
Expand Down
Original file line number
Diff line number
Diff line change
Expand Up
@@ -19,10 +19,9 @@ use crate::{
txn_result::{TxnEnvelopeResult, TxnResult},
HEADING_TRANSACTION,
},
config::{self, data, network},
config::{self, data, network, token::UnresolvedToken },
rpc::Error as SorobanRpcError,
tx::builder,
utils::contract_id_hash_from_asset,
};
use crate::config::address::AliasName;
Expand Down
Expand Up
@@ -54,10 +53,10 @@ pub enum Error {
Builder(#[from] builder::Error),
#[error(transparent)]
Asset (#[from] builder::asset ::Error),
Locator (#[from] locator ::Error),
#[error(transparent)]
Locator (#[from] locator ::Error),
Token (#[from] config::token ::Error),
#[error(transparent)]
Fee(#[from] fetch::fee::Error),
Expand Down
Expand Up
@@ -144,11 +143,19 @@ impl Cmd {
quiet: bool,
no_cache: bool,
) -> Result<TxnResult<stellar_strkey::Contract>, Error> {
// Parse asset
let print = Print::new(quiet);
let asset = self.asset.resolve(&config.locator)?;
let network = config.get_network()?;
// Resolve the asset up front, before any RPC, so an invalid asset or
// unresolvable issuer alias fails fast instead of after network calls.
let token = UnresolvedToken::Asset(self.asset.clone())
.resolve(&config.locator, &network.network_passphrase)?;
let contract_id = token.contract_id;
let asset = token
.asset()
.expect("an asset reference resolves to a SAC")
.clone();
let client = network.rpc_client()?;
client
.verify_network_passphrase(Some(&network.network_passphrase))
Expand All
@@ -163,7 +170,6 @@ impl Cmd {
.await?;
let sequence: i64 = account_details.seq_num.into();
let network_passphrase = &network.network_passphrase;
let contract_id = contract_id_hash_from_asset(&asset, network_passphrase);
let tx = build_wrap_token_tx(
asset,
&contract_id,
Expand Down
Original file line number
Diff line number
Diff line change
@@ -1,9 +1,9 @@
use clap::Parser;
use crate::config;
use crate::config::token::UnresolvedToken;
use crate::tx::builder;
use crate::utils::contract_id_hash_from_asset;
#[derive(Parser, Debug, Clone)]
#[group(skip)]
Expand All
@@ -22,7 +22,7 @@ pub enum Error {
#[error(transparent)]
Xdr(#[from] crate::xdr::Error),
#[error(transparent)]
Asset (#[from] builder::asset ::Error),
Token (#[from] config::token ::Error),
}
impl Cmd {
pub fn run(&self) -> Result<(), Error> {
Expand All
@@ -32,10 +32,8 @@ impl Cmd {
pub fn contract_address(&self) -> Result<stellar_strkey::Contract, Error> {
let network = self.config.get_network()?;
let contract_id = contract_id_hash_from_asset(
&self.asset.resolve(&self.config.locator)?,
&network.network_passphrase,
);
Ok(stellar_strkey::Contract(contract_id.0))
let token = UnresolvedToken::Asset(self.asset.clone())
.resolve(&self.config.locator, &network.network_passphrase)?;
Ok(token.contract_id)
}
}
Original file line number
Diff line number
Diff line change
@@ -1,13 +1,5 @@
use std::str::FromStr;
use crate::{
commands::contract::invoke,
config::{alias::UnresolvedContract, locator},
get_spec,
output::Format,
rpc,
tx::builder,
utils::contract_id_hash_from_asset,
commands::contract::invoke, config::token::ResolvedToken, get_spec, output::Format, rpc,
};
/// Output format shared by the `stellar token` subcommands.
Expand All
@@ -32,27 +24,8 @@ impl From<OutputFormat> for Format {
}
}
/// A `stellar token` target, resolved from the `--id` value.
///
/// The shape of the value decides how it is interpreted:
/// * `native` or `CODE:ISSUER` → a Stellar Asset Contract (SAC), resolved from
/// the classic asset.
/// * anything else → a contract, either a `C…` strkey or a saved alias.
#[derive(Clone, Debug)]
pub enum TokenTarget {
/// A SEP-41 contract addressed directly by id or alias.
Contract(UnresolvedContract),
/// A Stellar Asset Contract addressed by its underlying classic asset.
Asset(builder::Asset),
}
#[derive(thiserror::Error, Debug)]
pub enum Error {
#[error(transparent)]
Locator(#[from] locator::Error),
#[error(transparent)]
Asset(#[from] builder::asset::Error),
#[error(
"the Stellar Asset Contract {0} is not deployed on this network.\n\
Deploy it first with `stellar contract asset deploy --asset <ASSET>`, then retry."
Expand All
@@ -68,111 +41,30 @@ impl Error {
#[must_use]
pub fn error_type(&self) -> &'static str {
match self {
Error::Locator(_) => "config",
Error::Asset(_) => "invalid_asset",
Error::SacNotDeployed(_) => "sac_not_deployed",
Error::ContractNotFound(_) => "contract_not_found",
}
}
}
impl FromStr for TokenTarget {
type Err = builder::asset::Error;
fn from_str(value: &str) -> Result<Self, Self::Err> {
// `native` and the `CODE:ISSUER` shape are both classic assets, resolved
// to their Stellar Asset Contract — so a missing SAC reports
// `sac_not_deployed`, not `contract_not_found`. Everything else is a
// contract id or a saved alias.
if value == "native" || value.contains(':') {
Ok(TokenTarget::Asset(value.parse()?))
} else {
// `UnresolvedContract::from_str` is infallible.
Ok(TokenTarget::Contract(value.parse().unwrap()))
}
}
}
impl TokenTarget {
/// Resolve this target to a concrete contract id for the given network.
pub fn resolve_contract_id(
&self,
locator: &locator::Args,
network_passphrase: &str,
) -> Result<stellar_strkey::Contract, Error> {
match self {
TokenTarget::Contract(contract) => {
Ok(contract.resolve_contract_id(locator, network_passphrase)?)
}
TokenTarget::Asset(asset) => {
let asset = asset.resolve(locator)?;
Ok(contract_id_hash_from_asset(&asset, network_passphrase))
}
}
}
/// If `err` is a "contract not found" failure raised while fetching the
/// contract spec, translate it into a token-aware error: a missing SAC for
/// an asset target (pointing at `contract asset deploy`), or a missing
/// contract for a direct id/alias. Returns `None` for any other failure so
/// the caller can surface the underlying invoke error unchanged.
#[must_use]
pub fn not_deployed_error(
&self,
err: &invoke::Error,
contract_id: &stellar_strkey::Contract,
) -> Option<Error> {
let invoke::Error::GetSpecError(get_spec::Error::Rpc(rpc::Error::NotFound(kind, _))) = err
else {
return None;
};
if kind != "Contract" {
return None;
}
Some(if matches!(self, TokenTarget::Asset(_)) {
Error::SacNotDeployed(format!("{contract_id}"))
} else {
Error::ContractNotFound(format!("{contract_id}"))
})
}
}
#[cfg(test)]
mod tests {
use super::*;
// A valid contract strkey borrowed from the CLI's own help text.
const CONTRACT: &str = "CCR6QKTWZQYW6YUJ7UP7XXZRLWQPFRV6SWBLQS4ZQOSAF4BOUD77OTE2";
#[test]
fn native_parses_as_asset() {
assert!(matches!(
"native".parse::<TokenTarget>().unwrap(),
TokenTarget::Asset(builder::Asset::Native)
));
}
#[test]
fn code_issuer_parses_as_asset() {
assert!(matches!(
"USDC:issuer".parse::<TokenTarget>().unwrap(),
TokenTarget::Asset(builder::Asset::Asset(..))
));
}
#[test]
fn contract_strkey_parses_as_resolved_contract() {
assert!(matches!(
CONTRACT.parse::<TokenTarget>().unwrap(),
TokenTarget::Contract(UnresolvedContract::Resolved(_))
));
}
#[test]
fn bare_name_parses_as_contract_alias() {
assert!(matches!(
"alice".parse::<TokenTarget>().unwrap(),
TokenTarget::Contract(UnresolvedContract::Alias(_))
));
/// If `err` is a "contract not found" failure raised while fetching the contract
/// spec, translate it into a token-aware error keyed off what `token` resolved
/// to: a missing SAC (pointing at `contract asset deploy`), or a missing
/// contract for a direct id/alias. Returns `None` for any other failure so the
/// caller can surface the underlying invoke error unchanged.
#[must_use]
pub fn not_deployed_error(token: &ResolvedToken, err: &invoke::Error) -> Option<Error> {
let invoke::Error::GetSpecError(get_spec::Error::Rpc(rpc::Error::NotFound(kind, _))) = err
else {
return None;
};
if kind != "Contract" {
return None;
}
let contract_id = token.contract_id;
Some(if token.is_sac() {
Error::SacNotDeployed(format!("{contract_id}"))
} else {
Error::ContractNotFound(format!("{contract_id}"))
Comment thread
fnando marked this conversation as resolved.
Resolved
Uh oh!
There was an error while loading. Please reload this page.
})
}
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Loading
Oops, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.