1
// Copyright 2019-2025 PureStake Inc.
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
#![allow(dead_code)]
18

            
19
use cumulus_primitives_parachain_inherent::ParachainInherentData;
20
use fp_evm::GenesisAccount;
21
use frame_support::{
22
	assert_ok,
23
	traits::{OnFinalize, OnInitialize},
24
};
25
pub use moonbase_runtime::{
26
	currency::UNIT, AccountId, AsyncBacking, AuthorInherent, Balance, Ethereum, EvmForeignAssets,
27
	InflationInfo, ParachainStaking, Range, Runtime, RuntimeCall, RuntimeEvent, System,
28
	TransactionConverter, UncheckedExtrinsic, HOURS,
29
};
30
use nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID};
31
use polkadot_parachain::primitives::HeadData;
32
use sp_consensus_slots::Slot;
33
use sp_core::{Encode, H160};
34
use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent};
35

            
36
use std::collections::BTreeMap;
37

            
38
use fp_rpc::ConvertTransaction;
39
use pallet_transaction_payment::Multiplier;
40

            
41
11
pub fn existential_deposit() -> u128 {
42
11
	<Runtime as pallet_balances::Config>::ExistentialDeposit::get()
43
11
}
44

            
45
// A valid signed Alice transfer.
46
pub const VALID_ETH_TX: &str =
47
	"02f86d8205018085174876e80085e8d4a5100082520894f24ff3a9cf04c71dbc94d0b566f7a27b9456\
48
	6cac8080c001a0e1094e1a52520a75c0255db96132076dd0f1263089f838bea548cbdbfc64a4d19f031c\
49
	92a8cb04e2d68d20a6158d542a07ac440cc8d07b6e36af02db046d92df";
50

            
51
// An invalid signed Alice transfer with a gas limit artifically set to 0.
52
pub const INVALID_ETH_TX: &str =
53
	"f86180843b9aca00809412cb274aad8251c875c0bf6872b67d9983e53fdd01801ca00e28ba2dd3c5a\
54
	3fd467d4afd7aefb4a34b373314fff470bb9db743a84d674a0aa06e5994f2d07eafe1c37b4ce5471ca\
55
	ecec29011f6f5bf0b1a552c55ea348df35f";
