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
//! Test utilities
18
use crate::{
19
	self as pallet_parachain_staking, InflationDistributionAccount, InflationDistributionConfig,
20
};
21
use crate::{
22
	pallet, AwardedPts, Config, Event as ParachainStakingEvent, InflationInfo, Points, Range,
23
};
24
use block_author::BlockAuthor as BlockAuthorMap;
25
use frame_support::{
26
	construct_runtime, parameter_types,
27
	traits::{fungible::InspectFreeze, Everything, Get, OnFinalize, OnInitialize, VariantCountOf},
28
	weights::{constants::RocksDbWeight, Weight},
29
};
30
use frame_system::pallet_prelude::BlockNumberFor;
31
use sp_consensus_slots::Slot;
32
use sp_core::H256;
33
use sp_io;
34
use sp_runtime::BuildStorage;
35
use sp_runtime::{
36
	traits::{BlakeTwo256, IdentityLookup},
37
	Perbill, Percent,
38
};
39

            
40
pub type AccountId = u64;
41
pub type Balance = u128;
42
pub type BlockNumber = BlockNumberFor<Test>;
43

            
44
type Block = frame_system::mocking::MockBlockU32<Test>;
45

            
46
// Configure a mock runtime to test the pallet.
47
construct_runtime!(
48
	pub enum Test
49
	{
50
		System: frame_system,
51
		Balances: pallet_balances,
52
		ParachainStaking: pallet_parachain_staking::{Pallet, Call, Storage, Event<T>, FreezeReason},
53
		BlockAuthor: block_author,
54
	}
55
);
56

            
57
parameter_types! {
58
	pub const BlockHashCount: u32 = 250;
59
	pub const MaximumBlockWeight: Weight = Weight::from_parts(1024, 1);
60
	pub const MaximumBlockLength: u32 = 2 * 1024;
61
	pub const AvailableBlockRatio: Perbill = Perbill::one();
62
	pub const SS58Prefix: u8 = 42;
63
}
64
impl frame_system::Config for Test {
65
	type BaseCallFilter = Everything;
66
	type DbWeight = RocksDbWeight;
67
	type RuntimeOrigin = RuntimeOrigin;
68
	type RuntimeTask = RuntimeTask;
69
	type Nonce = u64;
70
	type Block = Block;
71
	type RuntimeCall = RuntimeCall;
72
	type Hash = H256;
73
	type Hashing = BlakeTwo256;
74
	type AccountId = AccountId;
75
	type Lookup = IdentityLookup<Self::AccountId>;
76
	type RuntimeEvent = RuntimeEvent;
77
	type BlockHashCount = BlockHashCount;
78
	type Version = ();
79
	type PalletInfo = PalletInfo;
80
	type AccountData = pallet_balances::AccountData<Balance>;
81
	type OnNewAccount = ();
82
	type OnKilledAccount = ();
83
	type SystemWeightInfo = ();
84
	type BlockWeights = ();
85
	type BlockLength = ();
86
	type SS58Prefix = SS58Prefix;
87
	type OnSetCode = ();
88
	type MaxConsumers = frame_support::traits::ConstU32<16>;
89
	type SingleBlockMigrations = ();
90
	type MultiBlockMigrator = ();
91
	type PreInherents = ();
92
	type PostInherents = ();
93
	type PostTransactions = ();
94
	type ExtensionsWeightInfo = ();
95
}
96
parameter_types! {
97
	pub const ExistentialDeposit: u128 = 0;
98
}
99
impl pallet_balances::Config for Test {
100
	type MaxReserves = ();
101
	type ReserveIdentifier = [u8; 4];
102
	type MaxLocks = ();
103
	type Balance = Balance;
104
	type RuntimeEvent = RuntimeEvent;
105
	type DustRemoval = ();
106
	type ExistentialDeposit = ExistentialDeposit;
107
	type AccountStore = System;
108
	type WeightInfo = ();
109
	type RuntimeHoldReason = ();
110
	type FreezeIdentifier = RuntimeFreezeReason;
111
	type MaxFreezes = VariantCountOf<Self::RuntimeFreezeReason>;
112
	type RuntimeFreezeReason = RuntimeFreezeReason;
113
	type DoneSlashHandler = ();
114
}
115
impl block_author::Config for Test {}
116
const GENESIS_BLOCKS_PER_ROUND: BlockNumber = 5;
117
const GENESIS_COLLATOR_COMMISSION: Perbill = Perbill::from_percent(20);
118
const GENESIS_PARACHAIN_BOND_RESERVE_PERCENT: Percent = Percent::from_percent(30);
119
const GENESIS_NUM_SELECTED_CANDIDATES: u32 = 5;
120

            
121
pub const POINTS_PER_BLOCK: u32 = 20;
122
pub const POINTS_PER_ROUND: u32 = GENESIS_BLOCKS_PER_ROUND * POINTS_PER_BLOCK;
123

            
124
parameter_types! {
125
	pub const MinBlocksPerRound: u32 = 3;
126
	pub const MaxOfflineRounds: u32 = 2;
127
	pub const LeaveCandidatesDelay: u32 = 2;
128
	pub const CandidateBondLessDelay: u32 = 2;
129
	pub const LeaveDelegatorsDelay: u32 = 2;
130
	pub const RevokeDelegationDelay: u32 = 2;
131
	pub const DelegationBondLessDelay: u32 = 2;
132
	pub const RewardPaymentDelay: u32 = 2;
133
	pub const MinSelectedCandidates: u32 = GENESIS_NUM_SELECTED_CANDIDATES;
134
	pub const MaxTopDelegationsPerCandidate: u32 = 4;
135
	pub const MaxBottomDelegationsPerCandidate: u32 = 4;
136
	pub const MaxDelegationsPerDelegator: u32 = 4;
137
	pub const MinCandidateStk: u128 = 10;
138
	pub const MinDelegation: u128 = 3;
139
	pub const MaxCandidates: u32 = 200;
140
}
141

            
142
pub struct StakingRoundSlotProvider;
143
impl Get<Slot> for StakingRoundSlotProvider {
144
230
	fn get() -> Slot {
145
230
		let block_number: u64 = System::block_number().into();
146
230
		Slot::from(block_number)
147
230
	}
148
}
149

            
150
parameter_types! {
151
	pub const LinearInflationThreshold: Option<Balance> = Some(1_200_000_000);
152
}
153

            
154
impl Config for Test {
155
	type Currency = Balances;
156
	type RuntimeFreezeReason = RuntimeFreezeReason;
157
	type MonetaryGovernanceOrigin = frame_system::EnsureRoot<AccountId>;
158
	type MinBlocksPerRound = MinBlocksPerRound;
159
	type MaxOfflineRounds = MaxOfflineRounds;
160
	type LeaveCandidatesDelay = LeaveCandidatesDelay;
161
	type CandidateBondLessDelay = CandidateBondLessDelay;
162
	type LeaveDelegatorsDelay = LeaveDelegatorsDelay;
163
	type RevokeDelegationDelay = RevokeDelegationDelay;
164
	type DelegationBondLessDelay = DelegationBondLessDelay;
165
	type RewardPaymentDelay = RewardPaymentDelay;
166
	type MinSelectedCandidates = MinSelectedCandidates;
167
	type MaxTopDelegationsPerCandidate = MaxTopDelegationsPerCandidate;
168
	type MaxBottomDelegationsPerCandidate = MaxBottomDelegationsPerCandidate;
169
	type MaxDelegationsPerDelegator = MaxDelegationsPerDelegator;
170
	type MinCandidateStk = MinCandidateStk;
171
	type MinDelegation = MinDelegation;
172
	type BlockAuthor = BlockAuthor;
173
	type OnCollatorPayout = ();
174
	type PayoutCollatorReward = ();
175
	type OnInactiveCollator = ();
176
	type OnNewRound = ();
177
	type SlotProvider = StakingRoundSlotProvider;
178
	type WeightInfo = ();
179
	type MaxCandidates = MaxCandidates;
180
	type SlotDuration = frame_support::traits::ConstU64<6_000>;
181
	type BlockTime = frame_support::traits::ConstU64<6_000>;
182
	type LinearInflationThreshold = LinearInflationThreshold;
183
}
184

            
185
pub(crate) struct ExtBuilder {
186
	// endowed accounts with balances
187
	balances: Vec<(AccountId, Balance)>,
188
	// [collator, amount]
189
	collators: Vec<(AccountId, Balance)>,
190
	// [delegator, collator, delegation_amount, auto_compound_percent]
191
	delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
192
	// inflation config
193
	inflation: InflationInfo<Balance>,
194
}
195

            
196
impl Default for ExtBuilder {
197
251
	fn default() -> ExtBuilder {
198
251
		ExtBuilder {
199
251
			balances: vec![],
200
251
			delegations: vec![],
201
251
			collators: vec![],
202
251
			inflation: InflationInfo {
203
251
				expect: Range {
204
251
					min: 700,
205
251
					ideal: 700,
206
251
					max: 700,
207
251
				},
208
251
				// not used
209
251
				annual: Range {
210
251
					min: Perbill::from_percent(50),
211
251
					ideal: Perbill::from_percent(50),
212
251
					max: Perbill::from_percent(50),
213
251
				},
214
251
				// unrealistically high parameterization, only for testing
215
251
				round: Range {
216
251
					min: Perbill::from_percent(5),
217
251
					ideal: Perbill::from_percent(5),
218
251
					max: Perbill::from_percent(5),
219
251
				},
220
251
			},
221
251
		}
222
251
	}
223
}
224

            
225
impl ExtBuilder {
226
191
	pub(crate) fn with_balances(mut self, balances: Vec<(AccountId, Balance)>) -> Self {
227
191
		self.balances = balances;
228
191
		self
229
191
	}
230

            
231
177
	pub(crate) fn with_candidates(mut self, collators: Vec<(AccountId, Balance)>) -> Self {
232
177
		self.collators = collators;
233
177
		self
234
177
	}
235

            
236
103
	pub(crate) fn with_delegations(
237
103
		mut self,
238
103
		delegations: Vec<(AccountId, AccountId, Balance)>,
239
103
	) -> Self {
240
103
		self.delegations = delegations
241
103
			.into_iter()
242
8946
			.map(|d| (d.0, d.1, d.2, Percent::zero()))
243
103
			.collect();
244
103
		self
245
103
	}
246

            
247
2
	pub(crate) fn with_auto_compounding_delegations(
248
2
		mut self,
249
2
		delegations: Vec<(AccountId, AccountId, Balance, Percent)>,
250
2
	) -> Self {
251
2
		self.delegations = delegations;
252
2
		self
253
2
	}
254

            
255
	#[allow(dead_code)]
256
	pub(crate) fn with_inflation(mut self, inflation: InflationInfo<Balance>) -> Self {
257
		self.inflation = inflation;
258
		self
259
	}
260

            
261
251
	pub(crate) fn build(self) -> sp_io::TestExternalities {
262
251
		let mut t = frame_system::GenesisConfig::<Test>::default()
263
251
			.build_storage()
264
251
			.expect("Frame system builds valid default genesis config");
265

            
266
251
		pallet_balances::GenesisConfig::<Test> {
267
251
			balances: self.balances,
268
251
			dev_accounts: None,
269
251
		}
270
251
		.assimilate_storage(&mut t)
271
251
		.expect("Pallet balances storage can be assimilated");
272
251
		pallet_parachain_staking::GenesisConfig::<Test> {
273
251
			candidates: self.collators,
274
251
			delegations: self.delegations,
275
251
			inflation_config: self.inflation,
276
251
			collator_commission: GENESIS_COLLATOR_COMMISSION,
277
251
			parachain_bond_reserve_percent: GENESIS_PARACHAIN_BOND_RESERVE_PERCENT,
278
251
			blocks_per_round: GENESIS_BLOCKS_PER_ROUND,
279
251
			num_selected_candidates: GENESIS_NUM_SELECTED_CANDIDATES,
280
251
		}
281
251
		.assimilate_storage(&mut t)
282
251
		.expect("Parachain Staking's storage can be assimilated");
283

            
284
251
		let mut ext = sp_io::TestExternalities::new(t);
285
251
		ext.execute_with(|| System::set_block_number(1));
286
251
		ext
287
251
	}
288
}
289

            
290
/// Rolls forward one block. Returns the new block number.
291
1149
fn roll_one_block() -> BlockNumber {
292
1149
	ParachainStaking::on_finalize(System::block_number());
293
1149
	Balances::on_finalize(System::block_number());
294
1149
	System::on_finalize(System::block_number());
295
1149
	System::set_block_number(System::block_number() + 1);
296
1149
	System::reset_events();
297
1149
	System::on_initialize(System::block_number());
298
1149
	Balances::on_initialize(System::block_number());
299
1149
	ParachainStaking::on_initialize(System::block_number());
300
1149
	System::block_number()
301
1149
}
302

            
303
/// Rolls to the desired block. Returns the number of blocks played.
304
132
pub(crate) fn roll_to(n: BlockNumber) -> BlockNumber {
305
132
	let mut num_blocks = 0;
306
132
	let mut block = System::block_number();
307
1172
	while block < n {
308
1040
		block = roll_one_block();
309
1040
		num_blocks += 1;
310
1040
	}
311
132
	num_blocks
312
132
}
313

            
314
/// Rolls desired number of blocks. Returns the final block.
315
63
pub(crate) fn roll_blocks(num_blocks: u32) -> BlockNumber {
316
63
	let mut block = System::block_number();
317
109
	for _ in 0..num_blocks {
318
109
		block = roll_one_block();
319
109
	}
320
63
	block
321
63
}
322

            
323
/// Rolls block-by-block to the beginning of the specified round.
324
/// This will complete the block in which the round change occurs.
325
/// Returns the number of blocks played.
326
73
pub(crate) fn roll_to_round_begin(round: BlockNumber) -> BlockNumber {
327
73
	let r = ParachainStaking::round();
328

            
329
	// Return 0 if target round has already passed
330
73
	if round < r.current + 1 {
331
3
		return 0;
332
70
	}
333

            
334
	// Calculate target block by adding round length for each round difference
335
70
	let target = r.first + (round - r.current) * r.length;
336
70
	roll_to(target)
337
73
}
338

            
339
/// Rolls block-by-block to the end of the specified round.
340
/// The block following will be the one in which the specified round change occurs.
341
12
pub(crate) fn roll_to_round_end(round: BlockNumber) -> BlockNumber {
342
12
	let r = ParachainStaking::round();
343

            
344
	// Return 0 if target round has already passed
345
12
	if round < r.current {
346
1
		return 0;
347
11
	}
348

            
349
	// Calculate target block by adding round length for each round difference
350
11
	let target = r.first + (round - r.current + 1) * r.length - 1;
351
11
	roll_to(target)
352
12
}
353

            
354
34
pub(crate) fn inflation_configs(
355
34
	pbr: AccountId,
356
34
	pbr_percent: u8,
357
34
	treasury: AccountId,
358
34
	treasury_percent: u8,
359
34
) -> InflationDistributionConfig<AccountId> {
360
34
	[
361
34
		InflationDistributionAccount {
362
34
			account: pbr,
363
34
			percent: Percent::from_percent(pbr_percent),
364
34
		},
365
34
		InflationDistributionAccount {
366
34
			account: treasury,
367
34
			percent: Percent::from_percent(treasury_percent),
368
34
		},
369
34
	]
370
34
	.into()
371
34
}
372

            
373
201
pub(crate) fn events() -> Vec<pallet::Event<Test>> {
374
201
	System::events()
375
201
		.into_iter()
376
201
		.map(|r| r.event)
377
713
		.filter_map(|e| {
378
713
			if let RuntimeEvent::ParachainStaking(inner) = e {
379
547
				Some(inner)
380
			} else {
381
166
				None
382
			}
383
713
		})
384
201
		.collect::<Vec<_>>()
385
201
}
386

            
387
/// Asserts that some events were never emitted.
388
///
389
/// # Example
390
///
391
/// ```
392
/// assert_no_events!();
393
/// ```
394
#[macro_export]
395
macro_rules! assert_no_events {
396
	() => {
397
		similar_asserts::assert_eq!(Vec::<Event<Test>>::new(), crate::mock::events())
398
	};
399
}
400

            
401
/// Asserts that emitted events match exactly the given input.
402
///
403
/// # Example
404
///
405
/// ```
406
/// assert_events_eq!(
407
///		Foo { x: 1, y: 2 },
408
///		Bar { value: "test" },
409
///		Baz { a: 10, b: 20 },
410
/// );
411
/// ```
412
#[macro_export]
413
macro_rules! assert_events_eq {
414
	($event:expr) => {
415
		similar_asserts::assert_eq!(vec![$event], crate::mock::events());
416
	};
417
	($($events:expr,)+) => {
418
		similar_asserts::assert_eq!(vec![$($events,)+], crate::mock::events());
419
	};
420
}
421

            
422
/// Asserts that some emitted events match the given input.
423
///
424
/// # Example
425
///
426
/// ```
427
/// assert_events_emitted!(
428
///		Foo { x: 1, y: 2 },
429
///		Baz { a: 10, b: 20 },
430
/// );
431
/// ```
432
#[macro_export]
433
macro_rules! assert_events_emitted {
434
	($event:expr) => {
435
		[$event].into_iter().for_each(|e| assert!(
436
90
			crate::mock::events().into_iter().find(|x| x == &e).is_some(),
437
2
			"Event {:?} was not found in events: \n{:#?}",
438
			e,
439
2
			crate::mock::events()
440
		));
441
	};
442
	($($events:expr,)+) => {
443
		[$($events,)+].into_iter().for_each(|e| assert!(
444
6
			crate::mock::events().into_iter().find(|x| x == &e).is_some(),
445
			"Event {:?} was not found in events: \n{:#?}",
446
			e,
447
			crate::mock::events()
448
		));
449
	};
450
}
451

            
452
/// Asserts that some events were never emitted.
453
///
454
/// # Example
455
///
456
/// ```
457
/// assert_events_not_emitted!(
458
///		Foo { x: 1, y: 2 },
459
///		Bar { value: "test" },
460
/// );
461
/// ```
462
#[macro_export]
463
macro_rules! assert_events_not_emitted {
464
	($event:expr) => {
465
		[$event].into_iter().for_each(|e| assert!(
466
			crate::mock::events().into_iter().find(|x| x != &e).is_some(),
467
			"Event {:?} was unexpectedly found in events: \n{:#?}",
468
			e,
469
			crate::mock::events()
470
		));
471
	};
472
	($($events:expr,)+) => {
473
		[$($events,)+].into_iter().for_each(|e| assert!(
474
			crate::mock::events().into_iter().find(|x| x != &e).is_some(),
475
			"Event {:?} was unexpectedly found in events: \n{:#?}",
476
			e,
477
			crate::mock::events()
478
		));
479
	};
480
}
481

            
482
/// Asserts that the emitted events are exactly equal to the input patterns.
483
///
484
/// # Example
485
///
486
/// ```
487
/// assert_events_eq_match!(
488
///		Foo { x: 1, .. },
489
///		Bar { .. },
490
///		Baz { a: 10, b: 20 },
491
/// );
492
/// ```
493
#[macro_export]
494
macro_rules! assert_events_eq_match {
495
	($index:expr;) => {
496
		assert_eq!(
497
			$index,
498
			crate::mock::events().len(),
499
			"Found {} extra event(s): \n{:#?}",
500
			crate::mock::events().len()-$index,
501
			crate::mock::events()
502
		);
503
	};
504
	($index:expr; $event:pat_param, $($events:pat_param,)*) => {
505
		assert!(
506
			matches!(
507
				crate::mock::events().get($index),
508
				Some($event),
509
			),
510
			"Event {:#?} was not found at index {}: \n{:#?}",
511
			stringify!($event),
512
			$index,
513
			crate::mock::events()
514
		);
515
		assert_events_eq_match!($index+1; $($events,)*);
516
	};
517
	($event:pat_param) => {
518
		assert_events_eq_match!(0; $event,);
519
	};
520
	($($events:pat_param,)+) => {
521
		assert_events_eq_match!(0; $($events,)+);
522
	};
523
}
524

            
525
/// Asserts that some emitted events match the input patterns.
526
///
527
/// # Example
528
///
529
/// ```
530
/// assert_events_emitted_match!(
531
///		Foo { x: 1, .. },
532
///		Baz { a: 10, b: 20 },
533
/// );
534
/// ```
535
#[macro_export]
536
macro_rules! assert_events_emitted_match {
537
	($event:pat_param) => {
538
		assert!(
539
59
			crate::mock::events().into_iter().any(|x| matches!(x, $event)),
540
			"Event {:?} was not found in events: \n{:#?}",
541
			stringify!($event),
542
			crate::mock::events()
543
		);
544
	};
545
	($event:pat_param, $($events:pat_param,)+) => {
546
		assert_events_emitted_match!($event);
547
		$(
548
			assert_events_emitted_match!($events);
549
		)+
550
	};
551
}
552

            
553
/// Asserts that the input patterns match none of the emitted events.
554
///
555
/// # Example
556
///
557
/// ```
558
/// assert_events_not_emitted_match!(
559
///		Foo { x: 1, .. },
560
///		Baz { a: 10, b: 20 },
561
/// );
562
/// ```
563
#[macro_export]
564
macro_rules! assert_events_not_emitted_match {
565
	($event:pat_param) => {
566
		assert!(
567
			crate::mock::events().into_iter().any(|x| !matches!(x, $event)),
568
			"Event {:?} was unexpectedly found in events: \n{:#?}",
569
			stringify!($event),
570
			crate::mock::events()
571
		);
572
	};
573
	($event:pat_param, $($events:pat_param,)+) => {
574
		assert_events_not_emitted_match!($event);
575
		$(
576
			assert_events_not_emitted_match!($events);
577
		)+
578
	};
579
}
580

            
581
// Same storage changes as ParachainStaking::on_finalize
582
65
pub(crate) fn set_author(round: BlockNumber, acc: u64, pts: u32) {
583
65
	<Points<Test>>::mutate(round, |p| *p += pts);
584
65
	<AwardedPts<Test>>::mutate(round, acc, |p| *p += pts);
585
65
}
586

            
587
// Allows to change the block author (default is always 0)
588
6
pub(crate) fn set_block_author(acc: u64) {
589
6
	<BlockAuthorMap<Test>>::set(acc);
590
6
}
591

            
592
/// fn to query the freeze amount for a specific reason
593
27
pub(crate) fn query_freeze_amount(account_id: u64, reason: &RuntimeFreezeReason) -> Balance {
594
27
	Balances::balance_frozen(reason, &account_id)
595
27
}
596

            
597
#[test]
598
1
fn geneses() {
599
1
	ExtBuilder::default()
600
1
		.with_balances(vec![
601
1
			(1, 1000),
602
1
			(2, 300),
603
1
			(3, 100),
604
1
			(4, 100),
605
1
			(5, 100),
606
1
			(6, 100),
607
1
			(7, 100),
608
1
			(8, 9),
609
1
			(9, 4),
610
1
		])
611
1
		.with_candidates(vec![(1, 500), (2, 200)])
612
1
		.with_delegations(vec![(3, 1, 100), (4, 1, 100), (5, 2, 100), (6, 2, 100)])
613
1
		.build()
614
1
		.execute_with(|| {
615
1
			assert!(System::events().is_empty());
616
			// collators
617
1
			assert_eq!(
618
1
				ParachainStaking::get_collator_stakable_free_balance(&1),
619
				500
620
			);
621
1
			let collator_freeze_reason: RuntimeFreezeReason =
622
1
				pallet_parachain_staking::pallet::FreezeReason::StakingCollator.into();
623
1
			let delegator_freeze_reason: RuntimeFreezeReason =
624
1
				pallet_parachain_staking::pallet::FreezeReason::StakingDelegator.into();
625
1
			assert_eq!(query_freeze_amount(1, &collator_freeze_reason), 500);
626
1
			assert!(ParachainStaking::is_candidate(&1));
627
1
			assert_eq!(query_freeze_amount(2, &collator_freeze_reason), 200);
628
1
			assert_eq!(
629
1
				ParachainStaking::get_collator_stakable_free_balance(&2),
630
				100
631
			);
632
1
			assert!(ParachainStaking::is_candidate(&2));
633
			// delegators
634
5
			for x in 3..7 {
635
4
				assert!(ParachainStaking::is_delegator(&x));
636
4
				assert_eq!(ParachainStaking::get_delegator_stakable_balance(&x), 0);
637
4
				assert_eq!(query_freeze_amount(x, &delegator_freeze_reason), 100);
638
			}
639
			// uninvolved
640
4
			for x in 7..10 {
641
3
				assert!(!ParachainStaking::is_delegator(&x));
642
			}
643
			// no delegator staking locks
644
1
			assert_eq!(query_freeze_amount(7, &delegator_freeze_reason), 0);
645
1
			assert_eq!(ParachainStaking::get_delegator_stakable_balance(&7), 100);
646
1
			assert_eq!(query_freeze_amount(8, &delegator_freeze_reason), 0);
647
1
			assert_eq!(ParachainStaking::get_delegator_stakable_balance(&8), 9);
648
1
			assert_eq!(query_freeze_amount(9, &delegator_freeze_reason), 0);
649
1
			assert_eq!(ParachainStaking::get_delegator_stakable_balance(&9), 4);
650
			// no collator staking locks
651
1
			assert_eq!(
652
1
				ParachainStaking::get_collator_stakable_free_balance(&7),
653
				100
654
			);
655
1
			assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&8), 9);
656
1
			assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&9), 4);
