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

            
20
use frame_support::traits::Everything;
21
use frame_support::{construct_runtime, pallet_prelude::*, parameter_types};
22
use frame_system::EnsureRoot;
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::Location;
30

            
31
pub type Balance = u128;
32

            
33
type AccountId = MockAccount;
34
type Block = frame_system::mocking::MockBlock<Test>;
35

            
36
482
construct_runtime!(
37
	pub enum Test
38
	{
39
		System: frame_system,
40
		Balances: pallet_balances,
41
		Timestamp: pallet_timestamp,
42
		EVM: pallet_evm,
43
		Ethereum: pallet_ethereum,
44
		EvmForeignAssets: pallet_moonbeam_foreign_assets,
45
	}
46
1505
);
47

            
48
parameter_types! {
49
	pub const BlockHashCount: u32 = 250;
50
}
51

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

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

            
103
parameter_types! {
104
	pub const MinimumPeriod: u64 = 6000 / 2;
105
}
106

            
107
impl pallet_timestamp::Config for Test {
108
	type Moment = u64;
109
	type OnTimestampSet = ();
110
	type MinimumPeriod = MinimumPeriod;
111
	type WeightInfo = ();
112
}
113

            
114
parameter_types! {
115
	pub BlockGasLimit: U256 = U256::from(u64::MAX);
116
	pub const WeightPerGas: Weight = Weight::from_parts(1, 0);
117
	pub GasLimitPovSizeRatio: u64 = 16;
118
	pub GasLimitStorageGrowthRatio: u64 = 366;
119
}
120

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

            
147
parameter_types! {
148
	pub const PostBlockAndTxnHashes: PostLogContent = PostLogContent::BlockAndTxnHashes;
149
}
150

            
151
impl pallet_ethereum::Config for Test {
152
	type RuntimeEvent = RuntimeEvent;
153
	type StateRoot = IntermediateStateRoot<<Test as frame_system::Config>::Version>;
154
	type PostLogContent = PostBlockAndTxnHashes;
155
	type ExtraDataLength = ConstU32<30>;
156
}
157

            
158
/// Gets parameters of last `ForeignAssetCreatedHook::on_asset_created` hook invocation
159
1
pub fn get_asset_created_hook_invocation<ForeignAsset: Decode>() -> Option<(ForeignAsset, AssetId)>
160
1
{
161
1
	storage::unhashed::get_raw(b"____on_foreign_asset_created")
162
1
		.map(|output| Decode::decode(&mut output.as_slice()).expect("Decoding should work"))
163
1
}
164

            
165
/// Notes down parameters of current `ForeignAssetCreatedHook::on_asset_created` hook invocation
166
5
fn note_on_asset_created_hook_invocation<ForeignAsset: Encode>(
167
5
	foreign_asset: &ForeignAsset,
168
5
	asset_id: &AssetId,
169
5
) {
170
5
	storage::unhashed::put_raw(
171
5
		b"____on_foreign_asset_created",
172
5
		(foreign_asset, asset_id).encode().as_slice(),
173
5
	);
174
5
}
175

            
176
/// Test hook that records the hook invocation with exact params
177
pub struct NoteDownHook<ForeignAsset>(PhantomData<ForeignAsset>);
178

            
179
impl<ForeignAsset: Encode> ForeignAssetCreatedHook<ForeignAsset> for NoteDownHook<ForeignAsset> {
180
5
	fn on_asset_created(foreign_asset: &ForeignAsset, asset_id: &AssetId) {
181
5
		note_on_asset_created_hook_invocation(foreign_asset, asset_id);
182
5
	}
183
}
184

            
185
pub struct AccountIdToH160;
186
impl sp_runtime::traits::Convert<AccountId, H160> for AccountIdToH160 {
187
12
	fn convert(account_id: AccountId) -> H160 {
188
12
		account_id.into()
189
12
	}
190
}
191

            
192
impl crate::Config for Test {
193
	type AccountIdToH160 = AccountIdToH160;
194
	type AssetIdFilter = Everything;
195
	type EvmRunner = pallet_evm::runner::stack::Runner<Self>;
196
	type ForeignAssetCreatorOrigin = EnsureRoot<AccountId>;
197
	type ForeignAssetFreezerOrigin = EnsureRoot<AccountId>;
198
	type ForeignAssetModifierOrigin = EnsureRoot<AccountId>;
199
	type ForeignAssetUnfreezerOrigin = EnsureRoot<AccountId>;
200
	type OnForeignAssetCreated = NoteDownHook<Location>;
201
	type MaxForeignAssets = ConstU32<3>;
202
	type RuntimeEvent = RuntimeEvent;
203
	type WeightInfo = ();
204
	type XcmLocationToH160 = ();
205
}
206

            
207
pub(crate) struct ExtBuilder {
208
	// endowed accounts with balances
209
	balances: Vec<(AccountId, Balance)>,
210
}
211

            
212
impl Default for ExtBuilder {
213
6
	fn default() -> ExtBuilder {
214
6
		ExtBuilder { balances: vec![] }
215
6
	}
216
}
217

            
218
impl ExtBuilder {
219
6
	pub(crate) fn build(self) -> sp_io::TestExternalities {
220
6
		let mut t = frame_system::GenesisConfig::<Test>::default()
221
6
			.build_storage()
222
6
			.expect("Frame system builds valid default genesis config");
223
6

            
224
6
		pallet_balances::GenesisConfig::<Test> {
225
6
			balances: self.balances,
226
6
		}
227
6
		.assimilate_storage(&mut t)
228
6
		.expect("Pallet balances storage can be assimilated");
229
6
		let mut ext = sp_io::TestExternalities::new(t);
230
6
		ext.execute_with(|| System::set_block_number(1));
231
6
		ext
232
6
	}
233
}
234

            
235
2
pub(crate) fn events() -> Vec<super::Event<Test>> {
236
2
	System::events()
237
2
		.into_iter()
238
7
		.map(|r| r.event)
239
7
		.filter_map(|e| {
240
7
			if let RuntimeEvent::EvmForeignAssets(inner) = e {
241
3
				Some(inner)
242
			} else {
243
4
				None
244
			}
245
7
		})
246
2
		.collect::<Vec<_>>()
247
2
}
248

            
249
2
pub fn expect_events(e: Vec<super::Event<Test>>) {
250
2
	assert_eq!(events(), e);
251
2
}