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
	COLLATOR_LOCK_ID, DELEGATOR_LOCK_ID,
24
};
25
use block_author::BlockAuthor as BlockAuthorMap;
26
use frame_support::{
27
	construct_runtime, parameter_types,
28
	traits::{Everything, Get, LockIdentifier, OnFinalize, OnInitialize},
29
	weights::{constants::RocksDbWeight, Weight},
30
};
31
use frame_system::pallet_prelude::BlockNumberFor;
32
use sp_consensus_slots::Slot;
33
use sp_core::H256;
34
use sp_io;
35
use sp_runtime::BuildStorage;
36
use sp_runtime::{
37
	traits::{BlakeTwo256, IdentityLookup},
38
	Perbill, Percent,
39
};
40

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

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

            
47
// Configure a mock runtime to test the pallet.
48
44558
construct_runtime!(
49
44558
	pub enum Test
50
44558
	{
51
44558
		System: frame_system,
52
44558
		Balances: pallet_balances,
53
44558
		ParachainStaking: pallet_parachain_staking,
54
44558
		BlockAuthor: block_author,
55
44558
	}
56
44558
);
57

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
593
/// fn to query the lock amount
594
25
pub(crate) fn query_lock_amount(account_id: u64, id: LockIdentifier) -> Option<Balance> {
595
25
	for lock in Balances::locks(&account_id) {
596
19
		if lock.id == id {
597
19
			return Some(lock.amount);
598
		}
599
	}
600
6
	None
601
25
}
602

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

            
702
#[frame_support::pallet]
703
pub mod block_author {
704
	use super::*;
705
	use frame_support::pallet_prelude::*;
706
	use frame_support::traits::Get;
707

            
708
	#[pallet::config]
709
	pub trait Config: frame_system::Config {}
710

            
711
3
	#[pallet::pallet]
712
	pub struct Pallet<T>(_);
713

            
714
2310
	#[pallet::storage]
715
	#[pallet::getter(fn block_author)]
716
	pub(super) type BlockAuthor<T> = StorageValue<_, AccountId, ValueQuery>;
717

            
718
	impl<T: Config> Get<AccountId> for Pallet<T> {
719
1149
		fn get() -> AccountId {
720
1149
			<BlockAuthor<T>>::get()
721
1149
		}
722
	}
723
}
724

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

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

            
735
1
		let num_blocks = roll_to_round_begin(2);
736
1
		assert_eq!(System::block_number(), 5);
737
1
		assert_eq!(num_blocks, 4);
738

            
739
1
		let num_blocks = roll_to_round_begin(3);
740
1
		assert_eq!(System::block_number(), 10);
741
1
		assert_eq!(num_blocks, 5);
742
1
	});
743
1
}
744

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

            
751
1
		let num_blocks = roll_to_round_end(1);
752
1
		assert_eq!(System::block_number(), 4);
753
1
		assert_eq!(num_blocks, 3);
754

            
755
1
		let num_blocks = roll_to_round_end(2);
756
1
		assert_eq!(System::block_number(), 9);
757
1
		assert_eq!(num_blocks, 5);
758

            
759
1
		let num_blocks = roll_to_round_end(3);
760
1
		assert_eq!(System::block_number(), 14);
761
1
		assert_eq!(num_blocks, 5);
762
1
	});
