Introduce XcmFeesToAccount fee manager (#1234)

Combination of paritytech/polkadot#7005, its addon PR
paritytech/polkadot#7585 and its companion paritytech/cumulus#2433.

This PR introduces a new XcmFeesToAccount struct which implements the
`FeeManager` trait, and assigns this struct as the `FeeManager` in the
XCM config for all runtimes.

The struct simply deposits all fees handled by the XCM executor to a
specified account. In all runtimes, the specified account is configured
as the treasury account.

XCM __delivery__ fees are now being introduced (unless the root origin
is sending a message to a system parachain on behalf of the originating
chain).

# Note for reviewers

Most file changes are tests that had to be modified to account for the
new fees.
Main changes are in:
- cumulus/pallets/xcmp-queue/src/lib.rs <- To make it track the delivery
fees exponential factor
- polkadot/xcm/xcm-builder/src/fee_handling.rs <- Added. Has the
FeeManager implementation
- All runtime xcm_config files <- To add the FeeManager to the XCM
configuration

# Important note

After this change, instructions that create and send a new XCM (Query*,
Report*, ExportMessage, InitiateReserveWithdraw, InitiateTeleport,
DepositReserveAsset, TransferReserveAsset, LockAsset and RequestUnlock)
will require the corresponding origin account in the origin register to
pay for transport delivery fees, and the onward message will fail to be
sent if the origin account does not have the required amount. This
delivery fee is on top of what we already collect as tx fees in
pallet-xcm and XCM BuyExecution fees!

Wallet UIs that want to expose the new delivery fee can do so using the
formula:

```
delivery_fee_factor * (base_fee + encoded_msg_len * per_byte_fee)
```

where the delivery fee factor can be obtained from the corresponding
pallet based on which transport you are using (UMP, HRMP or bridges),
the base fee is a constant, the encoded message length from the message
itself and the per byte fee is the same as the configured per byte fee
for txs (i.e. `TransactionByteFee`).

---------

Co-authored-by: Branislav Kontur <bkontur@gmail.com>
Co-authored-by: joe petrowski <25483142+joepetrowski@users.noreply.github.com>
Co-authored-by: Giles Cope <gilescope@gmail.com>
Co-authored-by: command-bot <>
Co-authored-by: Francisco Aguirre <franciscoaguirreperez@gmail.com>
Co-authored-by: Liam Aharon <liam.aharon@hotmail.com>
Co-authored-by: Kian Paimani <5588131+kianenigma@users.noreply.github.com>
This commit is contained in:
Keith Yeung
2023-10-18 23:22:25 +08:00
committed by GitHub
parent 1cf7d3aafa
commit 3dece311be
99 changed files with 2229 additions and 468 deletions
@@ -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",
]
+119 -10
View File
@@ -29,10 +29,10 @@
use codec::{Decode, Encode, MaxEncodedLen};
use cumulus_primitives_core::{
relay_chain, AbridgedHostConfiguration, ChannelStatus, CollationInfo, DmpMessageHandler,
GetChannelInfo, InboundDownwardMessage, InboundHrmpMessage, MessageSendError,
OutboundHrmpMessage, ParaId, PersistedValidationData, UpwardMessage, UpwardMessageSender,
XcmpMessageHandler, XcmpMessageSource,
relay_chain, AbridgedHostConfiguration, ChannelInfo, ChannelStatus, CollationInfo,
DmpMessageHandler, GetChannelInfo, InboundDownwardMessage, InboundHrmpMessage,
MessageSendError, OutboundHrmpMessage, ParaId, PersistedValidationData, UpwardMessage,
UpwardMessageSender, XcmpMessageHandler, XcmpMessageSource,
};
use cumulus_primitives_parachain_inherent::{MessageQueueChain, ParachainInherentData};
use frame_support::{
@@ -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,10 @@ pub mod pallet {
#[pallet::hooks]
impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {
/// 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`]).
/// Also does the sending for HRMP messages it takes from `OutboundXcmpMessageSource`.
fn on_finalize(_: BlockNumberFor<T>) {
<DidSetValidationCode<T>>::kill();
<UpgradeRestrictionSignal<T>>::kill();
@@ -326,6 +345,17 @@ pub mod pallet {
UpwardMessages::<T>::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 +751,7 @@ pub mod pallet {
StorageValue<_, Vec<Ancestor<T::Hash>>, 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<T: Config> =
@@ -860,6 +890,17 @@ pub mod pallet {
pub(super) type PendingUpwardMessages<T: Config> =
StorageValue<_, Vec<UpwardMessage>, 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<T: Config> =
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 +1017,31 @@ impl<T: Config> Pallet<T> {
}
}
impl<T: Config> FeeTracker for Pallet<T> {
type Id = ();
fn get_fee_factor(_: Self::Id) -> FixedU128 {
UpwardDeliveryFeeFactor::<T>::get()
}
fn increase_fee_factor(_: Self::Id, message_size_factor: FixedU128) -> FixedU128 {
<UpwardDeliveryFeeFactor<T>>::mutate(|f| {
*f = f.saturating_mul(
ump_constants::EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor),
);
*f
})
}
fn decrease_fee_factor(_: Self::Id) -> FixedU128 {
<UpwardDeliveryFeeFactor<T>>::mutate(|f| {
*f =
UpwardInitialDeliveryFeeFactor::get().max(*f / ump_constants::EXPONENTIAL_FEE_BASE);
*f
})
}
}
impl<T: Config> GetChannelInfo for Pallet<T> {
fn get_channel_status(id: ParaId) -> ChannelStatus {
// Note, that we are using `relevant_messaging_state` which may be from the previous
@@ -1019,10 +1085,17 @@ impl<T: Config> GetChannelInfo for Pallet<T> {
ChannelStatus::Ready(max_size_now as usize, max_size_ever as usize)
}
fn get_channel_max(id: ParaId) -> Option<usize> {
fn get_channel_info(id: ParaId) -> Option<ChannelInfo> {
let channels = Self::relevant_messaging_state()?.egress_channels;
let index = channels.binary_search_by_key(&id, |item| item.0).ok()?;
Some(channels[index].1.max_message_size as usize)
let info = ChannelInfo {
max_capacity: channels[index].1.max_capacity,
max_total_size: channels[index].1.max_total_size,
max_message_size: channels[index].1.max_message_size,
msg_count: channels[index].1.msg_count,
total_size: channels[index].1.total_size,
};
Some(info)
}
}
@@ -1427,6 +1500,23 @@ impl<T: Config> Pallet<T> {
})
}
/// Open HRMP channel for using it in benchmarks or tests.
///
/// The caller assumes that the pallet will accept regular outbound message to the sibling
/// `target_parachain` after this call. No other assumptions are made.
#[cfg(any(feature = "runtime-benchmarks", feature = "std"))]
pub fn open_custom_outbound_hrmp_channel_for_benchmarks_or_tests(
target_parachain: ParaId,
channel: cumulus_primitives_core::AbridgedHrmpChannel,
) {
RelevantMessagingState::<T>::put(MessagingStateSnapshot {
dmq_mqc_head: Default::default(),
relay_dispatch_queue_remaining_capacity: Default::default(),
ingress_channels: Default::default(),
egress_channels: vec![(target_parachain, channel)],
})
}
/// Prepare/insert relevant data for `schedule_code_upgrade` for benchmarks.
#[cfg(feature = "runtime-benchmarks")]
pub fn initialize_for_set_code_benchmark(max_code_size: u32) {
@@ -1468,7 +1558,13 @@ impl<T: Config> frame_system::SetCode<T> for ParachainSetCode<T> {
}
impl<T: Config> Pallet<T> {
/// 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 +1578,22 @@ impl<T: Config> Pallet<T> {
//
// 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.
<PendingUpwardMessages<T>>::append(message.clone());
let pending_messages = PendingUpwardMessages::<T>::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
@@ -1495,8 +1604,8 @@ impl<T: Config> Pallet<T> {
// returned back to the sender.
//
// Thus fall through here.
<PendingUpwardMessages<T>>::append(message.clone());
};
<PendingUpwardMessages<T>>::append(message.clone());
// The relay ump does not use using_encoded
// We apply the same this to use the same hash
@@ -1496,3 +1496,53 @@ fn deposits_relay_parent_storage_root() {
},
);
}
#[test]
fn ump_fee_factor_increases_and_decreases() {
BlockTests::new()
.with_relay_sproof_builder(|_, _, sproof| {
sproof.host_config.max_upward_queue_size = 100;
sproof.host_config.max_upward_message_num_per_candidate = 1;
})
.add_with_post_test(
1,
|| {
// Fee factor increases in `send_upward_message`
ParachainSystem::send_upward_message(b"Test".to_vec()).unwrap();
assert_eq!(UpwardDeliveryFeeFactor::<Test>::get(), FixedU128::from_u32(1));
ParachainSystem::send_upward_message(
b"This message will be enough to increase the fee factor".to_vec(),
)
.unwrap();
assert_eq!(
UpwardDeliveryFeeFactor::<Test>::get(),
FixedU128::from_rational(105, 100)
);
},
|| {
// Factor decreases in `on_finalize`, but only if we are below the threshold
let messages = UpwardMessages::<Test>::get();
assert_eq!(messages, vec![b"Test".to_vec()]);
assert_eq!(
UpwardDeliveryFeeFactor::<Test>::get(),
FixedU128::from_rational(105, 100)
);
},
)
.add_with_post_test(
2,
|| {
// We do nothing here
},
|| {
let messages = UpwardMessages::<Test>::get();
assert_eq!(
messages,
vec![b"This message will be enough to increase the fee factor".to_vec(),]
);
// Now the delivery fee factor is decreased, since we are below the threshold
assert_eq!(UpwardDeliveryFeeFactor::<Test>::get(), FixedU128::from_u32(1));
},
);
}
+9 -3
View File
@@ -14,13 +14,15 @@ scale-info = { version = "2.9.0", default-features = false, features = ["derive"
frame-support = { path = "../../../substrate/frame/support", default-features = false}
frame-system = { path = "../../../substrate/frame/system", default-features = false}
sp-io = { path = "../../../substrate/primitives/io", default-features = false}
sp-core = { path = "../../../substrate/primitives/core", default-features = false }
sp-runtime = { path = "../../../substrate/primitives/runtime", default-features = false}
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}
xcm-executor = { package = "staging-xcm-executor", path = "../../../polkadot/xcm/xcm-executor", 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 }
# Cumulus
cumulus-primitives-core = { path = "../../primitives/core", default-features = false }
@@ -54,7 +56,9 @@ std = [
"frame-system/std",
"log/std",
"polkadot-runtime-common/std",
"polkadot-runtime-parachains/std",
"scale-info/std",
"sp-core/std",
"sp-io/std",
"sp-runtime/std",
"sp-std/std",
@@ -69,6 +73,7 @@ runtime-benchmarks = [
"frame-system/runtime-benchmarks",
"pallet-balances/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
"polkadot-runtime-parachains/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
@@ -79,6 +84,7 @@ try-runtime = [
"frame-system/try-runtime",
"pallet-balances/try-runtime",
"polkadot-runtime-common/try-runtime",
"polkadot-runtime-parachains/try-runtime",
"sp-runtime/try-runtime",
]
bridging = [ "bp-xcm-bridge-hub-router" ]
+158 -43
View File
@@ -22,6 +22,16 @@
//! Also provides an implementation of `SendXcm` which can be placed in a router tuple for relaying
//! XCM over XCMP if the destination is `Parent/Parachain`. It requires an implementation of
//! `XcmExecutor` for dispatching incoming XCM messages.
//!
//! To prevent out of memory errors on the `OutboundXcmpMessages` queue, an exponential fee factor
//! (`DeliveryFeeFactor`) is set, much like the one used in DMP.
//! The fee factor increases whenever the total size of messages in a particular channel passes a
//! threshold. This threshold is defined as a percentage of the maximum total size the channel can
//! have. More concretely, the threshold is `max_total_size` / `THRESHOLD_FACTOR`, where:
//! - `max_total_size` is the maximum size, in bytes, of the channel, not number of messages.
//! It is defined in the channel configuration.
//! - `THRESHOLD_FACTOR` just declares which percentage of the max size is the actual threshold.
//! If it's 2, then the threshold is half of the max size, if it's 4, it's a quarter, and so on.
#![cfg_attr(not(feature = "std"), no_std)]
@@ -49,13 +59,15 @@ 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},
ChaChaRng,
};
use scale_info::TypeInfo;
use sp_runtime::RuntimeDebug;
use sp_core::MAX_POSSIBLE_ALLOCATION;
use sp_runtime::{FixedU128, RuntimeDebug, Saturating};
use sp_std::{convert::TryFrom, prelude::*};
use xcm::{latest::prelude::*, VersionedXcm, WrapVersion, MAX_XCM_DECODE_DEPTH};
use xcm_executor::traits::ConvertOrigin;
@@ -68,6 +80,19 @@ pub type OverweightIndex = u64;
const LOG_TARGET: &str = "xcmp_queue";
const DEFAULT_POV_SIZE: u64 = 64 * 1024; // 64 KB
/// Constants related to delivery fee calculation
pub mod delivery_fee_constants {
use super::FixedU128;
/// Fees will start increasing 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 contribution of each KB to a fee factor increase
pub const MESSAGE_SIZE_FEE_BASE: FixedU128 = FixedU128::from_rational(1, 1000); // 0.001
}
// Maximum amount of messages to process per block. This is a temporary measure until we properly
// account for proof size weights.
const MAX_MESSAGES_PER_BLOCK: u8 = 10;
@@ -77,7 +102,7 @@ const MAX_OVERWEIGHT_MESSAGES: u32 = 1000;
#[frame_support::pallet]
pub mod pallet {
use super::*;
use frame_support::pallet_prelude::*;
use frame_support::{pallet_prelude::*, Twox64Concat};
use frame_system::pallet_prelude::*;
#[pallet::pallet]
@@ -109,7 +134,7 @@ pub mod pallet {
type ControllerOriginConverter: ConvertOrigin<Self::RuntimeOrigin>;
/// The price for delivering an XCM to a sibling parachain destination.
type PriceForSiblingDelivery: PriceForParachainDelivery;
type PriceForSiblingDelivery: PriceForMessageDelivery<Id = ParaId>;
/// The weight information of this pallet.
type WeightInfo: WeightInfo;
@@ -374,6 +399,17 @@ pub mod pallet {
/// Whether or not the XCMP queue is suspended from executing incoming XCMs or not.
#[pallet::storage]
pub(super) type QueueSuspended<T: Config> = StorageValue<_, bool, ValueQuery>;
/// Initialization value for the DeliveryFee factor.
#[pallet::type_value]
pub fn InitialFactor() -> FixedU128 {
FixedU128::from_u32(1)
}
/// The factor to multiply the base delivery fee by.
#[pallet::storage]
pub(super) type DeliveryFeeFactor<T: Config> =
StorageMap<_, Twox64Concat, ParaId, FixedU128, ValueQuery, InitialFactor>;
}
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, TypeInfo)]
@@ -403,7 +439,7 @@ pub struct InboundChannelDetails {
}
/// Struct containing detailed information about the outbound channel.
#[derive(Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
#[derive(Debug, Clone, Eq, PartialEq, Encode, Decode, TypeInfo)]
pub struct OutboundChannelDetails {
/// The `ParaId` of the parachain that this channel is connected with.
recipient: ParaId,
@@ -503,56 +539,90 @@ impl<T: Config> Pallet<T> {
/// length prefixed and can thus decode each fragment from the aggregate stream. With this,
/// we can concatenate them into a single aggregate blob without needing to be concerned
/// about encoding fragment boundaries.
///
/// If successful, returns the number of pages in the outbound queue after enqueuing the new
/// fragment.
fn send_fragment<Fragment: Encode>(
recipient: ParaId,
format: XcmpMessageFormat,
fragment: Fragment,
) -> Result<u32, MessageSendError> {
let data = fragment.encode();
let encoded_fragment = fragment.encode();
// Optimization note: `max_message_size` could potentially be stored in
// `OutboundXcmpMessages` once known; that way it's only accessed when a new page is needed.
let max_message_size =
T::ChannelInfo::get_channel_max(recipient).ok_or(MessageSendError::NoChannel)?;
if data.len() > max_message_size {
let channel_info =
T::ChannelInfo::get_channel_info(recipient).ok_or(MessageSendError::NoChannel)?;
let max_message_size = channel_info.max_message_size as usize;
// Max message size refers to aggregates, or pages. Not to individual fragments.
if encoded_fragment.len() > max_message_size {
return Err(MessageSendError::TooBig)
}
let mut s = <OutboundXcmpStatus<T>>::get();
let details = if let Some(details) = s.iter_mut().find(|item| item.recipient == recipient) {
let mut all_channels = <OutboundXcmpStatus<T>>::get();
let channel_details = if let Some(details) =
all_channels.iter_mut().find(|channel| channel.recipient == recipient)
{
details
} else {
s.push(OutboundChannelDetails::new(recipient));
s.last_mut().expect("can't be empty; a new element was just pushed; qed")
all_channels.push(OutboundChannelDetails::new(recipient));
all_channels
.last_mut()
.expect("can't be empty; a new element was just pushed; qed")
};
let have_active = details.last_index > details.first_index;
let appended = have_active &&
<OutboundXcmpMessages<T>>::mutate(recipient, details.last_index - 1, |s| {
if XcmpMessageFormat::decode_with_depth_limit(MAX_XCM_DECODE_DEPTH, &mut &s[..]) !=
Ok(format)
{
return false
}
if s.len() + data.len() > max_message_size {
return false
}
s.extend_from_slice(&data[..]);
true
});
if appended {
Ok((details.last_index - details.first_index - 1) as u32)
let have_active = channel_details.last_index > channel_details.first_index;
// Try to append fragment to the last page, if there is enough space.
// We return the size of the last page inside of the option, to not calculate it again.
let appended_to_last_page = have_active
.then(|| {
<OutboundXcmpMessages<T>>::mutate(
recipient,
channel_details.last_index - 1,
|page| {
if XcmpMessageFormat::decode_with_depth_limit(
MAX_XCM_DECODE_DEPTH,
&mut &page[..],
) != Ok(format)
{
return None
}
if page.len() + encoded_fragment.len() > max_message_size {
return None
}
page.extend_from_slice(&encoded_fragment[..]);
Some(page.len())
},
)
})
.flatten();
let (number_of_pages, last_page_size) = if let Some(size) = appended_to_last_page {
let number_of_pages = (channel_details.last_index - channel_details.first_index) as u32;
(number_of_pages, size)
} else {
// Need to add a new page.
let page_index = details.last_index;
details.last_index += 1;
let page_index = channel_details.last_index;
channel_details.last_index += 1;
let mut new_page = format.encode();
new_page.extend_from_slice(&data[..]);
new_page.extend_from_slice(&encoded_fragment[..]);
let last_page_size = new_page.len();
let number_of_pages = (channel_details.last_index - channel_details.first_index) as u32;
<OutboundXcmpMessages<T>>::insert(recipient, page_index, new_page);
let r = (details.last_index - details.first_index - 1) as u32;
<OutboundXcmpStatus<T>>::put(s);
Ok(r)
<OutboundXcmpStatus<T>>::put(all_channels);
(number_of_pages, last_page_size)
};
// We have to count the total size here since `channel_info.total_size` is not updated at
// this point in time. We assume all previous pages are filled, which, in practice, is not
// always the case.
let total_size =
number_of_pages.saturating_sub(1) * max_message_size as u32 + last_page_size as u32;
let threshold = channel_info.max_total_size / delivery_fee_constants::THRESHOLD_FACTOR;
if total_size > threshold {
let message_size_factor = FixedU128::from((encoded_fragment.len() / 1024) as u128)
.saturating_mul(delivery_fee_constants::MESSAGE_SIZE_FEE_BASE);
Self::increase_fee_factor(recipient, message_size_factor);
}
Ok(number_of_pages)
}
/// Sends a signal to the `dest` chain over XCMP. This is guaranteed to be dispatched on this
@@ -1004,9 +1074,8 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
// Record the fact we received it.
match status.binary_search_by_key(&sender, |item| item.sender) {
Ok(i) => {
let count = status[i].message_metadata.len();
if count as u32 >= suspend_threshold && status[i].state == InboundState::Ok
{
let count = status[i].message_metadata.len() as u32;
if count >= suspend_threshold && status[i].state == InboundState::Ok {
status[i].state = InboundState::Suspended;
let r = Self::send_signal(sender, ChannelSignal::Suspend);
if r.is_err() {
@@ -1015,7 +1084,7 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
);
}
}
if (count as u32) < drop_threshold {
if count < drop_threshold {
status[i].message_metadata.push((sent_at, format));
} else {
debug_assert!(
@@ -1023,6 +1092,13 @@ impl<T: Config> XcmpMessageHandler for Pallet<T> {
"XCMP channel queue full. Silently dropping message"
);
}
// Update the delivery fee factor, if applicable.
if count > suspend_threshold {
let message_size_factor =
FixedU128::from((data_ref.len() / 1024) as u128)
.saturating_mul(delivery_fee_constants::MESSAGE_SIZE_FEE_BASE);
Self::increase_fee_factor(sender, message_size_factor);
}
},
Err(_) => status.push(InboundChannelDetails {
sender,
@@ -1120,6 +1196,21 @@ impl<T: Config> XcmpMessageSource for Pallet<T> {
result.push((para_id, page));
}
let max_total_size = match T::ChannelInfo::get_channel_info(para_id) {
Some(channel_info) => channel_info.max_total_size,
None => {
log::warn!("calling `get_channel_info` with no RelevantMessagingState?!");
MAX_POSSIBLE_ALLOCATION // We use this as a fallback in case the messaging state is not present
},
};
let threshold = max_total_size.saturating_div(delivery_fee_constants::THRESHOLD_FACTOR);
let remaining_total_size: usize = (first_index..last_index)
.map(|index| OutboundXcmpMessages::<T>::decode_len(para_id, index).unwrap())
.sum();
if remaining_total_size <= threshold as usize {
Self::decrease_fee_factor(para_id);
}
*status = OutboundChannelDetails {
recipient: para_id,
state: outbound_state,
@@ -1172,7 +1263,7 @@ impl<T: Config> SendXcm for Pallet<T> {
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))
@@ -1198,3 +1289,27 @@ impl<T: Config> SendXcm for Pallet<T> {
}
}
}
impl<T: Config> FeeTracker for Pallet<T> {
type Id = ParaId;
fn get_fee_factor(id: Self::Id) -> FixedU128 {
<DeliveryFeeFactor<T>>::get(id)
}
fn increase_fee_factor(id: Self::Id, message_size_factor: FixedU128) -> FixedU128 {
<DeliveryFeeFactor<T>>::mutate(id, |f| {
*f = f.saturating_mul(
delivery_fee_constants::EXPONENTIAL_FEE_BASE.saturating_add(message_size_factor),
);
*f
})
}
fn decrease_fee_factor(id: Self::Id) -> FixedU128 {
<DeliveryFeeFactor<T>>::mutate(id, |f| {
*f = InitialFactor::get().max(*f / delivery_fee_constants::EXPONENTIAL_FEE_BASE);
*f
})
}
}
+20 -2
View File
@@ -85,8 +85,10 @@ parameter_types! {
pub const MaxReserves: u32 = 50;
}
pub type Balance = u64;
impl pallet_balances::Config for Test {
type Balance = u64;
type Balance = Balance;
type RuntimeEvent = RuntimeEvent;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
@@ -196,6 +198,22 @@ impl<RuntimeOrigin: OriginTrait> ConvertOrigin<RuntimeOrigin>
}
}
parameter_types! {
/// The asset ID for the asset that we use to pay for message delivery fees.
pub FeeAssetId: AssetId = Concrete(RelayChain::get());
/// The base fee for the message delivery fees.
pub const BaseDeliveryFee: Balance = 300_000_000;
/// The fee per byte
pub const ByteFee: Balance = 1_000_000;
}
pub type PriceForSiblingParachainDelivery = polkadot_runtime_common::xcm_sender::ExponentialPrice<
FeeAssetId,
BaseDeliveryFee,
ByteFee,
XcmpQueue,
>;
impl Config for Test {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
@@ -205,7 +223,7 @@ impl Config for Test {
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = SystemParachainAsSuperuser<RuntimeOrigin>;
type WeightInfo = ();
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
}
pub fn new_test_ext() -> sp_io::TestExternalities {
+77 -5
View File
@@ -324,13 +324,14 @@ fn xcmp_queue_consumes_dest_and_msg_on_ok_validate() {
let dest = (Parent, X1(Parachain(5555)));
let mut dest_wrapper = Some(dest.into());
let mut msg_wrapper = Some(message.clone());
assert!(<XcmpQueue as SendXcm>::validate(&mut dest_wrapper, &mut msg_wrapper).is_ok());
// check wrapper were consumed
assert_eq!(None, dest_wrapper.take());
assert_eq!(None, msg_wrapper.take());
new_test_ext().execute_with(|| {
assert!(<XcmpQueue as SendXcm>::validate(&mut dest_wrapper, &mut msg_wrapper).is_ok());
// check wrapper were consumed
assert_eq!(None, dest_wrapper.take());
assert_eq!(None, msg_wrapper.take());
// another try with router chain with asserting sender
assert_eq!(
Err(SendError::Transport("NoChannel")),
@@ -370,3 +371,74 @@ fn xcmp_queue_send_xcm_works() {
.any(|(para_id, _)| para_id == &sibling_para_id));
})
}
#[test]
fn verify_fee_factor_increase_and_decrease() {
use cumulus_primitives_core::AbridgedHrmpChannel;
use sp_runtime::FixedU128;
let sibling_para_id = ParaId::from(12345);
let destination = (Parent, Parachain(sibling_para_id.into())).into();
let xcm = Xcm(vec![ClearOrigin; 100]);
let versioned_xcm = VersionedXcm::from(xcm.clone());
let mut xcmp_message = XcmpMessageFormat::ConcatenatedVersionedXcm.encode();
xcmp_message.extend(versioned_xcm.encode());
new_test_ext().execute_with(|| {
let initial = InitialFactor::get();
assert_eq!(DeliveryFeeFactor::<Test>::get(sibling_para_id), initial);
// Open channel so messages can actually be sent
ParachainSystem::open_custom_outbound_hrmp_channel_for_benchmarks_or_tests(
sibling_para_id,
AbridgedHrmpChannel {
max_capacity: 10,
max_total_size: 1000,
max_message_size: 104,
msg_count: 0,
total_size: 0,
mqc_head: None,
},
);
// Fee factor is only increased in `send_fragment`, which is called by `send_xcm`.
// When queue is not congested, fee factor doesn't change.
assert_ok!(send_xcm::<XcmpQueue>(destination, xcm.clone())); // Size 104
assert_ok!(send_xcm::<XcmpQueue>(destination, xcm.clone())); // Size 208
assert_ok!(send_xcm::<XcmpQueue>(destination, xcm.clone())); // Size 312
assert_ok!(send_xcm::<XcmpQueue>(destination, xcm.clone())); // Size 416
assert_eq!(DeliveryFeeFactor::<Test>::get(sibling_para_id), initial);
// Sending the message right now is cheap
let (_, delivery_fees) = validate_send::<XcmpQueue>(destination, xcm.clone())
.expect("message can be sent; qed");
let Fungible(delivery_fee_amount) = delivery_fees.inner()[0].fun else { unreachable!("asset is fungible; qed"); };
assert_eq!(delivery_fee_amount, 402_000_000);
let smaller_xcm = Xcm(vec![ClearOrigin; 30]);
// When we get to half of `max_total_size`, because `THRESHOLD_FACTOR` is 2,
// then the fee factor starts to increase.
assert_ok!(send_xcm::<XcmpQueue>(destination, xcm.clone())); // Size 520
assert_eq!(DeliveryFeeFactor::<Test>::get(sibling_para_id), FixedU128::from_float(1.05));
for _ in 0..12 { // We finish at size 929
assert_ok!(send_xcm::<XcmpQueue>(destination, smaller_xcm.clone()));
}
assert!(DeliveryFeeFactor::<Test>::get(sibling_para_id) > FixedU128::from_float(1.88));
// Sending the message right now is expensive
let (_, delivery_fees) = validate_send::<XcmpQueue>(destination, xcm.clone())
.expect("message can be sent; qed");
let Fungible(delivery_fee_amount) = delivery_fees.inner()[0].fun else { unreachable!("asset is fungible; qed"); };
assert_eq!(delivery_fee_amount, 758_030_955);
// Fee factor only decreases in `take_outbound_messages`
for _ in 0..5 { // We take 5 100 byte pages
XcmpQueue::take_outbound_messages(1);
}
assert!(DeliveryFeeFactor::<Test>::get(sibling_para_id) < FixedU128::from_float(1.72));
XcmpQueue::take_outbound_messages(1);
assert!(DeliveryFeeFactor::<Test>::get(sibling_para_id) < FixedU128::from_float(1.63));
});
}
@@ -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<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = ();
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
+2
View File
@@ -40,6 +40,7 @@ xcm-builder = { package = "staging-xcm-builder", path = "../../../polkadot/xcm/x
pallet-collator-selection = { path = "../../pallets/collator-selection", default-features = false }
cumulus-primitives-core = { path = "../../primitives/core", default-features = false }
cumulus-primitives-utility = { path = "../../primitives/utility", default-features = false }
parachain-info = { path = "../pallets/parachain-info", default-features = false }
[dev-dependencies]
pallet-authorship = { path = "../../../substrate/frame/authorship", default-features = false}
@@ -61,6 +62,7 @@ std = [
"pallet-authorship/std",
"pallet-balances/std",
"pallet-collator-selection/std",
"parachain-info/std",
"polkadot-core-primitives/std",
"polkadot-primitives/std",
"rococo-runtime-constants/std",
+7 -1
View File
@@ -73,7 +73,10 @@ mod types {
/// Common constants of parachains.
mod constants {
use super::types::BlockNumber;
use frame_support::weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight};
use frame_support::{
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
PalletId,
};
use sp_runtime::Perbill;
/// This determines the average expected block time that we are targeting. Blocks will be
/// produced at a minimum duration defined by `SLOT_DURATION`. `SLOT_DURATION` is picked up by
@@ -101,6 +104,9 @@ mod constants {
WEIGHT_REF_TIME_PER_SECOND.saturating_div(2),
polkadot_primitives::MAX_POV_SIZE as u64,
);
/// Treasury pallet id of the local chain, used to convert into AccountId
pub const TREASURY_PALLET_ID: PalletId = PalletId(*b"py/trsry");
}
/// Opaque types. These are used by the CLI to instantiate machinery that don't need to know
+22 -2
View File
@@ -16,10 +16,9 @@
use crate::impls::AccountIdOf;
use cumulus_primitives_core::{IsSystem, ParaId};
use frame_support::{
traits::{fungibles::Inspect, tokens::ConversionToAssetBalance, ContainsPair},
traits::{fungibles::Inspect, tokens::ConversionToAssetBalance, Contains, ContainsPair},
weights::Weight,
};
use log;
use sp_runtime::traits::Get;
use sp_std::marker::PhantomData;
use xcm::latest::prelude::*;
@@ -80,6 +79,27 @@ impl<Location: Get<MultiLocation>> ContainsPair<MultiAsset, MultiLocation>
}
}
pub struct RelayOrOtherSystemParachains<
SystemParachainMatcher: Contains<MultiLocation>,
Runtime: parachain_info::Config,
> {
_runtime: PhantomData<(SystemParachainMatcher, Runtime)>,
}
impl<SystemParachainMatcher: Contains<MultiLocation>, Runtime: parachain_info::Config>
Contains<MultiLocation> for RelayOrOtherSystemParachains<SystemParachainMatcher, Runtime>
{
fn contains(l: &MultiLocation) -> bool {
let self_para_id: u32 = parachain_info::Pallet::<Runtime>::get().into();
if let MultiLocation { parents: 0, interior: X1(Parachain(para_id)) } = l {
if *para_id == self_para_id {
return false
}
}
matches!(l, MultiLocation { parents: 1, interior: Here }) ||
SystemParachainMatcher::contains(l)
}
}
/// Accepts an asset if it is a concrete asset from the system (Relay Chain or system parachain).
pub struct ConcreteAssetFromSystem<AssetLocation>(PhantomData<AssetLocation>);
impl<AssetLocation: Get<MultiLocation>> ContainsPair<MultiAsset, MultiLocation>
@@ -25,8 +25,11 @@ polkadot-parachain-primitives = { path = "../../../../../../polkadot/parachain",
polkadot-runtime-parachains = { path = "../../../../../../polkadot/runtime/parachains" }
xcm = { package = "staging-xcm", path = "../../../../../../polkadot/xcm", default-features = false}
pallet-xcm = { path = "../../../../../../polkadot/xcm/pallet-xcm", default-features = false}
xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../polkadot/xcm/xcm-executor", default-features = false}
rococo-runtime = { path = "../../../../../../polkadot/runtime/rococo", default-features = false }
# Cumulus
asset-test-utils = { path = "../../../../runtimes/assets/test-utils", default-features = false }
parachains-common = { path = "../../../../common" }
asset-hub-rococo-runtime = { path = "../../../../runtimes/assets/asset-hub-rococo" }
@@ -47,5 +50,7 @@ runtime-benchmarks = [
"parachains-common/runtime-benchmarks",
"polkadot-parachain-primitives/runtime-benchmarks",
"polkadot-runtime-parachains/runtime-benchmarks",
"rococo-runtime/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
]
@@ -13,6 +13,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub use asset_test_utils::xcm_helpers;
pub use codec::Encode;
pub use frame_support::{
assert_err, assert_ok,
@@ -14,6 +14,8 @@
// limitations under the License.
use crate::*;
use asset_hub_rococo_runtime::xcm_config::XcmConfig as AssetHubRococoXcmConfig;
use rococo_runtime::xcm_config::XcmConfig as RococoXcmConfig;
fn relay_origin_assertions(t: RelayToSystemParaTest) {
type RuntimeEvent = <Rococo as Chain>::RuntimeEvent;
@@ -182,10 +184,16 @@ fn limited_reserve_transfer_native_asset_from_relay_to_system_para_fails() {
test.set_dispatchable::<Rococo>(relay_limited_reserve_transfer_assets);
test.assert();
let delivery_fees = Rococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<RococoXcmConfig as xcm_executor::Config>::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;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
assert_eq!(receiver_balance_before, receiver_balance_after);
}
@@ -244,7 +252,13 @@ fn reserve_transfer_native_asset_from_relay_to_system_para_fails() {
let sender_balance_after = test.sender.balance;
let receiver_balance_after = test.receiver.balance;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
let delivery_fees = Rococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<RococoXcmConfig as xcm_executor::Config>::XcmSender,
>(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest)
});
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
assert_eq!(receiver_balance_before, receiver_balance_after);
}
@@ -306,7 +320,13 @@ fn limited_reserve_transfer_native_asset_from_system_para_to_para() {
let sender_balance_after = test.sender.balance;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
let delivery_fees = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::XcmSender,
>(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest)
});
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// TODO: Check receiver balance when Penpal runtime is improved to propery handle reserve
// transfers
}
@@ -338,7 +358,13 @@ fn reserve_transfer_native_asset_from_system_para_to_para() {
let sender_balance_after = test.sender.balance;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
let delivery_fees = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::XcmSender,
>(test.args.assets.clone(), 0, test.args.weight_limit, test.args.beneficiary, test.args.dest)
});
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// TODO: Check receiver balance when Penpal runtime is improved to propery handle reserve
// transfers
}
@@ -14,6 +14,8 @@
// limitations under the License.
use crate::*;
use asset_hub_rococo_runtime::xcm_config::XcmConfig as AssetHubRococoXcmConfig;
use rococo_runtime::xcm_config::XcmConfig as RococoXcmConfig;
fn relay_origin_assertions(t: RelayToSystemParaTest) {
type RuntimeEvent = <Rococo as Chain>::RuntimeEvent;
@@ -171,11 +173,17 @@ fn limited_teleport_native_assets_from_relay_to_system_para_works() {
test.set_dispatchable::<Rococo>(relay_limited_teleport_assets);
test.assert();
let delivery_fees = Rococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<RococoXcmConfig as xcm_executor::Config>::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);
}
@@ -212,8 +220,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 = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::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);
}
@@ -247,8 +261,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 = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::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);
}
@@ -274,11 +294,17 @@ fn teleport_native_assets_from_relay_to_system_para_works() {
test.set_dispatchable::<Rococo>(relay_teleport_assets);
test.assert();
let delivery_fees = Rococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<RococoXcmConfig as xcm_executor::Config>::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);
}
@@ -315,8 +341,14 @@ fn 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 = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::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);
}
@@ -347,11 +379,17 @@ fn teleport_native_assets_from_system_para_to_relay_fails() {
test.set_dispatchable::<AssetHubRococo>(system_para_teleport_assets);
test.assert();
let delivery_fees = AssetHubRococo::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubRococoXcmConfig as xcm_executor::Config>::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);
}
@@ -359,11 +397,12 @@ fn teleport_native_assets_from_system_para_to_relay_fails() {
#[test]
fn teleport_to_other_system_parachains_works() {
let amount = ASSET_HUB_ROCOCO_ED * 100;
let native_asset: VersionedMultiAssets = (Parent, amount).into();
let native_asset: MultiAssets = (Parent, amount).into();
test_parachain_is_trusted_teleporter!(
AssetHubRococo, // Origin
vec![BridgeHubRococo], // Destinations
AssetHubRococo, // Origin
AssetHubRococoXcmConfig, // XCM Configuration
vec![BridgeHubRococo], // Destinations
(native_asset, amount)
);
}
@@ -30,10 +30,13 @@ xcm = { package = "staging-xcm", path = "../../../../../../polkadot/xcm", defaul
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}
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" }
asset-hub-westend-runtime = { path = "../../../../runtimes/assets/asset-hub-westend" }
asset-test-utils = { path = "../../../../runtimes/assets/test-utils", default-features = false }
cumulus-pallet-dmp-queue = { default-features = false, path = "../../../../../pallets/dmp-queue" }
cumulus-pallet-parachain-system = { default-features = false, path = "../../../../../pallets/parachain-system" }
@@ -59,6 +62,7 @@ runtime-benchmarks = [
"polkadot-runtime-common/runtime-benchmarks",
"polkadot-runtime-parachains/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"westend-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
]
@@ -13,6 +13,7 @@
// See the License for the specific language governing permissions and
// limitations under the License.
pub use asset_test_utils::xcm_helpers;
pub use codec::Encode;
pub use frame_support::{
assert_err, assert_ok,
@@ -14,6 +14,8 @@
// limitations under the License.
use crate::*;
use asset_hub_westend_runtime::xcm_config::XcmConfig;
use westend_runtime::xcm_config::XcmConfig as WestendXcmConfig;
fn relay_origin_assertions(t: RelayToSystemParaTest) {
type RuntimeEvent = <Westend as Chain>::RuntimeEvent;
@@ -179,10 +181,16 @@ fn limited_reserve_transfer_native_asset_from_relay_to_system_para_fails() {
test.set_dispatchable::<Westend>(relay_limited_reserve_transfer_assets);
test.assert();
let delivery_fees = Westend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<WestendXcmConfig as xcm_executor::Config>::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;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
assert_eq!(receiver_balance_before, receiver_balance_after);
}
@@ -238,10 +246,16 @@ fn reserve_transfer_native_asset_from_relay_to_system_para_fails() {
test.set_dispatchable::<Westend>(relay_reserve_transfer_assets);
test.assert();
let delivery_fees = Westend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<WestendXcmConfig as xcm_executor::Config>::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;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
assert_eq!(receiver_balance_before, receiver_balance_after);
}
@@ -303,7 +317,17 @@ fn limited_reserve_transfer_native_asset_from_system_para_to_para() {
let sender_balance_after = test.sender.balance;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
let delivery_fees = AssetHubWestend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<<XcmConfig as xcm_executor::Config>::XcmSender>(
test.args.assets.clone(),
0,
test.args.weight_limit,
test.args.beneficiary,
test.args.dest,
)
});
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// TODO: Check receiver balance when Penpal runtime is improved to propery handle reserve
// transfers
}
@@ -335,7 +359,17 @@ fn reserve_transfer_native_asset_from_system_para_to_para() {
let sender_balance_after = test.sender.balance;
assert_eq!(sender_balance_before - amount_to_send, sender_balance_after);
let delivery_fees = AssetHubWestend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<<XcmConfig as xcm_executor::Config>::XcmSender>(
test.args.assets.clone(),
0,
test.args.weight_limit,
test.args.beneficiary,
test.args.dest,
)
});
assert_eq!(sender_balance_before - amount_to_send - delivery_fees, sender_balance_after);
// TODO: Check receiver balance when Penpal runtime is improved to propery handle reserve
// transfers
}
@@ -16,6 +16,8 @@
#![allow(dead_code)] // <https://github.com/paritytech/cumulus/issues/3027>
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) {
type RuntimeEvent = <Westend as Chain>::RuntimeEvent;
@@ -173,11 +175,17 @@ fn limited_teleport_native_assets_from_relay_to_system_para_works() {
test.set_dispatchable::<Westend>(relay_limited_teleport_assets);
test.assert();
let delivery_fees = Westend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<WestendXcmConfig as xcm_executor::Config>::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);
}
@@ -214,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::<
<AssetHubWestendXcmConfig as xcm_executor::Config>::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);
}
@@ -249,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::<
<AssetHubWestendXcmConfig as xcm_executor::Config>::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);
}
@@ -276,11 +296,17 @@ fn teleport_native_assets_from_relay_to_system_para_works() {
test.set_dispatchable::<Westend>(relay_teleport_assets);
test.assert();
let delivery_fees = Westend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<WestendXcmConfig as xcm_executor::Config>::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);
}
@@ -314,11 +340,17 @@ fn teleport_native_assets_back_from_system_para_to_relay_works() {
test.set_dispatchable::<AssetHubWestend>(system_para_teleport_assets);
test.assert();
let delivery_fees = AssetHubWestend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubWestendXcmConfig as xcm_executor::Config>::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);
}
@@ -349,11 +381,17 @@ fn teleport_native_assets_from_system_para_to_relay_fails() {
test.set_dispatchable::<AssetHubWestend>(system_para_teleport_assets);
test.assert();
let delivery_fees = AssetHubWestend::execute_with(|| {
xcm_helpers::transfer_assets_delivery_fees::<
<AssetHubWestendXcmConfig as xcm_executor::Config>::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);
}
@@ -19,13 +19,16 @@ polkadot-parachain-primitives = { path = "../../../../../../polkadot/parachain",
polkadot-runtime-parachains = { path = "../../../../../../polkadot/runtime/parachains" }
xcm = { package = "staging-xcm", path = "../../../../../../polkadot/xcm", default-features = false}
pallet-xcm = { path = "../../../../../../polkadot/xcm/pallet-xcm", default-features = false}
xcm-executor = { package = "staging-xcm-executor", path = "../../../../../../polkadot/xcm/xcm-executor", default-features = false}
# Cumulus
asset-test-utils = { path = "../../../../../parachains/runtimes/assets/test-utils", default-features = false }
parachains-common = { path = "../../../../common" }
cumulus-pallet-xcmp-queue = { path = "../../../../../pallets/xcmp-queue", default-features = false}
cumulus-pallet-dmp-queue = { path = "../../../../../pallets/dmp-queue", default-features = false}
pallet-bridge-messages = { path = "../../../../../../bridges/modules/messages", default-features = false}
bp-messages = { path = "../../../../../../bridges/primitives/messages", default-features = false}
bridge-hub-rococo-runtime = { path = "../../../../../parachains/runtimes/bridge-hubs/bridge-hub-rococo", default-features = false }
# Local
xcm-emulator = { path = "../../../../../xcm/xcm-emulator", default-features = false}
@@ -14,14 +14,16 @@
// limitations under the License.
use crate::*;
use bridge_hub_rococo_runtime::xcm_config::XcmConfig;
#[test]
fn teleport_to_other_system_parachains_works() {
let amount = BRIDGE_HUB_ROCOCO_ED * 100;
let native_asset: VersionedMultiAssets = (Parent, amount).into();
let native_asset: MultiAssets = (Parent, amount).into();
test_parachain_is_trusted_teleporter!(
BridgeHubRococo, // Origin
XcmConfig, // XCM configuration
vec![AssetHubRococo], // Destinations
(native_asset, amount)
);
@@ -15,7 +15,7 @@
#[macro_export]
macro_rules! test_parachain_is_trusted_teleporter {
( $sender_para:ty, vec![$( $receiver_para:ty ),+], ($assets:expr, $amount:expr) ) => {
( $sender_para:ty, $sender_xcm_config:ty, vec![$( $receiver_para:ty ),+], ($assets:expr, $amount:expr) ) => {
$crate::paste::paste! {
// init Origin variables
let sender = [<$sender_para Sender>]::get();
@@ -32,19 +32,22 @@ macro_rules! test_parachain_is_trusted_teleporter {
let para_receiver_balance_before =
<$receiver_para as $crate::Chain>::account_data_of(receiver.clone()).free;
let para_destination =
<$sender_para>::sibling_location_of(<$receiver_para>::para_id()).into();
let beneficiary =
<$sender_para>::sibling_location_of(<$receiver_para>::para_id());
let beneficiary: MultiLocation =
$crate::AccountId32 { network: None, id: receiver.clone().into() }.into();
dbg!(&origin);
dbg!(&para_destination);
// Send XCM message from Origin Parachain
// We are only testing the limited teleport version, which should be ok since success will
// depend only on a proper `XcmConfig` at destination.
<$sender_para>::execute_with(|| {
assert_ok!(<$sender_para as [<$sender_para Pallet>]>::PolkadotXcm::limited_teleport_assets(
origin.clone(),
bx!(para_destination),
bx!(beneficiary),
bx!($assets.clone()),
bx!(para_destination.into()),
bx!(beneficiary.into()),
bx!($assets.clone().into()),
fee_asset_item,
weight_limit.clone(),
));
@@ -89,8 +92,13 @@ macro_rules! test_parachain_is_trusted_teleporter {
<$sender_para as $crate::Chain>::account_data_of(sender.clone()).free;
let para_receiver_balance_after =
<$receiver_para as $crate::Chain>::account_data_of(receiver.clone()).free;
let delivery_fees = <$sender_para>::execute_with(|| {
asset_test_utils::xcm_helpers::transfer_assets_delivery_fees::<
<$sender_xcm_config as xcm_executor::Config>::XcmSender,
>($assets.clone(), fee_asset_item, weight_limit.clone(), beneficiary, para_destination)
});
assert_eq!(para_sender_balance_before - $amount, para_sender_balance_after);
assert_eq!(para_sender_balance_before - $amount - delivery_fees, para_sender_balance_after);
assert!(para_receiver_balance_after > para_receiver_balance_before);
// Update sender balance
@@ -14,14 +14,7 @@
// limitations under the License.
use parachains_common::AccountId;
use xcm::{
prelude::{
AccountId32, All, BuyExecution, DepositAsset, MultiAsset, MultiAssets, MultiLocation,
OriginKind, RefundSurplus, Transact, UnpaidExecution, VersionedXcm, Weight, WeightLimit,
WithdrawAsset, Xcm, X1,
},
DoubleEncoded,
};
use xcm::{prelude::*, DoubleEncoded};
/// Helper method to build a XCM with a `Transact` instruction and paying for its execution
pub fn xcm_transact_paid_execution(
@@ -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::{
@@ -88,7 +90,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 crate::xcm_config::{
@@ -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<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -1211,9 +1213,21 @@ impl_runtime_apis! {
use xcm_config::{KsmLocation, MaxAssetsIntoHolding};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = 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 = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(KsmLocation::get())
}
@@ -1269,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) {
@@ -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::{FromSiblingParachain, IsForeignConcreteAsset},
@@ -34,6 +34,7 @@ use parachains_common::{
xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem},
};
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::{
@@ -532,11 +533,21 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
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<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -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::{
@@ -118,7 +120,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 crate::xcm_config::ForeignCreatorsSovereignAccountOf;
@@ -581,7 +583,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
EnsureXcm<IsVoiceOfBody<FellowshipLocation, FellowsBodyId>>,
>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -1090,9 +1092,21 @@ impl_runtime_apis! {
use xcm_config::{DotLocation, MaxAssetsIntoHolding};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = 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 = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(DotLocation::get())
}
@@ -1148,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) {
@@ -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};
use frame_support::{
@@ -30,6 +30,7 @@ use parachains_common::{
xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem},
};
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::{
@@ -456,11 +457,21 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
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<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -55,6 +55,7 @@ sp-weights = { path = "../../../../../substrate/primitives/weights", default-fea
primitive-types = { version = "0.12.1", default-features = false, features = ["codec", "scale-info", "num-traits"] }
# Polkadot
rococo-runtime = { path = "../../../../../polkadot/runtime/rococo", default-features = false }
rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", default-features = false}
pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false}
pallet-xcm-benchmarks = { path = "../../../../../polkadot/xcm/pallet-xcm-benchmarks", default-features = false, optional = true }
@@ -130,6 +131,7 @@ runtime-benchmarks = [
"parachains-common/runtime-benchmarks",
"polkadot-parachain-primitives/runtime-benchmarks",
"polkadot-runtime-common/runtime-benchmarks",
"rococo-runtime/runtime-benchmarks",
"sp-runtime/runtime-benchmarks",
"xcm-builder/runtime-benchmarks",
"xcm-executor/runtime-benchmarks",
@@ -165,6 +167,7 @@ try-runtime = [
"pallet-xcm/try-runtime",
"parachain-info/try-runtime",
"polkadot-runtime-common/try-runtime",
"rococo-runtime/try-runtime",
"sp-runtime/try-runtime",
]
std = [
@@ -218,6 +221,7 @@ std = [
"polkadot-parachain-primitives/std",
"polkadot-runtime-common/std",
"rococo-runtime-constants/std",
"rococo-runtime/std",
"scale-info/std",
"sp-api/std",
"sp-block-builder/std",
@@ -93,7 +93,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 crate::xcm_config::{
@@ -636,6 +636,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::TokenLocation::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<XcmConfig>;
@@ -645,7 +659,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = xcm_config::XcmOriginToTransactDispatchOrigin;
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -1315,9 +1329,21 @@ impl_runtime_apis! {
use xcm_config::{TokenLocation, MaxAssetsIntoHolding};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
TokenLocation::get(),
ExistentialDeposit::get()
).into());
}
impl pallet_xcm_benchmarks::Config for Runtime {
type XcmConfig = xcm_config::XcmConfig;
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(TokenLocation::get())
}
@@ -1373,6 +1399,7 @@ impl_runtime_apis! {
}
impl pallet_xcm_benchmarks::generic::Config for Runtime {
type TransactAsset = Balances;
type RuntimeCall = RuntimeCall;
fn worst_case_response() -> (u64, Response) {
@@ -14,10 +14,11 @@
// limitations under the License.
use super::{
AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, ForeignAssets,
ForeignAssetsInstance, ParachainInfo, ParachainSystem, PolkadotXcm, PoolAssets, Runtime,
RuntimeCall, RuntimeEvent, RuntimeFlavor, RuntimeOrigin, ToRococoXcmRouter, ToWococoXcmRouter,
TransactionByteFee, TrustBackedAssetsInstance, WeightToFee, XcmpQueue,
AccountId, AllPalletsWithSystem, Assets, Authorship, Balance, Balances, BaseDeliveryFee,
FeeAssetId, ForeignAssets, ForeignAssetsInstance, ParachainInfo, ParachainSystem, PolkadotXcm,
PoolAssets, Runtime, RuntimeCall, RuntimeEvent, RuntimeFlavor, RuntimeOrigin,
ToRococoXcmRouter, ToWococoXcmRouter, TransactionByteFee, TrustBackedAssetsInstance,
WeightToFee, XcmpQueue,
};
use assets_common::{
local_and_foreign_assets::MatchesLocalAndForeignAssetsMultiLocation,
@@ -31,10 +32,17 @@ use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{
impls::ToStakingPot,
xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem},
xcm_config::{
AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem,
RelayOrOtherSystemParachains,
},
TREASURY_PALLET_ID,
};
use polkadot_parachain_primitives::primitives::Sibling;
use sp_runtime::traits::ConvertInto;
use polkadot_runtime_common::xcm_sender::ExponentialPrice;
use rococo_runtime::Treasury as RococoTreasury;
use rococo_runtime_constants::system_parachain::SystemParachains;
use sp_runtime::traits::{AccountIdConversion, ConvertInto};
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, AllAssets, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
@@ -46,6 +54,7 @@ use xcm_builder::{
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit,
TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
XcmFeesToAccount,
};
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
@@ -67,6 +76,7 @@ parameter_types! {
PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub const GovernanceLocation: MultiLocation = MultiLocation::parent();
pub TreasuryAccount: Option<AccountId> = Some(TREASURY_PALLET_ID.into_account_truncating());
}
/// Adapter for resolving `NetworkId` based on `pub storage Flavor: RuntimeFlavor`.
@@ -521,6 +531,23 @@ pub type ForeignAssetFeeAsExistentialDepositMultiplierFeeCharger =
ForeignAssetsInstance,
>;
parameter_types! {
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(<RococoTreasury as PalletInfoAccess>::index() as u8)).into();
}
pub struct RelayTreasury;
impl Contains<MultiLocation> 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<SystemParachains, Runtime>, RelayTreasury);
/// Cases where a remote origin is accepted as trusted Teleporter for a given asset:
///
/// - ROC with the parent Relay Chain and sibling system parachains; and
@@ -588,8 +615,7 @@ impl xcm_executor::Config for XcmConfig {
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type AssetLocker = ();
type AssetExchanger = ();
// TODO:check-parameter: change and assert in tests when (https://github.com/paritytech/polkadot-sdk/pull/1234) merged
type FeeManager = ();
type FeeManager = XcmFeesToAccount<Self, WaivedLocations, AccountId, TreasuryAccount>;
type MessageExporter = ();
type UniversalAliases =
(bridging::to_wococo::UniversalAliases, bridging::to_rococo::UniversalAliases);
@@ -602,10 +628,13 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// For routing XCM messages which do not cross local consensus boundary.
type LocalXcmRouter = (
// Two routers - use UMP to communicate with the relay chain:
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
);
@@ -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",
@@ -88,6 +88,7 @@ use assets_common::{
foreign_creators::ForeignCreators, matching::FromSiblingParachain, MultiLocationForAssetId,
};
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use xcm::latest::prelude::*;
use xcm_executor::XcmExecutor;
use crate::xcm_config::ForeignCreatorsSovereignAccountOf;
@@ -604,6 +605,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::WestendLocation::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<XcmConfig>;
@@ -613,7 +628,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -1262,9 +1277,21 @@ impl_runtime_apis! {
use xcm_config::{MaxAssetsIntoHolding, WestendLocation};
use pallet_xcm_benchmarks::asset_instance_from;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
WestendLocation::get(),
ExistentialDeposit::get()
).into());
}
impl pallet_xcm_benchmarks::Config for Runtime {
type XcmConfig = xcm_config::XcmConfig;
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(WestendLocation::get())
}
@@ -1320,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) {
@@ -1421,7 +1449,6 @@ pub mod migrations {
};
use parachains_common::impls::AccountIdOf;
use sp_runtime::{traits::StaticLookup, Saturating};
use xcm::latest::prelude::*;
/// Temporary migration because of bug with native asset, it can be removed once applied on
/// `AssetHubWestend`. Migrates pools with `MultiLocation { parents: 0, interior: Here }` to
@@ -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::{
@@ -31,10 +32,17 @@ use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{
impls::ToStakingPot,
xcm_config::{AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem},
xcm_config::{
AssetFeeAsExistentialDepositMultiplier, ConcreteAssetFromSystem,
RelayOrOtherSystemParachains,
},
TREASURY_PALLET_ID,
};
use polkadot_parachain_primitives::primitives::Sibling;
use sp_runtime::traits::ConvertInto;
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::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
@@ -45,6 +53,7 @@ use xcm_builder::{
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, StartsWith, StartsWithExplicitGlobalConsensus, TakeWeightCredit,
TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
XcmFeesToAccount,
};
use xcm_executor::{traits::WithOriginFilter, XcmExecutor};
@@ -65,6 +74,7 @@ parameter_types! {
pub PoolAssetsPalletLocation: MultiLocation =
PalletInstance(<PoolAssets as PalletInfoAccess>::index() as u8).into();
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub TreasuryAccount: Option<AccountId> = Some(TREASURY_PALLET_ID.into_account_truncating());
}
/// Type for specifying how a `MultiLocation` can be converted into an `AccountId`. This is used
@@ -482,6 +492,36 @@ pub type AssetFeeAsExistentialDepositMultiplierFeeCharger = AssetFeeAsExistentia
TrustBackedAssetsInstance,
>;
match_types! {
pub type SystemParachains: impl Contains<MultiLocation> = {
MultiLocation {
parents: 1,
interior: X1(Parachain(
system_parachain::ASSET_HUB_ID |
system_parachain::COLLECTIVES_ID |
system_parachain::BRIDGE_HUB_ID
)),
}
};
}
parameter_types! {
pub RelayTreasuryLocation: MultiLocation = (Parent, PalletInstance(<WestendTreasury as PalletInfoAccess>::index() as u8)).into();
}
pub struct RelayTreasury;
impl Contains<MultiLocation> 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<SystemParachains, Runtime>, RelayTreasury);
/// Cases where a remote origin is accepted as trusted Teleporter for a given asset:
///
/// - WND with the parent Relay Chain and sibling system parachains; and
@@ -531,7 +571,7 @@ impl xcm_executor::Config for XcmConfig {
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type AssetLocker = ();
type AssetExchanger = ();
type FeeManager = ();
type FeeManager = XcmFeesToAccount<Self, WaivedLocations, AccountId, TreasuryAccount>;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = WithOriginFilter<SafeCallFilter>;
@@ -542,11 +582,14 @@ impl xcm_executor::Config for XcmConfig {
/// Local origins on this chain are allowed to dispatch XCM sends/executions.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -34,11 +34,11 @@ parachain-info = { path = "../../../pallets/parachain-info", default-features =
parachains-runtimes-test-utils = { path = "../../test-utils", default-features = false }
# Polkadot
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}
pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false}
polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", 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 }
pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false }
polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false }
# Bridges
pallet-xcm-bridge-hub-router = { path = "../../../../../bridges/modules/xcm-bridge-hub-router", default-features = false }
@@ -18,4 +18,5 @@
pub mod test_cases;
pub mod test_cases_over_bridge;
pub mod xcm_helpers;
pub use parachains_runtimes_test_utils::*;
@@ -15,10 +15,13 @@
//! Module contains predefined test-case scenarios for `Runtime` with various assets.
use super::xcm_helpers;
use codec::Encode;
use frame_support::{
assert_noop, assert_ok,
traits::{fungibles::InspectEnumerable, Get, OnFinalize, OnInitialize, OriginTrait},
traits::{
fungible::Mutate, fungibles::InspectEnumerable, Get, OnFinalize, OnInitialize, OriginTrait,
},
weights::Weight,
};
use frame_system::pallet_prelude::BlockNumberFor;
@@ -175,6 +178,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::<XcmConfig::XcmSender>(
(native_asset_id, native_asset_to_teleport_away.into()).into(),
0,
Unlimited,
dest_beneficiary,
dest,
);
<pallet_balances::Pallet<Runtime>>::mint_into(
&target_account,
delivery_fees.into(),
)
.unwrap();
assert_ok!(RuntimeHelper::<Runtime>::do_teleport_assets::<HrmpChannelOpener>(
RuntimeHelper::<Runtime>::origin_of(target_account.clone()),
dest,
@@ -184,6 +202,7 @@ pub fn teleports_for_native_asset_works<
included_head.clone(),
&alice,
));
// check balances
assert_eq!(
<pallet_balances::Pallet<Runtime>>::free_balance(&target_account),
@@ -232,10 +251,21 @@ pub fn teleports_for_native_asset_works<
&alice,
));
let delivery_fees =
xcm_helpers::transfer_assets_delivery_fees::<XcmConfig::XcmSender>(
(native_asset_id, native_asset_to_teleport_away.into()).into(),
0,
Unlimited,
dest_beneficiary,
dest,
);
// check balances
assert_eq!(
<pallet_balances::Pallet<Runtime>>::free_balance(&target_account),
target_account_balance_before_teleport - native_asset_to_teleport_away
target_account_balance_before_teleport -
native_asset_to_teleport_away -
delivery_fees.into()
);
assert_eq!(
<pallet_balances::Pallet<Runtime>>::free_balance(&CheckingAccount::get()),
@@ -370,7 +400,7 @@ pub fn teleports_for_foreign_assets_works<
fun: Fungible(buy_execution_fee_amount),
};
let teleported_foreign_asset_amount = 10000000000000;
let teleported_foreign_asset_amount = 10_000_000_000_000;
let runtime_para_id = 1000;
ExtBuilder::<Runtime>::default()
.with_collators(collator_session_keys.collators())
@@ -400,11 +430,11 @@ pub fn teleports_for_foreign_assets_works<
<pallet_balances::Pallet<Runtime>>::free_balance(&target_account),
existential_deposit
);
// check `CheckingAccount` before
assert_eq!(
<pallet_balances::Pallet<Runtime>>::free_balance(&CheckingAccount::get()),
existential_deposit
);
// check `CheckingAccount` before
assert_eq!(
<pallet_assets::Pallet<Runtime, ForeignAssetsPalletInstance>>::balance(
foreign_asset_id_multilocation.into(),
@@ -540,6 +570,21 @@ pub fn teleports_for_foreign_assets_works<
.into()
);
// Make sure the target account has enough native asset to pay for delivery fees
let delivery_fees =
xcm_helpers::transfer_assets_delivery_fees::<XcmConfig::XcmSender>(
(foreign_asset_id_multilocation, asset_to_teleport_away).into(),
0,
Unlimited,
dest_beneficiary,
dest,
);
<pallet_balances::Pallet<Runtime>>::mint_into(
&target_account,
delivery_fees.into(),
)
.unwrap();
assert_ok!(RuntimeHelper::<Runtime>::do_teleport_assets::<HrmpChannelOpener>(
RuntimeHelper::<Runtime>::origin_of(target_account.clone()),
dest,
@@ -20,7 +20,9 @@ use codec::Encode;
use cumulus_primitives_core::XcmpMessageSource;
use frame_support::{
assert_ok,
traits::{Currency, OnFinalize, OnInitialize, OriginTrait, ProcessMessageError},
traits::{
fungible::Mutate, Currency, OnFinalize, OnInitialize, OriginTrait, ProcessMessageError,
},
};
use frame_system::pallet_prelude::BlockNumberFor;
use parachains_common::{AccountId, Balance};
@@ -164,6 +166,12 @@ pub fn limited_reserve_transfer_assets_for_native_asset_works<
}),
};
// Make sure sender has enough funds for paying delivery fees
// TODO: Get this fee via weighing the corresponding message
let delivery_fees = 1324039894;
<pallet_balances::Pallet<Runtime>>::mint_into(&alice_account, delivery_fees.into())
.unwrap();
// do pallet_xcm call reserve transfer
assert_ok!(<pallet_xcm::Pallet<Runtime>>::limited_reserve_transfer_assets(
RuntimeHelper::<Runtime, AllPalletsWithoutSystem>::origin_of(alice_account.clone()),
@@ -0,0 +1,108 @@
// Copyright Parity Technologies (UK) Ltd.
// This file is part of Cumulus.
// Cumulus is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Cumulus is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Cumulus. If not, see <http://www.gnu.org/licenses/>.
//! Helpers for calculating XCM delivery fees.
use xcm::latest::prelude::*;
/// Returns the delivery fees amount for pallet xcm's `teleport_assets` and
/// `reserve_transfer_assets` extrinsics.
/// Because it returns only a `u128`, it assumes delivery fees are only paid
/// in one asset and that asset is known.
pub fn transfer_assets_delivery_fees<S: SendXcm>(
assets: MultiAssets,
fee_asset_item: u32,
weight_limit: WeightLimit,
beneficiary: MultiLocation,
destination: MultiLocation,
) -> u128 {
let message = teleport_assets_dummy_message(assets, fee_asset_item, weight_limit, beneficiary);
get_fungible_delivery_fees::<S>(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<S: SendXcm>(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::<S>(querier, message)
}
/// Returns the delivery fees amount for the execution of `PayOverXcm`
pub fn pay_over_xcm_delivery_fees<S: SendXcm>(
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::<S>(destination, message)
}
/// Approximates the actual message sent by the teleport extrinsic.
/// The assets are not reanchored and the topic is a dummy one.
/// However, it should have the same encoded size, which is what matters for delivery fees.
/// Also has same encoded size as the one created by the reserve transfer assets extrinsic.
fn teleport_assets_dummy_message(
assets: MultiAssets,
fee_asset_item: u32,
weight_limit: WeightLimit,
beneficiary: MultiLocation,
) -> Xcm<()> {
Xcm(vec![
ReceiveTeleportedAsset(assets.clone()), // Same encoded size as `ReserveAssetDeposited`
ClearOrigin,
BuyExecution { fees: assets.get(fee_asset_item as usize).unwrap().clone(), weight_limit },
DepositAsset { assets: Wild(AllCounted(assets.len() as u32)), beneficiary },
SetTopic([0u8; 32]), // Dummy topic
])
}
/// Given a message, a sender, and a destination, it returns the delivery fees
fn get_fungible_delivery_fees<S: SendXcm>(destination: MultiLocation, message: Xcm<()>) -> u128 {
let Ok((_, delivery_fees)) = validate_send::<S>(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
}
}
@@ -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::{
@@ -75,7 +77,7 @@ use parachains_common::{
};
// XCM Imports
use xcm::latest::prelude::BodyId;
use xcm::latest::prelude::*;
use xcm_executor::XcmExecutor;
/// The address format for describing accounts.
@@ -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<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -671,9 +673,21 @@ impl_runtime_apis! {
use xcm::latest::prelude::*;
use xcm_config::KsmRelayLocation;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = 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 = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(KsmRelayLocation::get())
}
@@ -714,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) {
@@ -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,
@@ -26,6 +27,7 @@ use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem};
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 +222,21 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
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<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -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::{
@@ -75,7 +77,7 @@ use parachains_common::{
HOURS, MAXIMUM_BLOCK_WEIGHT, NORMAL_DISPATCH_RATIO, SLOT_DURATION,
};
// XCM Imports
use xcm::latest::prelude::BodyId;
use xcm::latest::prelude::*;
use xcm_executor::XcmExecutor;
/// The address format for describing accounts.
@@ -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<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -671,9 +673,21 @@ impl_runtime_apis! {
use xcm::latest::prelude::*;
use xcm_config::DotRelayLocation;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = 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 = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(DotRelayLocation::get())
}
@@ -714,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) {
@@ -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,
@@ -26,6 +27,7 @@ use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem};
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 +226,21 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
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<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -75,6 +75,7 @@ use bp_runtime::HeaderId;
pub use sp_runtime::BuildStorage;
use polkadot_runtime_common::{BlockHashCount, SlowAdjustingFeeUpdate};
use xcm::latest::prelude::*;
use weights::{BlockExecutionWeight, ExtrinsicBaseWeight, RocksDbWeight};
@@ -362,6 +363,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::TokenLocation::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<XcmConfig>;
@@ -371,7 +386,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ControllerOrigin = EnsureRoot<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -1014,9 +1029,21 @@ impl_runtime_apis! {
use xcm::latest::prelude::*;
use xcm_config::TokenLocation;
parameter_types! {
pub ExistentialDepositMultiAsset: Option<MultiAsset> = Some((
TokenLocation::get(),
ExistentialDeposit::get()
).into());
}
impl pallet_xcm_benchmarks::Config for Runtime {
type XcmConfig = xcm_config::XcmConfig;
type AccountIdConverter = xcm_config::LocationToAccountId;
type DeliveryHelper = cumulus_primitives_utility::ToParentDeliveryHelper<
XcmConfig,
ExistentialDepositMultiAsset,
xcm_config::PriceForParentDelivery,
>;
fn valid_destination() -> Result<MultiLocation, BenchmarkError> {
Ok(TokenLocation::get())
}
@@ -1057,6 +1084,7 @@ impl_runtime_apis! {
}
impl pallet_xcm_benchmarks::generic::Config for Runtime {
type TransactAsset = Balances;
type RuntimeCall = RuntimeCall;
fn worst_case_response() -> (u64, Response) {
@@ -15,10 +15,10 @@
// along with Cumulus. If not, see <http://www.gnu.org/licenses/>.
use super::{
AccountId, AllPalletsWithSystem, Balances, BridgeGrandpaRococoInstance,
BridgeGrandpaWococoInstance, DeliveryRewardInBalance, ParachainInfo, ParachainSystem,
PolkadotXcm, RequiredStakeForStakeAndSlash, Runtime, RuntimeCall, RuntimeEvent, RuntimeFlavor,
RuntimeOrigin, WeightToFee, XcmpQueue,
AccountId, AllPalletsWithSystem, Balances, BaseDeliveryFee, BridgeGrandpaRococoInstance,
BridgeGrandpaWococoInstance, DeliveryRewardInBalance, FeeAssetId, ParachainInfo,
ParachainSystem, PolkadotXcm, RequiredStakeForStakeAndSlash, Runtime, RuntimeCall,
RuntimeEvent, RuntimeFlavor, RuntimeOrigin, TransactionByteFee, WeightToFee, XcmpQueue,
};
use crate::{
bridge_hub_rococo_config::ToBridgeHubWococoHaulBlobExporter,
@@ -30,9 +30,16 @@ use frame_support::{
};
use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem};
use parachains_common::{
impls::ToStakingPot,
xcm_config::{ConcreteAssetFromSystem, 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_core::Get;
use sp_runtime::traits::AccountIdConversion;
use xcm::latest::prelude::*;
use xcm_builder::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
@@ -41,6 +48,7 @@ use xcm_builder::{
ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative, SiblingParachainConvertsVia,
SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
TrailingSetTopicAsId, UsingComponents, WeightInfoBounds, WithComputedOrigin, WithUniqueTopic,
XcmFeesToAccount,
};
use xcm_executor::{
traits::{ExportXcm, WithOriginFilter},
@@ -55,6 +63,7 @@ parameter_types! {
X2(GlobalConsensus(RelayNetwork::get()), Parachain(ParachainInfo::parachain_id().into()));
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub TreasuryAccount: Option<AccountId> = Some(TREASURY_PALLET_ID.into_account_truncating());
}
/// Adapter for resolving `NetworkId` based on `pub storage Flavor: RuntimeFlavor`.
@@ -253,7 +262,12 @@ impl xcm_executor::Config for XcmConfig {
type SubscriptionService = PolkadotXcm;
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type FeeManager = ();
type FeeManager = XcmFeesToAccount<
Self,
RelayOrOtherSystemParachains<SystemParachains, Runtime>,
AccountId,
TreasuryAccount,
>;
type MessageExporter = BridgeHubRococoOrBridgeHubWococoSwitchExporter;
type UniversalAliases = Nothing;
type CallDispatcher = WithOriginFilter<SafeCallFilter>;
@@ -261,6 +275,9 @@ impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
}
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// Converts a local signed origin into an XCM multilocation.
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
@@ -269,7 +286,7 @@ pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, R
/// queues.
pub type XcmRouter = WithUniqueTopic<(
// Two routers - use UMP to communicate with the relay chain:
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -186,7 +186,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
XcmConfig::AssetTransactor::deposit_asset(
&ed,
&sibling_parachain_location,
&XcmContext::with_message_id([0; 32]),
Some(&XcmContext::with_message_id([0; 32])),
)
.expect("deposited ed");
}
@@ -194,7 +194,7 @@ pub fn handle_export_message_from_system_parachain_to_outbound_queue_works<
XcmConfig::AssetTransactor::deposit_asset(
&fee,
&sibling_parachain_location,
&XcmContext::with_message_id([0; 32]),
Some(&XcmContext::with_message_id([0; 32])),
)
.expect("deposited fee");
@@ -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<XcmConfig>;
@@ -410,7 +425,8 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
type ControllerOrigin = EitherOfDiverse<EnsureRoot<AccountId>, Fellows>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = weights::cumulus_pallet_xcmp_queue::WeightInfo<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery =
polkadot_runtime_common::xcm_sender::NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -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,
@@ -26,6 +27,7 @@ use frame_system::EnsureRoot;
use pallet_xcm::XcmPassthrough;
use parachains_common::{impls::ToStakingPot, xcm_config::ConcreteAssetFromSystem};
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 +281,14 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -54,13 +54,14 @@ pallet-contracts = { path = "../../../../../substrate/frame/contracts", default-
pallet-contracts-primitives = { path = "../../../../../substrate/frame/contracts/primitives", default-features = false}
# Polkadot
pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false}
polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", default-features = false}
polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false}
polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", 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}
pallet-xcm = { path = "../../../../../polkadot/xcm/pallet-xcm", default-features = false }
polkadot-core-primitives = { path = "../../../../../polkadot/core-primitives", default-features = false }
polkadot-parachain-primitives = { path = "../../../../../polkadot/parachain", default-features = false }
polkadot-runtime-common = { path = "../../../../../polkadot/runtime/common", default-features = false }
rococo-runtime-constants = { path = "../../../../../polkadot/runtime/rococo/constants", 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 }
# Cumulus
cumulus-pallet-aura-ext = { path = "../../../../pallets/aura-ext", default-features = false }
@@ -115,6 +116,7 @@ std = [
"polkadot-core-primitives/std",
"polkadot-parachain-primitives/std",
"polkadot-runtime-common/std",
"rococo-runtime-constants/std",
"scale-info/std",
"sp-api/std",
"sp-block-builder/std",
@@ -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<Balances, DealWithFees<Runtime>>;
type WeightToFee = WeightToFee;
/// Relay Chain `TransactionByteFee` / 10
type LengthToFee = ConstantMultiplier<Balance, ConstU128<MILLICENTS>>;
type LengthToFee = ConstantMultiplier<Balance, TransactionByteFee>;
type FeeMultiplierUpdate = SlowAdjustingFeeUpdate<Self>;
type OperationalFeeMultiplier = ConstU8<5>;
}
@@ -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},
@@ -24,8 +25,14 @@ use frame_support::{
};
use frame_system::EnsureRoot;
use pallet_xcm::{EnsureXcm, IsMajorityOfBody, XcmPassthrough};
use parachains_common::xcm_config::ConcreteAssetFromSystem;
use parachains_common::{
xcm_config::{ConcreteAssetFromSystem, 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::*;
use xcm_builder::{
AccountId32Aliases, AllowExplicitUnpaidExecutionFrom, AllowKnownQueryResponses,
@@ -34,7 +41,7 @@ use xcm_builder::{
NativeAsset, ParentAsSuperuser, ParentIsPreset, RelayChainAsNative, SiblingParachainAsNative,
SiblingParachainConvertsVia, SignedAccountId32AsNative, SignedToAccountId32,
SovereignSignedViaLocation, TakeWeightCredit, TrailingSetTopicAsId, UsingComponents,
WithComputedOrigin, WithUniqueTopic,
WithComputedOrigin, WithUniqueTopic, XcmFeesToAccount,
};
use xcm_executor::XcmExecutor;
@@ -44,7 +51,7 @@ parameter_types! {
pub RelayChainOrigin: RuntimeOrigin = cumulus_pallet_xcm::Origin::Relay.into();
pub UniversalLocation: InteriorMultiLocation = Parachain(ParachainInfo::parachain_id().into()).into();
pub const ExecutiveBody: BodyId = BodyId::Executive;
pub CheckingAccount: AccountId = PolkadotXcm::check_account();
pub TreasuryAccount: Option<AccountId> = Some(TREASURY_PALLET_ID.into_account_truncating());
}
/// We allow root and the Relay Chain council to execute privileged collator selection operations.
@@ -167,7 +174,12 @@ impl xcm_executor::Config for XcmConfig {
type MaxAssetsIntoHolding = ConstU32<8>;
type AssetLocker = ();
type AssetExchanger = ();
type FeeManager = ();
type FeeManager = XcmFeesToAccount<
Self,
RelayOrOtherSystemParachains<SystemParachains, Runtime>,
AccountId,
TreasuryAccount,
>;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
@@ -179,11 +191,14 @@ impl xcm_executor::Config for XcmConfig {
/// Forms the basis for local origins sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, RelayNetwork>;
pub type PriceForParentDelivery =
ExponentialPrice<FeeAssetId, BaseDeliveryFee, TransactionByteFee, ParachainSystem>;
/// 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<ParachainSystem, PolkadotXcm, ()>,
cumulus_primitives_utility::ParentAsUmp<ParachainSystem, PolkadotXcm, PriceForParentDelivery>,
// ..and XCMP to communicate with the sibling chains.
XcmpQueue,
)>;
@@ -231,6 +246,20 @@ impl cumulus_pallet_xcm::Config for Runtime {
type XcmExecutor = XcmExecutor<XcmConfig>;
}
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<XcmConfig>;
@@ -243,7 +272,7 @@ impl cumulus_pallet_xcmp_queue::Config for Runtime {
>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = PriceForSiblingParachainDelivery;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -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<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = ();
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
@@ -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",
@@ -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<AccountId>;
type ControllerOriginConverter = XcmOriginToTransactDispatchOrigin;
type WeightInfo = cumulus_pallet_xcmp_queue::weights::SubstrateWeight<Runtime>;
type PriceForSiblingDelivery = ();
type PriceForSiblingDelivery = NoPriceForMessageDelivery<ParaId>;
}
impl cumulus_pallet_dmp_queue::Config for Runtime {
+1 -1
View File
@@ -96,7 +96,7 @@ pub struct ChannelInfo {
pub trait GetChannelInfo {
fn get_channel_status(id: ParaId) -> ChannelStatus;
fn get_channel_max(id: ParaId) -> Option<usize>;
fn get_channel_info(id: ParaId) -> Option<ChannelInfo>;
}
/// Something that should be called when sending an upward message.
+8 -3
View File
@@ -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",
+60 -23
View File
@@ -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<T: Get<MultiAssets>> PriceForParentDelivery for ConstantPrice<T> {
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<T, W, P> SendXcm for ParentAsUmp<T, W, P>
where
T: UpwardMessageSender,
W: WrapVersion,
P: PriceForParentDelivery,
P: PriceForMessageDelivery<Id = ()>,
{
type Ticket = Vec<u8>;
@@ -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<FungiblesMutateAdapter, AccountId, ReceiverAcc
impl<
FungiblesMutateAdapter: TransactAsset,
AccountId: Clone + Into<[u8; 32]>,
ReceiverAccount: frame_support::traits::Get<Option<AccountId>>,
ReceiverAccount: Get<Option<AccountId>>,
> TakeRevenue for XcmFeesTo32ByteAccount<FungiblesMutateAdapter, AccountId, ReceiverAccount>
{
fn take_revenue(revenue: MultiAsset) {
@@ -288,9 +272,7 @@ impl<
let ok = FungiblesMutateAdapter::deposit_asset(
&revenue,
&(X1(AccountId32 { network: None, id: receiver.into() }).into()),
// We aren't able to track the XCM that initiated the fee deposit, so we create a
// fake message hash here
&XcmContext::with_message_id([0; 32]),
None,
)
.is_ok();
@@ -542,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<XcmConfig, ExistentialDeposit, PriceForDelivery>(
sp_std::marker::PhantomData<(XcmConfig, ExistentialDeposit, PriceForDelivery)>,
);
#[cfg(feature = "runtime-benchmarks")]
impl<
XcmConfig: xcm_executor::Config,
ExistentialDeposit: Get<Option<MultiAsset>>,
PriceForDelivery: PriceForMessageDelivery<Id = ()>,
> pallet_xcm_benchmarks::EnsureDelivery
for ToParentDeliveryHelper<XcmConfig, ExistentialDeposit, PriceForDelivery>
{
fn ensure_successful_delivery(
origin_ref: &MultiLocation,
_dest: &MultiLocation,
fee_reason: xcm_executor::traits::FeeReason,
) -> (Option<xcm_executor::FeesMode>, Option<MultiAssets>) {
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<MultiAsset> = 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)
}
}
+3 -3
View File
@@ -1335,10 +1335,10 @@ pub struct TestContext<T, Origin: Chain, Destination: Chain> {
pub args: T,
}
/// Struct that help with tests where either dispatchables or assertions need
/// Struct that helps with tests where either dispatchables or assertions need
/// to be reused. The struct keeps the test's arguments of your choice in the generic `Args`.
/// These arguments can be easily reused and shared between the assertions functions
/// and dispatchables functions, which are also stored in `Test`.
/// These arguments can be easily reused and shared between the assertion functions
/// and dispatchable functions, which are also stored in `Test`.
/// `Origin` corresponds to the chain where the XCM interaction starts with an initial execution.
/// `Destination` corresponds to the last chain where an effect of the intial execution is expected
/// happen. `Hops` refer all the ordered intermediary chains an initial XCM execution can provoke