657
1
		});
658
1
	ExtBuilder::default()
659
1
		.with_balances(vec![
660
1
			(1, 100),
661
1
			(2, 100),
662
1
			(3, 100),
663
1
			(4, 100),
664
1
			(5, 100),
665
1
			(6, 100),
666
1
			(7, 100),
667
1
			(8, 100),
668
1
			(9, 100),
669
1
			(10, 100),
670
1
		])
671
1
		.with_candidates(vec![(1, 20), (2, 20), (3, 20), (4, 20), (5, 10)])
672
1
		.with_delegations(vec![
673
1
			(6, 1, 10),
674
1
			(7, 1, 10),
675
1
			(8, 2, 10),
676
1
			(9, 2, 10),
677
1
			(10, 1, 10),
678
1
		])
679
1
		.build()
680
1
		.execute_with(|| {
681
			// Define freeze reasons once
682
1
			let collator_freeze_reason: RuntimeFreezeReason =
683
1
				pallet_parachain_staking::pallet::FreezeReason::StakingCollator.into();
684
1
			let delegator_freeze_reason: RuntimeFreezeReason =
685
1
				pallet_parachain_staking::pallet::FreezeReason::StakingDelegator.into();
686
1
			assert!(System::events().is_empty());
687
			// collators
688
5
			for x in 1..5 {
689
4
				assert!(ParachainStaking::is_candidate(&x));
690
4
				assert_eq!(query_freeze_amount(x, &collator_freeze_reason), 20);
691
4
				assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&x), 80);
692
			}
