1
// Copyright 2024 Moonbeam foundation
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
//! A minimal runtime including the multi block migrations pallet
18

            
19
use super::*;
20
use crate as pallet_moonbeam_lazy_migrations;
21
use frame_support::traits::{AsEnsureOriginWithArg, ConstU128, EitherOf};
22
use frame_support::weights::constants::RocksDbWeight;
23
use frame_support::{construct_runtime, parameter_types, traits::Everything, weights::Weight};
24
use frame_system::{EnsureRoot, EnsureSigned, Origin};
25
use pallet_asset_manager::AssetRegistrar;
26
use pallet_evm::{EnsureAddressNever, EnsureAddressRoot, FrameSystemAccountProvider};
27
use pallet_moonbeam_foreign_assets::{MapSuccessToGovernance, MapSuccessToXcm};
28
use precompile_utils::testing::MockAccount;
29
use sp_core::{ConstU32, H160, H256, U256};
30
use sp_runtime::{
31
	traits::{BlakeTwo256, Hash, IdentityLookup},
32
	BuildStorage, Perbill,
33
};
34
use xcm::v4::Junction;
35

            
36
pub type AssetId = u128;
37
pub type Balance = u128;
38
pub type AccountId = MockAccount;
39
type Block = frame_system::mocking::MockBlock<Test>;
40

            
41
// Configure a mock runtime to test the pallet.
42
4198
construct_runtime!(
43
	pub enum Test
44
	{
45
		System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
46
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
47
		Timestamp: pallet_timestamp,
48
		EVM: pallet_evm,
49
		LazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call},
50
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>},
51
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>},
52
		MoonbeamForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>},
53
	}
