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
208
construct_runtime!(
42
208
	pub enum Test
43
208
	{
44
208
		System: frame_system,
45
208
		Balances: pallet_balances,
46
208
		Timestamp: pallet_timestamp,
47
208
		EVM: pallet_evm,
48
208
		Ethereum: pallet_ethereum,
49
208
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
50
208
	}
51
208
);
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
	type CreateOriginFilter = ();
152
	type CreateInnerOriginFilter = ();
153
}
154

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

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

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

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

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

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

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

            
200
parameter_types! {
201
	pub const ForeignAssetCreationDeposit: u128 = 100;
202
}
203

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

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

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

            
258
pub type ForeignAssetManagerOrigin =
259
	EitherOf<MapSuccessToGovernance<EnsureRoot<AccountId>>, MapSuccessToXcm<SiblingOrigin>>;
260

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

            
278
	type Currency = Balances;
279
}
280

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

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

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

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

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

            
324
3
pub fn expect_events(e: Vec<super::Event<Test>>) {
325
3
	assert_eq!(events(), e);
326
3
}