693
1
			assert!(ParachainStaking::is_candidate(&5));
694
1
			assert_eq!(query_freeze_amount(5, &collator_freeze_reason), 10);
695
1
			assert_eq!(ParachainStaking::get_collator_stakable_free_balance(&5), 90);
696
			// delegators
697
6
			for x in 6..11 {
698
5
				assert!(ParachainStaking::is_delegator(&x));
699
5
				assert_eq!(query_freeze_amount(x, &delegator_freeze_reason), 10);
700
5
				assert_eq!(ParachainStaking::get_delegator_stakable_balance(&x), 90);
701
			}
702
1
		});
703
1
}
704

            
705
#[frame_support::pallet]
706
pub mod block_author {
707
	use super::*;
708
	use frame_support::pallet_prelude::*;
709
	use frame_support::traits::Get;
710

            
711
	#[pallet::config]
712
	pub trait Config: frame_system::Config {}
713

            
714
	#[pallet::pallet]
715
	pub struct Pallet<T>(_);
716

            
717
	#[pallet::storage]
718
	#[pallet::getter(fn block_author)]
719
	pub(super) type BlockAuthor<T> = StorageValue<_, AccountId, ValueQuery>;
720

            
721
	impl<T: Config> Get<AccountId> for Pallet<T> {
722
1149
		fn get() -> AccountId {
723
1149
			<BlockAuthor<T>>::get()
724
1149
		}
725
	}
726
}
727

            
728
#[test]
729
1
fn roll_to_round_begin_works() {
730
1
	ExtBuilder::default().build().execute_with(|| {
731
		// these tests assume blocks-per-round of 5, as established by GENESIS_BLOCKS_PER_ROUND
732
1
		assert_eq!(System::block_number(), 1); // we start on block 1
733

            
734
1
		let num_blocks = roll_to_round_begin(1);
735
1
		assert_eq!(System::block_number(), 1); // no-op, we're already on this round
736
1
		assert_eq!(num_blocks, 0);
737

            
738
1
		let num_blocks = roll_to_round_begin(2);
739
1
		assert_eq!(System::block_number(), 5);
740
1
		assert_eq!(num_blocks, 4);
741

            
742
1
		let num_blocks = roll_to_round_begin(3);
743
1
		assert_eq!(System::block_number(), 10);
744
1
		assert_eq!(num_blocks, 5);
745
1
	});
746
1
}
747

            
748
#[test]
749
1
fn roll_to_round_end_works() {
750
1
	ExtBuilder::default().build().execute_with(|| {
751
		// these tests assume blocks-per-round of 5, as established by GENESIS_BLOCKS_PER_ROUND
752
1
		assert_eq!(System::block_number(), 1); // we start on block 1
753

            
754
1
		let num_blocks = roll_to_round_end(1);
755
1
		assert_eq!(System::block_number(), 4);
756
1
		assert_eq!(num_blocks, 3);
757

            
758
1
		let num_blocks = roll_to_round_end(2);
759
1
		assert_eq!(System::block_number(), 9);
760
1
		assert_eq!(num_blocks, 5);
761

            
762
1
		let num_blocks = roll_to_round_end(3);
763
1
		assert_eq!(System::block_number(), 14);
764
1
		assert_eq!(num_blocks, 5);
765
1
	});
766
1
}
767

            
768
#[test]
769
#[should_panic]
770
1
fn test_assert_events_eq_fails_if_event_missing() {
771
1
	ExtBuilder::default().build().execute_with(|| {
772
1
		inject_test_events();
773

            
774
1
		assert_events_eq!(
775
1
			ParachainStakingEvent::CollatorChosen {
776
1
				round: 2,
777
1
				collator_account: 1,
778
1
				total_exposed_amount: 10,
779
1
			},
780
1
			ParachainStakingEvent::NewRound {
781
1
				starting_block: 10,
782
1
				round: 2,
783
1
				selected_collators_number: 1,
784
1
				total_balance: 10,
785
1
			},
786
		);
787
1
	});
788
1
}
789

            
790
#[test]
791
#[should_panic]
792
1
fn test_assert_events_eq_fails_if_event_extra() {
793
1
	ExtBuilder::default().build().execute_with(|| {
794
1
		inject_test_events();
795

            
796
1
		assert_events_eq!(
797
1
			ParachainStakingEvent::CollatorChosen {
798
1
				round: 2,
799
1
				collator_account: 1,
800
1
				total_exposed_amount: 10,
801
1
			},
802
1
			ParachainStakingEvent::NewRound {
803
1
				starting_block: 10,
804
1
				round: 2,
805
1
				selected_collators_number: 1,
806
1
				total_balance: 10,
807
1
			},
808
1
			ParachainStakingEvent::Rewarded {
809
1
				account: 1,
810
1
				rewards: 100,
811
1
			},
812
1
			ParachainStakingEvent::Rewarded {
813
1
				account: 1,
814
1
				rewards: 200,
815
1
			},
816
		);
817
1
	});
818
1
}
819

            
820
#[test]
821
#[should_panic]
822
1
fn test_assert_events_eq_fails_if_event_wrong_order() {
823
1
	ExtBuilder::default().build().execute_with(|| {
824
1
		inject_test_events();
825

            
826
1
		assert_events_eq!(
827
1
			ParachainStakingEvent::Rewarded {
828
1
				account: 1,
829
1
				rewards: 100,
830
1
			},
831
1
			ParachainStakingEvent::CollatorChosen {
832
1
				round: 2,
833
1
				collator_account: 1,
834
1
				total_exposed_amount: 10,
835
1
			},
836
1
			ParachainStakingEvent::NewRound {
837
1
				starting_block: 10,
838
1
				round: 2,
839
1
				selected_collators_number: 1,
840
1
				total_balance: 10,
841
1
			},
842
		);
843
1
	});
844
1
}
845

            
846
#[test]
847
#[should_panic]
848
1
fn test_assert_events_eq_fails_if_event_wrong_value() {
849
1
	ExtBuilder::default().build().execute_with(|| {
850
1
		inject_test_events();
851

            
852
1
		assert_events_eq!(
853
1
			ParachainStakingEvent::CollatorChosen {
854
1
				round: 2,
855
1
				collator_account: 1,
856
1
				total_exposed_amount: 10,
857
1
			},
858
1
			ParachainStakingEvent::NewRound {
859
1
				starting_block: 10,
860
1
				round: 2,
861
1
				selected_collators_number: 1,
862
1
				total_balance: 10,
863
1
			},
864
1
			ParachainStakingEvent::Rewarded {
865
1
				account: 1,
866
1
				rewards: 50,
867
1
			},
868
		);
869
1
	});
870
1
}
871

            
872
#[test]
873
1
fn test_assert_events_eq_passes_if_all_events_present_single() {
874
1
	ExtBuilder::default().build().execute_with(|| {
875
1
		System::deposit_event(ParachainStakingEvent::Rewarded {
876
1
			account: 1,
877
1
			rewards: 100,
878
1
		});
879

            
880
1
		assert_events_eq!(ParachainStakingEvent::Rewarded {
881
1
			account: 1,
882
1
			rewards: 100,
883
1
		});
884
1
	});
885
1
}
886

            
887
#[test]
888
1
fn test_assert_events_eq_passes_if_all_events_present_multiple() {
889
1
	ExtBuilder::default().build().execute_with(|| {
890
1
		inject_test_events();
891

            
892
1
		assert_events_eq!(
893
1
			ParachainStakingEvent::CollatorChosen {
894
1
				round: 2,
895
1
				collator_account: 1,
896
1
				total_exposed_amount: 10,
897
1
			},
898
1
			ParachainStakingEvent::NewRound {
899
1
				starting_block: 10,
900
1
				round: 2,
901
1
				selected_collators_number: 1,
902
1
				total_balance: 10,
903
1
			},
904
1
			ParachainStakingEvent::Rewarded {
905
1
				account: 1,
906
1
				rewards: 100,
907
1
			},
908
		);
909
1
	});
910
1
}
911

            
912
#[test]
913
#[should_panic]
914
1
fn test_assert_events_emitted_fails_if_event_missing() {
915
1
	ExtBuilder::default().build().execute_with(|| {
916
1
		inject_test_events();
917

            
918
1
		assert_events_emitted!(ParachainStakingEvent::DelegatorExitScheduled {
919
1
			round: 2,
920
1
			delegator: 3,
921
1
			scheduled_exit: 4,
922
1
		});
923
1
	});
924
1
}
925

            
926
#[test]
927
#[should_panic]
928
1
fn test_assert_events_emitted_fails_if_event_wrong_value() {
929
1
	ExtBuilder::default().build().execute_with(|| {
930
1
		inject_test_events();
931

            
932
1
		assert_events_emitted!(ParachainStakingEvent::Rewarded {
933
1
			account: 1,
934
1
			rewards: 50,
935
1
		});
936
1
	});
937
1
}
938

            
939
#[test]
940
1
fn test_assert_events_emitted_passes_if_all_events_present_single() {
941
1
	ExtBuilder::default().build().execute_with(|| {
942
1
		System::deposit_event(ParachainStakingEvent::Rewarded {
943
1
			account: 1,
944
1
			rewards: 100,
945
1
		});
946

            
947
1
		assert_events_emitted!(ParachainStakingEvent::Rewarded {
948
1
			account: 1,
949
1
			rewards: 100,
950
1
		});
951
1
	});
952
1
}
953

            
954
#[test]
955
1
fn test_assert_events_emitted_passes_if_all_events_present_multiple() {
956
1
	ExtBuilder::default().build().execute_with(|| {
957
1
		inject_test_events();
958

            
959
1
		assert_events_emitted!(
960
1
			ParachainStakingEvent::CollatorChosen {
961
1
				round: 2,
962
1
				collator_account: 1,
963
1
				total_exposed_amount: 10,
964
1
			},
965
1
			ParachainStakingEvent::Rewarded {
966
1
				account: 1,
967
1
				rewards: 100,
968
1
			},
969
		);
970
1
	});
971
1
}
972

            
973
#[test]
974
#[should_panic]
975
1
fn test_assert_events_eq_match_fails_if_event_missing() {
976
1
	ExtBuilder::default().build().execute_with(|| {
977
1
		inject_test_events();
978

            
979
1
		assert_events_eq_match!(
980
			ParachainStakingEvent::CollatorChosen { .. },
981
			ParachainStakingEvent::NewRound { .. },
982
		);
983
	});
984
1
}
985

            
986
#[test]
987
#[should_panic]
988
1
fn test_assert_events_eq_match_fails_if_event_extra() {
989
1
	ExtBuilder::default().build().execute_with(|| {
990
1
		inject_test_events();
991

            
992
1
		assert_events_eq_match!(
993
			ParachainStakingEvent::CollatorChosen { .. },
994
			ParachainStakingEvent::NewRound { .. },
995
			ParachainStakingEvent::Rewarded { .. },
996
			ParachainStakingEvent::Rewarded { .. },
997
		);
998
	});
999
1
}
#[test]
#[should_panic]
1
fn test_assert_events_eq_match_fails_if_event_wrong_order() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_eq_match!(
			ParachainStakingEvent::Rewarded { .. },
			ParachainStakingEvent::CollatorChosen { .. },
			ParachainStakingEvent::NewRound { .. },
		);
	});
