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 moonriver_runtime::{
26
	asset_config::AssetRegistrarMetadata, currency::MOVR, xcm_config::AssetType, AccountId,
27
	AssetId, AssetManager, AsyncBacking, AuthorInherent, Balance, Ethereum, InflationInfo,
28
	ParachainStaking, Range, Runtime, RuntimeCall, RuntimeEvent, System, TransactionConverter,
29
	UncheckedExtrinsic, HOURS,
30
};
31
use nimbus_primitives::{NimbusId, NIMBUS_ENGINE_ID};
32
use polkadot_parachain::primitives::HeadData;
33
use sp_consensus_slots::Slot;
34
use sp_core::{Encode, H160};
35
use sp_runtime::{traits::Dispatchable, BuildStorage, Digest, DigestItem, Perbill, Percent};
36

            
37
use cumulus_pallet_parachain_system::MessagingStateSnapshot;
38
use cumulus_primitives_core::AbridgedHrmpChannel;
39
use fp_rpc::ConvertTransaction;
40
use moonriver_runtime::bridge_config::XcmOverPolkadotInstance;
41
use moonriver_runtime::{Assets, EvmForeignAssets, XcmWeightTrader};
42
use pallet_transaction_payment::Multiplier;
43
use std::collections::BTreeMap;
44
use xcm::latest::{InteriorLocation, Location};
45

            
46
10
pub fn existential_deposit() -> u128 {
47
10
	<Runtime as pallet_balances::Config>::ExistentialDeposit::get()
48
10
}
49

            
50
// A valid signed Alice transfer.
51
pub const VALID_ETH_TX: &str =
52
	"02f86d8205018085174876e80085e8d4a5100082520894f24ff3a9cf04c71dbc94d0b566f7a27b9456\
53
	6cac8080c001a0e1094e1a52520a75c0255db96132076dd0f1263089f838bea548cbdbfc64a4d19f031c\
54
	92a8cb04e2d68d20a6158d542a07ac440cc8d07b6e36af02db046d92df";
55

            
56
// An invalid signed Alice transfer with a gas limit artifically set to 0.
57
pub const INVALID_ETH_TX: &str =
58
	"f86180843b9aca00809412cb274aad8251c875c0bf6872b67d9983e53fdd01801ca00e28ba2dd3c5a\
59
	3fd467d4afd7aefb4a34b373314fff470bb9db743a84d674a0aa06e5994f2d07eafe1c37b4ce5471ca\
60
	ecec29011f6f5bf0b1a552c55ea348df35f";
61

            
62
3
pub fn rpc_run_to_block(n: u32) {
63
6
	while System::block_number() < n {
64
3
		Ethereum::on_finalize(System::block_number());
65
3
		System::set_block_number(System::block_number() + 1);
66
3
		Ethereum::on_initialize(System::block_number());
67
3
	}
68
3
}
69

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

            
92
6600
		increase_last_relay_slot_number(1);
93
6600

            
94
6600
		// Initialize the new block
95
6600
		AuthorInherent::on_initialize(System::block_number());
96
6600
		ParachainStaking::on_initialize(System::block_number());
