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 remove command #837

Merged
merged 38 commits into from
Feb 15, 2023
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
b7e587a
first version of remove command integration
lean-apple Nov 22, 2022
810661a
import remove command
lean-apple Nov 23, 2022
4b86a21
fix some type errors for code_hash
lean-apple Dec 7, 2022
d6c41d9
update with last changes
lean-apple Dec 7, 2022
08d5198
optimize parse_code_hash function use
lean-apple Dec 14, 2022
ebeecd5
remove rpc call and code use
lean-apple Dec 19, 2022
9fa4706
Merge branch 'master' into ln-add-remove-command
lean-apple Jan 9, 2023
ea7f284
get last changes
lean-apple Jan 16, 2023
f07ee02
use new way to get code_hash
lean-apple Jan 16, 2023
a3fea1d
fix event for remove command result
lean-apple Jan 19, 2023
f27a4ee
fix fmt
lean-apple Jan 19, 2023
3426398
change the way to get code hash
lean-apple Jan 20, 2023
2f2f68c
add last changes
lean-apple Jan 23, 2023
def1ade
add remove command integration test
lean-apple Jan 24, 2023
33a6662
fix fmt
lean-apple Jan 24, 2023
05d9e75
Merge branch 'master' into ln-add-remove-command
lean-apple Jan 25, 2023
27e25b9
ignore integration tests
lean-apple Jan 25, 2023
2b2ce84
complete documentation for remove command
lean-apple Jan 25, 2023
d94be80
remove unused parse code hash function
lean-apple Jan 25, 2023
67e5a77
fix: draft for code_hash arg return
lean-apple Jan 27, 2023
dcccb12
complete remove command documentation with code-hash
lean-apple Jan 27, 2023
4aee17f
fix previous merge of last changes
lean-apple Jan 27, 2023
bb30200
fix previous merge of last changes
lean-apple Jan 27, 2023
6551782
fix previous merge of last changes
lean-apple Jan 27, 2023
9daca4c
fix: fix code_hash check but still error variant issue
lean-apple Jan 27, 2023
c9fc21c
Merge branch 'master' into ln-add-remove-command
lean-apple Feb 2, 2023
e80644a
fix code-hash handle
lean-apple Feb 3, 2023
caf4879
get last changes
lean-apple Feb 10, 2023
6058aa8
optimize get hash and error message
lean-apple Feb 13, 2023
bd958be
fix documentation
lean-apple Feb 13, 2023
3622781
improve code_hash
lean-apple Feb 14, 2023
7383163
fix error handling
lean-apple Feb 14, 2023
a857219
Add api imports
ascjones Feb 15, 2023
a39c712
Use correct event type
ascjones Feb 15, 2023
cba704b
Fix extrinsics.md
ascjones Feb 15, 2023
c733739
Fix extrinsics.md
ascjones Feb 15, 2023
27763a2
Wrap long error message
ascjones Feb 15, 2023
59117d8
Error message formatting
ascjones Feb 15, 2023
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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,9 @@ First release candidate for compatibility with `ink! 4.0-rc`.
### Changed
- Extrinsics: allow specifying contract artifact directly [#893](https://github.com/paritytech/cargo-contract/pull/893)

### Added
- Add `cargo contract remove` command [#837](https://github.com/paritytech/cargo-contract/pull/837)

## [2.0.0-beta.2] - 2023-01-09

### Changed
Expand Down
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ This can be either an event, an invocation of a contract message, or an invocati

The argument has to be given as hex-encoding, starting with `0x`.

##### `cargo contract remove`

Remove a contract to a `pallet-contracts` enabled chain. See [extrinsics](docs/extrinsics.md).
ascjones marked this conversation as resolved.
Show resolved Hide resolved

## License

The entire code within this repository is licensed under the [GPLv3](LICENSE).
Expand Down
2 changes: 1 addition & 1 deletion crates/cargo-contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -67,5 +67,5 @@ std = []
test-ci-only = []

# Enable this to execute tests which depend on a locally running contracts enabed chain
# e.g.https://github.com/paritytech/canvas-node
# e.g.https://github.com/paritytech/substrate-contracts-node
integration-tests = []
66 changes: 57 additions & 9 deletions crates/cargo-contract/src/cmd/extrinsics/integration_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -193,22 +193,14 @@ async fn build_upload_instantiate_call() {
.output()
.expect("failed to execute process");
println!("status: {}", output.status);
let stdout = str::from_utf8(&output.stdout).unwrap();
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(output.status.success(), "upload code failed: {}", stderr);

// find the code hash in the output
let regex = regex::Regex::new("0x([0-9A-Fa-f]+)").unwrap();
let caps = regex.captures(stdout).expect("Failed to find codehash");
let code_hash = caps.get(1).unwrap().as_str();
assert_eq!(64, code_hash.len());

tracing::debug!("Instantiating the contract with code hash `{}`", code_hash);
tracing::debug!("Instantiating the contract");
let output = cargo_contract(project_path.as_path())
.arg("instantiate")
.args(["--constructor", "new"])
.args(["--args", "true"])
.args(["--code-hash", code_hash])
.args(["--suri", "//Alice"])
.output()
.expect("failed to execute process");
Expand Down Expand Up @@ -253,3 +245,59 @@ async fn build_upload_instantiate_call() {
// prevent the node_process from being dropped and killed
let _ = node_process;
}

/// Sanity test the whole lifecycle of:
/// build -> upload -> remove
#[ignore]
#[async_std::test]
async fn build_upload_remove() {
init_tracing_subscriber();

let tmp_dir = tempfile::Builder::new()
.prefix("cargo-contract.cli.test.")
.tempdir()
.expect("temporary directory creation failed");

// Spawn the contracts node
let node_process = ContractsNodeProcess::spawn(CONTRACTS_NODE)
.await
.expect("Error spawning contracts node");

// cargo contract new flipper
cargo_contract(tmp_dir.path())
.arg("new")
.arg("incrementer")
.assert()
.success();

// cd incrementer
let mut project_path = tmp_dir.path().to_path_buf();
project_path.push("incrementer");

tracing::debug!("Building contract in {}", project_path.to_string_lossy());
cargo_contract(project_path.as_path())
.arg("build")
.assert()
.success();

tracing::debug!("Uploading the code to the substrate-contracts-node chain");
let output = cargo_contract(project_path.as_path())
.arg("upload")
.args(["--suri", "//Alice"])
.output()
.expect("failed to execute process");
println!("status: {}", output.status);
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(output.status.success(), "upload code failed: {}", stderr);

tracing::debug!("Removing the contract");
let output = cargo_contract(project_path.as_path())
.arg("remove")
.args(["--suri", "//Alice"])
.output()
.expect("failed to execute process");
let stderr = str::from_utf8(&output.stderr).unwrap();
assert!(output.status.success(), "remove failed: {}", stderr);

let _ = node_process;
}
3 changes: 3 additions & 0 deletions crates/cargo-contract/src/cmd/extrinsics/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ mod call;
mod error;
mod events;
mod instantiate;
mod remove;
mod runtime_api;
mod upload;

Expand Down Expand Up @@ -47,6 +48,7 @@ use std::{
};

use crate::DEFAULT_KEY_COL_WIDTH;

use contract_build::{
name_value_println,
CrateMetadata,
Expand Down Expand Up @@ -86,6 +88,7 @@ use contract_metadata::ContractMetadata;
pub use contract_transcode::ContractMessageTranscoder;
pub use error::ErrorVariant;
pub use instantiate::InstantiateCommand;
pub use remove::RemoveCommand;
pub use subxt::PolkadotConfig as DefaultConfig;
pub use upload::UploadCommand;

Expand Down
133 changes: 133 additions & 0 deletions crates/cargo-contract/src/cmd/extrinsics/remove.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
// Copyright 2018-2022 Parity Technologies (UK) Ltd.
// This file is part of cargo-contract.
//
// cargo-contract is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// cargo-contract is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.

use super::{
runtime_api::api,
submit_extrinsic,
Client,
CodeHash,
ContractMessageTranscoder,
ExtrinsicOpts,
PairSigner,
TokenMetadata,
};
use crate::{
cmd::extrinsics::{
events::DisplayEvents,
ErrorVariant,
},
name_value_println,
};
use anyhow::Result;
use std::fmt::Debug;
use subxt::OnlineClient;

#[derive(Debug, clap::Args)]
#[clap(name = "remove", about = "Remove a contract's code")]
pub struct RemoveCommand {
#[clap(flatten)]
extrinsic_opts: ExtrinsicOpts,
/// Export the call output in JSON format.
#[clap(long, conflicts_with = "verbose")]
output_json: bool,
}

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

pub fn run(&self) -> Result<(), ErrorVariant> {
let artifacts = self.extrinsic_opts.contract_artifacts()?;
let transcoder = artifacts.contract_transcoder()?;
let signer = super::pair_signer(self.extrinsic_opts.signer()?);

let artifacts_path = artifacts.artifact_path().to_path_buf();
let code = artifacts.code.ok_or_else(|| {
anyhow::anyhow!(
"Contract code not found from artifact file {}",
artifacts_path.display()
)
})?;
ascjones marked this conversation as resolved.
Show resolved Hide resolved
let code_hash = code.code_hash();
ascjones marked this conversation as resolved.
Show resolved Hide resolved

async_std::task::block_on(async {
let url = self.extrinsic_opts.url_to_string();
let client = OnlineClient::from_url(url.clone()).await?;

if let Some(code_removed) = self
.remove_code(&client, sp_core::H256(code_hash), &signer, &transcoder)
.await?
{
let remove_result = RemoveResult {
ascjones marked this conversation as resolved.
Show resolved Hide resolved
code_hash: format!("{:?}", code_removed.code_hash),
};
if self.output_json {
println!("{}", remove_result.to_json()?);
} else {
remove_result.print();
}
Ok(())
ascjones marked this conversation as resolved.
Show resolved Hide resolved
} else {
Err(anyhow::anyhow!(
"This contract could not have been removed for the supplied code hash: {code_hash:?}")
.into())
}
})
}

async fn remove_code(
&self,
client: &Client,
code_hash: CodeHash,
signer: &PairSigner,
transcoder: &ContractMessageTranscoder,
) -> Result<Option<api::contracts::events::CodeRemoved>, ErrorVariant> {
let call = super::runtime_api::api::tx()
.contracts()
.remove_code(sp_core::H256(code_hash.0));

let result = submit_extrinsic(client, &call, signer).await?;
let display_events =
DisplayEvents::from_events(&result, Some(transcoder), &client.metadata())?;

let output = if self.output_json {
display_events.to_json()?
} else {
let token_metadata = TokenMetadata::query(client).await?;
display_events
.display_events(self.extrinsic_opts.verbosity()?, &token_metadata)?
};
println!("{}", output);
let code_removed = result.find_first::<api::contracts::events::CodeRemoved>()?;
Ok(code_removed)
}
}

/// Reference to an existing code hash or a new Wasm module.
#[derive(serde::Serialize)]
pub struct RemoveResult {
code_hash: String,
}
impl RemoveResult {
pub fn to_json(&self) -> Result<String> {
Ok(serde_json::to_string_pretty(self)?)
}

pub fn print(&self) {
name_value_println!("Code hash", format!("{:?}", self.code_hash));
}
}
1 change: 1 addition & 0 deletions crates/cargo-contract/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,5 +32,6 @@ pub(crate) use self::extrinsics::{
CallCommand,
ErrorVariant,
InstantiateCommand,
RemoveCommand,
UploadCommand,
};
9 changes: 9 additions & 0 deletions crates/cargo-contract/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ use self::cmd::{
DecodeCommand,
ErrorVariant,
InstantiateCommand,
RemoveCommand,
TestCommand,
UploadCommand,
};
Expand Down Expand Up @@ -126,6 +127,9 @@ enum Command {
/// Decodes a contracts input or output data (supplied in hex-encoding)
#[clap(name = "decode")]
Decode(DecodeCommand),
/// Remove contract code
#[clap(name = "remove")]
Remove(RemoveCommand),
}

fn main() {
Expand Down Expand Up @@ -192,6 +196,11 @@ fn exec(cmd: Command) -> Result<()> {
.map_err(|err| map_extrinsic_err(err, call.is_json()))
}
Command::Decode(decode) => decode.run().map_err(format_err),
Command::Remove(remove) => {
remove
.run()
.map_err(|err| map_extrinsic_err(err, remove.is_json()))
}
}
}

Expand Down
10 changes: 10 additions & 0 deletions docs/extrinsics.md
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,16 @@ cargo contract call \
- `--message` the name of the contract message to invoke.
- `--args` accepts a space separated list of values, encoded in order as the arguments of the message to invoke.

### `remove`

Remove the Wasm code of the contract to the target chain. Invokes the [`remove_code`](https://github.com/paritytech/substrate/blob/master/frame/contracts/src/lib.rs#L581)
dispatchable.

e.g. `cargo contract remove --suri //Alice`

Assumes that `cargo contract build` and `cargo contract upload` have already been run to produce the contract artifacts.
ascjones marked this conversation as resolved.
Show resolved Hide resolved
Yet be sure your contract has not been instantiated ie it is not used by any contract.
ascjones marked this conversation as resolved.
Show resolved Hide resolved

## Specifying the contract artifact

The above examples assume the working directory is the contract source code where the `Cargo.toml` file is located.
Expand Down