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 moonbeam_tests_primitives::MemoryFeeTrader;
27
use pallet_evm::{
28
	EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider, SubstrateBlockHashMapping,
29
};
30
use pallet_xcm_transactor::RelayIndices;
31
use parity_scale_codec::{Decode, DecodeWithMemTracking, Encode};
32
use precompile_utils::{precompile_set::*, testing::MockAccount};
33
use scale_info::TypeInfo;
34
use sp_core::{H160, H256};
35
use sp_runtime::{
36
	traits::{BlakeTwo256, IdentityLookup},
37
	BuildStorage, Perbill,
38
};
39
use xcm::latest::{prelude::*, Error as XcmError};
40
use xcm_builder::FixedWeightBounds;
41
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
42

            
43
pub type AccountId = MockAccount;
44
pub type Balance = u128;
45

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

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

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

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

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

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

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

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

            
159
pub type AssetId = u128;
160

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

            
169
pub struct DoNothingRouter;
170
impl SendXcm for DoNothingRouter {
171
	type Ticket = ();
172

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

            
180
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
181
		Ok(XcmHash::default())
182
	}
183
}
184

            
185
parameter_types! {
186
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
187

            
188
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
189
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
190

            
191
	pub SelfLocation: Location =
192
		Location::new(1, [Parachain(ParachainId::get().into())]);
193

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

            
204
	pub UniversalLocation: InteriorLocation = Here;
205
}
206

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

            
221
pub struct CurrencyIdToLocation;
222

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

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

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

            
256
#[derive(
257
	Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo, DecodeWithMemTracking,
258
)]
259
pub enum MockTransactors {
260
	Relay,
261
}
262

            
263
impl TryFrom<u8> for MockTransactors {
264
	type Error = ();
265

            
266
	fn try_from(value: u8) -> Result<Self, Self::Error> {
267
		match value {
268
			0x0 => Ok(MockTransactors::Relay),
269
			_ => Err(()),
270
		}
271
	}
272
}
273

            
274
impl xcm_primitives::XcmTransact for MockTransactors {
275
	fn destination(self) -> Location {
276
		match self {
277
			MockTransactors::Relay => Location::parent(),
278
		}
279
	}
280

            
281
	fn utility_pallet_index(&self) -> u8 {
282
		RelayIndices::<Runtime>::get().utility
283
	}
284

            
285
14
	fn staking_pallet_index(&self) -> u8 {
286
14
		RelayIndices::<Runtime>::get().staking
287
14
	}
288
}
289

            
290
pub struct DummyAssetTransactor;
291
impl TransactAsset for DummyAssetTransactor {
292
	fn deposit_asset(_what: &Asset, _who: &Location, _context: Option<&XcmContext>) -> XcmResult {
293
		Ok(())
294
	}
295

            
296
	fn withdraw_asset(
297
		_what: &Asset,
298
		_who: &Location,
299
		_maybe_context: Option<&XcmContext>,
300
	) -> Result<AssetsInHolding, XcmError> {
301
		Ok(AssetsInHolding::default())
302
	}
303
}
304

            
305
parameter_types! {
306
	pub SelfLocationAbsolute: Location = Location {
307
		parents: 1,
308
		interior: [Parachain(ParachainId::get().into())].into(),
309
	};
310
	pub StakingTransactor: MockTransactors = MockTransactors::Relay;
311
}
312

            
313
impl pallet_xcm_transactor::Config for Runtime {
314
	type Balance = Balance;
315
	type Transactor = MockTransactors;
316
	type DerivativeAddressRegistrationOrigin = frame_system::EnsureRoot<AccountId>;
317
	type SovereignAccountDispatcherOrigin = frame_system::EnsureRoot<AccountId>;
318
	type CurrencyId = CurrencyId;
319
	type AccountIdToLocation = AccountIdToLocation;
320
	type CurrencyIdToLocation = CurrencyIdToLocation;
321
	type SelfLocation = SelfLocation;
322
	type Weigher = FixedWeightBounds<BaseXcmWeight, RuntimeCall, MaxInstructions>;
323
	type UniversalLocation = UniversalLocation;
324
	type BaseXcmWeight = BaseXcmWeight;
325
	type XcmSender = DoNothingRouter;
326
	type AssetTransactor = DummyAssetTransactor;
327
	type ReserveProvider = xcm_primitives::AbsoluteAndRelativeReserve<SelfLocationAbsolute>;
328
	type WeightInfo = ();
329
	type HrmpManipulatorOrigin = frame_system::EnsureRoot<AccountId>;
330
	type HrmpOpenOrigin = frame_system::EnsureRoot<AccountId>;
331
	type MaxHrmpFee = ();
332
	type FeeTrader = MemoryFeeTrader;
333
}
334

            
335
pub type Precompiles<R> = PrecompileSetBuilder<
336
	R,