1
}
#[test]
#[should_panic]
1
fn test_assert_events_eq_match_fails_if_event_wrong_value() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_eq_match!(
			ParachainStakingEvent::CollatorChosen { .. },
			ParachainStakingEvent::NewRound { .. },
			ParachainStakingEvent::Rewarded { rewards: 50, .. },
		);
	});
1
}
#[test]
1
fn test_assert_events_eq_match_passes_if_all_events_present_single() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		System::deposit_event(ParachainStakingEvent::Rewarded {
1
			account: 1,
1
			rewards: 100,
1
		});
1
		assert_events_eq_match!(ParachainStakingEvent::Rewarded { account: 1, .. });
1
	});
1
}
#[test]
1
fn test_assert_events_eq_match_passes_if_all_events_present_multiple() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_eq_match!(
			ParachainStakingEvent::CollatorChosen {
				round: 2,
				collator_account: 1,
				..
			},
			ParachainStakingEvent::NewRound {
				starting_block: 10,
				..
			},
			ParachainStakingEvent::Rewarded {
				account: 1,
				rewards: 100,
			},
		);
1
	});
1
}
#[test]
#[should_panic]
1
fn test_assert_events_emitted_match_fails_if_event_missing() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_emitted_match!(ParachainStakingEvent::DelegatorExitScheduled {
			round: 2,
			..
		});
	});
