Skip to content

Commit

Permalink
Add -y flag to accept defaults for sui client (MystenLabs#8624)
Browse files Browse the repository at this point in the history
## Description 

`sui client` only allows interactive initialization of the local configs
(in `~/.sui`). This makes it possible to use the client in automation
via a `-y` flag to accept the defaults of using devnet as the network
and generating a new ed25519 key.

## Test Plan 

`cargo nextest run` succeeds for all but one or two few flaky tests:
```
» c nextest run --no-fail-fast

...

     Summary [ 246.873s] 898 tests run: 898 passed (4 slow), 9 skipped
```

Works with a new env (after `rm -rf ~/.sui`):
```
» sui client -y                                      
Creating config file ["/Users/jordankylejensen/.sui/sui_config/client.yaml"] with default (devnet) full node server and ed25519 key scheme.Generated new keypair for address with scheme "ed25519" [0xadb80fbfea1e98869f939f83bbc24f343e657745]
Secret Recovery Phrase : [patient slot rely silly alone squeeze juice term tilt bundle fiscal visual volume kangaroo plate voice rookie grocery opinion brown recipe hover rebel define]
```

Help output is informative:
```
» sui client --help                                  
sui-client 
Client for interacting with the Sui network

USAGE:
    sui client [OPTIONS] [SUBCOMMAND]
OPTIONS:
        --client.config <CONFIG>    Sets the file storing the state of our user accounts (an empty
                                    one will be created if missing)
    -h, --help                      Print help information
        --json                      Return command outputs in json format
    -y, --yes                       Accept the default config for setting up a new client, using
                                    devnet as the network and generating new key(s) using the
                                    ed25519 scheme
```

---
If your changes are not user-facing and not a breaking change, you can
skip the following section. Otherwise, please indicate what changed, and
then add to the Release Notes section as highlighted during the release
process.

### Type of Change (Check all that apply)

- [X] user-visible impact
- [ ] breaking change for a client SDKs
- [ ] breaking change for FNs (FN binary must upgrade)
- [ ] breaking change for validators or node operators (must upgrade
binaries)
- [ ] breaking change for on-chain data layout
- [ ] necessitate either a data wipe or data migration

### Release notes
- Add `-y` flag for accepting client defaults when initializing a new
local configuration.
  • Loading branch information
after-ephemera authored Feb 24, 2023
1 parent d2526c5 commit 56c4e21
Showing 1 changed file with 41 additions and 15 deletions.
56 changes: 41 additions & 15 deletions crates/sui/src/sui_commands.rs
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ pub enum SuiCommand {
/// Return command outputs in json format.
#[clap(long, global = true)]
json: bool,
#[clap(short = 'y', long = "yes")]
accept_defaults: bool,
},

/// Tool to build and test Move applications.
Expand Down Expand Up @@ -202,13 +204,18 @@ impl SuiCommand {
}
SuiCommand::Console { config } => {
let config = config.unwrap_or(sui_config_dir()?.join(SUI_CLIENT_CONFIG));
prompt_if_no_config(&config).await?;
prompt_if_no_config(&config, false).await?;
let context = WalletContext::new(&config, None).await?;
start_console(context, &mut stdout(), &mut stderr()).await
}
SuiCommand::Client { config, cmd, json } => {
SuiCommand::Client {
config,
cmd,
json,
accept_defaults,
} => {
let config_path = config.unwrap_or(sui_config_dir()?.join(SUI_CLIENT_CONFIG));
prompt_if_no_config(&config_path).await?;
prompt_if_no_config(&config_path, accept_defaults).await?;
let mut context = WalletContext::new(&config_path, None).await?;
if let Some(cmd) = cmd {
cmd.execute(&mut context).await?.print(!json);
Expand Down Expand Up @@ -390,7 +397,10 @@ async fn genesis(
Ok(())
}

async fn prompt_if_no_config(wallet_conf_path: &Path) -> Result<(), anyhow::Error> {
async fn prompt_if_no_config(
wallet_conf_path: &Path,
accept_defaults: bool,
) -> Result<(), anyhow::Error> {
// Prompt user for connect to devnet fullnode if config does not exist.
if !wallet_conf_path.exists() {
let env = match std::env::var_os("SUI_CONFIG_WITH_RPC_URL") {
Expand All @@ -400,13 +410,25 @@ async fn prompt_if_no_config(wallet_conf_path: &Path) -> Result<(), anyhow::Erro
ws: None,
}),
None => {
print!(
"Config file [{:?}] doesn't exist, do you want to connect to a Sui full node server [yN]?",
wallet_conf_path
);
if matches!(read_line(), Ok(line) if line.trim().to_lowercase() == "y") {
print!("Sui full node server url (Default to Sui DevNet if not specified) : ");
let url = read_line()?;
if accept_defaults {
print!("Creating config file [{:?}] with default (devnet) full node server and ed25519 key scheme.", wallet_conf_path);
} else {
print!(
"Config file [{:?}] doesn't exist, do you want to connect to a Sui full node server [yN]?",
wallet_conf_path
);
}
if accept_defaults
|| matches!(read_line(), Ok(line) if line.trim().to_lowercase() == "y")
{
let url = if accept_defaults {
String::new()
} else {
print!(
"Sui full node server url (Default to Sui DevNet if not specified) : "
);
read_line()?
};
Some(if url.trim().is_empty() {
SuiEnv::devnet()
} else {
Expand Down Expand Up @@ -435,10 +457,14 @@ async fn prompt_if_no_config(wallet_conf_path: &Path) -> Result<(), anyhow::Erro
.unwrap_or(&sui_config_dir()?)
.join(SUI_KEYSTORE_FILENAME);
let mut keystore = Keystore::from(FileBasedKeystore::new(&keystore_path)?);
println!("Select key scheme to generate keypair (0 for ed25519, 1 for secp256k1, 2: for secp256r1:");
let key_scheme = match SignatureScheme::from_flag(read_line()?.trim()) {
Ok(s) => s,
Err(e) => return Err(anyhow!("{e}")),
let key_scheme = if accept_defaults {
SignatureScheme::ED25519
} else {
println!("Select key scheme to generate keypair (0 for ed25519, 1 for secp256k1, 2: for secp256r1:");
match SignatureScheme::from_flag(read_line()?.trim()) {
Ok(s) => s,
Err(e) => return Err(anyhow!("{e}")),
}
};
let (new_address, phrase, scheme) =
keystore.generate_and_add_new_key(key_scheme, None)?;
Expand Down

0 comments on commit 56c4e21

Please sign in to comment.