56

            
57
3
pub fn rpc_run_to_block(n: u32) {
58
6
	while System::block_number() < n {
59
3
		Ethereum::on_finalize(System::block_number());
60
3
		System::set_block_number(System::block_number() + 1);
61
3
		Ethereum::on_initialize(System::block_number());
62
3
	}
63
3
}
64

            
65
/// Utility function that advances the chain to the desired block number.
66
/// If an author is provided, that author information is injected to all the blocks in the meantime.
67
9
pub fn run_to_block(n: u32, author: Option<NimbusId>) {
68
9
	// Finalize the first block
69
9
	Ethereum::on_finalize(System::block_number());
70
6609
	while System::block_number() < n {
71
		// Set the new block number and author
72
6600
		match author {
73
6600
			Some(ref author) => {
74
6600
				let pre_digest = Digest {
75
6600
					logs: vec![DigestItem::PreRuntime(NIMBUS_ENGINE_ID, author.encode())],
76
6600
				};
77
6600
				System::reset_events();
78
6600
				System::initialize(
79
6600
					&(System::block_number() + 1),
80
6600
					&System::parent_hash(),
81
6600
					&pre_digest,
82
6600
				);
83
6600
			}
84
			None => {
85
				System::set_block_number(System::block_number() + 1);
86
			}
87
		}
88

            
89
6600
		increase_last_relay_slot_number(1);
90
6600

            
91
6600
		// Initialize the new block
92
6600
		AuthorInherent::on_initialize(System::block_number());
93
6600
		ParachainStaking::on_initialize(System::block_number());
94
6600
		Ethereum::on_initialize(System::block_number());
95
6600

            
96
6600
		// Finalize the block
97
6600
		Ethereum::on_finalize(System::block_number());
98
6600
		ParachainStaking::on_finalize(System::block_number());
99
	}
100
9
}
101

            
102
8
pub fn last_event() -> RuntimeEvent {
103
8
	System::events().pop().expect("Event expected").event
104
8
}
105

            
106
// Test struct with the purpose of initializing xcm assets
107
#[derive(Clone)]
108
pub struct XcmAssetInitialization {
109
	pub asset_id: u128,
110
	pub xcm_location: xcm::v5::Location,
111
	pub decimals: u8,
112
	pub name: &'static str,
113
	pub symbol: &'static str,
114
	pub balances: Vec<(AccountId, Balance)>,
115
}
116

            
117
pub struct ExtBuilder {
118
	// endowed accounts with balances
119
	balances: Vec<(AccountId, Balance)>,
120
	// [collator, amount]
121
	collators: Vec<(AccountId, Balance)>,
122
	// [delegator, collator, nomination_amount]
123
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
124
	// per-round inflation config
125
	inflation: InflationInfo<Balance>,
126
	// AuthorId -> AccoutId mappings
127
	mappings: Vec<(NimbusId, AccountId)>,
128
	// Crowdloan fund
129
	crowdloan_fund: Balance,
130
	// Chain id
131
	chain_id: u64,
132
	// EVM genesis accounts
133
	evm_accounts: BTreeMap<H160, GenesisAccount>,
134
	// [assettype, metadata, Vec<Account, Balance>]
135
	xcm_assets: Vec<XcmAssetInitialization>,
136
	safe_xcm_version: Option<u32>,
137
}
138

            
139
impl Default for ExtBuilder {
140
65
	fn default() -> ExtBuilder {
141
65
		ExtBuilder {
142
65
			balances: vec![],
143
65
			delegations: vec![],
144
65
			collators: vec![],
145
65
			inflation: InflationInfo {
146
65
				expect: Range {
147
65
					min: 100_000 * UNIT,
148
65
					ideal: 200_000 * UNIT,
149
65
					max: 500_000 * UNIT,
150
65
				},
151
65
				// not used
152
65
				annual: Range {
153
65
					min: Perbill::from_percent(50),
154
65
					ideal: Perbill::from_percent(50),
155
65
					max: Perbill::from_percent(50),
156
65
				},
157
65
				// unrealistically high parameterization, only for testing
158
65
				round: Range {
159
65
					min: Perbill::from_percent(5),
160
65
					ideal: Perbill::from_percent(5),
161
65
					max: Perbill::from_percent(5),
162
65
				},
163
65
			},
164
65
			mappings: vec![],
165
65
			crowdloan_fund: 0,
166
65
			chain_id: CHAIN_ID,
167
65
			evm_accounts: BTreeMap::new(),
168
65
			xcm_assets: vec![],
169
65
			safe_xcm_version: None,
170
65
		}
171
65
	}
172
}
173

            
174
impl ExtBuilder {
175
2
	pub fn with_evm_accounts(mut self, accounts: BTreeMap<H160, GenesisAccount>) -> Self {
176
2
		self.evm_accounts = accounts;
177
2
		self
178
2
	}
179

            
180
44
	pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
181
44
		self.balances = balances;
182
44
		self
183
44
	}
184

            
185
14
	pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
186
14
		self.collators = collators;
187
14
		self
188
14
	}
189

            
190
7
	pub fn with_delegations(mut self, delegations: Vec<(AccountId, AccountId, Balance)>) -> Self {
191
7
		self.delegations = delegations
192
7
			.into_iter()
193
8
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
194
7
			.collect();
195
7
		self
196
7
	}
197

            
198
4
	pub fn with_xcm_assets(mut self, xcm_assets: Vec<XcmAssetInitialization>) -> Self {
199
4
		self.xcm_assets = xcm_assets;
200
4
		self
201
4
	}