97
6600

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

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

            
107
// Helper function to give a simple evm context suitable for tests.
108
// We can remove this once https://github.com/rust-blockchain/evm/pull/35
109
// is in our dependency graph.
110
pub fn evm_test_context() -> fp_evm::Context {
111
	fp_evm::Context {
112
		address: Default::default(),
113
		caller: Default::default(),
114
		apparent_value: From::from(0),
115
	}
116
}
117

            
118
// Test struct with the purpose of initializing xcm assets
119
#[derive(Clone)]
120
pub struct XcmAssetInitialization {
121
	pub asset_type: AssetType,
122
	pub metadata: AssetRegistrarMetadata,
123
	pub balances: Vec<(AccountId, Balance)>,
124
	pub is_sufficient: bool,
125
}
126

            
127
pub struct ExtBuilder {
128
	// endowed accounts with balances
129
	balances: Vec<(AccountId, Balance)>,
130
	// [collator, amount]
131
	collators: Vec<(AccountId, Balance)>,
132
	// [delegator, collator, nomination_amount]
133
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
134
	// per-round inflation config
135
	inflation: InflationInfo<Balance>,
136
	// AuthorId -> AccoutId mappings
137
	mappings: Vec<(NimbusId, AccountId)>,
138
	// Crowdloan fund
139
	crowdloan_fund: Balance,
140
	// Chain id
141
	chain_id: u64,
142
	// EVM genesis accounts
143
	evm_accounts: BTreeMap<H160, GenesisAccount>,
144
	// [assettype, metadata, Vec<Account, Balance,>, is_sufficient]
145
	xcm_assets: Vec<XcmAssetInitialization>,
146
	evm_native_foreign_assets: bool,
147
	safe_xcm_version: Option<u32>,
148
	opened_bridges: Vec<(Location, InteriorLocation, Option<bp_moonbeam::LaneId>)>,
149
}
150

            
151
impl Default for ExtBuilder {
152
64
	fn default() -> ExtBuilder {
153
64
		ExtBuilder {
154
64
			balances: vec![],
155
64
			delegations: vec![],
156
64
			collators: vec![],
157
64
			inflation: InflationInfo {
158
64
				expect: Range {
159
64
					min: 100_000 * MOVR,
160
64
					ideal: 200_000 * MOVR,
161
64
					max: 500_000 * MOVR,
162
64
				},
163
64
				// not used
164
64
				annual: Range {
165
64
					min: Perbill::from_percent(50),
166
64
					ideal: Perbill::from_percent(50),
167
64
					max: Perbill::from_percent(50),
168
64
				},
169
64
				// unrealistically high parameterization, only for testing
170
64
				round: Range {
171
64
					min: Perbill::from_percent(5),
172
64
					ideal: Perbill::from_percent(5),
173
64
					max: Perbill::from_percent(5),
174
64
				},
175
64
			},
176
64
			mappings: vec![],
177
64
			crowdloan_fund: 0,
178
64
			chain_id: CHAIN_ID,
179
64
			evm_accounts: BTreeMap::new(),
180
64
			xcm_assets: vec![],
181
64
			evm_native_foreign_assets: false,
182
64
			safe_xcm_version: None,
183
64
			opened_bridges: vec![],
184
64
		}
185
64
	}
186
}
187

            
188
impl ExtBuilder {
189
2
	pub fn with_evm_accounts(mut self, accounts: BTreeMap<H160, GenesisAccount>) -> Self {
190
2
		self.evm_accounts = accounts;
191
2
		self
192
2
	}
193

            
194
44
	pub fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
195
44
		self.balances = balances;
196
44
		self
197
44
	}
198

            
199
15
	pub fn with_collators(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
200
15
		self.collators = collators;
201
15
		self
202
15
	}
203

            
204
7
	pub fn with_delegations(mut self, delegations: Vec<(AccountId, AccountId, Balance)>) -> Self {
205
7
		self.delegations = delegations
206
7
			.into_iter()
207
8
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
208
7
			.collect();
209
7
		self
210
7
	}
211

            
212
6
	pub fn with_crowdloan_fund(mut self, crowdloan_fund: Balance) -> Self {
213
6
		self.crowdloan_fund = crowdloan_fund;
214
6
		self
215
6
	}
216

            
217
14
	pub fn with_mappings(mut self, mappings: Vec<(NimbusId, AccountId)>) -> Self {
218
14
		self.mappings = mappings;
219
14
		self
220
14
	}
221

            
222
	#[allow(dead_code)]
223
	pub fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
224
		self.inflation = inflation;
225
		self
226
	}
227

            
228
9
	pub fn with_xcm_assets(mut self, xcm_assets: Vec<XcmAssetInitialization>) -> Self {
229
9
		self.xcm_assets = xcm_assets;
230
9
		self
231
9
	}
232

            
233
4
	pub fn with_evm_native_foreign_assets(mut self) -> Self {
234
4
		self.evm_native_foreign_assets = true;
235
4
		self
236
4
	}
237

            
238
7
	pub fn with_safe_xcm_version(mut self, safe_xcm_version: u32) -> Self {
239
7
		self.safe_xcm_version = Some(safe_xcm_version);
240
7
		self
241
7
	}
242

            
243
2
	pub fn with_open_bridges(
244
2
		mut self,
245
2
		opened_bridges: Vec<(Location, InteriorLocation, Option<bp_moonbeam::LaneId>)>,
246
2
	) -> Self {
247
2
		self.opened_bridges = opened_bridges;
248
2
		self
249
2
	}