337
	PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R, StakingTransactor>>,
338
>;
339

            
340
pub type PCall = RelayEncoderPrecompileCall<Runtime, StakingTransactor>;
341

            
342
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
343
/// Block storage limit in bytes. Set to 40 KB.
344
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
345

            
346
parameter_types! {
347
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
348
	pub PrecompilesValue: Precompiles<Runtime> = Precompiles::new();
349
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
350
	pub GasLimitPovSizeRatio: u64 = {
351
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
352
		block_gas_limit.saturating_div(MAX_POV_SIZE)
353
	};
354
	pub GasLimitStorageGrowthRatio: u64 = {
355
		let block_gas_limit = BlockGasLimit::get().min(u64::MAX.into()).low_u64();
356
		block_gas_limit.saturating_div(BLOCK_STORAGE_LIMIT)
357
	};
358
}
359

            
360
impl pallet_evm::Config for Runtime {
361
	type FeeCalculator = ();
362
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
363
	type WeightPerGas = WeightPerGas;
364
	type CallOrigin = EnsureAddressRoot<AccountId>;
365
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
366
	type AddressMapping = AccountId;
367
	type Currency = Balances;
368
	type Runner = pallet_evm::runner::stack::Runner<Self>;
369
	type PrecompilesValue = PrecompilesValue;
370
	type PrecompilesType = Precompiles<Self>;
371
	type ChainId = ();
372
	type OnChargeTransaction = ();
373
	type BlockGasLimit = BlockGasLimit;
374
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
375
	type FindAuthor = ();
376
	type OnCreate = ();
377
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
378
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
379
	type Timestamp = Timestamp;
380
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
381
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
382
	type CreateOriginFilter = ();
383
	type CreateInnerOriginFilter = ();
384
}
385

            
386
parameter_types! {
387
	pub const MinimumPeriod: u64 = 5;
388
}
389
impl pallet_timestamp::Config for Runtime {
390
	type Moment = u64;
391
	type OnTimestampSet = ();
392
	type MinimumPeriod = MinimumPeriod;
393
	type WeightInfo = ();
394
}
395

            
396
parameter_types! {
397
	pub const TestMaxInitContributors: u32 = 8;
398
	pub const TestMinimumReward: u128 = 0;
399
	pub const TestInitialized: bool = false;
400
	pub const TestInitializationPayment: Perbill = Perbill::from_percent(20);
401
}
402

            
403
pub(crate) struct ExtBuilder {
404
	// endowed accounts with balances
405
	balances: Vec<(AccountId, Balance)>,
406
}
407

            
408
impl Default for ExtBuilder {
409
13
	fn default() -> ExtBuilder {
410
13
		ExtBuilder { balances: vec![] }
411
13
	}
412
}
413

            
414
impl ExtBuilder {
415
10
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
416
10
		self.balances = balances;
417
10
		self
418
10
	}
419

            
420
13
	pub(crate) fn build(self) -> sp_io::TestExternalities {
421
13
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
422
13
			.build_storage()
423
13
			.expect("Frame system builds valid default genesis config");
424

            
425
13
		pallet_balances::GenesisConfig::<Runtime> {
426
13
			balances: self.balances,
427
13
			dev_accounts: Default::default(),
428
13
		}
429
13
		.assimilate_storage(&mut t)
430
13
		.expect("Pallet balances storage can be assimilated");
431

            
432
13
		let mut ext = sp_io::TestExternalities::new(t);
433
13
		ext.execute_with(|| System::set_block_number(1));
434
13
		ext.execute_with(|| {
435
13
			pallet_xcm_transactor::RelayIndices::<Runtime>::put(
436
				crate::test_relay_runtime::TEST_RELAY_INDICES,
437
			);
438
13
		});
439
13
		ext
440
13
	}
441
}