Skip to content

Commit

Permalink
Move functions to config instead.
Browse files Browse the repository at this point in the history
  • Loading branch information
fnando committed Jun 13, 2024
1 parent b2edc3a commit 5d3da77
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 34 deletions.
50 changes: 27 additions & 23 deletions cmd/soroban-cli/src/commands/config/alias.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,16 @@ use std::{
collections::HashMap,
fs::{self, create_dir_all, OpenOptions},
io::Write,
path::{Path, PathBuf},
path::PathBuf,
};

use serde::{Deserialize, Serialize};
use stellar_strkey::DecodeError;

use crate::commands::config;

use super::Args;

#[derive(Serialize, Deserialize, Default)]
pub struct Data {
ids: HashMap<String, String>,
Expand All @@ -23,79 +27,79 @@ pub enum Error {
CannotAccessConfigDir,
#[error("cannot parse contract ID {0}: {1}")]
CannotParseContractId(String, DecodeError),
#[error(transparent)]
Config(#[from] config::Error),
}

impl Data {
pub fn load(config_dir: &Path, alias: &str) -> Result<Option<Self>, Error> {
let path = Self::alias_path(config_dir, alias);
impl Args {
pub fn load(&self, alias: &str) -> Result<Option<Data>, Error> {
let path = self.alias_path(alias)?;

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

let content = fs::read_to_string(path)?;
let data: Self = serde_json::from_str(&content).unwrap_or_default();
let data: Data = serde_json::from_str(&content).unwrap_or_default();

Ok(Some(data))
}

pub fn alias_path(config_dir: &Path, alias: &str) -> PathBuf {
fn alias_path(&self, alias: &str) -> Result<PathBuf, Error> {
let file_name = format!("{alias}.json");
config_dir.join("contract-ids").join(file_name)
let config_dir = self.config_dir()?;
Ok(config_dir.join("contract-ids").join(file_name))
}

pub fn save_contract_id(
config_dir: &Path,
contract_id: &str,
alias: Option<&String>,
network_passphrase: &str,
) -> Result<(), Error> {
pub fn save_contract_id(&self, contract_id: &str, alias: Option<&String>) -> Result<(), Error> {
let Some(alias) = alias else {
return Ok(());
};

let path = Self::alias_path(config_dir, alias);
let path = self.alias_path(alias)?;
let dir = path.parent().ok_or(Error::CannotAccessConfigDir)?;

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

let content = fs::read_to_string(&path).unwrap_or_default();
let mut data: Self = serde_json::from_str(&content).unwrap_or_default();
let mut data: Data = serde_json::from_str(&content).unwrap_or_default();

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

let network = self.get_network()?;

data.ids
.insert(network_passphrase.into(), contract_id.into());
.insert(network.network_passphrase, contract_id.into());

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

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

pub fn get_contract_id(
&self,
alias: &str,
config_dir: &Path,
network_passphrase: &str,
) -> Result<Option<String>, Error> {
let Some(alias_data) = Self::load(config_dir, alias)? else {
let Some(alias_data) = self.load(alias)? else {
return Ok(None);
};

Ok(alias_data.ids.get(network_passphrase).cloned())
}

pub fn load_contract_id_or_default(
pub fn resolve_contract_id(
&self,
alias_or_contract_id: &str,
config_dir: &Path,
network_passphrase: &str,
) -> Result<[u8; 32], Error> {
let contract_id =
Self::get_contract_id(alias_or_contract_id, config_dir, network_passphrase)?
.unwrap_or_else(|| alias_or_contract_id.to_string());
let contract_id = self
.get_contract_id(alias_or_contract_id, network_passphrase)?
.unwrap_or_else(|| alias_or_contract_id.to_string());

soroban_spec_tools::utils::contract_id_from_str(&contract_id)
.map_err(|e| Error::CannotParseContractId(contract_id.clone(), e))
Expand Down
8 changes: 2 additions & 6 deletions cmd/soroban-cli/src/commands/contract/deploy/wasm.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,12 +120,8 @@ impl Cmd {
match res {
TxnEnvelopeResult::TxnEnvelope(tx) => println!("{}", tx.to_xdr_base64(Limits::none())?),
TxnEnvelopeResult::Res(contract) => {
alias::Data::save_contract_id(
&self.config.config_dir()?,
&contract,
self.alias.as_ref(),
&self.config.get_network()?.network_passphrase,
)?;
self.config
.save_contract_id(&contract, self.alias.as_ref())?;

println!("{contract}");
}
Expand Down
8 changes: 3 additions & 5 deletions cmd/soroban-cli/src/commands/contract/invoke.rs
Original file line number Diff line number Diff line change
Expand Up @@ -316,11 +316,9 @@ impl NetworkRunnable for Cmd {
let unwrap_config = config.unwrap_or(&self.config);
let network = unwrap_config.get_network()?;
tracing::trace!(?network);
let contract_id = alias::Data::load_contract_id_or_default(
&self.contract_id,
&self.config.config_dir()?,
&network.network_passphrase,
)?;
let contract_id = self
.config
.resolve_contract_id(&self.contract_id, &network.network_passphrase)?;
let spec_entries = self.spec_entries()?;
if let Some(spec_entries) = &spec_entries {
// For testing wasm arg parsing
Expand Down

0 comments on commit 5d3da77

Please sign in to comment.