202

            
203
6
	pub fn with_crowdloan_fund(mut self, crowdloan_fund: Balance) -> Self {
204
6
		self.crowdloan_fund = crowdloan_fund;
205
6
		self
206
6
	}
207

            
208
13
	pub fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
209
13
		self.mappings = mappings;
210
13
		self
211
13
	}
212

            
213
6
	pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
214
6
		self.safe_xcm_version = Some(safe_xcm_version);
215
6
		self
216
6
	}
217

            
218
	#[allow(dead_code)]
219
	pub fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
220
		self.inflation = inflation;
221
		self
222
	}
223

            
224
65
	pub fn build(self) -> sp_io::TestExternalities {
225
65
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
226
65
			.build_storage()
227
65
			.unwrap();
228
65

            
229
65
		pallet_balances::GenesisConfig::<Runtime> {
230
65
			balances: self.balances,
231
65
		}
232
65
		.assimilate_storage(&mut t)
233
65
		.unwrap();
234
65

            
235
65
		pallet_parachain_staking::GenesisConfig::<Runtime> {
236
65
			candidates: self.collators,
237
65
			delegations: self.delegations,
238
65
			inflation_config: self.inflation,
239
65
			collator_commission: Perbill::from_percent(20),
240
65
			parachain_bond_reserve_percent: Percent::from_percent(30),
241
65
			blocks_per_round: 2 * HOURS,
242
65
			num_selected_candidates: 8,
243
65
		}
244
65
		.assimilate_storage(&mut t)
245
65
		.unwrap();
246
65

            
247
65
		pallet_crowdloan_rewards::GenesisConfig::<Runtime> {
248
65
			funded_amount: self.crowdloan_fund,
249
65
		}
250
65
		.assimilate_storage(&mut t)
251
65
		.unwrap();
252
65

            
253
65
		pallet_author_mapping::GenesisConfig::<Runtime> {
254
65
			mappings: self.mappings,
255
65
		}
256
65
		.assimilate_storage(&mut t)
257
65
		.unwrap();
258
65

            
259
65
		let genesis_config = pallet_evm_chain_id::GenesisConfig::<Runtime> {
260
65
			chain_id: self.chain_id,
261
65
			..Default::default()
262
65
		};
263
65
		genesis_config.assimilate_storage(&mut t).unwrap();
264
65

            
265
65
		let genesis_config = pallet_evm::GenesisConfig::<Runtime> {
266
65
			accounts: self.evm_accounts,
267
65
			..Default::default()
268
65
		};
269
65
		genesis_config.assimilate_storage(&mut t).unwrap();
270
65

            
271
65
		let genesis_config = pallet_ethereum::GenesisConfig::<Runtime> {
272
65
			..Default::default()
273
65
		};
274
65
		genesis_config.assimilate_storage(&mut t).unwrap();
275
65

            
276
65
		let genesis_config = pallet_xcm::GenesisConfig::<Runtime> {
277
65
			safe_xcm_version: self.safe_xcm_version,
278
65
			..Default::default()
279
65
		};
280
65
		genesis_config.assimilate_storage(&mut t).unwrap();
281
65

            
282
65
		let genesis_config = pallet_transaction_payment::GenesisConfig::<Runtime> {
283
65
			multiplier: Multiplier::from(8u128),
284
65
			..Default::default()
285
65
		};
286
65
		genesis_config.assimilate_storage(&mut t).unwrap();
287
65

            
288
65
		let mut ext = sp_io::TestExternalities::new(t);
289
65

            
290
65
		let xcm_assets = self.xcm_assets.clone();
291
65

            
292
65
		ext.execute_with(|| {
293
			// If any xcm assets specified, we register them here
294
69
			for xcm_asset_initialization in xcm_assets {
295
4
				let asset_id = xcm_asset_initialization.asset_id;
296
4
				EvmForeignAssets::create_foreign_asset(
297
4
					root_origin(),
298
4
					asset_id,
299
4
					xcm_asset_initialization.xcm_location,
300
4
					xcm_asset_initialization.decimals,
301
4
					xcm_asset_initialization
302
4
						.symbol
303
4
						.as_bytes()
304
4
						.to_vec()
305
4
						.try_into()
306
4
						.expect("too long"),
307
4
					xcm_asset_initialization
308
4
						.name
309
4
						.as_bytes()
310
4
						.to_vec()
311
4
						.try_into()
312
4
						.expect("too long"),
313
4
				)
314
4
				.expect("fail to create foreign asset");
315

            
316
8
				for (account, balance) in xcm_asset_initialization.balances {
317
4
					if EvmForeignAssets::mint_into(asset_id, account, balance.into()).is_err() {
318
						panic!("fail to mint foreign asset");
319
4
					}
320
				}
321
			}
322
65
			System::set_block_number(1);
323
65
		});
324
65
		ext
325
65
	}
