Skip to content

Commit

Permalink
Simplify extrinisics crate and remove printing logic (#1495)
Browse files Browse the repository at this point in the history
  • Loading branch information
smiasojed authored Feb 21, 2024
1 parent dbc00de commit ea5ccca
Show file tree
Hide file tree
Showing 17 changed files with 414 additions and 718 deletions.
2 changes: 2 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions crates/cargo-contract/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ subxt = "0.34.0"
sp-core = "28.0.0"
sp-weights = "27.0.0"
hex = "0.4.3"
subxt-signer = { version = "0.34.0", features = ["subxt", "sr25519"] }

[build-dependencies]
anyhow = "1.0.80"
Expand Down
51 changes: 33 additions & 18 deletions crates/cargo-contract/src/cmd/call.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ use ink_env::{
use std::fmt::Debug;

use super::{
create_signer,
display_contract_exec_result,
display_contract_exec_result_debug,
display_dry_run_result_warning,
Expand All @@ -44,15 +45,17 @@ use contract_extrinsics::{
BalanceVariant,
CallCommandBuilder,
CallExec,
DisplayEvents,
ExtrinsicOptsBuilder,
TokenMetadata,
};
use contract_transcode::Value;
use sp_weights::Weight;
use subxt::{
Config,
PolkadotConfig as DefaultConfig,
};

use subxt_signer::sr25519::Keypair;
#[derive(Debug, clap::Args)]
#[clap(name = "call", about = "Call a contract")]
pub struct CallCommand {
Expand Down Expand Up @@ -92,24 +95,32 @@ impl CallCommand {
}

pub async fn handle(&self) -> Result<(), ErrorVariant> {
let extrinsic_opts = ExtrinsicOptsBuilder::default()
let token_metadata =
TokenMetadata::query::<DefaultConfig>(&self.extrinsic_cli_opts.url).await?;

let signer = create_signer(&self.extrinsic_cli_opts.suri)?;
let extrinsic_opts = ExtrinsicOptsBuilder::new(signer)
.file(self.extrinsic_cli_opts.file.clone())
.manifest_path(self.extrinsic_cli_opts.manifest_path.clone())
.url(self.extrinsic_cli_opts.url.clone())
.suri(self.extrinsic_cli_opts.suri.clone())
.storage_deposit_limit(self.extrinsic_cli_opts.storage_deposit_limit.clone())
.storage_deposit_limit(
self.extrinsic_cli_opts
.storage_deposit_limit
.clone()
.map(|bv| bv.denominate_balance(&token_metadata))
.transpose()?,
)
.verbosity(self.extrinsic_cli_opts.verbosity()?)
.done();
let call_exec = CallCommandBuilder::default()
.contract(self.contract.clone())
.message(self.message.clone())
.args(self.args.clone())
.extrinsic_opts(extrinsic_opts)
.gas_limit(self.gas_limit)
.proof_size(self.proof_size)
.value(self.value.clone())
.done()
.await?;
let call_exec =
CallCommandBuilder::new(self.contract.clone(), &self.message, extrinsic_opts)
.args(self.args.clone())
.gas_limit(self.gas_limit)
.proof_size(self.proof_size)
.value(self.value.denominate_balance(&token_metadata)?)
.done()
.await?;
let metadata = call_exec.client().metadata();

if !self.extrinsic_cli_opts.execute {
let result = call_exec.call_dry_run().await?;
Expand Down Expand Up @@ -143,7 +154,6 @@ impl CallCommand {
};
}
Err(ref err) => {
let metadata = call_exec.client().metadata();
let object = ErrorVariant::from_dispatch_error(err, &metadata)?;
if self.output_json() {
return Err(object)
Expand Down Expand Up @@ -179,13 +189,18 @@ impl CallCommand {
);
})?;
}
let display_events = call_exec.call(Some(gas_limit)).await?;
let events = call_exec.call(Some(gas_limit)).await?;
let display_events = DisplayEvents::from_events::<
DefaultConfig,
DefaultEnvironment,
>(&events, None, &metadata)?;

let output = if self.output_json() {
display_events.to_json()?
} else {
display_events.display_events::<DefaultEnvironment>(
self.extrinsic_cli_opts.verbosity().unwrap(),
call_exec.token_metadata(),
&token_metadata,
)?
};
println!("{output}");
Expand All @@ -196,7 +211,7 @@ impl CallCommand {

/// A helper function to estimate the gas required for a contract call.
async fn pre_submit_dry_run_gas_estimate_call(
call_exec: &CallExec<DefaultConfig, DefaultEnvironment>,
call_exec: &CallExec<DefaultConfig, DefaultEnvironment, Keypair>,
output_json: bool,
skip_dry_run: bool,
) -> Result<Weight> {
Expand Down
57 changes: 35 additions & 22 deletions crates/cargo-contract/src/cmd/instantiate.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
// along with cargo-contract. If not, see <http://www.gnu.org/licenses/>.

use super::{
create_signer,
display_contract_exec_result,
display_contract_exec_result_debug,
display_dry_run_result_warning,
Expand Down Expand Up @@ -47,6 +48,7 @@ use contract_extrinsics::{
InstantiateCommandBuilder,
InstantiateDryRunResult,
InstantiateExecResult,
TokenMetadata,
};
use ink_env::{
DefaultEnvironment,
Expand All @@ -55,6 +57,7 @@ use ink_env::{
use sp_core::Bytes;
use std::fmt::Debug;
use subxt::PolkadotConfig as DefaultConfig;
use subxt_signer::sr25519::Keypair;

#[derive(Debug, clap::Args)]
pub struct InstantiateCommand {
Expand Down Expand Up @@ -100,24 +103,35 @@ impl InstantiateCommand {
}

pub async fn handle(&self) -> Result<(), ErrorVariant> {
let extrinsic_opts = ExtrinsicOptsBuilder::default()
let token_metadata =
TokenMetadata::query::<DefaultConfig>(&self.extrinsic_cli_opts.url).await?;

let signer = create_signer(&self.extrinsic_cli_opts.suri)?;
let extrinsic_opts = ExtrinsicOptsBuilder::new(signer)
.file(self.extrinsic_cli_opts.file.clone())
.manifest_path(self.extrinsic_cli_opts.manifest_path.clone())
.url(self.extrinsic_cli_opts.url.clone())
.suri(self.extrinsic_cli_opts.suri.clone())
.storage_deposit_limit(self.extrinsic_cli_opts.storage_deposit_limit.clone())
.storage_deposit_limit(
self.extrinsic_cli_opts
.storage_deposit_limit
.clone()
.map(|bv| bv.denominate_balance(&token_metadata))
.transpose()?,
)
.done();
let instantiate_exec: InstantiateExec<DefaultConfig, DefaultEnvironment> =
InstantiateCommandBuilder::default()
.constructor(self.constructor.clone())
.args(self.args.clone())
.extrinsic_opts(extrinsic_opts)
.value(self.value.clone())
.gas_limit(self.gas_limit)
.proof_size(self.proof_size)
.salt(self.salt.clone())
.done()
.await?;
let instantiate_exec: InstantiateExec<
DefaultConfig,
DefaultEnvironment,
Keypair,
> = InstantiateCommandBuilder::new(extrinsic_opts)
.constructor(self.constructor.clone())
.args(self.args.clone())
.value(self.value.denominate_balance(&token_metadata)?)
.gas_limit(self.gas_limit)
.proof_size(self.proof_size)
.salt(self.salt.clone())
.done()
.await?;

if !self.extrinsic_cli_opts.execute {
let result = instantiate_exec.instantiate_dry_run().await?;
Expand Down Expand Up @@ -171,6 +185,7 @@ impl InstantiateCommand {
display_result(
&instantiate_exec,
instantiate_result,
&token_metadata,
self.output_json(),
self.extrinsic_cli_opts.verbosity().unwrap(),
)
Expand All @@ -182,7 +197,7 @@ impl InstantiateCommand {

/// A helper function to estimate the gas required for a contract instantiation.
async fn pre_submit_dry_run_gas_estimate_instantiate(
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment>,
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment, Keypair>,
output_json: bool,
skip_dry_run: bool,
) -> Result<Weight> {
Expand Down Expand Up @@ -238,13 +253,14 @@ async fn pre_submit_dry_run_gas_estimate_instantiate(
/// Displays the results of contract instantiation, including contract address,
/// events, and optional code hash.
pub async fn display_result(
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment>,
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment, Keypair>,
instantiate_exec_result: InstantiateExecResult<DefaultConfig>,
token_metadata: &TokenMetadata,
output_json: bool,
verbosity: Verbosity,
) -> Result<(), ErrorVariant> {
let events = DisplayEvents::from_events::<DefaultConfig, DefaultEnvironment>(
&instantiate_exec_result.result,
&instantiate_exec_result.events,
Some(instantiate_exec.transcoder()),
&instantiate_exec.client().metadata(),
)?;
Expand All @@ -261,10 +277,7 @@ pub async fn display_result(
} else {
println!(
"{}",
events.display_events::<DefaultEnvironment>(
verbosity,
&instantiate_exec_result.token_metadata
)?
events.display_events::<DefaultEnvironment>(verbosity, token_metadata)?
);
if let Some(code_hash) = instantiate_exec_result.code_hash {
name_value_println!("Code hash", format!("{code_hash:?}"));
Expand All @@ -275,7 +288,7 @@ pub async fn display_result(
}

pub fn print_default_instantiate_preview(
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment>,
instantiate_exec: &InstantiateExec<DefaultConfig, DefaultEnvironment, Keypair>,
gas_limit: Weight,
) {
name_value_println!(
Expand Down
11 changes: 11 additions & 0 deletions crates/cargo-contract/src/cmd/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,10 @@ pub use subxt::{
Config,
PolkadotConfig as DefaultConfig,
};
use subxt_signer::{
sr25519::Keypair,
SecretUri,
};

/// Arguments required for creating and sending an extrinsic to a substrate node.
#[derive(Clone, Debug, clap::Args)]
Expand Down Expand Up @@ -271,6 +275,13 @@ pub fn display_all_contracts(contracts: &[<DefaultConfig as Config>::AccountId])
.for_each(|e: &<DefaultConfig as Config>::AccountId| println!("{}", e))
}

/// Create a Signer from a secret URI.
pub fn create_signer(suri: &str) -> Result<Keypair> {
let uri = <SecretUri as std::str::FromStr>::from_str(suri)?;
let keypair = Keypair::from_uri(&uri)?;
Ok(keypair)
}

/// Parse a hex encoded 32 byte hash. Returns error if not exactly 32 bytes.
pub fn parse_code_hash(input: &str) -> Result<<DefaultConfig as Config>::Hash> {
let bytes = contract_build::util::decode_hex(input)?;
Expand Down
33 changes: 25 additions & 8 deletions crates/cargo-contract/src/cmd/remove.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,21 +18,25 @@ use crate::ErrorVariant;
use std::fmt::Debug;

use super::{
create_signer,
parse_code_hash,
CLIExtrinsicOpts,
};
use anyhow::Result;
use contract_build::name_value_println;
use contract_extrinsics::{
DisplayEvents,
ExtrinsicOptsBuilder,
RemoveCommandBuilder,
RemoveExec,
TokenMetadata,
};
use ink_env::DefaultEnvironment;
use subxt::{
Config,
PolkadotConfig as DefaultConfig,
};
use subxt_signer::sr25519::Keypair;

#[derive(Debug, clap::Args)]
#[clap(name = "remove", about = "Remove a contract's code")]
Expand All @@ -54,27 +58,40 @@ impl RemoveCommand {
}

pub async fn handle(&self) -> Result<(), ErrorVariant> {
let extrinsic_opts = ExtrinsicOptsBuilder::default()
let token_metadata =
TokenMetadata::query::<DefaultConfig>(&self.extrinsic_cli_opts.url).await?;

let signer: Keypair = create_signer(&self.extrinsic_cli_opts.suri)?;
let extrinsic_opts = ExtrinsicOptsBuilder::new(signer)
.file(self.extrinsic_cli_opts.file.clone())
.manifest_path(self.extrinsic_cli_opts.manifest_path.clone())
.url(self.extrinsic_cli_opts.url.clone())
.suri(self.extrinsic_cli_opts.suri.clone())
.storage_deposit_limit(self.extrinsic_cli_opts.storage_deposit_limit.clone())
.storage_deposit_limit(
self.extrinsic_cli_opts
.storage_deposit_limit
.clone()
.map(|bv| bv.denominate_balance(&token_metadata))
.transpose()?,
)
.done();
let remove_exec: RemoveExec<DefaultConfig, DefaultEnvironment> =
RemoveCommandBuilder::default()
let remove_exec: RemoveExec<DefaultConfig, DefaultEnvironment, Keypair> =
RemoveCommandBuilder::new(extrinsic_opts)
.code_hash(self.code_hash)
.extrinsic_opts(extrinsic_opts)
.done()
.await?;
let remove_result = remove_exec.remove_code().await?;
let display_events = remove_result.display_events;
let display_events =
DisplayEvents::from_events::<DefaultConfig, DefaultEnvironment>(
&remove_result.events,
Some(remove_exec.transcoder()),
&remove_exec.client().metadata(),
)?;
let output_events = if self.output_json() {
display_events.to_json()?
} else {
display_events.display_events::<DefaultEnvironment>(
self.extrinsic_cli_opts.verbosity().unwrap(),
remove_exec.token_metadata(),
&token_metadata,
)?
};
if let Some(code_removed) = remove_result.code_removed {
Expand Down
Loading

0 comments on commit ea5ccca

Please sign in to comment.