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
	pub enum Runtime	{
49
		System: frame_system,
50
		Balances: pallet_balances,
51
		Evm: pallet_evm,
52
		ParachainSystem: cumulus_pallet_parachain_system,
53
		Timestamp: pallet_timestamp,
54
		XcmTransactor: pallet_xcm_transactor,
55
		MessageQueue: pallet_message_queue,
56
	}
57
598
);
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
}
94

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

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

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

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

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

            
153
pub type AssetId = u128;
154

            
155
#[derive(Clone, Eq, Debug, PartialEq, Ord, PartialOrd, Encode, Decode, TypeInfo)]
156
pub enum CurrencyId {
157
	SelfReserve,
158
	OtherReserve(AssetId),
159
}
160

            
161
pub struct DoNothingRouter;
162
impl SendXcm for DoNothingRouter {
163
	type Ticket = ();
164

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

            
172
	fn deliver(_: Self::Ticket) -> Result<XcmHash, SendError> {
173
		Ok(XcmHash::default())
174
	}
175
}
176

            
177
parameter_types! {
178
	pub Ancestry: Location = Parachain(ParachainId::get().into()).into();
179

            
180
	pub const BaseXcmWeight: Weight = Weight::from_parts(1000u64, 1000u64);
181
	pub const RelayNetwork: NetworkId = NetworkId::Polkadot;
182

            
183
	pub SelfLocation: Location =
184
		Location::new(1, [Parachain(ParachainId::get().into())]);
185

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

            
196
	pub UniversalLocation: InteriorLocation = Here;
197
}
198

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

            
213
pub struct CurrencyIdToLocation;
214

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

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

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

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

            
253
impl TryFrom<u8> for MockTransactors {
254
	type Error = ();
255

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

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

            
279
impl xcm_primitives::XcmTransact for MockTransactors {
280
	fn destination(self) -> Location {
281
		match self {
282
			MockTransactors::Relay => Location::parent(),
283
		}
284
	}
285
}
286

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

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

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

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

            
331
pub type Precompiles<R> =
332
	PrecompileSetBuilder<R, PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R>>>;
333

            
334
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
335

            
336
const MAX_POV_SIZE: u64 = 5 * 1024 * 1024;
337
/// Block storage limit in bytes. Set to 40 KB.
338
const BLOCK_STORAGE_LIMIT: u64 = 40 * 1024;
339

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

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

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

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

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

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

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

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

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

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