1
// Copyright 2019-2025 PureStake Inc.
2
// This file is part of Moonbeam.
3

            
4
// Moonbeam is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8

            
9
// Moonbeam is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13

            
14
// You should have received a copy of the GNU General Public License
15
// along with Moonbeam.  If not, see <http://www.gnu.org/licenses/>.
16

            
17
//! Test utilities
18
use super::*;
19
use cumulus_primitives_core::{relay_chain::HrmpChannelId, ParaId};
20
use frame_support::traits::{
21
	EnsureOrigin, Everything, Nothing, OriginTrait, PalletInfo as PalletInfoTrait,
22
};
23
use frame_support::{construct_runtime, parameter_types, weights::Weight};
24
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
25
use parity_scale_codec::{Decode, Encode};
26
use precompile_utils::{mock_account, precompile_set::*, testing::MockAccount};
27
use scale_info::TypeInfo;
28
use sp_core::H256;
29
use sp_runtime::BuildStorage;
30
use sp_runtime::{
31
	traits::{BlakeTwo256, IdentityLookup},
32
	Perbill,
33
};
34
use xcm::latest::{prelude::*, Error as XcmError};
35
use xcm_builder::{AllowUnpaidExecutionFrom, FixedWeightBounds};
36
use xcm_executor::{
37
	traits::{TransactAsset, WeightTrader},
38
	AssetsInHolding,
39
};
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43
pub type AssetId = u128;
44
type XcmV2Weight = u64;
45

            
46
type Block = frame_system::mocking::MockBlockU32<Runtime>;
47

            
48
53
construct_runtime!(
49
	pub enum Runtime	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		Evm: pallet_evm,
53
		Timestamp: pallet_timestamp,
54
		PolkadotXcm: pallet_xcm,
55
		XcmTransactor: pallet_xcm_transactor,
56
	}
57
88
);
58

            
59
mock_account!(SelfReserveAccount, |_| MockAccount::from_u64(2));
60

            
61
parameter_types! {
62
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
63
	pub UniversalLocation: InteriorLocation = RelayNetwork::get().into();
64
}
65

            
66
parameter_types! {
67
	pub const BlockHashCount: u32 = 250;
68
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
69
	pub const MaximumBlockLength: u32 = 2 * 1024;
70
	pub const AvailableBlockRatio: Perbill = Perbill::one();
71
	pub const SS58Prefix: u8 = 42;
72
}
73

            
74
impl frame_system::Config for Runtime {
75
	type BaseCallFilter = Everything;
76
	type DbWeight = ();
77
	type RuntimeOrigin = RuntimeOrigin;
78
	type RuntimeTask = RuntimeTask;
79
	type Nonce = u64;
80
	type Block = Block;
81
	type RuntimeCall = RuntimeCall;
82
	type Hash = H256;
83
	type Hashing = BlakeTwo256;
84
	type AccountId = AccountId;
85
	type Lookup = IdentityLookup<Self::AccountId>;
86
	type RuntimeEvent = RuntimeEvent;
87
	type BlockHashCount = BlockHashCount;
88
	type Version = ();
89
	type PalletInfo = PalletInfo;
90
	type AccountData = pallet_balances::AccountData<Balance>;
91
	type OnNewAccount = ();
92
	type OnKilledAccount = ();
93
	type SystemWeightInfo = ();
94
	type BlockWeights = ();
95
	type BlockLength = ();
96
	type SS58Prefix = SS58Prefix;
97
	type OnSetCode = ();
98
	type MaxConsumers = frame_support::traits::ConstU32<16>;
99
	type SingleBlockMigrations = ();
100
	type MultiBlockMigrator = ();
101
	type PreInherents = ();
102
	type PostInherents = ();
103
	type PostTransactions = ();
104
}
105
parameter_types! {
106
	pub const ExistentialDeposit: u128 = 0;
107
}
108
impl pallet_balances::Config for Runtime {
109
	type MaxReserves = ();
110
	type ReserveIdentifier = [u8; 4];
111
	type MaxLocks = ();
112
	type Balance = Balance;
113
	type RuntimeEvent = RuntimeEvent;
114
	type DustRemoval = ();
115
	type ExistentialDeposit = ExistentialDeposit;
116
	type AccountStore = System;
117
	type WeightInfo = ();
118
	type RuntimeHoldReason = ();
119
	type FreezeIdentifier = ();
120
	type MaxFreezes = ();
121
	type RuntimeFreezeReason = ();
122
}
123

            
124
pub struct DoNothingRouter;
125
impl SendXcm for DoNothingRouter {
126
	type Ticket = ();
127

            
128
	fn validate(
129
		_destination: &mut Option<Location>,
130
		_message: &mut Option<Xcm<()>>,
131
	) -> SendResult<Self::Ticket> {
132
		Ok(((), Assets::new()))
133
	}
134

            
135
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
136
		Ok(XcmHash::default())
137
	}
