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

            
20
use cumulus_primitives_core::AggregateMessageOrigin;
21
use frame_support::{
22
	construct_runtime, parameter_types,
23
	traits::{Everything, PalletInfo as PalletInfoTrait},
24
	weights::Weight,
25
};
26
use pallet_evm::{
27
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, SubstrateBlockHashMapping,
28
};
29
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
30
use precompile_utils::{precompile_set::*, testing::MockAccount};
31
use scale_info::TypeInfo;
32
use sp_core::{H160, H256};
33
use sp_runtime::{
34
	traits::{BlakeTwo256, IdentityLookup},
35
	BuildStorage, Perbill,
36
};
37
use xcm::latest::{prelude::*, Error as XcmError};
38
use xcm_builder::FixedWeightBounds;
39
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
40

            
41
pub type AccountId = MockAccount;
42
pub type Balance = u128;
43

            
44
type Block = frame_system::mocking::MockBlockU32<Runtime>;
45

            
46
// Configure a mock runtime to test the pallet.
47
13
construct_runtime!(
48
13
	pub enum Runtime	{
49
13
		System: frame_system,
50
13
		Balances: pallet_balances,
51
13
		Evm: pallet_evm,
52
13
		ParachainSystem: cumulus_pallet_parachain_system,
53
13
		Timestamp: pallet_timestamp,
54
13
		XcmTransactor: pallet_xcm_transactor,
55
13
		MessageQueue: pallet_message_queue,
56
13
	}
57
13
);
58

            
59
parameter_types! {
60
	pub const BlockHashCount: u32 = 250;
61
	pub const SS58Prefix: u8 = 42;
62
}
63
impl frame_system::Config for Runtime {
64
	type BaseCallFilter = Everything;
65
	type DbWeight = ();
66
	type RuntimeOrigin = RuntimeOrigin;
67
	type RuntimeTask = RuntimeTask;
68
	type Nonce = u64;
69
	type Block = Block;
70
	type RuntimeCall = RuntimeCall;
71
	type Hash = H256;
72
	type Hashing = BlakeTwo256;
73
	type AccountId = AccountId;
74
	type Lookup = IdentityLookup<Self::AccountId>;
75
	type RuntimeEvent = RuntimeEvent;
76
	type BlockHashCount = BlockHashCount;
77
	type Version = ();
78
	type PalletInfo = PalletInfo;
79
	type AccountData = pallet_balances::AccountData<Balance>;
80
	type OnNewAccount = ();
81
	type OnKilledAccount = ();
82
	type SystemWeightInfo = ();
83
	type BlockWeights = ();
84
	type BlockLength = ();
85
	type SS58Prefix = SS58Prefix;
86
	type OnSetCode = cumulus_pallet_parachain_system::ParachainSetCode<Self>;
87
	type MaxConsumers = frame_support::traits::ConstU32<16>;
88
	type SingleBlockMigrations = ();
89
	type MultiBlockMigrator = ();
90
	type PreInherents = ();
91
	type PostInherents = ();
92
	type PostTransactions = ();
93
	type ExtensionsWeightInfo = ();
94
}
95

            
96
parameter_types! {
97
	pub ParachainId: cumulus_primitives_core::ParaId = 100.into();
98
	pub const RelayOrigin: AggregateMessageOrigin = AggregateMessageOrigin::Parent;
99
}
100

            
101
impl cumulus_pallet_parachain_system::Config for Runtime {
102
	type SelfParaId = ParachainId;
103
	type RuntimeEvent = RuntimeEvent;
104
	type OnSystemEvent = ();
105
	type OutboundXcmpMessageSource = ();
106
	type XcmpMessageHandler = ();
107
	type ReservedXcmpWeight = ();
108
	type DmpQueue = frame_support::traits::EnqueueWithOrigin<MessageQueue, RelayOrigin>;
109
	type ReservedDmpWeight = ();
110
	type CheckAssociatedRelayNumber = cumulus_pallet_parachain_system::RelayNumberStrictlyIncreases;
111
	type ConsensusHook = cumulus_pallet_parachain_system::ExpectParentIncluded;
112
	type WeightInfo = cumulus_pallet_parachain_system::weights::SubstrateWeight<Runtime>;
113
	type SelectCore = cumulus_pallet_parachain_system::DefaultCoreSelector<Runtime>;
114
}
115

            
116
parameter_types! {
117
	pub MessageQueueServiceWeight: Weight = Weight::from_parts(1_000_000_000, 1_000_000);
118
	pub const MessageQueueHeapSize: u32 = 65_536;
119
	pub const MessageQueueMaxStale: u32 = 16;
120
}
121

            
122
impl pallet_message_queue::Config for Runtime {
123
	type RuntimeEvent = RuntimeEvent;
124
	type Size = u32;
125
	type HeapSize = MessageQueueHeapSize;
126
	type MaxStale = MessageQueueMaxStale;
127
	type ServiceWeight = MessageQueueServiceWeight;
128
	type MessageProcessor =
129
		pallet_message_queue::mock_helpers::NoopMessageProcessor<AggregateMessageOrigin>;
130
	type QueueChangeHandler = ();
131
	type WeightInfo = ();
132
	type QueuePausedQuery = ();
133
	type IdleMaxServiceWeight = MessageQueueServiceWeight;
134
}
135

            
136
parameter_types! {
137
	pub const ExistentialDeposit: u128 = 0;
138
}
139
impl pallet_balances::Config for Runtime {
140
	type MaxReserves = ();
141
	type ReserveIdentifier = ();
142
	type MaxLocks = ();
143
	type Balance = Balance;
144
	type RuntimeEvent = RuntimeEvent;
145
	type DustRemoval = ();
146
	type ExistentialDeposit = ExistentialDeposit;
147
	type AccountStore = System;
148
	type WeightInfo = ();
149
	type RuntimeHoldReason = ();
150
	type FreezeIdentifier = ();
151
	type MaxFreezes = ();
152
	type RuntimeFreezeReason = ();
153
	type DoneSlashHandler = ();
154
}
155

            
156
pub type AssetId = u128;
157

            
158
#[derive(
159
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
160
)]
161
pub enum CurrencyId {
162
	SelfReserve,
163
	OtherReserve(AssetId),
164
}
165

            
166
pub struct DoNothingRouter;
167
impl SendXcm for DoNothingRouter {
168
	type Ticket = ();
169

            
170
	fn validate(
171
		_destination: &mut Option<Location>,
172
		_message: &mut Option<Xcm<()>>,
173
	) -> SendResult<Self::Ticket> {
174
		Ok(((), Assets::new()))
175
	}
176

            
177
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
178
		Ok(XcmHash::default())
179
	}
