1
// Copyright 2019-2022 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::{EnsureAddressNever, EnsureAddressRoot, SubstrateBlockHashMapping};
27
use parity_scale_codec::{Decode, Encode};
28
use precompile_utils::{precompile_set::*, testing::MockAccount};
29
use scale_info::TypeInfo;
30
use sp_core::{H160, H256};
31
use sp_runtime::{
32
	traits::{BlakeTwo256, IdentityLookup},
33
	BuildStorage, Perbill,
34
};
35
use xcm::latest::{prelude::*, Error as XcmError};
36
use xcm_builder::FixedWeightBounds;
37
use xcm_executor::{traits::TransactAsset, AssetsInHolding};
38

            
39
pub type AccountId = MockAccount;
40
pub type Balance = u128;
41

            
42
type Block = frame_system::mocking::MockBlockU32<Runtime>;
43

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

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

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

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

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

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

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

            
151
pub type AssetId = u128;
152

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

            
159
pub struct DoNothingRouter;
160
impl SendXcm for DoNothingRouter {
161
	type Ticket = ();
162

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

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

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

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

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

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

            
194
	pub UniversalLocation: InteriorLocation = Here;
195
}
196

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

            
211
pub struct CurrencyIdToLocation;
212

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

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

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

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

            
251
impl TryFrom<u8> for MockTransactors {
252
	type Error = ();
253

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

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

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

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

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

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

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

            
329
pub type Precompiles<R> =
330
	PrecompileSetBuilder<R, PrecompileAt<AddressU64<1>, RelayEncoderPrecompile<R>>>;
331

            
332
pub type PCall = RelayEncoderPrecompileCall<Runtime>;
333

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

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

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

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

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

            
394
pub(crate) struct ExtBuilder {
395
	// endowed accounts with balances
396
	balances: Vec<(AccountId, Balance)>,
397
}
398

            
399
impl Default for ExtBuilder {
400
13
	fn default() -> ExtBuilder {
401
13
		ExtBuilder { balances: vec![] }
402
13
	}
403
}
404

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

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

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

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