Skip to content

Commit

Permalink
Add --binary flag for info command (#1311)
Browse files Browse the repository at this point in the history
* add info structure

* add info import

* change function call

* wip - fix some issues

* fix client error

* fix: fix info_contract_call getter

* remove from extrenstics condition

* Decode bytes into type.

* add first accountid handling

* refactor contract info getter and decoder by using fetch

* first draft for print in a good way contract ways

* add integration test for info

* remove extrenstics and add url flag for info command

* remove the useless check for accountId

* add doc

* fix fmt

* update changelog

* refactor: move out extrinstics info command

* remove ignore comments for integration tests

* change output format for info command

* remove tracing debug in integration tests

* fix fmt

* change trie id format

* fix fmt and format in a better way comments and output

* remove output_json

* fix fmt

* fix fmt output for trie_id

* change comments, docs and removing debug for inetgration tests

* complete doc

* docs: change minor term

* first draft to add output_json flag

* fix serde_json data to print

* remove useless comments for tests and doc

* Derive `Default` instances, make clippy happy 🦖

* fix output-json result

* remove useless return + fmt

* update changelog + doc

* first draft to print pristine_code

* fix fmt and clippy

* wip - second draft for binary flag

* wip - format ouput depending on the flag

* optimize the display

* fix fmt

* fix master merge and restore changes

* add docs + first draft of test

* complete tests

* fix error merge

* fix error merge

* change to display only pristine code

* fix temporary test

* fix fmt

* reimport items in binary outpuson

* Update crates/cargo-contract/src/cmd/info.rs

Co-authored-by: Michael Müller <[email protected]>

* Update crates/cargo-contract/src/cmd/info.rs

Co-authored-by: Michael Müller <[email protected]>

* Implemented combination of --binary and --output-json including code cleanup

* Removed BoundedVec from API

---------

Co-authored-by: lean-apple <[email protected]>
Co-authored-by: Andrew Jones <[email protected]>
Co-authored-by: Léa Narzis <[email protected]>
Co-authored-by: Michael Müller <[email protected]>
  • Loading branch information
5 people authored Sep 4, 2023
1 parent 0627b1e commit 497cb88
Show file tree
Hide file tree
Showing 5 changed files with 95 additions and 8 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Adds workflow for publishing docker images for the verifiable builds - [#1267](https://github.com/paritytech/cargo-contract/pull/1267)
- Detect `INK_STATIC_BUFFER_SIZE` env var - [#1310](https://github.com/paritytech/cargo-contract/pull/1310)
- Add `verify` command - [#1306](https://github.com/paritytech/cargo-contract/pull/1306)
- Add `--binary` flag for `info` command - [#1311](https://github.com/paritytech/cargo-contract/pull/1311/)

## [4.0.0-alpha]

Expand Down
53 changes: 48 additions & 5 deletions crates/cargo-contract/src/cmd/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,9 +24,13 @@ use anyhow::{
};
use contract_extrinsics::{
fetch_contract_info,
fetch_wasm_code,
ErrorVariant,
};
use std::fmt::Debug;
use std::{
fmt::Debug,
io::Write,
};
use subxt::{
Config,
OnlineClient,
Expand All @@ -50,6 +54,9 @@ pub struct InfoCommand {
/// Export the instantiate output in JSON format.
#[clap(name = "output-json", long)]
output_json: bool,
/// Display the contract's Wasm bytecode.
#[clap(name = "binary", long)]
binary: bool,
}

impl InfoCommand {
Expand All @@ -67,10 +74,46 @@ impl InfoCommand {

match info_result {
Some(info_to_json) => {
if self.output_json {
println!("{}", info_to_json.to_json()?);
} else {
basic_display_format_contract_info(&info_to_json);
match (self.output_json, self.binary) {
(true, false) => println!("{}", info_to_json.to_json()?),
(false, false) => {
basic_display_format_contract_info(&info_to_json)
}
// Binary flag applied
(_, true) => {
let wasm_code =
fetch_wasm_code(*info_to_json.code_hash(), &client)
.await?;
match (wasm_code, self.output_json) {
(Some(code), false) => {
std::io::stdout()
.write_all(&code)
.expect("Writing to stdout failed")
}
(Some(code), true) => {
let wasm = serde_json::json!({
"wasm": format!("0x{}", hex::encode(code))
});
println!(
"{}",
serde_json::to_string_pretty(&wasm).map_err(
|err| {
anyhow!(
"JSON serialization failed: {}",
err
)
}
)?
);
}
(None, _) => {
return Err(anyhow!(
"Contract wasm code was not found"
)
.into())
}
}
}
}
Ok(())
}
Expand Down
31 changes: 29 additions & 2 deletions crates/extrinsics/src/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ use crate::{
UploadCommandBuilder,
};
use anyhow::Result;
use contract_build::code_hash;
use predicates::prelude::*;
use std::{
ffi::OsStr,
Expand Down Expand Up @@ -358,15 +359,15 @@ async fn build_upload_instantiate_info() {
let contract_account = extract_contract_address(stdout);
assert_eq!(48, contract_account.len(), "{stdout:?}");

cargo_contract(project_path.as_path())
let output = cargo_contract(project_path.as_path())
.arg("info")
.args(["--contract", contract_account])
.output()
.expect("failed to execute process");
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(output.status.success(), "getting info failed: {stderr}");

cargo_contract(project_path.as_path())
let output = cargo_contract(project_path.as_path())
.arg("info")
.args(["--contract", contract_account])
.arg("--output-json")
Expand All @@ -378,6 +379,32 @@ async fn build_upload_instantiate_info() {
"getting info as JSON format failed: {stderr}"
);

let output = cargo_contract(project_path.as_path())
.arg("info")
.args(["--contract", contract_account])
.arg("--binary")
.output()
.expect("failed to execute process");
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(
output.status.success(),
"getting Wasm code failed: {stderr}"
);

// construct the contract file path
let contract_wasm = project_path.join("target/ink/flipper.wasm");

let code = std::fs::read(contract_wasm).expect("contract Wasm file not found");
assert_eq!(code_hash(&code), code_hash(&output.stdout));

cargo_contract(project_path.as_path())
.arg("info")
.args(["--contract", contract_account])
.arg("--output-json")
.arg("--binary")
.assert()
.stdout(predicate::str::contains(r#""wasm": "0x"#));

// prevent the node_process from being dropped and killed
let _ = node_process;
}
Expand Down
17 changes: 16 additions & 1 deletion crates/extrinsics/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ use jsonrpsee::{
};
use std::path::PathBuf;

use crate::runtime_api::api::{self,};
use crate::runtime_api::api;
use contract_build::{
CrateMetadata,
DEFAULT_KEY_COL_WIDTH,
Expand Down Expand Up @@ -363,6 +363,21 @@ impl ContractInfo {
}
}

/// Fetch the contract wasm code from the storage using the provided client and code hash.
pub async fn fetch_wasm_code(hash: CodeHash, client: &Client) -> Result<Option<Vec<u8>>> {
let pristine_code_address = api::storage().contracts().pristine_code(hash);

let pristine_bytes = client
.storage()
.at_latest()
.await?
.fetch(&pristine_code_address)
.await?
.map(|v| v.0);

Ok(pristine_bytes)
}

/// Copy of `pallet_contracts_primitives::StorageDeposit` which implements `Serialize`,
/// required for json output.
#[derive(Eq, PartialEq, Ord, PartialOrd, Clone, serde::Serialize)]
Expand Down
1 change: 1 addition & 0 deletions docs/info.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,4 @@ cargo contract info \
*Optional*
- `--url` the url of the rpc endpoint you want to specify - by default `ws://localhost:9944`.
- `--output-json` to export the output as JSON.
- `--binary` outputs Wasm code as a binary blob. If used in combination with `--output-json`, outputs Wasm code as JSON object with hex string.

0 comments on commit 497cb88

Please sign in to comment.