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 cumulus_pallet_parachain_system::MessagingStateSnapshot;
37
use cumulus_primitives_core::AbridgedHrmpChannel;
38
use fp_rpc::ConvertTransaction;
39
use moonbase_runtime::XcmWeightTrader;
40
use pallet_transaction_payment::Multiplier;
41
use std::collections::BTreeMap;
42

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

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

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

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

            
67
/// Utility function that advances the chain to the desired block number.
68
/// If an author is provided, that author information is injected to all the blocks in the meantime.
69
9
pub fn run_to_block(n: u32, author: Option<NimbusId>) {
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
		ParachainStaking::on_finalize(System::block_number());
98
	}
99
9
}
100

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
292
67
		ext.execute_with(|| {
293
67
			// Mock hrmp egress_channels
294
67
			cumulus_pallet_parachain_system::RelevantMessagingState::<Runtime>::put(
295
67
				MessagingStateSnapshot {
296
67
					dmq_mqc_head: Default::default(),
297
67
					relay_dispatch_queue_remaining_capacity: Default::default(),
298
67
					ingress_channels: vec![],
299
67
					egress_channels: vec![(
300
67
						1_001.into(),
301
67
						AbridgedHrmpChannel {
302
67
							max_capacity: u32::MAX,
303
67
							max_total_size: u32::MAX,
304
67
							max_message_size: u32::MAX,
305
67
							msg_count: 0,
306
67
							total_size: 0,
307
67
							mqc_head: None,
308
67
						},
309
67
					)],
310
67
				},
311
67
			);
312

            
313
			// If any xcm assets specified, we register them here
314
71
			for xcm_asset_initialization in xcm_assets {
315
4
				let asset_id = xcm_asset_initialization.asset_id;
316
4
				EvmForeignAssets::create_foreign_asset(
317
4
					root_origin(),
318
4
					asset_id,
319
4
					xcm_asset_initialization.xcm_location.clone(),
320
4
					xcm_asset_initialization.decimals,
321
4
					xcm_asset_initialization
322
4
						.symbol
323
4
						.as_bytes()
324
4
						.to_vec()
325
4
						.try_into()
326
4
						.expect("too long"),
327
4
					xcm_asset_initialization
328
4
						.name
329
4
						.as_bytes()
330
4
						.to_vec()
331
4
						.try_into()
332
4
						.expect("too long"),
333
4
				)
334
4
				.expect("fail to create foreign asset");
335
4

            
336
4
				XcmWeightTrader::add_asset(
337
4
					root_origin(),
338
4
					xcm_asset_initialization.xcm_location,
339
4
					UNIT,
340
4
				)
341
4
				.expect("register evm native foreign asset as sufficient");
342

            
343
8
				for (account, balance) in xcm_asset_initialization.balances {
344
4
					if EvmForeignAssets::mint_into(asset_id, account, balance.into()).is_err() {
345
						panic!("fail to mint foreign asset");
346
4
					}
347
				}
348
			}
349
67
			System::set_block_number(1);
350
67
		});
351
67
		ext
352
67
	}
353
}
354

            
355
pub const CHAIN_ID: u64 = 1281;
356
pub const ALICE: [u8; 20] = [4u8; 20];
357
pub const ALICE_NIMBUS: [u8; 32] = [4u8; 32];
358
pub const BOB: [u8; 20] = [5u8; 20];
359
pub const CHARLIE: [u8; 20] = [6u8; 20];
360
pub const DAVE: [u8; 20] = [7u8; 20];
361
pub const EVM_CONTRACT: [u8; 20] = [8u8; 20];
362

            
363
23
pub fn origin_of(account_id: AccountId) -> <Runtime as frame_system::Config>::RuntimeOrigin {
364
23
	<Runtime as frame_system::Config>::RuntimeOrigin::signed(account_id)
365
23
}
366

            
367
10
pub fn inherent_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
368
10
	<Runtime as frame_system::Config>::RuntimeOrigin::none()
369
10
}
370

            
371
32
pub fn root_origin() -> <Runtime as frame_system::Config>::RuntimeOrigin {
372
32
	<Runtime as frame_system::Config>::RuntimeOrigin::root()
373
32
}
374

            
375
7
pub fn unchecked_eth_tx(raw_hex_tx: &str) -> UncheckedExtrinsic {
376
7
	let converter = TransactionConverter;
377
7
	converter.convert_transaction(ethereum_transaction(raw_hex_tx))
378
7
}
379

            
380
9
pub fn ethereum_transaction(raw_hex_tx: &str) -> pallet_ethereum::Transaction {
381
9
	let bytes = hex::decode(raw_hex_tx).expect("Transaction bytes.");
382
9
	let transaction = ethereum::EnvelopedDecodable::decode(&bytes[..]);
383
9
	assert!(transaction.is_ok());
384
9
	transaction.unwrap()
385
9
}
386

            
387
/// Mock the inherent that sets validation data in ParachainSystem, which
388
/// contains the `relay_chain_block_number`, which is used in `author-filter` as a
389
/// source of randomness to filter valid authors at each block.
390
10
pub fn set_parachain_inherent_data() {
391
	use cumulus_primitives_core::PersistedValidationData;
392
	use cumulus_test_relay_sproof_builder::RelayStateSproofBuilder;
393

            
394
10
	let author = AccountId::from(<pallet_evm::Pallet<Runtime>>::find_author());
395
10
	pallet_author_inherent::Author::<Runtime>::put(author);
396
10

            
397
10
	let mut relay_sproof = RelayStateSproofBuilder::default();
398
10
	relay_sproof.para_id = 100u32.into();
399
10
	relay_sproof.included_para_head = Some(HeadData(vec![1, 2, 3]));
400
10

            
401
10
	let additional_key_values = vec![];
402
10

            
403
10
	relay_sproof.additional_key_values = additional_key_values;
404
10

            
405
10
	let (relay_parent_storage_root, relay_chain_state) = relay_sproof.into_state_root_and_proof();
406
10

            
407
10
	let vfp = PersistedValidationData {
408
10
		relay_parent_number: 1u32,
409
10
		relay_parent_storage_root,
410
10
		..Default::default()
411
10
	};
412
10
	let parachain_inherent_data = ParachainInherentData {
413
10
		validation_data: vfp,
414
10
		relay_chain_state: relay_chain_state,
415
10
		downward_messages: Default::default(),
416
10
		horizontal_messages: Default::default(),
417
10
	};
418
10
	assert_ok!(RuntimeCall::ParachainSystem(
419
10
		cumulus_pallet_parachain_system::Call::<Runtime>::set_validation_data {
420
10
			data: parachain_inherent_data
421
10
		}
422
10
	)
423
10
	.dispatch(inherent_origin()));
424
10
}
425

            
426
6602
pub(crate) fn increase_last_relay_slot_number(amount: u64) {
427
6602
	let last_relay_slot = u64::from(AsyncBacking::slot_info().unwrap_or_default().0);
428
6602
	frame_support::storage::unhashed::put(
429
6602
		&frame_support::storage::storage_prefix(b"AsyncBacking", b"SlotInfo"),
430
6602
		&((Slot::from(last_relay_slot + amount), 0)),
431
6602
	);
432
6602
}