Lines
35.51 %
Functions
7.58 %
Branches
100 %
// Copyright 2019-2025 PureStake Inc.
// This file is part of Moonbeam.
// Moonbeam 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.
// Moonbeam 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 Moonbeam. If not, see <http://www.gnu.org/licenses/>.
//! Test utilities
use super::*;
use cumulus_primitives_core::AggregateMessageOrigin;
use frame_support::{
construct_runtime, parameter_types,
traits::{Everything, PalletInfo as PalletInfoTrait},
weights::Weight,
};
use pallet_evm::{
EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, SubstrateBlockHashMapping,
use parity_scale_codec::{Decode, Encode};
use precompile_utils::{precompile_set::*, testing::MockAccount};
use scale_info::TypeInfo;
use sp_core::{H160, H256};
use sp_runtime::{
traits::{BlakeTwo256, IdentityLookup},
BuildStorage, Perbill,
use xcm::latest::{prelude::*, Error as XcmError};
use xcm_builder::FixedWeightBounds;
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
pub type AccountId = MockAccount;
pub type Balance = u128;
type Block = frame_system::mocking::MockBlockU32<Runtime>;
// Configure a mock runtime to test the pallet.
construct_runtime!(
pub enum Runtime {
System: frame_system,
Balances: pallet_balances,
Evm: pallet_evm,
ParachainSystem: cumulus_pallet_parachain_system,
Timestamp: pallet_timestamp,
XcmTransactor: pallet_xcm_transactor,
MessageQueue: pallet_message_queue,
}
);
parameter_types! {
pub const BlockHashCount: u32 = 250;
pub const SS58Prefix: u8 = 42;
impl frame_system::Config for Runtime {
type BaseCallFilter = Everything;
type DbWeight = ();
type RuntimeOrigin = RuntimeOrigin;
type RuntimeTask = RuntimeTask;
type Nonce = u64;
type Block = Block;
type RuntimeCall = RuntimeCall;
type Hash = H256;
type Hashing = BlakeTwo256;
type AccountId = AccountId;
type Lookup = IdentityLookup<Self::AccountId>;
type RuntimeEvent = RuntimeEvent;
type BlockHashCount = BlockHashCount;
type Version = ();
type PalletInfo = PalletInfo;
type AccountData = pallet_balances::AccountData<Balance>;
type OnNewAccount = ();
type OnKilledAccount = ();
type SystemWeightInfo = ();
type BlockWeights = ();
type BlockLength = ();
type SS58Prefix = SS58Prefix;
type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
type MaxConsumers = frame_support::traits::ConstU32<16>;
type SingleBlockMigrations = ();
type MultiBlockMigrator = ();
type PreInherents = ();
type PostInherents = ();
type PostTransactions = ();
type ExtensionsWeightInfo = ();
pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
impl cumulus_pallet_parachain_system::Config for Runtime {
type SelfParaId = ParachainId;
type OnSystemEvent = ();
type OutboundXcmpMessageSource = ();
type XcmpMessageHandler = ();
type ReservedXcmpWeight = ();
type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
type ReservedDmpWeight = ();
type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
type ConsensusHook = cumulus_pallet_parachain_system::ExpectParentIncluded;
type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight<Runtime>;
type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
pub const MessageQueueHeapSize: u32 = 65_536;
pub const MessageQueueMaxStale: u32 = 16;
impl pallet_message_queue::Config for Runtime {
type Size = u32;
type HeapSize = MessageQueueHeapSize;
type MaxStale = MessageQueueMaxStale;
type ServiceWeight = MessageQueueServiceWeight;
type MessageProcessor =
pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
type QueueChangeHandler = ();
type WeightInfo = ();
type QueuePausedQuery = ();
type IdleMaxServiceWeight = MessageQueueServiceWeight;
pub const ExistentialDeposit: u128 = 0;
impl pallet_balances::Config for Runtime {
type MaxReserves = ();
type ReserveIdentifier = ();
type MaxLocks = ();
type Balance = Balance;
type DustRemoval = ();
type ExistentialDeposit = ExistentialDeposit;
type AccountStore = System;
type RuntimeHoldReason = ();
type FreezeIdentifier = ();
type MaxFreezes = ();
type RuntimeFreezeReason = ();
type DoneSlashHandler = ();
pub type AssetId = u128;
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
pub enum CurrencyId {
SelfReserve,
OtherReserve(AssetId),
pub struct DoNothingRouter;
impl SendXcm for DoNothingRouter {
type Ticket = ();
fn validate(
_destination: &mut Option<Location>,
_message: &mut Option<Xcm<()>>,
) -> SendResult<Self::Ticket> {
Ok(((), Assets::new()))
fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
Ok(XcmHash::default())
pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
pub SelfLocation: Location =
Location::new(1, [Parachain(ParachainId::get().into())]);
pub SelfReserve: Location = Location::new(
1,
[
Parachain(ParachainId::get().into()),
PalletInstance(
<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
)
]);
pub MaxInstructions: u32 = 100;
pub UniversalLocation: InteriorLocation = Here;
pub struct AccountIdToLocation;
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
fn convert(account: AccountId) -> Location {
let as_h160: H160 = account.into();
Location::new(
0,
[AccountKey20 {
network: None,
key: as_h160.as_fixed_bytes().clone(),
}],
pub struct CurrencyIdToLocation;
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
fn convert(currency: CurrencyId) -> Option<Location> {
match currency {
CurrencyId::SelfReserve => {
let multi: Location = SelfReserve::get();
Some(multi)
// To distinguish between relay and others, specially for reserve asset
CurrencyId::OtherReserve(asset) => {
if asset == 0 {
Some(Location::parent())
} else {
Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
// We need to use the encoding from the relay mock runtime
#[derive(Encode, Decode)]
pub enum RelayCall {
#[codec(index = 5u8)]
// the index should match the position of the module in `construct_runtime!`
Utility(UtilityCall),
pub enum UtilityCall {
#[codec(index = 1u8)]
AsDerivative(u16),
pub enum MockTransactors {
Relay,
impl TryFrom<u8> for MockTransactors {
type Error = ();
fn try_from(value: u8) -> Result<Self, Self::Error> {
match value {
0x0 => Ok(MockTransactors::Relay),
_ => Err(()),
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
match self {
MockTransactors::Relay => match call {
xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
let mut call =
RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
call.append(&mut b.clone());
call
},
impl xcm_primitives::XcmTransact for MockTransactors {
fn destination(self) -> Location {
MockTransactors::Relay => Location::parent(),
pub struct DummyAssetTransactor;
impl TransactAsset for DummyAssetTransactor {
fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
Ok(())
fn withdraw_asset(
_what: &Asset,
_who: &Location,
_maybe_context: Option<&XcmContext>,
) -> Result<AssetsInHolding, XcmError> {
Ok(AssetsInHolding::default())
pub SelfLocationAbsolute: Location = Location {
parents: 1,
interior: [Parachain(ParachainId::get().into())].into(),
impl pallet_xcm_transactor::Config for Runtime {
type Transactor = MockTransactors;
type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
type CurrencyId = CurrencyId;
type AccountIdToLocation = AccountIdToLocation;
type CurrencyIdToLocation = CurrencyIdToLocation;
type SelfLocation = SelfLocation;
type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
type UniversalLocation = UniversalLocation;
type BaseXcmWeight = BaseXcmWeight;
type XcmSender = DoNothingRouter;
type AssetTransactor = DummyAssetTransactor;
type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
type MaxHrmpFee = ();
pub type Precompiles<R> =
PrecompileSetBuilder<R, PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R>>>;
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
/// Block storage limit in bytes. Set to 40 KB.
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
pub BlockGasLimit: U256 = U256::from(u64::MAX);
pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
pub GasLimitPovSizeRatio: u64 = {
let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
block_gas_limit.saturating_div(MAX_POV_SIZE)
pub GasLimitStorageGrowthRatio: u64 = {
block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
impl pallet_evm::Config for Runtime {
type FeeCalculator = ();
type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
type WeightPerGas = WeightPerGas;
type CallOrigin = EnsureAddressRoot<AccountId>;
type WithdrawOrigin = EnsureAddressNever<AccountId>;
type AddressMapping = AccountId;
type Currency = Balances;
type Runner = pallet_evm::runner::stack::Runner<Self>;
type PrecompilesValue = PrecompilesValue;
type PrecompilesType = Precompiles<Self>;
type ChainId = ();
type OnChargeTransaction = ();
type BlockGasLimit = BlockGasLimit;
type BlockHashMapping = SubstrateBlockHashMapping<Self>;
type FindAuthor = ();
type OnCreate = ();
type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
type Timestamp = Timestamp;
type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
type AccountProvider = FrameSystemAccountProvider<Runtime>;
pub const MinimumPeriod: u64 = 5;
impl pallet_timestamp::Config for Runtime {
type Moment = u64;
type OnTimestampSet = ();
type MinimumPeriod = MinimumPeriod;
pub const TestMaxInitContributors: u32 = 8;
pub const TestMinimumReward: u128 = 0;
pub const TestInitialized: bool = false;
pub const TestInitializationPayment: Perbill = Perbill::from_percent(20);
pub(crate) struct ExtBuilder {
// endowed accounts with balances
balances: Vec<(AccountId, Balance)>,
impl Default for ExtBuilder {
fn default() -> ExtBuilder {
ExtBuilder { balances: vec![] }
impl ExtBuilder {
pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
self.balances = balances;
self
pub(crate) fn build(self) -> sp_io::TestExternalities {
let mut t = frame_system::GenesisConfig::<Runtime>::default()
.build_storage()
.expect("Frame system builds valid default genesis config");
pallet_balances::GenesisConfig::<Runtime> {
balances: self.balances,
.assimilate_storage(&mut t)
.expect("Pallet balances storage can be assimilated");
let mut ext = sp_io::TestExternalities::new(t);
ext.execute_with(|| System::set_block_number(1));
ext.execute_with(|| {
pallet_xcm_transactor::RelayIndices::<Runtime>::put(
crate::test_relay_runtime::TEST_RELAY_INDICES,
});
ext