763
1
}
764

            
765
#[test]
766
#[should_panic]
767
1
fn test_assert_events_eq_fails_if_event_missing() {
768
1
	ExtBuilder::default().build().execute_with(|| {
769
1
		inject_test_events();
770
1

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

            
787
#[test]
788
#[should_panic]
789
1
fn test_assert_events_eq_fails_if_event_extra() {
790
1
	ExtBuilder::default().build().execute_with(|| {
791
1
		inject_test_events();
792
1

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

            
817
#[test]
818
#[should_panic]
819
1
fn test_assert_events_eq_fails_if_event_wrong_order() {
820
1
	ExtBuilder::default().build().execute_with(|| {
821
1
		inject_test_events();
822
1

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

            
843
#[test]
844
#[should_panic]
845
1
fn test_assert_events_eq_fails_if_event_wrong_value() {
846
1
	ExtBuilder::default().build().execute_with(|| {
847
1
		inject_test_events();
848
1

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

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

            
877
1
		assert_events_eq!(ParachainStakingEvent::Rewarded {
878
1
			account: 1,
879
1
			rewards: 100,
880
1
		});
881
1
	});
882
1
}
883

            
884
#[test]
885
1
fn test_assert_events_eq_passes_if_all_events_present_multiple() {
886
1
	ExtBuilder::default().build().execute_with(|| {
887
1
		inject_test_events();
888
1

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

            
909
#[test]
910
#[should_panic]
911
1
fn test_assert_events_emitted_fails_if_event_missing() {
912
1
	ExtBuilder::default().build().execute_with(|| {
913
1
		inject_test_events();
914
1

            
915
1
		assert_events_emitted!(ParachainStakingEvent::DelegatorExitScheduled {
916
1
			round: 2,
917
1
			delegator: 3,
918
1
			scheduled_exit: 4,
919
1
		});
920
1
	});
921
1
}
922

            
923
#[test]
924
#[should_panic]
925
1
fn test_assert_events_emitted_fails_if_event_wrong_value() {
926
1
	ExtBuilder::default().build().execute_with(|| {
927
1
		inject_test_events();
928
1

            
929
1
		assert_events_emitted!(ParachainStakingEvent::Rewarded {
930
1
			account: 1,
931
1
			rewards: 50,
932
1
		});
933
1
	});
934
1
}
935

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

            
944
1
		assert_events_emitted!(ParachainStakingEvent::Rewarded {
945
1
			account: 1,
946
1
			rewards: 100,
947
1
		});
948
1
	});
949
1
}
950

            
951
#[test]
952
1
fn test_assert_events_emitted_passes_if_all_events_present_multiple() {
953
1
	ExtBuilder::default().build().execute_with(|| {
954
1
		inject_test_events();
955
1

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

            
970
#[test]
971
#[should_panic]
972
1
fn test_assert_events_eq_match_fails_if_event_missing() {
973
1
	ExtBuilder::default().build().execute_with(|| {
974
1
		inject_test_events();
975
1

            
976
1
		assert_events_eq_match!(
977
1
			ParachainStakingEvent::CollatorChosen { .. },
978
1
			ParachainStakingEvent::NewRound { .. },
979
1
		);
980
1
	});
981
1
}
982

            
983
#[test]
984
#[should_panic]
985
1
fn test_assert_events_eq_match_fails_if_event_extra() {
986
1
	ExtBuilder::default().build().execute_with(|| {
987
1
		inject_test_events();
988
1

            
989
1
		assert_events_eq_match!(
990
1
			ParachainStakingEvent::CollatorChosen { .. },
991
1
			ParachainStakingEvent::NewRound { .. },
992
1
			ParachainStakingEvent::Rewarded { .. },
993
1
			ParachainStakingEvent::Rewarded { .. },
994
1
		);
995
1
	});
996
1
}
997

            
998
#[test]
999
#[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

            
1
		assert_events_eq_match!(
1
			ParachainStakingEvent::Rewarded { .. },
1
			ParachainStakingEvent::CollatorChosen { .. },
1
			ParachainStakingEvent::NewRound { .. },
1
		);
1
	});
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

            
1
		assert_events_eq_match!(
1
			ParachainStakingEvent::CollatorChosen { .. },
1
			ParachainStakingEvent::NewRound { .. },
1
			ParachainStakingEvent::Rewarded { rewards: 50, .. },
1
		);
1
	});
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

            
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

            
1
		assert_events_eq_match!(
1
			ParachainStakingEvent::CollatorChosen {
1
				round: 2,
1
				collator_account: 1,
1
				..
1
			},
1
			ParachainStakingEvent::NewRound {
1
				starting_block: 10,
1
				..
1
			},
1
			ParachainStakingEvent::Rewarded {
1
				account: 1,
1
				rewards: 100,
1
			},
1
		);
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

            
1
		assert_events_emitted_match!(ParachainStakingEvent::DelegatorExitScheduled {
1
			round: 2,
1
			..
1
		});
1
	});
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

            
1
		assert_events_emitted_match!(ParachainStakingEvent::Rewarded { rewards: 50, .. });
1
	});
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

            
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

            
1
		assert_events_emitted_match!(
1
			ParachainStakingEvent::CollatorChosen {
1
				total_exposed_amount: 10,
1
				..
1
			},
1
			ParachainStakingEvent::Rewarded {
1
				account: 1,
1
				rewards: 100,
1
			},
1
		);
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
}