-
Notifications
You must be signed in to change notification settings - Fork 49
/
lib.rs
2403 lines (2114 loc) · 82.8 KB
/
lib.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! # Staking Module
//!
//! The Staking module is used to manage funds at stake by network maintainers.
//!
//! - [`staking::Trait`](./trait.Trait.html)
//! - [`Call`](./enum.Call.html)
//! - [`Module`](./struct.Module.html)
//!
//! ## Overview
//!
//! The Staking module is the means by which a set of network maintainers (known as _authorities_
//! in some contexts and _validators_ in others) are chosen based upon those who voluntarily place
//! funds under deposit. Under deposit, those funds are rewarded under normal operation but are
//! held at pain of _slash_ (expropriation) should the staked maintainer be found not to be
//! discharging its duties properly.
//!
//! ### Terminology
//! <!-- Original author of paragraph: @gavofyork -->
//!
//! - Staking: The process of locking up funds for some time, placing them at risk of slashing
//! (loss) in order to become a rewarded maintainer of the network.
//! - Validating: The process of running a node to actively maintain the network, either by
//! producing blocks or guaranteeing finality of the chain.
//! - Nominating: The process of placing staked funds behind one or more validators in order to
//! share in any reward, and punishment, they take.
//! - Stash account: The account holding an owner's funds used for staking.
//! - Controller account: The account that controls an owner's funds for staking.
//! - Era: A (whole) number of sessions, which is the period that the validator set (and each
//! validator's active nominator set) is recalculated and where rewards are paid out.
//! - Slash: The punishment of a staker by reducing its funds.
//!
//! ### Goals
//! <!-- Original author of paragraph: @gavofyork -->
//!
//! The staking system in Substrate NPoS is designed to make the following possible:
//!
//! - Stake funds that are controlled by a cold wallet.
//! - Withdraw some, or deposit more, funds without interrupting the role of an entity.
//! - Switch between roles (nominator, validator, idle) with minimal overhead.
//!
//! ### Scenarios
//!
//! #### Staking
//!
//! Almost any interaction with the Staking module requires a process of _**bonding**_ (also known
//! as being a _staker_). To become *bonded*, a fund-holding account known as the _stash account_,
//! which holds some or all of the funds that become frozen in place as part of the staking process,
//! is paired with an active **controller** account, which issues instructions on how they shall be
//! used.
//!
//! An account pair can become bonded using the [`bond`](./enum.Call.html#variant.bond) call.
//!
//! Stash accounts can change their associated controller using the
//! [`set_controller`](./enum.Call.html#variant.set_controller) call.
//!
//! There are three possible roles that any staked account pair can be in: `Validator`, `Nominator`
//! and `Idle` (defined in [`StakerStatus`](./enum.StakerStatus.html)). There are three
//! corresponding instructions to change between roles, namely:
//! [`validate`](./enum.Call.html#variant.validate), [`nominate`](./enum.Call.html#variant.nominate),
//! and [`chill`](./enum.Call.html#variant.chill).
//!
//! #### Validating
//!
//! A **validator** takes the role of either validating blocks or ensuring their finality,
//! maintaining the veracity of the network. A validator should avoid both any sort of malicious
//! misbehavior and going offline. Bonded accounts that state interest in being a validator do NOT
//! get immediately chosen as a validator. Instead, they are declared as a _candidate_ and they
//! _might_ get elected at the _next era_ as a validator. The result of the election is determined
//! by nominators and their votes.
//!
//! An account can become a validator candidate via the
//! [`validate`](./enum.Call.html#variant.validate) call.
//!
//! #### Nomination
//!
//! A **nominator** does not take any _direct_ role in maintaining the network, instead, it votes on
//! a set of validators to be elected. Once interest in nomination is stated by an account, it
//! takes effect at the next election round. The funds in the nominator's stash account indicate the
//! _weight_ of its vote. Both the rewards and any punishment that a validator earns are shared
//! between the validator and its nominators. This rule incentivizes the nominators to NOT vote for
//! the misbehaving/offline validators as much as possible, simply because the nominators will also
//! lose funds if they vote poorly.
//!
//! An account can become a nominator via the [`nominate`](enum.Call.html#variant.nominate) call.
//!
//! #### Rewards and Slash
//!
//! The **reward and slashing** procedure is the core of the Staking module, attempting to _embrace
//! valid behavior_ while _punishing any misbehavior or lack of availability_.
//!
//! Slashing can occur at any point in time, once misbehavior is reported. Once slashing is
//! determined, a value is deducted from the balance of the validator and all the nominators who
//! voted for this validator (values are deducted from the _stash_ account of the slashed entity).
//!
//! Slashing logic is further described in the documentation of the `slashing` module.
//!
//! Similar to slashing, rewards are also shared among a validator and its associated nominators.
//! Yet, the reward funds are not always transferred to the stash account and can be configured.
//! See [Reward Calculation](#reward-calculation) for more details.
//!
//! #### Chilling
//!
//! Finally, any of the roles above can choose to step back temporarily and just chill for a while.
//! This means that if they are a nominator, they will not be considered as voters anymore and if
//! they are validators, they will no longer be a candidate for the next election.
//!
//! An account can step back via the [`chill`](enum.Call.html#variant.chill) call.
//!
//! ## Interface
//!
//! ### Dispatchable Functions
//!
//! The dispatchable functions of the Staking module enable the steps needed for entities to accept
//! and change their role, alongside some helper functions to get/set the metadata of the module.
//!
//! ### Public Functions
//!
//! The Staking module contains many public storage items and (im)mutable functions.
//!
//! ## Usage
//!
//! ### Example: Rewarding a validator by id.
//!
//! ```
//! use frame_support::{decl_module, dispatch};
//! use frame_system::{self as system, ensure_signed};
//! use darwinia_staking::{self as staking};
//!
//! pub trait Trait: staking::Trait {}
//!
//! decl_module! {
//! pub struct Module<T: Trait> for enum Call where origin: T::Origin {
//! /// Reward a validator.
//! pub fn reward_myself(origin) -> dispatch::DispatchResult {
//! let reported = ensure_signed(origin)?;
//! <staking::Module<T>>::reward_by_ids(vec![(reported, 10)]);
//! Ok(())
//! }
//! }
//! }
//! # fn main() { }
//! ```
//!
//! ## Implementation Details
//!
//! ### Slot Stake
//!
//! The term [`SlotStake`](./struct.Module.html#method.slot_stake) will be used throughout this
//! section. It refers to a value calculated at the end of each era, containing the _minimum value
//! at stake among all validators._ Note that a validator's value at stake might be a combination
//! of the validator's own stake and the votes it received. See [`Exposure`](./struct.Exposure.html)
//! for more details.
//!
//! ### Reward Calculation
//!
//! Validators and nominators are rewarded at the end of each era. The total reward of an era is
//! calculated using the era duration and the staking rate (the total amount of tokens staked by
//! nominators and validators, divided by the total token supply). It aims to incentivise toward a
//! defined staking rate. The full specification can be found
//! [here](https://research.web3.foundation/en/latest/polkadot/Token%20Economics.html#inflation-model).
//!
//! Total reward is split among validators and their nominators depending on the number of points
//! they received during the era. Points are added to a validator using
//! [`reward_by_ids`](./enum.Call.html#variant.reward_by_ids) or
//! [`reward_by_indices`](./enum.Call.html#variant.reward_by_indices).
//!
//! [`Module`](./struct.Module.html) implements
//! [`pallet_authorship::EventHandler`](../pallet_authorship/trait.EventHandler.html) to add reward points
//! to block producer and block producer of referenced uncles.
//!
//! The validator and its nominator split their reward as following:
//!
//! The validator can declare an amount, named
//! [`commission`](./struct.ValidatorPrefs.html#structfield.commission), that does not
//! get shared with the nominators at each reward payout through its
//! [`ValidatorPrefs`](./struct.ValidatorPrefs.html). This value gets deducted from the total reward
//! that is paid to the validator and its nominators. The remaining portion is split among the
//! validator and all of the nominators that nominated the validator, proportional to the value
//! staked behind this validator (_i.e._ dividing the
//! [`own`](./struct.Exposure.html#structfield.own) or
//! [`others`](./struct.Exposure.html#structfield.others) by
//! [`total`](./struct.Exposure.html#structfield.total) in [`Exposure`](./struct.Exposure.html)).
//!
//! All entities who receive a reward have the option to choose their reward destination
//! through the [`Payee`](./struct.Payee.html) storage item (see
//! [`set_payee`](enum.Call.html#variant.set_payee)), to be one of the following:
//!
//! - Controller account, (obviously) not increasing the staked value.
//! - Stash account, not increasing the staked value.
//! - Stash account, also increasing the staked value.
//!
//! ### Additional Fund Management Operations
//!
//! Any funds already placed into stash can be the target of the following operations:
//!
//! The controller account can free a portion (or all) of the funds using the
//! [`unbond`](enum.Call.html#variant.unbond) call. Note that the funds are not immediately
//! accessible. Instead, a duration denoted by [`BondingDurationInEra`](./struct.BondingDurationInEra.html)
//! (in number of eras) must pass until the funds can actually be removed. Once the
//! `BondingDurationInEra` is over, the [`withdraw_unbonded`](./enum.Call.html#variant.withdraw_unbonded)
//! call can be used to actually withdraw the funds.
//!
//! Note that there is a limitation to the number of fund-chunks that can be scheduled to be
//! unlocked in the future via [`unbond`](enum.Call.html#variant.unbond). In case this maximum
//! (`MAX_UNLOCKING_CHUNKS`) is reached, the bonded account _must_ first wait until a successful
//! call to `withdraw_unbonded` to remove some of the chunks.
//!
//! ### Election Algorithm
//!
//! The current election algorithm is implemented based on Phragmén.
//! The reference implementation can be found
//! [here](https://github.com/w3f/consensus/tree/master/NPoS).
//!
//! The election algorithm, aside from electing the validators with the most stake value and votes,
//! tries to divide the nominator votes among candidates in an equal manner. To further assure this,
//! an optional post-processing can be applied that iteratively normalizes the nominator staked
//! values until the total difference among votes of a particular nominator are less than a
//! threshold.
//!
//! ## GenesisConfig
//!
//! The Staking module depends on the [`GenesisConfig`](./struct.GenesisConfig.html).
//!
//! ## Related Modules
//!
//! - [Balances](../pallet_balances/index.html): Used to manage values at stake.
//! - [Session](../pallet_session/index.html): Used to manage sessions. Also, a list of new validators
//! is stored in the Session module's `Validators` at the end of each era.
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(drain_filter)]
#![recursion_limit = "128"]
#[cfg(test)]
mod mock;
#[cfg(test)]
mod tests;
mod inflation;
mod migration;
mod slashing;
mod types {
use sp_std::vec::Vec;
use crate::*;
/// Counter for the number of eras that have passed.
pub type EraIndex = u32;
/// Counter for the number of "reward" points earned by a given validator.
pub type Points = u32;
/// Balance of an account.
pub type Balance = u128;
/// Type used for expressing timestamp.
pub type Moment = Timestamp;
pub type RingBalance<T> = <RingCurrency<T> as Currency<AccountId<T>>>::Balance;
pub type RingPositiveImbalance<T> = <RingCurrency<T> as Currency<AccountId<T>>>::PositiveImbalance;
pub type RingNegativeImbalance<T> = <RingCurrency<T> as Currency<AccountId<T>>>::NegativeImbalance;
pub type KtonBalance<T> = <KtonCurrency<T> as Currency<AccountId<T>>>::Balance;
pub type KtonPositiveImbalance<T> = <KtonCurrency<T> as Currency<AccountId<T>>>::PositiveImbalance;
pub type KtonNegativeImbalance<T> = <KtonCurrency<T> as Currency<AccountId<T>>>::NegativeImbalance;
pub type StakingLedgerT<T> =
StakingLedger<AccountId<T>, RingBalance<T>, KtonBalance<T>, BlockNumber<T>, MomentT<T>>;
pub type StakingBalanceT<T> = StakingBalance<RingBalance<T>, KtonBalance<T>>;
pub type MomentT<T> = <TimeT<T> as Time>::Moment;
pub type Rewards<T> = (RingBalance<T>, Vec<NominatorReward<AccountId<T>, RingBalance<T>>>);
/// A timestamp: milliseconds since the unix epoch.
/// `u64` is enough to represent a duration of half a billion years, when the
/// time scale is milliseconds.
type Timestamp = u64;
type AccountId<T> = <T as system::Trait>::AccountId;
type BlockNumber<T> = <T as system::Trait>::BlockNumber;
type TimeT<T> = <T as Trait>::Time;
type RingCurrency<T> = <T as Trait>::RingCurrency;
type KtonCurrency<T> = <T as Trait>::KtonCurrency;
}
pub use types::{EraIndex, Points};
use codec::{Decode, Encode, HasCompact};
use frame_support::{
decl_error, decl_event, decl_module, decl_storage, ensure,
traits::{Currency, Get, Imbalance, OnFreeBalanceZero, OnUnbalanced, Time},
weights::SimpleDispatchInfo,
};
use frame_system::{self as system, ensure_root, ensure_signed};
use pallet_session::{historical::OnSessionEnding, SelectInitialValidators};
use sp_runtime::{
traits::{
CheckedSub, Convert, EnsureOrigin, One, SaturatedConversion, Saturating, SimpleArithmetic, StaticLookup, Zero,
},
DispatchResult, Perbill, Perquintill, RuntimeDebug,
};
#[cfg(feature = "std")]
use sp_runtime::{Deserialize, Serialize};
use sp_staking::{
offence::{Offence, OffenceDetails, OnOffenceHandler, ReportOffence},
SessionIndex,
};
use sp_std::{borrow::ToOwned, convert::TryInto, marker::PhantomData, vec, vec::Vec};
use darwinia_phragmen::{PhragmenStakedAssignment, Power, Votes};
use darwinia_support::{
LockIdentifier, LockableCurrency, NormalLock, OnDepositRedeem, OnUnbalancedKton, StakingLock, WithdrawLock,
WithdrawReason, WithdrawReasons,
};
use types::*;
const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4;
const MONTH_IN_MINUTES: Moment = 30 * 24 * 60;
const MONTH_IN_MILLISECONDS: Moment = MONTH_IN_MINUTES * 60 * 1000;
const MAX_NOMINATIONS: usize = 16;
const MAX_UNLOCKING_CHUNKS: usize = 32;
const STAKING_ID: LockIdentifier = *b"staking ";
/// Reward points of an era. Used to split era total payout between validators.
#[derive(Encode, Decode, Default)]
pub struct EraPoints {
/// Total number of points. Equals the sum of reward points for each validator.
total: Points,
/// The reward points earned by a given validator. The index of this vec corresponds to the
/// index into the current validator set.
individual: Vec<Points>,
}
impl EraPoints {
/// Add the reward to the validator at the given index. Index must be valid
/// (i.e. `index < current_elected.len()`).
fn add_points_to_index(&mut self, index: u32, points: u32) {
if let Some(new_total) = self.total.checked_add(points) {
self.total = new_total;
self.individual
.resize((index as usize + 1).max(self.individual.len()), 0);
self.individual[index as usize] += points; // Addition is less than total
}
}
}
/// Indicates the initial status of the staker.
#[derive(RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum StakerStatus<AccountId> {
/// Chilling.
Idle,
/// Declared desire in validating or already participating in it.
Validator,
/// Nominating for a group of other stakers.
Nominator(Vec<AccountId>),
}
/// A destination account for payment.
#[derive(PartialEq, Eq, Copy, Clone, Encode, Decode, RuntimeDebug)]
pub enum RewardDestination {
/// Pay into the stash account, increasing the amount at stake accordingly.
Staked { promise_month: Moment },
/// Pay into the stash account, not increasing the amount at stake.
Stash,
/// Pay into the controller account.
Controller,
}
impl Default for RewardDestination {
fn default() -> Self {
RewardDestination::Staked { promise_month: 0 }
}
}
/// Preference of what happens regarding validation.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorPrefs {
/// Reward that validator takes up-front; only the rest is split between themselves and
/// nominators.
#[codec(compact)]
pub commission: Perbill,
}
impl Default for ValidatorPrefs {
fn default() -> Self {
ValidatorPrefs {
commission: Default::default(),
}
}
}
/// To unify *Ring* and *Kton* balances.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub enum StakingBalance<RingBalance, KtonBalance>
where
RingBalance: HasCompact,
KtonBalance: HasCompact,
{
All,
RingBalance(RingBalance),
KtonBalance(KtonBalance),
}
impl<RingBalance, KtonBalance> Default for StakingBalance<RingBalance, KtonBalance>
where
RingBalance: Default + HasCompact,
KtonBalance: Default + HasCompact,
{
fn default() -> Self {
StakingBalance::RingBalance(Default::default())
}
}
/// The *Ring* under deposit.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct TimeDepositItem<RingBalance: HasCompact, Moment> {
#[codec(compact)]
pub value: RingBalance,
#[codec(compact)]
pub start_time: Moment,
#[codec(compact)]
pub expire_time: Moment,
}
/// The ledger of a (bonded) stash.
#[derive(PartialEq, Eq, Clone, Default, Encode, Decode, RuntimeDebug)]
pub struct StakingLedger<AccountId, RingBalance, KtonBalance, BlockNumber, Timestamp>
where
RingBalance: HasCompact,
KtonBalance: HasCompact,
{
/// The stash account whose balance is actually locked and at stake.
pub stash: AccountId,
/// The total amount of the stash's *RING* that will be at stake in any forthcoming
/// rounds.
#[codec(compact)]
pub active_ring: RingBalance,
// active time-deposit ring
#[codec(compact)]
pub active_deposit_ring: RingBalance,
/// The total amount of the stash's *KTON* that will be at stake in any forthcoming
/// rounds.
#[codec(compact)]
pub active_kton: KtonBalance,
// If you deposit *RING* for a minimum period,
// you can get *KTON* as bonus which can also be used for staking.
pub deposit_items: Vec<TimeDepositItem<RingBalance, Timestamp>>,
// TODO doc
pub ring_staking_lock: StakingLock<RingBalance, BlockNumber>,
// TODO doc
pub kton_staking_lock: StakingLock<KtonBalance, BlockNumber>,
}
impl<AccountId, RingBalance, KtonBalance, BlockNumber, Timestamp>
StakingLedger<AccountId, RingBalance, KtonBalance, BlockNumber, Timestamp>
where
RingBalance: SimpleArithmetic + Saturating + Copy,
KtonBalance: SimpleArithmetic + Saturating + Copy,
BlockNumber: PartialOrd,
Timestamp: PartialOrd,
{
/// Slash the validator for a given amount of balance. This can grow the value
/// of the slash in the case that the validator has less than `minimum_balance`
/// active funds. Returns the amount of funds actually slashed.
///
/// Slashes from `active` funds first, and then `unlocking`, starting with the
/// chunks that are closest to unlocking.
fn slash(
&mut self,
slash_ring: RingBalance,
slash_kton: KtonBalance,
bn: BlockNumber,
ts: Timestamp,
) -> (RingBalance, KtonBalance) {
let slash_out_of = |active_ring: &mut RingBalance,
active_deposit_ring: &mut RingBalance,
deposit_item: &mut Vec<TimeDepositItem<RingBalance, Timestamp>>,
active_kton: &mut KtonBalance,
slash_ring: &mut RingBalance,
slash_kton: &mut KtonBalance| {
let slash_from_active_ring = (*slash_ring).min(*active_ring);
let slash_from_active_kton = (*slash_kton).min(*active_kton);
if !slash_from_active_ring.is_zero() {
let normal_ring = *active_ring - *active_deposit_ring;
if normal_ring < *slash_ring {
let mut slash_deposit_ring = *slash_ring - (*active_ring - *active_deposit_ring);
*active_deposit_ring -= slash_deposit_ring;
deposit_item.drain_filter(|item| {
if ts >= item.expire_time {
true
} else {
if slash_deposit_ring.is_zero() {
false
} else {
if slash_deposit_ring > item.value {
slash_deposit_ring -= item.value;
true
} else {
item.value -= sp_std::mem::replace(&mut slash_deposit_ring, Zero::zero());
false
}
}
}
});
}
*active_ring -= slash_from_active_ring;
*slash_ring -= slash_from_active_ring;
}
if !slash_from_active_kton.is_zero() {
*active_kton -= slash_from_active_kton;
*slash_kton -= slash_from_active_kton;
}
};
let (mut apply_slash_ring, mut apply_slash_kton) = (slash_ring, slash_kton);
let StakingLedger {
active_ring,
active_deposit_ring,
deposit_items,
active_kton,
ring_staking_lock,
kton_staking_lock,
..
} = self;
slash_out_of(
active_ring,
active_deposit_ring,
deposit_items,
active_kton,
&mut apply_slash_ring,
&mut apply_slash_kton,
);
if !apply_slash_ring.is_zero() {
ring_staking_lock.unbondings.drain_filter(|lock| {
if bn >= lock.until {
true
} else {
if apply_slash_ring.is_zero() {
false
} else {
if apply_slash_ring > lock.amount {
apply_slash_ring -= lock.amount;
true
} else {
lock.amount -= sp_std::mem::replace(&mut apply_slash_ring, Zero::zero());
false
}
}
}
});
}
if !apply_slash_kton.is_zero() {
kton_staking_lock.unbondings.drain_filter(|lock| {
if bn >= lock.until {
true
} else {
if apply_slash_kton.is_zero() {
false
} else {
if apply_slash_kton > lock.amount {
apply_slash_kton -= lock.amount;
true
} else {
lock.amount -= sp_std::mem::replace(&mut apply_slash_kton, Zero::zero());
false
}
}
}
});
}
(slash_ring - apply_slash_ring, slash_kton - apply_slash_kton)
}
}
/// A record of the nominations made by a specific account.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct Nominations<AccountId> {
/// The targets of nomination.
pub targets: Vec<AccountId>,
/// The era the nominations were submitted.
pub submitted_in: EraIndex,
/// Whether the nominations have been suppressed.
pub suppressed: bool,
}
/// The amount of exposure (to slashing) than an individual nominator has.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug)]
pub struct IndividualExposure<AccountId, RingBalance, KtonBalance>
where
RingBalance: HasCompact,
KtonBalance: HasCompact,
{
/// The stash account of the nominator in question.
who: AccountId,
/// Amount of funds exposed.
#[codec(compact)]
ring_balance: RingBalance,
#[codec(compact)]
kton_balance: KtonBalance,
power: Power,
}
/// A snapshot of the stake backing a single validator in the system.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Default, RuntimeDebug)]
pub struct Exposure<AccountId, RingBalance, KtonBalance>
where
RingBalance: HasCompact,
KtonBalance: HasCompact,
{
/// The validator's own stash that is exposed.
#[codec(compact)]
pub own_ring_balance: RingBalance,
#[codec(compact)]
pub own_kton_balance: KtonBalance,
pub own_power: Power,
/// The total balance backing this validator.
pub total_power: Power,
/// The portions of nominators stashes that are exposed.
pub others: Vec<IndividualExposure<AccountId, RingBalance, KtonBalance>>,
}
/// A typed conversion from stash account ID to the current exposure of nominators
/// on that account.
pub struct ExposureOf<T>(PhantomData<T>);
impl<T: Trait> Convert<T::AccountId, Option<Exposure<T::AccountId, RingBalance<T>, KtonBalance<T>>>> for ExposureOf<T> {
fn convert(validator: T::AccountId) -> Option<Exposure<T::AccountId, RingBalance<T>, KtonBalance<T>>> {
Some(<Module<T>>::stakers(&validator))
}
}
// FIXME: RingBalance: HasCompact
// TODO: doc
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorReward<AccountId, RingBalance> {
who: AccountId,
#[codec(compact)]
amount: RingBalance,
nominators_reward: Vec<NominatorReward<AccountId, RingBalance>>,
}
// TODO: doc
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct NominatorReward<AccountId, RingBalance> {
who: AccountId,
#[codec(compact)]
amount: RingBalance,
}
/// A pending slash record. The value of the slash has been computed but not applied yet,
/// rather deferred for several eras.
#[derive(Encode, Decode, Default, RuntimeDebug)]
pub struct UnappliedSlash<AccountId, RingBalance, KtonBalance> {
/// The stash ID of the offending validator.
validator: AccountId,
/// The validator's own slash.
own: slashing::RK<RingBalance, KtonBalance>,
/// All other slashed stakers and amounts.
others: Vec<(AccountId, slashing::RK<RingBalance, KtonBalance>)>,
/// Reporters of the offence; bounty payout recipients.
reporters: Vec<AccountId>,
/// The amount of payout.
payout: slashing::RK<RingBalance, KtonBalance>,
}
/// Means for interacting with a specialized version of the `session` trait.
///
/// This is needed because `Staking` sets the `ValidatorIdOf` of the `pallet_session::Trait`
pub trait SessionInterface<AccountId>: system::Trait {
/// Disable a given validator by stash ID.
///
/// Returns `true` if new era should be forced at the end of this session.
/// This allows preventing a situation where there is too many validators
/// disabled and block production stalls.
fn disable_validator(validator: &AccountId) -> Result<bool, ()>;
/// Get the validators from session.
fn validators() -> Vec<AccountId>;
/// Prune historical session tries up to but not including the given index.
fn prune_historical_up_to(up_to: SessionIndex);
}
impl<T: Trait> SessionInterface<<T as system::Trait>::AccountId> for T
where
T: pallet_session::Trait<ValidatorId = <T as system::Trait>::AccountId>,
T: pallet_session::historical::Trait<
FullIdentification = Exposure<<T as system::Trait>::AccountId, RingBalance<T>, KtonBalance<T>>,
FullIdentificationOf = ExposureOf<T>,
>,
T::SessionHandler: pallet_session::SessionHandler<<T as system::Trait>::AccountId>,
T::OnSessionEnding: pallet_session::OnSessionEnding<<T as system::Trait>::AccountId>,
T::SelectInitialValidators: pallet_session::SelectInitialValidators<<T as system::Trait>::AccountId>,
T::ValidatorIdOf: Convert<<T as system::Trait>::AccountId, Option<<T as system::Trait>::AccountId>>,
{
fn disable_validator(validator: &<T as system::Trait>::AccountId) -> Result<bool, ()> {
<pallet_session::Module<T>>::disable(validator)
}
fn validators() -> Vec<<T as system::Trait>::AccountId> {
<pallet_session::Module<T>>::validators()
}
fn prune_historical_up_to(up_to: SessionIndex) {
<pallet_session::historical::Module<T>>::prune_up_to(up_to);
}
}
pub trait Trait: system::Trait {
/// Time used for computing era duration.
type Time: Time;
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
/// Number of sessions per era.
type SessionsPerEra: Get<SessionIndex>;
/// Number of eras that staked funds must remain bonded for.
type BondingDurationInEra: Get<EraIndex>;
/// Number of eras that staked funds must remain bonded for.
type BondingDurationInBlockNumber: Get<Self::BlockNumber>;
/// Number of eras that slashes are deferred by, after computation. This
/// should be less than the bonding duration. Set to 0 if slashes should be
/// applied immediately, without opportunity for intervention.
type SlashDeferDuration: Get<EraIndex>;
/// The origin which can cancel a deferred slash. Root can always do this.
type SlashCancelOrigin: EnsureOrigin<Self::Origin>;
/// Interface for interacting with a session module.
type SessionInterface: self::SessionInterface<Self::AccountId>;
/// The *RING* balance.
type RingCurrency: LockableCurrency<Self::AccountId, Moment = Self::BlockNumber>;
/// Tokens have been minted and are unused for validator-reward.
type RingRewardRemainder: OnUnbalanced<RingNegativeImbalance<Self>>;
/// Handler for the unbalanced *RING* reduction when slashing a staker.
type RingSlash: OnUnbalanced<RingNegativeImbalance<Self>>;
/// Handler for the unbalanced *RING* increment when rewarding a staker.
type RingReward: OnUnbalanced<RingPositiveImbalance<Self>>;
/// The *KTON* balance
type KtonCurrency: LockableCurrency<Self::AccountId, Moment = Self::BlockNumber>;
// FIXME: Ugly hack due to https://github.com/rust-lang/rust/issues/31844#issuecomment-557918823
/// Handler for the unbalanced *KTON* reduction when slashing a staker.
type KtonSlash: OnUnbalancedKton<KtonNegativeImbalance<Self>>;
/// Handler for the unbalanced *KTON* increment when rewarding a staker.
type KtonReward: OnUnbalanced<KtonPositiveImbalance<Self>>;
// TODO: doc
type Cap: Get<RingBalance<Self>>;
// TODO: doc
type TotalPower: Get<Power>;
// TODO: doc
type GenesisTime: Get<MomentT<Self>>;
}
/// Mode of era-forcing.
#[derive(Copy, Clone, PartialEq, Eq, Encode, Decode, RuntimeDebug)]
#[cfg_attr(feature = "std", derive(Serialize, Deserialize))]
pub enum Forcing {
/// Not forcing anything - just let whatever happen.
NotForcing,
/// Force a new era, then reset to `NotForcing` as soon as it is done.
ForceNew,
/// Avoid a new era indefinitely.
ForceNone,
/// Force a new era at the end of all sessions indefinitely.
ForceAlways,
}
impl Default for Forcing {
fn default() -> Self {
Forcing::NotForcing
}
}
decl_storage! {
trait Store for Module<T: Trait> as Staking {
/// The ideal number of staking participants.
pub ValidatorCount get(fn validator_count) config(): u32;
/// Minimum number of staking participants before emergency conditions are imposed.
pub MinimumValidatorCount get(fn minimum_validator_count) config(): u32 = DEFAULT_MINIMUM_VALIDATOR_COUNT;
/// Any validators that may never be slashed or forcibly kicked. It's a Vec since they're
/// easy to initialize and the performance hit is minimal (we expect no more than four
/// invulnerables) and restricted to testnets.
pub Invulnerables get(fn invulnerables) config(): Vec<T::AccountId>;
/// Map from all locked "stash" accounts to the controller account.
pub Bonded get(fn bonded): map T::AccountId => Option<T::AccountId>;
/// Map from all (unlocked) "controller" accounts to the info regarding the staking.
pub Ledger get(fn ledger): map T::AccountId => Option<StakingLedgerT<T>>;
/// Where the reward payment should be made. Keyed by stash.
pub Payee get(fn payee): map T::AccountId => RewardDestination;
/// The map from (wannabe) validator stash key to the preferences of that validator.
pub Validators get(fn validators): linked_map T::AccountId => ValidatorPrefs;
/// The map from nominator stash key to the set of stash keys of all validators to nominate.
///
/// NOTE: is private so that we can ensure upgraded before all typical accesses.
/// Direct storage APIs can still bypass this protection.
Nominators get(fn nominators): linked_map T::AccountId => Option<Nominations<T::AccountId>>;
/// Nominators for a particular account that is in action right now. You can't iterate
/// through validators here, but you can find them in the Session module.
///
/// This is keyed by the stash account.
pub Stakers get(fn stakers): map T::AccountId => Exposure<T::AccountId, RingBalance<T>, KtonBalance<T>>;
/// The currently elected validator set keyed by stash account ID.
pub CurrentElected get(fn current_elected): Vec<T::AccountId>;
/// The current era index.
pub CurrentEra get(fn current_era) config(): EraIndex;
/// The start of the current era.
pub CurrentEraStart get(fn current_era_start): MomentT<T>;
/// The session index at which the current era started.
pub CurrentEraStartSessionIndex get(fn current_era_start_session_index): SessionIndex;
/// Rewards for the current era. Using indices of current elected set.
CurrentEraPointsEarned get(fn current_era_reward): EraPoints;
/// The amount of balance actively at stake for each validator slot, currently.
///
/// This is used to derive rewards and punishments.
pub SlotStake get(fn slot_stake) build(|config: &GenesisConfig<T>| {
config
.stakers
.iter()
.map(|&(_, _, r, _)| <Module<T>>::currency_to_power::<_>(r, <Module<T>>::ring_pool()))
.min()
.unwrap_or_default()
}): Power;
/// True if the next session change will be a new era regardless of index.
pub ForceEra get(fn force_era) config(): Forcing;
/// The percentage of the slash that is distributed to reporters.
///
/// The rest of the slashed value is handled by the `Slash`.
pub SlashRewardFraction get(fn slash_reward_fraction) config(): Perbill;
/// The amount of currency given to reporters of a slash event which was
/// canceled by extraordinary circumstances (e.g. governance).
pub CanceledSlashPayout get(fn canceled_payout) config(): Power;
/// All unapplied slashes that are queued for later.
pub UnappliedSlashes: map EraIndex => Vec<UnappliedSlash<T::AccountId, RingBalance<T>, KtonBalance<T>>>;
/// Total *Ring* in pool.
pub RingPool get(fn ring_pool): RingBalance<T>;
/// Total *Kton* in pool.
pub KtonPool get(fn kton_pool): KtonBalance<T>;
/// The percentage of the total payout that is distributed to validators and nominators
///
/// The reset might go to Treasury or something else.
pub PayoutFraction get(fn payout_fraction) config(): Perbill;
/// A mapping from still-bonded eras to the first session index of that era.
BondedEras: Vec<(EraIndex, SessionIndex)>;
/// All slashing events on validators, mapped by era to the highest slash proportion
/// and slash value of the era.
ValidatorSlashInEra:
double_map EraIndex, twox_128(T::AccountId) => Option<(Perbill, slashing::RKT<T>)>;
/// All slashing events on nominators, mapped by era to the highest slash value of the era.
NominatorSlashInEra: double_map EraIndex, twox_128(T::AccountId) => Option<slashing::RKT<T>>;
/// Slashing spans for stash accounts.
SlashingSpans: map T::AccountId => Option<slashing::SlashingSpans>;
/// Records information about the maximum slash of a stash within a slashing span,
/// as well as how much reward has been paid out.
SpanSlash: map (T::AccountId, slashing::SpanIndex) => slashing::SpanRecord<RingBalance<T>, KtonBalance<T>>;
/// The earliest era for which we have a pending, unapplied slash.
EarliestUnappliedSlash: Option<EraIndex>;
/// The version of storage for upgrade.
StorageVersion: u32;
}
add_extra_genesis {
config(stakers): Vec<(T::AccountId, T::AccountId, RingBalance<T>, StakerStatus<T::AccountId>)>;
build(|config: &GenesisConfig<T>| {
for &(ref stash, ref controller, r, ref status) in &config.stakers {
assert!(
T::RingCurrency::free_balance(&stash) >= r,
"Stash does not have enough balance to bond.",
);
let _ = <Module<T>>::bond(
T::Origin::from(Some(stash.to_owned()).into()),
T::Lookup::unlookup(controller.to_owned()),
StakingBalance::RingBalance(r),
RewardDestination::Staked { promise_month: 0 },
0,
);
let _ = match status {
StakerStatus::Validator => {
<Module<T>>::validate(
T::Origin::from(Some(controller.to_owned()).into()),
Default::default(),
)
},
StakerStatus::Nominator(votes) => {
<Module<T>>::nominate(
T::Origin::from(Some(controller.to_owned()).into()),
votes.iter().map(|l| T::Lookup::unlookup(l.to_owned())).collect(),
)
}, _ => Ok(())
};
}
StorageVersion::put(migration::CURRENT_VERSION);
});
}
}
decl_event!(
pub enum Event<T>
where
<T as system::Trait>::AccountId,
<T as system::Trait>::BlockNumber,
RingBalance = RingBalance<T>,
KtonBalance = KtonBalance<T>,
MomentT = MomentT<T>,
{
/// Bond succeed.
/// `amount` in `RingBalance<T>`, `start_time` in `MomentT<T>`, `expired_time` in `MomentT<T>`
BondRing(RingBalance, MomentT, MomentT),
/// Bond succeed.
/// `amount`
BondKton(KtonBalance),
/// Unbond succeed.
/// `amount` in `RingBalance<T>`, `now` in `BlockNumber`
UnbondRing(RingBalance, BlockNumber),
/// Unbond succeed.
/// `amount` om `KtonBalance<T>`, `now` in `BlockNumber`
UnbondKton(KtonBalance, BlockNumber),
/// All validators have been rewarded by the first balance; the second is the remainder
/// from the maximum amount of reward; the third is validator and nominators' reward.
Reward(RingBalance, RingBalance, Vec<ValidatorReward<AccountId, RingBalance>>),
/// One validator (and its nominators) has been slashed by the given amount.
Slash(AccountId, RingBalance, KtonBalance),
/// An old slashing report from a prior era was discarded because it could
/// not be processed.
OldSlashingReportDiscarded(SessionIndex),
}
);
decl_error! {
/// Error for the staking module.
pub enum Error for Module<T: Trait> {
/// Not a controller account.
NotController,
/// Not a stash account.
NotStash,
/// Stash is already bonded.
AlreadyBonded,
/// Controller is already paired.
AlreadyPaired,
/// Targets cannot be empty.
EmptyTargets,
/// Duplicate index.
DuplicateIndex,
/// Slash record index out of bounds.
InvalidSlashIndex,
/// Can not bond with value less than minimum balance.
InsufficientValue,
/// Can not schedule more unlock chunks.
NoMoreChunks,
}
}
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {