From 87897f4d97a25bbdba03ae7adc75210a0a6b8995 Mon Sep 17 00:00:00 2001 From: Michael Eberhardt <64731211+neutrinoks@users.noreply.github.com> Date: Fri, 11 Oct 2024 16:31:24 +0400 Subject: [PATCH] feat: add submission result type flag --- .../storagext-cli/src/cmd/market.rs | 54 ++++--- .../storagext-cli/src/cmd/storage_provider.rs | 71 +++++---- cli/polka-storage/storagext-cli/src/main.rs | 13 +- .../storagext/src/clients/market.rs | 27 +++- .../storagext/src/clients/storage_provider.rs | 33 ++++- .../storagext/src/runtime/client.rs | 140 ++++++++++++++++-- .../storagext/src/runtime/mod.rs | 2 +- 7 files changed, 269 insertions(+), 71 deletions(-) diff --git a/cli/polka-storage/storagext-cli/src/cmd/market.rs b/cli/polka-storage/storagext-cli/src/cmd/market.rs index d5e74edeb..4c9676ff9 100644 --- a/cli/polka-storage/storagext-cli/src/cmd/market.rs +++ b/cli/polka-storage/storagext-cli/src/cmd/market.rs @@ -6,7 +6,7 @@ use primitives_proofs::DealId; use storagext::{ deser::DeserializablePath, multipair::{DebugPair, MultiPairSigner}, - runtime::SubmissionResult, + runtime::{ResultType, SubmissionResult}, types::market::DealProposal as SxtDealProposal, MarketClientExt, PolkaStorageConfig, }; @@ -81,6 +81,7 @@ impl MarketCommand { account_keypair: Option, n_retries: u32, retry_interval: Duration, + result_type: ResultType, output_format: OutputFormat, ) -> Result<(), anyhow::Error> { let client = storagext::Client::new(node_rpc, n_retries, retry_interval).await?; @@ -110,7 +111,7 @@ impl MarketCommand { return Err(missing_keypair_error::().into()); }; else_ - .with_keypair(client, account_keypair, output_format) + .with_keypair(client, account_keypair, result_type, output_format) .await?; } }; @@ -122,6 +123,7 @@ impl MarketCommand { self, client: Client, account_keypair: MultiPairSigner, + result_type: ResultType, output_format: OutputFormat, ) -> Result<(), anyhow::Error> where @@ -131,17 +133,17 @@ impl MarketCommand { let submission_result = match self { MarketCommand::AddBalance { amount } => { - Self::add_balance(client, account_keypair, amount).await? + Self::add_balance(client, account_keypair, amount, result_type).await? } MarketCommand::SettleDealPayments { deal_ids } => { if deal_ids.is_empty() { bail!("No deals provided to settle"); } - Self::settle_deal_payments(client, account_keypair, deal_ids).await? + Self::settle_deal_payments(client, account_keypair, deal_ids, result_type).await? } MarketCommand::WithdrawBalance { amount } => { - Self::withdraw_balance(client, account_keypair, amount).await? + Self::withdraw_balance(client, account_keypair, amount, result_type).await? } MarketCommand::PublishStorageDeals { deals, @@ -156,17 +158,23 @@ impl MarketCommand { client_ed25519_key.map(DebugPair::into_inner) ) .expect("client is required to submit at least one key, this should've been handled by clap's ArgGroup"); - Self::publish_storage_deals(client, account_keypair, client_keypair, deals).await? + Self::publish_storage_deals( + client, + account_keypair, + client_keypair, + deals, + result_type, + ) + .await? } _unsigned => unreachable!("unsigned commands should have been previously handled"), }; - let hash = submission_result.hash; + let (hash, events) = submission_result.unwrap_both(); // This monstrosity first converts incoming events into a "generic" (subxt generated) event, // and then we extract only the Market events. We could probably extract this into a proper // iterator but the effort to improvement ratio seems low (for 2 pallets at least). - let submission_results = submission_result - .events + let events = events .iter() .flat_map(|event| { event.map(|details| details.as_root_event::()) @@ -176,7 +184,7 @@ impl MarketCommand { Err(err) => Some(Err(err)), _ => None, }); - for event in submission_results { + for event in events { let event = event?; let output = output_format.format(&event)?; match output_format { @@ -191,14 +199,17 @@ impl MarketCommand { client: Client, account_keypair: MultiPairSigner, amount: u128, + result_type: ResultType, ) -> Result, subxt::Error> where Client: MarketClientExt, { - let submission_result = client.add_balance(&account_keypair, amount).await?; + let submission_result = client + .add_balance(&account_keypair, amount, result_type) + .await?; tracing::debug!( "[{}] Successfully added {} to Market Balance", - submission_result.hash, + submission_result, amount ); @@ -210,6 +221,7 @@ impl MarketCommand { account_keypair: MultiPairSigner, client_keypair: MultiPairSigner, deals: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: MarketClientExt, @@ -219,11 +231,12 @@ impl MarketCommand { &account_keypair, &client_keypair, deals.into_iter().map(Into::into).collect(), + result_type, ) .await?; tracing::debug!( "[{}] Successfully published storage deals", - submission_result.hash + submission_result ); Ok(submission_result) @@ -233,17 +246,15 @@ impl MarketCommand { client: Client, account_keypair: MultiPairSigner, deal_ids: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: MarketClientExt, { let submission_result = client - .settle_deal_payments(&account_keypair, deal_ids) + .settle_deal_payments(&account_keypair, deal_ids, result_type) .await?; - tracing::debug!( - "[{}] Successfully settled deal payments", - submission_result.hash - ); + tracing::debug!("[{}] Successfully settled deal payments", submission_result,); Ok(submission_result) } @@ -252,14 +263,17 @@ impl MarketCommand { client: Client, account_keypair: MultiPairSigner, amount: u128, + result_type: ResultType, ) -> Result, subxt::Error> where Client: MarketClientExt, { - let submission_result = client.withdraw_balance(&account_keypair, amount).await?; + let submission_result = client + .withdraw_balance(&account_keypair, amount, result_type) + .await?; tracing::debug!( "[{}] Successfully withdrew {} from Market Balance", - submission_result.hash, + submission_result, amount ); diff --git a/cli/polka-storage/storagext-cli/src/cmd/storage_provider.rs b/cli/polka-storage/storagext-cli/src/cmd/storage_provider.rs index 934589e51..4f60da85c 100644 --- a/cli/polka-storage/storagext-cli/src/cmd/storage_provider.rs +++ b/cli/polka-storage/storagext-cli/src/cmd/storage_provider.rs @@ -7,7 +7,7 @@ use storagext::{ multipair::MultiPairSigner, runtime::{ runtime_types::pallet_storage_provider::sector::ProveCommitSector as RuntimeProveCommitSector, - SubmissionResult, + ResultType, SubmissionResult, }, types::storage_provider::{ FaultDeclaration as SxtFaultDeclaration, ProveCommitSector as SxtProveCommitSector, @@ -95,6 +95,7 @@ impl StorageProviderCommand { account_keypair: Option, n_retries: u32, retry_interval: Duration, + result_type: ResultType, output_format: OutputFormat, ) -> Result<(), anyhow::Error> { let client = storagext::Client::new(node_rpc, n_retries, retry_interval).await?; @@ -123,7 +124,7 @@ impl StorageProviderCommand { return Err(missing_keypair_error::().into()); }; else_ - .with_keypair(client, account_keypair, output_format) + .with_keypair(client, account_keypair, result_type, output_format) .await?; } }; @@ -135,6 +136,7 @@ impl StorageProviderCommand { self, client: Client, account_keypair: MultiPairSigner, + result_type: ResultType, output_format: OutputFormat, ) -> Result<(), anyhow::Error> where @@ -147,32 +149,43 @@ impl StorageProviderCommand { peer_id, post_proof, } => { - Self::register_storage_provider(client, account_keypair, peer_id, post_proof) - .await? + Self::register_storage_provider( + client, + account_keypair, + peer_id, + post_proof, + result_type, + ) + .await? } StorageProviderCommand::PreCommit { pre_commit_sectors } => { - Self::pre_commit(client, account_keypair, pre_commit_sectors).await? + Self::pre_commit(client, account_keypair, pre_commit_sectors, result_type).await? } StorageProviderCommand::ProveCommit { prove_commit_sectors, - } => Self::prove_commit(client, account_keypair, prove_commit_sectors).await?, + } => { + Self::prove_commit(client, account_keypair, prove_commit_sectors, result_type) + .await? + } StorageProviderCommand::SubmitWindowedProofOfSpaceTime { windowed_post } => { - Self::submit_windowed_post(client, account_keypair, windowed_post).await? + Self::submit_windowed_post(client, account_keypair, windowed_post, result_type) + .await? } StorageProviderCommand::DeclareFaults { faults } => { - Self::declare_faults(client, account_keypair, faults).await? + Self::declare_faults(client, account_keypair, faults, result_type).await? } StorageProviderCommand::DeclareFaultsRecovered { recoveries } => { - Self::declare_faults_recovered(client, account_keypair, recoveries).await? + Self::declare_faults_recovered(client, account_keypair, recoveries, result_type) + .await? } _unsigned => unreachable!("unsigned commands should have been previously handled"), }; + let (hash, events) = submission_result.unwrap_both(); // This monstrosity first converts incoming events into a "generic" (subxt generated) event, // and then we extract only the Market events. We could probably extract this into a proper // iterator but the effort to improvement ratio seems low (for 2 pallets at least). - let submission_results = submission_result - .events + let events = events .iter() .flat_map(|event| { event.map(|details| details.as_root_event::()) @@ -182,11 +195,11 @@ impl StorageProviderCommand { Err(err) => Some(Err(err)), _ => None, }); - for event in submission_results { + for event in events { let event = event?; let output = output_format.format(&event)?; match output_format { - OutputFormat::Plain => println!("[{}] {}", submission_result.hash, output), + OutputFormat::Plain => println!("[{}] {}", hash, output), OutputFormat::Json => println!("{}", output), } } @@ -198,16 +211,17 @@ impl StorageProviderCommand { account_keypair: MultiPairSigner, peer_id: String, post_proof: RegisteredPoStProof, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, { let submission_result = client - .register_storage_provider(&account_keypair, peer_id.clone(), post_proof) + .register_storage_provider(&account_keypair, peer_id.clone(), post_proof, result_type) .await?; tracing::debug!( "[{}] Successfully registered {}, seal: {:?} in Storage Provider Pallet", - submission_result.hash, + submission_result, peer_id, post_proof ); @@ -219,6 +233,7 @@ impl StorageProviderCommand { client: Client, account_keypair: MultiPairSigner, pre_commit_sectors: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, @@ -230,11 +245,11 @@ impl StorageProviderCommand { .unzip(); let submission_result = client - .pre_commit_sectors(&account_keypair, pre_commit_sectors) + .pre_commit_sectors(&account_keypair, pre_commit_sectors, result_type) .await?; tracing::debug!( "[{}] Successfully pre-commited sectors {:?}.", - submission_result.hash, + submission_result, sector_numbers ); @@ -245,6 +260,7 @@ impl StorageProviderCommand { client: Client, account_keypair: MultiPairSigner, prove_commit_sectors: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, @@ -260,11 +276,11 @@ impl StorageProviderCommand { }) .unzip(); let submission_result = client - .prove_commit_sectors(&account_keypair, prove_commit_sectors) + .prove_commit_sectors(&account_keypair, prove_commit_sectors, result_type) .await?; tracing::debug!( "[{}] Successfully proven sector {:?}.", - submission_result.hash, + submission_result, sector_numbers ); @@ -275,14 +291,15 @@ impl StorageProviderCommand { client: Client, account_keypair: MultiPairSigner, windowed_post: SxtSubmitWindowedPoStParams, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, { let submission_result = client - .submit_windowed_post(&account_keypair, windowed_post.into()) + .submit_windowed_post(&account_keypair, windowed_post.into(), result_type) .await?; - tracing::debug!("[{}] Successfully submitted proof.", submission_result.hash); + tracing::debug!("[{}] Successfully submitted proof.", submission_result); Ok(submission_result) } @@ -291,12 +308,15 @@ impl StorageProviderCommand { client: Client, account_keypair: MultiPairSigner, faults: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, { - let submission_result = client.declare_faults(&account_keypair, faults).await?; - tracing::debug!("[{}] Successfully declared faults.", submission_result.hash); + let submission_result = client + .declare_faults(&account_keypair, faults, result_type) + .await?; + tracing::debug!("[{}] Successfully declared faults.", submission_result); Ok(submission_result) } @@ -305,14 +325,15 @@ impl StorageProviderCommand { client: Client, account_keypair: MultiPairSigner, recoveries: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Client: StorageProviderClientExt, { let submission_result = client - .declare_faults_recovered(&account_keypair, recoveries) + .declare_faults_recovered(&account_keypair, recoveries, result_type) .await?; - tracing::debug!("[{}] Successfully declared faults.", submission_result.hash); + tracing::debug!("[{}] Successfully declared faults.", submission_result); Ok(submission_result) } diff --git a/cli/polka-storage/storagext-cli/src/main.rs b/cli/polka-storage/storagext-cli/src/main.rs index b512d357a..0dc7fbca6 100644 --- a/cli/polka-storage/storagext-cli/src/main.rs +++ b/cli/polka-storage/storagext-cli/src/main.rs @@ -6,7 +6,10 @@ use std::{fmt::Debug, time::Duration}; use clap::{ArgGroup, Parser, Subcommand}; use cmd::{market::MarketCommand, storage_provider::StorageProviderCommand, system::SystemCommand}; -use storagext::multipair::{DebugPair, MultiPairSigner}; +use storagext::{ + multipair::{DebugPair, MultiPairSigner}, + runtime::ResultType, +}; use subxt::ext::sp_core::{ ecdsa::Pair as ECDSAPair, ed25519::Pair as Ed25519Pair, sr25519::Pair as Sr25519Pair, }; @@ -77,6 +80,10 @@ struct Cli { #[arg(long, env, default_value = DEFAULT_RETRY_INTERVAL_MS, value_parser = parse_ms)] pub retry_interval: Duration, + /// The expected return type, i.e. none, hash, events, etc.. + #[arg(long, env, default_value_t = ResultType::None, value_parser = ResultType::value_parser)] + pub result_type: ResultType, + /// Output format. #[arg(long, env, value_parser = OutputFormat::value_parser, default_value_t = OutputFormat::Plain)] pub format: OutputFormat, @@ -101,6 +108,7 @@ impl SubCommand { account_keypair: Option, n_retries: u32, retry_interval: Duration, + result_type: ResultType, output_format: OutputFormat, ) -> Result<(), anyhow::Error> { match self { @@ -110,6 +118,7 @@ impl SubCommand { account_keypair, n_retries, retry_interval, + result_type, output_format, ) .await?; @@ -120,6 +129,7 @@ impl SubCommand { account_keypair, n_retries, retry_interval, + result_type, output_format, ) .await?; @@ -179,6 +189,7 @@ async fn main() -> Result<(), anyhow::Error> { multi_pair_signer, cli_arguments.n_retries, cli_arguments.retry_interval, + cli_arguments.result_type, cli_arguments.format, ) .await?; diff --git a/cli/polka-storage/storagext/src/clients/market.rs b/cli/polka-storage/storagext/src/clients/market.rs index ee7b9e6e5..ac117eef6 100644 --- a/cli/polka-storage/storagext/src/clients/market.rs +++ b/cli/polka-storage/storagext/src/clients/market.rs @@ -6,7 +6,7 @@ use subxt::{ext::sp_core::crypto::Ss58Codec, utils::Static}; use crate::{ runtime::{ self, - client::SubmissionResult, + client::{ResultType, SubmissionResult}, runtime_types::pallet_market::pallet::{ BalanceEntry, ClientDealProposal as RuntimeClientDealProposal, }, @@ -34,6 +34,7 @@ pub trait MarketClientExt { &self, account_keypair: &Keypair, amount: Currency, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -43,6 +44,7 @@ pub trait MarketClientExt { &self, account_keypair: &Keypair, amount: Currency, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -54,6 +56,7 @@ pub trait MarketClientExt { &self, account_keypair: &Keypair, deal_ids: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -66,6 +69,7 @@ pub trait MarketClientExt { account_keypair: &Keypair, client_keypair: &ClientKeypair, deals: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer, @@ -78,6 +82,7 @@ pub trait MarketClientExt { &self, account_keypair: &Keypair, deals: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -102,12 +107,14 @@ impl MarketClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, amount: Currency, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, { let payload = runtime::tx().market().withdraw_balance(amount); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -122,12 +129,14 @@ impl MarketClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, amount: Currency, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, { let payload = runtime::tx().market().add_balance(amount); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -142,6 +151,7 @@ impl MarketClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, mut deal_ids: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -160,7 +170,8 @@ impl MarketClientExt for crate::runtime::client::Client { .market() .settle_deal_payments(bounded_unbounded_deal_ids); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -175,6 +186,7 @@ impl MarketClientExt for crate::runtime::client::Client { account_keypair: &Keypair, client_keypair: &ClientKeypair, mut deals: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -202,7 +214,8 @@ impl MarketClientExt for crate::runtime::client::Client { .market() .publish_storage_deals(bounded_unbounded_deals); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -216,6 +229,7 @@ impl MarketClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, mut deals: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -240,7 +254,8 @@ impl MarketClientExt for crate::runtime::client::Client { .market() .publish_storage_deals(bounded_unbounded_deals); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( diff --git a/cli/polka-storage/storagext/src/clients/storage_provider.rs b/cli/polka-storage/storagext/src/clients/storage_provider.rs index 6ed02891e..f6b3aa12e 100644 --- a/cli/polka-storage/storagext/src/clients/storage_provider.rs +++ b/cli/polka-storage/storagext/src/clients/storage_provider.rs @@ -11,7 +11,7 @@ use crate::{ runtime::{ self, bounded_vec::IntoBoundedByteVec, - client::SubmissionResult, + client::{ResultType, SubmissionResult}, runtime_types::pallet_storage_provider::{ proofs::SubmitWindowedPoStParams, sector::ProveCommitSector, }, @@ -19,12 +19,14 @@ use crate::{ types::storage_provider::{FaultDeclaration, RecoveryDeclaration, SectorPreCommitInfo}, PolkaStorageConfig, }; + pub trait StorageProviderClientExt { fn register_storage_provider( &self, account_keypair: &Keypair, peer_id: String, post_proof: RegisteredPoStProof, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -33,6 +35,7 @@ pub trait StorageProviderClientExt { &self, account_keypair: &Keypair, sectors: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -41,6 +44,7 @@ pub trait StorageProviderClientExt { &self, account_keypair: &Keypair, sectors: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -49,6 +53,7 @@ pub trait StorageProviderClientExt { &self, account_keypair: &Keypair, windowed_post: SubmitWindowedPoStParams, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -57,6 +62,7 @@ pub trait StorageProviderClientExt { &self, account_keypair: &Keypair, faults: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -65,6 +71,7 @@ pub trait StorageProviderClientExt { &self, account_keypair: &Keypair, recoveries: Vec, + result_type: ResultType, ) -> impl Future, subxt::Error>> where Keypair: subxt::tx::Signer; @@ -92,6 +99,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { account_keypair: &Keypair, peer_id: String, post_proof: RegisteredPoStProof, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -100,7 +108,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { .storage_provider() .register_storage_provider(peer_id.into_bounded_byte_vec(), post_proof); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -114,6 +123,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, sectors: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -121,7 +131,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { let sectors = BoundedVec(sectors.into_iter().map(Into::into).collect()); let payload = runtime::tx().storage_provider().pre_commit_sectors(sectors); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -135,6 +146,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, sectors: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -144,7 +156,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { .storage_provider() .prove_commit_sectors(sectors); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -158,6 +171,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, windowed_post: SubmitWindowedPoStParams, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -166,7 +180,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { .storage_provider() .submit_windowed_post(windowed_post); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -180,6 +195,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, faults: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -188,7 +204,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { .storage_provider() .declare_faults(faults.into()); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument( @@ -202,6 +219,7 @@ impl StorageProviderClientExt for crate::runtime::client::Client { &self, account_keypair: &Keypair, recoveries: Vec, + result_type: ResultType, ) -> Result, subxt::Error> where Keypair: subxt::tx::Signer, @@ -210,7 +228,8 @@ impl StorageProviderClientExt for crate::runtime::client::Client { .storage_provider() .declare_faults_recovered(recoveries.into()); - self.traced_submission(&payload, account_keypair).await + self.traced_submission(&payload, account_keypair, result_type) + .await } #[tracing::instrument(level = "debug", skip_all)] diff --git a/cli/polka-storage/storagext/src/runtime/client.rs b/cli/polka-storage/storagext/src/runtime/client.rs index 5cf101e78..c06ad8e57 100644 --- a/cli/polka-storage/storagext/src/runtime/client.rs +++ b/cli/polka-storage/storagext/src/runtime/client.rs @@ -6,15 +6,122 @@ use subxt::{blocks::ExtrinsicEvents, OnlineClient}; use crate::PolkaStorageConfig; /// Helper type for [`Client::traced_submission`] successful results. -pub struct SubmissionResult +pub enum SubmissionResult where Config: subxt::Config, { + /// No return value appended. + None, /// Submission block hash. - pub hash: Config::Hash, - + Hash(Config::Hash), /// Resulting extrinsic's events. - pub events: ExtrinsicEvents, + Events(ExtrinsicEvents), + /// Combined. Return of a hash and the events. + Both { + hash: Config::Hash, + events: ExtrinsicEvents, + }, +} + +impl SubmissionResult +where + Config: subxt::Config, +{ + /// Like other `unwrap()` implementations that unwraps the expected `Config::Hash`. + /// Method will panic in case it does not contain the expected return data type. + pub fn unwrap_hash(self) -> Config::Hash { + match self { + SubmissionResult::Hash(hash) => hash, + _ => panic!("expected hash but contained something different"), + } + } + + /// Like other `unwrap()` implementations that unwraps the expected `Config::Hash`. + /// Method will panic in case it does not contain the expected return data type. + pub fn unwrap_events(self) -> ExtrinsicEvents { + match self { + SubmissionResult::Events(events) => events, + _ => panic!("expected events but contained something different"), + } + } + + /// Like other `unwrap()` implementations that unwraps the combined tuple. + /// Method will panic in case it does not contain the expected return data type. + pub fn unwrap_both(self) -> (Config::Hash, ExtrinsicEvents) { + match self { + SubmissionResult::Both { hash, events } => (hash, events), + _ => panic!("expected events but contained something different"), + } + } +} + +// impl core::fmt::Debug for SubmissionResult +// where +// Config: subxt::Config, +// { +// fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { +// match self { +// ResultType::None => write!(f, "ResultTypNone"), +// } +// } +// } + +impl core::fmt::Display for SubmissionResult +where + Config: subxt::Config, +{ + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + match self { + SubmissionResult::None => write!(f, "None"), + SubmissionResult::Hash(hash) => write!(f, "{hash:?}"), + SubmissionResult::Events(events) => write!(f, "{events:?}"), + SubmissionResult::Both { hash, events } => { + write!(f, "Hash: {hash:?}, Events: {events:?}") + } + } + } +} + +/// Selector type for the result type. +#[derive(Clone, Debug, Default)] +pub enum ResultType { + /// No return value is expected. + #[default] + None, + /// The block's hash of the submission shall be returned. + Hash, + /// The extrinsic's event of the submission shall be returned. + Events, + /// Both types will be returned as combined return value. + Both, +} + +impl ResultType { + pub fn value_parser(s: &str) -> Result { + match s.to_lowercase().as_str() { + "none" => Ok(ResultType::None), + "hash" => Ok(ResultType::Hash), + "events" => Ok(ResultType::Events), + "both" => Ok(ResultType::Both), + format => Err(format!("unknown format: {}", format)), + } + } + + // pub fn format(&self, value: &T) -> Result + // where + // T: std::fmt::Display + serde::Serialize, + // { + // match self { + // ResultType::None => Ok(value.to_string()), + // ResultType::Hash => serde_json::to_string(value), + // } + // } +} + +impl core::fmt::Display for ResultType { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self) + } } /// Client to interact with a pallet extrinsics. @@ -70,6 +177,7 @@ impl Client { &self, call: &Call, account_keypair: &Keypair, + result_type: ResultType, ) -> Result, subxt::Error> where Call: subxt::tx::Payload, @@ -93,13 +201,23 @@ impl Client { "successfully submitted extrinsic" ); - // finalized != successful - let xt_events = finalized_xt.wait_for_success().await?; - - Ok(SubmissionResult { - hash: block_hash, - events: xt_events, - }) + match result_type { + ResultType::None => Ok(SubmissionResult::None), + ResultType::Hash => Ok(SubmissionResult::Hash(block_hash)), + ResultType::Events => { + // finalized != successful + let events = finalized_xt.wait_for_success().await?; + Ok(SubmissionResult::Events(events)) + } + ResultType::Both => { + // finalized != successful + let events = finalized_xt.wait_for_success().await?; + Ok(SubmissionResult::Both { + hash: block_hash, + events, + }) + } + } } } diff --git a/cli/polka-storage/storagext/src/runtime/mod.rs b/cli/polka-storage/storagext/src/runtime/mod.rs index c3423f8ab..a61f437d7 100644 --- a/cli/polka-storage/storagext/src/runtime/mod.rs +++ b/cli/polka-storage/storagext/src/runtime/mod.rs @@ -99,7 +99,7 @@ pub mod display; mod polka_storage_runtime {} // Using self keeps the import separate from the others -pub use client::SubmissionResult; +pub use client::{ResultType, SubmissionResult}; pub use self::polka_storage_runtime::*; #[cfg(test)]