326
}
327

            
328
pub const CHAIN_ID: u64 = 1281;
329
pub const ALICE: [u8; 20] = [4u8; 20];
330
pub const ALICE_NIMBUS: [u8; 32] = [4u8; 32];
331
pub const BOB: [u8; 20] = [5u8; 20];
332
pub const CHARLIE: [u8; 20] = [6u8; 20];
333
pub const DAVE: [u8; 20] = [7u8; 20];
334
pub const EVM_CONTRACT: [u8; 20] = [8u8; 20];
335

            
336
23
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
337
23
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
338
23
}
339

            
340
7
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
341
7
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
342
7
}
343

            
344
28
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
345
28
	<Runtime as frame_system::Config>::RuntimeOrigin::root()
346
28
}
347

            
348
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
349
7
	let converter = TransactionConverter;
350
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
351
7
}
352

            
353
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
354
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
355
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
356
9
	assert!(transaction.is_ok());
357
9
	transaction.unwrap()
358
9
}
359

            
360
/// Mock the inherent that sets validation data in ParachainSystem, which
361
/// contains the `relay_chain_block_number`, which is used in `author-filter` as a
362
/// source of randomness to filter valid authors at each block.
363
7
pub fn set_parachain_inherent_data() {
364
	use cumulus_primitives_core::PersistedValidationData;
365
	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
366

            
367
7
	let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
368
7
	pallet_author_inherent::Author::<Runtime>::put(author);
369
7

            
370
7
	let mut relay_sproof = RelayStateSproofBuilder::default();
371
7
	relay_sproof.para_id = 100u32.into();
372
7
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
373
7

            
374
7
	let additional_key_values = vec![(
375
7
		moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
376
7
		sp_timestamp::Timestamp::default().encode(),
377
7
	)];
378
7

            
379
7
	relay_sproof.additional_key_values = additional_key_values;
380
7

            
381
7
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
382
7

            
383
7
	let vfp = PersistedValidationData {
384
7
		relay_parent_number: 1u32,
385
7
		relay_parent_storage_root,
386
7
		..Default::default()
387
7
	};
388
7
	let parachain_inherent_data = ParachainInherentData {
389
7
		validation_data: vfp,
390
7
		relay_chain_state: relay_chain_state,
391
7
		downward_messages: Default::default(),
392
7
		horizontal_messages: Default::default(),
393
7
	};
394
7
	assert_ok!(RuntimeCall::ParachainSystem(
395
7
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
396
7
			data: parachain_inherent_data
397
7
		}
398
7
	)
399
7
	.dispatch(inherent_origin()));
400
7
}
401

            
402
6602
pub(crate) fn increase_last_relay_slot_number(amount: u64) {
403
6602
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
404
6602
	frame_support::storage::unhashed::put(
405
6602
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
406
6602
		&((Slot::from(last_relay_slot + amount), 0)),
407
6602
	);
408
6602
}