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

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

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

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

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

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

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

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

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

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

            
157
pub type AssetId = u128;
158

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

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

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

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

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

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

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

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

            
202
	pub UniversalLocation: InteriorLocation = Here;
203
}
204

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

            
219
pub struct CurrencyIdToLocation;
220

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

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

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

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

            
261
impl TryFrom<u8> for MockTransactors {
262
	type Error = ();
263

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

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

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

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

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

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

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

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

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

            
338
pub type PCall = RelayEncoderPrecompileCall<Runtime, StakingTransactor>;
339

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

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

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

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

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

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

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

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

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

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

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