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
852
construct_runtime!(
42
217
	pub enum Test
43
217
	{
44
217
		System: frame_system,
45
217
		Balances: pallet_balances,
46
217
		Timestamp: pallet_timestamp,
47
217
		EVM: pallet_evm,
48
217
		Ethereum: pallet_ethereum,
49
217
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
50
217
	}
51
892
);
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 RuntimeEvent = RuntimeEvent;
137
	type PrecompilesType = ();
138
	type PrecompilesValue = ();
139
	type Runner = pallet_evm::runner::stack::Runner<Self>;
140
	type ChainId = ();
141
	type BlockGasLimit = BlockGasLimit;
142
	type OnChargeTransaction = ();
143
	type FindAuthor = ();
144
	type BlockHashMapping = SubstrateBlockHashMapping<Self>;
145
	type OnCreate = ();
146
	type GasLimitPovSizeRatio = GasLimitPovSizeRatio;
147
	type GasLimitStorageGrowthRatio = GasLimitStorageGrowthRatio;
148
	type Timestamp = Timestamp;
149
	type WeightInfo = pallet_evm::weights::SubstrateWeight<Test>;
150
	type AccountProvider = FrameSystemAccountProvider<Test>;
151
}
152

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

            
157
impl pallet_ethereum::Config for Test {
158
	type RuntimeEvent = RuntimeEvent;
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
2
{
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
7
fn note_on_asset_created_hook_invocation<ForeignAsset: Encode>(
173
7
	foreign_asset: &ForeignAsset,
174
7
	asset_id: &AssetId,
175
7
) {
176
7
	storage::unhashed::put_raw(
177
7
		b"____on_foreign_asset_created",
178
7
		(foreign_asset, asset_id).encode().as_slice(),
179
7
	);
180
7
}
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
7
	fn on_asset_created(foreign_asset: &ForeignAsset, asset_id: &AssetId) {
187
7
		note_on_asset_created_hook_invocation(foreign_asset, asset_id);
188
7
	}
189
}
190

            
191
pub struct AccountIdToH160;
192
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
193
19
	fn convert(account_id: AccountId) -> H160 {
194
19
		account_id.into()
195
19
	}
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 SiblingOrigin;
225
impl EnsureOrigin<<Test as frame_system::Config>::RuntimeOrigin> for SiblingOrigin {
226
	type Success = Location;
227
12
	fn try_origin(
228
12
		original_origin: <Test as frame_system::Config>::RuntimeOrigin,
229
12
	) -> Result<Self::Success, <Test as frame_system::Config>::RuntimeOrigin> {
230
12
		match original_origin.clone().caller {
231
12
			OriginCaller::system(o) => match o {
232
12
				Origin::<Test>::Signed(account) => {
233
12
					let para_id = if account == PARA_A {
234
8
						1
235
4
					} else if account == PARA_B {
236
						2
237
4
					} else if account == PARA_C {
238
2
						3
239
					} else {
240
2
						return Err(original_origin);
241
					};
242
10
					Ok(Location::new(1, [Junction::Parachain(para_id)]))
243
				}
244
				_ => Err(original_origin),
245
			},
246
			_ => Err(original_origin),
247
		}
248
12
	}
249

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

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

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

            
276
	type Currency = Balances;
277
}
278

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

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

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

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

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

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