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
construct_runtime!(
49
	pub enum Runtime	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		Evm: pallet_evm,
53
		ParachainSystem: cumulus_pallet_parachain_system,
54
		Timestamp: pallet_timestamp,
55
		XcmTransactor: pallet_xcm_transactor,
56
		MessageQueue: pallet_message_queue,
57
	}
58
);
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
	type RelayParentOffset = ConstU32<0>;
116
}
117

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

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

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

            
158
pub type AssetId = u128;
159

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

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

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

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

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

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

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

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

            
203
	pub UniversalLocation: InteriorLocation = Here;
204
}
205

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

            
220
pub struct CurrencyIdToLocation;
221

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

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

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

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

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

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

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

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

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

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

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

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

            
312
impl pallet_xcm_transactor::Config for Runtime {
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 Runner = pallet_evm::runner::stack::Runner<Self>;
367
	type PrecompilesValue = PrecompilesValue;
368
	type PrecompilesType = Precompiles<Self>;
369
	type ChainId = ();
370
	type OnChargeTransaction = ();
371
	type BlockGasLimit = BlockGasLimit;
372
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
373
	type FindAuthor = ();
374
	type OnCreate = ();
375
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
376
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
377
	type Timestamp = Timestamp;
378
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Runtime>;
379
	type AccountProvider = FrameSystemAccountProvider<Runtime>;
380
	type CreateOriginFilter = ();
381
	type CreateInnerOriginFilter = ();
382
}
383

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

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

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

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

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

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

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

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