180
}
181

            
182
parameter_types! {
183
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
184

            
185
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
186
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
187

            
188
	pub SelfLocation: Location =
189
		Location::new(1, [Parachain(ParachainId::get().into())]);
190

            
191
	pub SelfReserve: Location = Location::new(
192
		1,
193
		[
194
			Parachain(ParachainId::get().into()),
195
			PalletInstance(
196
				<Runtime as frame_system::Config>::PalletInfo::index::<Balances>().unwrap() as u8
197
			)
198
		]);
199
	pub MaxInstructions: u32 = 100;
200

            
201
	pub UniversalLocation: InteriorLocation = Here;
202
}
203

            
204
pub struct AccountIdToLocation;
205
impl sp_runtime::traits::Convert<AccountId, Location> for AccountIdToLocation {
206
	fn convert(account: AccountId) -> Location {
207
		let as_h160: H160 = account.into();
208
		Location::new(
209
			0,
210
			[AccountKey20 {
211
				network: None,
212
				key: as_h160.as_fixed_bytes().clone(),
213
			}],
214
		)
215
	}
216
}
217

            
218
pub struct CurrencyIdToLocation;
219

            
220
impl sp_runtime::traits::Convert<CurrencyId, Option<Location>> for CurrencyIdToLocation {
221
	fn convert(currency: CurrencyId) -> Option<Location> {
222
		match currency {
223
			CurrencyId::SelfReserve => {
224
				let multi: Location = SelfReserve::get();
225
				Some(multi)
226
			}
227
			// To distinguish between relay and others, specially for reserve asset
228
			CurrencyId::OtherReserve(asset) => {
229
				if asset == 0 {
230
					Some(Location::parent())
231
				} else {
232
					Some(Location::new(1, [Parachain(2), GeneralIndex(asset)]))
233
				}
234
			}
235
		}
236
	}
237
}
238

            
239
// We need to use the encoding from the relay mock runtime
240
#[derive(Encode, Decode)]
241
pub enum RelayCall {
242
	#[codec(index = 5u8)]
243
	// the index should match the position of the module in `construct_runtime!`
244
	Utility(UtilityCall),
245
}
246

            
247
#[derive(Encode, Decode)]
248
pub enum UtilityCall {
249
	#[codec(index = 1u8)]
250
	AsDerivative(u16),
251
}
252

            
253
#[derive(
254
	Clone,
