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, 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
248
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
249
);
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(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
159
pub enum CurrencyId {
160
	SelfReserve,
161
	OtherReserve(AssetId),
162
}
163

            
164
pub struct DoNothingRouter;
165
impl SendXcm for DoNothingRouter {
166
	type Ticket = ();
167

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

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

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

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

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

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

            
199
	pub UniversalLocation: InteriorLocation = Here;
200
}
201

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

            
216
pub struct CurrencyIdToLocation;
217

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

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

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

            
251
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
252
pub enum MockTransactors {
253
	Relay,
254
}
255

            
256
impl TryFrom<u8> for MockTransactors {
257
	type Error = ();
258

            
259
	fn try_from(value: u8) -> Result<Self, Self::Error> {
260
		match value {
261
			0x0 => Ok(MockTransactors::Relay),
262
			_ => Err(()),
263
		}
264
	}
265
}
266

            
267
impl xcm_primitives::UtilityEncodeCall for MockTransactors {
268
	fn encode_call(self, call: xcm_primitives::UtilityAvailableCalls) -> Vec<u8> {
269
		match self {
270
			MockTransactors::Relay => match call {
271
				xcm_primitives::UtilityAvailableCalls::AsDerivative(a, b) => {
272
					let mut call =
273
						RelayCall::Utility(UtilityCall::AsDerivative(a.clone())).encode();
274
					call.append(&mut b.clone());
275
					call
276
				}
277
			},
278
		}
279
	}
280
}
281

            
282
impl xcm_primitives::XcmTransact for MockTransactors {
283
	fn destination(self) -> Location {
284
		match self {
285
			MockTransactors::Relay => Location::parent(),
286
		}
287
	}
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
}
311

            
312
impl pallet_xcm_transactor::Config for Runtime {
313
	type RuntimeEvent = RuntimeEvent;
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
}
333

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

            
337
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
338

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

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

            
357
impl pallet_evm::Config for Runtime {
358
	type FeeCalculator = ();
359
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
360
	type WeightPerGas = WeightPerGas;
361
	type CallOrigin = EnsureAddressRoot<AccountId>;
362
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
363
	type AddressMapping = AccountId;
364
	type Currency = Balances;
365
	type RuntimeEvent = RuntimeEvent;
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
}
381

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

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

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

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

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

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

            
421
13
		pallet_balances::GenesisConfig::<Runtime> {
422
13
			balances: self.balances,
423
13
		}
424
13
		.assimilate_storage(&mut t)
425
13
		.expect("Pallet balances storage can be assimilated");
426
13

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