diff --git a/Cargo.lock b/Cargo.lock index d858daa5e092..3343a5fbe3b1 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -869,6 +869,7 @@ dependencies = [ "staging-xcm-builder", "staging-xcm-executor", "westend-runtime", + "westend-runtime-constants", "xcm-emulator", ] @@ -942,6 +943,7 @@ dependencies = [ "staging-xcm-builder", "staging-xcm-executor", "substrate-wasm-builder", + "westend-runtime", "westend-runtime-constants", ] @@ -3543,6 +3545,7 @@ dependencies = [ "log", "parity-scale-codec", "polkadot-parachain-primitives", + "polkadot-runtime-parachains", "sc-client-api", "scale-info", "sp-core", @@ -3723,8 +3726,10 @@ dependencies = [ "cumulus-primitives-core", "frame-support", "log", + "pallet-xcm-benchmarks", "parity-scale-codec", "polkadot-runtime-common", + "polkadot-runtime-parachains", "sp-io", "sp-runtime", "sp-std", @@ -13995,6 +14000,7 @@ dependencies = [ "parachains-common", "parity-scale-codec", "polkadot-parachain-primitives", + "polkadot-runtime-common", "scale-info", "sp-api", "sp-block-builder", diff --git a/cumulus/pallets/parachain-system/Cargo.toml b/cumulus/pallets/parachain-system/Cargo.toml index 5470dce47480..64e238ecab69 100644 --- a/cumulus/pallets/parachain-system/Cargo.toml +++ b/cumulus/pallets/parachain-system/Cargo.toml @@ -29,6 +29,7 @@ sp-version = { path = "../../../substrate/primitives/version", default-features # Polkadot polkadot-parachain-primitives = { path = "../../../polkadot/parachain", default-features = false, features = [ "wasm-api" ]} +polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} # Cumulus @@ -63,6 +64,7 @@ std = [ "frame-system/std", "log/std", "polkadot-parachain-primitives/std", + "polkadot-runtime-parachains/std", "scale-info/std", "sp-core/std", "sp-externalities/std", @@ -80,12 +82,14 @@ runtime-benchmarks = [ "frame-support/runtime-benchmarks", "frame-system/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-parachains/runtime-benchmarks", "sp-runtime/runtime-benchmarks", ] try-runtime = [ "frame-support/try-runtime", "frame-system/try-runtime", + "polkadot-runtime-parachains/try-runtime", "sp-runtime/try-runtime", ] diff --git a/cumulus/pallets/parachain-system/src/lib.rs b/cumulus/pallets/parachain-system/src/lib.rs index eaf15768e290..3b1d0525d15f 100644 --- a/cumulus/pallets/parachain-system/src/lib.rs +++ b/cumulus/pallets/parachain-system/src/lib.rs @@ -45,6 +45,7 @@ use frame_support::{ }; use frame_system::{ensure_none, ensure_root, pallet_prelude::HeaderFor}; use polkadot_parachain_primitives::primitives::RelayChainBlockNumber; +use polkadot_runtime_parachains::FeeTracker; use scale_info::TypeInfo; use sp_runtime::{ traits::{Block as BlockT, BlockNumberProvider, Hash}, @@ -52,7 +53,7 @@ use sp_runtime::{ InvalidTransaction, TransactionLongevity, TransactionSource, TransactionValidity, ValidTransaction, }, - DispatchError, RuntimeDebug, + DispatchError, FixedU128, RuntimeDebug, Saturating, }; use sp_std::{cmp, collections::btree_map::BTreeMap, prelude::*}; use xcm::latest::XcmHash; @@ -177,6 +178,20 @@ where check_version: bool, } +pub mod ump_constants { + use super::FixedU128; + + /// `host_config.max_upward_queue_size / THRESHOLD_FACTOR` is the threshold after which delivery + /// starts getting exponentially more expensive. + /// `2` means the price starts to increase when queue is half full. + pub const THRESHOLD_FACTOR: u32 = 2; + /// The base number the delivery fee factor gets multiplied by every time it is increased. + /// Also the number it gets divided by when decreased. + pub const EXPONENTIAL_FEE_BASE: FixedU128 = FixedU128::from_rational(105, 100); // 1.05 + /// The base number message size in KB is multiplied by before increasing the fee factor. + pub const MESSAGE_SIZE_FEE_BASE: FixedU128 = FixedU128::from_rational(1, 1000); // 0.001 +} + #[frame_support::pallet] pub mod pallet { use super::*; @@ -240,6 +255,9 @@ pub mod pallet { #[pallet::hooks] impl Hooks> for Pallet { + /// Handles actually sending upward messages by moving them from `PendingUpwardMessages` to + /// `UpwardMessages`. Decreases the delivery fee factor if after sending messages, the queue + /// total size is less than the threshold (see [`ump_constants::THRESHOLD_FACTOR`]). fn on_finalize(_: BlockNumberFor) { >::kill(); >::kill(); @@ -326,6 +344,17 @@ pub mod pallet { UpwardMessages::::put(&up[..num as usize]); *up = up.split_off(num as usize); + // If the total size of the pending messages is less than the threshold, + // we decrease the fee factor, since the queue is less congested. + // This makes delivery of new messages cheaper. + let threshold = host_config + .max_upward_queue_size + .saturating_div(ump_constants::THRESHOLD_FACTOR); + let remaining_total_size: usize = up.iter().map(UpwardMessage::len).sum(); + if remaining_total_size <= threshold as usize { + Self::decrease_fee_factor(()); + } + (num, total_size) }); @@ -721,7 +750,7 @@ pub mod pallet { StorageValue<_, Vec>, ValueQuery>; /// Storage field that keeps track of bandwidth used by the unincluded segment along with the - /// latest the latest HRMP watermark. Used for limiting the acceptance of new blocks with + /// latest HRMP watermark. Used for limiting the acceptance of new blocks with /// respect to relay chain constraints. #[pallet::storage] pub(super) type AggregatedUnincludedSegment = @@ -860,6 +889,17 @@ pub mod pallet { pub(super) type PendingUpwardMessages = StorageValue<_, Vec, ValueQuery>; + /// Initialization value for the delivery fee factor for UMP. + #[pallet::type_value] + pub fn UpwardInitialDeliveryFeeFactor() -> FixedU128 { + FixedU128::from_u32(1) + } + + /// The factor to multiply the base delivery fee by for UMP. + #[pallet::storage] + pub(super) type UpwardDeliveryFeeFactor = + StorageValue<_, FixedU128, ValueQuery, UpwardInitialDeliveryFeeFactor>; + /// The number of HRMP messages we observed in `on_initialize` and thus used that number for /// announcing the weight of `on_initialize` and `on_finalize`. #[pallet::storage] @@ -976,6 +1016,31 @@ impl Pallet { } } +impl FeeTracker for Pallet { + type Id = (); + + fn get_fee_factor(_: Self::Id) -> FixedU128 { + UpwardDeliveryFeeFactor::::get() + } + + fn increase_fee_factor(_: Self::Id, message_size_factor: FixedU128) -> FixedU128 { + >::mutate(|f| { + *f = f.saturating_mul( + ump_constants::EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor), + ); + *f + }) + } + + fn decrease_fee_factor(_: Self::Id) -> FixedU128 { + >::mutate(|f| { + *f = + UpwardInitialDeliveryFeeFactor::get().max(*f / ump_constants::EXPONENTIAL_FEE_BASE); + *f + }) + } +} + impl GetChannelInfo for Pallet { fn get_channel_status(id: ParaId) -> ChannelStatus { // Note, that we are using `relevant_messaging_state` which may be from the previous @@ -1468,7 +1533,13 @@ impl frame_system::SetCode for ParachainSetCode { } impl Pallet { + /// Puts a message in the `PendingUpwardMessages` storage item. + /// The message will be later sent in `on_finalize`. + /// Checks host configuration to see if message is too big. + /// Increases the delivery fee factor if the queue is sufficiently (see + /// [`ump_constants::THRESHOLD_FACTOR`]) congested. pub fn send_upward_message(message: UpwardMessage) -> Result<(u32, XcmHash), MessageSendError> { + let message_len = message.len(); // Check if the message fits into the relay-chain constraints. // // Note, that we are using `host_configuration` here which may be from the previous @@ -1482,9 +1553,21 @@ impl Pallet { // // However, changing this setting is expected to be rare. if let Some(cfg) = Self::host_configuration() { - if message.len() > cfg.max_upward_message_size as usize { + if message_len > cfg.max_upward_message_size as usize { return Err(MessageSendError::TooBig) } + let threshold = + cfg.max_upward_queue_size.saturating_div(ump_constants::THRESHOLD_FACTOR); + // We check the threshold against total size and not number of messages since messages + // could be big or small. + let pending_messages = PendingUpwardMessages::::get(); + let total_size: usize = pending_messages.iter().map(UpwardMessage::len).sum(); + if total_size > threshold as usize { + // We increase the fee factor by a factor based on the new message's size in KB + let message_size_factor = FixedU128::from((message_len / 1024) as u128) + .saturating_mul(ump_constants::MESSAGE_SIZE_FEE_BASE); + Self::increase_fee_factor((), message_size_factor); + } } else { // This storage field should carry over from the previous block. So if it's None // then it must be that this is an edge-case where a message is attempted to be @@ -1496,6 +1579,7 @@ impl Pallet { // // Thus fall through here. }; + >::append(message.clone()); // The relay ump does not use using_encoded diff --git a/cumulus/pallets/xcmp-queue/src/lib.rs b/cumulus/pallets/xcmp-queue/src/lib.rs index 812cecfc57c7..66204b021d78 100644 --- a/cumulus/pallets/xcmp-queue/src/lib.rs +++ b/cumulus/pallets/xcmp-queue/src/lib.rs @@ -47,7 +47,7 @@ use frame_support::{ traits::{EnsureOrigin, Get}, weights::{constants::WEIGHT_REF_TIME_PER_MILLIS, Weight}, }; -use polkadot_runtime_common::xcm_sender::PriceForParachainDelivery; +use polkadot_runtime_common::xcm_sender::PriceForMessageDelivery; use polkadot_runtime_parachains::FeeTracker; use rand_chacha::{ rand_core::{RngCore, SeedableRng}, @@ -110,7 +110,7 @@ pub mod pallet { type ControllerOriginConverter: ConvertOrigin; /// The price for delivering an XCM to a sibling parachain destination. - type PriceForSiblingDelivery: PriceForParachainDelivery; + type PriceForSiblingDelivery: PriceForMessageDelivery; /// The weight information of this pallet. type WeightInfo: WeightInfo; @@ -970,28 +970,6 @@ impl Pallet { } }); } - - /// Increases the delivery fee factor by a multiplicative factor and stores the resulting value. - /// - /// Returns the new delivery fee factor after the increase. - pub(crate) fn increase_fee_factor(para: ParaId, message_size_factor: FixedU128) -> FixedU128 { - >::mutate(para, |f| { - *f = f.saturating_mul(EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor)); - *f - }) - } - - /// Decreases the delivery fee factor by a multiplicative factor and stores the resulting value. - /// - /// Does not reduce the fee factor below the initial value, which is currently set as 1. - /// - /// Returns the new delivery fee factor after the decrease. - pub(crate) fn decrease_fee_factor(para: ParaId) -> FixedU128 { - >::mutate(para, |f| { - *f = InitialFactor::get().max(*f / EXPONENTIAL_FEE_BASE); - *f - }) - } } impl XcmpMessageHandler for Pallet { @@ -1203,7 +1181,7 @@ impl SendXcm for Pallet { MultiLocation { parents: 1, interior: X1(Parachain(id)) } => { let xcm = msg.take().ok_or(SendError::MissingArgument)?; let id = ParaId::from(*id); - let price = T::PriceForSiblingDelivery::price_for_parachain_delivery(id, &xcm); + let price = T::PriceForSiblingDelivery::price_for_delivery(id, &xcm); let versioned_xcm = T::VersionWrapper::wrap_version(&d, xcm) .map_err(|()| SendError::DestinationUnsupported)?; Ok(((id, versioned_xcm), price)) @@ -1231,7 +1209,23 @@ impl SendXcm for Pallet { } impl FeeTracker for Pallet { - fn get_fee_factor(para: ParaId) -> FixedU128 { - >::get(para) + type Id = ParaId; + + fn get_fee_factor(id: Self::Id) -> FixedU128 { + >::get(id) + } + + fn increase_fee_factor(id: Self::Id, message_size_factor: FixedU128) -> FixedU128 { + >::mutate(id, |f| { + *f = f.saturating_mul(EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor)); + *f + }) + } + + fn decrease_fee_factor(id: Self::Id) -> FixedU128 { + >::mutate(id, |f| { + *f = InitialFactor::get().max(*f / EXPONENTIAL_FEE_BASE); + *f + }) } } diff --git a/cumulus/pallets/xcmp-queue/src/mock.rs b/cumulus/pallets/xcmp-queue/src/mock.rs index a3f10fa5428c..e7ae1a68703e 100644 --- a/cumulus/pallets/xcmp-queue/src/mock.rs +++ b/cumulus/pallets/xcmp-queue/src/mock.rs @@ -23,6 +23,7 @@ use frame_support::{ traits::{ConstU32, Everything, Nothing, OriginTrait}, }; use frame_system::EnsureRoot; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_core::H256; use sp_runtime::{ traits::{BlakeTwo256, IdentityLookup}, @@ -205,7 +206,7 @@ impl Config for Test { type ControllerOrigin = EnsureRoot; type ControllerOriginConverter = SystemParachainAsSuperuser; type WeightInfo = (); - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } pub fn new_test_ext() -> sp_io::TestExternalities { diff --git a/cumulus/parachain-template/runtime/src/lib.rs b/cumulus/parachain-template/runtime/src/lib.rs index b9bf97d7786f..b6bf8419ec46 100644 --- a/cumulus/parachain-template/runtime/src/lib.rs +++ b/cumulus/parachain-template/runtime/src/lib.rs @@ -10,6 +10,8 @@ mod weights; pub mod xcm_config; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use smallvec::smallvec; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; @@ -412,7 +414,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = EnsureRoot; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = (); - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { diff --git a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/Cargo.toml index f4f75dd31c54..fd8d78c6e8e5 100644 --- a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/Cargo.toml @@ -31,6 +31,7 @@ xcm-builder = { package = "staging-xcm-builder", path = "../../../../../../polk xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../polkadot/xcm/xcm-executor", default-features = false} pallet-xcm = { path = "../../../../../../polkadot/xcm/pallet-xcm", default-features = false} westend-runtime = { path = "../../../../../../polkadot/runtime/westend", default-features = false } +westend-runtime-constants = { path = "../../../../../../polkadot/runtime/westend/constants", default-features = false } # Cumulus parachains-common = { path = "../../../../common" } diff --git a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/reserve_transfer.rs b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/reserve_transfer.rs index addbee69830a..3b48e6529ff7 100644 --- a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/reserve_transfer.rs +++ b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/reserve_transfer.rs @@ -14,8 +14,8 @@ // limitations under the License. use crate::*; -use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig; use asset_hub_westend_runtime::xcm_config::XcmConfig; +use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig; fn relay_origin_assertions(t: RelayToSystemParaTest) { type RuntimeEvent = ::RuntimeEvent; @@ -182,13 +182,9 @@ fn limited_reserve_transfer_native_asset_from_relay_to_system_para_fails() { test.assert(); let delivery_fees = Westend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::<::XcmSender>( - test.args.assets.clone(), - 0, - test.args.weight_limit, - test.args.beneficiary, - test.args.dest, - ) + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) }); let sender_balance_after = test.sender.balance; @@ -251,13 +247,9 @@ fn reserve_transfer_native_asset_from_relay_to_system_para_fails() { test.assert(); let delivery_fees = Westend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::<::XcmSender>( - test.args.assets.clone(), - 0, - test.args.weight_limit, - test.args.beneficiary, - test.args.dest, - ) + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) }); let sender_balance_after = test.sender.balance; diff --git a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/teleport.rs b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/teleport.rs index 51b4035c728d..a302344bb07c 100644 --- a/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/teleport.rs +++ b/cumulus/parachains/integration-tests/emulated/assets/asset-hub-westend/src/tests/teleport.rs @@ -16,6 +16,7 @@ #![allow(dead_code)] // use crate::*; +use asset_hub_westend_runtime::xcm_config::XcmConfig as AssetHubWestendXcmConfig; use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig; fn relay_origin_assertions(t: RelayToSystemParaTest) { @@ -175,13 +176,9 @@ fn limited_teleport_native_assets_from_relay_to_system_para_works() { test.assert(); let delivery_fees = Westend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::<::XcmSender>( - test.args.assets.clone(), - 0, - test.args.weight_limit, - test.args.beneficiary, - test.args.dest, - ) + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) }); let sender_balance_after = test.sender.balance; @@ -225,8 +222,14 @@ fn limited_teleport_native_assets_back_from_system_para_to_relay_works() { let sender_balance_after = test.sender.balance; let receiver_balance_after = test.receiver.balance; + let delivery_fees = AssetHubWestend::execute_with(|| { + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) + }); + // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send, sender_balance_after); + assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); } @@ -260,8 +263,14 @@ fn limited_teleport_native_assets_from_system_para_to_relay_fails() { let sender_balance_after = test.sender.balance; let receiver_balance_after = test.receiver.balance; + let delivery_fees = AssetHubWestend::execute_with(|| { + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) + }); + // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send, sender_balance_after); + assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance does not change assert_eq!(receiver_balance_after, receiver_balance_before); } @@ -288,13 +297,9 @@ fn teleport_native_assets_from_relay_to_system_para_works() { test.assert(); let delivery_fees = Westend::execute_with(|| { - xcm_helpers::transfer_assets_delivery_fees::<::XcmSender>( - test.args.assets.clone(), - 0, - test.args.weight_limit, - test.args.beneficiary, - test.args.dest, - ) + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) }); let sender_balance_after = test.sender.balance; @@ -335,11 +340,17 @@ fn teleport_native_assets_back_from_system_para_to_relay_works() { test.set_dispatchable::(system_para_teleport_assets); test.assert(); + let delivery_fees = AssetHubWestend::execute_with(|| { + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) + }); + let sender_balance_after = test.sender.balance; let receiver_balance_after = test.receiver.balance; // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send, sender_balance_after); + assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance is increased assert!(receiver_balance_after > receiver_balance_before); } @@ -370,11 +381,17 @@ fn teleport_native_assets_from_system_para_to_relay_fails() { test.set_dispatchable::(system_para_teleport_assets); test.assert(); + let delivery_fees = AssetHubWestend::execute_with(|| { + xcm_helpers::transfer_assets_delivery_fees::< + ::XcmSender, + >(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest) + }); + let sender_balance_after = test.sender.balance; let receiver_balance_after = test.receiver.balance; // Sender's balance is reduced - assert_eq!(sender_balance_before - amount_to_send, sender_balance_after); + assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after); // Receiver's balance does not change assert_eq!(receiver_balance_after, receiver_balance_before); } diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs index cd49d516a53a..5c51a3a52324 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/lib.rs @@ -34,6 +34,8 @@ use assets_common::{ AssetIdForTrustBackedAssetsConvert, MultiLocationForAssetId, }; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ @@ -645,7 +647,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { >; type ControllerOriginConverter = xcm_config::XcmOriginToTransactDispatchOrigin; type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { @@ -1211,10 +1213,21 @@ impl_runtime_apis! { use xcm_config::{KsmLocation, MaxAssetsIntoHolding}; use pallet_xcm_benchmarks::asset_instance_from; + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + KsmLocation::get(), + ExistentialDeposit::get() + ).into()); + } + impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = (); // No requirement for UMP + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; fn valid_destination() -> Result { Ok(KsmLocation::get()) } @@ -1270,6 +1283,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs index 0a7176847017..c53db960cc81 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-kusama/src/xcm_config.rs @@ -16,9 +16,9 @@ use super::{ AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TrustBackedAssetsInstance, WeightToFee, XcmpQueue, + TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue, }; -use crate::ForeignAssets; +use crate::{ForeignAssets, CENTS}; use assets_common::{ local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation, matching::{ @@ -31,11 +31,9 @@ use frame_support::{ }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; -use parachains_common::{ - impls::ToStakingPot, - xcm_config::AssetFeeAsExistentialDepositMultiplier, -}; +use parachains_common::{impls::ToStakingPot, xcm_config::AssetFeeAsExistentialDepositMultiplier}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::ConvertInto; use xcm::latest::prelude::*; use xcm_builder::{ @@ -531,11 +529,21 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(KsmLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs index 0869748c9361..b58d094deec6 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/lib.rs @@ -66,6 +66,8 @@ use assets_common::{ foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId, }; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ @@ -581,7 +583,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { EnsureXcm>, >; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { @@ -1090,10 +1092,21 @@ impl_runtime_apis! { use xcm_config::{DotLocation, MaxAssetsIntoHolding}; use pallet_xcm_benchmarks::asset_instance_from; + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::DotLocation::get(), + ExistentialDeposit::get() + ).into()); + } + impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = (); + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; fn valid_destination() -> Result { Ok(DotLocation::get()) } @@ -1149,6 +1162,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs index e6d6162a2a3f..92c17ed872c2 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-polkadot/src/xcm_config.rs @@ -16,7 +16,7 @@ use super::{ AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ForeignAssets, ParachainInfo, ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TrustBackedAssetsInstance, WeightToFee, XcmpQueue, + TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue, CENTS, }; use assets_common::matching::{ FromSiblingParachain, IsForeignConcreteAsset, StartsWith, StartsWithExplicitGlobalConsensus, @@ -27,11 +27,9 @@ use frame_support::{ }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; -use parachains_common::{ - impls::ToStakingPot, - xcm_config::AssetFeeAsExistentialDepositMultiplier, -}; +use parachains_common::{impls::ToStakingPot, xcm_config::AssetFeeAsExistentialDepositMultiplier}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::ConvertInto; use xcm::latest::prelude::*; use xcm_builder::{ @@ -455,11 +453,21 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(DotLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml index f7f6fdf68e46..cb5fba1684cc 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/Cargo.toml @@ -60,6 +60,7 @@ polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", d polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false} polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false} westend-runtime-constants = { path = "../../../../../polkadot/runtime/westend/constants", default-features = false} +westend-runtime = { path = "../../../../../polkadot/runtime/westend", default-features = false } xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false} xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false} xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false} @@ -116,6 +117,7 @@ runtime-benchmarks = [ "polkadot-parachain-primitives/runtime-benchmarks", "polkadot-runtime-common/runtime-benchmarks", "sp-runtime/runtime-benchmarks", + "westend-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", ] @@ -149,6 +151,7 @@ try-runtime = [ "parachain-info/try-runtime", "polkadot-runtime-common/try-runtime", "sp-runtime/try-runtime", + "westend-runtime/try-runtime", ] std = [ "assets-common/std", @@ -210,6 +213,7 @@ std = [ "sp-version/std", "substrate-wasm-builder", "westend-runtime-constants/std", + "westend-runtime/std", "xcm-builder/std", "xcm-executor/std", "xcm/std", diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs index 40cdd6380261..97b4ae986c2c 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/lib.rs @@ -1276,25 +1276,21 @@ impl_runtime_apis! { use xcm::latest::prelude::*; use xcm_config::{MaxAssetsIntoHolding, WestendLocation}; use pallet_xcm_benchmarks::asset_instance_from; - use cumulus_primitives_core::ParaId; parameter_types! { pub ExistentialDepositMultiAsset: Option = Some(( xcm_config::WestendLocation::get(), ExistentialDeposit::get() ).into()); - pub ToParachain: ParaId = westend_runtime_constants::system_parachain::BRIDGE_HUB_ID.into(); } impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = polkadot_runtime_common::xcm_sender::ToParachainDeliveryHelper< + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< XcmConfig, ExistentialDepositMultiAsset, - PriceForSiblingParachainDelivery, - ToParachain, - (), + xcm_config::PriceForParentDelivery, >; fn valid_destination() -> Result { Ok(WestendLocation::get()) @@ -1351,6 +1347,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs index a175c3129fb7..24cd063e3b2d 100644 --- a/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/assets/asset-hub-westend/src/xcm_config.rs @@ -14,9 +14,10 @@ // limitations under the License. use super::{ - AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ParachainInfo, - ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - TrustBackedAssetsInstance, WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, BaseDeliveryFee, + FeeAssetId, ParachainInfo, ParachainSystem, PolkadotXcm, PoolAssets, Runtime, RuntimeCall, + RuntimeEvent, RuntimeOrigin, TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, + XcmpQueue, }; use crate::ForeignAssets; use assets_common::{ @@ -37,7 +38,9 @@ use parachains_common::{ TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use sp_runtime::traits::{AccountIdConversion, ConvertInto}; +use westend_runtime::Treasury as WestendTreasury; use westend_runtime_constants::system_parachain; use xcm::latest::prelude::*; use xcm_builder::{ @@ -500,6 +503,23 @@ match_types! { }; } +parameter_types! { + pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(::index() as u8)).into(); +} + +pub struct RelayTreasury; +impl Contains for RelayTreasury { + fn contains(location: &MultiLocation) -> bool { + let relay_treasury_location = RelayTreasuryLocation::get(); + *location == relay_treasury_location + } +} + +/// Locations that will not be charged fees in the executor, +/// either execution or delivery. +/// We only waive fees for system functions, which these locations represent. +pub type WaivedLocations = (RelayOrOtherSystemParachains, RelayTreasury); + pub struct XcmConfig; impl xcm_executor::Config for XcmConfig { type RuntimeCall = RuntimeCall; @@ -546,12 +566,7 @@ impl xcm_executor::Config for XcmConfig { type MaxAssetsIntoHolding = MaxAssetsIntoHolding; type AssetLocker = (); type AssetExchanger = (); - type FeeManager = XcmFeesToAccount< - Self, - RelayOrOtherSystemParachains, - AccountId, - TreasuryAccount, - >; + type FeeManager = XcmFeesToAccount; type MessageExporter = (); type UniversalAliases = Nothing; type CallDispatcher = WithOriginFilter; @@ -562,11 +577,14 @@ impl xcm_executor::Config for XcmConfig { /// Local origins on this chain are allowed to dispatch XCM sends/executions. pub type LocalOriginToLocation = SignedToAccountId32; +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs index 51689c828663..215d29185349 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/test_cases.rs @@ -177,6 +177,21 @@ pub fn teleports_for_native_asset_works< target_account_balance_before_teleport - existential_deposit ); + // Mint funds into account to ensure it has enough balance to pay delivery fees + let delivery_fees = + xcm_helpers::transfer_assets_delivery_fees::( + (native_asset_id, native_asset_to_teleport_away.into()).into(), + 0, + Unlimited, + dest_beneficiary, + dest, + ); + >::mint_into( + &target_account, + delivery_fees.into(), + ) + .unwrap(); + assert_ok!(RuntimeHelper::::do_teleport_assets::( RuntimeHelper::::origin_of(target_account.clone()), dest, diff --git a/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs b/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs index f036f9283dc3..0aebe38fef53 100644 --- a/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs +++ b/cumulus/parachains/runtimes/assets/test-utils/src/xcm_helpers.rs @@ -30,13 +30,47 @@ pub fn transfer_assets_delivery_fees( destination: MultiLocation, ) -> u128 { let message = teleport_assets_dummy_message(assets, fee_asset_item, weight_limit, beneficiary); - let Ok((_, delivery_fees)) = validate_send::(destination, message) else { unreachable!("message can be sent; qed") }; - if let Some(delivery_fee) = delivery_fees.inner().first() { - let Fungible(delivery_fee_amount) = delivery_fee.fun else { unreachable!("asset is fungible; qed"); }; - delivery_fee_amount - } else { - 0 - } + get_fungible_delivery_fees::(destination, message) +} + +/// Returns the delivery fees amount for a query response as a result of the execution +/// of a `ExpectError` instruction with no error. +pub fn query_response_delivery_fees(querier: MultiLocation) -> u128 { + // Message to calculate delivery fees, it's encoded size is what's important. + // This message reports that there was no error, if an error is reported, the encoded size would + // be different. + let message = Xcm(vec![ + SetFeesMode { jit_withdraw: true }, + QueryResponse { + query_id: 0, // Dummy query id + response: Response::ExecutionResult(None), + max_weight: Weight::zero(), + querier: Some(querier), + }, + SetTopic([0u8; 32]), // Dummy topic + ]); + get_fungible_delivery_fees::(querier, message) +} + +/// Returns the delivery fees amount for the execution of `PayOverXcm` +pub fn pay_over_xcm_delivery_fees( + interior: Junctions, + destination: MultiLocation, + beneficiary: MultiLocation, + asset: MultiAsset, +) -> u128 { + // This is a dummy message. + // The encoded size is all that matters for delivery fees. + let message = Xcm(vec![ + DescendOrigin(interior), + UnpaidExecution { weight_limit: Unlimited, check_origin: None }, + SetAppendix(Xcm(vec![ + SetFeesMode { jit_withdraw: true }, + ReportError(QueryResponseInfo { destination, query_id: 0, max_weight: Weight::zero() }), + ])), + TransferAsset { beneficiary, assets: vec![asset].into() }, + ]); + get_fungible_delivery_fees::(destination, message) } /// Approximates the actual message sent by the teleport extrinsic. @@ -57,3 +91,18 @@ fn teleport_assets_dummy_message( SetTopic([0u8; 32]), // Dummy topic ]) } + +/// Given a message, a sender, and a destination, it returns the delivery fees +fn get_fungible_delivery_fees(destination: MultiLocation, message: Xcm<()>) -> u128 { + let Ok((_, delivery_fees)) = validate_send::(destination, message) else { + unreachable!("message can be sent; qed") + }; + if let Some(delivery_fee) = delivery_fees.inner().first() { + let Fungible(delivery_fee_amount) = delivery_fee.fun else { + unreachable!("asset is fungible; qed"); + }; + delivery_fee_amount + } else { + 0 + } +} diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs index 5154ba676ef9..190987b1cfeb 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/lib.rs @@ -26,6 +26,8 @@ mod weights; pub mod xcm_config; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ @@ -314,7 +316,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = RootOrFellows; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { @@ -671,10 +673,21 @@ impl_runtime_apis! { use xcm::latest::prelude::*; use xcm_config::KsmRelayLocation; + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::KsmRelayLocation::get(), + ExistentialDeposit::get() + ).into()); + } + impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = (); // No requirements for UMP + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; fn valid_destination() -> Result { Ok(KsmRelayLocation::get()) } @@ -715,6 +728,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs index fba36e363a97..addc2fc5c3d5 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-kusama/src/xcm_config.rs @@ -16,7 +16,8 @@ use super::{ AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, + CENTS, }; use frame_support::{ match_types, parameter_types, @@ -24,11 +25,9 @@ use frame_support::{ }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; -use parachains_common::{ - impls::ToStakingPot, - xcm_config::ConcreteNativeAssetFrom, -}; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteNativeAssetFrom}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, @@ -220,11 +219,21 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(KsmRelayLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs index dbf99c037603..dc23135f05d7 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/lib.rs @@ -26,6 +26,8 @@ mod weights; pub mod xcm_config; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::{crypto::KeyTypeId, OpaqueMetadata}; use sp_runtime::{ @@ -314,7 +316,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = RootOrFellows; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { @@ -671,10 +673,21 @@ impl_runtime_apis! { use xcm::latest::prelude::*; use xcm_config::DotRelayLocation; + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::DotRelayLocation::get(), + ExistentialDeposit::get() + ).into()); + } + impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = (); // No requirements for UMP + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; fn valid_destination() -> Result { Ok(DotRelayLocation::get()) } @@ -715,6 +728,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs index 6cb3c25ce412..6d1ffb193eb3 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-polkadot/src/xcm_config.rs @@ -16,7 +16,8 @@ use super::{ AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, + CENTS, }; use frame_support::{ match_types, parameter_types, @@ -24,11 +25,9 @@ use frame_support::{ }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; -use parachains_common::{ - impls::ToStakingPot, - xcm_config::ConcreteNativeAssetFrom, -}; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteNativeAssetFrom}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, @@ -224,11 +223,21 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(DotRelayLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs index a1c30e8ac7f0..0052207856a3 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/lib.rs @@ -999,10 +999,21 @@ impl_runtime_apis! { use xcm::latest::prelude::*; use xcm_config::RelayLocation; + parameter_types! { + pub ExistentialDepositMultiAsset: Option = Some(( + xcm_config::RelayLocation::get(), + ExistentialDeposit::get() + ).into()); + } + impl pallet_xcm_benchmarks::Config for Runtime { type XcmConfig = xcm_config::XcmConfig; type AccountIdConverter = xcm_config::LocationToAccountId; - type DeliveryHelper = (); // No requirements for UMP + type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper< + XcmConfig, + ExistentialDepositMultiAsset, + xcm_config::PriceForParentDelivery, + >; fn valid_destination() -> Result { Ok(RelayLocation::get()) } @@ -1043,6 +1054,7 @@ impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs index 3baa90dadcf0..e392ca056d0e 100644 --- a/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/bridge-hubs/bridge-hub-rococo/src/xcm_config.rs @@ -15,10 +15,10 @@ // along with Cumulus. If not, see . use super::{ - AccountId, AllPalletsWithSystem, Balances, BridgeGrandpaRococoInstance, - BridgeGrandpaWococoInstance, DeliveryRewardInBalance, ParachainInfo, ParachainSystem, - PolkadotXcm, RequiredStakeForStakeAndSlash, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, - WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, BridgeGrandpaRococoInstance, + BridgeGrandpaWococoInstance, DeliveryRewardInBalance, FeeAssetId, ParachainInfo, + ParachainSystem, PolkadotXcm, RequiredStakeForStakeAndSlash, Runtime, RuntimeCall, + RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, }; use crate::{ bridge_hub_rococo_config::ToBridgeHubWococoHaulBlobExporter, @@ -36,6 +36,7 @@ use parachains_common::{ TREASURY_PALLET_ID, }; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use rococo_runtime_constants::system_parachain::SystemParachains; use sp_core::Get; use sp_runtime::traits::AccountIdConversion; @@ -272,6 +273,9 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Nothing; } +pub type PriceForParentDelivery = + ExponentialPrice; + /// Converts a local signed origin into an XCM multilocation. /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; @@ -280,7 +284,7 @@ pub type LocalOriginToLocation = SignedToAccountId32, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs index ff16f93d8f54..cec4152bcc31 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/lib.rs @@ -45,6 +45,7 @@ pub mod fellowship; pub use ambassador::pallet_ambassador_origins; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; use fellowship::{ migration::import_kusama_fellowship, pallet_fellowship_origins, Fellows, FellowshipCollectiveInstance, @@ -98,7 +99,7 @@ pub use sp_runtime::BuildStorage; // Polkadot imports use pallet_xcm::{EnsureXcm, IsVoiceOfBody}; use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate}; -use xcm::latest::BodyId; +use xcm::latest::prelude::*; use xcm_executor::XcmExecutor; use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight}; @@ -401,6 +402,20 @@ impl parachain_info::Config for Runtime {} impl cumulus_pallet_aura_ext::Config for Runtime {} +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(xcm_config::DotLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice< + FeeAssetId, + BaseDeliveryFee, + TransactionByteFee, + XcmpQueue, +>; + impl cumulus_pallet_xcmp_queue::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; @@ -410,7 +425,8 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = EitherOfDiverse, Fellows>; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = + polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { diff --git a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs index d8a12ee42dd2..9cf7ee4fe243 100644 --- a/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/collectives/collectives-polkadot/src/xcm_config.rs @@ -14,8 +14,9 @@ // limitations under the License. use super::{ - AccountId, AllPalletsWithSystem, Balances, Fellows, ParachainInfo, ParachainSystem, - PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, FeeAssetId, Fellows, ParachainInfo, + ParachainSystem, PolkadotXcm, Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, + TransactionByteFee, WeightToFee, XcmpQueue, }; use frame_support::{ match_types, parameter_types, @@ -24,11 +25,9 @@ use frame_support::{ }; use frame_system::EnsureRoot; use pallet_xcm::XcmPassthrough; -use parachains_common::{ - impls::ToStakingPot, - xcm_config::ConcreteNativeAssetFrom, -}; +use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteNativeAssetFrom}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use xcm::latest::prelude::*; use xcm_builder::{ AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses, @@ -279,11 +278,14 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs index 70392c5ecbcc..1ea3eaa2e478 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/lib.rs @@ -224,13 +224,17 @@ impl pallet_balances::Config for Runtime { type MaxFreezes = ConstU32<0>; } +parameter_types! { + pub const TransactionByteFee: Balance = MILLICENTS; +} + impl pallet_transaction_payment::Config for Runtime { type RuntimeEvent = RuntimeEvent; type OnChargeTransaction = pallet_transaction_payment::CurrencyAdapter>; type WeightToFee = WeightToFee; /// Relay Chain `TransactionByteFee` / 10 - type LengthToFee = ConstantMultiplier>; + type LengthToFee = ConstantMultiplier; type FeeMultiplierUpdate = SlowAdjustingFeeUpdate; type OperationalFeeMultiplier = ConstU8<5>; } diff --git a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs index 3bf2b3e50816..52d72ba84e0a 100644 --- a/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs +++ b/cumulus/parachains/runtimes/contracts/contracts-rococo/src/xcm_config.rs @@ -15,8 +15,9 @@ use super::{ AccountId, AllPalletsWithSystem, Balances, ParachainInfo, ParachainSystem, PolkadotXcm, - Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, WeightToFee, XcmpQueue, + Runtime, RuntimeCall, RuntimeEvent, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue, }; +use crate::common::rococo::currency::CENTS; use frame_support::{ match_types, parameter_types, traits::{ConstU32, EitherOfDiverse, Everything, Nothing}, @@ -26,6 +27,7 @@ use frame_system::EnsureRoot; use pallet_xcm::{EnsureXcm, IsMajorityOfBody, XcmPassthrough}; use parachains_common::{xcm_config::RelayOrOtherSystemParachains, TREASURY_PALLET_ID}; use polkadot_parachain_primitives::primitives::Sibling; +use polkadot_runtime_common::xcm_sender::ExponentialPrice; use rococo_runtime_constants::system_parachain::SystemParachains; use sp_runtime::traits::AccountIdConversion; use xcm::latest::prelude::*; @@ -184,11 +186,14 @@ impl xcm_executor::Config for XcmConfig { /// Forms the basis for local origins sending/executing XCMs. pub type LocalOriginToLocation = SignedToAccountId32; +pub type PriceForParentDelivery = + ExponentialPrice; + /// The means for routing XCM messages which are not for local execution into the right message /// queues. pub type XcmRouter = WithUniqueTopic<( // Two routers - use UMP to communicate with the relay chain: - cumulus_primitives_utility::ParentAsUmp, + cumulus_primitives_utility::ParentAsUmp, // ..and XCMP to communicate with the sibling chains. XcmpQueue, )>; @@ -236,6 +241,20 @@ impl cumulus_pallet_xcm::Config for Runtime { type XcmExecutor = XcmExecutor; } +parameter_types! { + /// The asset ID for the asset that we use to pay for message delivery fees. + pub FeeAssetId: AssetId = Concrete(RelayLocation::get()); + /// The base fee for the message delivery fees. + pub const BaseDeliveryFee: u128 = CENTS.saturating_mul(3); +} + +pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice< + FeeAssetId, + BaseDeliveryFee, + TransactionByteFee, + XcmpQueue, +>; + impl cumulus_pallet_xcmp_queue::Config for Runtime { type RuntimeEvent = RuntimeEvent; type XcmExecutor = XcmExecutor; @@ -248,7 +267,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { >; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = PriceForSiblingParachainDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { diff --git a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs index fe0f19c30632..86389425eb5e 100644 --- a/cumulus/parachains/runtimes/testing/penpal/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/penpal/src/lib.rs @@ -33,6 +33,7 @@ mod weights; pub mod xcm_config; use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; use frame_support::{ construct_runtime, dispatch::DispatchClass, @@ -50,6 +51,7 @@ use frame_system::{ limits::{BlockLength, BlockWeights}, EnsureRoot, EnsureSigned, }; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use smallvec::smallvec; use sp_api::impl_runtime_apis; pub use sp_consensus_aura::sr25519::AuthorityId as AuraId; @@ -488,7 +490,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = EnsureRoot; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = (); - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml index 029d5d10f986..a662a5e80665 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/Cargo.toml @@ -42,6 +42,7 @@ polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", de xcm = { package = "staging-xcm", path = "../../../../../polkadot/xcm", default-features = false} xcm-builder = { package = "staging-xcm-builder", path = "../../../../../polkadot/xcm/xcm-builder", default-features = false} xcm-executor = { package = "staging-xcm-executor", path = "../../../../../polkadot/xcm/xcm-executor", default-features = false} +polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false } # Cumulus cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false } @@ -86,6 +87,7 @@ std = [ "parachain-info/std", "parachains-common/std", "polkadot-parachain-primitives/std", + "polkadot-runtime-common/std", "scale-info/std", "sp-api/std", "sp-block-builder/std", @@ -118,6 +120,7 @@ runtime-benchmarks = [ "pallet-xcm/runtime-benchmarks", "parachains-common/runtime-benchmarks", "polkadot-parachain-primitives/runtime-benchmarks", + "polkadot-runtime-common/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", diff --git a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs index 50c5a445c25f..dcea349f3a0e 100644 --- a/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs +++ b/cumulus/parachains/runtimes/testing/rococo-parachain/src/lib.rs @@ -23,6 +23,8 @@ include!(concat!(env!("OUT_DIR"), "/wasm_binary.rs")); use cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases; +use cumulus_primitives_core::ParaId; +use polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery; use sp_api::impl_runtime_apis; use sp_core::OpaqueMetadata; use sp_runtime::{ @@ -511,7 +513,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime { type ControllerOrigin = EnsureRoot; type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin; type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight; - type PriceForSiblingDelivery = (); + type PriceForSiblingDelivery = NoPriceForMessageDelivery; } impl cumulus_pallet_dmp_queue::Config for Runtime { diff --git a/cumulus/primitives/utility/Cargo.toml b/cumulus/primitives/utility/Cargo.toml index 9ed1e664ac21..691a4599b2c4 100644 --- a/cumulus/primitives/utility/Cargo.toml +++ b/cumulus/primitives/utility/Cargo.toml @@ -15,11 +15,12 @@ sp-runtime = { path = "../../../substrate/primitives/runtime", default-features sp-std = { path = "../../../substrate/primitives/std", default-features = false} # Polkadot -polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false} -xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false} +polkadot-runtime-common = { path = "../../../polkadot/runtime/common", default-features = false } +polkadot-runtime-parachains = { path = "../../../polkadot/runtime/parachains", default-features = false } +xcm = { package = "staging-xcm", path = "../../../polkadot/xcm", default-features = false } xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", default-features = false} xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/xcm-builder", default-features = false} - +pallet-xcm-benchmarks = { path = "../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false } # Cumulus cumulus-primitives-core = { path = "../core", default-features = false } @@ -30,7 +31,9 @@ std = [ "codec/std", "cumulus-primitives-core/std", "frame-support/std", + "pallet-xcm-benchmarks/std", "polkadot-runtime-common/std", + "polkadot-runtime-parachains/std", "sp-io/std", "sp-runtime/std", "sp-std/std", @@ -41,7 +44,9 @@ std = [ runtime-benchmarks = [ "frame-support/runtime-benchmarks", + "pallet-xcm-benchmarks/runtime-benchmarks", "polkadot-runtime-common/runtime-benchmarks", + "polkadot-runtime-parachains/runtime-benchmarks", "sp-runtime/runtime-benchmarks", "xcm-builder/runtime-benchmarks", "xcm-executor/runtime-benchmarks", diff --git a/cumulus/primitives/utility/src/lib.rs b/cumulus/primitives/utility/src/lib.rs index 024598a99198..c4ce67194855 100644 --- a/cumulus/primitives/utility/src/lib.rs +++ b/cumulus/primitives/utility/src/lib.rs @@ -28,29 +28,13 @@ use frame_support::{ }, weights::Weight, }; -use polkadot_runtime_common::xcm_sender::ConstantPrice; +use polkadot_runtime_common::xcm_sender::PriceForMessageDelivery; use sp_runtime::{traits::Saturating, SaturatedConversion}; use sp_std::{marker::PhantomData, prelude::*}; use xcm::{latest::prelude::*, WrapVersion}; use xcm_builder::TakeRevenue; use xcm_executor::traits::{MatchesFungibles, TransactAsset, WeightTrader}; -pub trait PriceForParentDelivery { - fn price_for_parent_delivery(message: &Xcm<()>) -> MultiAssets; -} - -impl PriceForParentDelivery for () { - fn price_for_parent_delivery(_: &Xcm<()>) -> MultiAssets { - MultiAssets::new() - } -} - -impl> PriceForParentDelivery for ConstantPrice { - fn price_for_parent_delivery(_: &Xcm<()>) -> MultiAssets { - T::get() - } -} - /// Xcm router which recognises the `Parent` destination and handles it by sending the message into /// the given UMP `UpwardMessageSender` implementation. Thus this essentially adapts an /// `UpwardMessageSender` trait impl into a `SendXcm` trait impl. @@ -63,7 +47,7 @@ impl SendXcm for ParentAsUmp where T: UpwardMessageSender, W: WrapVersion, - P: PriceForParentDelivery, + P: PriceForMessageDelivery, { type Ticket = Vec; @@ -76,7 +60,7 @@ where if d.contains_parents_only(1) { // An upward message for the relay chain. let xcm = msg.take().ok_or(SendError::MissingArgument)?; - let price = P::price_for_parent_delivery(&xcm); + let price = P::price_for_delivery((), &xcm); let versioned_xcm = W::wrap_version(&d, xcm).map_err(|()| SendError::DestinationUnsupported)?; let data = versioned_xcm.encode(); @@ -280,7 +264,7 @@ pub struct XcmFeesTo32ByteAccount, - ReceiverAccount: frame_support::traits::Get>, + ReceiverAccount: Get>, > TakeRevenue for XcmFeesTo32ByteAccount { fn take_revenue(revenue: MultiAsset) { @@ -540,3 +524,58 @@ mod tests { assert_eq!(trader.buy_weight(weight_to_buy, payment, &ctx), Err(XcmError::NotWithdrawable)); } } + +/// Implementation of `pallet_xcm_benchmarks::EnsureDelivery` which helps to ensure delivery to the +/// parent relay chain. Deposits existential deposit for origin (if needed). +/// Deposits estimated fee to the origin account (if needed). +/// Allows to trigger additional logic for specific `ParaId` (e.g. open HRMP channel) (if neeeded). +#[cfg(feature = "runtime-benchmarks")] +pub struct ToParentDeliveryHelper( + sp_std::marker::PhantomData<(XcmConfig, ExistentialDeposit, PriceForDelivery)>, +); + +#[cfg(feature = "runtime-benchmarks")] +impl< + XcmConfig: xcm_executor::Config, + ExistentialDeposit: Get>, + PriceForDelivery: PriceForMessageDelivery, + > pallet_xcm_benchmarks::EnsureDelivery + for ToParentDeliveryHelper +{ + fn ensure_successful_delivery( + origin_ref: &MultiLocation, + _dest: &MultiLocation, + fee_reason: xcm_executor::traits::FeeReason, + ) -> (Option, Option) { + use xcm::latest::{MAX_INSTRUCTIONS_TO_DECODE, MAX_ITEMS_IN_MULTIASSETS}; + use xcm_executor::{traits::FeeManager, FeesMode}; + + let mut fees_mode = None; + if !XcmConfig::FeeManager::is_waived(Some(origin_ref), fee_reason) { + // if not waived, we need to set up accounts for paying and receiving fees + + // mint ED to origin if needed + if let Some(ed) = ExistentialDeposit::get() { + XcmConfig::AssetTransactor::deposit_asset(&ed, &origin_ref, None).unwrap(); + } + + // overestimate delivery fee + let mut max_assets: Vec = Vec::new(); + for i in 0..MAX_ITEMS_IN_MULTIASSETS { + max_assets.push((GeneralIndex(i as u128), 100u128).into()); + } + let overestimated_xcm = + vec![WithdrawAsset(max_assets.into()); MAX_INSTRUCTIONS_TO_DECODE as usize].into(); + let overestimated_fees = PriceForDelivery::price_for_delivery((), &overestimated_xcm); + + // mint overestimated fee to origin + for fee in overestimated_fees.inner() { + XcmConfig::AssetTransactor::deposit_asset(&fee, &origin_ref, None).unwrap(); + } + + // expected worst case - direct withdraw + fees_mode = Some(FeesMode { jit_withdraw: true }); + } + (fees_mode, None) + } +} diff --git a/polkadot/runtime/common/src/xcm_sender.rs b/polkadot/runtime/common/src/xcm_sender.rs index 846206cd88b5..4d31c92cdd3a 100644 --- a/polkadot/runtime/common/src/xcm_sender.rs +++ b/polkadot/runtime/common/src/xcm_sender.rs @@ -31,25 +31,40 @@ use SendError::*; /// Simple value-bearing trait for determining/expressing the assets required to be paid for a /// messages to be delivered to a parachain. -pub trait PriceForParachainDelivery { +pub trait PriceForMessageDelivery { + /// Type used for charging different prices to different destinations + type Id; /// Return the assets required to deliver `message` to the given `para` destination. - fn price_for_parachain_delivery(para: ParaId, message: &Xcm<()>) -> MultiAssets; + fn price_for_delivery(id: Self::Id, message: &Xcm<()>) -> MultiAssets; } -impl PriceForParachainDelivery for () { - fn price_for_parachain_delivery(_: ParaId, _: &Xcm<()>) -> MultiAssets { +impl PriceForMessageDelivery for () { + type Id = (); + + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { + MultiAssets::new() + } +} + +pub struct NoPriceForMessageDelivery(PhantomData); +impl PriceForMessageDelivery for NoPriceForMessageDelivery { + type Id = Id; + + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { MultiAssets::new() } } -/// Implementation of [`PriceForParachainDelivery`] which returns a fixed price. +/// Implementation of [`PriceForMessageDelivery`] which returns a fixed price. pub struct ConstantPrice(sp_std::marker::PhantomData); -impl> PriceForParachainDelivery for ConstantPrice { - fn price_for_parachain_delivery(_: ParaId, _: &Xcm<()>) -> MultiAssets { +impl> PriceForMessageDelivery for ConstantPrice { + type Id = (); + + fn price_for_delivery(_: Self::Id, _: &Xcm<()>) -> MultiAssets { T::get() } } -/// Implementation of [`PriceForParachainDelivery`] which returns an exponentially increasing price. +/// Implementation of [`PriceForMessageDelivery`] which returns an exponentially increasing price. /// The formula for the fee is based on the sum of a base fee plus a message length fee, multiplied /// by a specified factor. In mathematical form: /// @@ -64,13 +79,15 @@ impl> PriceForParachainDelivery for ConstantPrice { /// - `M`: The fee to pay for each and every byte of the message after encoding it. /// - `F`: A fee factor multiplier. It can be understood as the exponent term in the formula. pub struct ExponentialPrice(sp_std::marker::PhantomData<(A, B, M, F)>); -impl, B: Get, M: Get, F: FeeTracker> PriceForParachainDelivery +impl, B: Get, M: Get, F: FeeTracker> PriceForMessageDelivery for ExponentialPrice { - fn price_for_parachain_delivery(para: ParaId, msg: &Xcm<()>) -> MultiAssets { + type Id = F::Id; + + fn price_for_delivery(id: Self::Id, msg: &Xcm<()>) -> MultiAssets { let msg_fee = (msg.encoded_size() as u128).saturating_mul(M::get()); let fee_sum = B::get().saturating_add(msg_fee); - let amount = F::get_fee_factor(para).saturating_mul_int(fee_sum); + let amount = F::get_fee_factor(id).saturating_mul_int(fee_sum); (A::get(), amount).into() } } @@ -78,8 +95,10 @@ impl, B: Get, M: Get, F: FeeTracker> PriceForParacha /// XCM sender for relay chain. It only sends downward message. pub struct ChildParachainRouter(PhantomData<(T, W, P)>); -impl - SendXcm for ChildParachainRouter +impl SendXcm + for ChildParachainRouter +where + P: PriceForMessageDelivery, { type Ticket = (HostConfiguration>, ParaId, Vec); @@ -99,7 +118,7 @@ impl>::config(); let para = id.into(); - let price = P::price_for_parachain_delivery(para, &xcm); + let price = P::price_for_delivery(para, &xcm); let blob = W::wrap_version(&d, xcm).map_err(|()| DestinationUnsupported)?.encode(); >::can_queue_downward_message(&config, ¶, &blob) .map_err(Into::::into)?; @@ -142,7 +161,7 @@ pub struct ToParachainDeliveryHelper< impl< XcmConfig: xcm_executor::Config, ExistentialDeposit: Get>, - PriceForDelivery: PriceForParachainDelivery, + PriceForDelivery: PriceForMessageDelivery, Parachain: Get, ToParachainHelper: EnsureForParachain, > pallet_xcm_benchmarks::EnsureDelivery @@ -175,10 +194,8 @@ impl< // overestimate delivery fee let overestimated_xcm = vec![ClearOrigin; 128].into(); - let overestimated_fees = PriceForDelivery::price_for_parachain_delivery( - Parachain::get(), - &overestimated_xcm, - ); + let overestimated_fees = + PriceForDelivery::price_for_delivery(Parachain::get(), &overestimated_xcm); // mint overestimated fee to origin for fee in overestimated_fees.inner() { @@ -202,7 +219,7 @@ pub trait EnsureForParachain { } #[cfg(feature = "runtime-benchmarks")] impl EnsureForParachain for () { - fn ensure(_para_id: ParaId) { + fn ensure(_: ParaId) { // doing nothing } } @@ -222,7 +239,17 @@ mod tests { struct TestFeeTracker; impl FeeTracker for TestFeeTracker { - fn get_fee_factor(_: ParaId) -> FixedU128 { + type Id = ParaId; + + fn get_fee_factor(_: Self::Id) -> FixedU128 { + FixedU128::from_rational(101, 100) + } + + fn increase_fee_factor(_: Self::Id, _: FixedU128) -> FixedU128 { + FixedU128::from_rational(101, 100) + } + + fn decrease_fee_factor(_: Self::Id) -> FixedU128 { FixedU128::from_rational(101, 100) } } @@ -240,21 +267,21 @@ mod tests { // message_length = 1 let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + m); assert_eq!( - TestExponentialPrice::price_for_parachain_delivery(id, &Xcm(vec![])), + TestExponentialPrice::price_for_delivery(id, &Xcm(vec![])), (FeeAssetId::get(), result).into() ); // message size = 2 let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + (2 * m)); assert_eq!( - TestExponentialPrice::price_for_parachain_delivery(id, &Xcm(vec![ClearOrigin])), + TestExponentialPrice::price_for_delivery(id, &Xcm(vec![ClearOrigin])), (FeeAssetId::get(), result).into() ); // message size = 4 let result: u128 = TestFeeTracker::get_fee_factor(id).saturating_mul_int(b + (4 * m)); assert_eq!( - TestExponentialPrice::price_for_parachain_delivery( + TestExponentialPrice::price_for_delivery( id, &Xcm(vec![SetAppendix(Xcm(vec![ClearOrigin]))]) ), diff --git a/polkadot/runtime/parachains/src/dmp.rs b/polkadot/runtime/parachains/src/dmp.rs index bfc3be456e6c..78994a9e34ba 100644 --- a/polkadot/runtime/parachains/src/dmp.rs +++ b/polkadot/runtime/parachains/src/dmp.rs @@ -336,32 +336,26 @@ impl Pallet { ) -> Vec>> { DownwardMessageQueues::::get(&recipient) } +} - /// Increases the delivery fee factor by a multiplicative factor and stores the resulting value. - /// - /// Returns the new delivery fee factor after the increase. - pub(crate) fn increase_fee_factor(para: ParaId, message_size_factor: FixedU128) -> FixedU128 { - >::mutate(para, |f| { +impl FeeTracker for Pallet { + type Id = ParaId; + + fn get_fee_factor(id: Self::Id) -> FixedU128 { + DeliveryFeeFactor::::get(id) + } + + fn increase_fee_factor(id: Self::Id, message_size_factor: FixedU128) -> FixedU128 { + >::mutate(id, |f| { *f = f.saturating_mul(EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor)); *f }) } - /// Decreases the delivery fee factor by a multiplicative factor and stores the resulting value. - /// - /// Does not reduce the fee factor below the initial value, which is currently set as 1. - /// - /// Returns the new delivery fee factor after the decrease. - pub(crate) fn decrease_fee_factor(para: ParaId) -> FixedU128 { - >::mutate(para, |f| { + fn decrease_fee_factor(id: Self::Id) -> FixedU128 { + >::mutate(id, |f| { *f = InitialFactor::get().max(*f / EXPONENTIAL_FEE_BASE); *f }) } } - -impl FeeTracker for Pallet { - fn get_fee_factor(para: ParaId) -> FixedU128 { - DeliveryFeeFactor::::get(para) - } -} diff --git a/polkadot/runtime/parachains/src/lib.rs b/polkadot/runtime/parachains/src/lib.rs index 7477a06d16a3..bc35ade4c6eb 100644 --- a/polkadot/runtime/parachains/src/lib.rs +++ b/polkadot/runtime/parachains/src/lib.rs @@ -59,9 +59,21 @@ use sp_runtime::{DispatchResult, FixedU128}; /// Trait for tracking message delivery fees on a transport protocol. pub trait FeeTracker { + /// Type used for assigning different fee factors to different destinations + type Id; /// Returns the evolving exponential fee factor which will be used to calculate the delivery /// fees. - fn get_fee_factor(para: ParaId) -> FixedU128; + fn get_fee_factor(id: Self::Id) -> FixedU128; + /// Increases the delivery fee factor by a factor based on message size and records the result. + /// + /// Returns the new delivery fee factor after the increase. + fn increase_fee_factor(id: Self::Id, message_size_factor: FixedU128) -> FixedU128; + /// Decreases the delivery fee factor by a constant factor and records the result. + /// + /// Does not reduce the fee factor below the initial value, which is currently set as 1. + /// + /// Returns the new delivery fee factor after the decrease. + fn decrease_fee_factor(id: Self::Id) -> FixedU128; } /// Schedule a para to be initialized at the start of the next session with the given genesis data. diff --git a/polkadot/runtime/rococo/src/lib.rs b/polkadot/runtime/rococo/src/lib.rs index 4ea4532b1199..a74fdc878655 100644 --- a/polkadot/runtime/rococo/src/lib.rs +++ b/polkadot/runtime/rococo/src/lib.rs @@ -2063,6 +2063,7 @@ sp_api::impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/polkadot/runtime/westend/src/lib.rs b/polkadot/runtime/westend/src/lib.rs index 98eb22aba946..94c3e0df9f25 100644 --- a/polkadot/runtime/westend/src/lib.rs +++ b/polkadot/runtime/westend/src/lib.rs @@ -2230,6 +2230,7 @@ sp_api::impl_runtime_apis! { } impl pallet_xcm_benchmarks::generic::Config for Runtime { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { diff --git a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs index 87e63fbe3107..9939f16aa29f 100644 --- a/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs +++ b/polkadot/runtime/westend/src/weights/xcm/pallet_xcm_benchmarks_fungible.rs @@ -17,7 +17,7 @@ //! Autogenerated weights for `pallet_xcm_benchmarks::fungible` //! //! THIS FILE WAS AUTO-GENERATED USING THE SUBSTRATE BENCHMARK CLI VERSION 4.0.0-dev -//! DATE: 2023-09-28, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` +//! DATE: 2023-10-03, STEPS: `50`, REPEAT: `20`, LOW RANGE: `[]`, HIGH RANGE: `[]` //! WORST CASE MAP SIZE: `1000000` //! HOSTNAME: `runner-nbnwcyh-project-674-concurrent-0`, CPU: `Intel(R) Xeon(R) CPU @ 2.60GHz` //! WASM-EXECUTION: Compiled, CHAIN: Some("westend-dev"), DB CACHE: 1024 @@ -55,8 +55,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `3593` - // Minimum execution time: 24_642_000 picoseconds. - Weight::from_parts(24_973_000, 3593) + // Minimum execution time: 24_815_000 picoseconds. + Weight::from_parts(25_098_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -66,8 +66,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `101` // Estimated: `6196` - // Minimum execution time: 50_882_000 picoseconds. - Weight::from_parts(51_516_000, 6196) + // Minimum execution time: 51_268_000 picoseconds. + Weight::from_parts(51_857_000, 6196) .saturating_add(T::DbWeight::get().reads(2)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -85,8 +85,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `210` // Estimated: `6196` - // Minimum execution time: 73_923_000 picoseconds. - Weight::from_parts(75_454_000, 6196) + // Minimum execution time: 74_113_000 picoseconds. + Weight::from_parts(74_721_000, 6196) .saturating_add(T::DbWeight::get().reads(6)) .saturating_add(T::DbWeight::get().writes(4)) } @@ -111,8 +111,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3574` - // Minimum execution time: 29_035_000 picoseconds. - Weight::from_parts(30_086_000, 3574) + // Minimum execution time: 28_919_000 picoseconds. + Weight::from_parts(29_703_000, 3574) .saturating_add(T::DbWeight::get().reads(4)) .saturating_add(T::DbWeight::get().writes(2)) } @@ -122,8 +122,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `103` // Estimated: `3593` - // Minimum execution time: 22_094_000 picoseconds. - Weight::from_parts(22_560_000, 3593) + // Minimum execution time: 21_685_000 picoseconds. + Weight::from_parts(22_528_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -133,8 +133,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `0` // Estimated: `3593` - // Minimum execution time: 24_771_000 picoseconds. - Weight::from_parts(25_280_000, 3593) + // Minimum execution time: 25_192_000 picoseconds. + Weight::from_parts(25_445_000, 3593) .saturating_add(T::DbWeight::get().reads(1)) .saturating_add(T::DbWeight::get().writes(1)) } @@ -152,8 +152,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3593` - // Minimum execution time: 49_777_000 picoseconds. - Weight::from_parts(50_833_000, 3593) + // Minimum execution time: 49_349_000 picoseconds. + Weight::from_parts(50_476_000, 3593) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } @@ -171,8 +171,8 @@ impl WeightInfo { // Proof Size summary in bytes: // Measured: `109` // Estimated: `3593` - // Minimum execution time: 51_425_000 picoseconds. - Weight::from_parts(52_213_000, 3593) + // Minimum execution time: 51_386_000 picoseconds. + Weight::from_parts(52_141_000, 3593) .saturating_add(T::DbWeight::get().reads(5)) .saturating_add(T::DbWeight::get().writes(3)) } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs index 02b5f0c6b05a..d32eb8d4a52f 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/fungible/benchmarking.rs @@ -15,7 +15,7 @@ // along with Polkadot. If not, see . use super::*; -use crate::{account_and_location, new_executor, AssetTransactorOf, XcmCallOf}; +use crate::{account_and_location, new_executor, AssetTransactorOf, EnsureDelivery, XcmCallOf}; use frame_benchmarking::{benchmarks_instance_pallet, BenchmarkError, BenchmarkResult}; use frame_support::{ pallet_prelude::Get, @@ -24,7 +24,7 @@ use frame_support::{ }; use sp_runtime::traits::{Bounded, Zero}; use sp_std::{prelude::*, vec}; -use xcm::latest::prelude::*; +use xcm::latest::{prelude::*, MAX_ITEMS_IN_MULTIASSETS}; use xcm_executor::traits::{ConvertLocation, FeeReason, TransactAsset}; benchmarks_instance_pallet! { @@ -88,7 +88,6 @@ benchmarks_instance_pallet! { let dest_location = T::valid_destination()?; let dest_account = T::AccountIdConverter::convert_location(&dest_location).unwrap(); - use crate::EnsureDelivery; let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( &sender_location, &dest_location, @@ -142,16 +141,33 @@ benchmarks_instance_pallet! { } initiate_reserve_withdraw { + let (sender_account, sender_location) = account_and_location::(1); let holding = T::worst_case_holding(1); - let assets_filter = MultiAssetFilter::Definite(holding.clone()); + let assets_filter = MultiAssetFilter::Definite(holding.clone().into_inner().into_iter().take(MAX_ITEMS_IN_MULTIASSETS).collect::>().into()); let reserve = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; - let mut executor = new_executor::(Default::default()); + + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &reserve, + FeeReason::InitiateReserveWithdraw, + ); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + + let mut executor = new_executor::(sender_location); executor.set_holding(holding.into()); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let instruction = Instruction::InitiateReserveWithdraw { assets: assets_filter, reserve, xcm: Xcm(vec![]) }; let xcm = Xcm(vec![instruction]); }: { executor.bench_process(xcm)?; } verify { + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // The execute completing successfully is as good as we can check. // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs index 4583ecdba89f..c6b76e0ffade 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/benchmarking.rs @@ -15,27 +15,45 @@ // along with Polkadot. If not, see . use super::*; -use crate::{new_executor, XcmCallOf}; +use crate::{account_and_location, new_executor, EnsureDelivery, XcmCallOf}; use codec::Encode; use frame_benchmarking::{benchmarks, BenchmarkError}; -use frame_support::dispatch::GetDispatchInfo; +use frame_support::{dispatch::GetDispatchInfo, traits::fungible::Inspect}; use sp_std::vec; use xcm::{ latest::{prelude::*, MaxDispatchErrorLen, MaybeErrorCode, Weight}, DoubleEncoded, }; -use xcm_executor::{ExecutorError, FeesMode}; +use xcm_executor::{ + traits::{ConvertLocation, FeeReason}, + ExecutorError, FeesMode, +}; benchmarks! { report_holding { + let (sender_account, sender_location) = account_and_location::(1); let holding = T::worst_case_holding(0); + let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; - let mut executor = new_executor::(Default::default()); + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + + let mut executor = new_executor::(sender_location); executor.set_holding(holding.clone().into()); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let instruction = Instruction::>::ReportHolding { response_info: QueryResponseInfo { - destination: T::valid_destination()?, + destination, query_id: Default::default(), max_weight: Weight::MAX, }, @@ -44,11 +62,11 @@ benchmarks! { }; let xcm = Xcm(vec![instruction]); - } : { executor.bench_process(xcm)?; } verify { - // The completion of execution above is enough to validate this is completed. + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); } // This benchmark does not use any additional orders or instructions. This should be managed @@ -182,11 +200,26 @@ benchmarks! { } report_error { - let mut executor = new_executor::(Default::default()); - executor.set_error(Some((0u32, XcmError::Unimplemented))); + let (sender_account, sender_location) = account_and_location::(1); let query_id = Default::default(); - let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; let max_weight = Default::default(); + let destination = T::valid_destination().map_err(|_| BenchmarkError::Skip)?; + + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + + let mut executor = new_executor::(sender_location); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } + executor.set_error(Some((0u32, XcmError::Unimplemented))); let instruction = Instruction::ReportError(QueryResponseInfo { query_id, destination, max_weight @@ -195,7 +228,8 @@ benchmarks! { }: { executor.bench_process(xcm)?; } verify { - // the execution succeeding is all we need to verify this xcm was successful + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); } claim_asset { @@ -360,10 +394,24 @@ benchmarks! { } query_pallet { + let (sender_account, sender_location) = account_and_location::(1); 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 (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::QueryPallet, + ); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + let mut executor = new_executor::(sender_location); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let instruction = Instruction::QueryPallet { module_name: b"frame_system".to_vec(), @@ -373,6 +421,8 @@ benchmarks! { }: { executor.bench_process(xcm)?; } verify { + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -394,11 +444,25 @@ benchmarks! { } report_transact_status { + let (sender_account, sender_location) = account_and_location::(1); 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 (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &sender_location, + &destination, + FeeReason::Report, + ); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + + let mut executor = new_executor::(sender_location); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } executor.set_transact_status(b"MyError".to_vec().into()); let instruction = Instruction::ReportTransactStatus(QueryResponseInfo { @@ -410,6 +474,8 @@ benchmarks! { }: { executor.bench_process(xcm)?; } verify { + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -491,14 +557,30 @@ benchmarks! { let inner_xcm = Xcm(vec![ClearOrigin; x as usize]); // Get `origin`, `network` and `destination` from configured runtime. let (origin, network, destination) = T::export_message_origin_and_destination()?; + + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &origin, + &destination.into(), + FeeReason::Export(network), + ); + let sender_account = T::AccountIdConverter::convert_location(&origin).unwrap(); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + let mut executor = new_executor::(origin); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let xcm = Xcm(vec![ExportMessage { network, destination, xcm: inner_xcm, }]); }: { executor.bench_process(xcm)?; } verify { - // The execute completing successfully is as good as we can check. + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -517,14 +599,30 @@ benchmarks! { lock_asset { let (unlocker, owner, asset) = T::unlockable_asset()?; + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &owner, + &unlocker, + FeeReason::LockAsset, + ); + let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap(); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + let mut executor = new_executor::(owner); executor.set_holding(asset.clone().into()); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let instruction = Instruction::LockAsset { asset, unlocker }; let xcm = Xcm(vec![instruction]); }: { executor.bench_process(xcm)?; } verify { + // Check delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } @@ -595,13 +693,29 @@ benchmarks! { .enact() .map_err(|_| BenchmarkError::Skip)?; + let (expected_fees_mode, expected_assets_in_holding) = T::DeliveryHelper::ensure_successful_delivery( + &owner, + &locker, + FeeReason::RequestUnlock, + ); + let sender_account = T::AccountIdConverter::convert_location(&owner).unwrap(); + let sender_account_balance_before = T::TransactAsset::balance(&sender_account); + // ... then request for an unlock with the RequestUnlock instruction. let mut executor = new_executor::(owner); + if let Some(expected_fees_mode) = expected_fees_mode { + executor.set_fees_mode(expected_fees_mode); + } + if let Some(expected_assets_in_holding) = expected_assets_in_holding { + executor.set_holding(expected_assets_in_holding.into()); + } let instruction = Instruction::RequestUnlock { asset, locker }; let xcm = Xcm(vec![instruction]); }: { executor.bench_process(xcm)?; } verify { + // Check we charged the delivery fees + assert!(T::TransactAsset::balance(&sender_account) <= sender_account_balance_before); // TODO: Potentially add new trait to XcmSender to detect a queued outgoing message. #4426 } diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs index 7099542dd415..4cb95ed5ac6c 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mock.rs @@ -23,7 +23,7 @@ use frame_support::{ traits::{Everything, OriginTrait}, weights::Weight, }; -use sp_core::H256; +use sp_core::{ConstU32, H256}; use sp_runtime::traits::{BlakeTwo256, IdentityLookup, TrailingZeroInput}; use xcm_builder::{ test_utils::{ @@ -40,6 +40,7 @@ frame_support::construct_runtime!( pub enum Test { System: frame_system::{Pallet, Call, Config, Storage, Event}, + Balances: pallet_balances::{Pallet, Call, Storage, Config, Event}, XcmGenericBenchmarks: generic::{Pallet}, } ); @@ -137,6 +138,26 @@ impl xcm_executor::Config for XcmConfig { type Aliasers = Aliasers; } +parameter_types! { + pub const ExistentialDeposit: u64 = 7; +} + +impl pallet_balances::Config for Test { + type MaxLocks = (); + type MaxReserves = (); + type ReserveIdentifier = [u8; 8]; + type Balance = u64; + type DustRemoval = (); + type RuntimeEvent = RuntimeEvent; + type ExistentialDeposit = ExistentialDeposit; + type AccountStore = System; + type WeightInfo = (); + type RuntimeHoldReason = RuntimeHoldReason; + type FreezeIdentifier = (); + type MaxHolds = ConstU32<0>; + type MaxFreezes = ConstU32<0>; +} + impl crate::Config for Test { type XcmConfig = XcmConfig; type AccountIdConverter = AccountIdConverter; @@ -156,6 +177,7 @@ impl crate::Config for Test { } impl generic::Config for Test { + type TransactAsset = Balances; type RuntimeCall = RuntimeCall; fn worst_case_response() -> (u64, Response) { @@ -188,7 +210,7 @@ impl generic::Config for Test { fn unlockable_asset() -> Result<(MultiLocation, MultiLocation, MultiAsset), BenchmarkError> { let assets: MultiAsset = (Concrete(Here.into()), 100).into(); - Ok((Default::default(), Default::default(), assets)) + Ok((Default::default(), account_id_junction::(1).into(), assets)) } fn export_message_origin_and_destination( diff --git a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs index f207c238a39f..cbdfa8d0112c 100644 --- a/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs +++ b/polkadot/xcm/pallet-xcm-benchmarks/src/generic/mod.rs @@ -38,6 +38,11 @@ pub mod pallet { + From> + Encode; + /// The type of `fungible` that is being used under the hood. + /// + /// This is useful for testing and checking. + type TransactAsset: frame_support::traits::fungible::Mutate; + /// The response which causes the most runtime weight. fn worst_case_response() -> (u64, Response); diff --git a/polkadot/xcm/src/v3/mod.rs b/polkadot/xcm/src/v3/mod.rs index 6f1e8e783113..a3490108e8b4 100644 --- a/polkadot/xcm/src/v3/mod.rs +++ b/polkadot/xcm/src/v3/mod.rs @@ -45,7 +45,7 @@ pub use junction::{BodyId, BodyPart, Junction, NetworkId}; pub use junctions::Junctions; pub use multiasset::{ AssetId, AssetInstance, Fungibility, MultiAsset, MultiAssetFilter, MultiAssets, - WildFungibility, WildMultiAsset, + WildFungibility, WildMultiAsset, MAX_ITEMS_IN_MULTIASSETS, }; pub use multilocation::{ Ancestor, AncestorThen, InteriorMultiLocation, MultiLocation, Parent, ParentThen, @@ -70,7 +70,7 @@ pub type QueryId = u64; #[scale_info(bounds(), skip_type_params(Call))] pub struct Xcm(pub Vec>); -const MAX_INSTRUCTIONS_TO_DECODE: u8 = 100; +pub const MAX_INSTRUCTIONS_TO_DECODE: u8 = 100; environmental::environmental!(instructions_count: u8); diff --git a/substrate/frame/support/procedural/src/pallet/expand/warnings.rs b/substrate/frame/support/procedural/src/pallet/expand/warnings.rs index ae5890878a2f..6ce2097c2684 100644 --- a/substrate/frame/support/procedural/src/pallet/expand/warnings.rs +++ b/substrate/frame/support/procedural/src/pallet/expand/warnings.rs @@ -34,7 +34,7 @@ pub(crate) fn weight_witness_warning( return } let CallWeightDef::Immediate(w) = &method.weight else { - return; + return }; let partial_warning = Warning::new_deprecated("UncheckedWeightWitness") @@ -67,7 +67,7 @@ pub(crate) fn weight_constant_warning( return } let syn::Expr::Lit(lit) = weight else { - return; + return }; let warning = Warning::new_deprecated("ConstantWeight")