250

            
251
64
	pub fn build(self) -> sp_io::TestExternalities {
252
64
		let mut t = frame_system::GenesisConfig::<Runtime>::default()
253
64
			.build_storage()
254
64
			.unwrap();
255
64

            
256
64
		parachain_info::GenesisConfig::<Runtime> {
257
64
			parachain_id: <bp_moonriver::Moonriver as bp_runtime::Parachain>::PARACHAIN_ID.into(),
258
64
			_config: Default::default(),
259
64
		}
260
64
		.assimilate_storage(&mut t)
261
64
		.unwrap();
262
64

            
263
64
		pallet_balances::GenesisConfig::<Runtime> {
264
64
			balances: self.balances,
265
64
		}
266
64
		.assimilate_storage(&mut t)
267
64
		.unwrap();
268
64

            
269
64
		pallet_parachain_staking::GenesisConfig::<Runtime> {
270
64
			candidates: self.collators,
271
64
			delegations: self.delegations,
272
64
			inflation_config: self.inflation,
273
64
			collator_commission: Perbill::from_percent(20),
274
64
			parachain_bond_reserve_percent: Percent::from_percent(30),
275
64
			blocks_per_round: 2 * HOURS,
276
64
			num_selected_candidates: 8,
277
64
		}
278
64
		.assimilate_storage(&mut t)
279
64
		.unwrap();
280
64

            
281
64
		pallet_crowdloan_rewards::GenesisConfig::<Runtime> {
282
64
			funded_amount: self.crowdloan_fund,
283
64
		}
284
64
		.assimilate_storage(&mut t)
285
64
		.unwrap();
286
64

            
287
64
		pallet_author_mapping::GenesisConfig::<Runtime> {
288
64
			mappings: self.mappings,
289
64
		}
290
64
		.assimilate_storage(&mut t)
291
64
		.unwrap();
292
64

            
293
64
		let genesis_config = pallet_evm_chain_id::GenesisConfig::<Runtime> {
294
64
			chain_id: self.chain_id,
295
64
			..Default::default()
296
64
		};
297
64
		genesis_config.assimilate_storage(&mut t).unwrap();
298
64

            
299
64
		let genesis_config = pallet_evm::GenesisConfig::<Runtime> {
300
64
			accounts: self.evm_accounts,
301
64
			..Default::default()
302
64
		};
303
64
		genesis_config.assimilate_storage(&mut t).unwrap();
304
64

            
305
64
		let genesis_config = pallet_ethereum::GenesisConfig::<Runtime> {
306
64
			..Default::default()
307
64
		};
308
64
		genesis_config.assimilate_storage(&mut t).unwrap();
309
64

            
310
64
		let genesis_config = pallet_xcm::GenesisConfig::<Runtime> {
311
64
			safe_xcm_version: self.safe_xcm_version,
312
64
			..Default::default()
313
64
		};
314
64
		genesis_config.assimilate_storage(&mut t).unwrap();
315
64

            
316
64
		let genesis_config = pallet_transaction_payment::GenesisConfig::<Runtime> {
317
64
			multiplier: Multiplier::from(10u128),
318
64
			..Default::default()
319
64
		};
320
64
		genesis_config.assimilate_storage(&mut t).unwrap();
321
64

            
322
64
		let genesis_config = pallet_xcm_bridge::GenesisConfig::<Runtime, XcmOverPolkadotInstance> {
323
64
			opened_bridges: self.opened_bridges,
324
64
			_phantom: Default::default(),
325
64
		};
326
64
		genesis_config.assimilate_storage(&mut t).unwrap();
327
64

            
328
64
		let mut ext = sp_io::TestExternalities::new(t);
329
64
		let xcm_assets = self.xcm_assets.clone();
330
64
		ext.execute_with(|| {
331
64
			// Mock hrmp egress_channels
332
64
			cumulus_pallet_parachain_system::RelevantMessagingState::<Runtime>::put(
333
64
				MessagingStateSnapshot {
334
64
					dmq_mqc_head: Default::default(),
335
64
					relay_dispatch_queue_remaining_capacity: Default::default(),
336
64
					ingress_channels: vec![],
337
64
					egress_channels: vec![(
338
64
						1_000.into(),
339
64
						AbridgedHrmpChannel {
340
64
							max_capacity: u32::MAX,
341
64
							max_total_size: u32::MAX,
342
64
							max_message_size: u32::MAX,
343
64
							msg_count: 0,
344
64
							total_size: 0,
345
64
							mqc_head: None,
346
64
						},
347
64
					)],
348
64
				},
349
64
			);
350

            
351
			// If any xcm assets specified, we register them here
352
73
			for xcm_asset_initialization in xcm_assets {
353
9
				let asset_id: AssetId = xcm_asset_initialization.asset_type.clone().into();
354
9
				if self.evm_native_foreign_assets {
355
4
					let AssetType::Xcm(location) = xcm_asset_initialization.asset_type;
356
4
					let metadata = xcm_asset_initialization.metadata.clone();
357
4
					EvmForeignAssets::register_foreign_asset(
358
4
						asset_id,
359
4
						xcm::VersionedLocation::from(location).try_into().unwrap(),
360
4
						metadata.decimals,
361
4
						metadata.symbol.try_into().unwrap(),
362
4
						metadata.name.try_into().unwrap(),
363
4
					)
364
4
					.expect("register evm native foreign asset");
365
4

            
366
4
					if xcm_asset_initialization.is_sufficient {
367
4
						XcmWeightTrader::add_asset(
368
4
							root_origin(),
369
4
							xcm::VersionedLocation::from(location).try_into().unwrap(),
370
4
							MOVR, // 1 to 1 ratio
371
4
						)
372
4
						.expect("register evm native foreign asset as sufficient");
373
4
					}
374

            
375
8
					for (account, balance) in xcm_asset_initialization.balances {
376
4
						EvmForeignAssets::mint_into(asset_id.into(), account, balance.into())
377
4
							.expect("mint evm native foreign asset");
378
4
					}
379
				} else {
380
5
					AssetManager::register_foreign_asset(
381
5
						root_origin(),
382
5
						xcm_asset_initialization.asset_type,
383
5
						xcm_asset_initialization.metadata,
384
5
						1,
385
5
						xcm_asset_initialization.is_sufficient,
386
5
					)
387
5
					.unwrap();
388
10
					for (account, balance) in xcm_asset_initialization.balances {
389
5
						Assets::mint(
390
5
							origin_of(AssetManager::account_id()),
391
5
							asset_id.into(),
392
5
							account,
393
5
							balance,
394
5
						)
395
5
						.unwrap();
396
5
					}
397
				}
398
			}
399
64
			System::set_block_number(1);
400
64
		});
401
64
		ext
402
64
	}
