Skip to content

Commit

Permalink
feat: Added loading indicators for "contract" group commands (#357)
Browse files Browse the repository at this point in the history
  • Loading branch information
FroVolod authored Jun 26, 2024
1 parent 50afeee commit 03be69e
Show file tree
Hide file tree
Showing 7 changed files with 211 additions and 141 deletions.
68 changes: 35 additions & 33 deletions src/commands/contract/call_function/as_read_only/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -77,39 +77,7 @@ impl FunctionContext {
let function_name = scope.function_name.clone();

move |network_config, block_reference| {
let args = super::call_function_args_type::function_args(
function_args.clone(),
function_args_type.clone(),
)?;

let call_result = network_config
.json_rpc_client()
.blocking_call_view_function(
&account_id,
&function_name,
args,
block_reference.clone(),
)
.wrap_err_with(|| {
format!("Failed to fetch query for view method: '{}' (contract <{}> on network <{}>)",
function_name,
account_id,
network_config.network_name
)
})?;
call_result.print_logs();
eprintln!("Result:");
if call_result.result.is_empty() {
eprintln!("Empty result");
} else if let Ok(json_result) = call_result.parse_result_from_json::<serde_json::Value>() {
println!("{}", serde_json::to_string_pretty(&json_result)?);
} else if let Ok(string_result) = String::from_utf8(call_result.result) {
println!("{string_result}");
} else {
eprintln!("The returned value is not printable (binary data)");
}
eprintln!("--------------");
Ok(())
call_view_function(network_config, &account_id, &function_name, function_args.clone(), function_args_type.clone(), block_reference)
}
});

Expand Down Expand Up @@ -140,3 +108,37 @@ impl Function {
super::input_view_function_name(&context.global_context, &context.contract_account_id)
}
}

#[tracing::instrument(name = "Getting a response to a view method ...", skip_all)]
fn call_view_function(
network_config: &crate::config::NetworkConfig,
account_id: &near_primitives::types::AccountId,
function_name: &str,
function_args: String,
function_args_type: super::call_function_args_type::FunctionArgsType,
block_reference: &near_primitives::types::BlockReference,
) -> crate::CliResult {
let args = super::call_function_args_type::function_args(function_args, function_args_type)?;
let call_result = network_config
.json_rpc_client()
.blocking_call_view_function(account_id, function_name, args, block_reference.clone())
.wrap_err_with(|| {
format!(
"Failed to fetch query for view method: '{}' (contract <{}> on network <{}>)",
function_name, account_id, network_config.network_name
)
})?;
call_result.print_logs();
eprintln!("Result:");
if call_result.result.is_empty() {
eprintln!("Empty result");
} else if let Ok(json_result) = call_result.parse_result_from_json::<serde_json::Value>() {
println!("{}", serde_json::to_string_pretty(&json_result)?);
} else if let Ok(string_result) = String::from_utf8(call_result.result) {
println!("{string_result}");
} else {
eprintln!("The returned value is not printable (binary data)");
}
eprintln!("--------------");
Ok(())
}
35 changes: 24 additions & 11 deletions src/commands/contract/download_abi/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,17 +69,7 @@ impl DownloadContractContext {
let file_path: std::path::PathBuf = scope.file_path.clone().into();

move |network_config, block_reference| {
let abi_root = tokio::runtime::Runtime::new()
.unwrap()
.block_on(super::inspect::get_contract_abi(&network_config.json_rpc_client(), block_reference, &account_id))?;
std::fs::File::create(&file_path)
.wrap_err_with(|| format!("Failed to create file: {:?}", &file_path))?
.write(&serde_json::to_vec_pretty(&abi_root)?)
.wrap_err_with(|| {
format!("Failed to write to file: {:?}", &file_path)
})?;
eprintln!("\nThe file {:?} was downloaded successfully", &file_path);
Ok(())
download_contract_abi(&account_id, &file_path, network_config, block_reference)
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
Expand Down Expand Up @@ -110,3 +100,26 @@ impl DownloadContractAbi {
))
}
}

