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
6
	pub enum Runtime	{
50
6
		System: frame_system,
51
6
		Balances: pallet_balances,
52
6
		Evm: pallet_evm,
53
6
		Timestamp: pallet_timestamp,
54
6
		PolkadotXcm: pallet_xcm,
55
6
		XcmTransactor: pallet_xcm_transactor,
56
6
	}
57
54
);
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
	type ExtensionsWeightInfo = ();
105
}
106
parameter_types! {
107
	pub const ExistentialDeposit: u128 = 0;
108
}
109
impl pallet_balances::Config for Runtime {
110
	type MaxReserves = ();
111
	type ReserveIdentifier = [u8; 4];
112
	type MaxLocks = ();
113
	type Balance = Balance;
114
	type RuntimeEvent = RuntimeEvent;
115
	type DustRemoval = ();
116
	type ExistentialDeposit = ExistentialDeposit;
117
	type AccountStore = System;
118
	type WeightInfo = ();
119
	type RuntimeHoldReason = ();
120
	type FreezeIdentifier = ();
121
	type MaxFreezes = ();
122
	type RuntimeFreezeReason = ();
123
	type DoneSlashHandler = ();
124
}
125

            
126
pub struct DoNothingRouter;
127
impl SendXcm for DoNothingRouter {
128
	type Ticket = ();
129

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

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

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

            
168
parameter_types! {
169
	pub const MaxAssetsIntoHolding: u32 = 64;
170
}
171

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

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

            
213
pub type Barrier = AllowUnpaidExecutionFrom<Everything>;
214

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

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

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

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

            
246
pub type PCall = GmpPrecompileCall<Runtime>;
247

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
458
pub struct CurrencyIdToMultiLocation;
459

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

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

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

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

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

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

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