1
}
#[test]
#[should_panic]
1
fn test_assert_events_emitted_match_fails_if_event_wrong_value() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_emitted_match!(ParachainStakingEvent::Rewarded { rewards: 50, .. });
	});
1
}
#[test]
1
fn test_assert_events_emitted_match_passes_if_all_events_present_single() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		System::deposit_event(ParachainStakingEvent::Rewarded {
1
			account: 1,
1
			rewards: 100,
1
		});
1
		assert_events_emitted_match!(ParachainStakingEvent::Rewarded { rewards: 100, .. });
1
	});
1
}
#[test]
1
fn test_assert_events_emitted_match_passes_if_all_events_present_multiple() {
1
	ExtBuilder::default().build().execute_with(|| {
1
		inject_test_events();
1
		assert_events_emitted_match!(
			ParachainStakingEvent::CollatorChosen {
				total_exposed_amount: 10,
				..
			},
			ParachainStakingEvent::Rewarded {
				account: 1,
				rewards: 100,
			},
		);
1
	});
1
}
16
fn inject_test_events() {
16
	[
16
		ParachainStakingEvent::CollatorChosen {
16
			round: 2,
16
			collator_account: 1,
16
			total_exposed_amount: 10,
16
		},
16
		ParachainStakingEvent::NewRound {
16
			starting_block: 10,
16
			round: 2,
16
			selected_collators_number: 1,
16
			total_balance: 10,
16
		},
16
		ParachainStakingEvent::Rewarded {
16
			account: 1,
16
			rewards: 100,
16
		},
16
	]
16
	.into_iter()
16
	.for_each(System::deposit_event);
16
}