feat: initialize Kurdistan SDK - independent fork of Polkadot SDK

This commit is contained in:
2025-12-13 15:44:15 +03:00
commit 286de54384
6841 changed files with 1848356 additions and 0 deletions
+777
View File
@@ -0,0 +1,777 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use super::*;
use frame_benchmarking::v2::*;
use frame_support::{assert_ok, weights::Weight};
use frame_system::RawOrigin;
use xcm::{latest::prelude::*, MAX_INSTRUCTIONS_TO_DECODE};
use xcm_builder::EnsureDelivery;
use xcm_executor::traits::FeeReason;
type RuntimeOrigin<T> = <T as frame_system::Config>::RuntimeOrigin;
/// Pallet we're benchmarking here.
pub struct Pallet<T: Config>(crate::Pallet<T>);
/// Trait that must be implemented by runtime to be able to benchmark pallet properly.
pub trait Config: crate::Config + pallet_balances::Config {
/// Helper that ensures successful delivery for extrinsics/benchmarks which need `SendXcm`.
type DeliveryHelper: EnsureDelivery;
/// A `Location` that can be reached via `XcmRouter`. Used only in benchmarks.
///
/// If `None`, the benchmarks that depend on a reachable destination will be skipped.
fn reachable_dest() -> Option<Location> {
None
}
/// A `(Asset, Location)` pair representing asset and the destination it can be
/// teleported to. Used only in benchmarks.
///
/// Implementation should also make sure `dest` is reachable/connected.
///
/// If `None`, the benchmarks that depend on this will default to `Weight::MAX`.
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
None
}
/// A `(Asset, Location)` pair representing asset and the destination it can be
/// reserve-transferred to. Used only in benchmarks.
///
/// Implementation should also make sure `dest` is reachable/connected.
///
/// If `None`, the benchmarks that depend on this will default to `Weight::MAX`.
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
None
}
/// Sets up a complex transfer (usually consisting of a teleport and reserve-based transfer), so
/// that runtime can properly benchmark `transfer_assets()` extrinsic. Should return a tuple
/// `(Asset, AssetId, Location, dyn FnOnce())` representing the assets to transfer, the
/// `AssetId` of the asset to be used for fees, the destination chain for the transfer, and a
/// `verify()` closure to verify the intended transfer side-effects.
///
/// Implementation should make sure the provided assets can be transacted by the runtime, there
/// are enough balances in the involved accounts, and that `dest` is reachable/connected.
///
/// Used only in benchmarks.
///
/// If `None`, the benchmarks that depend on this will default to `Weight::MAX`.
fn set_up_complex_asset_transfer() -> Option<(Assets, AssetId, Location, Box<dyn FnOnce()>)> {
None
}
/// Gets an asset that can be handled by the AssetTransactor.
///
/// Used only in benchmarks.
///
/// Used, for example, in the benchmark for `claim_assets`.
fn get_asset() -> Asset;
}
#[benchmarks]
mod benchmarks {
use super::*;
#[benchmark]
fn send() -> Result<(), BenchmarkError> {
let send_origin =
T::SendXcmOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
if T::SendXcmOrigin::try_origin(send_origin.clone()).is_err() {
return Err(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)));
}
let msg = Xcm(vec![ClearOrigin]);
let versioned_dest: VersionedLocation = T::reachable_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?
.into();
let versioned_msg = VersionedXcm::from(msg);
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&versioned_dest.clone().try_into().unwrap(),
FeeReason::ChargeFees,
);
#[extrinsic_call]
_(send_origin as RuntimeOrigin<T>, Box::new(versioned_dest), Box::new(versioned_msg));
Ok(())
}
#[benchmark]
fn teleport_assets() -> Result<(), BenchmarkError> {
let (asset, destination) = T::teleportable_asset_and_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let assets: Assets = asset.clone().into();
let caller: T::AccountId = whitelisted_caller();
let send_origin = RawOrigin::Signed(caller.clone());
let origin_location = T::ExecuteXcmOrigin::try_origin(send_origin.clone().into())
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
if !T::XcmTeleportFilter::contains(&(origin_location.clone(), assets.clone().into_inner()))
{
return Err(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)));
}
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&origin_location,
&destination,
FeeReason::ChargeFees,
);
match &asset.fun {
Fungible(amount) => {
// Add transferred_amount to origin
<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::deposit_asset(
&Asset { fun: Fungible(*amount), id: asset.id.clone() },
&origin_location,
None,
)
.map_err(|error| {
tracing::error!("Fungible asset couldn't be deposited, error: {:?}", error);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?;
},
NonFungible(_instance) => {
<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::deposit_asset(
&asset,
&origin_location,
None,
)
.map_err(|error| {
tracing::error!("Nonfungible asset couldn't be deposited, error: {:?}", error);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?;
},
};
let recipient = [0u8; 32];
let versioned_dest: VersionedLocation = destination.into();
let versioned_beneficiary: VersionedLocation =
AccountId32 { network: None, id: recipient.into() }.into();
let versioned_assets: VersionedAssets = assets.into();
let fee_asset_id: AssetId = asset.id;
#[extrinsic_call]
_(
send_origin,
Box::new(versioned_dest),
Box::new(versioned_beneficiary),
Box::new(versioned_assets),
Box::new(fee_asset_id.into()),
);
Ok(())
}
#[benchmark]
fn reserve_transfer_assets() -> Result<(), BenchmarkError> {
let (asset, destination) = T::reserve_transferable_asset_and_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let assets: Assets = asset.clone().into();
let caller: T::AccountId = whitelisted_caller();
let send_origin = RawOrigin::Signed(caller.clone());
let origin_location = T::ExecuteXcmOrigin::try_origin(send_origin.clone().into())
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
if !T::XcmReserveTransferFilter::contains(&(
origin_location.clone(),
assets.clone().into_inner(),
)) {
return Err(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)));
}
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
let (_, _) = T::DeliveryHelper::ensure_successful_delivery(
&origin_location,
&destination,
FeeReason::ChargeFees,
);
match &asset.fun {
Fungible(amount) => {
// Add transferred_amount to origin
<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::deposit_asset(
&Asset { fun: Fungible(*amount), id: asset.id.clone() },
&origin_location,
None,
)
.map_err(|error| {
tracing::error!("Fungible asset couldn't be deposited, error: {:?}", error);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?;
},
NonFungible(_instance) => {
<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::deposit_asset(
&asset,
&origin_location,
None,
)
.map_err(|error| {
tracing::error!("Nonfungible asset couldn't be deposited, error: {:?}", error);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?;
},
};
let recipient = [0u8; 32];
let versioned_dest: VersionedLocation = destination.clone().into();
let versioned_beneficiary: VersionedLocation =
AccountId32 { network: None, id: recipient.into() }.into();
let versioned_assets: VersionedAssets = assets.into();
let fee_asset_id: AssetId = asset.id.clone();
#[extrinsic_call]
_(
send_origin,
Box::new(versioned_dest),
Box::new(versioned_beneficiary),
Box::new(versioned_assets),
Box::new(fee_asset_id.into()),
);
match &asset.fun {
Fungible(amount) => {
assert_ok!(<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::withdraw_asset(
&Asset { fun: Fungible(*amount), id: asset.id },
&destination,
None,
));
},
NonFungible(_instance) => {
assert_ok!(<T::XcmExecutor as XcmAssetTransfers>::AssetTransactor::withdraw_asset(
&asset,
&destination,
None,
));
},
};
Ok(())
}
#[benchmark]
fn transfer_assets() -> Result<(), BenchmarkError> {
let (assets, fee_asset_id, destination, verify_fn) = T::set_up_complex_asset_transfer()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let caller: T::AccountId = whitelisted_caller();
let send_origin = RawOrigin::Signed(caller.clone());
let recipient = [0u8; 32];
let versioned_dest: VersionedLocation = destination.into();
let versioned_beneficiary: VersionedLocation =
AccountId32 { network: None, id: recipient.into() }.into();
let versioned_assets: VersionedAssets = assets.into();
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&versioned_dest.clone().try_into().unwrap(),
FeeReason::ChargeFees,
);
#[extrinsic_call]
_(
send_origin,
Box::new(versioned_dest),
Box::new(versioned_beneficiary),
Box::new(versioned_assets),
Box::new(fee_asset_id.into()),
WeightLimit::Unlimited,
);
// run provided verification function
verify_fn();
Ok(())
}
#[benchmark]
fn execute() -> Result<(), BenchmarkError> {
let execute_origin =
T::ExecuteXcmOrigin::try_successful_origin().map_err(|_| BenchmarkError::Weightless)?;
let origin_location = T::ExecuteXcmOrigin::try_origin(execute_origin.clone())
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let msg = Xcm(vec![ClearOrigin]);
if !T::XcmExecuteFilter::contains(&(origin_location, msg.clone())) {
return Err(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)));
}
let versioned_msg = VersionedXcm::from(msg);
#[extrinsic_call]
_(execute_origin as RuntimeOrigin<T>, Box::new(versioned_msg), Weight::MAX);
Ok(())
}
#[benchmark]
fn force_xcm_version() -> Result<(), BenchmarkError> {
let loc = T::reachable_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let xcm_version = 2;
#[extrinsic_call]
_(RawOrigin::Root, Box::new(loc), xcm_version);
Ok(())
}
#[benchmark]
fn force_default_xcm_version() {
#[extrinsic_call]
_(RawOrigin::Root, Some(2))
}
#[benchmark]
fn force_subscribe_version_notify() -> Result<(), BenchmarkError> {
let versioned_loc: VersionedLocation = T::reachable_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?
.into();
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&versioned_loc.clone().try_into().unwrap(),
FeeReason::ChargeFees,
);
#[extrinsic_call]
_(RawOrigin::Root, Box::new(versioned_loc));
Ok(())
}
#[benchmark]
fn force_unsubscribe_version_notify() -> Result<(), BenchmarkError> {
let loc = T::reachable_dest()
.ok_or(BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let versioned_loc: VersionedLocation = loc.clone().into();
// Ensure that origin can send to destination
// (e.g. setup delivery fees, ensure router setup, ...)
T::DeliveryHelper::ensure_successful_delivery(
&Default::default(),
&versioned_loc.clone().try_into().unwrap(),
FeeReason::ChargeFees,
);
let _ = crate::Pallet::<T>::request_version_notify(loc);
#[extrinsic_call]
_(RawOrigin::Root, Box::new(versioned_loc));
Ok(())
}
#[benchmark]
fn force_suspension() {
#[extrinsic_call]
_(RawOrigin::Root, true)
}
#[benchmark]
fn migrate_supported_version() {
let old_version = XCM_VERSION - 1;
let loc = VersionedLocation::from(Location::from(Parent));
SupportedVersion::<T>::insert(old_version, loc, old_version);
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::MigrateSupportedVersion,
Weight::zero(),
);
}
}
#[benchmark]
fn migrate_version_notifiers() {
let old_version = XCM_VERSION - 1;
let loc = VersionedLocation::from(Location::from(Parent));
VersionNotifiers::<T>::insert(old_version, loc, 0);
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::MigrateVersionNotifiers,
Weight::zero(),
);
}
}
#[benchmark]
fn already_notified_target() -> Result<(), BenchmarkError> {
let loc = T::reachable_dest().ok_or(BenchmarkError::Override(
BenchmarkResult::from_weight(T::DbWeight::get().reads(1)),
))?;
let loc = VersionedLocation::from(loc);
let current_version = T::AdvertisedXcmVersion::get();
VersionNotifyTargets::<T>::insert(
current_version,
loc,
(0, Weight::zero(), current_version),
);
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::NotifyCurrentTargets(None),
Weight::zero(),
);
}
Ok(())
}
#[benchmark]
fn notify_current_targets() -> Result<(), BenchmarkError> {
let loc = T::reachable_dest().ok_or(BenchmarkError::Override(
BenchmarkResult::from_weight(T::DbWeight::get().reads_writes(1, 3)),
))?;
let loc = VersionedLocation::from(loc);
let current_version = T::AdvertisedXcmVersion::get();
let old_version = current_version - 1;
VersionNotifyTargets::<T>::insert(current_version, loc, (0, Weight::zero(), old_version));
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::NotifyCurrentTargets(None),
Weight::zero(),
);
}
Ok(())
}
#[benchmark]
fn notify_target_migration_fail() {
let newer_xcm_version = xcm::prelude::XCM_VERSION;
let older_xcm_version = newer_xcm_version - 1;
let bad_location: Location = Plurality { id: BodyId::Unit, part: BodyPart::Voice }.into();
let bad_location = VersionedLocation::from(bad_location)
.into_version(older_xcm_version)
.expect("Version conversion should work");
let current_version = T::AdvertisedXcmVersion::get();
VersionNotifyTargets::<T>::insert(
current_version,
bad_location,
(0, Weight::zero(), current_version),
);
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::MigrateAndNotifyOldTargets,
Weight::zero(),
);
}
}
#[benchmark]
fn migrate_version_notify_targets() {
let current_version = T::AdvertisedXcmVersion::get();
let old_version = current_version - 1;
let loc = VersionedLocation::from(Location::from(Parent));
VersionNotifyTargets::<T>::insert(old_version, loc, (0, Weight::zero(), current_version));
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::MigrateAndNotifyOldTargets,
Weight::zero(),
);
}
}
#[benchmark]
fn migrate_and_notify_old_targets() -> Result<(), BenchmarkError> {
let loc = T::reachable_dest().ok_or(BenchmarkError::Override(
BenchmarkResult::from_weight(T::DbWeight::get().reads_writes(1, 3)),
))?;
let loc = VersionedLocation::from(loc);
let old_version = T::AdvertisedXcmVersion::get() - 1;
VersionNotifyTargets::<T>::insert(old_version, loc, (0, Weight::zero(), old_version));
#[block]
{
crate::Pallet::<T>::lazy_migration(
VersionMigrationStage::MigrateAndNotifyOldTargets,
Weight::zero(),
);
}
Ok(())
}
#[benchmark]
fn new_query() {
let responder = Location::from(Parent);
let timeout = 1u32.into();
let match_querier = Location::from(Here);
#[block]
{
crate::Pallet::<T>::new_query(responder, timeout, match_querier);
}
}
#[benchmark]
fn take_response() {
let responder = Location::from(Parent);
let timeout = 1u32.into();
let match_querier = Location::from(Here);
let query_id = crate::Pallet::<T>::new_query(responder, timeout, match_querier);
let infos = (0..xcm::v3::MaxPalletsInfo::get())
.map(|_| {
PalletInfo::new(
u32::MAX,
(0..xcm::v3::MaxPalletNameLen::get())
.map(|_| 97u8)
.collect::<Vec<_>>()
.try_into()
.unwrap(),
(0..xcm::v3::MaxPalletNameLen::get())
.map(|_| 97u8)
.collect::<Vec<_>>()
.try_into()
.unwrap(),
u32::MAX,
u32::MAX,
u32::MAX,
)
.unwrap()
})
.collect::<Vec<_>>();
crate::Pallet::<T>::expect_response(
query_id,
Response::PalletsInfo(infos.try_into().unwrap()),
);
#[block]
{
<crate::Pallet<T> as QueryHandler>::take_response(query_id);
}
}
#[benchmark]
fn claim_assets() -> Result<(), BenchmarkError> {
let claim_origin = RawOrigin::Signed(whitelisted_caller());
let claim_location = T::ExecuteXcmOrigin::try_origin(claim_origin.clone().into())
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
let asset: Asset = T::get_asset();
// Trap assets for claiming later
crate::Pallet::<T>::drop_assets(
&claim_location,
asset.clone().into(),
&XcmContext { origin: None, message_id: [0u8; 32], topic: None },
);
let versioned_assets = VersionedAssets::from(Assets::from(asset));
#[extrinsic_call]
_(
claim_origin,
Box::new(versioned_assets),
Box::new(VersionedLocation::from(claim_location)),
);
Ok(())
}
#[benchmark]
fn add_authorized_alias() -> Result<(), BenchmarkError> {
let who: T::AccountId = whitelisted_caller();
let origin = RawOrigin::Signed(who.clone());
let origin_location: VersionedLocation =
T::ExecuteXcmOrigin::try_origin(origin.clone().into())
.map_err(|_| {
tracing::error!(
target: "xcm::benchmarking::pallet_xcm::add_authorized_alias",
?origin,
"try_origin failed",
);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?
.into();
// Give some multiple of ED
let balance = T::ExistentialDeposit::get() * 1000000u32.into();
let _ =
<pallet_balances::Pallet::<T> as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
let mut existing_aliases = BoundedVec::<OriginAliaser, MaxAuthorizedAliases>::new();
// prepopulate list with `max-1` aliases to benchmark worst case
for i in 1..MaxAuthorizedAliases::get() {
let alias =
Location::new(1, [Teyrchain(i), AccountId32 { network: None, id: [42_u8; 32] }])
.into();
let aliaser = OriginAliaser { location: alias, expiry: None };
existing_aliases.try_push(aliaser).unwrap()
}
let footprint = aliasers_footprint(existing_aliases.len());
let ticket = TicketOf::<T>::new(&who, footprint).map_err(|e| {
tracing::error!(
target: "xcm::benchmarking::pallet_xcm::add_authorized_alias",
?who,
?footprint,
error=?e,
"could not create ticket",
);
BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX))
})?;
let entry = AuthorizedAliasesEntry { aliasers: existing_aliases, ticket };
AuthorizedAliases::<T>::insert(&origin_location, entry);
// now benchmark adding new alias
let aliaser: VersionedLocation =
Location::new(1, [Teyrchain(1234), AccountId32 { network: None, id: [42_u8; 32] }])
.into();
#[extrinsic_call]
_(origin, Box::new(aliaser), None);
Ok(())
}
#[benchmark]
fn remove_authorized_alias() -> Result<(), BenchmarkError> {
let who: T::AccountId = whitelisted_caller();
let origin = RawOrigin::Signed(who.clone());
let error = BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX));
let origin_location =
T::ExecuteXcmOrigin::try_origin(origin.clone().into()).map_err(|_| {
tracing::error!(
target: "xcm::benchmarking::pallet_xcm::remove_authorized_alias",
?origin,
"try_origin failed",
);
error.clone()
})?;
// remove `network` from inner `AccountId32` for easier matching of automatic AccountId ->
// Location conversions.
let origin_location: VersionedLocation = match origin_location.unpack() {
(0, [AccountId32 { network: _, id }]) =>
Location::new(0, [AccountId32 { network: None, id: *id }]).into(),
_ => {
tracing::error!(
target: "xcm::benchmarking::pallet_xcm::remove_authorized_alias",
?origin_location,
"unexpected origin failed",
);
return Err(error.clone());
},
};
// Give some multiple of ED
let balance = T::ExistentialDeposit::get() * 1000000u32.into();
let _ =
<pallet_balances::Pallet::<T> as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
let mut existing_aliases = BoundedVec::<OriginAliaser, MaxAuthorizedAliases>::new();
// prepopulate list with `max` aliases to benchmark worst case
for i in 1..MaxAuthorizedAliases::get() + 1 {
let alias =
Location::new(1, [Teyrchain(i), AccountId32 { network: None, id: [42_u8; 32] }])
.into();
let aliaser = OriginAliaser { location: alias, expiry: None };
existing_aliases.try_push(aliaser).unwrap()
}
let footprint = aliasers_footprint(existing_aliases.len());
let ticket = TicketOf::<T>::new(&who, footprint).map_err(|e| {
tracing::error!(
target: "xcm::benchmarking::pallet_xcm::remove_authorized_alias",
?who,
?footprint,
error=?e,
"could not create ticket",
);
error
})?;
let entry = AuthorizedAliasesEntry { aliasers: existing_aliases, ticket };
AuthorizedAliases::<T>::insert(&origin_location, entry);
// now benchmark removing an alias
let aliaser_to_remove: VersionedLocation =
Location::new(1, [Teyrchain(1), AccountId32 { network: None, id: [42_u8; 32] }]).into();
#[extrinsic_call]
_(origin, Box::new(aliaser_to_remove));
Ok(())
}
#[benchmark]
fn weigh_message() -> Result<(), BenchmarkError> {
let msg = Xcm(vec![ClearOrigin; MAX_INSTRUCTIONS_TO_DECODE.into()]);
let versioned_msg = VersionedXcm::from(msg);
#[block]
{
crate::Pallet::<T>::query_xcm_weight(versioned_msg)
.map_err(|_| BenchmarkError::Override(BenchmarkResult::from_weight(Weight::MAX)))?;
}
Ok(())
}
impl_benchmark_test_suite!(
Pallet,
crate::mock::new_test_ext_with_balances(Vec::new()),
crate::mock::Test
);
}
pub mod helpers {
use super::*;
pub fn native_teleport_as_asset_transfer<T>(
native_asset_location: Location,
destination: Location,
) -> Option<(Assets, AssetId, Location, Box<dyn FnOnce()>)>
where
T: Config + pallet_balances::Config,
u128: From<<T as pallet_balances::Config>::Balance>,
{
// Relay/native token can be teleported to/from AH.
let amount = T::ExistentialDeposit::get() * 100u32.into();
let assets: Assets =
Asset { fun: Fungible(amount.into()), id: AssetId(native_asset_location.clone()) }
.into();
let fee_asset_id: AssetId = AssetId(native_asset_location);
// Give some multiple of transferred amount
let balance = amount * 10u32.into();
let who = whitelisted_caller();
let _ =
<pallet_balances::Pallet::<T> as frame_support::traits::Currency<_>>::make_free_balance_be(&who, balance);
// verify initial balance
assert_eq!(pallet_balances::Pallet::<T>::free_balance(&who), balance);
// verify transferred successfully
let verify = Box::new(move || {
// verify balance after transfer, decreased by transferred amount (and delivery fees)
assert!(pallet_balances::Pallet::<T>::free_balance(&who) <= balance - amount);
});
Some((assets, fee_asset_id, destination, verify))
}
}
+208
View File
@@ -0,0 +1,208 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Errors for the XCM pallet.
use codec::{Decode, DecodeWithMemTracking, Encode};
use frame_support::PalletError;
use scale_info::TypeInfo;
use xcm::latest::Error as XcmError;
#[derive(
Copy, Clone, Encode, Decode, DecodeWithMemTracking, Eq, PartialEq, Debug, TypeInfo, PalletError,
)]
pub enum ExecutionError {
// Errors that happen due to instructions being executed. These alone are defined in the
// XCM specification.
/// An arithmetic overflow happened.
#[codec(index = 0)]
Overflow,
/// The instruction is intentionally unsupported.
#[codec(index = 1)]
Unimplemented,
/// Origin Register does not contain a value value for a reserve transfer notification.
#[codec(index = 2)]
UntrustedReserveLocation,
/// Origin Register does not contain a value value for a teleport notification.
#[codec(index = 3)]
UntrustedTeleportLocation,
/// `MultiLocation` value too large to descend further.
#[codec(index = 4)]
LocationFull,
/// `MultiLocation` value ascend more parents than known ancestors of local location.
#[codec(index = 5)]
LocationNotInvertible,
/// The Origin Register does not contain a valid value for instruction.
#[codec(index = 6)]
BadOrigin,
/// The location parameter is not a valid value for the instruction.
#[codec(index = 7)]
InvalidLocation,
/// The given asset is not handled.
#[codec(index = 8)]
AssetNotFound,
/// An asset transaction (like withdraw or deposit) failed (typically due to type conversions).
#[codec(index = 9)]
FailedToTransactAsset,
/// An asset cannot be withdrawn, potentially due to lack of ownership, availability or rights.
#[codec(index = 10)]
NotWithdrawable,
/// An asset cannot be deposited under the ownership of a particular location.
#[codec(index = 11)]
LocationCannotHold,
/// Attempt to send a message greater than the maximum supported by the transport protocol.
#[codec(index = 12)]
ExceedsMaxMessageSize,
/// The given message cannot be translated into a format supported by the destination.
#[codec(index = 13)]
DestinationUnsupported,
/// Destination is routable, but there is some issue with the transport mechanism.
#[codec(index = 14)]
Transport,
/// Destination is known to be unroutable.
#[codec(index = 15)]
Unroutable,
/// Used by `ClaimAsset` when the given claim could not be recognized/found.
#[codec(index = 16)]
UnknownClaim,
/// Used by `Transact` when the functor cannot be decoded.
#[codec(index = 17)]
FailedToDecode,
/// Used by `Transact` to indicate that the given weight limit could be breached by the
/// functor.
#[codec(index = 18)]
MaxWeightInvalid,
/// Used by `BuyExecution` when the Holding Register does not contain payable fees.
#[codec(index = 19)]
NotHoldingFees,
/// Used by `BuyExecution` when the fees declared to purchase weight are insufficient.
#[codec(index = 20)]
TooExpensive,
/// Used by the `Trap` instruction to force an error intentionally. Its code is included.
#[codec(index = 21)]
Trap,
/// Used by `ExpectAsset`, `ExpectError` and `ExpectOrigin` when the expectation was not true.
#[codec(index = 22)]
ExpectationFalse,
/// The provided pallet index was not found.
#[codec(index = 23)]
PalletNotFound,
/// The given pallet's name is different to that expected.
#[codec(index = 24)]
NameMismatch,
/// The given pallet's version has an incompatible version to that expected.
#[codec(index = 25)]
VersionIncompatible,
/// The given operation would lead to an overflow of the Holding Register.
#[codec(index = 26)]
HoldingWouldOverflow,
/// The message was unable to be exported.
#[codec(index = 27)]
ExportError,
/// `MultiLocation` value failed to be reanchored.
#[codec(index = 28)]
ReanchorFailed,
/// No deal is possible under the given constraints.
#[codec(index = 29)]
NoDeal,
/// Fees were required which the origin could not pay.
#[codec(index = 30)]
FeesNotMet,
/// Some other error with locking.
#[codec(index = 31)]
LockError,
/// The state was not in a condition where the operation was valid to make.
#[codec(index = 32)]
NoPermission,
/// The universal location of the local consensus is improper.
#[codec(index = 33)]
Unanchored,
/// An asset cannot be deposited, probably because (too much of) it already exists.
#[codec(index = 34)]
NotDepositable,
/// Too many assets matched the given asset filter.
#[codec(index = 35)]
TooManyAssets,
// Errors that happen prior to instructions being executed. These fall outside of the XCM
// spec.
/// XCM version not able to be handled.
UnhandledXcmVersion,
/// Execution of the XCM would potentially result in a greater weight used than weight limit.
WeightLimitReached,
/// The XCM did not pass the barrier condition for execution.
///
/// The barrier condition differs on different chains and in different circumstances, but
/// generally it means that the conditions surrounding the message were not such that the chain
/// considers the message worth spending time executing. Since most chains lift the barrier to
/// execution on appropriate payment, presentation of an NFT voucher, or based on the message
/// origin, it means that none of those were the case.
Barrier,
/// The weight of an XCM message is not computable ahead of execution.
WeightNotComputable,
/// Recursion stack limit reached
// TODO(https://github.com/pezkuwichain/pezkuwi-sdk/issues/148): This should have a fixed index since
// we use it in `FrameTransactionalProcessor` // which is used in instructions.
// Or we should create a different error for that.
ExceedsStackLimit,
}
impl From<XcmError> for ExecutionError {
fn from(error: XcmError) -> Self {
match error {
XcmError::Overflow => Self::Overflow,
XcmError::Unimplemented => Self::Unimplemented,
XcmError::UntrustedReserveLocation => Self::UntrustedReserveLocation,
XcmError::UntrustedTeleportLocation => Self::UntrustedTeleportLocation,
XcmError::LocationFull => Self::LocationFull,
XcmError::LocationNotInvertible => Self::LocationNotInvertible,
XcmError::BadOrigin => Self::BadOrigin,
XcmError::InvalidLocation => Self::InvalidLocation,
XcmError::AssetNotFound => Self::AssetNotFound,
XcmError::FailedToTransactAsset(_) => Self::FailedToTransactAsset,
XcmError::NotWithdrawable => Self::NotWithdrawable,
XcmError::LocationCannotHold => Self::LocationCannotHold,
XcmError::ExceedsMaxMessageSize => Self::ExceedsMaxMessageSize,
XcmError::DestinationUnsupported => Self::DestinationUnsupported,
XcmError::Transport(_) => Self::Transport,
XcmError::Unroutable => Self::Unroutable,
XcmError::UnknownClaim => Self::UnknownClaim,
XcmError::FailedToDecode => Self::FailedToDecode,
XcmError::MaxWeightInvalid => Self::MaxWeightInvalid,
XcmError::NotHoldingFees => Self::NotHoldingFees,
XcmError::TooExpensive => Self::TooExpensive,
XcmError::Trap(_) => Self::Trap,
XcmError::ExpectationFalse => Self::ExpectationFalse,
XcmError::PalletNotFound => Self::PalletNotFound,
XcmError::NameMismatch => Self::NameMismatch,
XcmError::VersionIncompatible => Self::VersionIncompatible,
XcmError::HoldingWouldOverflow => Self::HoldingWouldOverflow,
XcmError::ExportError => Self::ExportError,
XcmError::ReanchorFailed => Self::ReanchorFailed,
XcmError::NoDeal => Self::NoDeal,
XcmError::FeesNotMet => Self::FeesNotMet,
XcmError::LockError => Self::LockError,
XcmError::NoPermission => Self::NoPermission,
XcmError::Unanchored => Self::Unanchored,
XcmError::NotDepositable => Self::NotDepositable,
XcmError::TooManyAssets => Self::TooManyAssets,
XcmError::UnhandledXcmVersion => Self::UnhandledXcmVersion,
XcmError::WeightLimitReached(_) => Self::WeightLimitReached,
XcmError::Barrier => Self::Barrier,
XcmError::WeightNotComputable => Self::WeightNotComputable,
XcmError::ExceedsStackLimit => Self::ExceedsStackLimit,
}
}
}
File diff suppressed because it is too large Load Diff
+542
View File
@@ -0,0 +1,542 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
use crate::{
pallet::CurrentMigration, Config, CurrentXcmVersion, Pallet, VersionMigrationStage,
VersionNotifyTargets,
};
use frame_support::{
pallet_prelude::*,
traits::{OnRuntimeUpgrade, StorageVersion, UncheckedOnRuntimeUpgrade},
weights::Weight,
};
const DEFAULT_PROOF_SIZE: u64 = 64 * 1024;
/// Utilities for handling XCM version migration for the relevant data.
pub mod data {
use crate::*;
/// A trait for handling XCM versioned data migration for the requested `XcmVersion`.
pub(crate) trait NeedsMigration {
type MigratedData;
/// Returns true if data does not match `minimal_allowed_xcm_version`.
fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool;
/// Attempts to migrate data. `Ok(None)` means no migration is needed.
/// `Ok(Some(Self::MigratedData))` should contain the migrated data.
fn try_migrate(self, to_xcm_version: XcmVersion) -> Result<Option<Self::MigratedData>, ()>;
}
/// Implementation of `NeedsMigration` for `LockedFungibles` data.
impl<B, M> NeedsMigration for BoundedVec<(B, VersionedLocation), M> {
type MigratedData = Self;
fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool {
self.iter()
.any(|(_, unlocker)| unlocker.identify_version() < minimal_allowed_xcm_version)
}
fn try_migrate(
mut self,
to_xcm_version: XcmVersion,
) -> Result<Option<Self::MigratedData>, ()> {
let mut was_modified = false;
for locked in self.iter_mut() {
if locked.1.identify_version() < to_xcm_version {
let Ok(new_unlocker) = locked.1.clone().into_version(to_xcm_version) else {
return Err(());
};
locked.1 = new_unlocker;
was_modified = true;
}
}
if was_modified {
Ok(Some(self))
} else {
Ok(None)
}
}
}
/// Implementation of `NeedsMigration` for `Queries` data.
impl<BlockNumber> NeedsMigration for QueryStatus<BlockNumber> {
type MigratedData = Self;
fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool {
match &self {
QueryStatus::Pending { responder, maybe_match_querier, .. } =>
responder.identify_version() < minimal_allowed_xcm_version ||
maybe_match_querier
.as_ref()
.map(|v| v.identify_version() < minimal_allowed_xcm_version)
.unwrap_or(false),
QueryStatus::VersionNotifier { origin, .. } =>
origin.identify_version() < minimal_allowed_xcm_version,
QueryStatus::Ready { response, .. } =>
response.identify_version() < minimal_allowed_xcm_version,
}
}
fn try_migrate(self, to_xcm_version: XcmVersion) -> Result<Option<Self::MigratedData>, ()> {
if !self.needs_migration(to_xcm_version) {
return Ok(None);
}
// do migration
match self {
QueryStatus::Pending { responder, maybe_match_querier, maybe_notify, timeout } => {
let Ok(responder) = responder.into_version(to_xcm_version) else {
return Err(());
};
let Ok(maybe_match_querier) =
maybe_match_querier.map(|mmq| mmq.into_version(to_xcm_version)).transpose()
else {
return Err(());
};
Ok(Some(QueryStatus::Pending {
responder,
maybe_match_querier,
maybe_notify,
timeout,
}))
},
QueryStatus::VersionNotifier { origin, is_active } => origin
.into_version(to_xcm_version)
.map(|origin| Some(QueryStatus::VersionNotifier { origin, is_active })),
QueryStatus::Ready { response, at } => response
.into_version(to_xcm_version)
.map(|response| Some(QueryStatus::Ready { response, at })),
}
}
}
/// Implementation of `NeedsMigration` for `RemoteLockedFungibles` key type.
impl<A> NeedsMigration for (XcmVersion, A, VersionedAssetId) {
type MigratedData = Self;
fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool {
self.0 < minimal_allowed_xcm_version ||
self.2.identify_version() < minimal_allowed_xcm_version
}
fn try_migrate(self, to_xcm_version: XcmVersion) -> Result<Option<Self::MigratedData>, ()> {
if !self.needs_migration(to_xcm_version) {
return Ok(None);
}
let Ok(asset_id) = self.2.into_version(to_xcm_version) else { return Err(()) };
Ok(Some((to_xcm_version, self.1, asset_id)))
}
}
/// Implementation of `NeedsMigration` for `RemoteLockedFungibles` data.
impl<ConsumerIdentifier, MaxConsumers: Get<u32>> NeedsMigration
for RemoteLockedFungibleRecord<ConsumerIdentifier, MaxConsumers>
{
type MigratedData = Self;
fn needs_migration(&self, minimal_allowed_xcm_version: XcmVersion) -> bool {
self.owner.identify_version() < minimal_allowed_xcm_version ||
self.locker.identify_version() < minimal_allowed_xcm_version
}
fn try_migrate(self, to_xcm_version: XcmVersion) -> Result<Option<Self::MigratedData>, ()> {
if !self.needs_migration(to_xcm_version) {
return Ok(None);
}
let RemoteLockedFungibleRecord { amount, owner, locker, consumers } = self;
let Ok(owner) = owner.into_version(to_xcm_version) else { return Err(()) };
let Ok(locker) = locker.into_version(to_xcm_version) else { return Err(()) };
Ok(Some(RemoteLockedFungibleRecord { amount, owner, locker, consumers }))
}
}
/// Implementation of `NeedsMigration` for `AuthorizedAliases` data.
impl<M: Get<u32>, T: Config> NeedsMigration
for (&VersionedLocation, AuthorizedAliasesEntry<TicketOf<T>, M>, PhantomData<T>)
{
type MigratedData = (VersionedLocation, AuthorizedAliasesEntry<TicketOf<T>, M>);
fn needs_migration(&self, required_version: XcmVersion) -> bool {
self.0.identify_version() != required_version ||
self.1
.aliasers
.iter()
.any(|alias| alias.location.identify_version() != required_version)
}
fn try_migrate(
self,
required_version: XcmVersion,
) -> Result<Option<Self::MigratedData>, ()> {
if !self.needs_migration(required_version) {
return Ok(None);
}
let key = if self.0.identify_version() != required_version {
let Ok(converted_key) = self.0.clone().into_version(required_version) else {
return Err(());
};
converted_key
} else {
self.0.clone()
};
let mut new_aliases = BoundedVec::<OriginAliaser, M>::new();
let (aliasers, ticket) = (self.1.aliasers, self.1.ticket);
for alias in aliasers {
let OriginAliaser { mut location, expiry } = alias.clone();
if location.identify_version() != required_version {
location = location.into_version(required_version)?;
}
new_aliases.try_push(OriginAliaser { location, expiry }).map_err(|_| ())?;
}
Ok(Some((key, AuthorizedAliasesEntry { aliasers: new_aliases, ticket })))
}
}
impl<T: Config> Pallet<T> {
/// Migrates relevant data to the `required_xcm_version`.
pub(crate) fn migrate_data_to_xcm_version(
weight: &mut Weight,
required_xcm_version: XcmVersion,
) {
const LOG_TARGET: &str = "runtime::xcm::pallet_xcm::migrate_data_to_xcm_version";
// check and migrate `Queries`
let queries_to_migrate = Queries::<T>::iter().filter_map(|(id, data)| {
weight.saturating_add(T::DbWeight::get().reads(1));
match data.try_migrate(required_xcm_version) {
Ok(Some(new_data)) => Some((id, new_data)),
Ok(None) => None,
Err(_) => {
tracing::error!(
target: LOG_TARGET,
?id,
?required_xcm_version,
"`Queries` cannot be migrated!"
);
None
},
}
});
for (id, new_data) in queries_to_migrate {
tracing::info!(
target: LOG_TARGET,
query_id = ?id,
?new_data,
"Migrating `Queries`"
);
Queries::<T>::insert(id, new_data);
weight.saturating_add(T::DbWeight::get().writes(1));
}
// check and migrate `LockedFungibles`
let locked_fungibles_to_migrate =
LockedFungibles::<T>::iter().filter_map(|(id, data)| {
weight.saturating_add(T::DbWeight::get().reads(1));
match data.try_migrate(required_xcm_version) {
Ok(Some(new_data)) => Some((id, new_data)),
Ok(None) => None,
Err(_) => {
tracing::error!(
target: LOG_TARGET,
?id,
?required_xcm_version,
"`LockedFungibles` cannot be migrated!"
);
None
},
}
});
for (id, new_data) in locked_fungibles_to_migrate {
tracing::info!(
target: LOG_TARGET,
account_id = ?id,
?new_data,
"Migrating `LockedFungibles`"
);
LockedFungibles::<T>::insert(id, new_data);
weight.saturating_add(T::DbWeight::get().writes(1));
}
// check and migrate `RemoteLockedFungibles` - 1. step - just data
let remote_locked_fungibles_to_migrate =
RemoteLockedFungibles::<T>::iter().filter_map(|(id, data)| {
weight.saturating_add(T::DbWeight::get().reads(1));
match data.try_migrate(required_xcm_version) {
Ok(Some(new_data)) => Some((id, new_data)),
Ok(None) => None,
Err(_) => {
tracing::error!(
target: LOG_TARGET,
?id,
?required_xcm_version,
"`RemoteLockedFungibles` data cannot be migrated!"
);
None
},
}
});
for (id, new_data) in remote_locked_fungibles_to_migrate {
tracing::info!(
target: LOG_TARGET,
key = ?id,
amount = ?new_data.amount,
locker = ?new_data.locker,
owner = ?new_data.owner,
consumers_count = ?new_data.consumers.len(),
"Migrating `RemoteLockedFungibles` data"
);
RemoteLockedFungibles::<T>::insert(id, new_data);
weight.saturating_add(T::DbWeight::get().writes(1));
}
// check and migrate `RemoteLockedFungibles` - 2. step - key
let remote_locked_fungibles_keys_to_migrate = RemoteLockedFungibles::<T>::iter_keys()
.filter_map(|key| {
if key.needs_migration(required_xcm_version) {
let old_key = key.clone();
match key.try_migrate(required_xcm_version) {
Ok(Some(new_key)) => Some((old_key, new_key)),
Ok(None) => None,
Err(_) => {
tracing::error!(
target: LOG_TARGET,
id = ?old_key,
?required_xcm_version,
"`RemoteLockedFungibles` key cannot be migrated!"
);
None
},
}
} else {
None
}
});
for (old_key, new_key) in remote_locked_fungibles_keys_to_migrate {
weight.saturating_add(T::DbWeight::get().reads(1));
// make sure, that we don't override accidentally other data
if RemoteLockedFungibles::<T>::get(&new_key).is_some() {
tracing::error!(
target: LOG_TARGET,
?old_key,
?new_key,
"`RemoteLockedFungibles` already contains data for a `new_key`!"
);
// let's just skip for now, could be potentially caused with missing this
// migration before (manual clean-up?).
continue;
}
tracing::info!(
target: LOG_TARGET,
?old_key,
?new_key,
"Migrating `RemoteLockedFungibles` key"
);
// now we can swap the keys
RemoteLockedFungibles::<T>::swap::<
(
NMapKey<Twox64Concat, XcmVersion>,
NMapKey<Blake2_128Concat, T::AccountId>,
NMapKey<Blake2_128Concat, VersionedAssetId>,
),
_,
_,
>(&old_key, &new_key);
weight.saturating_add(T::DbWeight::get().writes(1));
}
// check and migrate `AuthorizedAliases`
let aliases_to_migrate = AuthorizedAliases::<T>::iter().filter_map(|(id, data)| {
weight.saturating_add(T::DbWeight::get().reads(1));
match (&id, data, PhantomData::<T>).try_migrate(required_xcm_version) {
Ok(Some((new_id, new_data))) => Some((id, new_id, new_data)),
Ok(None) => None,
Err(_) => {
tracing::error!(
target: LOG_TARGET,
?id,
?required_xcm_version,
"`AuthorizedAliases` cannot be migrated!"
);
None
},
}
});
let mut count = 0;
for (old_id, new_id, new_data) in aliases_to_migrate {
tracing::info!(
target: LOG_TARGET,
?new_id,
?new_data,
"Migrating `AuthorizedAliases`"
);
AuthorizedAliases::<T>::remove(old_id);
AuthorizedAliases::<T>::insert(new_id, new_data);
count = count + 1;
}
// two writes per key, one to remove old entry, one to write new entry
weight.saturating_add(T::DbWeight::get().writes(count * 2));
}
}
}
pub mod v1 {
use super::*;
use crate::{CurrentMigration, VersionMigrationStage};
/// Named with the 'VersionUnchecked'-prefix because although this implements some version
/// checking, the version checking is not complete as it will begin failing after the upgrade is
/// enacted on-chain.
///
/// Use experimental [`MigrateToV1`] instead.
pub struct VersionUncheckedMigrateToV1<T>(core::marker::PhantomData<T>);
impl<T: Config> UncheckedOnRuntimeUpgrade for VersionUncheckedMigrateToV1<T> {
fn on_runtime_upgrade() -> Weight {
let mut weight = T::DbWeight::get().reads(1);
if StorageVersion::get::<Pallet<T>>() != 0 {
tracing::warn!("skipping v1, should be removed");
return weight;
}
weight.saturating_accrue(T::DbWeight::get().writes(1));
CurrentMigration::<T>::put(VersionMigrationStage::default());
let translate = |pre: (u64, u64, u32)| -> Option<(u64, Weight, u32)> {
weight.saturating_accrue(T::DbWeight::get().reads_writes(1, 1));
let translated = (pre.0, Weight::from_parts(pre.1, DEFAULT_PROOF_SIZE), pre.2);
tracing::info!("Migrated VersionNotifyTarget {:?} to {:?}", pre, translated);
Some(translated)
};
VersionNotifyTargets::<T>::translate_values(translate);
tracing::info!("v1 applied successfully");
weight.saturating_accrue(T::DbWeight::get().writes(1));
StorageVersion::new(1).put::<Pallet<T>>();
weight
}
}
/// Version checked migration to v1.
///
/// Wrapped in [`frame_support::migrations::VersionedMigration`] so the pre/post checks don't
/// begin failing after the upgrade is enacted on-chain.
pub type MigrateToV1<T> = frame_support::migrations::VersionedMigration<
0,
1,
VersionUncheckedMigrateToV1<T>,
crate::pallet::Pallet<T>,
<T as frame_system::Config>::DbWeight,
>;
}
/// When adding a new XCM version, we need to run this migration for `pallet_xcm` to ensure that all
/// previously stored data with subkey prefix `XCM_VERSION-1` (and below) are migrated to the
/// `XCM_VERSION`.
///
/// NOTE: This migration can be permanently added to the runtime migrations.
pub struct MigrateToLatestXcmVersion<T>(core::marker::PhantomData<T>);
impl<T: Config> OnRuntimeUpgrade for MigrateToLatestXcmVersion<T> {
fn on_runtime_upgrade() -> Weight {
let mut weight = T::DbWeight::get().reads(1);
// trigger expensive/lazy migration (kind of multi-block)
CurrentMigration::<T>::put(VersionMigrationStage::default());
weight.saturating_accrue(T::DbWeight::get().writes(1));
// migrate other operational data to the latest XCM version in-place
let latest = CurrentXcmVersion::get();
Pallet::<T>::migrate_data_to_xcm_version(&mut weight, latest);
weight
}
#[cfg(feature = "try-runtime")]
fn post_upgrade(_: alloc::vec::Vec<u8>) -> Result<(), sp_runtime::TryRuntimeError> {
use data::NeedsMigration;
const LOG_TARGET: &str = "runtime::xcm::pallet_xcm::migrate_to_latest";
let latest = CurrentXcmVersion::get();
let number_of_queries_to_migrate = crate::Queries::<T>::iter()
.filter(|(id, data)| {
let needs_migration = data.needs_migration(latest);
if needs_migration {
tracing::warn!(
target: LOG_TARGET,
query_id = ?id,
query = ?data,
"Query was not migrated!"
)
}
needs_migration
})
.count();
let number_of_locked_fungibles_to_migrate = crate::LockedFungibles::<T>::iter()
.filter_map(|(id, data)| {
if data.needs_migration(latest) {
tracing::warn!(
target: LOG_TARGET,
?id,
?data,
"LockedFungibles item was not migrated!"
);
Some(true)
} else {
None
}
})
.count();
let number_of_remote_locked_fungibles_to_migrate =
crate::RemoteLockedFungibles::<T>::iter()
.filter_map(|(key, data)| {
if key.needs_migration(latest) || data.needs_migration(latest) {
tracing::warn!(
target: LOG_TARGET,
?key,
"RemoteLockedFungibles item was not migrated!"
);
Some(true)
} else {
None
}
})
.count();
ensure!(number_of_queries_to_migrate == 0, "must migrate all `Queries`.");
ensure!(number_of_locked_fungibles_to_migrate == 0, "must migrate all `LockedFungibles`.");
ensure!(
number_of_remote_locked_fungibles_to_migrate == 0,
"must migrate all `RemoteLockedFungibles`."
);
Ok(())
}
}
+751
View File
@@ -0,0 +1,751 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
pub use core::cell::RefCell;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{
fungible::HoldConsideration, AsEnsureOriginWithArg, ConstU128, ConstU32, Contains, Equals,
Everything, EverythingBut, Footprint, Nothing,
},
weights::Weight,
};
use frame_system::EnsureRoot;
use pezkuwi_runtime_teyrchains::origin;
use pezkuwi_teyrchain_primitives::primitives::Id as ParaId;
use sp_core::H256;
use sp_runtime::{
traits::{Convert, IdentityLookup},
AccountId32, BuildStorage,
};
use xcm::prelude::*;
use xcm_builder::{
AccountId32Aliases, AllowKnownQueryResponses, AllowSubscriptionsFrom,
AllowTopLevelPaidExecutionFrom, Case, ChildSystemTeyrchainAsSuperuser, ChildTeyrchainAsNative,
ChildTeyrchainConvertsVia, DescribeAllTerminal, EnsureDecodableXcm, FixedRateOfFungible,
FixedWeightBounds, FrameTransactionalProcessor, FungibleAdapter, FungiblesAdapter,
HashedDescription, IsConcrete, MatchedConvertedConcreteId, NoChecking, SendXcmFeeToAccount,
SignedAccountId32AsNative, SignedToAccountId32, SovereignSignedViaLocation, TakeWeightCredit,
XcmFeeManagerFromComponents,
};
use xcm_executor::{
traits::{Identity, JustTry},
XcmExecutor,
};
use xcm_simulator::helpers::derive_topic_id;
use crate::{self as pallet_xcm, TestWeightInfo};
pub type AccountId = AccountId32;
pub type Balance = u128;
type Block = frame_system::mocking::MockBlock<Test>;
#[frame_support::pallet]
pub mod pallet_test_notifier {
use crate::{ensure_response, QueryId};
use frame_support::pallet_prelude::*;
use frame_system::pallet_prelude::*;
use sp_runtime::DispatchResult;
use xcm::latest::prelude::*;
use xcm_executor::traits::QueryHandler;
#[pallet::pallet]
pub struct Pallet<T>(_);
#[pallet::config]
pub trait Config: frame_system::Config + crate::Config {
#[allow(deprecated)]
type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;
type RuntimeOrigin: IsType<<Self as frame_system::Config>::RuntimeOrigin>
+ Into<Result<crate::Origin, <Self as Config>::RuntimeOrigin>>;
type RuntimeCall: IsType<<Self as crate::Config>::RuntimeCall> + From<Call<Self>>;
}
#[pallet::event]
#[pallet::generate_deposit(pub(super) fn deposit_event)]
pub enum Event<T: Config> {
QueryPrepared(QueryId),
NotifyQueryPrepared(QueryId),
ResponseReceived(Location, QueryId, Response),
}
#[pallet::error]
pub enum Error<T> {
UnexpectedId,
BadAccountFormat,
}
#[pallet::call]
impl<T: Config> Pallet<T> {
#[pallet::call_index(0)]
#[pallet::weight(Weight::from_parts(1_000_000, 1_000_000))]
pub fn prepare_new_query(origin: OriginFor<T>, querier: Location) -> DispatchResult {
let who = ensure_signed(origin)?;
let id = who
.using_encoded(|mut d| <[u8; 32]>::decode(&mut d))
.map_err(|_| Error::<T>::BadAccountFormat)?;
let qid = <crate::Pallet<T> as QueryHandler>::new_query(
Junction::AccountId32 { network: None, id },
100u32.into(),
querier,
);
Self::deposit_event(Event::<T>::QueryPrepared(qid));
Ok(())
}
#[pallet::call_index(1)]
#[pallet::weight(Weight::from_parts(1_000_000, 1_000_000))]
pub fn prepare_new_notify_query(origin: OriginFor<T>, querier: Location) -> DispatchResult {
let who = ensure_signed(origin)?;
let id = who
.using_encoded(|mut d| <[u8; 32]>::decode(&mut d))
.map_err(|_| Error::<T>::BadAccountFormat)?;
let call =
Call::<T>::notification_received { query_id: 0, response: Default::default() };
let qid = crate::Pallet::<T>::new_notify_query(
Junction::AccountId32 { network: None, id },
<T as Config>::RuntimeCall::from(call),
100u32.into(),
querier,
);
Self::deposit_event(Event::<T>::NotifyQueryPrepared(qid));
Ok(())
}
#[pallet::call_index(2)]
#[pallet::weight(Weight::from_parts(1_000_000, 1_000_000))]
pub fn notification_received(
origin: OriginFor<T>,
query_id: QueryId,
response: Response,
) -> DispatchResult {
let responder = ensure_response(<T as Config>::RuntimeOrigin::from(origin))?;
Self::deposit_event(Event::<T>::ResponseReceived(responder, query_id, response));
Ok(())
}
}
}
construct_runtime!(
pub enum Test
{
System: frame_system,
Balances: pallet_balances,
AssetsPallet: pallet_assets,
ParasOrigin: origin,
XcmPallet: pallet_xcm,
TestNotifier: pallet_test_notifier,
}
);
thread_local! {
pub static SENT_XCM: RefCell<Vec<(Location, Xcm<()>)>> = RefCell::new(Vec::new());
pub static FAIL_SEND_XCM: RefCell<bool> = RefCell::new(false);
}
pub(crate) fn sent_xcm() -> Vec<(Location, Xcm<()>)> {
SENT_XCM.with(|q| (*q.borrow()).clone())
}
pub(crate) fn take_sent_xcm() -> Vec<(Location, Xcm<()>)> {
SENT_XCM.with(|q| {
let mut r = Vec::new();
std::mem::swap(&mut r, &mut *q.borrow_mut());
r
})
}
pub(crate) fn set_send_xcm_artificial_failure(should_fail: bool) {
FAIL_SEND_XCM.with(|q| *q.borrow_mut() = should_fail);
}
/// Sender that never returns error.
pub struct TestSendXcm;
impl SendXcm for TestSendXcm {
type Ticket = (Location, Xcm<()>);
fn validate(
dest: &mut Option<Location>,
msg: &mut Option<Xcm<()>>,
) -> SendResult<(Location, Xcm<()>)> {
if FAIL_SEND_XCM.with(|q| *q.borrow()) {
return Err(SendError::Transport("Intentional send failure used in tests"));
}
let pair = (dest.take().unwrap(), msg.take().unwrap());
Ok((pair, Assets::new()))
}
fn deliver(pair: (Location, Xcm<()>)) -> Result<XcmHash, SendError> {
let message = pair.1.clone();
if message
.iter()
.any(|instr| matches!(instr, ExpectError(Some((1, XcmError::Unimplemented)))))
{
return Err(SendError::Transport("Intentional deliver failure used in tests".into()));
}
let hash = derive_topic_id(&message);
SENT_XCM.with(|q| q.borrow_mut().push(pair));
Ok(hash)
}
}
/// Sender that returns error if `X8` junction and stops routing
pub struct TestSendXcmErrX8;
impl SendXcm for TestSendXcmErrX8 {
type Ticket = (Location, Xcm<()>);
fn validate(
dest: &mut Option<Location>,
_: &mut Option<Xcm<()>>,
) -> SendResult<(Location, Xcm<()>)> {
if dest.as_ref().unwrap().len() == 8 {
dest.take();
Err(SendError::Transport("Destination location full"))
} else {
Err(SendError::NotApplicable)
}
}
fn deliver(pair: (Location, Xcm<()>)) -> Result<XcmHash, SendError> {
let hash = derive_topic_id(&pair.1);
SENT_XCM.with(|q| q.borrow_mut().push(pair));
Ok(hash)
}
}
parameter_types! {
pub Para3000: u32 = 3000;
pub Para3000Location: Location = Teyrchain(Para3000::get()).into();
pub Para3000PaymentAmount: u128 = 1;
pub Para3000PaymentAssets: Assets = Assets::from(Asset::from((Here, Para3000PaymentAmount::get())));
}
/// Sender only sends to `Teyrchain(3000)` destination requiring payment.
pub struct TestPaidForPara3000SendXcm;
impl SendXcm for TestPaidForPara3000SendXcm {
type Ticket = (Location, Xcm<()>);
fn validate(
dest: &mut Option<Location>,
msg: &mut Option<Xcm<()>>,
) -> SendResult<(Location, Xcm<()>)> {
if let Some(dest) = dest.as_ref() {
if !dest.eq(&Para3000Location::get()) {
return Err(SendError::NotApplicable);
}
} else {
return Err(SendError::NotApplicable);
}
let pair = (dest.take().unwrap(), msg.take().unwrap());
Ok((pair, Para3000PaymentAssets::get()))
}
fn deliver(pair: (Location, Xcm<()>)) -> Result<XcmHash, SendError> {
let hash = derive_topic_id(&pair.1);
SENT_XCM.with(|q| q.borrow_mut().push(pair));
Ok(hash)
}
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Test {
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
type Nonce = u64;
type Hash = H256;
type Hashing = ::sp_runtime::traits::BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type Block = Block;
type RuntimeEvent = RuntimeEvent;
type BlockWeights = ();
type BlockLength = ();
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type DbWeight = ();
type BaseCallFilter = Everything;
type SystemWeightInfo = ();
type SS58Prefix = ();
type OnSetCode = ();
type MaxConsumers = frame_support::traits::ConstU32<16>;
}
parameter_types! {
pub ExistentialDeposit: Balance = 1;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Test {
type Balance = Balance;
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
}
#[cfg(feature = "runtime-benchmarks")]
/// Simple conversion of `u32` into an `AssetId` for use in benchmarking.
pub struct XcmBenchmarkHelper;
#[cfg(feature = "runtime-benchmarks")]
impl pallet_assets::BenchmarkHelper<Location, ()> for XcmBenchmarkHelper {
fn create_asset_id_parameter(id: u32) -> Location {
Location::new(1, [Teyrchain(id)])
}
fn create_reserve_id_parameter(_: u32) {}
}
impl pallet_assets::Config for Test {
type RuntimeEvent = RuntimeEvent;
type Balance = Balance;
type AssetId = Location;
type AssetIdParameter = Location;
type ReserveData = ();
type Currency = Balances;
type CreateOrigin = AsEnsureOriginWithArg<frame_system::EnsureSigned<AccountId>>;
type ForceOrigin = EnsureRoot<AccountId>;
type AssetDeposit = ConstU128<1>;
type AssetAccountDeposit = ConstU128<10>;
type MetadataDepositBase = ConstU128<1>;
type MetadataDepositPerByte = ConstU128<1>;
type ApprovalDeposit = ConstU128<1>;
type StringLimit = ConstU32<50>;
type Holder = ();
type Freezer = ();
type WeightInfo = ();
type CallbackHandle = ();
type Extra = ();
type RemoveItemsLimit = ConstU32<5>;
#[cfg(feature = "runtime-benchmarks")]
type BenchmarkHelper = XcmBenchmarkHelper;
}
// This child teyrchain is a system teyrchain trusted to teleport native token.
pub const SOME_SYSTEM_PARA: u32 = 1001;
// This child teyrchain acts as trusted reserve for its assets in tests.
// USDT allowed to teleport to/from here.
pub const FOREIGN_ASSET_RESERVE_PARA_ID: u32 = 2001;
// Inner junction of reserve asset on `FOREIGN_ASSET_RESERVE_PARA_ID`.
pub const FOREIGN_ASSET_INNER_JUNCTION: Junction = GeneralIndex(1234567);
// This child teyrchain acts as trusted reserve for say.. USDC that can be used for fees.
pub const USDC_RESERVE_PARA_ID: u32 = 2002;
// Inner junction of reserve asset on `USDC_RESERVE_PARA_ID`.
pub const USDC_INNER_JUNCTION: Junction = PalletInstance(42);
// This child teyrchain is a trusted teleporter for say.. USDT (T from Teleport :)).
// We'll use USDT in tests that teleport fees.
pub const USDT_PARA_ID: u32 = 2003;
// This child teyrchain is not configured as trusted reserve or teleport location for any assets.
pub const OTHER_PARA_ID: u32 = 2009;
// This child teyrchain is used for filtered/disallowed assets.
pub const FILTERED_PARA_ID: u32 = 2010;
parameter_types! {
pub const RelayLocation: Location = Here.into_location();
pub const NativeAsset: Asset = Asset {
fun: Fungible(10),
id: AssetId(Here.into_location()),
};
pub SystemTeyrchainLocation: Location = Location::new(
0,
[Teyrchain(SOME_SYSTEM_PARA)]
);
pub ForeignReserveLocation: Location = Location::new(
0,
[Teyrchain(FOREIGN_ASSET_RESERVE_PARA_ID)]
);
pub PaidParaForeignReserveLocation: Location = Location::new(
0,
[Teyrchain(Para3000::get())]
);
pub ForeignAsset: Asset = Asset {
fun: Fungible(10),
id: AssetId(Location::new(
0,
[Teyrchain(FOREIGN_ASSET_RESERVE_PARA_ID), FOREIGN_ASSET_INNER_JUNCTION],
)),
};
pub PaidParaForeignAsset: Asset = Asset {
fun: Fungible(10),
id: AssetId(Location::new(
0,
[Teyrchain(Para3000::get())],
)),
};
pub UsdcReserveLocation: Location = Location::new(
0,
[Teyrchain(USDC_RESERVE_PARA_ID)]
);
pub Usdc: Asset = Asset {
fun: Fungible(10),
id: AssetId(Location::new(
0,
[Teyrchain(USDC_RESERVE_PARA_ID), USDC_INNER_JUNCTION],
)),
};
pub UsdtTeleportLocation: Location = Location::new(
0,
[Teyrchain(USDT_PARA_ID)]
);
pub Usdt: Asset = Asset {
fun: Fungible(10),
id: AssetId(Location::new(
0,
[Teyrchain(USDT_PARA_ID)],
)),
};
pub FilteredTeleportLocation: Location = Location::new(
0,
[Teyrchain(FILTERED_PARA_ID)]
);
pub FilteredTeleportAsset: Asset = Asset {
fun: Fungible(10),
id: AssetId(Location::new(
0,
[Teyrchain(FILTERED_PARA_ID)],
)),
};
pub const AnyNetwork: Option<NetworkId> = None;
pub UniversalLocation: InteriorLocation = GlobalConsensus(ByGenesis([0; 32])).into();
pub UnitWeightCost: u64 = 1_000;
pub CheckingAccount: AccountId = XcmPallet::check_account();
}
pub type SovereignAccountOf = (
ChildTeyrchainConvertsVia<ParaId, AccountId>,
AccountId32Aliases<AnyNetwork, AccountId>,
HashedDescription<AccountId, DescribeAllTerminal>,
);
pub type ForeignAssetsConvertedConcreteId = MatchedConvertedConcreteId<
Location,
Balance,
// Excludes relay/parent chain currency
EverythingBut<(Equals<RelayLocation>,)>,
Identity,
JustTry,
>;
pub type AssetTransactors = (
FungibleAdapter<Balances, IsConcrete<RelayLocation>, SovereignAccountOf, AccountId, ()>,
FungiblesAdapter<
AssetsPallet,
ForeignAssetsConvertedConcreteId,
SovereignAccountOf,
AccountId,
NoChecking,
CheckingAccount,
>,
);
type LocalOriginConverter = (
SovereignSignedViaLocation<SovereignAccountOf, RuntimeOrigin>,
ChildTeyrchainAsNative<origin::Origin, RuntimeOrigin>,
SignedAccountId32AsNative<AnyNetwork, RuntimeOrigin>,
ChildSystemTeyrchainAsSuperuser<ParaId, RuntimeOrigin>,
);
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000);
pub CurrencyPerSecondPerByte: (AssetId, u128, u128) = (AssetId(RelayLocation::get()), 1, 1);
pub TrustedLocal: (AssetFilter, Location) = (All.into(), Here.into());
pub TrustedSystemPara: (AssetFilter, Location) = (NativeAsset::get().into(), SystemTeyrchainLocation::get());
pub TrustedUsdt: (AssetFilter, Location) = (Usdt::get().into(), UsdtTeleportLocation::get());
pub TrustedFilteredTeleport: (AssetFilter, Location) = (FilteredTeleportAsset::get().into(), FilteredTeleportLocation::get());
pub TeleportUsdtToForeign: (AssetFilter, Location) = (Usdt::get().into(), ForeignReserveLocation::get());
pub TrustedForeign: (AssetFilter, Location) = (ForeignAsset::get().into(), ForeignReserveLocation::get());
pub TrustedPaidParaForeign: (AssetFilter, Location) = (PaidParaForeignAsset::get().into(), PaidParaForeignReserveLocation::get());
pub TrustedUsdc: (AssetFilter, Location) = (Usdc::get().into(), UsdcReserveLocation::get());
pub const MaxInstructions: u32 = 100;
pub const MaxAssetsIntoHolding: u32 = 64;
pub XcmFeesTargetAccount: AccountId = AccountId::new([167u8; 32]);
}
pub const XCM_FEES_NOT_WAIVED_USER_ACCOUNT: [u8; 32] = [37u8; 32];
pub struct XcmFeesNotWaivedLocations;
impl Contains<Location> for XcmFeesNotWaivedLocations {
fn contains(location: &Location) -> bool {
matches!(
location.unpack(),
(0, [Junction::AccountId32 { network: None, id: XCM_FEES_NOT_WAIVED_USER_ACCOUNT }])
)
}
}
pub type Barrier = (
TakeWeightCredit,
AllowTopLevelPaidExecutionFrom<Everything>,
AllowKnownQueryResponses<XcmPallet>,
AllowSubscriptionsFrom<Everything>,
);
pub type XcmRouter =
EnsureDecodableXcm<(TestPaidForPara3000SendXcm, TestSendXcmErrX8, TestSendXcm)>;
pub type Trader = FixedRateOfFungible<CurrencyPerSecondPerByte, ()>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type RuntimeCall = RuntimeCall;
type XcmSender = XcmRouter;
type XcmEventEmitter = XcmPallet;
type AssetTransactor = AssetTransactors;
type OriginConverter = LocalOriginConverter;
type IsReserve = (Case<TrustedForeign>, Case<TrustedUsdc>, Case<TrustedPaidParaForeign>);
type IsTeleporter = (
Case<TrustedLocal>,
Case<TrustedSystemPara>,
Case<TrustedUsdt>,
Case<TeleportUsdtToForeign>,
Case<TrustedFilteredTeleport>,
);
type UniversalLocation = UniversalLocation;
type Barrier = Barrier;
type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
type Trader = Trader;
type ResponseHandler = XcmPallet;
type AssetTrap = XcmPallet;
type AssetLocker = ();
type AssetExchanger = ();
type AssetClaims = XcmPallet;
type SubscriptionService = XcmPallet;
type PalletInstancesInfo = AllPalletsWithSystem;
type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
type FeeManager = XcmFeeManagerFromComponents<
EverythingBut<XcmFeesNotWaivedLocations>,
SendXcmFeeToAccount<Self::AssetTransactor, XcmFeesTargetAccount>,
>;
type MessageExporter = ();
type UniversalAliases = Nothing;
type CallDispatcher = RuntimeCall;
type SafeCallFilter = Everything;
type Aliasers = Nothing;
type TransactionalProcessor = FrameTransactionalProcessor;
type HrmpNewChannelOpenRequestHandler = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type XcmRecorder = XcmPallet;
}
/// Converts a local signed origin into an XCM location. Forms the basis for local origins
/// sending/executing XCMs.
pub type LocalOriginToLocation = SignedToAccountId32<RuntimeOrigin, AccountId, AnyNetwork>;
parameter_types! {
pub static AdvertisedXcmVersion: pallet_xcm::XcmVersion = 4;
pub const AuthorizeAliasHoldReason: RuntimeHoldReason = RuntimeHoldReason::XcmPallet(pallet_xcm::HoldReason::AuthorizeAlias);
}
pub struct ConvertDeposit;
impl Convert<Footprint, u128> for ConvertDeposit {
fn convert(a: Footprint) -> u128 {
(a.count * 2 + a.size) as u128
}
}
pub struct XcmTeleportFiltered;
impl Contains<(Location, Vec<Asset>)> for XcmTeleportFiltered {
fn contains(t: &(Location, Vec<Asset>)) -> bool {
let filtered = FilteredTeleportAsset::get();
t.1.iter().any(|asset| asset == &filtered)
}
}
impl pallet_xcm::Config for Test {
type RuntimeEvent = RuntimeEvent;
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmRouter = XcmRouter;
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmTeleportFilter = EverythingBut<XcmTeleportFiltered>;
type XcmReserveTransferFilter = Everything;
type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
type UniversalLocation = UniversalLocation;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
type AdvertisedXcmVersion = AdvertisedXcmVersion;
type AdminOrigin = EnsureRoot<AccountId>;
type TrustedLockers = ();
type SovereignAccountOf = AccountId32Aliases<(), AccountId32>;
type Currency = Balances;
type CurrencyMatcher = IsConcrete<RelayLocation>;
type MaxLockers = frame_support::traits::ConstU32<8>;
type MaxRemoteLockConsumers = frame_support::traits::ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type WeightInfo = TestWeightInfo;
type AuthorizedAliasConsideration =
HoldConsideration<AccountId, Balances, AuthorizeAliasHoldReason, ConvertDeposit>;
}
impl origin::Config for Test {}
impl pallet_test_notifier::Config for Test {
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type RuntimeCall = RuntimeCall;
}
#[cfg(feature = "runtime-benchmarks")]
pub struct TestDeliveryHelper;
#[cfg(feature = "runtime-benchmarks")]
impl xcm_builder::EnsureDelivery for TestDeliveryHelper {
fn ensure_successful_delivery(
origin_ref: &Location,
_dest: &Location,
_fee_reason: xcm_executor::traits::FeeReason,
) -> (Option<xcm_executor::FeesMode>, Option<Assets>) {
use xcm_executor::traits::ConvertLocation;
let account = SovereignAccountOf::convert_location(origin_ref).expect("Valid location");
// Give the existential deposit at least
let balance = ExistentialDeposit::get();
let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
&account, balance,
);
(None, None)
}
}
#[cfg(feature = "runtime-benchmarks")]
impl super::benchmarking::Config for Test {
type DeliveryHelper = TestDeliveryHelper;
fn reachable_dest() -> Option<Location> {
Some(Teyrchain(1000).into())
}
fn teleportable_asset_and_dest() -> Option<(Asset, Location)> {
Some((NativeAsset::get(), SystemTeyrchainLocation::get()))
}
fn reserve_transferable_asset_and_dest() -> Option<(Asset, Location)> {
Some((
Asset { fun: Fungible(10), id: AssetId(Here.into_location()) },
Teyrchain(OTHER_PARA_ID).into(),
))
}
fn set_up_complex_asset_transfer() -> Option<(Assets, AssetId, Location, Box<dyn FnOnce()>)> {
use crate::tests::assets_transfer::{into_assets_checked, set_up_foreign_asset};
// Transfer native asset (local reserve) to `USDT_PARA_ID`. Using teleport-trusted USDT for
// fees.
let asset_amount = 10u128;
let fee_amount = 2u128;
let existential_deposit = ExistentialDeposit::get();
let caller = frame_benchmarking::whitelisted_caller();
// Give some multiple of the existential deposit
let balance = asset_amount + existential_deposit * 1000;
let _ = <Balances as frame_support::traits::Currency<_>>::make_free_balance_be(
&caller, balance,
);
// create sufficient foreign asset USDT
let usdt_initial_local_amount = fee_amount * 10;
let (usdt_chain, _, usdt_id_location) = set_up_foreign_asset(
USDT_PARA_ID,
None,
caller.clone(),
usdt_initial_local_amount,
true,
);
// native assets transfer destination is USDT chain (teleport trust only for USDT)
let dest = usdt_chain;
let (assets, fee_asset, _) = into_assets_checked(
// USDT for fees (is sufficient on local chain too) - teleported
(usdt_id_location.clone(), fee_amount).into(),
// native asset to transfer (not used for fees) - local reserve
(Location::here(), asset_amount).into(),
);
// verify initial balances
assert_eq!(Balances::free_balance(&caller), balance);
assert_eq!(
AssetsPallet::balance(usdt_id_location.clone(), &caller),
usdt_initial_local_amount
);
// verify transferred successfully
let verify = Box::new(move || {
// verify balances after transfer, decreased by transferred amounts
assert_eq!(Balances::free_balance(&caller), balance - asset_amount);
assert_eq!(
AssetsPallet::balance(usdt_id_location, &caller),
usdt_initial_local_amount - fee_amount
);
});
Some((assets, fee_asset.id, dest, verify))
}
fn get_asset() -> Asset {
Asset { id: AssetId(Location::here()), fun: Fungible(ExistentialDeposit::get()) }
}
}
pub(crate) fn all_events() -> Vec<RuntimeEvent> {
System::events().into_iter().map(|e| e.event).collect()
}
pub(crate) fn last_events(n: usize) -> Vec<RuntimeEvent> {
let all_events = all_events();
let split_idx = all_events.len().saturating_sub(n);
all_events.split_at(split_idx).1.to_vec()
}
pub(crate) fn last_event() -> RuntimeEvent {
last_events(1).pop().expect("RuntimeEvent expected")
}
pub(crate) fn buy_execution<C>(fees: impl Into<Asset>) -> Instruction<C> {
use xcm::latest::prelude::*;
BuyExecution { fees: fees.into(), weight_limit: Unlimited }
}
pub(crate) fn buy_limited_execution<C>(
fees: impl Into<Asset>,
weight_limit: WeightLimit,
) -> Instruction<C> {
use xcm::latest::prelude::*;
BuyExecution { fees: fees.into(), weight_limit }
}
pub(crate) fn new_test_ext_with_balances(
balances: Vec<(AccountId, Balance)>,
) -> sp_io::TestExternalities {
new_test_ext_with_balances_and_xcm_version(
balances,
// By default set actual latest XCM version
Some(XCM_VERSION),
vec![],
)
}
pub(crate) fn new_test_ext_with_balances_and_xcm_version(
balances: Vec<(AccountId, Balance)>,
safe_xcm_version: Option<XcmVersion>,
supported_version: Vec<(Location, XcmVersion)>,
) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Test>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Test> { balances, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
pallet_xcm::GenesisConfig::<Test> { safe_xcm_version, supported_version, ..Default::default() }
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext
}
File diff suppressed because it is too large Load Diff
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,162 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// This file is part of Pezkuwi.
// Pezkuwi 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.
// Pezkuwi 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 Pezkuwi. If not, see <http://www.gnu.org/licenses/>.
//! Validation of the `transfer_assets` call.
//! This validation is a temporary patch in preparation for the Asset Hub Migration (AHM).
//! This module will be removed after the migration and the determined
//! reserve location will be adjusted accordingly to be Asset Hub.
//! For more information, see <https://github.com/pezkuwichain/pezkuwi-sdk/issues/158>.
use crate::{Config, Error, Pallet};
use alloc::vec::Vec;
use hex_literal::hex;
use sp_core::Get;
use xcm::prelude::*;
use xcm_executor::traits::TransferType;
/// The genesis hash of the Paseo Relay Chain. Used to identify it.
const PASEO_GENESIS_HASH: [u8; 32] =
hex!["77afd6190f1554ad45fd0d31aee62aacc33c6db0ea801129acb813f913e0764f"];
impl<T: Config> Pallet<T> {
/// Check if network native asset reserve transfers should be blocked during Asset Hub
/// Migration.
///
/// During the Asset Hub Migration (AHM), the native network asset's reserve will move
/// from the Relay Chain to Asset Hub. The `transfer_assets` function automatically determines
/// reserves based on asset ID location, which would incorrectly assume Relay Chain as the
/// reserve.
///
/// This function blocks native network asset reserve transfers to prevent issues during
/// the migration.
/// Users should use `limited_reserve_transfer_assets`, `transfer_assets_using_type_and_then` or
/// `execute` instead, which allows explicit reserve specification.
pub(crate) fn ensure_network_asset_reserve_transfer_allowed(
assets: &Vec<Asset>,
fee_asset_id: &AssetId,
assets_transfer_type: &TransferType,
fees_transfer_type: &TransferType,
) -> Result<(), Error<T>> {
// Extract fee asset and check both assets and fees separately.
let mut remaining_assets = assets.clone();
let fee_asset_index =
assets.iter().position(|a| a.id == *fee_asset_id).ok_or(Error::<T>::Empty)?;
let fee_asset = remaining_assets.remove(fee_asset_index);
// Check remaining assets with their transfer type.
Self::ensure_one_transfer_type_allowed(&remaining_assets, &assets_transfer_type)?;
// Check fee asset with its transfer type.
Self::ensure_one_transfer_type_allowed(&[fee_asset], &fees_transfer_type)?;
Ok(())
}
/// Checks that the transfer of `assets` is allowed.
///
/// Returns an error if `transfer_type` is a reserve transfer and the network's native asset is
/// being transferred. Allows the transfer otherwise.
fn ensure_one_transfer_type_allowed(
assets: &[Asset],
transfer_type: &TransferType,
) -> Result<(), Error<T>> {
// Check if any reserve transfer (LocalReserve, DestinationReserve, or RemoteReserve)
// is being attempted.
let is_reserve_transfer = matches!(
transfer_type,
TransferType::LocalReserve |
TransferType::DestinationReserve |
TransferType::RemoteReserve(_)
);
if !is_reserve_transfer {
// If not a reserve transfer (e.g., teleport), allow it.
return Ok(());
}
// Check if any asset is a network native asset.
for asset in assets {
if Self::is_network_native_asset(&asset.id) {
tracing::debug!(
target: "xcm::pallet_xcm::transfer_assets",
asset_id = ?asset.id, ?transfer_type,
"Network native asset reserve transfer blocked in preparation for the Asset Hub Migration. Use `transfer_assets_using_type_and_then` instead and explicitly mention the reserve."
);
// It's error-prone to try to determine the reserve in this circumstances.
return Err(Error::<T>::InvalidAssetUnknownReserve);
}
}
Ok(())
}
/// Check if the given asset ID represents a network native asset based on our
/// UniversalLocation.
///
/// Returns true if the asset is a native network asset (HEZ, KSM, ZGR, PAS) that should be
/// blocked during Asset Hub Migration.
fn is_network_native_asset(asset_id: &AssetId) -> bool {
let universal_location = T::UniversalLocation::get();
let asset_location = &asset_id.0;
match universal_location.len() {
// Case 1: We are on the Relay Chain itself.
// UniversalLocation: GlobalConsensus(Network).
// Network asset ID: Here.
1 => {
if let Some(Junction::GlobalConsensus(network)) = universal_location.first() {
let is_target_network = match network {
NetworkId::Pezkuwi | NetworkId::Kusama => true,
NetworkId::ByGenesis(genesis_hash) => {
// Check if this is Zagros by genesis hash
*genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH ||
*genesis_hash == PASEO_GENESIS_HASH ||
*genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests.
},
_ => false,
};
is_target_network && asset_location.is_here()
} else {
false
}
},
// Case 2: We are on a teyrchain within one of the specified networks.
// UniversalLocation: GlobalConsensus(Network)/Teyrchain(id).
// Network asset ID: Parent.
2 => {
if let (Some(Junction::GlobalConsensus(network)), Some(Junction::Teyrchain(_))) =
(universal_location.first(), universal_location.last())
{
let is_target_network = match network {
NetworkId::Pezkuwi | NetworkId::Kusama => true,
NetworkId::ByGenesis(genesis_hash) => {
// Check if this is Zagros by genesis hash
*genesis_hash == xcm::v5::ZAGROS_GENESIS_HASH ||
*genesis_hash == PASEO_GENESIS_HASH ||
*genesis_hash == xcm::v5::PEZKUWICHAIN_GENESIS_HASH // Used in tests.
},
_ => false,
};
is_target_network && *asset_location == Location::parent()
} else {
false
}
},
// Case 3: We are not on a relay or teyrchain. We return false.
_ => false,
}
}
}
+33
View File
@@ -0,0 +1,33 @@
// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use xcm::latest::XcmHash;
/// Finds the message ID of the first `XcmPallet::Sent` event in the given events.
pub fn find_xcm_sent_message_id<T>(
events: impl IntoIterator<Item = <T as crate::Config>::RuntimeEvent>,
) -> Option<XcmHash>
where
T: crate::Config,
<T as crate::Config>::RuntimeEvent: TryInto<crate::Event<T>>,
{
events.into_iter().find_map(|event| {
if let Ok(crate::Event::Sent { message_id, .. }) = event.try_into() {
Some(message_id)
} else {
None
}
})
}