Skip to content
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

chore(iota)!: Set active env when adding new env if empty #5330

Open
wants to merge 7 commits into
base: develop
Choose a base branch
from
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
6 changes: 3 additions & 3 deletions crates/iota-faucet/src/bin/merge_coins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ use tracing::info;

#[tokio::main]
async fn main() -> Result<(), anyhow::Error> {
let mut wallet = create_wallet_context(60)?;
let wallet = create_wallet_context(60)?;
let active_address = wallet
.active_address()
.map_err(|err| FaucetError::Wallet(err.to_string()))?;
Expand All @@ -43,7 +43,7 @@ async fn main() -> Result<(), anyhow::Error> {

async fn _split_coins_equally(
gas_coin: &str,
mut wallet: WalletContext,
wallet: WalletContext,
count: u64,
) -> Result<(), anyhow::Error> {
let active_address = wallet
Expand Down Expand Up @@ -75,7 +75,7 @@ async fn _split_coins_equally(
Ok(())
}

async fn _merge_coins(gas_coin: &str, mut wallet: WalletContext) -> Result<(), anyhow::Error> {
async fn _merge_coins(gas_coin: &str, wallet: WalletContext) -> Result<(), anyhow::Error> {
let active_address = wallet
.active_address()
.map_err(|err| FaucetError::Wallet(err.to_string()))?;
Expand Down
2 changes: 1 addition & 1 deletion crates/iota-faucet/src/faucet/simple_faucet.rs
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ const BATCH_TIMEOUT: Duration = Duration::from_secs(10);

impl SimpleFaucet {
pub async fn new(
mut wallet: WalletContext,
wallet: WalletContext,
prometheus_registry: &Registry,
wal_path: &Path,
config: FaucetConfig,
Expand Down
2 changes: 1 addition & 1 deletion crates/iota-json-rpc-tests/tests/indexer_api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -440,7 +440,7 @@ async fn test_query_transaction_blocks_pagination() -> Result<(), anyhow::Error>

#[sim_test]
async fn test_query_transaction_blocks() -> Result<(), anyhow::Error> {
let mut cluster = TestClusterBuilder::new().build().await;
let cluster = TestClusterBuilder::new().build().await;
let context = &cluster.wallet;
let client = context.get_client().await.unwrap();

Expand Down
2 changes: 1 addition & 1 deletion crates/iota-package-management/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ pub async fn update_lock_file(
)
};
let install_dir = install_dir.unwrap_or(PathBuf::from("."));
let env = context.config().get_active_env().context(
let env = context.active_env().context(
"Could not resolve environment from active wallet context. \
Try ensure `iota client active-env` is valid.",
)?;
Expand Down
2 changes: 1 addition & 1 deletion crates/iota-sdk/examples/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ pub async fn setup_for_write() -> Result<(IotaClient, IotaAddress, IotaAddress),
pub async fn setup_for_read() -> Result<(IotaClient, IotaAddress), anyhow::Error> {
let client = IotaClientBuilder::default().build_testnet().await?;
println!("IOTA testnet version is: {}", client.api_version());
let mut wallet = retrieve_wallet()?;
let wallet = retrieve_wallet()?;
assert!(wallet.get_addresses().len() >= 2);
let active_address = wallet.active_address()?;

Expand Down
41 changes: 22 additions & 19 deletions crates/iota-sdk/src/iota_client_config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,33 +78,36 @@ impl IotaClientConfig {
self.active_address = address.into();
}

/// Get the first [`IotaEnv`] or one by its alias.
pub fn get_env(&self, alias: &Option<String>) -> Option<&IotaEnv> {
if let Some(alias) = alias {
self.envs.iter().find(|env| &env.alias == alias)
} else {
self.envs.first()
}
/// Get an [`IotaEnv`] by its alias.
pub fn get_env(&self, alias: &str) -> Option<&IotaEnv> {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't really know how to feel about this change tbh

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How so?

self.envs.iter().find(|env| env.alias == alias)
}

/// Get the active [`IotaEnv`].
pub fn get_active_env(&self) -> Result<&IotaEnv, anyhow::Error> {
self.get_env(&self.active_env).ok_or_else(|| {
anyhow!(
"Environment configuration not found for env [{}]",
self.active_env.as_deref().unwrap_or("None")
)
})
self.active_env
.as_ref()
.and_then(|alias| self.get_env(alias))
.ok_or_else(|| {
anyhow!(
"Environment configuration not found for env [{}]",
self.active_env.as_deref().unwrap_or("None")
)
})
}

/// Add an [`IotaEnv`].
pub fn add_env(&mut self, env: IotaEnv) {
if !self
.envs
.iter()
.any(|other_env| other_env.alias == env.alias)
{
self.envs.push(env)
if self.get_env(&env.alias).is_none() {
if self
.active_env
.as_ref()
.and_then(|env| self.get_env(env))
.is_none()
{
self.set_active_env(env.alias.clone());
}
self.envs.push(env);
}
}
}
Expand Down
43 changes: 28 additions & 15 deletions crates/iota-sdk/src/wallet_context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,10 @@ use shared_crypto::intent::Intent;
use tokio::sync::RwLock;
use tracing::warn;

use crate::{IotaClient, iota_client_config::IotaClientConfig};
use crate::{
IotaClient,
iota_client_config::{IotaClientConfig, IotaEnv},
};

/// Wallet for managing accounts, objects, and interact with client APIs.
// Mainly used in the CLI and tests.
Expand Down Expand Up @@ -75,8 +78,7 @@ impl WalletContext {
} else {
drop(read);
let client = self
.config
.get_active_env()?
.active_env()?
.create_rpc_client(self.request_timeout, self.max_concurrent_requests)
.await?;
if let Err(e) = client.check_api_version() {
Expand All @@ -87,25 +89,36 @@ impl WalletContext {
})
}

// TODO: Ger rid of mut
/// Get the active [`IotaAddress`].
/// If not set, set it to the first address in the keystore.
pub fn active_address(&mut self) -> Result<IotaAddress, anyhow::Error> {
/// If not set, defaults to the first address in the keystore.
pub fn active_address(&self) -> Result<IotaAddress, anyhow::Error> {
if self.config.keystore.addresses().is_empty() {
return Err(anyhow!(
"No managed addresses. Create new address with `new-address` command."
"No managed addresses. Create new address with the `new-address` command."
));
}

// Ok to unwrap because we checked that config addresses not empty
// Set it if not exists
self.config.active_address = Some(
self.config
.active_address
.unwrap_or(*self.config.keystore.addresses().first().unwrap()),
);
Ok(if let Some(addr) = self.config.active_address() {
*addr
} else {
self.config.keystore().addresses()[0]
})
}

Ok(self.config.active_address.unwrap())
/// Get the active [`IotaEnv`].
/// If not set, defaults to the first environment in the config.
pub fn active_env(&self) -> Result<&IotaEnv, anyhow::Error> {
if self.config.envs.is_empty() {
return Err(anyhow!(
"No managed environments. Create new environment with the `new-env` command."
));
}

Ok(if self.config.active_env().is_some() {
self.config.get_active_env()?
} else {
&self.config.envs()[0]
})
}

/// Get the latest object reference given a object id.
Expand Down
64 changes: 27 additions & 37 deletions crates/iota/src/client_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -715,7 +715,7 @@ impl IotaClientCommands {
profile_output,
config_objects: None,
};
let rpc = context.config().get_active_env()?.rpc().clone();
let rpc = context.active_env()?.rpc().clone();
let _command_result =
iota_replay::execute_replay_command(Some(rpc), false, false, None, None, cmd)
.await?;
Expand All @@ -737,7 +737,7 @@ impl IotaClientCommands {
config_objects: None,
};

let rpc = context.config().get_active_env()?.rpc().clone();
let rpc = context.active_env()?.rpc().clone();
let _command_result =
iota_replay::execute_replay_command(Some(rpc), false, false, None, None, cmd)
.await?;
Expand All @@ -754,7 +754,7 @@ impl IotaClientCommands {
num_tasks: 16,
persist_path: None,
};
let rpc = context.config().get_active_env()?.rpc().clone();
let rpc = context.active_env()?.rpc().clone();
let _command_result =
iota_replay::execute_replay_command(Some(rpc), false, false, None, None, cmd)
.await?;
Expand All @@ -772,7 +772,7 @@ impl IotaClientCommands {
terminate_early,
max_tasks: 16,
};
let rpc = context.config().get_active_env()?.rpc().clone();
let rpc = context.active_env()?.rpc().clone();
let _command_result =
iota_replay::execute_replay_command(Some(rpc), false, false, None, None, cmd)
.await?;
Expand Down Expand Up @@ -912,11 +912,7 @@ impl IotaClientCommands {
} else {
None
};
let env_alias = context
.config()
.get_active_env()
.map(|e| e.alias().clone())
.ok();
let env_alias = context.active_env().map(|e| e.alias().clone()).ok();
let upgrade_result = upgrade_package(
client.read_api(),
build_config.clone(),
Expand Down Expand Up @@ -1443,27 +1439,27 @@ impl IotaClientCommands {
let url = if let Some(url) = url {
url
} else {
let active_env = context.config().get_active_env();
let active_env = context.active_env().map_err(|_| {
anyhow::anyhow!(
"No URL for faucet was provided and there is no active network."
)
})?;

if let Ok(env) = active_env {
let faucet_url = if let Some(faucet_url) = env.faucet() {
faucet_url
} else {
match env.rpc().as_str() {
IOTA_DEVNET_URL => IOTA_DEVNET_GAS_URL,
IOTA_TESTNET_URL => IOTA_TESTNET_GAS_URL,
IOTA_LOCAL_NETWORK_URL | IOTA_LOCAL_NETWORK_URL_0 => {
IOTA_LOCAL_NETWORK_GAS_URL
}
_ => bail!(
"Cannot recognize the active network. Please provide the gas faucet full URL."
),
}
};
faucet_url.to_string()
let faucet_url = if let Some(faucet_url) = active_env.faucet() {
faucet_url
} else {
bail!("No URL for faucet was provided and there is no active network.")
}
match active_env.rpc().as_str() {
IOTA_DEVNET_URL => IOTA_DEVNET_GAS_URL,
IOTA_TESTNET_URL => IOTA_TESTNET_GAS_URL,
IOTA_LOCAL_NETWORK_URL | IOTA_LOCAL_NETWORK_URL_0 => {
IOTA_LOCAL_NETWORK_GAS_URL
}
_ => bail!(
"Cannot recognize the active network. Please provide the gas faucet full URL."
),
}
};
faucet_url.to_string()
};
request_tokens_from_faucet(address, url).await?;
IotaClientCommandResult::NoOutput
Expand Down Expand Up @@ -1590,12 +1586,7 @@ impl IotaClientCommands {
basic_auth,
faucet,
} => {
if context
.config()
.envs()
.iter()
.any(|env| env.alias() == &alias)
{
if context.config().get_env(&alias).is_some() {
return Err(anyhow!(
"Environment config with name [{alias}] already exists."
));
Expand Down Expand Up @@ -1668,12 +1659,11 @@ impl IotaClientCommands {
}

pub fn switch_env(config: &mut IotaClientConfig, env: &str) -> Result<(), anyhow::Error> {
let env = Some(env.into());
ensure!(
config.get_env(&env).is_some(),
config.get_env(env).is_some(),
"Environment config not found for [{env:?}], add new environment config using the `iota client new-env` command."
);
config.set_active_env(env);
config.set_active_env(env.to_owned());
Ok(())
}
}
Expand Down
Loading