255
	Eq,
256
	Debug,
257
	PartialEq,
258
	Ord,
259
	PartialOrd,
260
	Encode,
261
	Decode,
262
	TypeInfo,
263
	DecodeWithMemTracking,
264
	serde::Serialize,
265
	serde::Deserialize,
266
)]
267
pub enum MockTransactors {
268
	Relay,
269
	AssetHub,
270
}
271

            
272
impl TryFrom<u8> for MockTransactors {
273
	type Error = ();
274

            
275
	fn try_from(value: u8) -> Result<Self, Self::Error> {
276
		match value {
277
			0x0 => Ok(MockTransactors::Relay),
278
			0x1 => Ok(MockTransactors::AssetHub),
279
			_ => Err(()),
280
		}
281
	}
282
}
283

            
284
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
285
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
286
		match self {
287
			MockTransactors::Relay | MockTransactors::AssetHub => match call {
288
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
289
					let mut call =
290
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
291
					call.append(&mut b.clone());
292
					call
293
				}
294
			},
295
		}
296
	}
297
}
298

            
299
impl xcm_primitives::XcmTransact for MockTransactors {
300
	fn destination(self) -> Location {
301
		match self {
302
			MockTransactors::Relay => Location::parent(),
303
			MockTransactors::AssetHub => Location::new(1, [Parachain(1000)]),
304
		}
305
	}
306
}
307

            
308
impl xcm_primitives::RelayChainTransactor for MockTransactors {
309
15
	fn relay() -> Self {
310
15
		MockTransactors::Relay
311
15
	}
312
}
313

            
314
impl xcm_primitives::AssetHubTransactor for MockTransactors {
315
1
	fn asset_hub() -> Self {
316
1
		MockTransactors::AssetHub
317
1
	}
318
}
319

            
320
pub struct DummyAssetTransactor;
321
impl TransactAsset for DummyAssetTransactor {
322
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
323
		Ok(())
324
	}
325

            
326
	fn withdraw_asset(
327
		_what: &Asset,
328
		_who: &Location,
329
		_maybe_context: Option<&XcmContext>,
330
	) -> Result<AssetsInHolding, XcmError> {
331
		Ok(AssetsInHolding::default())
332
	}
333
}
334

            
335
parameter_types! {
336
	pub SelfLocationAbsolute: Location = Location {
337
		parents: 1,
338
		interior: [Parachain(ParachainId::get().into())].into(),
339
	};
340
}
341

            
342
impl pallet_xcm_transactor::Config for Runtime {
343
	type RuntimeEvent = RuntimeEvent;
344
	type Balance = Balance;
345
	type Transactor = MockTransactors;
346
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
347
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
348
	type CurrencyId = CurrencyId;
349
	type AccountIdToLocation = AccountIdToLocation;
350
	type CurrencyIdToLocation = CurrencyIdToLocation;
351
	type SelfLocation = SelfLocation;
352
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
353
	type UniversalLocation = UniversalLocation;
354
	type BaseXcmWeight = BaseXcmWeight;
355
	type XcmSender = DoNothingRouter;
356
	type AssetTransactor = DummyAssetTransactor;
357
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
358
	type WeightInfo = ();
359
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
360
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
361
	type MaxHrmpFee = ();
362
}
363

            
364
pub type Precompiles<R> =
365
	PrecompileSetBuilder<R, PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R>>>;
