-
Notifications
You must be signed in to change notification settings - Fork 49
Expand file tree
/
Copy pathlib.rs
More file actions
1537 lines (1310 loc) · 51.5 KB
/
lib.rs
File metadata and controls
1537 lines (1310 loc) · 51.5 KB
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)]
#![cfg_attr(all(feature = "bench", test), feature(test))]
#[cfg(all(feature = "bench", test))]
extern crate test;
pub mod inflation;
use codec::{Decode, Encode, HasCompact};
use rstd::{borrow::ToOwned, convert::TryInto, prelude::*, result};
use session::{historical::OnSessionEnding, SelectInitialValidators};
use sr_primitives::{
traits::{CheckedSub, Convert, One, SaturatedConversion, Saturating, StaticLookup, Zero},
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, WithdrawReason, WithdrawReasons},
};
use system::{ensure_root, ensure_signed};
use darwinia_support::{LockIdentifier, LockableCurrency, NormalLock, StakingLock, TimeStamp, WithdrawLock};
use phragmen::{build_support_map, elect, equalize, ExtendedBalance, PhragmenStakedAssignment};
#[allow(unused)]
#[cfg(any(feature = "bench", test))]
mod mock;
//
#[cfg(test)]
mod tests;
//#[cfg(all(feature = "bench", test))]
//mod benches;
const DEFAULT_MINIMUM_VALIDATOR_COUNT: u32 = 4;
const MAX_NOMINATIONS: usize = 16;
const MAX_UNSTAKE_THRESHOLD: u32 = 10;
const MAX_UNLOCKING_CHUNKS: u32 = 32;
const MONTH_IN_SECONDS: u32 = 2_592_000;
const STAKING_ID: LockIdentifier = *b"staking ";
/// 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;
/// 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
}
}
}
#[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>),
}
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct ValidatorPrefs {
/// Validator should ensure this many more slashes than is necessary before being unstaked.
#[codec(compact)]
pub unstake_threshold: u32,
/// percent of Reward that validator takes up-front; only the rest is split between themselves and
/// nominators.
pub validator_payment_ratio: Perbill,
}
impl Default for ValidatorPrefs {
fn default() -> Self {
ValidatorPrefs {
unstake_threshold: 3,
validator_payment_ratio: Default::default(),
}
}
}
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub enum StakingBalance<Ring, Kton> {
Ring(Ring),
Kton(Kton),
}
impl<Ring: Default, Kton: Default> Default for StakingBalance<Ring, Kton> {
fn default() -> Self {
StakingBalance::Ring(Default::default())
}
}
/// 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
}
}
#[derive(PartialEq, Eq, Clone, Encode, Decode, RuntimeDebug)]
pub struct TimeDepositItem<Ring: HasCompact, Moment> {
#[codec(compact)]
value: Ring,
#[codec(compact)]
start_time: Moment,
#[codec(compact)]
expire_time: Moment,
}
#[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, TimeStamp>,
pub kton_staking_lock: StakingLock<Kton, TimeStamp>,
}
/// 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> {
/// The stash account of the nominator in question.
who: AccountId,
/// Amount of funds exposed.
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> {
/// The total balance backing this validator.
pub total: Power,
/// The validator's own stash that is exposed.
pub own: Power,
/// The portions of nominators stashes that are exposed.
pub others: Vec<IndividualExposure<AccountId, Power>>,
}
/// 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, Balance: HasCompact> {
who: AccountId,
amount: Balance,
own_slash: Balance, // the amount of `who`'s own exposure that was slashed
}
type RingBalanceOf<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::Balance;
type KtonBalanceOf<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::Balance;
// for ring
type RingPositiveImbalanceOf<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
type RingNegativeImbalanceOf<T> = <<T as Trait>::Ring as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
// for kton
type KtonPositiveImbalanceOf<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::PositiveImbalance;
type KtonNegativeImbalanceOf<T> = <<T as Trait>::Kton as Currency<<T as system::Trait>::AccountId>>::NegativeImbalance;
type MomentOf<T> = <<T as Trait>::Time as Time>::Moment;
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, ExtendedBalance>,
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 {
type Ring: LockableCurrency<Self::AccountId, Moment = Self::Moment>;
type Kton: LockableCurrency<Self::AccountId, Moment = Self::Moment>;
/// Time used for computing era duration.
type Time: Time;
type CurrencyToVote: Convert<ExtendedBalance, u64> + Convert<u128, ExtendedBalance>;
type RingRewardRemainder: OnUnbalanced<RingNegativeImbalanceOf<Self>>;
/// The overarching event type.
type Event: From<Event<Self>> + Into<<Self as system::Trait>::Event>;
/// Handler for the unbalanced reduction when slashing a staker.
type RingSlash: OnUnbalanced<RingNegativeImbalanceOf<Self>>;
/// Handler for the unbalanced increment when rewarding a staker.
type RingReward: OnUnbalanced<RingPositiveImbalanceOf<Self>>;
type KtonSlash: OnUnbalanced<KtonNegativeImbalanceOf<Self>>;
type KtonReward: OnUnbalanced<KtonPositiveImbalanceOf<Self>>;
/// Number of sessions per era.
type SessionsPerEra: Get<SessionIndex>;
/// Number of seconds that staked funds must remain bonded for.
type BondingDuration: Get<TimeStamp>;
// custom
type Cap: Get<<Self::Ring as Currency<Self::AccountId>>::Balance>;
type GenesisTime: Get<MomentOf<Self>>;
type ErasPerEpoch: Get<EraIndex>;
/// Interface for interacting with a session module.
type SessionInterface: self::SessionInterface<Self::AccountId>;
}
/// 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 {
pub ValidatorCount get(validator_count) config(): u32;
pub MinimumValidatorCount get(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>;
pub SessionReward get(session_reward) config(): Perbill = Perbill::from_percent(60);
pub Bonded get(bonded): map T::AccountId => Option<T::AccountId>;
pub Ledger get(ledger): map T::AccountId => Option<StakingLedger<T::AccountId, RingBalanceOf<T>, KtonBalanceOf<T>, T::Moment>>;
pub Payee get(payee): map T::AccountId => RewardDestination;
pub Validators get(validators): linked_map T::AccountId => ValidatorPrefs;
pub Nominators get(nominators): linked_map T::AccountId => Vec<T::AccountId>;
pub Stakers get(stakers): map T::AccountId => Exposure<T::AccountId, ExtendedBalance>;
pub CurrentElected get(current_elected): Vec<T::AccountId>;
pub CurrentEra get(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): ExtendedBalance;
/// 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;
/// 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, ExtendedBalance>>;
pub NodeName get(node_name): map T::AccountId => Vec<u8>;
pub RingPool get(ring_pool): RingBalanceOf<T>;
pub KtonPool get(kton_pool): KtonBalanceOf<T>;
}
add_extra_genesis {
config(stakers):
Vec<(T::AccountId, T::AccountId, RingBalanceOf<T>, StakerStatus<T::AccountId>)>;
build(| config: &GenesisConfig<T>| {
for &(ref stash, ref controller, balance, ref status) in &config.stakers {
assert!(T::Ring::free_balance(&stash) >= balance);
let _ = <Module<T>>::bond(
T::Origin::from(Some(stash.clone()).into()),
T::Lookup::unlookup(controller.clone()),
StakingBalance::Ring(balance),
RewardDestination::Stash,
12
);
let _ = match status {
StakerStatus::Validator => {
<Module<T>>::validate(
T::Origin::from(Some(controller.clone()).into()),
[0;8].to_vec(),
0,
3
)
},
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 Balance = RingBalanceOf<T>, <T as system::Trait>::AccountId {
/// All validators have been rewarded by the given balance.
Reward(Balance, Balance),
// TODO: refactor to Balance later?
Slash(AccountId, ExtendedBalance),
OldSlashingReportDiscarded(SessionIndex),
/// NodeName changed
NodeNameUpdated,
}
);
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 eras that staked funds must remain bonded for.
const BondingDuration: TimeStamp = T::BondingDuration::get();
fn deposit_event() = default;
fn bond(
origin,
controller: <T::Lookup as StaticLookup>::Source,
value: StakingBalance<RingBalanceOf<T>, KtonBalanceOf<T>>,
payee: RewardDestination,
promise_month: u32
) {
let stash = ensure_signed(origin)?;
if <Bonded<T>>::exists(&stash) {
return Err("stash already bonded")
}
let controller = T::Lookup::lookup(controller)?;
if <Ledger<T>>::exists(&controller) {
return Err("controller already paired")
}
ensure!(promise_month <= 36, "months at most is 36.");
<Bonded<T>>::insert(&stash, &controller);
<Payee<T>>::insert(&stash, payee);
let ledger = StakingLedger {stash: stash.clone(), ..Default::default()};
match value {
StakingBalance::Ring(r) => {
let stash_balance = T::Ring::free_balance(&stash);
let value = r.min(stash_balance);
// increase ring pool
<RingPool<T>>::mutate(|r| *r += value);
Self::bond_helper_in_ring(&stash, &controller, value, promise_month, ledger);
},
StakingBalance::Kton(k) => {
let stash_balance = T::Kton::free_balance(&stash);
let value: KtonBalanceOf<T> = k.min(stash_balance);
// increase kton pool
<KtonPool<T>>::mutate(|k| *k += value);
Self::bond_helper_in_kton(&controller, value, ledger);
},
}
}
fn bond_extra(
origin,
value: StakingBalance<RingBalanceOf<T>, KtonBalanceOf<T>>,
promise_month: u32
) {
let stash = ensure_signed(origin)?;
let controller = Self::bonded(&stash).ok_or("not a stash")?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
ensure!(promise_month <= 36, "months at most is 36.");
match value {
StakingBalance::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);
<RingPool<T>>::mutate(|r| *r += extra);
Self::bond_helper_in_ring(&stash, &controller, extra, promise_month, ledger);
}
},
StakingBalance::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);
<KtonPool<T>>::mutate(|k| *k += extra);
Self::bond_helper_in_kton(&controller, extra, ledger);
}
},
}
}
/// 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
fn unbond(origin, value: StakingBalance<RingBalanceOf<T>, KtonBalanceOf<T>>) {
let controller = ensure_signed(origin)?;
Self::clear_mature_deposits(&controller);
let mut ledger = Self::ledger(&controller).ok_or("not a controller")?;
let StakingLedger {
active_ring,
active_deposit_ring,
active_kton,
ring_staking_lock,
kton_staking_lock,
..
} = &mut ledger;
ensure!(
ring_staking_lock.unbondings.len() + kton_staking_lock.unbondings.len() < MAX_UNLOCKING_CHUNKS.try_into().unwrap(),
"can not schedule more unlock chunks"
);
let at = <timestamp::Module<T>>::now().saturated_into::<TimeStamp>() + T::BondingDuration::get();
match value {
StakingBalance::Ring(r) => {
// total_active_ring = normal_ring + time_deposit_ring
// Only active normal ring can be unbond
let active_normal_ring = *active_ring - *active_deposit_ring;
// unbond normal ring first
let available_unbond_ring = r.min(active_normal_ring);
<RingPool<T>>::mutate(|r| *r -= available_unbond_ring);
if !available_unbond_ring.is_zero() {
*active_ring -= available_unbond_ring;
ring_staking_lock.unbondings.push(NormalLock { amount: available_unbond_ring, until: at });
Self::update_ledger(&controller, &mut ledger, value);
}
},
StakingBalance::Kton(k) => {
let unbond_kton = k.min(*active_kton);
if !unbond_kton.is_zero() {
<KtonPool<T>>::mutate(|k| *k -= unbond_kton);
*active_kton -= unbond_kton;
kton_staking_lock.unbondings.push(NormalLock { amount: unbond_kton, until: at });
Self::update_ledger(&controller, &mut ledger, value);
}
},
}
}
/// called by controller
fn deposit_extra(origin, value: RingBalanceOf<T>, promise_month: u32) {
let controller = ensure_signed(origin)?;
if Self::ledger(&controller).is_none() { return Err("not a controller"); }
ensure!(promise_month >= 3 && promise_month <= 36, "months at least is 3 and at most is 36.");
Self::clear_mature_deposits(&controller);
let now = <timestamp::Module<T>>::now();
let mut ledger = Self::ledger(&controller).unwrap();
let StakingLedger {
stash,
active_ring,
active_deposit_ring,
deposit_items,
..
} = &mut ledger;
let value = value.min(*active_ring - *active_deposit_ring); // active_normal_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 + (MONTH_IN_SECONDS * promise_month).into(),
});
<Ledger<T>>::insert(&controller, ledger);
}
fn claim_mature_deposits(origin) {
let controller = ensure_signed(origin)?;
Self::clear_mature_deposits(&controller);
}
fn claim_deposits_with_punish(origin, expire_time: T::Moment) {
let controller = ensure_signed(origin)?;
let mut ledger = Self::ledger(&controller).ok_or("not a controller")?;
let now = <timestamp::Module<T>>::now();
ensure!(expire_time > now, "use unbond instead.");
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::<u32>() / MONTH_IN_SECONDS;
let plan_duration = (item.expire_time - item.start_time).saturated_into::<u32>() / MONTH_IN_SECONDS;
(
inflation::compute_kton_return::<T>(item.value, plan_duration)
-
inflation::compute_kton_return::<T>(item.value, passed_duration)
) * 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);
}
fn validate(origin, name: Vec<u8>, ratio: u32, unstake_threshold: u32) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
let stash = &ledger.stash;
ensure!(
unstake_threshold <= MAX_UNSTAKE_THRESHOLD,
"unstake threshold too large"
);
// at most 100%
let ratio = Perbill::from_percent(ratio.min(100));
let prefs = ValidatorPrefs { unstake_threshold: unstake_threshold, validator_payment_ratio: ratio };
<Nominators<T>>::remove(stash);
<Validators<T>>::insert(stash, prefs);
if !<NodeName<T>>::exists(&controller) {
<NodeName<T>>::insert(controller, name);
Self::deposit_event(RawEvent::NodeNameUpdated);
}
}
fn nominate(origin, targets: Vec<<T::Lookup as StaticLookup>::Source>) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
let stash = &ledger.stash;
ensure!(!targets.is_empty(), "targets cannot be empty");
let targets = targets.into_iter()
.take(MAX_NOMINATIONS)
.map(T::Lookup::lookup)
.collect::<result::Result<Vec<T::AccountId>, _>>()?;
<Validators<T>>::remove(stash);
<Nominators<T>>::insert(stash, targets);
}
fn chill(origin) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
let stash = &ledger.stash;
<Validators<T>>::remove(stash);
<Nominators<T>>::remove(stash);
}
fn set_payee(origin, payee: RewardDestination) {
let controller = ensure_signed(origin)?;
let ledger = Self::ledger(&controller).ok_or("not a controller")?;
let stash = &ledger.stash;
<Payee<T>>::insert(stash, payee);
}
fn set_controller(origin, controller: <T::Lookup as StaticLookup>::Source) {
let stash = ensure_signed(origin)?;
let old_controller = Self::bonded(&stash).ok_or("not a stash")?;
let controller = T::Lookup::lookup(controller)?;
if <Ledger<T>>::exists(&controller) {
return Err("controller already paired")
}
if controller != old_controller {
<Bonded<T>>::insert(&stash, &controller);
if let Some(l) = <Ledger<T>>::take(&old_controller) {
<Ledger<T>>::insert(&controller, l);
}
}
}
/// The ideal number of validators.
fn set_validator_count(origin, #[compact] new: u32) {
ensure_root(origin)?;
ValidatorCount::put(new);
}
// ----- Root calls.
fn force_new_era(origin) {
ensure_root(origin)?;
ForceEra::put(Forcing::ForceNone);
}
/// Set the validators who cannot be slashed (if any).
fn set_invulnerables(origin, validators: Vec<T::AccountId>) {
ensure_root(origin)?;
<Invulnerables<T>>::put(validators);
}
}
}
impl<T: Trait> Module<T> {
pub fn clear_mature_deposits(controller: &T::AccountId) {
if let Some(mut ledger) = Self::ledger(&controller) {
let now = <timestamp::Module<T>>::now();
let StakingLedger {
active_deposit_ring,
deposit_items,
..
} = &mut ledger;
deposit_items.retain(|item| {
if item.expire_time > now {
true
} else {
*active_deposit_ring = active_deposit_ring.saturating_sub(item.value);
false
}
});
<Ledger<T>>::insert(controller, ledger);
};
}
fn bond_helper_in_ring(
stash: &T::AccountId,
controller: &T::AccountId,
value: RingBalanceOf<T>,
promise_month: u32,
mut ledger: StakingLedger<T::AccountId, RingBalanceOf<T>, KtonBalanceOf<T>, T::Moment>,
) {
// if stash promise to a extra-lock
// there will be extra reward, kton, which
// can also be use to stake.
if promise_month >= 3 {
ledger.active_deposit_ring += value;
// 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);
let now = <timestamp::Module<T>>::now();
let expire_time = now + (MONTH_IN_SECONDS * promise_month).into();
ledger.deposit_items.push(TimeDepositItem {
value,
start_time: now,
expire_time,
});
}
ledger.active_ring = ledger.active_ring.saturating_add(value);
Self::update_ledger(&controller, &mut ledger, StakingBalance::Ring(value));
}
fn bond_helper_in_kton(
controller: &T::AccountId,
value: KtonBalanceOf<T>,
mut ledger: StakingLedger<T::AccountId, RingBalanceOf<T>, KtonBalanceOf<T>, T::Moment>,
) {
ledger.active_kton += value;
Self::update_ledger(&controller, &mut ledger, StakingBalance::Kton(value));
}
fn update_ledger(
controller: &T::AccountId,
ledger: &mut StakingLedger<T::AccountId, RingBalanceOf<T>, KtonBalanceOf<T>, T::Moment>,
staking_balance: StakingBalance<RingBalanceOf<T>, KtonBalanceOf<T>>,
) {
match staking_balance {
StakingBalance::Ring(_r) => {
ledger.ring_staking_lock.staking_amount = ledger.active_ring;
T::Ring::set_lock(
STAKING_ID,
&ledger.stash,
WithdrawLock::WithStaking(ledger.ring_staking_lock.clone()),
WithdrawReasons::all(),
);
}
StakingBalance::Kton(_k) => {
ledger.kton_staking_lock.staking_amount = ledger.active_kton;
T::Kton::set_lock(
STAKING_ID,
&ledger.stash,
WithdrawLock::WithStaking(ledger.kton_staking_lock.clone()),
WithdrawReasons::all(),
);
}
}
<Ledger<T>>::insert(controller, ledger);
}
/// Slash a given validator by a specific amount with given (historical) exposure.
///
/// Removes the slash from the validator's balance by preference,
/// and reduces the nominators' balance if needed.
///
/// Returns the resulting `NegativeImbalance` to allow distributing the slashed amount and
/// pushes an entry onto the slash journal.
fn slash_validator(
stash: &T::AccountId,
slash: ExtendedBalance,
exposure: &Exposure<T::AccountId, ExtendedBalance>,
journal: &mut Vec<SlashJournalEntry<T::AccountId, ExtendedBalance>>,
) -> (RingNegativeImbalanceOf<T>, KtonNegativeImbalanceOf<T>) {
// The amount we are actually going to slash (can't be bigger than the validator's total
// exposure)
let slash = slash.min(exposure.total);
// limit what we'll slash of the stash's own to only what's in
// the exposure.
//
// note: this is fine only because we limit reports of the current era.
// otherwise, these funds may have already been slashed due to something
// reported from a prior era.
let already_slashed_own = journal
.iter()
.filter(|entry| &entry.who == stash)
.map(|entry| entry.own_slash)
.fold(ExtendedBalance::zero(), |a, c| a.saturating_add(c));
let own_remaining = exposure.own.saturating_sub(already_slashed_own);
// The amount we'll slash from the validator's stash directly.
let own_slash = own_remaining.min(slash);
let (mut ring_imbalance, mut kton_imbalance, missing) =
Self::slash_individual(stash, Perbill::from_rational_approximation(own_slash, exposure.own)); // T::Currency::slash(stash, own_slash);
let own_slash = own_slash - missing;
// The amount remaining that we can't slash from the validator,
// that must be taken from the nominators.
let rest_slash = slash - own_slash;
if !rest_slash.is_zero() {
// The total to be slashed from the nominators.
let total = exposure.total - exposure.own;
if !total.is_zero() {
for i in exposure.others.iter() {
let per_u64 = Perbill::from_rational_approximation(i.value, total);
// best effort - not much that can be done on fail.
// imbalance.subsume(T::Currency::slash(&i.who, per_u64 * rest_slash).0)
let (r, k, _) = Self::slash_individual(
&i.who,
Perbill::from_rational_approximation(per_u64 * rest_slash, i.value),
);
ring_imbalance.subsume(r);
kton_imbalance.subsume(k);
}
}
}
journal.push(SlashJournalEntry {
who: stash.to_owned(),
own_slash,
amount: slash,
});
// trigger the event
Self::deposit_event(RawEvent::Slash(stash.to_owned(), slash));
(ring_imbalance, kton_imbalance)
}
// TODO: there is reserve balance in Balance.Slash, we assuming it is zero for now.
fn slash_individual(
stash: &T::AccountId,
slash_ratio: Perbill,
) -> (RingNegativeImbalanceOf<T>, KtonNegativeImbalanceOf<T>, ExtendedBalance) {
let controller = Self::bonded(stash).unwrap();
let mut ledger = Self::ledger(&controller).unwrap();
// slash ring
let (ring_imbalance, _) = if !ledger.active_ring.is_zero() {
let slashable_ring = slash_ratio * ledger.active_ring;
let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalance::Ring(slashable_ring));
T::Ring::slash(stash, value_slashed.0)
} else {
(<RingNegativeImbalanceOf<T>>::zero(), Zero::zero())
};
let (kton_imbalance, _) = if !ledger.active_kton.is_zero() {
let slashable_kton = slash_ratio * ledger.active_kton;
let value_slashed = Self::slash_helper(&controller, &mut ledger, StakingBalance::Kton(slashable_kton));
T::Kton::slash(stash, value_slashed.1)
} else {
(<KtonNegativeImbalanceOf<T>>::zero(), Zero::zero())
};
(ring_imbalance, kton_imbalance, 0)
}
fn slash_helper(
controller: &T::AccountId,
ledger: &mut StakingLedger<T::AccountId, RingBalanceOf<T>, KtonBalanceOf<T>, T::Moment>,
value: StakingBalance<RingBalanceOf<T>, KtonBalanceOf<T>>,
) -> (RingBalanceOf<T>, KtonBalanceOf<T>) {
match value {
StakingBalance::Ring(r) => {
let StakingLedger {
active_ring,
active_deposit_ring,
deposit_items,
..
} = ledger;
// if slashing ring, first slashing normal ring
// then, slashing time-deposit ring
// TODO: check one more time (may be removed later)
let total_value = r.min(*active_ring);
let normal_active_value = total_value.min(*active_ring - *active_deposit_ring);
// to prevent overflow
// first slash normal bonded ring
<RingPool<T>>::mutate(|r| *r -= normal_active_value);
*active_ring -= normal_active_value;
// bonded + unbondings
// first slash active normal ring
let mut value_left = total_value - normal_active_value;
// then slash active time-promise ring
// from the nearest expire time
if !value_left.is_zero() {
// sorted by expire_time from far to near
deposit_items
.sort_unstable_by_key(|item| u64::max_value() - item.expire_time.saturated_into::<u64>());
deposit_items.drain_filter(|item| {
if value_left.is_zero() {
return false;
}
let value_removed = value_left.min(item.value);
*active_ring -= value_removed;
*active_deposit_ring -= value_removed;
item.value -= value_removed;