1
// Copyright 2025 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
use super::*;
18
use crate as pallet_moonbeam_foreign_assets;
19

            
20
use frame_support::traits::{EitherOf, Everything};
21
use frame_support::{construct_runtime, pallet_prelude::*, parameter_types};
22
use frame_system::{EnsureRoot, Origin};
23
use pallet_ethereum::{IntermediateStateRoot, PostLogContent};
24
use pallet_evm::{FrameSystemAccountProvider, SubstrateBlockHashMapping};
25
use precompile_utils::testing::MockAccount;
26
use sp_core::{H256, U256};
27
use sp_runtime::traits::{BlakeTwo256, IdentityLookup};
28
use sp_runtime::BuildStorage;
29
use xcm::latest::{Junction, Location};
30

            
31
pub const PARA_A: AccountId = MockAccount(H160([101; 20]));
32
pub const PARA_B: AccountId = MockAccount(H160([102; 20]));
33
pub const PARA_C: AccountId = MockAccount(H160([103; 20]));
34

            
35
pub type Balance = u128;
36

            
37
pub type BlockNumber = u32;
38
type AccountId = MockAccount;
39
type Block = frame_system::mocking::MockBlock<Test>;
40

            
41
construct_runtime!(
42
	pub enum Test
43
	{
44
		System: frame_system,
45
		Balances: pallet_balances,
46
		Timestamp: pallet_timestamp,
47
		EVM: pallet_evm,
48
		Ethereum: pallet_ethereum,
49
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
50
	}
51
);
52

            
53
parameter_types! {
54
	pub const BlockHashCount: u32 = 250;
55
}
56

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

            
90
parameter_types! {
91
	pub const ExistentialDeposit: u128 = 0;
92
}
93
impl pallet_balances::Config for Test {
94
	type MaxReserves = ();
95
	type ReserveIdentifier = [u8; 4];
96
	type MaxLocks = ();
97
	type Balance = Balance;
98
	type RuntimeEvent = RuntimeEvent;
99
	type DustRemoval = ();
100
	type ExistentialDeposit = ExistentialDeposit;
101
	type AccountStore = System;
102
	type WeightInfo = ();
103
	type RuntimeHoldReason = ();
104
	type FreezeIdentifier = ();
105
	type MaxFreezes = ();
106
	type RuntimeFreezeReason = ();
107
	type DoneSlashHandler = ();
108
}
109

            
110
parameter_types! {
111
	pub const MinimumPeriod: u64 = 6000 / 2;
112
}
113

            
114
impl pallet_timestamp::Config for Test {
115
	type Moment = u64;
116
	type OnTimestampSet = ();
117
	type MinimumPeriod = MinimumPeriod;
118
	type WeightInfo = ();
119
}
120

            
121
parameter_types! {
122
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
123
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
124
	pub GasLimitPovSizeRatio: u64 = 16;
125
	pub GasLimitStorageGrowthRatio: u64 = 366;
126
}
127

            
128
impl pallet_evm::Config for Test {
129
	type FeeCalculator = ();
130
	type GasWeightMapping = pallet_evm::FixedGasWeightMapping<Self>;
131
	type WeightPerGas = WeightPerGas;
132
	type CallOrigin = pallet_evm::EnsureAddressRoot<AccountId>;
133
	type WithdrawOrigin = pallet_evm::EnsureAddressNever<AccountId>;
134
	type AddressMapping = AccountId;
135
	type Currency = Balances;
136
	type PrecompilesType = ();
137
	type PrecompilesValue = ();
138
	type Runner = pallet_evm::runner::stack::Runner<Self>;
139
	type ChainId = ();
140
	type BlockGasLimit = BlockGasLimit;
141
	type OnChargeTransaction = ();
142
	type FindAuthor = ();
143
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
144
	type OnCreate = ();
145
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
146
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
147
	type Timestamp = Timestamp;
148
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Test>;
149
	type AccountProvider = FrameSystemAccountProvider<Test>;
150
	type CreateOriginFilter = ();
151
	type CreateInnerOriginFilter = ();
152
}
153

            
154
parameter_types! {
155
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
156
}
157

            
158
impl pallet_ethereum::Config for Test {
159
	type StateRoot = IntermediateStateRoot<<Test as frame_system::Config>::Version>;
160
	type PostLogContent = PostBlockAndTxnHashes;
161
	type ExtraDataLength = ConstU32<30>;
162
}
163

            
164
/// Gets parameters of last `ForeignAssetCreatedHook::on_asset_created` hook invocation
165
2
pub fn get_asset_created_hook_invocation<ForeignAsset: Decode>() -> Option<(ForeignAsset, AssetId)>
166
{
167
2
	storage::unhashed::get_raw(b"____on_foreign_asset_created")
168
2
		.map(|output| Decode::decode(&mut output.as_slice()).expect("Decoding should work"))
169
2
}
170

            
171
/// Notes down parameters of current `ForeignAssetCreatedHook::on_asset_created` hook invocation
172
14
fn note_on_asset_created_hook_invocation<ForeignAsset: Encode>(
173
14
	foreign_asset: &ForeignAsset,
174
14
	asset_id: &AssetId,
175
14
) {
176
14
	storage::unhashed::put_raw(
177
14
		b"____on_foreign_asset_created",
178
14
		(foreign_asset, asset_id).encode().as_slice(),
179
	);
180
14
}
181

            
182
/// Test hook that records the hook invocation with exact params
183
pub struct NoteDownHook<ForeignAsset>(PhantomData<ForeignAsset>);
184

            
185
impl<ForeignAsset: Encode> ForeignAssetCreatedHook<ForeignAsset> for NoteDownHook<ForeignAsset> {
186
14
	fn on_asset_created(foreign_asset: &ForeignAsset, asset_id: &AssetId) {
187
14
		note_on_asset_created_hook_invocation(foreign_asset, asset_id);
188
14
	}
189
}
190

            
191
pub struct AccountIdToH160;
192
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
193
44
	fn convert(account_id: AccountId) -> H160 {
194
44
		account_id.into()
195
44
	}