403
}
404

            
405
pub const CHAIN_ID: u64 = 1281;
406
pub const ALICE: [u8; 20] = [4u8; 20];
407
pub const ALICE_NIMBUS: [u8; 32] = [4u8; 32];
408
pub const BOB: [u8; 20] = [5u8; 20];
409
pub const CHARLIE: [u8; 20] = [6u8; 20];
410
pub const DAVE: [u8; 20] = [7u8; 20];
411
pub const EVM_CONTRACT: [u8; 20] = [8u8; 20];
412

            
413
28
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
414
28
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
415
28
}
416

            
417
14
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
418
14
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
419
14
}
420

            
421
27
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
422
27
	<Runtime as frame_system::Config>::RuntimeOrigin::root()
423
27
}
424

            
425
/// Mock the inherent that sets validation data in ParachainSystem, which
426
/// contains the `relay_chain_block_number`, which is used in `author-filter` as a
427
/// source of randomness to filter valid authors at each block.
428
14
pub fn set_parachain_inherent_data() {
429
	use cumulus_primitives_core::PersistedValidationData;
430
	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
431

            
432
14
	let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
433
14
	pallet_author_inherent::Author::<Runtime>::put(author);
434
14

            
435
14
	let mut relay_sproof = RelayStateSproofBuilder::default();
436
14
	relay_sproof.para_id = bp_moonriver::PARACHAIN_ID.into();
437
14
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
438
14

            
439
14
	let additional_key_values = vec![(
440
14
		moonbeam_core_primitives::well_known_relay_keys::TIMESTAMP_NOW.to_vec(),
441
14
		sp_timestamp::Timestamp::default().encode(),
442
14
	)];
443
14

            
444
14
	relay_sproof.additional_key_values = additional_key_values;
445
14

            
446
14
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
447
14

            
448
14
	let vfp = PersistedValidationData {
449
14
		relay_parent_number: 1u32,
450
14
		relay_parent_storage_root,
451
14
		..Default::default()
452
14
	};
453
14
	let parachain_inherent_data = ParachainInherentData {
454
14
		validation_data: vfp,
455
14
		relay_chain_state: relay_chain_state,
456
14
		downward_messages: Default::default(),
457
14
		horizontal_messages: Default::default(),
458
14
	};
459
14
	assert_ok!(RuntimeCall::ParachainSystem(
460
14
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
461
14
			data: parachain_inherent_data
462
14
		}
463
14
	)
464
14
	.dispatch(inherent_origin()));
465
14
}
466

            
467
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
468
7
	let converter = TransactionConverter;
469
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
470
7
}
471

            
472
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
473
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
474
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
475
9
	assert!(transaction.is_ok());
476
9
	transaction.unwrap()
477
9
}
478

            
479
6602
pub(crate) fn increase_last_relay_slot_number(amount: u64) {
480
6602
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
481
6602
	frame_support::storage::unhashed::put(
482
6602
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
483
6602
		&((Slot::from(last_relay_slot + amount), 0)),
484
6602
	);
485
6602
}