-
Notifications
You must be signed in to change notification settings - Fork 49
/
lib.rs
2024 lines (1746 loc) · 68.3 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
// Copyright 2017-2019 Parity Technologies (UK) Ltd.
// This file is part of Substrate.
// Substrate is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Substrate is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Substrate. If not, see <http://www.gnu.org/licenses/>.
#![recursion_limit = "128"]
#![cfg_attr(not(feature = "std"), no_std)]
#![feature(drain_filter)]
pub mod inflation;
mod err {
pub const CONTROLLER_INVALID: &'static str = "Controller Account - INVALID";
pub const CONTROLLER_ALREADY_PAIRED: &'static str = "Controller Account - ALREADY PAIRED";
pub const STASH_INVALID: &'static str = "Stash Account - INVALID";
pub const STASH_ALREADY_BONDED: &'static str = "Stash Account - ALREADY BONDED";
pub const UNLOCK_CHUNKS_REACH_MAX: &'static str = "Unlock Chunks - REACH MAX VALUE 32";
pub const CLAIM_DEPOSITS_EXPIRE_TIME_INVALID: &'static str =
"Claim Deposits With Punish - NOTHING TO CLAIM AT THIS TIME";
pub const TARGETS_INVALID: &'static str = "Targets - CAN NOT BE EMPTY";
pub const NODE_NAME_REACH_MAX: &'static str = "Node Name - REACH MAX LENGTH 32";
pub const NODE_NAME_CONTAINS_INVALID_CHARS: &'static str = "Node Name - CONTAINS INVALID CHARS SUCH AS '.' AND '@'";
pub const NODE_NAME_CONTAINS_URLS: &'static str = "Node Name - CONTAINS URLS";
}
#[allow(unused)]
#[cfg(all(feature = "std", test))]
mod mock;
#[cfg(all(feature = "std", test))]
mod tests;
use codec::{Decode, Encode, HasCompact};
use phragmen::{build_support_map, elect, equalize, ExtendedBalance as Power, PhragmenStakedAssignment};
#[cfg(feature = "std")]
use regex::bytes::Regex;
#[cfg(not(feature = "std"))]
use rstd::borrow::ToOwned;
use rstd::{prelude::*, result};
use session::{historical::OnSessionEnding, SelectInitialValidators};
use sr_primitives::{
traits::{Bounded, CheckedSub, Convert, One, SaturatedConversion, Saturating, StaticLookup, Zero},
weights::SimpleDispatchInfo,
Perbill, Perquintill, RuntimeDebug,
};
#[cfg(feature = "std")]
use sr_primitives::{Deserialize, Serialize};
use sr_staking_primitives::{
offence::{Offence, OffenceDetails, OnOffenceHandler, ReportOffence},
SessionIndex,
};
use srml_support::{
decl_event, decl_module, decl_storage, ensure,
traits::{Currency, Get, Imbalance, OnFreeBalanceZero, OnUnbalanced, Time},
};
use system::{ensure_root, ensure_signed};
use darwinia_support::{
LockIdentifier, LockableCurrency, NormalLock, OnDepositRedeem, StakingLock, WithdrawLock, WithdrawReason,
WithdrawReasons,
};
pub type Balance = u128;
pub type Moment = u64;
/// 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;
type Ring<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::Balance;
type PositiveImbalanceRing<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
type NegativeImbalanceRing<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
type Kton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::Balance;
type PositiveImbalanceKton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
type NegativeImbalanceKton<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
type MomentOf<T> = <<T as Trait>::Time as Time>::Moment;
const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4;
const MAX_NOMINATIONS: usize = 16;
const MAX_UNLOCKING_CHUNKS: u32 = 32;
const MONTH_IN_MILLISECONDS: Moment = 30 * 24 * 60 * 60 * 1000;
const NODE_NAME_MAX_LENGTH: 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: Points) {
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.
/// for now, we don't use this.
// DeprecatedStaked,
/// 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::Stash
}
}
/// Preference of what happens on a slash event.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorPrefs {
pub node_name: Vec<u8>,
/// percent of Reward that validator takes up-front; only the rest is split between themselves and
/// nominators.
#[codec(compact)]
pub validator_payment_ratio: u32,
}
impl ValidatorPrefs {
/// Check whether a node name is considered as valid
fn check_node_name(&self) -> result::Result<(), &'static str> {
let name = self.node_name.as_slice();
{
if name.len() >= NODE_NAME_MAX_LENGTH {
return Err(err::NODE_NAME_REACH_MAX);
}
}
#[cfg(not(feature = "std"))]
{
if name.contains(&b'.') || name.contains(&b'@') {
return Err(err::NODE_NAME_CONTAINS_INVALID_CHARS);
}
if name.starts_with("http".as_bytes())
|| name.starts_with("https".as_bytes())
|| name.starts_with("www".as_bytes())
|| name.ends_with("com".as_bytes())
|| name.ends_with("cn".as_bytes())
|| name.ends_with("io".as_bytes())
|| name.ends_with("org".as_bytes())
|| name.ends_with("xyz".as_bytes())
{
return Err(err::NODE_NAME_CONTAINS_URLS);
}
}
// TODO: https://github.com/rust-lang/regex/issues/476
#[cfg(feature = "std")]
{
let invalid_chars = r"[\\.@]";
let re = Regex::new(invalid_chars).unwrap();
if re.is_match(&name) {
return Err(err::NODE_NAME_CONTAINS_INVALID_CHARS);
}
let invalid_patterns = r"^(https?|www)";
let re = Regex::new(invalid_patterns).unwrap();
if re.is_match(&name) {
return Err(err::NODE_NAME_CONTAINS_URLS);
}
let invalid_patterns = r"(com|cn|io|org|xyz)$";
let re = Regex::new(invalid_patterns).unwrap();
if re.is_match(&name) {
return Err(err::NODE_NAME_CONTAINS_URLS);
}
}
Ok(())
}
}
impl Default for ValidatorPrefs {
fn default() -> Self {
ValidatorPrefs {
node_name: vec![],
validator_payment_ratio: 0,
}
}
}
/// To unify *Ring* and *Kton* balances.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub enum StakingBalances<Ring, Kton>
where
Ring: HasCompact,
Kton: HasCompact,
{
Ring(Ring),
Kton(Kton),
}
impl<Ring, Kton> Default for StakingBalances<Ring, Kton>
where
Ring: Default + HasCompact,
Kton: Default + HasCompact,
{
fn default() -> Self {
StakingBalances::Ring(Default::default())
}
}
/// The *Ring* under deposit.
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct TimeDepositItem<Ring: HasCompact, Moment> {
#[codec(compact)]
pub value: Ring,
#[codec(compact)]
pub start_time: Moment,
#[codec(compact)]
pub expire_time: Moment,
}
/// The ledger of a (bonded) stash.
#[derive(PartialEq, Eq, Default, Clone, Encode, Decode, RuntimeDebug)]
pub struct StakingLedger<AccountId, Ring: HasCompact, Kton: HasCompact, Moment> {
/// The stash account whose balance is actually locked and at stake.
pub stash: AccountId,
/// The total amount of the stash's balance that will be at stake in any forthcoming
/// rounds.
#[codec(compact)]
pub active_ring: Ring,
// active time-deposit ring
#[codec(compact)]
pub active_deposit_ring: Ring,
/// The total amount of the stash's balance that will be at stake in any forthcoming
/// rounds.
#[codec(compact)]
pub active_kton: Kton,
// time-deposit items:
// 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<Ring, Moment>>,
pub ring_staking_lock: StakingLock<Ring, Moment>,
pub kton_staking_lock: StakingLock<Kton, Moment>,
}
/// The amount of exposure (to slashing) than an individual nominator has.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, RuntimeDebug)]
pub struct IndividualExposure<AccountId, Power: HasCompact> {
/// The stash account of the nominator in question.
who: AccountId,
/// Amount of funds exposed.
#[codec(compact)]
value: 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, Power: HasCompact> {
/// The total balance backing this validator.
#[codec(compact)]
pub total: Power,
/// The validator's own stash that is exposed.
#[codec(compact)]
pub own: Power,
/// The portions of nominators stashes that are exposed.
pub others: Vec<IndividualExposure<AccountId, Power>>,
}
// TODO: doc
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorReward<AccountId, Ring: HasCompact> {
who: AccountId,
#[codec(compact)]
amount: Ring,
nominators_reward: Vec<NominatorReward<AccountId, Ring>>,
}
// TODO: doc
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct NominatorReward<AccountId, Ring: HasCompact> {
who: AccountId,
#[codec(compact)]
amount: Ring,
}
/// A slashing event occurred, slashing a validator for a given amount of balance.
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Default, RuntimeDebug)]
pub struct SlashJournalEntry<AccountId, Power: HasCompact> {
who: AccountId,
#[codec(compact)]
amount: Power,
// the amount of `who`'s own exposure that was slashed
#[codec(compact)]
own_slash: Power,
}
/// Means for interacting with a specialized version of the `session` trait.
///
/// This is needed because `Staking` sets the `ValidatorIdOf` of the `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: session::Trait<ValidatorId = <T as system::Trait>::AccountId>,
T: session::historical::Trait<
FullIdentification = Exposure<<T as system::Trait>::AccountId, Power>,
FullIdentificationOf = ExposureOf<T>,
>,
T::SessionHandler: session::SessionHandler<<T as system::Trait>::AccountId>,
T::OnSessionEnding: session::OnSessionEnding<<T as system::Trait>::AccountId>,
T::SelectInitialValidators: 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, ()> {
<session::Module<T>>::disable(validator)
}
fn validators() -> Vec<<T as system::Trait>::AccountId> {
<session::Module<T>>::validators()
}
fn prune_historical_up_to(up_to: SessionIndex) {
<session::historical::Module<T>>::prune_up_to(up_to);
}
}
pub trait Trait: timestamp::Trait + session::Trait {
/// Time used for computing era duration.
type Time: Time;
/// Convert a balance into a number used for election calculation.
/// This must fit into a `u64` but is allowed to be sensibly lossy.
/// TODO: #1377
/// The backward convert should be removed as the new Phragmen API returns ratio.
/// The post-processing needs it but will be moved to off-chain. TODO: #2908
type CurrencyToVote: Convert<Power, u64> + Convert<u128, Power>;
/// 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 `Moment` that staked funds must remain bonded for.
type BondingDuration: Get<Self::Moment>;
/// Number of eras that staked funds must remain bonded for.
type BondingDurationInEra: Get<EraIndex>;
/// Interface for interacting with a session module.
type SessionInterface: self::SessionInterface<Self::AccountId>;
/// The staking balances.
type Ring: LockableCurrency<Self::AccountId, Moment = Self::Moment>;
/// Tokens have been minted and are unused for validator-reward.
type RingRewardRemainder: OnUnbalanced<NegativeImbalanceRing<Self>>;
/// Handler for the unbalanced reduction when slashing a staker.
type RingSlash: OnUnbalanced<NegativeImbalanceRing<Self>>;
/// Handler for the unbalanced increment when rewarding a staker.
type RingReward: OnUnbalanced<PositiveImbalanceRing<Self>>;
/// The staking balances.
type Kton: LockableCurrency<Self::AccountId, Moment = Self::Moment>;
/// Handler for the unbalanced reduction when slashing a staker.
type KtonSlash: OnUnbalanced<NegativeImbalanceKton<Self>>;
/// Handler for the unbalanced increment when rewarding a staker.
type KtonReward: OnUnbalanced<PositiveImbalanceKton<Self>>;
// TODO: doc
type Cap: Get<<Self::Ring as Currency<Self::AccountId>>::Balance>;
// TODO: doc
type GenesisTime: Get<MomentOf<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<StakingLedger<T::AccountId, Ring<T>, Kton<T>, T::Moment>>;
/// 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.
pub Nominators get(fn nominators): linked_map T::AccountId => Vec<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, Power>;
/// 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): MomentOf<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(|&(_, _, value, _)| value.saturated_into()).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;
/// Total *Ring* in pool.
pub RingPool get(fn ring_pool): Ring<T>;
/// Total *Kton* in pool.
pub KtonPool get(fn kton_pool): Kton<T>;
/// A mapping from still-bonded eras to the first session index of that era.
BondedEras: Vec<(EraIndex, SessionIndex)>;
/// All slashes that have occurred in a given era.
EraSlashJournal get(fn era_slash_journal): map EraIndex => Vec<SlashJournalEntry<T::AccountId, Power>>;
}
add_extra_genesis {
config(stakers): Vec<(T::AccountId, T::AccountId, Ring<T>, StakerStatus<T::AccountId>)>;
build(|config: &GenesisConfig<T>| {
for &(ref stash, ref controller, ring, ref status) in &config.stakers {
assert!(T::Ring::free_balance(&stash) >= ring);
let _ = <Module<T>>::bond(
T::Origin::from(Some(stash.clone()).into()),
T::Lookup::unlookup(controller.clone()),
StakingBalances::Ring(ring),
RewardDestination::Stash,
0,
);
let _ = match status {
StakerStatus::Validator => {
<Module<T>>::validate(
T::Origin::from(Some(controller.clone()).into()),
ValidatorPrefs {
node_name: "Darwinia Node".into(),
..Default::default()
},
)
},
StakerStatus::Nominator(votes) => {
<Module<T>>::nominate(
T::Origin::from(Some(controller.clone()).into()),
votes.iter().map(|l| {T::Lookup::unlookup(l.clone())}).collect(),
)
},
_ => Ok(())
};
}
});
}
}
decl_event!(
pub enum Event<T>
where
<T as system::Trait>::AccountId
{
/// 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(Balance, Balance, Vec<ValidatorReward<AccountId, Balance>>),
// TODO: refactor to Balance later?
/// One validator (and its nominators) has been slashed by the given amount.
Slash(AccountId, Power),
/// An old slashing report from a prior era was discarded because it could
/// not be processed.
OldSlashingReportDiscarded(SessionIndex),
/// NodeName changed.
NodeNameUpdated,
/// Bond succeed.
/// `amount`, `now`, `duration` in month
Bond(StakingBalances<Balance, Balance>, Moment, Moment),
/// Unbond succeed.
/// `amount`, `now`
Unbond(StakingBalances<Balance, Balance>, Moment),
// Develop
// Print(u128),
}
);
decl_module! {
pub struct Module<T: Trait> for enum Call where origin: T::Origin {
/// Number of sessions per era.
const SessionsPerEra: SessionIndex = T::SessionsPerEra::get();
/// Number of `Moment` that staked funds must remain bonded for.
const BondingDuration: T::Moment = T::BondingDuration::get();
/// Number of eras that staked funds must remain bonded for.
const BondingDurationInEra: EraIndex = T::BondingDurationInEra::get();
fn deposit_event() = default;
fn on_finalize() {
// Set the start of the first era.
if !<CurrentEraStart<T>>::exists() {
<CurrentEraStart<T>>::put(T::Time::now());
}
}
/// Take the origin account as a stash and lock up `value` of its balance. `controller` will
/// be the account that controls it.
///
/// `value` must be more than the `minimum_balance` specified by `T::Currency`.
///
/// The dispatch origin for this call must be _Signed_ by the stash account.
///
/// # <weight>
/// - Independent of the arguments. Moderate complexity.
/// - O(1).
/// - Three extra DB entries.
///
/// NOTE: Two of the storage writes (`Self::bonded`, `Self::payee`) are _never_ cleaned unless
/// the `origin` falls below _existential deposit_ and gets removed as dust.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn bond(
origin,
controller: <T::Lookup as StaticLookup>::Source,
value: StakingBalances<Ring<T>, Kton<T>>,
payee: RewardDestination,
promise_month: Moment
) {
let stash = ensure_signed(origin)?;
ensure!(!<Bonded<T>>::exists(&stash), err::STASH_ALREADY_BONDED);
let controller = T::Lookup::lookup(controller)?;
ensure!(!<Ledger<T>>::exists(&controller), err::CONTROLLER_ALREADY_PAIRED);
// You're auto-bonded forever, here. We might improve this by only bonding when
// you actually validate/nominate and remove once you unbond __everything__.
<Bonded<T>>::insert(&stash, &controller);
<Payee<T>>::insert(&stash, payee);
let ledger = StakingLedger {
stash: stash.clone(),
..Default::default()
};
let now = <timestamp::Module<T>>::now().saturated_into::<Moment>();
let promise_month = promise_month.min(36);
match value {
StakingBalances::Ring(r) => {
let stash_balance = T::Ring::free_balance(&stash);
let value = r.min(stash_balance);
Self::bond_helper_in_ring(&stash, &controller, value, promise_month, ledger);
<RingPool<T>>::mutate(|r| *r += value);
<Module<T>>::deposit_event(RawEvent::Bond(
StakingBalances::Ring(value.saturated_into()),
now,
promise_month,
));
},
StakingBalances::Kton(k) => {
let stash_balance = T::Kton::free_balance(&stash);
let value = k.min(stash_balance);
Self::bond_helper_in_kton(&controller, value, ledger);
<KtonPool<T>>::mutate(|k| *k += value);
<Module<T>>::deposit_event(RawEvent::Bond(
StakingBalances::Kton(value.saturated_into()),
now,
promise_month,
));
},
}
}
/// Add some extra amount that have appeared in the stash `free_balance` into the balance up
/// for staking.
///
/// Use this if there are additional funds in your stash account that you wish to bond.
/// Unlike [`bond`] or [`unbond`] this function does not impose any limitation on the amount
/// that can be added.
///
/// The dispatch origin for this call must be _Signed_ by the stash, not the controller.
///
/// # <weight>
/// - Independent of the arguments. Insignificant complexity.
/// - O(1).
/// - One DB entry.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(500_000)]
fn bond_extra(
origin,
value: StakingBalances<Ring<T>, Kton<T>>,
promise_month: Moment
) {
let stash = ensure_signed(origin)?;
let controller = Self::bonded(&stash).ok_or(err::STASH_INVALID)?;
let ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?;
let now = <timestamp::Module<T>>::now().saturated_into::<Moment>();
let promise_month = promise_month.min(36);
match value {
StakingBalances::Ring(r) => {
let stash_balance = T::Ring::free_balance(&stash);
if let Some(extra) = stash_balance.checked_sub(&ledger.active_ring) {
let extra = extra.min(r);
Self::bond_helper_in_ring(&stash, &controller, extra, promise_month, ledger);
<RingPool<T>>::mutate(|r| *r += extra);
<Module<T>>::deposit_event(RawEvent::Bond(
StakingBalances::Ring(extra.saturated_into()),
now,
promise_month,
));
}
},
StakingBalances::Kton(k) => {
let stash_balance = T::Kton::free_balance(&stash);
if let Some(extra) = stash_balance.checked_sub(&ledger.active_kton) {
let extra = extra.min(k);
Self::bond_helper_in_kton(&controller, extra, ledger);
<KtonPool<T>>::mutate(|k| *k += extra);
<Module<T>>::deposit_event(RawEvent::Bond(
StakingBalances::Kton(extra.saturated_into()),
now,
promise_month,
));
}
},
}
}
// TODO: doc
fn deposit_extra(origin, value: Ring<T>, promise_month: Moment) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?;
let promise_month = promise_month.max(3).min(36);
let now = <timestamp::Module<T>>::now();
let mut ledger = Self::clear_mature_deposits(ledger);
let StakingLedger {
stash,
active_ring,
active_deposit_ring,
deposit_items,
..
} = &mut ledger;
let value = value.min(*active_ring - *active_deposit_ring);
// for now, kton_return is free
// mint kton
let kton_return = inflation::compute_kton_return::<T>(value, promise_month);
let kton_positive_imbalance = T::Kton::deposit_creating(stash, kton_return);
T::KtonReward::on_unbalanced(kton_positive_imbalance);
*active_deposit_ring += value;
deposit_items.push(TimeDepositItem {
value,
start_time: now,
expire_time: now + T::Moment::saturated_from((promise_month * MONTH_IN_MILLISECONDS).into()),
});
<Ledger<T>>::insert(&controller, ledger);
<Module<T>>::deposit_event(RawEvent::Bond(
StakingBalances::Ring(value.saturated_into()),
now.saturated_into::<Moment>(),
promise_month,
));
}
/// for normal_ring or normal_kton, follow the original substrate pattern
/// for time_deposit_ring, transform it into normal_ring first
/// modify time_deposit_items and time_deposit_ring amount
/// Schedule a portion of the stash to be unlocked ready for transfer out after the bond
/// period ends. If this leaves an amount actively bonded less than
/// T::Currency::minimum_balance(), then it is increased to the full amount.
///
/// Once the unlock period is done, the funds will be withdrew automatically and ready for transfer.
///
/// No more than a limited number of unlocking chunks (see `MAX_UNLOCKING_CHUNKS`)
/// can co-exists at the same time. In that case, [`StakingLock::shrink`] need
/// to be called first to remove some of the chunks (if possible).
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
///
/// # <weight>
/// - Independent of the arguments. Limited but potentially exploitable complexity.
/// - Contains a limited number of reads.
/// - Each call (requires the remainder of the bonded balance to be above `minimum_balance`)
/// will cause a new entry to be inserted into a vector (`StakingLock.unbondings`) kept in storage.
/// - One DB entry.
/// </weight>
#[weight = SimpleDispatchInfo::FixedNormal(400_000)]
fn unbond(origin, value: StakingBalances<Ring<T>, Kton<T>>) {
let controller = ensure_signed(origin)?;
let mut ledger = Self::clear_mature_deposits(Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?);
let StakingLedger {
active_ring,
active_deposit_ring,
active_kton,
ring_staking_lock,
kton_staking_lock,
..
} = &mut ledger;
let now = <timestamp::Module<T>>::now();
ring_staking_lock.shrink(now);
kton_staking_lock.shrink(now);
// due to the macro parser, we've to add a bracket
// actually, this's totally wrong:
// `a as u32 + b as u32 < c`
// workaround:
// 1. `(a as u32 + b as u32) < c`
// 2. `let c_ = a as u32 + b as u32; c_ < c`
ensure!(
(ring_staking_lock.unbondings.len() as u32 + kton_staking_lock.unbondings.len() as u32) < MAX_UNLOCKING_CHUNKS,
err::UNLOCK_CHUNKS_REACH_MAX,
);
match value {
StakingBalances::Ring(r) => {
// only active normal ring can be unbond
// active_ring = active_normal_ring + active_deposit_ring
let active_normal_ring = *active_ring - *active_deposit_ring;
let available_unbond_ring = r.min(active_normal_ring);
if !available_unbond_ring.is_zero() {
*active_ring -= available_unbond_ring;
ring_staking_lock.unbondings.push(NormalLock {
amount: available_unbond_ring,
until: now + T::BondingDuration::get(),
});
Self::update_ledger(&controller, &mut ledger, value);
<RingPool<T>>::mutate(|r| *r -= available_unbond_ring);
<Module<T>>::deposit_event(RawEvent::Unbond(
StakingBalances::Ring(available_unbond_ring.saturated_into()),
now.saturated_into::<Moment>(),
));
}
},
StakingBalances::Kton(k) => {
let unbond_kton = k.min(*active_kton);
if !unbond_kton.is_zero() {
*active_kton -= unbond_kton;
kton_staking_lock.unbondings.push(NormalLock {
amount: unbond_kton,
until: now + T::BondingDuration::get(),
});
Self::update_ledger(&controller, &mut ledger, value);
<KtonPool<T>>::mutate(|k| *k -= unbond_kton);
<Module<T>>::deposit_event(RawEvent::Unbond(
StakingBalances::Kton(unbond_kton.saturated_into()),
now.saturated_into::<Moment>(),
));
}
},
}
}
// TODO: doc
fn claim_mature_deposits(origin) {
let controller = ensure_signed(origin)?;
let ledger = Self::clear_mature_deposits(Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?);
<Ledger<T>>::insert(controller, ledger);
}
// TODO: doc
fn try_claim_deposits_with_punish(origin, expire_time: T::Moment) {
let controller = ensure_signed(origin)?;
let mut ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?;
let now = <timestamp::Module<T>>::now();
ensure!(expire_time > now, err::CLAIM_DEPOSITS_EXPIRE_TIME_INVALID);
let StakingLedger {
stash,
active_deposit_ring,
deposit_items,
..
} = &mut ledger;
deposit_items.retain(|item| {
if item.expire_time != expire_time {
return true;
}
let kton_slash = {
let passed_duration = (now - item.start_time).saturated_into::<Moment>() / MONTH_IN_MILLISECONDS;
let plan_duration = (item.expire_time - item.start_time).saturated_into::<Moment>() / MONTH_IN_MILLISECONDS;
(
inflation::compute_kton_return::<T>(item.value, plan_duration)
-
inflation::compute_kton_return::<T>(item.value, passed_duration)
).max(1.into()) * 3.into()
};
// check total free balance and locked one
// strict on punishing in kton
if T::Kton::free_balance(stash)
.checked_sub(&kton_slash)
.and_then(|new_balance| {
T::Kton::ensure_can_withdraw(
stash,
kton_slash,
WithdrawReason::Transfer.into(),
new_balance
).ok()
})
.is_some()
{
*active_deposit_ring = active_deposit_ring.saturating_sub(item.value);
let (imbalance, _) = T::Kton::slash(stash, kton_slash);
T::KtonSlash::on_unbalanced(imbalance);
false
} else {
true
}
});
<Ledger<T>>::insert(&controller, ledger);
}
/// Declare the desire to validate for the origin controller.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
///
/// # <weight>
/// - Independent of the arguments. Insignificant complexity.
/// - Contains a limited number of reads.
/// - Writes are limited to the `origin` account key.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn validate(origin, prefs: ValidatorPrefs) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?;
prefs.check_node_name()?;
let stash = &ledger.stash;
let mut prefs = prefs;
// at most 100%
prefs.validator_payment_ratio = prefs.validator_payment_ratio.min(100);
<Nominators<T>>::remove(stash);
<Validators<T>>::mutate(stash, |prefs_| {
let exists = !prefs_.node_name.is_empty();
*prefs_ = prefs;
if exists {
Self::deposit_event(RawEvent::NodeNameUpdated);
}
});
}
/// Declare the desire to nominate `targets` for the origin controller.
///
/// Effects will be felt at the beginning of the next era.
///
/// The dispatch origin for this call must be _Signed_ by the controller, not the stash.
///
/// # <weight>
/// - The transaction's complexity is proportional to the size of `targets`,
/// which is capped at `MAX_NOMINATIONS`.
/// - Both the reads and writes follow a similar pattern.
/// # </weight>
#[weight = SimpleDispatchInfo::FixedNormal(750_000)]
fn nominate(origin, targets: Vec<<T::Lookup as StaticLookup>::Source>) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or(err::CONTROLLER_INVALID)?;
let stash = &ledger.stash;
ensure!(!targets.is_empty(), err::TARGETS_INVALID);
let targets = targets.into_iter()
.take(MAX_NOMINATIONS)
.map(T::Lookup::lookup)
.collect::<result::Result<Vec<T::AccountId>, _>>()?;