54
10267
);
55

            
56
parameter_types! {
57
	pub const BlockHashCount: u32 = 250;
58
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
59
	pub const MaximumBlockLength: u32 = 2 * 1024;
60
	pub const AvailableBlockRatio: Perbill = Perbill::one();
61
	pub const SS58Prefix: u8 = 42;
62
}
63

            
64
impl frame_system::Config for Test {
65
	type BaseCallFilter = Everything;
66
	type DbWeight = RocksDbWeight;
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 = ();
88
	type MaxConsumers = frame_support::traits::ConstU32<16>;
89
	type SingleBlockMigrations = ();
90
	type MultiBlockMigrator = ();
91
	type PreInherents = ();
92
	type PostInherents = ();
93
	type PostTransactions = ();
94
}
95

            
96
parameter_types! {
97
	pub const ExistentialDeposit: u128 = 0;
98
}
99
impl pallet_balances::Config for Test {
100
	type MaxReserves = ();
101
	type ReserveIdentifier = ();
102
	type MaxLocks = ();
103
	type Balance = Balance;
104
	type RuntimeEvent = RuntimeEvent;
105
	type DustRemoval = ();
106
	type ExistentialDeposit = ExistentialDeposit;
107
	type AccountStore = System;
108
	type WeightInfo = ();
109
	type RuntimeHoldReason = ();
110
	type FreezeIdentifier = ();
111
	type MaxFreezes = ();
112
	type RuntimeFreezeReason = ();
113
}
114

            
115
parameter_types! {
116
	pub const MinimumPeriod: u64 = 6000 / 2;
117
}
118

            
119
impl pallet_timestamp::Config for Test {
120
	type Moment = u64;
121
	type OnTimestampSet = ();
122
	type MinimumPeriod = MinimumPeriod;
123
	type WeightInfo = ();
124
}
125

            
126
parameter_types! {
127
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
128
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
129
	pub GasLimitPovSizeRatio: u64 = 16;
130
	pub GasLimitStorageGrowthRatio: u64 = 366;
131
	pub SuicideQuickClearLimit: u32 = 0;
132
}
133

            
134
impl pallet_evm::Config for Test {
135
	type FeeCalculator = ();
136
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
137
	type WeightPerGas = WeightPerGas;
138
	type CallOrigin = EnsureAddressRoot<AccountId>;
139
	type WithdrawOrigin = EnsureAddressNever<AccountId>;
140
	type AddressMapping = AccountId;
141
	type Currency = Balances;
142
	type RuntimeEvent = RuntimeEvent;
143
	type Runner = pallet_evm::runner::stack::Runner<Self>;
144
	type PrecompilesType = ();
145
	type PrecompilesValue = ();
146
	type ChainId = ();
147
	type OnChargeTransaction = ();
148
	type BlockGasLimit = BlockGasLimit;
149
	type BlockHashMapping = pallet_evm::SubstrateBlockHashMapping<Self>;
150
	type FindAuthor = ();
151
	type OnCreate = ();
152
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
153
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
154
	type Timestamp = Timestamp;
155
	type WeightInfo = ();
156
	type SuicideQuickClearLimit = SuicideQuickClearLimit;
157
	type AccountProvider = FrameSystemAccountProvider<Test>;
158
}
159

            
160
parameter_types! {
161
	pub const AssetDeposit: u128 = 1;
162
	pub const MetadataDepositBase: u128 = 1;
163
	pub const MetadataDepositPerByte: u128 = 1;
164
	pub const ApprovalDeposit: u128 = 1;
165
	pub const AssetsStringLimit: u32 = 50;
166
	pub const AssetAccountDeposit: u128 = 1;
167
}
168

            
169
// Required for runtime benchmarks
170
pallet_assets::runtime_benchmarks_enabled! {
171
	pub struct BenchmarkHelper;
172
	impl<AssetIdParameter> pallet_assets::BenchmarkHelper<AssetIdParameter> for BenchmarkHelper
173
	where
174
		AssetIdParameter: From<u128>,
175
	{
176
		fn create_asset_id_parameter(id: u32) -> AssetIdParameter {
177
			(id as u128).into()
178
		}
179
	}
180
}
181

            
182
impl pallet_assets::Config<()> for Test {
183
	type RuntimeEvent = RuntimeEvent;
184
	type Balance = Balance;
185
	type AssetId = AssetId;
186
	type Currency = Balances;
187
	type ForceOrigin = EnsureRoot<AccountId>;
188
	type AssetDeposit = AssetDeposit;
189
	type MetadataDepositBase = MetadataDepositBase;
190
	type MetadataDepositPerByte = MetadataDepositPerByte;
191
	type ApprovalDeposit = ApprovalDeposit;
192
	type StringLimit = AssetsStringLimit;
193
	type Freezer = ();
194
	type Extra = ();
195
	type AssetAccountDeposit = AssetAccountDeposit;
196
	type WeightInfo = ();
197
	type RemoveItemsLimit = ConstU32<656>;
198
	type AssetIdParameter = AssetId;
199
	type CreateOrigin = AsEnsureOriginWithArg<EnsureSigned<AccountId>>;
200
	type CallbackHandle = ();
201
	pallet_assets::runtime_benchmarks_enabled! {
202
		type BenchmarkHelper = BenchmarkHelper;
203
	}
204
}
205

            
206
#[derive(Clone, Eq, PartialEq, Ord, PartialOrd, Encode, Decode, RuntimeDebug, TypeInfo)]
207
pub enum MockAssetType {
208
15
	Xcm(Location),
209
	MockAsset(AssetId),
210
}
211

            
212
impl Default for MockAssetType {
213
	fn default() -> Self {
214
		Self::MockAsset(0)
215
	}
216
}
217

            
218
impl From<MockAssetType> for AssetId {
219
34
	fn from(asset: MockAssetType) -> AssetId {
220
34
		match asset {
221
			MockAssetType::MockAsset(id) => id,
222
34
			MockAssetType::Xcm(id) => {
223
34
				let mut result: [u8; 16] = [0u8; 16];
224
34
				let hash: H256 = id.using_encoded(<Test as frame_system::Config>::Hashing::hash);
225
34
				result.copy_from_slice(&hash.as_fixed_bytes()[0..16]);
226
34
				u128::from_le_bytes(result)
227
			}
228
		}
229
34
	}
230
}
231

            
232
impl From<Location> for MockAssetType {
233
	fn from(location: Location) -> Self {
234
		Self::Xcm(location)
235
	}
236
}
237

            
238
impl Into<Option<Location>> for MockAssetType {
239
15
	fn into(self) -> Option<Location> {
240
15
		match self {
241
15
			Self::Xcm(location) => Some(location),
242
			_ => None,
243
		}
244
15
	}
245
}
246

            
247
pub struct MockAssetPalletRegistrar;
248

            
249
impl AssetRegistrar<Test> for MockAssetPalletRegistrar {
250
17
	fn create_foreign_asset(
251
17
		asset: u128,
252
17
		min_balance: u128,
253
17
		_metadata: u32,
254
17
		is_sufficient: bool,
255
17
	) -> Result<(), DispatchError> {
256
17
		Assets::force_create(
257
17
			RuntimeOrigin::root(),
258
17
			asset.into(),
259
17
			AssetManager::account_id(),
260
17
			is_sufficient,
261
17
			min_balance,
262
17
		)?;
263
17
		Ok(())
264
17
	}
265

            
266
	fn destroy_foreign_asset(_asset: u128) -> Result<(), DispatchError> {
267
		Ok(())
268
	}
269

            
270
	fn destroy_asset_dispatch_info_weight(_asset: u128) -> Weight {
271
		Weight::from_parts(0, 0)
272
	}
273
}
274

            
275
impl pallet_asset_manager::Config for Test {
276
	type RuntimeEvent = RuntimeEvent;
277
	type Balance = Balance;
278
	type AssetId = AssetId;
279
	type AssetRegistrarMetadata = u32;
280
	type ForeignAssetType = MockAssetType;
281
	type AssetRegistrar = MockAssetPalletRegistrar;
282
	type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
283
	type WeightInfo = ();
284
}
285

            
286
pub struct AccountIdToH160;
287
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
288
74
	fn convert(account_id: AccountId) -> H160 {
289
74
		account_id.into()
290
74
	}