138
}
139

            
140
impl pallet_xcm::Config for Runtime {
141
	type RuntimeEvent = RuntimeEvent;
142
	type ExecuteXcmOrigin = ConvertOriginToLocal;
143
	type XcmExecuteFilter = Everything;
144
	type XcmExecutor = xcm_executor::XcmExecutor<XcmConfig>;
145
	type XcmRouter = DoNothingRouter;
146
	type SendXcmOrigin = ConvertOriginToLocal;
147
	type Weigher = xcm_builder::FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
148
	type UniversalLocation = UniversalLocation;
149
	type XcmTeleportFilter = frame_support::traits::Everything;
150
	type XcmReserveTransferFilter = frame_support::traits::Everything;
151
	type RuntimeOrigin = RuntimeOrigin;
152
	type RuntimeCall = RuntimeCall;
153
	const VERSION_DISCOVERY_QUEUE_SIZE: u32 = 100;
154
	type AdvertisedXcmVersion = pallet_xcm::CurrentXcmVersion;
155
	type Currency = Balances;
156
	type CurrencyMatcher = ();
157
	type TrustedLockers = ();
158
	type SovereignAccountOf = ();
159
	type MaxLockers = ConstU32<8>;
160
	type WeightInfo = pallet_xcm::TestWeightInfo;
161
	type MaxRemoteLockConsumers = ConstU32<0>;
162
	type RemoteLockConsumerIdentifier = ();
163
	type AdminOrigin = frame_system::EnsureRoot<AccountId>;
164
}
165

            
166
parameter_types! {
167
	pub const MaxAssetsIntoHolding: u32 = 64;
168
}
169

            
170
pub struct XcmConfig;
171
impl xcm_executor::Config for XcmConfig {
172
	type RuntimeCall = RuntimeCall;
173
	type AssetTransactor = DummyAssetTransactor;
174
	type OriginConverter = pallet_xcm::XcmPassthrough<RuntimeOrigin>;
175
	type IsReserve = ();
176
	type IsTeleporter = ();
177
	type Barrier = Barrier;
178
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
179
	type Trader = DummyWeightTrader;
180
	type ResponseHandler = ();
181
	type SubscriptionService = ();
182
	type AssetTrap = ();
183
	type AssetClaims = ();
184
	type CallDispatcher = RuntimeCall;
185
	type XcmSender = DoNothingRouter;
186
	type UniversalLocation = UniversalLocation;
187
	type AssetLocker = ();
188
	type AssetExchanger = ();
189
	type PalletInstancesInfo = ();
190
	type MaxAssetsIntoHolding = MaxAssetsIntoHolding;
191
	type FeeManager = ();
192
	type MessageExporter = ();
193
	type UniversalAliases = Nothing;
194
	type SafeCallFilter = Everything;
195
	type Aliasers = Nothing;
196
	type TransactionalProcessor = ();
197
	type HrmpNewChannelOpenRequestHandler = ();
198
	type HrmpChannelAcceptedHandler = ();
199
	type HrmpChannelClosingHandler = ();
200
	type XcmRecorder = ();
201
}
202

            
203
pub type Precompiles<R> = PrecompileSetBuilder<
204
	R,
205
	(
206
		PrecompileAt<AddressU64<1>, GmpPrecompile<R>, (SubcallWithMaxNesting<1>,)>,
207
		RevertPrecompile<AddressU64<2>>,
208
	),
209
>;
210

            
211
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
212

            
213
pub struct DummyAssetTransactor;
214
impl TransactAsset for DummyAssetTransactor {
215
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
216
		Ok(())
217
	}
218

            
219
	fn withdraw_asset(
220
		_what: &Asset,
221
		_who: &Location,
222
		_maybe_context: Option<&XcmContext>,
223
	) -> Result<AssetsInHolding, XcmError> {
224
		Ok(AssetsInHolding::default())
225
	}
