From 2f41600833f1b0fa331c6f197e7d534c3c1ea3f8 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 19 Dec 2021 01:19:29 -0800 Subject: [PATCH 01/15] Create benchmarks for BurnAsset and ExpectAsset --- .../src/generic/benchmarking.rs | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index aee21000afde..ca7a621e3fc0 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -313,6 +313,36 @@ benchmarks! { // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } + burn_asset { + let holding = T::worst_case_holding(0); + let assets = holding.clone(); + + let mut executor = new_executor::(Default::default()); + executor.holding = holding.into(); + + let instruction = Instruction::BurnAsset(assets.into()); + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + assert!(executor.holding.is_empty()); + } + + expect_asset { + let holding = T::worst_case_holding(0); + let assets = holding.clone(); + + let mut executor = new_executor::(Default::default()); + executor.holding = holding.into(); + + let instruction = Instruction::ExpectAsset(assets.into()); + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + // `execute` completing successfully is as good as we can check. + } + impl_benchmark_test_suite!( Pallet, crate::generic::mock::new_test_ext(), From 7b56ff5982936fbe0baf43b358ed4b20ccf28255 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 19 Dec 2021 02:03:45 -0800 Subject: [PATCH 02/15] Add benchmarks for ExpectOrigin and ExpectError --- .../src/generic/benchmarking.rs | 45 ++++++++++++++++--- 1 file changed, 38 insertions(+), 7 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index ca7a621e3fc0..7a7cccba24f0 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -24,6 +24,7 @@ use xcm::{ latest::{prelude::*, MultiAssets}, DoubleEncoded, }; +use xcm_executor::ExecutorError; benchmarks! { report_holding { @@ -254,12 +255,10 @@ benchmarks! { } : { _result = executor.execute(xcm); } verify { - match _result { - Err(error) if error.xcm_error == XcmError::Trap(10) => { - // This is the success condition - }, - _ => Err("xcm trap did not return the expected error")? - }; + assert!(matches!(_result, Err(ExecutorError { + xcm_error: XcmError::Trap(10), + .. + }))); } subscribe_version { @@ -306,7 +305,7 @@ benchmarks! { executor.holding = holding.into(); let instruction = Instruction::InitiateReserveWithdraw { assets: assets_filter, reserve, xcm: Xcm(vec![]) }; let xcm = Xcm(vec![instruction]); - }:{ + }: { executor.execute(xcm)?; } verify { // The execute completing successfully is as good as we can check. @@ -343,6 +342,38 @@ benchmarks! { // `execute` completing successfully is as good as we can check. } + expect_origin { + let expected_origin = Parent.into(); + let mut executor = new_executor::(Default::default()); + + let instruction = Instruction::ExpectOrigin(Some(expected_origin)); + let xcm = Xcm(vec![instruction]); + let mut _result = Ok(()); + }: { + _result = executor.execute(xcm); + } verify { + assert!(matches!(_result, Err(ExecutorError { + xcm_error: XcmError::ExpectationFalse, + .. + }))); + } + + expect_error { + let mut executor = new_executor::(Default::default()); + executor.error = Some((3u32, XcmError::Overflow)); + + let instruction = Instruction::ExpectError(None); + let xcm = Xcm(vec![instruction]); + let mut _result = Ok(()); + }: { + _result = executor.execute(xcm); + } verify { + assert!(matches!(_result, Err(ExecutorError { + xcm_error: XcmError::ExpectationFalse, + .. + }))); + } + impl_benchmark_test_suite!( Pallet, crate::generic::mock::new_test_ext(), From ab1c0c7336d63534c34589be0eb769af25909116 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 19 Dec 2021 02:48:31 -0800 Subject: [PATCH 03/15] Add benchmarks for QueryPallet and ExpectPallet --- .../src/generic/benchmarking.rs | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 7a7cccba24f0..f701ca92e427 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -374,6 +374,40 @@ benchmarks! { }))); } + query_pallet { + let query_id = Default::default(); + let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; + let max_weight = Default::default(); + let mut executor = new_executor::(Default::default()); + + let instruction = Instruction::QueryPallet { + module_name: b"frame_system".to_vec(), + response_info: QueryResponseInfo { destination, query_id, max_weight }, + }; + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + } + + expect_pallet { + let mut executor = new_executor::(Default::default()); + + let instruction = Instruction::ExpectPallet { + index: 0, + name: b"System".to_vec(), + module_name: b"frame_system".to_vec(), + crate_major: 4, + min_crate_minor: 0, + }; + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + // the execution succeeding is all we need to verify this xcm was successful + } + impl_benchmark_test_suite!( Pallet, crate::generic::mock::new_test_ext(), From a09968018c969971e7d5821153b3d42d0ce5b1a0 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 19 Dec 2021 02:57:21 -0800 Subject: [PATCH 04/15] Add benchmarks for ReportTransactStatus and ClearTransactStatus --- .../src/generic/benchmarking.rs | 37 +++++++++++++++++-- 1 file changed, 33 insertions(+), 4 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index f701ca92e427..1d3f48530bcd 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -20,10 +20,7 @@ use codec::Encode; use frame_benchmarking::{benchmarks, BenchmarkError}; use frame_support::dispatch::GetDispatchInfo; use sp_std::vec; -use xcm::{ - latest::{prelude::*, MultiAssets}, - DoubleEncoded, -}; +use xcm::{DoubleEncoded, latest::{MaybeErrorCode, MultiAssets, prelude::*}, v2::Instruction::QueryResponse}; use xcm_executor::ExecutorError; benchmarks! { @@ -408,6 +405,38 @@ benchmarks! { // the execution succeeding is all we need to verify this xcm was successful } + report_transact_status { + let query_id = Default::default(); + let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; + let max_weight = Default::default(); + + let mut executor = new_executor::(Default::default()); + executor.transact_status = MaybeErrorCode::Error(b"MyError".to_vec()); + + let instruction = Instruction::ReportTransactStatus(QueryResponseInfo { + query_id, + destination, + max_weight, + }); + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 + } + + clear_transact_status { + let mut executor = new_executor::(Default::default()); + executor.transact_status = MaybeErrorCode::Error(b"MyError".to_vec()); + + let instruction = Instruction::ClearTransactStatus; + let xcm = Xcm(vec![instruction]); + }: { + executor.execute(xcm)?; + } verify { + assert_eq!(executor.transact_status, MaybeErrorCode::Success); + } + impl_benchmark_test_suite!( Pallet, crate::generic::mock::new_test_ext(), From 74ea1a824f4f713ce2f974ca9bad5e69c82db174 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Sun, 19 Dec 2021 02:58:34 -0800 Subject: [PATCH 05/15] cargo fmt --- xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 1d3f48530bcd..eb568e18a12e 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -20,7 +20,10 @@ use codec::Encode; use frame_benchmarking::{benchmarks, BenchmarkError}; use frame_support::dispatch::GetDispatchInfo; use sp_std::vec; -use xcm::{DoubleEncoded, latest::{MaybeErrorCode, MultiAssets, prelude::*}, v2::Instruction::QueryResponse}; +use xcm::{ + latest::{prelude::*, MaybeErrorCode, MultiAssets}, + DoubleEncoded, +}; use xcm_executor::ExecutorError; benchmarks! { From 5d1bab7db7eb6d1a93f0ee66a5e09f853468a335 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 20 Dec 2021 02:34:19 -0800 Subject: [PATCH 06/15] Use AllPalletsWithSystem in mocks --- xcm/pallet-xcm-benchmarks/src/fungible/mock.rs | 2 +- xcm/pallet-xcm-benchmarks/src/generic/mock.rs | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs b/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs index 6647ff967999..6418e82f148c 100644 --- a/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/fungible/mock.rs @@ -143,7 +143,7 @@ impl xcm_executor::Config for XcmConfig { type AssetTrap = (); type AssetClaims = (); type SubscriptionService = (); - type PalletInstancesInfo = (); + type PalletInstancesInfo = AllPalletsWithSystem; type MaxAssetsIntoHolding = MaxAssetsIntoHolding; } diff --git a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 7f93c4c93a20..c78a69956a7f 100644 --- a/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -113,7 +113,7 @@ impl xcm_executor::Config for XcmConfig { type AssetTrap = TestAssetTrap; type AssetClaims = TestAssetTrap; type SubscriptionService = TestSubscriptionService; - type PalletInstancesInfo = (); + type PalletInstancesInfo = AllPalletsWithSystem; type MaxAssetsIntoHolding = MaxAssetsIntoHolding; } From 3c729b43386b24e41082d7e5ddbd3bb6f46922b6 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 20 Dec 2021 03:07:16 -0800 Subject: [PATCH 07/15] Update XCM generic benchmarks for westend --- .../xcm/pallet_xcm_benchmarks_generic.rs | 83 ++++++++++++++----- 1 file changed, 64 insertions(+), 19 deletions(-) diff --git a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs index e801911063c5..bd881fd41a81 100644 --- a/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs +++ b/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_generic.rs @@ -1,4 +1,4 @@ -// Copyright 2017-2021 Parity Technologies (UK) Ltd. +// Copyright 2021 Parity Technologies (UK) Ltd. // This file is part of Polkadot. // Polkadot is free software: you can redistribute it and/or modify @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::generic` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2021-12-01, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2021-12-20, STEPS: `50`, REPEAT: 20, LOW RANGE: `[]`, HIGH RANGE: `[]` //! EXECUTION: Some(Wasm), WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 128 // Executed Command: @@ -45,37 +45,44 @@ use sp_std::marker::PhantomData; /// Weights for `pallet_xcm_benchmarks::generic`. pub struct WeightInfo(PhantomData); impl WeightInfo { - pub fn report_holding() -> Weight { - 1_000_000_000 + // Storage: XcmPallet SupportedVersion (r:1 w:0) + // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) + // Storage: XcmPallet SafeXcmVersion (r:1 w:0) + // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) + // Storage: Dmp DownwardMessageQueues (r:1 w:1) + pub(crate) fn report_holding() -> Weight { + (35_446_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) } pub(crate) fn buy_execution() -> Weight { - (5_922_000 as Weight) + (5_228_000 as Weight) } // Storage: XcmPallet Queries (r:1 w:0) pub(crate) fn query_response() -> Weight { - (20_625_000 as Weight) + (18_708_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) } pub(crate) fn transact() -> Weight { - (22_198_000 as Weight) + (20_401_000 as Weight) } pub(crate) fn refund_surplus() -> Weight { - (6_122_000 as Weight) + (5_238_000 as Weight) } pub(crate) fn set_error_handler() -> Weight { - (5_758_000 as Weight) + (5_104_000 as Weight) } pub(crate) fn set_appendix() -> Weight { - (5_764_000 as Weight) + (5_095_000 as Weight) } pub(crate) fn clear_error() -> Weight { - (5_679_000 as Weight) + (5_010_000 as Weight) } pub(crate) fn descend_origin() -> Weight { - (7_206_000 as Weight) + (6_368_000 as Weight) } pub(crate) fn clear_origin() -> Weight { - (5_738_000 as Weight) + (5_011_000 as Weight) } // Storage: XcmPallet SupportedVersion (r:1 w:0) // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) @@ -83,18 +90,18 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn report_error() -> Weight { - (31_512_000 as Weight) + (27_823_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } // Storage: XcmPallet AssetTraps (r:1 w:1) pub(crate) fn claim_asset() -> Weight { - (13_594_000 as Weight) + (12_402_000 as Weight) .saturating_add(T::DbWeight::get().reads(1 as Weight)) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } pub(crate) fn trap() -> Weight { - (5_745_000 as Weight) + (5_022_000 as Weight) } // Storage: XcmPallet VersionNotifyTargets (r:1 w:1) // Storage: XcmPallet SupportedVersion (r:1 w:0) @@ -103,13 +110,13 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn subscribe_version() -> Weight { - (38_138_000 as Weight) + (32_492_000 as Weight) .saturating_add(T::DbWeight::get().reads(6 as Weight)) .saturating_add(T::DbWeight::get().writes(4 as Weight)) } // Storage: XcmPallet VersionNotifyTargets (r:0 w:1) pub(crate) fn unsubscribe_version() -> Weight { - (9_127_000 as Weight) + (7_777_000 as Weight) .saturating_add(T::DbWeight::get().writes(1 as Weight)) } // Storage: XcmPallet SupportedVersion (r:1 w:0) @@ -118,8 +125,46 @@ impl WeightInfo { // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) // Storage: Dmp DownwardMessageQueues (r:1 w:1) pub(crate) fn initiate_reserve_withdraw() -> Weight { - (41_443_000 as Weight) + (37_066_000 as Weight) .saturating_add(T::DbWeight::get().reads(5 as Weight)) .saturating_add(T::DbWeight::get().writes(3 as Weight)) } + pub(crate) fn burn_asset() -> Weight { + (7_935_000 as Weight) + } + pub(crate) fn expect_asset() -> Weight { + (5_237_000 as Weight) + } + pub(crate) fn expect_origin() -> Weight { + (5_245_000 as Weight) + } + pub(crate) fn expect_error() -> Weight { + (5_062_000 as Weight) + } + // Storage: XcmPallet SupportedVersion (r:1 w:0) + // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) + // Storage: XcmPallet SafeXcmVersion (r:1 w:0) + // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) + // Storage: Dmp DownwardMessageQueues (r:1 w:1) + pub(crate) fn query_pallet() -> Weight { + (28_876_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + pub(crate) fn expect_pallet() -> Weight { + (5_526_000 as Weight) + } + // Storage: XcmPallet SupportedVersion (r:1 w:0) + // Storage: XcmPallet VersionDiscoveryQueue (r:1 w:1) + // Storage: XcmPallet SafeXcmVersion (r:1 w:0) + // Storage: Dmp DownwardMessageQueueHeads (r:1 w:1) + // Storage: Dmp DownwardMessageQueues (r:1 w:1) + pub(crate) fn report_transact_status() -> Weight { + (27_889_000 as Weight) + .saturating_add(T::DbWeight::get().reads(5 as Weight)) + .saturating_add(T::DbWeight::get().writes(3 as Weight)) + } + pub(crate) fn clear_transact_status() -> Weight { + (5_100_000 as Weight) + } } From ec880ef3c80445cc6c4209bc1920d8ff16298911 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 20 Dec 2021 03:17:33 -0800 Subject: [PATCH 08/15] Remove default impls for some XCM weight functions --- runtime/westend/src/weights/xcm/mod.rs | 24 +++++++++++++++++++ xcm/src/v3/traits.rs | 32 +++++++------------------- 2 files changed, 32 insertions(+), 24 deletions(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index b8cafea6a598..c59c0d2d1fc1 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -182,4 +182,28 @@ impl XcmWeightInfo for WestendXcmWeight { fn unsubscribe_version() -> Weight { XcmGeneric::::unsubscribe_version() } + fn burn_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::burn_asset()) + } + fn expect_asset(assets: &MultiAssets) -> Weight { + assets.weigh_multi_assets(XcmGeneric::::expect_asset()) + } + fn expect_origin(_origin: &Option) -> Weight { + XcmGeneric::::expect_origin() + } + fn expect_error(_error: &Option<(u32, Error)>) -> Weight { + XcmGeneric::::expect_error() + } + fn query_pallet() -> Weight { + XcmGeneric::::query_pallet() + } + fn expect_pallet(_pallet_index: &u32) -> Weight { + XcmGeneric::::expect_pallet() + } + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { + XcmGeneric::::report_transact_status() + } + fn clear_transact_status() -> Weight { + XcmGeneric::::clear_transact_status() + } } diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index cd9bed5fa489..1840d429384c 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -415,28 +415,12 @@ pub trait XcmWeightInfo { fn trap(code: &u64) -> Weight; fn subscribe_version(query_id: &QueryId, max_response_weight: &u64) -> Weight; fn unsubscribe_version() -> Weight; - fn burn_asset(_assets: &MultiAssets) -> Weight { - 0 - } - fn expect_asset(_assets: &MultiAssets) -> Weight { - 0 - } - fn expect_origin(_origin: &Option) -> Weight { - 0 - } - fn expect_error(_error: &Option<(u32, Error)>) -> Weight { - 0 - } - fn query_pallet() -> Weight { - 0 - } - fn expect_pallet(_pallet_index: &u32) -> Weight { - 0 - } - fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { - 0 - } - fn clear_transact_status() -> Weight { - 0 - } + fn burn_asset(_assets: &MultiAssets) -> Weight; + fn expect_asset(_assets: &MultiAssets) -> Weight; + fn expect_origin(_origin: &Option) -> Weight; + fn expect_error(_error: &Option<(u32, Error)>) -> Weight; + fn query_pallet() -> Weight; + fn expect_pallet(_pallet_index: &u32) -> Weight; + fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight; + fn clear_transact_status() -> Weight; } From 22de225ecddc3ce88b92f41242e339477e58296d Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Mon, 20 Dec 2021 03:27:00 -0800 Subject: [PATCH 09/15] Fix compilation error --- runtime/westend/src/weights/xcm/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index c59c0d2d1fc1..7b2a2317184e 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -191,7 +191,7 @@ impl XcmWeightInfo for WestendXcmWeight { fn expect_origin(_origin: &Option) -> Weight { XcmGeneric::::expect_origin() } - fn expect_error(_error: &Option<(u32, Error)>) -> Weight { + fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { XcmGeneric::::expect_error() } fn query_pallet() -> Weight { From 3b7c47a6182e1b9227036c38b406d494c3fcf6fd Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 29 Dec 2021 02:09:08 -0800 Subject: [PATCH 10/15] Add weight_args helper attribute --- xcm/procedural/src/lib.rs | 2 +- xcm/procedural/src/weight_info.rs | 60 +++++++++++++++++++++---------- xcm/src/v3/mod.rs | 12 +++---- 3 files changed, 49 insertions(+), 25 deletions(-) diff --git a/xcm/procedural/src/lib.rs b/xcm/procedural/src/lib.rs index 8e43569b64d7..959650ebcdad 100644 --- a/xcm/procedural/src/lib.rs +++ b/xcm/procedural/src/lib.rs @@ -36,7 +36,7 @@ pub fn impl_conversion_functions_for_multilocation_v1(input: TokenStream) -> Tok .into() } -#[proc_macro_derive(XcmWeightInfoTrait)] +#[proc_macro_derive(XcmWeightInfoTrait, attributes(weight_args))] pub fn derive_xcm_weight_info(item: TokenStream) -> TokenStream { weight_info::derive(item) } diff --git a/xcm/procedural/src/weight_info.rs b/xcm/procedural/src/weight_info.rs index 6dc64b66d4eb..fa54a00851a4 100644 --- a/xcm/procedural/src/weight_info.rs +++ b/xcm/procedural/src/weight_info.rs @@ -27,26 +27,32 @@ pub fn derive(item: proc_macro::TokenStream) -> proc_macro::TokenStream { match data { syn::Data::Enum(syn::DataEnum { variants, .. }) => { - let methods = variants.into_iter().map(|syn::Variant { ident, fields, .. }| { - let snake_cased_ident = format_ident!("{}", ident.to_string().to_snake_case()); - let ref_fields = - fields.into_iter().enumerate().map(|(idx, syn::Field { ident, ty, .. })| { - let field_name = ident.unwrap_or_else(|| format_ident!("_{}", idx)); - let field_ty = match ty { - syn::Type::Reference(r) => { - // If the type is already a reference, do nothing - quote::quote!(#r) - }, - t => { - // Otherwise, make it a reference - quote::quote!(&#t) - }, - }; + let methods = + variants.into_iter().map(|syn::Variant { ident, fields, attrs, .. }| { + let snake_cased_ident = format_ident!("{}", ident.to_string().to_snake_case()); + let ref_fields = parse_args_attr(attrs).unwrap_or_else(|| { + fields + .into_iter() + .enumerate() + .map(|(idx, syn::Field { ident, ty, .. })| { + let field_name = ident.unwrap_or_else(|| format_ident!("_{}", idx)); + let field_ty = match ty { + syn::Type::Reference(r) => { + // If the type is already a reference, do nothing + quote::quote!(#r) + }, + t => { + // Otherwise, make it a reference + quote::quote!(&#t) + }, + }; - quote::quote!(#field_name: #field_ty,) + quote::quote!(#field_name: #field_ty,) + }) + .collect() }); - quote::quote!(fn #snake_cased_ident( #(#ref_fields)* ) -> Weight;) - }); + quote::quote!(fn #snake_cased_ident( #ref_fields ) -> Weight;) + }); let res = quote::quote! { pub trait XcmWeightInfo #generics { @@ -65,3 +71,21 @@ pub fn derive(item: proc_macro::TokenStream) -> proc_macro::TokenStream { }, } } + +fn parse_args_attr(attrs: Vec) -> Option { + attrs.into_iter().find_map(|attr| { + attr.path.get_ident().filter(|ident| *ident == "weight_args").and_then(|_| { + attr.parse_args_with(|stream: syn::parse::ParseStream| { + let mut fields = Vec::new(); + while !stream.is_empty() { + let ident: syn::Ident = stream.parse()?; + let _colon: syn::Token![:] = stream.parse()?; + let ty: syn::Type = stream.parse()?; + fields.push(quote::quote!(#ident: #ty)); + } + Ok(quote::quote!( #(#fields),* )) + }) + .ok() + }) + }) +} diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 29429a6ceb03..90321c238572 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -35,13 +35,11 @@ pub use multiasset::{ AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, WildFungibility, WildMultiAsset, }; -pub use traits::{ - Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm, Weight, XcmWeightInfo, -}; +pub use traits::{Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm}; // These parts of XCM v2 are unchanged in XCM v3, and are re-imported here. pub use super::v2::{ Ancestor, AncestorThen, BodyId, BodyPart, InteriorMultiLocation, Junction, Junctions, - MultiLocation, NetworkId, OriginKind, Parent, ParentThen, WeightLimit, + MultiLocation, NetworkId, OriginKind, Parent, ParentThen, Weight, WeightLimit, }; /// This module's XCM version. @@ -218,7 +216,7 @@ pub struct QueryResponseInfo { /// /// This is the inner XCM format and is version-sensitive. Messages are typically passed using the outer /// XCM format, known as `VersionedXcm`. -#[derive(Derivative, Encode, Decode, TypeInfo)] +#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)] #[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] #[codec(encode_bound())] #[codec(decode_bound())] @@ -662,6 +660,7 @@ pub enum Instruction { /// Kind: *Instruction* /// /// Errors: *Fallible*. + #[weight_args()] QueryPallet { module_name: Vec, response_info: QueryResponseInfo }, /// Ensure that a particular pallet with a particular version exists. @@ -678,6 +677,7 @@ pub enum Instruction { /// /// Errors: /// - `ExpectationFalse`: In case any of the expectations are broken. + #[weight_args(index: &u32)] ExpectPallet { #[codec(compact)] index: u32, @@ -771,7 +771,7 @@ impl Instruction { QueryPallet { module_name, response_info }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(repsonse_info) => ReportTransactStatus(repsonse_info), + ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, } } From bc168243c543104a08e5cd5ed77aefe8c3c35f78 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Wed, 29 Dec 2021 02:37:11 -0800 Subject: [PATCH 11/15] Remove manually written XcmWeightInfo --- xcm/src/v3/traits.rs | 57 -------------------------------------------- 1 file changed, 57 deletions(-) diff --git a/xcm/src/v3/traits.rs b/xcm/src/v3/traits.rs index 1840d429384c..2d4e8ff2325f 100644 --- a/xcm/src/v3/traits.rs +++ b/xcm/src/v3/traits.rs @@ -367,60 +367,3 @@ impl SendXcm for Tuple { Err(SendError::CannotReachDestination(destination.into(), message)) } } - -/// The info needed to weigh an XCM. -// TODO: Automate Generation -pub trait XcmWeightInfo { - fn withdraw_asset(assets: &MultiAssets) -> Weight; - fn reserve_asset_deposited(assets: &MultiAssets) -> Weight; - fn receive_teleported_asset(assets: &MultiAssets) -> Weight; - fn query_response(query_id: &u64, response: &Response, max_weight: &u64) -> Weight; - fn transfer_asset(assets: &MultiAssets, beneficiary: &MultiLocation) -> Weight; - fn transfer_reserve_asset(assets: &MultiAssets, dest: &MultiLocation, xcm: &Xcm<()>) -> Weight; - fn transact( - origin_kind: &OriginKind, - require_weight_at_most: &u64, - call: &DoubleEncoded, - ) -> Weight; - fn hrmp_new_channel_open_request( - sender: &u32, - max_message_size: &u32, - max_capacity: &u32, - ) -> Weight; - fn hrmp_channel_accepted(recipient: &u32) -> Weight; - fn hrmp_channel_closing(initiator: &u32, sender: &u32, recipient: &u32) -> Weight; - fn clear_origin() -> Weight; - fn descend_origin(who: &InteriorMultiLocation) -> Weight; - fn report_error(response_info: &QueryResponseInfo) -> Weight; - fn deposit_asset(assets: &MultiAssetFilter, beneficiary: &MultiLocation) -> Weight; - fn deposit_reserve_asset( - assets: &MultiAssetFilter, - dest: &MultiLocation, - xcm: &Xcm<()>, - ) -> Weight; - fn exchange_asset(give: &MultiAssetFilter, receive: &MultiAssets) -> Weight; - fn initiate_reserve_withdraw( - assets: &MultiAssetFilter, - reserve: &MultiLocation, - xcm: &Xcm<()>, - ) -> Weight; - fn initiate_teleport(assets: &MultiAssetFilter, dest: &MultiLocation, xcm: &Xcm<()>) -> Weight; - fn report_holding(response_info: &QueryResponseInfo, assets: &MultiAssetFilter) -> Weight; - fn buy_execution(fees: &MultiAsset, weight_limit: &WeightLimit) -> Weight; - fn refund_surplus() -> Weight; - fn set_error_handler(xcm: &Xcm) -> Weight; - fn set_appendix(xcm: &Xcm) -> Weight; - fn clear_error() -> Weight; - fn claim_asset(assets: &MultiAssets, ticket: &MultiLocation) -> Weight; - fn trap(code: &u64) -> Weight; - fn subscribe_version(query_id: &QueryId, max_response_weight: &u64) -> Weight; - fn unsubscribe_version() -> Weight; - fn burn_asset(_assets: &MultiAssets) -> Weight; - fn expect_asset(_assets: &MultiAssets) -> Weight; - fn expect_origin(_origin: &Option) -> Weight; - fn expect_error(_error: &Option<(u32, Error)>) -> Weight; - fn query_pallet() -> Weight; - fn expect_pallet(_pallet_index: &u32) -> Weight; - fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight; - fn clear_transact_status() -> Weight; -} From 70dc3f58ca69411dd8d661f6cd44f31a439cdf7e Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Thu, 30 Dec 2021 17:33:15 -0800 Subject: [PATCH 12/15] Parse trailing comma --- xcm/procedural/src/weight_info.rs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/xcm/procedural/src/weight_info.rs b/xcm/procedural/src/weight_info.rs index fa54a00851a4..2e8e4819998b 100644 --- a/xcm/procedural/src/weight_info.rs +++ b/xcm/procedural/src/weight_info.rs @@ -81,6 +81,9 @@ fn parse_args_attr(attrs: Vec) -> Option Date: Tue, 18 Jan 2022 01:44:05 -0800 Subject: [PATCH 13/15] Revert "Add weight_args helper attribute" This reverts commit 3b7c47a6182e1b9227036c38b406d494c3fcf6fd. --- xcm/procedural/src/lib.rs | 2 +- xcm/procedural/src/weight_info.rs | 63 +++++++++---------------------- xcm/src/v3/mod.rs | 12 +++--- 3 files changed, 25 insertions(+), 52 deletions(-) diff --git a/xcm/procedural/src/lib.rs b/xcm/procedural/src/lib.rs index 959650ebcdad..8e43569b64d7 100644 --- a/xcm/procedural/src/lib.rs +++ b/xcm/procedural/src/lib.rs @@ -36,7 +36,7 @@ pub fn impl_conversion_functions_for_multilocation_v1(input: TokenStream) -> Tok .into() } -#[proc_macro_derive(XcmWeightInfoTrait, attributes(weight_args))] +#[proc_macro_derive(XcmWeightInfoTrait)] pub fn derive_xcm_weight_info(item: TokenStream) -> TokenStream { weight_info::derive(item) } diff --git a/xcm/procedural/src/weight_info.rs b/xcm/procedural/src/weight_info.rs index 2e8e4819998b..6dc64b66d4eb 100644 --- a/xcm/procedural/src/weight_info.rs +++ b/xcm/procedural/src/weight_info.rs @@ -27,32 +27,26 @@ pub fn derive(item: proc_macro::TokenStream) -> proc_macro::TokenStream { match data { syn::Data::Enum(syn::DataEnum { variants, .. }) => { - let methods = - variants.into_iter().map(|syn::Variant { ident, fields, attrs, .. }| { - let snake_cased_ident = format_ident!("{}", ident.to_string().to_snake_case()); - let ref_fields = parse_args_attr(attrs).unwrap_or_else(|| { - fields - .into_iter() - .enumerate() - .map(|(idx, syn::Field { ident, ty, .. })| { - let field_name = ident.unwrap_or_else(|| format_ident!("_{}", idx)); - let field_ty = match ty { - syn::Type::Reference(r) => { - // If the type is already a reference, do nothing - quote::quote!(#r) - }, - t => { - // Otherwise, make it a reference - quote::quote!(&#t) - }, - }; + let methods = variants.into_iter().map(|syn::Variant { ident, fields, .. }| { + let snake_cased_ident = format_ident!("{}", ident.to_string().to_snake_case()); + let ref_fields = + fields.into_iter().enumerate().map(|(idx, syn::Field { ident, ty, .. })| { + let field_name = ident.unwrap_or_else(|| format_ident!("_{}", idx)); + let field_ty = match ty { + syn::Type::Reference(r) => { + // If the type is already a reference, do nothing + quote::quote!(#r) + }, + t => { + // Otherwise, make it a reference + quote::quote!(&#t) + }, + }; - quote::quote!(#field_name: #field_ty,) - }) - .collect() + quote::quote!(#field_name: #field_ty,) }); - quote::quote!(fn #snake_cased_ident( #ref_fields ) -> Weight;) - }); + quote::quote!(fn #snake_cased_ident( #(#ref_fields)* ) -> Weight;) + }); let res = quote::quote! { pub trait XcmWeightInfo #generics { @@ -71,24 +65,3 @@ pub fn derive(item: proc_macro::TokenStream) -> proc_macro::TokenStream { }, } } - -fn parse_args_attr(attrs: Vec) -> Option { - attrs.into_iter().find_map(|attr| { - attr.path.get_ident().filter(|ident| *ident == "weight_args").and_then(|_| { - attr.parse_args_with(|stream: syn::parse::ParseStream| { - let mut fields = Vec::new(); - while !stream.is_empty() { - let ident: syn::Ident = stream.parse()?; - let _colon: syn::Token![:] = stream.parse()?; - let ty: syn::Type = stream.parse()?; - if stream.peek(syn::Token![,]) { - let _trailing_comma: syn::Token![,] = stream.parse()?; - } - fields.push(quote::quote!(#ident: #ty)); - } - Ok(quote::quote!( #(#fields),* )) - }) - .ok() - }) - }) -} diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 90321c238572..29429a6ceb03 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -35,11 +35,13 @@ pub use multiasset::{ AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, WildFungibility, WildMultiAsset, }; -pub use traits::{Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm}; +pub use traits::{ + Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm, Weight, XcmWeightInfo, +}; // These parts of XCM v2 are unchanged in XCM v3, and are re-imported here. pub use super::v2::{ Ancestor, AncestorThen, BodyId, BodyPart, InteriorMultiLocation, Junction, Junctions, - MultiLocation, NetworkId, OriginKind, Parent, ParentThen, Weight, WeightLimit, + MultiLocation, NetworkId, OriginKind, Parent, ParentThen, WeightLimit, }; /// This module's XCM version. @@ -216,7 +218,7 @@ pub struct QueryResponseInfo { /// /// This is the inner XCM format and is version-sensitive. Messages are typically passed using the outer /// XCM format, known as `VersionedXcm`. -#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)] +#[derive(Derivative, Encode, Decode, TypeInfo)] #[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] #[codec(encode_bound())] #[codec(decode_bound())] @@ -660,7 +662,6 @@ pub enum Instruction { /// Kind: *Instruction* /// /// Errors: *Fallible*. - #[weight_args()] QueryPallet { module_name: Vec, response_info: QueryResponseInfo }, /// Ensure that a particular pallet with a particular version exists. @@ -677,7 +678,6 @@ pub enum Instruction { /// /// Errors: /// - `ExpectationFalse`: In case any of the expectations are broken. - #[weight_args(index: &u32)] ExpectPallet { #[codec(compact)] index: u32, @@ -771,7 +771,7 @@ impl Instruction { QueryPallet { module_name, response_info }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(response_info) => ReportTransactStatus(response_info), + ReportTransactStatus(repsonse_info) => ReportTransactStatus(repsonse_info), ClearTransactStatus => ClearTransactStatus, } } From e731fdf1cc4bcef05e3bedd1ed874796d4a08885 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 18 Jan 2022 02:20:18 -0800 Subject: [PATCH 14/15] Fixes --- runtime/westend/src/weights/xcm/mod.rs | 10 ++++++++-- xcm/src/v3/mod.rs | 16 ++++++++-------- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 7b2a2317184e..7afc7cdb65bf 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -194,10 +194,16 @@ impl XcmWeightInfo for WestendXcmWeight { fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { XcmGeneric::::expect_error() } - fn query_pallet() -> Weight { + fn query_pallet(_module_name: &Vec, _response_info: QueryResponseInfo) -> Weight { XcmGeneric::::query_pallet() } - fn expect_pallet(_pallet_index: &u32) -> Weight { + fn expect_pallet( + _index: &u32, + _name: &Vec, + _module_name: &Vec, + _crate_major: &u32, + _min_crate_minor: &u32, + ) -> Weight { XcmGeneric::::expect_pallet() } fn report_transact_status(_response_info: &QueryResponseInfo) -> Weight { diff --git a/xcm/src/v3/mod.rs b/xcm/src/v3/mod.rs index 29429a6ceb03..959847aebee5 100644 --- a/xcm/src/v3/mod.rs +++ b/xcm/src/v3/mod.rs @@ -35,13 +35,11 @@ pub use multiasset::{ AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, WildFungibility, WildMultiAsset, }; -pub use traits::{ - Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm, Weight, XcmWeightInfo, -}; +pub use traits::{Error, ExecuteXcm, Outcome, Result, SendError, SendResult, SendXcm}; // These parts of XCM v2 are unchanged in XCM v3, and are re-imported here. pub use super::v2::{ Ancestor, AncestorThen, BodyId, BodyPart, InteriorMultiLocation, Junction, Junctions, - MultiLocation, NetworkId, OriginKind, Parent, ParentThen, WeightLimit, + MultiLocation, NetworkId, OriginKind, Parent, ParentThen, Weight, WeightLimit, }; /// This module's XCM version. @@ -218,7 +216,7 @@ pub struct QueryResponseInfo { /// /// This is the inner XCM format and is version-sensitive. Messages are typically passed using the outer /// XCM format, known as `VersionedXcm`. -#[derive(Derivative, Encode, Decode, TypeInfo)] +#[derive(Derivative, Encode, Decode, TypeInfo, xcm_procedural::XcmWeightInfoTrait)] #[derivative(Clone(bound = ""), Eq(bound = ""), PartialEq(bound = ""), Debug(bound = ""))] #[codec(encode_bound())] #[codec(decode_bound())] @@ -771,7 +769,7 @@ impl Instruction { QueryPallet { module_name, response_info }, ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => ExpectPallet { index, name, module_name, crate_major, min_crate_minor }, - ReportTransactStatus(repsonse_info) => ReportTransactStatus(repsonse_info), + ReportTransactStatus(response_info) => ReportTransactStatus(response_info), ClearTransactStatus => ClearTransactStatus, } } @@ -822,8 +820,10 @@ impl> GetWeight for Instruction { ExpectAsset(assets) => W::expect_asset(assets), ExpectOrigin(origin) => W::expect_origin(origin), ExpectError(error) => W::expect_error(error), - QueryPallet { .. } => W::query_pallet(), - ExpectPallet { index, .. } => W::expect_pallet(index), + QueryPallet { module_name, response_info } => + W::query_pallet(module_name, response_info), + ExpectPallet { index, name, module_name, crate_major, min_crate_minor } => + W::expect_pallet(index, name, module_name, crate_major, min_crate_minor), ReportTransactStatus(response_info) => W::report_transact_status(response_info), ClearTransactStatus => W::clear_transact_status(), } From d32f33e0829e114b378a6905a05134b0f807cea1 Mon Sep 17 00:00:00 2001 From: Keith Yeung Date: Tue, 18 Jan 2022 02:44:32 -0800 Subject: [PATCH 15/15] Fixes --- runtime/westend/src/weights/xcm/mod.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/runtime/westend/src/weights/xcm/mod.rs b/runtime/westend/src/weights/xcm/mod.rs index 7afc7cdb65bf..0116b0a04d54 100644 --- a/runtime/westend/src/weights/xcm/mod.rs +++ b/runtime/westend/src/weights/xcm/mod.rs @@ -194,7 +194,7 @@ impl XcmWeightInfo for WestendXcmWeight { fn expect_error(_error: &Option<(u32, XcmError)>) -> Weight { XcmGeneric::::expect_error() } - fn query_pallet(_module_name: &Vec, _response_info: QueryResponseInfo) -> Weight { + fn query_pallet(_module_name: &Vec, _response_info: &QueryResponseInfo) -> Weight { XcmGeneric::::query_pallet() } fn expect_pallet(