366

            
367
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
368

            
369
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
370
/// Block storage limit in bytes. Set to 40 KB.
371
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
372

            
373
parameter_types! {
374
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
375
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
376
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
377
	pub GasLimitPovSizeRatio: u64 = {
378
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
379
		block_gas_limit.saturating_div(MAX_POV_SIZE)
380
	};
381
	pub GasLimitStorageGrowthRatio: u64 = {
382
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
383
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
384
	};
385
}
386

            
387
impl pallet_evm::Config for Runtime {
388
	type FeeCalculator = ();
389
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
390
	type WeightPerGas = WeightPerGas;
391
	type CallOrigin = EnsureAddressRoot<AccountId>;
392
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
393
	type AddressMapping = AccountId;
394
	type Currency = Balances;
395
	type RuntimeEvent = RuntimeEvent;
396
	type Runner = pallet_evm::runner::stack::Runner<Self>;
397
	type PrecompilesValue = PrecompilesValue;
398
	type PrecompilesType = Precompiles<Self>;
399
	type ChainId = ();
400
	type OnChargeTransaction = ();
401
	type BlockGasLimit = BlockGasLimit;
402
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
403
	type FindAuthor = ();
404
	type OnCreate = ();
405
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
406
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
407
	type Timestamp = Timestamp;
408
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
409
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
410
	type CreateOriginFilter = ();
411
	type CreateInnerOriginFilter = ();
412
}
413

            
414
parameter_types! {
415
	pub const MinimumPeriod: u64 = 5;
416
}
417
impl pallet_timestamp::Config for Runtime {
418
	type Moment = u64;
419
	type OnTimestampSet = ();
420
	type MinimumPeriod = MinimumPeriod;
421
	type WeightInfo = ();
422
}
423

            
424
parameter_types! {
425
	pub const TestMaxInitContributors: u32 = 8;
426
	pub const TestMinimumReward: u128 = 0;
427
	pub const TestInitialized: bool = false;
428
	pub const TestInitializationPayment: Perbill = Perbill::from_percent(20);
429
}
430

            
431
pub(crate) struct ExtBuilder {
432
	// endowed accounts with balances
433
	balances: Vec<(AccountId, Balance)>,
434
}
435

            
436
impl Default for ExtBuilder {
437
13
	fn default() -> ExtBuilder {
438
13
		ExtBuilder { balances: vec![] }
439
13
	}
440
}
441

            
442
impl ExtBuilder {
443
10
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
444
10
		self.balances = balances;
445
10
		self
446
10
	}
447

            
448
13
	pub(crate) fn build(self) -> sp_io::TestExternalities {
449
13
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
450
13
			.build_storage()
451
13
			.expect("Frame system builds valid default genesis config");
452
13

            
453
13
		pallet_balances::GenesisConfig::<Runtime> {
454
13
			balances: self.balances,
455
13
			dev_accounts: Default::default(),
456
13
		}
457
13
		.assimilate_storage(&mut t)
458
13
		.expect("Pallet balances storage can be assimilated");
459
13

            
460
13
		let mut ext = sp_io::TestExternalities::new(t);
461
13
		ext.execute_with(|| System::set_block_number(1));
462
13
		ext.execute_with(|| {
463
13
			pallet_xcm_transactor::RelayIndices::<Runtime>::put(
464
13
				crate::test_relay_runtime::TEST_RELAY_INDICES,
465
13
			);
466
13
		});
467
13
		ext
468
13
	}
469
}