#[tracing::instrument(name = "Download the ABI for the contract ...", skip_all)]
fn download_contract_abi(
account_id: &near_primitives::types::AccountId,
file_path: &std::path::PathBuf,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> crate::CliResult {
let abi_root =
tokio::runtime::Runtime::new()
.unwrap()
.block_on(super::inspect::get_contract_abi(
&network_config.json_rpc_client(),
block_reference,
account_id,
))?;
std::fs::File::create(file_path)
.wrap_err_with(|| format!("Failed to create file: {:?}", file_path))?
.write(&serde_json::to_vec_pretty(&abi_root)?)
.wrap_err_with(|| format!("Failed to write to file: {:?}", file_path))?;
eprintln!("\nThe file {:?} was downloaded successfully", file_path);
Ok(())
}
65 changes: 39 additions & 26 deletions src/commands/contract/download_wasm/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -71,32 +71,7 @@ impl DownloadContractContext {
let file_path: std::path::PathBuf = scope.file_path.clone().into();

move |network_config, block_reference| {
let query_view_method_response = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.wrap_err_with(|| format!("Failed to fetch query ViewCode for <{}> on network <{}>", &account_id, network_config.network_name))?;
let call_access_view =
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
query_view_method_response.kind
{
result
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
std::fs::File::create(&file_path)
.wrap_err_with(|| format!("Failed to create file: {:?}", &file_path))?
.write(&call_access_view.code)
.wrap_err_with(|| {
format!("Failed to write to file: {:?}", &file_path)
})?;
eprintln!("\nThe file {:?} was downloaded successfully", &file_path);

Ok(())
download_contract_code(&account_id, &file_path, network_config, block_reference.clone())
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
Expand Down Expand Up @@ -127,3 +102,41 @@ impl DownloadContract {
))
}
}

#[tracing::instrument(name = "Download contract code ...", skip_all)]
fn download_contract_code(
account_id: &near_primitives::types::AccountId,
file_path: &std::path::PathBuf,
network_config: &crate::config::NetworkConfig,
block_reference: near_primitives::types::BlockReference,
) -> crate::CliResult {
let query_view_method_response = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference,
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewCode for <{}> on network <{}>",
account_id, network_config.network_name
)
})?;
let call_access_view =
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewCode(result) =
query_view_method_response.kind
{
result
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
std::fs::File::create(file_path)
.wrap_err_with(|| format!("Failed to create file: {:?}", file_path))?
.write(&call_access_view.code)
.wrap_err_with(|| format!("Failed to write to file: {:?}", file_path))?;
eprintln!("\nThe file {:?} was downloaded successfully", file_path);

Ok(())
}
61 changes: 48 additions & 13 deletions src/commands/contract/inspect/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ use color_eyre::{
owo_colors::OwoColorize,
};
use thiserror::Error;
use tracing_indicatif::span_ext::IndicatifSpanExt;

use near_primitives::types::{BlockId, BlockReference};

Expand Down Expand Up @@ -47,19 +48,7 @@ impl ContractContext {
let account_id: near_primitives::types::AccountId = scope.contract_account_id.clone().into();

move |network_config, block_reference| {
let view_code_response = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.wrap_err_with(|| format!("Failed to fetch query ViewCode for <{}> on network <{}>", &account_id, network_config.network_name))?;

tokio::runtime::Runtime::new()
.unwrap()
.block_on(display_inspect_contract(&account_id, network_config, view_code_response))
inspect_contract(&account_id, network_config, block_reference)
}
});
Ok(Self(crate::network_view_at_block::ArgsForViewContext {
Expand All @@ -76,6 +65,46 @@ impl From<ContractContext> for crate::network_view_at_block::ArgsForViewContext
}
}

#[tracing::instrument(name = "Contract inspection ...", skip_all)]
fn inspect_contract(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> crate::CliResult {
let view_code_response = get_contract_code(account_id, network_config, block_reference)?;

tokio::runtime::Runtime::new()
.unwrap()
.block_on(display_inspect_contract(
account_id,
network_config,
view_code_response,
))
}

#[tracing::instrument(name = "Obtaining the contract code ...", skip_all)]
fn get_contract_code(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
block_reference: &near_primitives::types::BlockReference,
) -> color_eyre::eyre::Result<near_jsonrpc_client::methods::query::RpcQueryResponse> {
network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewCode {
account_id: account_id.clone(),
},
})
.wrap_err_with(|| {
format!(
"Failed to fetch query ViewCode for <{}> on network <{}>",
&account_id, network_config.network_name
)
})
}

