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

Add --output-json for call, instantiate & upload commands #722

Merged
merged 26 commits into from
Sep 12, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
Show all changes
26 commits
Select commit Hold shift + click to select a range
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
5 changes: 3 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,12 +5,13 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## [Unreleased]
- `--output-json` support for `call` and `instantiate` commands - [#722](https://github.com/paritytech/cargo-contract/pull/722)

## [2.0.0-alpha.2] - 2022-09-02

### Fixed
### Fixed
- Sync version of transcode crate to fix metadata parsing - [#723](https://githubcom/paritytech/cargo-contract/pull/723)
- Fix numbering of steps during `build` - [#715](https://githubcom/paritytech/cargo-contract/pull/715)
- Fix numbering of steps during `build` - [#715](https://github.com/paritytech/cargo-contract/pull/715)

## [2.0.0-alpha.1] - 2022-08-24

Expand Down
168 changes: 133 additions & 35 deletions crates/cargo-contract/src/cmd/extrinsics/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@

use super::{
display_contract_exec_result,
display_events,
error_details,
parse_balance,
prompt_confirm_tx,
state_call,
Expand All @@ -31,7 +29,14 @@ use super::{
PairSigner,
MAX_KEY_COL_WIDTH,
};

use crate::{
cmd::extrinsics::{
display_contract_exec_result_debug,
events::CallResult,
ErrorVariant,
GenericError,
},
name_value_println,
DEFAULT_KEY_COL_WIDTH,
};
Expand All @@ -40,8 +45,12 @@ use anyhow::{
Result,
};

use pallet_contracts_primitives::ContractExecResult;
use pallet_contracts_primitives::{
ContractExecResult,
StorageDeposit,
};
use scale::Encode;
use transcode::Value;

use std::fmt::Debug;
use subxt::{
Expand Down Expand Up @@ -70,9 +79,16 @@ pub struct CallCommand {
/// The value to be transferred as part of the call.
#[clap(name = "value", long, parse(try_from_str = parse_balance), default_value = "0")]
value: Balance,
/// Export the call output in JSON format.
#[clap(long, conflicts_with = "verbose")]
output_json: bool,
}

impl CallCommand {
pub fn is_json(&self) -> bool {
self.output_json
}

pub fn run(&self) -> Result<()> {
let crate_metadata = CrateMetadata::from_manifest_path(
self.extrinsic_opts.manifest_path.as_ref(),
Expand All @@ -94,27 +110,34 @@ impl CallCommand {
Ok(ref ret_val) => {
let value = transcoder
.decode_return(&self.message, &mut &ret_val.data.0[..])?;
name_value_println!(
"Result",
String::from("Success!"),
DEFAULT_KEY_COL_WIDTH
);
name_value_println!(
"Reverted",
format!("{:?}", ret_val.did_revert()),
DEFAULT_KEY_COL_WIDTH
);
name_value_println!(
"Data",
format!("{}", value),
DEFAULT_KEY_COL_WIDTH
);
display_contract_exec_result::<_, DEFAULT_KEY_COL_WIDTH>(&result)
let dry_run_result = CallDryRunResult {
result: String::from("Success!"),
reverted: ret_val.did_revert(),
data: value,
gas_consumed: result.gas_consumed,
gas_required: result.gas_required,
storage_deposit: result.storage_deposit.clone(),
};
if self.output_json {
println!("{}", dry_run_result.to_json()?);
Ok(())
} else {
dry_run_result.print();
display_contract_exec_result_debug::<_, DEFAULT_KEY_COL_WIDTH>(
&result,
)
}
}
Err(ref err) => {
let err = error_details(err, &client.metadata())?;
name_value_println!("Result", err, MAX_KEY_COL_WIDTH);
display_contract_exec_result::<_, MAX_KEY_COL_WIDTH>(&result)
let metadata = client.metadata();
let object = ErrorVariant::from_dispatch_error(err, &metadata)?;
if self.output_json {
eprintln!("{}", serde_json::to_string_pretty(&object)?);
Ok(())
} else {
name_value_println!("Result", object, MAX_KEY_COL_WIDTH);
display_contract_exec_result::<_, MAX_KEY_COL_WIDTH>(&result)
}
}
}
} else {
Expand Down Expand Up @@ -152,7 +175,12 @@ impl CallCommand {
tracing::debug!("calling contract {:?}", self.contract);

let gas_limit = self
.pre_submit_dry_run_gas_estimate(client, data.clone(), signer)
.pre_submit_dry_run_gas_estimate(
client,
data.clone(),
signer,
self.output_json,
)
.await?;

if !self.extrinsic_opts.skip_confirm {
Expand All @@ -175,14 +203,44 @@ impl CallCommand {
data,
);

let result = submit_extrinsic(client, &call, signer).await?;
let result = submit_extrinsic(client, &call, signer).await;

match result {
Ok(result) => {
let mut call_result = CallResult::from_events(
&result,
transcoder,
&client.metadata(),
Default::default(),
SkymanOne marked this conversation as resolved.
Show resolved Hide resolved
)?;

call_result.estimated_gas = gas_limit;

display_events(
&result,
transcoder,
&client.metadata(),
&self.extrinsic_opts.verbosity()?,
)
let output: String = if self.output_json {
call_result.to_json()?
} else {
call_result.display_events()
};
println!("{}", output);

Ok(())
}
Err(err) => {
if self.output_json {
eprintln!(
"{}",
serde_json::to_string_pretty(&ErrorVariant::Generic(
GenericError {
error: err.to_string()
}
))?
);
Ok(())
} else {
Err(err)
}
}
}
}

/// Dry run the call before tx submission. Returns the gas required estimate.
Expand All @@ -191,6 +249,7 @@ impl CallCommand {
client: &Client,
data: Vec<u8>,
signer: &PairSigner,
is_json: bool,
) -> Result<u64> {
if self.extrinsic_opts.skip_dry_run {
return match self.gas_limit {
Expand All @@ -202,18 +261,26 @@ impl CallCommand {
}
}
}
super::print_dry_running_status(&self.message);
if !is_json {
super::print_dry_running_status(&self.message);
}
let call_result = self.call_dry_run(data, signer).await?;
match call_result.result {
Ok(_) => {
super::print_gas_required_success(call_result.gas_required);
if !is_json {
super::print_gas_required_success(call_result.gas_required);
}
let gas_limit = self.gas_limit.unwrap_or(call_result.gas_required);
Ok(gas_limit)
}
Err(ref err) => {
let err = error_details(err, &client.metadata())?;
name_value_println!("Result", err, MAX_KEY_COL_WIDTH);
display_contract_exec_result::<_, MAX_KEY_COL_WIDTH>(&call_result)?;
let object = ErrorVariant::from_dispatch_error(err, &client.metadata())?;
if is_json {
eprintln!("{}", serde_json::to_string_pretty(&object)?);
} else {
name_value_println!("Result", object, MAX_KEY_COL_WIDTH);
display_contract_exec_result::<_, MAX_KEY_COL_WIDTH>(&call_result)?;
}
Err(anyhow!("Pre-submission dry-run failed. Use --skip-dry-run to skip this step."))
}
}
Expand All @@ -232,3 +299,34 @@ pub struct CallRequest {
storage_deposit_limit: Option<Balance>,
input_data: Vec<u8>,
}

/// Result of the contract call
#[derive(serde::Serialize)]
pub struct CallDryRunResult {
/// Result of a dry run
pub result: String,
/// Was the operation reverted
pub reverted: bool,
pub data: Value,
pub gas_consumed: u64,
pub gas_required: u64,
/// Storage deposit after the operation
pub storage_deposit: StorageDeposit<Balance>,
}

impl CallDryRunResult {
/// Returns a result in json format
pub fn to_json(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}

pub fn print(&self) {
name_value_println!("Result", self.result, DEFAULT_KEY_COL_WIDTH);
name_value_println!(
"Reverted",
format!("{:?}", self.reverted),
DEFAULT_KEY_COL_WIDTH
);
name_value_println!("Data", format!("{:?}", self.data), DEFAULT_KEY_COL_WIDTH);
}
}
Loading