xcm-simulator tests (#363)

This commit is contained in:
Amar Singh
2024-11-26 13:30:00 -05:00
committed by GitHub
parent 8666cb50c1
commit 9a0e668deb
42 changed files with 1746 additions and 1 deletions
@@ -0,0 +1,121 @@
pub mod parachain;
pub mod relay_chain;
use sp_runtime::BuildStorage;
use sp_tracing;
use xcm::prelude::*;
use xcm_executor::traits::ConvertLocation;
use xcm_simulator::{decl_test_network, decl_test_parachain, decl_test_relay_chain, TestExt};
pub const ALICE: sp_runtime::AccountId32 = sp_runtime::AccountId32::new([1u8; 32]);
pub const INITIAL_BALANCE: u128 = 1_000_000_000;
decl_test_parachain! {
pub struct ParaA {
Runtime = parachain::Runtime,
XcmpMessageHandler = parachain::MsgQueue,
DmpMessageHandler = parachain::MsgQueue,
new_ext = para_ext(1),
}
}
decl_test_parachain! {
pub struct ParaB {
Runtime = parachain::Runtime,
XcmpMessageHandler = parachain::MsgQueue,
DmpMessageHandler = parachain::MsgQueue,
new_ext = para_ext(2),
}
}
decl_test_relay_chain! {
pub struct Relay {
Runtime = relay_chain::Runtime,
RuntimeCall = relay_chain::RuntimeCall,
RuntimeEvent = relay_chain::RuntimeEvent,
XcmConfig = relay_chain::XcmConfig,
MessageQueue = relay_chain::MessageQueue,
System = relay_chain::System,
new_ext = relay_ext(),
}
}
decl_test_network! {
pub struct MockNet {
relay_chain = Relay,
parachains = vec![
(1, ParaA),
(2, ParaB),
],
}
}
pub fn parent_account_id() -> parachain::AccountId {
let location = (Parent,);
parachain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn child_account_id(para: u32) -> relay_chain::AccountId {
let location = (Parachain(para),);
relay_chain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn child_account_account_id(para: u32, who: sp_runtime::AccountId32) -> relay_chain::AccountId {
let location = (Parachain(para), AccountId32 { network: None, id: who.into() });
relay_chain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn sibling_account_account_id(para: u32, who: sp_runtime::AccountId32) -> parachain::AccountId {
let location = (Parent, Parachain(para), AccountId32 { network: None, id: who.into() });
parachain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn parent_account_account_id(who: sp_runtime::AccountId32) -> parachain::AccountId {
let location = (Parent, AccountId32 { network: None, id: who.into() });
parachain::location_converter::LocationConverter::convert_location(&location.into()).unwrap()
}
pub fn para_ext(para_id: u32) -> sp_io::TestExternalities {
use parachain::{MsgQueue, Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![(ALICE, INITIAL_BALANCE), (parent_account_id(), INITIAL_BALANCE)],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
sp_tracing::try_init_simple();
System::set_block_number(1);
MsgQueue::set_para_id(para_id.into());
});
ext
}
pub fn relay_ext() -> sp_io::TestExternalities {
use relay_chain::{Runtime, System};
let mut t = frame_system::GenesisConfig::<Runtime>::default().build_storage().unwrap();
pallet_balances::GenesisConfig::<Runtime> {
balances: vec![
(ALICE, INITIAL_BALANCE),
(child_account_id(1), INITIAL_BALANCE),
(child_account_id(2), INITIAL_BALANCE),
],
}
.assimilate_storage(&mut t)
.unwrap();
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| {
System::set_block_number(1);
});
ext
}
pub type RelayChainPalletXcm = pallet_xcm::Pallet<relay_chain::Runtime>;
pub type ParachainPalletXcm = pallet_xcm::Pallet<parachain::Runtime>;
@@ -0,0 +1,106 @@
mod xcm_config;
use core::marker::PhantomData;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{ConstU128, ContainsPair, Everything, Nothing},
weights::{constants::WEIGHT_REF_TIME_PER_SECOND, Weight},
};
use frame_system::EnsureRoot;
use sp_core::ConstU32;
use sp_runtime::{
traits::{Get, IdentityLookup},
AccountId32,
};
use xcm::latest::prelude::*;
use xcm_builder::{EnsureXcmOrigin, SignedToAccountId32};
pub use xcm_config::*;
use xcm_executor::XcmExecutor;
use xcm_simulator::mock_message_queue;
pub type AccountId = AccountId32;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u64 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountData = pallet_balances::AccountData<Balance>;
type AccountId = AccountId;
type Block = Block;
type Lookup = IdentityLookup<Self::AccountId>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type AccountStore = System;
type Balance = Balance;
type ExistentialDeposit = ConstU128<1>;
}
parameter_types! {
pub const ReservedXcmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
pub const ReservedDmpWeight: Weight = Weight::from_parts(WEIGHT_REF_TIME_PER_SECOND.saturating_div(4), 0);
}
impl mock_message_queue::Config for Runtime {
type RuntimeEvent = RuntimeEvent;
type XcmExecutor = XcmExecutor<XcmConfig>;
}
pub type LocalOriginToLocation =
SignedToAccountId32<RuntimeOrigin, AccountId, constants::RelayNetwork>;
pub struct TrustedLockerCase<T>(PhantomData<T>);
impl<T: Get<(Location, AssetFilter)>> ContainsPair<Location, Asset> for TrustedLockerCase<T> {
fn contains(origin: &Location, asset: &Asset) -> bool {
let (o, a) = T::get();
a.matches(asset) && &o == origin
}
}
parameter_types! {
pub RelayTokenForRelay: (Location, AssetFilter) = (Parent.into(), Wild(AllOf { id: AssetId(Parent.into()), fun: WildFungible }));
}
pub type TrustedLockers = TrustedLockerCase<RelayTokenForRelay>;
impl pallet_xcm::Config for Runtime {
type AdminOrigin = EnsureRoot<AccountId>;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = ();
type ExecuteXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type MaxLockers = ConstU32<8>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type SendXcmOrigin = EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type SovereignAccountOf = location_converter::LocationConverter;
type TrustedLockers = TrustedLockers;
type UniversalLocation = constants::UniversalLocation;
type Weigher = weigher::Weigher;
type WeightInfo = pallet_xcm::TestWeightInfo;
type XcmExecuteFilter = Everything;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmReserveTransferFilter = Everything;
type XcmRouter = XcmRouter;
type XcmTeleportFilter = Nothing;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
}
type Block = frame_system::mocking::MockBlock<Runtime>;
construct_runtime!(
pub struct Runtime {
System: frame_system,
Balances: pallet_balances,
MsgQueue: mock_message_queue,
PolkadotXcm: pallet_xcm,
}
);
@@ -0,0 +1,8 @@
use xcm_builder::{FungibleAdapter, IsConcrete};
use crate::parachain::{
constants::KsmLocation, location_converter::LocationConverter, AccountId, Balances,
};
pub type AssetTransactor =
FungibleAdapter<Balances, IsConcrete<KsmLocation>, LocationConverter, AccountId, ()>;
@@ -0,0 +1,4 @@
use frame_support::traits::Everything;
use xcm_builder::AllowUnpaidExecutionFrom;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
@@ -0,0 +1,16 @@
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_simulator::mock_message_queue::ParachainId;
use crate::xcm_mock::parachain::Runtime;
parameter_types! {
pub KsmPerSecondPerByte: (AssetId, u128, u128) = (AssetId(Parent.into()), 1, 1);
pub const MaxAssetsIntoHolding: u32 = 64;
}
parameter_types! {
pub const KsmLocation: Location = Location::parent();
pub const RelayNetwork: NetworkId = NetworkId::Kusama;
pub UniversalLocation: InteriorLocation = [GlobalConsensus(RelayNetwork::get()), Parachain(ParachainId::<Runtime>::get().into())].into();
}
@@ -0,0 +1,10 @@
use xcm_builder::{AccountId32Aliases, DescribeAllTerminal, DescribeFamily, HashedDescription};
use crate::xcm_mock::parachain::{constants::RelayNetwork, AccountId};
type LocationToAccountId = (
HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
AccountId32Aliases<RelayNetwork, AccountId>,
);
pub type LocationConverter = LocationToAccountId;
@@ -0,0 +1,47 @@
pub mod asset_transactor;
pub mod barrier;
pub mod constants;
pub mod location_converter;
pub mod origin_converter;
pub mod weigher;
use frame_support::traits::{Everything, Nothing};
use xcm_builder::{EnsureDecodableXcm, FixedRateOfFungible, FrameTransactionalProcessor};
use crate::xcm_mock::parachain::{MsgQueue, PolkadotXcm, RuntimeCall};
// Generated from `decl_test_network!`
pub type XcmRouter = EnsureDecodableXcm<crate::xcm_mock::ParachainXcmRouter<MsgQueue>>;
pub struct XcmConfig;
impl xcm_executor::Config for XcmConfig {
type Aliasers = Nothing;
type AssetClaims = ();
type AssetExchanger = ();
type AssetLocker = PolkadotXcm;
type AssetTransactor = asset_transactor::AssetTransactor;
type AssetTrap = ();
type Barrier = barrier::Barrier;
type CallDispatcher = RuntimeCall;
type FeeManager = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type HrmpNewChannelOpenRequestHandler = ();
type IsReserve = ();
type IsTeleporter = ();
type MaxAssetsIntoHolding = constants::MaxAssetsIntoHolding;
type MessageExporter = ();
type OriginConverter = origin_converter::OriginConverter;
type PalletInstancesInfo = ();
type ResponseHandler = ();
type RuntimeCall = RuntimeCall;
type SafeCallFilter = Everything;
type SubscriptionService = ();
type Trader = FixedRateOfFungible<constants::KsmPerSecondPerByte, ()>;
type TransactionalProcessor = FrameTransactionalProcessor;
type UniversalAliases = Nothing;
type UniversalLocation = constants::UniversalLocation;
type Weigher = weigher::Weigher;
type XcmRecorder = PolkadotXcm;
type XcmSender = XcmRouter;
}
@@ -0,0 +1,14 @@
use pallet_xcm::XcmPassthrough;
use xcm_builder::{SignedAccountId32AsNative, SovereignSignedViaLocation};
use crate::xcm_mock::parachain::{
constants::RelayNetwork, location_converter::LocationConverter, RuntimeOrigin,
};
type XcmOriginToCallOrigin = (
SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
XcmPassthrough<RuntimeOrigin>,
);
pub type OriginConverter = XcmOriginToCallOrigin;
@@ -0,0 +1,12 @@
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_builder::FixedWeightBounds;
use crate::xcm_mock::parachain::RuntimeCall;
parameter_types! {
pub const UnitWeightCost: Weight = Weight::from_parts(1, 1);
pub const MaxInstructions: u32 = 100;
}
pub type Weigher = FixedWeightBounds<UnitWeightCost, RuntimeCall, MaxInstructions>;
@@ -0,0 +1,138 @@
//! Relay chain runtime mock.
mod xcm_config;
use frame_support::{
construct_runtime, derive_impl, parameter_types,
traits::{ConstU128, Everything, Nothing, ProcessMessage, ProcessMessageError},
weights::{Weight, WeightMeter},
};
use frame_system::EnsureRoot;
use polkadot_runtime_parachains::{
configuration,
inclusion::{AggregateMessageOrigin, UmpQueueId},
origin, shared,
};
use sp_core::ConstU32;
use sp_runtime::{traits::IdentityLookup, AccountId32};
use xcm::latest::prelude::*;
use xcm_builder::{IsConcrete, SignedToAccountId32};
pub use xcm_config::*;
use xcm_executor::XcmExecutor;
pub type AccountId = AccountId32;
pub type Balance = u128;
parameter_types! {
pub const BlockHashCount: u64 = 250;
}
#[derive_impl(frame_system::config_preludes::TestDefaultConfig)]
impl frame_system::Config for Runtime {
type AccountData = pallet_balances::AccountData<Balance>;
type AccountId = AccountId;
type Block = Block;
type Lookup = IdentityLookup<Self::AccountId>;
}
#[derive_impl(pallet_balances::config_preludes::TestDefaultConfig)]
impl pallet_balances::Config for Runtime {
type AccountStore = System;
type Balance = Balance;
type ExistentialDeposit = ConstU128<1>;
}
impl shared::Config for Runtime {
type DisabledValidators = ();
}
impl configuration::Config for Runtime {
type WeightInfo = configuration::TestWeightInfo;
}
pub type LocalOriginToLocation =
SignedToAccountId32<RuntimeOrigin, AccountId, constants::RelayNetwork>;
impl pallet_xcm::Config for Runtime {
type AdminOrigin = EnsureRoot<AccountId>;
type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
type Currency = Balances;
type CurrencyMatcher = IsConcrete<constants::TokenLocation>;
// Anyone can execute XCM messages locally...
type ExecuteXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type MaxLockers = ConstU32<8>;
type MaxRemoteLockConsumers = ConstU32<0>;
type RemoteLockConsumerIdentifier = ();
type RuntimeCall = RuntimeCall;
type RuntimeEvent = RuntimeEvent;
type RuntimeOrigin = RuntimeOrigin;
type SendXcmOrigin = xcm_builder::EnsureXcmOrigin<RuntimeOrigin, LocalOriginToLocation>;
type SovereignAccountOf = location_converter::LocationConverter;
type TrustedLockers = ();
type UniversalLocation = constants::UniversalLocation;
type Weigher = weigher::Weigher;
type WeightInfo = pallet_xcm::TestWeightInfo;
type XcmExecuteFilter = Nothing;
type XcmExecutor = XcmExecutor<XcmConfig>;
type XcmReserveTransferFilter = Everything;
type XcmRouter = XcmRouter;
type XcmTeleportFilter = Everything;
const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
}
impl origin::Config for Runtime {}
type Block = frame_system::mocking::MockBlock<Runtime>;
parameter_types! {
/// Amount of weight that can be spent per block to service messages.
pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
pub const MessageQueueHeapSize: u32 = 65_536;
pub const MessageQueueMaxStale: u32 = 16;
}
/// Message processor to handle any messages that were enqueued into the `MessageQueue` pallet.
pub struct MessageProcessor;
impl ProcessMessage for MessageProcessor {
type Origin = AggregateMessageOrigin;
fn process_message(
message: &[u8],
origin: Self::Origin,
meter: &mut WeightMeter,
id: &mut [u8; 32],
) -> Result<bool, ProcessMessageError> {
let para = match origin {
AggregateMessageOrigin::Ump(UmpQueueId::Para(para)) => para,
};
xcm_builder::ProcessXcmMessage::<
Junction,
xcm_executor::XcmExecutor<XcmConfig>,
RuntimeCall,
>::process_message(message, Junction::Parachain(para.into()), meter, id)
}
}
impl pallet_message_queue::Config for Runtime {
type HeapSize = MessageQueueHeapSize;
type IdleMaxServiceWeight = ();
type MaxStale = MessageQueueMaxStale;
type MessageProcessor = MessageProcessor;
type QueueChangeHandler = ();
type QueuePausedQuery = ();
type RuntimeEvent = RuntimeEvent;
type ServiceWeight = MessageQueueServiceWeight;
type Size = u32;
type WeightInfo = ();
}
construct_runtime!(
pub enum Runtime
{
System: frame_system,
Balances: pallet_balances,
ParasOrigin: origin,
XcmPallet: pallet_xcm,
MessageQueue: pallet_message_queue,
}
);
@@ -0,0 +1,8 @@
use xcm_builder::{FungibleAdapter, IsConcrete};
use crate::xcm_mock::relay_chain::{
constants::TokenLocation, location_converter::LocationConverter, AccountId, Balances,
};
pub type AssetTransactor =
FungibleAdapter<Balances, IsConcrete<TokenLocation>, LocationConverter, AccountId, ()>;
@@ -0,0 +1,4 @@
use frame_support::traits::Everything;
use xcm_builder::AllowUnpaidExecutionFrom;
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
@@ -0,0 +1,15 @@
use frame_support::parameter_types;
use xcm::latest::prelude::*;
parameter_types! {
pub TokensPerSecondPerByte: (AssetId, u128, u128) =
(AssetId(TokenLocation::get()), 1_000_000_000_000, 1024 * 1024);
pub const MaxAssetsIntoHolding: u32 = 64;
}
parameter_types! {
pub const TokenLocation: Location = Here.into_location();
pub RelayNetwork: NetworkId = ByGenesis([0; 32]);
pub UniversalLocation: InteriorLocation = RelayNetwork::get().into();
pub UnitWeightCost: u64 = 1_000;
}
@@ -0,0 +1,10 @@
use xcm_builder::{AccountId32Aliases, DescribeAllTerminal, DescribeFamily, HashedDescription};
use crate::xcm_mock::relay_chain::{constants::RelayNetwork, AccountId};
type LocationToAccountId = (
HashedDescription<AccountId, DescribeFamily<DescribeAllTerminal>>,
AccountId32Aliases<RelayNetwork, AccountId>,
);
pub type LocationConverter = LocationToAccountId;
@@ -0,0 +1,48 @@
pub mod asset_transactor;
pub mod barrier;
pub mod constants;
pub mod location_converter;
pub mod origin_converter;
pub mod weigher;
use frame_support::traits::{Everything, Nothing};
use xcm_builder::{EnsureDecodableXcm, FixedRateOfFungible, FrameTransactionalProcessor};
use xcm_executor::Config;
use crate::xcm_mock::relay_chain::{RuntimeCall, XcmPallet};
// Generated from `decl_test_network!`
pub type XcmRouter = EnsureDecodableXcm<crate::xcm_mock::RelayChainXcmRouter>;
pub struct XcmConfig;
impl Config for XcmConfig {
type Aliasers = Nothing;
type AssetClaims = ();
type AssetExchanger = ();
type AssetLocker = XcmPallet;
type AssetTransactor = asset_transactor::AssetTransactor;
type AssetTrap = ();
type Barrier = barrier::Barrier;
type CallDispatcher = RuntimeCall;
type FeeManager = ();
type HrmpChannelAcceptedHandler = ();
type HrmpChannelClosingHandler = ();
type HrmpNewChannelOpenRequestHandler = ();
type IsReserve = ();
type IsTeleporter = ();
type MaxAssetsIntoHolding = constants::MaxAssetsIntoHolding;
type MessageExporter = ();
type OriginConverter = origin_converter::OriginConverter;
type PalletInstancesInfo = ();
type ResponseHandler = ();
type RuntimeCall = RuntimeCall;
type SafeCallFilter = Everything;
type SubscriptionService = ();
type Trader = FixedRateOfFungible<constants::TokensPerSecondPerByte, ()>;
type TransactionalProcessor = FrameTransactionalProcessor;
type UniversalAliases = Nothing;
type UniversalLocation = constants::UniversalLocation;
type Weigher = weigher::Weigher;
type XcmRecorder = XcmPallet;
type XcmSender = XcmRouter;
}
@@ -0,0 +1,19 @@
use polkadot_parachain_primitives::primitives::Id as ParaId;
use polkadot_runtime_parachains::origin;
use xcm_builder::{
ChildParachainAsNative, ChildSystemParachainAsSuperuser, SignedAccountId32AsNative,
SovereignSignedViaLocation,
};
use crate::xcm_mock::relay_chain::{
constants::RelayNetwork, location_converter::LocationConverter, RuntimeOrigin,
};
type LocalOriginConverter = (
SovereignSignedViaLocation<LocationConverter, RuntimeOrigin>,
ChildParachainAsNative<origin::Origin, RuntimeOrigin>,
SignedAccountId32AsNative<RelayNetwork, RuntimeOrigin>,
ChildSystemParachainAsSuperuser<ParaId, RuntimeOrigin>,
);
pub type OriginConverter = LocalOriginConverter;
@@ -0,0 +1,12 @@
use frame_support::parameter_types;
use xcm::latest::prelude::*;
use xcm_builder::FixedWeightBounds;
use crate::xcm_mock::relay_chain::RuntimeCall;
parameter_types! {
pub const BaseXcmWeight: Weight = Weight::from_parts(1_000, 1_000);
pub const MaxInstructions: u32 = 100;
}
pub type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;