#[tracing::instrument(name = "Analysis of contract data ...", skip_all)]
async fn display_inspect_contract(
account_id: &near_primitives::types::AccountId,
network_config: &crate::config::NetworkConfig,
Expand Down Expand Up @@ -345,12 +374,14 @@ async fn display_inspect_contract(
Ok(())
}

#[tracing::instrument(name = "Getting information about", skip_all)]
async fn get_account_view(
network_name: &str,
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<near_primitives::views::AccountView> {
tracing::Span::current().pb_set_message(&format!("{account_id} ..."));
for _ in 0..5 {
let account_view_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
Expand Down Expand Up @@ -381,12 +412,14 @@ async fn get_account_view(
)))
}

#[tracing::instrument(name = "Getting a list of", skip_all)]
async fn get_access_keys(
network_name: &str,
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
account_id: &near_primitives::types::AccountId,
) -> color_eyre::eyre::Result<Vec<near_primitives::views::AccessKeyInfoView>> {
tracing::Span::current().pb_set_message(&format!("{account_id} access keys ..."));
for _ in 0..5 {
let access_keys_response = json_rpc_client
.call(near_jsonrpc_client::methods::query::RpcQueryRequest {
Expand Down Expand Up @@ -432,6 +465,7 @@ pub enum FetchContractSourceMetadataError {
ContractSourceMetadataUnknownFormat(Report),
}

#[tracing::instrument(name = "Getting contract source metadata", skip_all)]
async fn get_contract_source_metadata(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
Expand Down Expand Up @@ -498,6 +532,7 @@ pub enum FetchAbiError {
),
}

#[tracing::instrument(name = "Obtaining the ABI for the contract ...", skip_all)]
pub async fn get_contract_abi(
json_rpc_client: &near_jsonrpc_client::JsonRpcClient,
block_reference: &BlockReference,
Expand Down
47 changes: 18 additions & 29 deletions src/commands/contract/view_storage/output_format/as_json.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
use crate::common::JsonRpcClientExt;
use color_eyre::eyre::Context;

#[derive(Debug, Clone, interactive_clap::InteractiveClap)]
#[interactive_clap(input_context = super::super::keys_to_view::KeysContext)]
#[interactive_clap(output_context = AsJsonContext)]
Expand All @@ -23,32 +20,24 @@ impl AsJsonContext {
let prefix = previous_context.prefix;

move |network_config, block_reference| {
let query_view_method_response = network_config
.json_rpc_client()
.blocking_call(near_jsonrpc_client::methods::query::RpcQueryRequest {
block_reference: block_reference.clone(),
request: near_primitives::views::QueryRequest::ViewState {
account_id: contract_account_id.clone(),
prefix: prefix.clone(),
include_proof: false,
},
})
.wrap_err_with(|| format!("Failed to fetch query ViewState for <{contract_account_id}> on network <{}>", network_config.network_name))?;
if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewState(result) =
query_view_method_response.kind
{
eprintln!("Contract state (values):");
println!(
"{}",
serde_json::to_string_pretty(&result.values)?
);
eprintln!(
"\nContract state (proof):\n{:#?}\n",
&result.proof
);
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
let query_view_method_response =
super::get_contract_state(&contract_account_id, prefix.clone(), network_config, block_reference.clone())?;

if let near_jsonrpc_primitives::types::query::QueryResponseKind::ViewState(result) =
query_view_method_response.kind
{
eprintln!("Contract state (values):");
println!(
"{}",
serde_json::to_string_pretty(&result.values)?
);
eprintln!(
"\nContract state (proof):\n{:#?}\n",
&result.proof
);
} else {
return Err(color_eyre::Report::msg("Error call result".to_string()));
};
Ok(())
}
});
Expand Down
Loading

0 comments on commit 03be69e

Please sign in to comment.