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
844
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
2522
);
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
}
88

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

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

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

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

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

            
152
parameter_types! {
153
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
154
}
155

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

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

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

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

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

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

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

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

            
223
pub struct SiblingOrigin;
224
impl EnsureOrigin<<Test as frame_system::Config>::RuntimeOrigin> for SiblingOrigin {
225
	type Success = Location;
226
12
	fn try_origin(
227
12
		original_origin: <Test as frame_system::Config>::RuntimeOrigin,
228
12
	) -> Result<Self::Success, <Test as frame_system::Config>::RuntimeOrigin> {
229
12
		match original_origin.clone().caller {
230
12
			OriginCaller::system(o) => match o {
231
12
				Origin::<Test>::Signed(account) => {
232
12
					let para_id = if account == PARA_A {
233
8
						1
234
4
					} else if account == PARA_B {
235
						2
236
4
					} else if account == PARA_C {
237
2
						3
238
					} else {
239
2
						return Err(original_origin);
240
					};
241
10
					Ok(Location::new(1, [Junction::Parachain(para_id)]))
242
				}
243
				_ => Err(original_origin),
244
			},
245
			_ => Err(original_origin),
246
		}
247
12
	}
248

            
249
	#[cfg(feature = "runtime-benchmarks")]
250
	fn try_successful_origin() -> Result<<Test as frame_system::Config>::RuntimeOrigin, ()> {
251
		Ok(RuntimeOrigin::signed(PARA_A))
252
	}
253
}
254

            
255
pub type ForeignAssetManagerOrigin =
256
	EitherOf<MapSuccessToGovernance<EnsureRoot<AccountId>>, MapSuccessToXcm<SiblingOrigin>>;
257

            
258
impl crate::Config for Test {
259
	type AccountIdToH160 = AccountIdToH160;
260
	type AssetIdFilter = Everything;
261
	type EvmRunner = pallet_evm::runner::stack::Runner<Self>;
262
	type ConvertLocation = SiblingAccountOf;
263
	type ForeignAssetCreatorOrigin = ForeignAssetManagerOrigin;
264
	type ForeignAssetModifierOrigin = ForeignAssetManagerOrigin;
265
	type ForeignAssetFreezerOrigin = ForeignAssetManagerOrigin;
266
	type ForeignAssetUnfreezerOrigin = ForeignAssetManagerOrigin;
267
	type OnForeignAssetCreated = NoteDownHook<Location>;
268
	type MaxForeignAssets = ConstU32<3>;
269
	type RuntimeEvent = RuntimeEvent;
270
	type WeightInfo = ();
271
	type XcmLocationToH160 = ();
272
	type ForeignAssetCreationDeposit = ForeignAssetCreationDeposit;
273
	type Balance = Balance;
274

            
275
	type Currency = Balances;
276
}
277

            
278
pub(crate) struct ExtBuilder {
279
	// endowed accounts with balances
280
	balances: Vec<(AccountId, Balance)>,
281
}
282

            
283
impl Default for ExtBuilder {
284
8
	fn default() -> ExtBuilder {
285
8
		ExtBuilder { balances: vec![] }
286
8
	}
287
}
288

            
289
impl ExtBuilder {
290
8
	pub(crate) fn build(self) -> sp_io::TestExternalities {
291
8
		let mut t = frame_system::GenesisConfig::<Test>::default()
292
8
			.build_storage()
293
8
			.expect("Frame system builds valid default genesis config");
294
8

            
295
8
		pallet_balances::GenesisConfig::<Test> {
296
8
			balances: self.balances,
297
8
		}
298
8
		.assimilate_storage(&mut t)
299
8
		.expect("Pallet balances storage can be assimilated");
300
8
		let mut ext = sp_io::TestExternalities::new(t);
301
8
		ext.execute_with(|| System::set_block_number(1));
302
8
		ext
303
8
	}
304
}
305

            
306
3
pub(crate) fn events() -> Vec<super::Event<Test>> {
307
3
	System::events()
308
3
		.into_iter()
309
15
		.map(|r| r.event)
310
15
		.filter_map(|e| {
311
15
			if let RuntimeEvent::EvmForeignAssets(inner) = e {
312
4
				Some(inner)
313
			} else {
314
11
				None
315
			}
316
15
		})
317
3
		.collect::<Vec<_>>()
318
3
}
319

            
320
3
pub fn expect_events(e: Vec<super::Event<Test>>) {
321
3
	assert_eq!(events(), e);
322
3
}