Skip to content

Commit

Permalink
refactor: generic sign and submit
Browse files Browse the repository at this point in the history
  • Loading branch information
Daanvdplas committed Dec 11, 2024
1 parent b787e08 commit 24c0c4d
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 36 deletions.
7 changes: 4 additions & 3 deletions crates/pop-cli/src/commands/call/chain.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ use clap::Args;
use pop_parachains::{
construct_extrinsic, construct_sudo_extrinsic, decode_call_data, encode_call_data,
find_dispatchable_by_name, find_pallet_by_name, parse_chain_metadata, set_up_client,
sign_and_submit_extrinsic, sign_and_submit_extrinsic_with_call_data, supported_actions, Action,
sign_and_submit_extrinsic, supported_actions, Action, CallData,
DynamicPayload, Function, OnlineClient, Pallet, Param, SubstrateConfig,
};
use url::Url;
Expand Down Expand Up @@ -62,7 +62,7 @@ impl CallChainCommand {
// Execute the call if call_data is provided.
if let Some(call_data) = self.call_data.as_ref() {
if let Err(e) = self
.submit_extrinsic_from_call_data(&chain.client, call_data, &mut cli::Cli)
.submit_extrinsic_from_call_data(&chain.client, &chain.url, call_data, &mut cli::Cli)
.await
{
display_message(&e.to_string(), false, &mut cli::Cli)?;
Expand Down Expand Up @@ -213,6 +213,7 @@ impl CallChainCommand {
async fn submit_extrinsic_from_call_data(
&self,
client: &OnlineClient<SubstrateConfig>,
url: &Url,
call_data: &str,
cli: &mut impl Cli,
) -> Result<()> {
Expand All @@ -238,7 +239,7 @@ impl CallChainCommand {
spinner.start("Signing and submitting the extrinsic and then waiting for finalization, please be patient...");
let call_data_bytes =
decode_call_data(call_data).map_err(|err| anyhow!("{}", format!("{err:?}")))?;
let result = sign_and_submit_extrinsic_with_call_data(client, call_data_bytes, suri)
let result = sign_and_submit_extrinsic(client, &url, CallData::new(call_data_bytes), suri)
.await
.map_err(|err| anyhow!("{}", format!("{err:?}")))?;

Expand Down
71 changes: 39 additions & 32 deletions crates/pop-parachains/src/call/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ use subxt::{
tx::{DynamicPayload, Payload},
OnlineClient, SubstrateConfig,
};
use pop_common::call::TokenMetadata;
use pop_common::call::{DisplayEvents, TokenMetadata, DefaultEnvironment, Verbosity};

pub mod metadata;

Expand Down Expand Up @@ -47,12 +47,13 @@ pub fn construct_sudo_extrinsic(xt: DynamicPayload) -> Result<DynamicPayload, Er
///
/// # Arguments
/// * `client` - The client used to interact with the chain.
/// * `url` - Endpoint of the node.
/// * `xt` - The extrinsic to be signed and submitted.
/// * `suri` - The secret URI (e.g., mnemonic or private key) for signing the extrinsic.
pub async fn sign_and_submit_extrinsic(
pub async fn sign_and_submit_extrinsic<C: Payload>(
client: &OnlineClient<SubstrateConfig>,
url: &url::Url,
xt: DynamicPayload,
xt: C,
suri: &str,
) -> Result<String, Error> {
let signer = create_signer(suri)?;
Expand All @@ -65,12 +66,13 @@ pub async fn sign_and_submit_extrinsic(
.await
.map_err(|e| Error::ExtrinsicSubmissionError(format!("{:?}", e)))?;

// Obtain required metadata and parse events.
let metadata = client.metadata();
let display_events =
pop_common::call::DisplayEvents::from_events::<SubstrateConfig, pop_common::call::DefaultEnvironment>(&result, None, &metadata)?;
let token_metadata = TokenMetadata::query::<SubstrateConfig>(url).await?;
let events =
display_events.display_events::<pop_common::call::DefaultEnvironment>(pop_common::call::Verbosity::Default, &token_metadata)?;
DisplayEvents::from_events::<SubstrateConfig, DefaultEnvironment>(&result, None, &metadata)?;
let events =
events.display_events::<DefaultEnvironment>(Verbosity::Default, &token_metadata)?;

Ok(format!(
"Extrinsic Submitted with hash: {:?}\n\n{}",
Expand Down Expand Up @@ -103,9 +105,15 @@ pub fn decode_call_data(call_data: &str) -> Result<Vec<u8>, Error> {
.map_err(|e| Error::CallDataDecodingError(e.to_string()))
}

// This struct implements the [`Payload`] trait and is used to submit
// pre-encoded SCALE call data directly, without the dynamic construction of transactions.
struct CallData(Vec<u8>);
/// This struct implements the [`Payload`] trait and is used to submit
/// pre-encoded SCALE call data directly, without the dynamic construction of transactions.
pub struct CallData(Vec<u8>);

impl CallData {
pub fn new(data: Vec<u8>) -> CallData {
CallData(data)
}
}

impl Payload for CallData {
fn encode_call_data_to(
Expand All @@ -118,29 +126,28 @@ impl Payload for CallData {
}
}

/// Signs and submits a given extrinsic.
///
/// # Arguments
/// * `client` - Reference to an `OnlineClient` connected to the chain.
/// * `call_data` - SCALE encoded bytes representing the extrinsic's call data.
/// * `suri` - The secret URI (e.g., mnemonic or private key) for signing the extrinsic.
pub async fn sign_and_submit_extrinsic_with_call_data(
client: &OnlineClient<SubstrateConfig>,
call_data: Vec<u8>,
suri: &str,
) -> Result<String, Error> {
let signer = create_signer(suri)?;
let payload = CallData(call_data);
let result = client
.tx()
.sign_and_submit_then_watch_default(&payload, &signer)
.await
.map_err(|e| Error::ExtrinsicSubmissionError(format!("{:?}", e)))?
.wait_for_finalized_success()
.await
.map_err(|e| Error::ExtrinsicSubmissionError(format!("{:?}", e)))?;
Ok(format!("{:?}", result.extrinsic_hash()))
}
// /// Signs and submits a given extrinsic.
// ///
// /// # Arguments
// /// * `client` - Reference to an `OnlineClient` connected to the chain.
// /// * `call_data` - SCALE encoded bytes representing the extrinsic's call data.
// /// * `suri` - The secret URI (e.g., mnemonic or private key) for signing the extrinsic.
// pub async fn sign_and_submit_extrinsic_with_call_data(
// client: &OnlineClient<SubstrateConfig>,
// call_data: Vec<u8>,
// suri: &str,
// ) -> Result<String, Error> {
// let signer = create_signer(suri)?;
// let result = client
// .tx()
// .sign_and_submit_then_watch_default(&payload, &signer)
// .await
// .map_err(|e| Error::ExtrinsicSubmissionError(format!("{:?}", e)))?
// .wait_for_finalized_success()
// .await
// .map_err(|e| Error::ExtrinsicSubmissionError(format!("{:?}", e)))?;
// Ok(format!("{:?}", result.extrinsic_hash()))
// }

#[cfg(test)]
mod tests {
Expand Down
2 changes: 1 addition & 1 deletion crates/pop-parachains/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ pub use call::{
params::Param,
parse_chain_metadata, Function, Pallet,
},
set_up_client, sign_and_submit_extrinsic, sign_and_submit_extrinsic_with_call_data,
set_up_client, sign_and_submit_extrinsic, CallData,
};
pub use errors::Error;
pub use indexmap::IndexSet;
Expand Down

0 comments on commit 24c0c4d

Please sign in to comment.