196
}
197

            
198
parameter_types! {
199
	pub const ForeignAssetCreationDeposit: u128 = 100;
200
}
201

            
202
pub struct SiblingAccountOf;
203
impl xcm_executor::traits::ConvertLocation<AccountId> for SiblingAccountOf {
204
2
	fn convert_location(location: &Location) -> Option<AccountId> {
205
2
		let (parents, junctions) = location.unpack();
206
2
		if parents != 1 {
207
			return None;
208
2
		}
209
2
		if junctions.len() != 1 {
210
			return None;
211
2
		}
212
2
		match junctions[0] {
213
2
			Junction::Parachain(id) => match id {
214
1
				1 => Some(PARA_A),
215
				2 => Some(PARA_B),
216
1
				3 => Some(PARA_C),
217
				_ => None,
218
			},
219
			_ => None,
220
		}
221
2
	}
222
}
223

            
224
pub struct MockLocationToH160;
225
impl xcm_executor::traits::ConvertLocation<H160> for MockLocationToH160 {
226
7
	fn convert_location(location: &Location) -> Option<H160> {
227
7
		match location.unpack() {
228
7
			(0, [Junction::AccountKey20 { network: _, key }]) => Some(H160::from(*key)),
229
			_ => None,
230
		}
231
7
	}
232
}
233

            
234
pub struct SiblingOrigin;
235
impl EnsureOrigin<<Test as frame_system::Config>::RuntimeOrigin> for SiblingOrigin {
236
	type Success = Location;
237
12
	fn try_origin(
238
12
		original_origin: <Test as frame_system::Config>::RuntimeOrigin,
239
12
	) -> Result<Self::Success, <Test as frame_system::Config>::RuntimeOrigin> {
240
12
		match original_origin.clone().caller {
241
12
			OriginCaller::system(o) => match o {
242
12
				Origin::<Test>::Signed(account) => {
243
12
					let para_id = if account == PARA_A {
244
8
						1
245
4
					} else if account == PARA_B {
246
						2
247
4
					} else if account == PARA_C {
248
2
						3
249
					} else {
250
2
						return Err(original_origin);
251
					};
252
10
					Ok(Location::new(1, [Junction::Parachain(para_id)]))
253
				}
254
				_ => Err(original_origin),
255
			},
256
			_ => Err(original_origin),
257
		}
258
12
	}
259

            
260
	#[cfg(feature = "runtime-benchmarks")]
261
	fn try_successful_origin() -> Result<<Test as frame_system::Config>::RuntimeOrigin, ()> {
262
		Ok(RuntimeOrigin::signed(PARA_A))
263
	}
264
}
265

            
266
pub type ForeignAssetManagerOrigin =
267
	EitherOf<MapSuccessToGovernance<EnsureRoot<AccountId>>, MapSuccessToXcm<SiblingOrigin>>;
268

            
269
impl crate::Config for Test {
270
	type AccountIdToH160 = AccountIdToH160;
271
	type AssetIdFilter = Everything;
272
	type EvmRunner = pallet_evm::runner::stack::Runner<Self>;
273
	type ConvertLocation = SiblingAccountOf;
274
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
275
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
276
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
277
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
278
	type OnForeignAssetCreated = NoteDownHook<Location>;
279
	type MaxForeignAssets = ConstU32<3>;
280
	type WeightInfo = ();
281
	type XcmLocationToH160 = MockLocationToH160;
282
	type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit;
283
	type Balance = Balance;
284

            
285
	type Currency = Balances;
286
}
287

            
288
pub(crate) struct ExtBuilder {
289
	// endowed accounts with balances
290
	balances: Vec<(AccountId, Balance)>,
291
}
292

            
293
impl Default for ExtBuilder {
294
15
	fn default() -> ExtBuilder {
295
15
		ExtBuilder { balances: vec![] }
296
15
	}
297
}
298

            
299
impl ExtBuilder {
300
15
	pub(crate) fn build(self) -> sp_io::TestExternalities {
301
15
		let mut t = frame_system::GenesisConfig::<Test>::default()
302
15
			.build_storage()
303
15
			.expect("Frame system builds valid default genesis config");
304

            
305
15
		pallet_balances::GenesisConfig::<Test> {
306
15
			balances: self.balances,
307
15
			dev_accounts: None,
308
15
		}
309
15
		.assimilate_storage(&mut t)
310
15
		.expect("Pallet balances storage can be assimilated");
311
15
		let mut ext = sp_io::TestExternalities::new(t);
312
15
		ext.execute_with(|| System::set_block_number(1));
313
15
		ext
314
15
	}
315
}
316

            
317
3
pub(crate) fn events() -> Vec<super::Event<Test>> {
318
3
	System::events()
319
3
		.into_iter()
320
3
		.map(|r| r.event)
321
15
		.filter_map(|e| {
322
15
			if let RuntimeEvent::EvmForeignAssets(inner) = e {
323
4
				Some(inner)
324
			} else {
325
11
				None
326
			}
327
15
		})
328
3
		.collect::<Vec<_>>()
329
3
}
330

            
331
3
pub fn expect_events(e: Vec<super::Event<Test>>) {
332
3
	assert_eq!(events(), e);
333
3
}