Skip to content

Commit

Permalink
Add support for contract id alias name when deploying and invoking co…
Browse files Browse the repository at this point in the history
…ntracts. (#1356)
  • Loading branch information
fnando authored Jun 11, 2024
1 parent 0eace80 commit e189c71
Show file tree
Hide file tree
Showing 4 changed files with 121 additions and 3 deletions.
1 change: 1 addition & 0 deletions FULL_HELP_DOCS.md
Original file line number Diff line number Diff line change
Expand Up @@ -456,6 +456,7 @@ Deploy a wasm contract

Possible values: `true`, `false`

* `--alias <ALIAS>` — The alias that will be used to save the contract's id



Expand Down
74 changes: 73 additions & 1 deletion cmd/soroban-cli/src/commands/contract/deploy/wasm.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,13 @@
use std::array::TryFromSliceError;
use std::fmt::Debug;
use std::fs::{self, create_dir_all};
use std::io::Write;
use std::num::ParseIntError;
use std::path::PathBuf;
use std::{array::TryFromSliceError, fs::OpenOptions};

use clap::{arg, command, Parser};
use rand::Rng;
use regex::Regex;
use soroban_env_host::{
xdr::{
AccountId, ContractExecutable, ContractIdPreimage, ContractIdPreimageFromAddress,
Expand All @@ -14,6 +18,7 @@ use soroban_env_host::{
HostError,
};

use crate::commands::contract::AliasData;
use crate::commands::{
config::data,
contract::{self, id::wasm::get_contract_id},
Expand Down Expand Up @@ -54,6 +59,9 @@ pub struct Cmd {
#[arg(long, short = 'i', default_value = "false")]
/// Whether to ignore safety checks when deploying contracts
pub ignore_checks: bool,
/// The alias that will be used to save the contract's id.
#[arg(long)]
pub alias: Option<String>,
}

#[derive(thiserror::Error, Debug)]
Expand Down Expand Up @@ -100,19 +108,83 @@ pub enum Error {
Network(#[from] network::Error),
#[error(transparent)]
Wasm(#[from] wasm::Error),
#[error("cannot access config dir for alias file")]
CannotAccessConfigDir,
#[error(
"alias must be 1-30 chars long, and have only letters, numbers, underscores and dashes"
)]
InvalidAliasFormat { alias: String },
#[error(transparent)]
JsonSerialization(#[from] serde_json::Error),
#[error(transparent)]
Io(#[from] std::io::Error),
}

impl Cmd {
pub async fn run(&self) -> Result<(), Error> {
self.validate_alias()?;

let res = self.run_against_rpc_server(None, None).await?.to_envelope();
match res {
TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
TxnEnvelopeResult::Res(contract) => {
self.save_contract_id(&contract)?;
println!("{contract}");
}
}
Ok(())
}

fn validate_alias(&self) -> Result<(), Error> {
match self.alias.clone() {
Some(alias) => {
let regex = Regex::new(r"^[a-zA-Z0-9_-]{1,30}$").unwrap();

if regex.is_match(&alias) {
Ok(())
} else {
Err(Error::InvalidAliasFormat { alias })
}
}
None => Ok(()),
}
}

fn alias_path_for(&self, alias: &str) -> Result<PathBuf, Error> {
let config_dir = self.config.config_dir()?;
let file_name = format!("{alias}.json");

Ok(config_dir.join("contract-ids").join(file_name))
}

fn save_contract_id(&self, contract: &String) -> Result<(), Error> {
let Some(alias) = &self.alias else {
return Ok(());
};

let file_path = self.alias_path_for(alias)?;
let dir = file_path.parent().ok_or(Error::CannotAccessConfigDir)?;

create_dir_all(dir).map_err(|_| Error::CannotAccessConfigDir)?;

let content = fs::read_to_string(&file_path).unwrap_or_default();
let mut data: AliasData = serde_json::from_str(&content).unwrap_or_default();

let mut to_file = OpenOptions::new()
.create(true)
.truncate(true)
.write(true)
.open(file_path)?;

data.ids.insert(
self.config.get_network()?.network_passphrase,
contract.into(),
);

let content = serde_json::to_string(&data)?;

Ok(to_file.write_all(content.as_bytes())?)
}
}

#[async_trait::async_trait]
Expand Down
40 changes: 38 additions & 2 deletions cmd/soroban-cli/src/commands/contract/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ use super::super::{
config::{self, locator},
events,
};
use super::AliasData;
use crate::commands::txn_result::{TxnEnvelopeResult, TxnResult};
use crate::commands::NetworkRunnable;
use crate::get_spec::{self, get_remote_contract_spec};
Expand Down Expand Up @@ -152,6 +153,12 @@ pub enum Error {
Network(#[from] network::Error),
#[error(transparent)]
GetSpecError(#[from] get_spec::Error),
#[error("unable to read alias file")]
UnableToReadAliasFile,
#[error("alias file not found")]
NoAliasFileFound,
#[error(transparent)]
JsonDeserialization(#[from] serde_json::Error),
}

impl From<Infallible> for Error {
Expand Down Expand Up @@ -305,8 +312,37 @@ impl Cmd {

impl Cmd {
fn contract_id(&self) -> Result<[u8; 32], Error> {
soroban_spec_tools::utils::contract_id_from_str(&self.contract_id)
.map_err(|e| Error::CannotParseContractId(self.contract_id.clone(), e))
let contract_id: String = match self.load_contract_id() {
Ok(Some(id)) => id.to_string(),
_ => self.contract_id.clone(),
};

soroban_spec_tools::utils::contract_id_from_str(&contract_id)
.map_err(|e| Error::CannotParseContractId(contract_id.clone(), e))
}

fn alias_path(&self) -> Result<PathBuf, Error> {
let config_dir = self.config.config_dir()?;
let file_name = format!("{}.json", self.contract_id);

Ok(config_dir.join("contract-ids").join(file_name))
}

fn load_contract_id(&self) -> Result<Option<String>, Error> {
let network = &self.config.get_network()?.network_passphrase;
let file_path = self.alias_path()?;

if !file_path.exists() {
return Ok(None);
}

let content = fs::read_to_string(file_path)?;
let data: AliasData = serde_json::from_str(&content)?;

match data.ids.get(network) {
Some(id) => Ok(Some(id.into())),
_ => Ok(None),
}
}
}

Expand Down
9 changes: 9 additions & 0 deletions cmd/soroban-cli/src/commands/contract/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,10 @@ pub mod optimize;
pub mod read;
pub mod restore;

use std::collections::HashMap;

use serde::{Deserialize, Serialize};

use crate::commands::global;

#[derive(Debug, clap::Subcommand)]
Expand Down Expand Up @@ -165,3 +169,8 @@ pub enum SpecOutput {
/// Pretty print of contract spec entries
Docs,
}

#[derive(Serialize, Deserialize, Default)]
pub struct AliasData {
ids: HashMap<String, String>,
}

0 comments on commit e189c71

Please sign in to comment.