226
}
227

            
228
pub struct DummyWeightTrader;
229
impl WeightTrader for DummyWeightTrader {
230
	fn new() -> Self {
231
		DummyWeightTrader
232
	}
233

            
234
	fn buy_weight(
235
		&mut self,
236
		_weight: Weight,
237
		_payment: AssetsInHolding,
238
		_context: &XcmContext,
239
	) -> Result<AssetsInHolding, XcmError> {
240
		Ok(AssetsInHolding::default())
241
	}
242
}
243

            
244
pub type PCall = GmpPrecompileCall<Runtime>;
245

            
246
mock_account!(Batch, |_| MockAccount::from_u64(1));
247
mock_account!(Revert, |_| MockAccount::from_u64(2));
248

            
249
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
250
/// Block storage limit in bytes. Set to 40 KB.
251
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
252

            
253
parameter_types! {
254
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
255
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
256
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
257
	pub GasLimitPovSizeRatio: u64 = {
258
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
259
		block_gas_limit.saturating_div(MAX_POV_SIZE)
260
	};
261
	pub GasLimitStorageGrowthRatio: u64 = {
262
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
263
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
264
	};
265
}
266

            
267
impl pallet_evm::Config for Runtime {
268
	type FeeCalculator = ();
269
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
270
	type WeightPerGas = WeightPerGas;
271
	type CallOrigin = EnsureAddressRoot<AccountId>;
272
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
273
	type AddressMapping = AccountId;
274
	type Currency = Balances;
275
	type RuntimeEvent = RuntimeEvent;
276
	type Runner = pallet_evm::runner::stack::Runner<Self>;
277
	type PrecompilesType = Precompiles<Runtime>;
278
	type PrecompilesValue = PrecompilesValue;
279
	type ChainId = ();
280
	type OnChargeTransaction = ();
281
	type BlockGasLimit = BlockGasLimit;
282
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
283
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
284
	type FindAuthor = ();
285
	type OnCreate = ();
286
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
287
	type SuicideQuickClearLimit = ConstU32<0>;
288
	type Timestamp = Timestamp;
289
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
290
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
291
}
292

            
293
#[derive(Encode, Decode)]
294
pub enum RelayCall {
295
	#[codec(index = 5u8)]
296
	// the index should match the position of the module in `construct_runtime!`
297
	Utility(UtilityCall),
298
	#[codec(index = 6u8)]
299
	// the index should match the position of the module in `construct_runtime!`
300
	Hrmp(HrmpCall),
301
}
302

            
303
#[derive(Encode, Decode)]
304
pub enum UtilityCall {
305
	#[codec(index = 1u8)]
306
	AsDerivative(u16),
307
}
308

            
309
// HRMP call encoding, needed for xcm transactor pallet
310
#[derive(Encode, Decode)]
311
pub enum HrmpCall {
312
	#[codec(index = 0u8)]
313
	InitOpenChannel(ParaId, u32, u32),
314
	#[codec(index = 1u8)]
315
	AcceptOpenChannel(ParaId),
316
	#[codec(index = 2u8)]
317
	CloseChannel(HrmpChannelId),
318
	#[codec(index = 6u8)]
319
	CancelOpenRequest(HrmpChannelId, u32),
320
}
321

            
322
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
323
pub enum MockTransactors {
324
	Relay,
325
}
326

            
327
impl xcm_primitives::XcmTransact for MockTransactors {
328
	fn destination(self) -> Location {
329
		match self {
330
			MockTransactors::Relay => Location::parent(),
331
		}
332
	}
333
}
334

            
335
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
336
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
337
		match self {
338
			MockTransactors::Relay => match call {
339
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
340
					let mut call =
341
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
342
					call.append(&mut b.clone());
343
					call
344
				}
345
			},
346
		}
347
	}
