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::v5::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
4183
construct_runtime!(
43
1148
	pub enum Test
44
1148
	{
45
1148
		System: frame_system::{Pallet, Call, Config<T>, Storage, Event<T>},
46
1148
		Balances: pallet_balances::{Pallet, Call, Storage, Config<T>, Event<T>},
47
1148
		Timestamp: pallet_timestamp,
48
1148
		EVM: pallet_evm,
49
1148
		LazyMigrations: pallet_moonbeam_lazy_migrations::{Pallet, Call},
50
1148
		Assets: pallet_assets::{Pallet, Call, Storage, Event<T>},
51
1148
		AssetManager: pallet_asset_manager::{Pallet, Call, Storage, Event<T>},
52
1148
		MoonbeamForeignAssets: pallet_moonbeam_foreign_assets::{Pallet, Call, Storage, Event<T>},
53
1148
	}
54
4346
);
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
	type ExtensionsWeightInfo = ();
95
}
96

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

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

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

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

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

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

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

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

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

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

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

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

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

            
248
pub struct MockAssetPalletRegistrar;
249

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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