Skip to content

Commit

Permalink
[aptos-cli] Cleanup errors and results to be consistent
Browse files Browse the repository at this point in the history
  • Loading branch information
gregnazario authored and aptos-bot committed Apr 21, 2022
1 parent 59422fc commit 5bf3d45
Show file tree
Hide file tree
Showing 9 changed files with 130 additions and 138 deletions.
70 changes: 29 additions & 41 deletions crates/aptos/src/account/create.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,10 @@
//! TODO: Examples
//!
use crate::{
common::types::{
account_address_from_public_key, EncodingOptions, ExtractPublicKey, PublicKeyInputOptions,
WriteTransactionOptions,
},
CliResult, Error as CommonError,
use crate::common::types::{
account_address_from_public_key, CliError, CliTypedResult, EncodingOptions, ExtractPublicKey,
PublicKeyInputOptions, WriteTransactionOptions,
};
use anyhow::Error;
use aptos_crypto::{ed25519::Ed25519PrivateKey, PrivateKey};
use aptos_rest_client::{Client as RestClient, Response, Transaction};
use aptos_sdk::{transaction_builder::TransactionFactory, types::LocalAccount};
Expand Down Expand Up @@ -55,17 +51,15 @@ impl CreateAccount {
.await
}

async fn get_sequence_number(&self, account: AccountAddress) -> Result<u64, CommonError> {
async fn get_sequence_number(&self, account: AccountAddress) -> CliTypedResult<u64> {
let account_response = self
.get_account(account)
.await
.map_err(|err| CommonError::ApiError(err.to_string()))?;
.map_err(|err| CliError::ApiError(err.to_string()))?;
let sequence_number = &account_response["sequence_number"];
match sequence_number.as_str() {
Some(number) => Ok(number.parse::<u64>().unwrap()),
None => Err(CommonError::ApiError(
"Sequence number not found".to_string(),
)),
None => Err(CliError::ApiError("Sequence number not found".to_string())),
}
}

Expand All @@ -75,7 +69,7 @@ impl CreateAccount {
sender_key: Ed25519PrivateKey,
sender_address: AccountAddress,
sequence_number: u64,
) -> Result<Response<Transaction>, Error> {
) -> CliTypedResult<Response<Transaction>> {
let client = RestClient::new(reqwest::Url::clone(&self.write_options.rest_options.url));
let transaction_factory = TransactionFactory::new(self.write_options.chain_id)
.with_gas_unit_price(1)
Expand All @@ -85,10 +79,13 @@ impl CreateAccount {
transaction_factory
.payload(aptos_stdlib::encode_create_account_script_function(address)),
);
client.submit_and_wait(&transaction).await
client
.submit_and_wait(&transaction)
.await
.map_err(|err| CliError::ApiError(err.to_string()))
}

async fn create_account_with_faucet(self, address: AccountAddress) -> Result<String, Error> {
async fn create_account_with_faucet(self, address: AccountAddress) -> CliTypedResult<()> {
let response = reqwest::Client::new()
// TODO: Currently, we are just using mint 0 to create an account using the faucet
// We should make a faucet endpoint for creating an account
Expand All @@ -97,51 +94,42 @@ impl CreateAccount {
"https://faucet.devnet.aptoslabs.com", self.initial_coins, address
))
.send()
.await?;
.await
.map_err(|err| CliError::ApiError(err.to_string()))?;
if response.status() == 200 {
Ok(response.status().to_string())
Ok(())
} else {
Err(Error::new(CommonError::ApiError(format!(
Err(CliError::ApiError(format!(
"Faucet issue: {}",
response.status()
))))
)))
}
}

async fn create_account_with_key(self, address: AccountAddress) -> Result<String, Error> {
async fn create_account_with_key(self, address: AccountAddress) -> CliTypedResult<()> {
let sender_private_key = self
.write_options
.private_key_options
.extract_private_key(self.encoding_options.encoding)?;
let sender_public_key = sender_private_key.public_key();
let sender_address = account_address_from_public_key(&sender_public_key);
let sequence_number = self.get_sequence_number(sender_address).await;
match sequence_number {
Ok(sequence_number) => self
.post_account(address, sender_private_key, sender_address, sequence_number)
.await
.map(|_| "Success".to_string()),
Err(err) => Err(Error::new(err)),
}
let sequence_number = self.get_sequence_number(sender_address).await?;
self.post_account(address, sender_private_key, sender_address, sequence_number)
.await?;
Ok(())
}

async fn execute_inner(self, address: AccountAddress) -> Result<String, Error> {
pub async fn execute(self) -> CliTypedResult<String> {
let public_key_to_create = self
.public_key_options
.extract_public_key(self.encoding_options.encoding)?;
let address = account_address_from_public_key(&public_key_to_create);

if self.use_faucet {
self.create_account_with_faucet(address).await
} else {
self.create_account_with_key(address).await
}
}

pub async fn execute(self) -> CliResult {
let public_key_to_create = self
.public_key_options
.extract_public_key(self.encoding_options.encoding)
.map_err(|err| err.to_string())?;
let new_address = account_address_from_public_key(&public_key_to_create);
self.execute_inner(new_address)
.await
.map(|_| format!("Account Created at {}", new_address))
.map_err(|err| err.to_string())
.map(|_| format!("Account Created at {}", address))
}
}
23 changes: 6 additions & 17 deletions crates/aptos/src/account/list.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,7 @@
//! TODO: Examples
//!
use crate::{
common::{types::RestOptions, utils::to_common_result},
CliResult, Error as CommonError,
};
use anyhow::Error;
use crate::common::types::{CliError, CliTypedResult, RestOptions};
use aptos_rest_client::{types::Resource, Client};
use aptos_types::account_address::AccountAddress;
use clap::Parser;
Expand All @@ -28,25 +24,18 @@ pub struct ListResources {
}

impl ListResources {
async fn get_resources(self) -> Result<Vec<serde_json::Value>, Error> {
// TODO: Format this in a reasonable way while providing all information
// add options like --tokens --nfts etc
pub(crate) async fn execute(self) -> CliTypedResult<Vec<serde_json::Value>> {
let client = Client::new(self.rest_options.url);
let response: Vec<Resource> = client
.get_account_resources(self.account)
.await?
.await
.map_err(|err| CliError::ApiError(err.to_string()))?
.into_inner();
Ok(response
.iter()
.map(|json| json.data.clone())
.collect::<Vec<serde_json::Value>>())
}

// TODO: Format this in a reasonable way while providing all information
// add options like --tokens --nfts etc
pub async fn execute(self) -> CliResult {
let result = self
.get_resources()
.await
.map_err(|err| CommonError::ApiError(err.to_string()));
to_common_result(result)
}
}
6 changes: 3 additions & 3 deletions crates/aptos/src/account/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
// Copyright (c) Aptos
// SPDX-License-Identifier: Apache-2.0

use crate::common::types::CliResult;
use crate::common::{types::CliResult, utils::to_common_result};
use clap::Subcommand;

pub mod create;
Expand All @@ -18,8 +18,8 @@ pub enum AccountTool {
impl AccountTool {
pub async fn execute(self) -> CliResult {
match self {
AccountTool::Create(tool) => tool.execute().await,
AccountTool::List(tool) => tool.execute().await,
AccountTool::Create(tool) => to_common_result(tool.execute().await),
AccountTool::List(tool) => to_common_result(tool.execute().await),
}
}
}
12 changes: 6 additions & 6 deletions crates/aptos/src/common/init.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,11 @@

use crate::{
common::{
types::CliConfig,
types::{CliConfig, CliError, CliTypedResult},
utils::{prompt_yes, to_common_success_result},
},
op::key::GenerateKey,
CliResult, Error,
CliResult,
};
use aptos_crypto::{ed25519::Ed25519PrivateKey, ValidCryptoMaterialStringExt};
use clap::Parser;
Expand All @@ -21,7 +21,7 @@ impl InitTool {
to_common_success_result(self.execute_inner().await)
}

async fn execute_inner(&self) -> Result<(), Error> {
async fn execute_inner(&self) -> CliTypedResult<()> {
let mut config = if CliConfig::config_exists()? {
if !prompt_yes(
"Aptos already initialized, do you want to overwrite the existing config?",
Expand All @@ -42,7 +42,7 @@ impl InitTool {
GenerateKey::generate_ed25519_in_memory()
} else {
Ed25519PrivateKey::from_encoded_string(input)
.map_err(|err| Error::UnableToParse("Ed25519PrivateKey", err.to_string()))?
.map_err(|err| CliError::UnableToParse("Ed25519PrivateKey", err.to_string()))?
};
config.private_key = Some(private_key);
config.save()?;
Expand All @@ -53,11 +53,11 @@ impl InitTool {
}

/// Reads a line from input
fn read_line(input_name: &'static str) -> Result<String, Error> {
fn read_line(input_name: &'static str) -> CliTypedResult<String> {
let mut input_buf = String::new();
let _ = std::io::stdin()
.read_line(&mut input_buf)
.map_err(|err| Error::IO(input_name.to_string(), err))?;
.map_err(|err| CliError::IO(input_name.to_string(), err))?;

Ok(input_buf)
}
Loading

0 comments on commit 5bf3d45

Please sign in to comment.