348
}
349

            
350
parameter_types! {
351
	pub SelfLocationAbsolute: Location = Location {
352
		parents: 1,
353
		interior: [Parachain(ParachainId::get().into())].into(),
354
	};
355
}
356

            
357
impl pallet_xcm_transactor::Config for Runtime {
358
	type RuntimeEvent = RuntimeEvent;
359
	type Balance = Balance;
360
	type Transactor = MockTransactors;
361
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
362
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
363
	type CurrencyId = CurrencyId;
364
	type AccountIdToLocation = AccountIdToLocation;
365
	type CurrencyIdToLocation = CurrencyIdToMultiLocation;
366
	type SelfLocation = SelfLocation;
367
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
368
	type UniversalLocation = UniversalLocation;
369
	type BaseXcmWeight = BaseXcmWeight;
370
	type XcmSender = DoNothingRouter;
371
	type AssetTransactor = DummyAssetTransactor;
372
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
373
	type WeightInfo = ();
374
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
375
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
376
	type MaxHrmpFee = ();
377
}
378

            
379
parameter_types! {
380
	pub const MinimumPeriod: u64 = 5;
381
}
382
impl pallet_timestamp::Config for Runtime {
383
	type Moment = u64;
384
	type OnTimestampSet = ();
385
	type MinimumPeriod = MinimumPeriod;
386
	type WeightInfo = ();
387
}
388

            
389
pub struct ConvertOriginToLocal;
390
impl<Origin: OriginTrait> EnsureOrigin<Origin> for ConvertOriginToLocal {
391
	type Success = Location;
392

            
393
	fn try_origin(_: Origin) -> Result<Location, Origin> {
394
		Ok(Location::here())
395
	}
396

            
397
	#[cfg(feature = "runtime-benchmarks")]
398
	fn try_successful_origin() -> Result<Origin, ()> {
399
		Ok(Origin::root())
400
	}
401
}
402

            
403
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
404
pub enum CurrencyId {
405
	SelfReserve,
406
	OtherReserve(AssetId),
407
}
408

            
409
// Implement the trait, where we convert AccountId to AssetID
410
impl AccountIdToCurrencyId<AccountId, CurrencyId> for Runtime {
411
	/// The way to convert an account to assetId is by ensuring that the prefix is 0XFFFFFFFF
412
	/// and by taking the lowest 128 bits as the assetId
413
	fn account_to_currency_id(account: AccountId) -> Option<CurrencyId> {
414
		match account {
415
			a if a.has_prefix_u32(0xffffffff) => Some(CurrencyId::OtherReserve(a.without_prefix())),
416
			a if a == AccountId::from(SelfReserveAccount) => Some(CurrencyId::SelfReserve),
417
			_ => None,
418
		}
419
	}
420
}
421

            
422
pub struct AccountIdToLocation;
423
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
424
	fn convert(account: AccountId) -> Location {
425
		let as_h160: H160 = account.into();
426
		Location::new(
427
			1,
428
			[AccountKey20 {
429
				network: None,
430
				key: as_h160.as_fixed_bytes().clone(),
431
			}],
432
		)
433
	}
434
}
435

            
436
parameter_types! {
437
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
438

            
439
	pub const BaseXcmWeight: XcmV2Weight = 1000;
440
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
441
	pub const MaxAssetsForTransfer: usize = 2;
442

            
443
	pub SelfLocation: Location =
444
		Location::new(1, [Parachain(ParachainId::get().into())]);
445

            
446
	pub SelfReserve: Location = Location::new(
447
		1,
448
		[
449
			Parachain(ParachainId::get().into()),
450
			PalletInstance(
451
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
452
			)
453
		]);
454
	pub MaxInstructions: u32 = 100;
455
}
456

            
457
pub struct CurrencyIdToMultiLocation;
458

            
459
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToMultiLocation {
460
	fn convert(currency: CurrencyId) -> Option<Location> {
461
		match currency {
462
			CurrencyId::SelfReserve => {
463
				let multi: Location = SelfReserve::get();
464
				Some(multi)
465
			}
466
			// To distinguish between relay and others, specially for reserve asset
467
			CurrencyId::OtherReserve(asset) => {
468
				if asset == 0 {
469
					Some(Location::parent())
470
				} else {
471
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
472
				}
473
			}
474
		}
475
	}
476
}
477

            
478
pub(crate) struct ExtBuilder {
479
	/// Endowed accounts with balances
480
	balances: Vec<(AccountId, Balance)>,
481
}
482

            
483
impl Default for ExtBuilder {
484
3
	fn default() -> ExtBuilder {
485
3
		ExtBuilder { balances: vec![] }
486
3
	}
487
}
488

            
489
impl ExtBuilder {
490
	/// Fund some accounts before starting the test
491
3
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
492
3
		self.balances = balances;
493
3
		self
494
3
	}
495

            
496
	/// Build the test externalities for use in tests
497
3
	pub(crate) fn build(self) -> sp_io::TestExternalities {
498
3
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
499
3
			.build_storage()
500
3
			.expect("Frame system builds valid default genesis config");
501
3

            
502
3
		pallet_balances::GenesisConfig::<Runtime> {
503
3
			balances: self.balances.clone(),
504
3
		}
505
3
		.assimilate_storage(&mut t)
506
3
		.expect("Pallet balances storage can be assimilated");
507
3

            
508
3
		let mut ext = sp_io::TestExternalities::new(t);
509
3
		ext.execute_with(|| {
510
3
			System::set_block_number(1);
511
3
		});
512
3
		ext
513
3
	}
514
}