291
}
292

            
293
pub struct SiblingAccountOf;
294
impl xcm_executor::traits::ConvertLocation<AccountId> for SiblingAccountOf {
295
	fn convert_location(location: &Location) -> Option<AccountId> {
296
		let (parents, junctions) = location.unpack();
297
		if parents != 1 {
298
			return None;
299
		}
300
		if junctions.len() != 1 {
301
			return None;
302
		}
303
		match junctions[0] {
304
			Junction::Parachain(id) => match id {
305
				1 => Some(PARA_A),
306
				2 => Some(PARA_B),
307
				3 => Some(PARA_C),
308
				_ => None,
309
			},
310
			_ => None,
311
		}
312
	}
313
}
314

            
315
pub struct SiblingOrigin;
316
impl EnsureOrigin<<Test as frame_system::Config>::RuntimeOrigin> for SiblingOrigin {
317
	type Success = Location;
318
	fn try_origin(
319
		original_origin: <Test as frame_system::Config>::RuntimeOrigin,
320
	) -> Result<Self::Success, <Test as frame_system::Config>::RuntimeOrigin> {
321
		match original_origin.clone().caller {
322
			OriginCaller::system(o) => match o {
323
				Origin::<Test>::Signed(account) => {
324
					let para_id = if account == PARA_A {
325
						1
326
					} else if account == PARA_B {
327
						2
328
					} else if account == PARA_C {
329
						3
330
					} else {
331
						return Err(original_origin);
332
					};
333
					Ok(Location::new(1, [Junction::Parachain(para_id)]))
334
				}
335
				_ => Err(original_origin),
336
			},
337
			_ => Err(original_origin),
338
		}
339
	}
340

            
341
	#[cfg(feature = "runtime-benchmarks")]
342
	fn try_successful_origin() -> Result<<Test as frame_system::Config>::RuntimeOrigin, ()> {
343
		Ok(RuntimeOrigin::signed(PARA_A))
344
	}
345
}
346

            
347
pub type ForeignAssetManagerOrigin =
348
	EitherOf<MapSuccessToGovernance<EnsureRoot<AccountId>>, MapSuccessToXcm<SiblingOrigin>>;
349

            
350
impl pallet_moonbeam_foreign_assets::Config for Test {
351
	type AccountIdToH160 = AccountIdToH160;
352
	type AssetIdFilter = Everything;
353
	type EvmRunner = pallet_evm::runner::stack::Runner<Self>;
354
	type ConvertLocation = SiblingAccountOf;
355
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
356
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
357
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
358
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
359
	type OnForeignAssetCreated = ();
360
	type MaxForeignAssets = ConstU32<3>;
361
	type RuntimeEvent = RuntimeEvent;
362
	type WeightInfo = ();
363
	type XcmLocationToH160 = ();
364
	type ForeignAssetCreationDeposit = ConstU128<1>;
365
	type Balance = Balance;
366
	type Currency = Balances;
367
}
368

            
369
impl Config for Test {
370
	type WeightInfo = ();
371
	type ForeignAssetMigratorOrigin = EnsureRoot<AccountId>;
372
}
373

            
374
// Constants for test accounts
375
pub const ALITH: AccountId = MockAccount(H160([1; 20]));
376
pub const BOB: AccountId = MockAccount(H160([2; 20]));
377

            
378
pub const PARA_A: AccountId = MockAccount(H160([2; 20]));
379
pub const PARA_B: AccountId = MockAccount(H160([2; 20]));
380
pub const PARA_C: AccountId = MockAccount(H160([2; 20]));
381

            
382
/// Externality builder for pallet migration's mock runtime
383
pub(crate) struct ExtBuilder {
384
	// endowed accounts with balances
385
	balances: Vec<(AccountId, Balance)>,
386
}
387

            
388
impl Default for ExtBuilder {
389
24
	fn default() -> ExtBuilder {
390
24
		ExtBuilder {
391
24
			balances: vec![
392
24
				(ALITH, 1000),
393
24
				(BOB, 1000),
394
24
				(AssetManager::account_id(), 1000),
395
24
			],
396
24
		}
397
24
	}
398
}
399

            
400
impl ExtBuilder {
401
24
	pub(crate) fn build(self) -> sp_io::TestExternalities {
402
24
		let mut storage = frame_system::GenesisConfig::<Test>::default()
403
24
			.build_storage()
404
24
			.expect("Frame system builds valid default genesis config");
405
24

            
406
24
		pallet_balances::GenesisConfig::<Test> {
407
24
			balances: self.balances,
408
24
		}
409
24
		.assimilate_storage(&mut storage)
410
24
		.expect("Pallet balances storage can be assimilated");
411
24

            
412
24
		let mut ext = sp_io::TestExternalities::new(storage);
413
24
		ext.execute_with(|| System::set_block_number(1));
414
24
		ext
415
24
	}
416
}