1#![cfg_attr(not(feature = "std"), no_std)]
19
20extern crate alloc;
24
25use crate::currency_to_vote::CurrencyToVote;
26use alloc::{collections::btree_map::BTreeMap, vec, vec::Vec};
27use codec::{Decode, DecodeWithMemTracking, Encode, FullCodec, HasCompact, MaxEncodedLen};
28use core::ops::{Add, AddAssign, Sub, SubAssign};
29use scale_info::TypeInfo;
30use sp_runtime::{
31 traits::{AtLeast32BitUnsigned, Zero},
32 Debug, DispatchError, DispatchResult, Perbill, Saturating, Weight,
33};
34
35pub mod budget;
36pub mod offence;
37
38pub mod currency_to_vote;
39
40pub type SessionIndex = u32;
42
43pub type EraIndex = u32;
45
46pub type Page = u32;
48
49#[derive(
51 Clone,
52 Copy,
53 PartialEq,
54 Eq,
55 Debug,
56 Encode,
57 Decode,
58 DecodeWithMemTracking,
59 TypeInfo,
60 MaxEncodedLen,
61)]
62#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
63pub enum ServiceKind {
64 #[codec(index = 0)]
66 RelayConsensus,
67 #[codec(index = 1)]
69 Collation,
70}
71
72pub trait RewardPoints<AccountId> {
74 fn reward(service: ServiceKind, points: Vec<(AccountId, u32)>);
76
77 fn weight(entries: u32) -> Weight;
79}
80
81pub trait RewardsReporter<ValidatorId> {
86 fn reward_by_ids(validators_points: impl IntoIterator<Item = (ValidatorId, u32)>);
87}
88
89impl RewardsReporter<sp_runtime::AccountId32> for () {
90 fn reward_by_ids(_validators_points: impl IntoIterator<Item = (sp_runtime::AccountId32, u32)>) {
91 }
92}
93
94#[derive(Clone, Debug)]
99pub enum StakingAccount<AccountId> {
100 Stash(AccountId),
101 Controller(AccountId),
102}
103
104#[cfg(feature = "std")]
105impl<AccountId> From<AccountId> for StakingAccount<AccountId> {
106 fn from(account: AccountId) -> Self {
107 StakingAccount::Stash(account)
108 }
109}
110
111#[derive(Debug, TypeInfo)]
113#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone))]
114pub enum StakerStatus<AccountId> {
115 Idle,
117 Validator,
119 Nominator(Vec<AccountId>),
121}
122
123#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
126pub struct Stake<Balance> {
127 pub total: Balance,
137 pub active: Balance,
140}
141
142#[impl_trait_for_tuples::impl_for_tuples(10)]
148pub trait OnStakingUpdate<AccountId, Balance> {
149 fn on_stake_update(_who: &AccountId, _prev_stake: Option<Stake<Balance>>) {}
154
155 fn on_nominator_add(_who: &AccountId) {}
159
160 fn on_nominator_update(_who: &AccountId, _prev_nominations: Vec<AccountId>) {}
166
167 fn on_nominator_remove(_who: &AccountId, _nominations: Vec<AccountId>) {}
172
173 fn on_validator_add(_who: &AccountId) {}
177
178 fn on_validator_update(_who: &AccountId) {}
182
183 fn on_validator_remove(_who: &AccountId) {}
185
186 fn on_unstake(_who: &AccountId) {}
188
189 fn on_slash(
197 _stash: &AccountId,
198 _slashed_active: Balance,
199 _slashed_unlocking: &BTreeMap<EraIndex, Balance>,
200 _slashed_total: Balance,
201 ) {
202 }
203
204 fn on_withdraw(_stash: &AccountId, _amount: Balance) {}
206}
207
208pub trait StakingInterface {
213 type Balance: Sub<Output = Self::Balance>
215 + Ord
216 + PartialEq
217 + Default
218 + Copy
219 + MaxEncodedLen
220 + FullCodec
221 + TypeInfo
222 + Saturating;
223
224 type AccountId: Clone + core::fmt::Debug;
226
227 type CurrencyToVote: CurrencyToVote<Self::Balance>;
229
230 fn minimum_nominator_bond() -> Self::Balance;
235
236 fn minimum_validator_bond() -> Self::Balance;
238
239 fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError>;
246
247 fn bonding_duration() -> EraIndex;
251
252 fn nominator_bonding_duration() -> EraIndex {
263 Self::bonding_duration()
264 }
265
266 fn current_era() -> EraIndex;
270
271 fn stake(who: &Self::AccountId) -> Result<Stake<Self::Balance>, DispatchError>;
273
274 fn total_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
276 Self::stake(who).map(|s| s.total)
277 }
278
279 fn active_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
281 Self::stake(who).map(|s| s.active)
282 }
283
284 fn is_unbonding(who: &Self::AccountId) -> Result<bool, DispatchError> {
286 Self::stake(who).map(|s| s.active != s.total)
287 }
288
289 fn fully_unbond(who: &Self::AccountId) -> DispatchResult {
291 Self::unbond(who, Self::stake(who)?.active)
292 }
293
294 fn bond(who: &Self::AccountId, value: Self::Balance, payee: &Self::AccountId)
296 -> DispatchResult;
297
298 fn nominate(who: &Self::AccountId, validators: Vec<Self::AccountId>) -> DispatchResult;
300
301 fn chill(who: &Self::AccountId) -> DispatchResult;
303
304 fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult;
308
309 fn unbond(stash: &Self::AccountId, value: Self::Balance) -> DispatchResult;
319
320 fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult;
322
323 fn withdraw_unbonded(
327 stash: Self::AccountId,
328 num_slashing_spans: u32,
329 ) -> Result<bool, DispatchError>;
330
331 fn desired_validator_count() -> u32;
333
334 fn election_ongoing() -> bool;
336
337 fn force_unstake(who: Self::AccountId) -> DispatchResult;
339
340 fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool;
342
343 fn status(who: &Self::AccountId) -> Result<StakerStatus<Self::AccountId>, DispatchError>;
345
346 fn is_validator(who: &Self::AccountId) -> bool {
348 Self::status(who).map(|s| matches!(s, StakerStatus::Validator)).unwrap_or(false)
349 }
350
351 fn is_virtual_staker(who: &Self::AccountId) -> bool;
357
358 fn nominations(who: &Self::AccountId) -> Option<Vec<Self::AccountId>> {
360 match Self::status(who) {
361 Ok(StakerStatus::Nominator(t)) => Some(t),
362 _ => None,
363 }
364 }
365
366 fn slash_reward_fraction() -> Perbill;
368
369 #[cfg(feature = "runtime-benchmarks")]
370 fn max_exposure_page_size() -> Page;
371
372 #[cfg(feature = "runtime-benchmarks")]
373 fn add_era_stakers(
374 current_era: &EraIndex,
375 stash: &Self::AccountId,
376 exposures: Vec<(Self::AccountId, Self::Balance)>,
377 );
378
379 #[cfg(any(feature = "std", feature = "runtime-benchmarks"))]
381 fn set_era(era: EraIndex);
382}
383
384pub trait StakingUnchecked: StakingInterface {
389 fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult;
393
394 fn virtual_bond(
400 keyless_who: &Self::AccountId,
401 value: Self::Balance,
402 payee: &Self::AccountId,
403 ) -> DispatchResult;
404
405 #[cfg(feature = "runtime-benchmarks")]
409 fn migrate_to_direct_staker(who: &Self::AccountId);
410}
411
412#[derive(
414 PartialEq,
415 Eq,
416 PartialOrd,
417 Ord,
418 Clone,
419 Encode,
420 Decode,
421 DecodeWithMemTracking,
422 Debug,
423 TypeInfo,
424 Copy,
425)]
426pub struct IndividualExposure<AccountId, Balance: HasCompact> {
427 pub who: AccountId,
429 #[codec(compact)]
431 pub value: Balance,
432}
433
434#[derive(
436 PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo,
437)]
438pub struct Exposure<AccountId, Balance: HasCompact> {
439 #[codec(compact)]
441 pub total: Balance,
442 #[codec(compact)]
444 pub own: Balance,
445 pub others: Vec<IndividualExposure<AccountId, Balance>>,
447}
448
449impl<AccountId, Balance: Default + HasCompact> Default for Exposure<AccountId, Balance> {
450 fn default() -> Self {
451 Self { total: Default::default(), own: Default::default(), others: vec![] }
452 }
453}
454
455impl<
456 AccountId: Clone,
457 Balance: HasCompact + AtLeast32BitUnsigned + Copy + codec::MaxEncodedLen,
458 > Exposure<AccountId, Balance>
459{
460 pub fn split_others(&mut self, n_others: u32) -> Self {
468 let head_others: Vec<_> =
469 self.others.drain(..(n_others as usize).min(self.others.len())).collect();
470
471 let total_others_head: Balance = head_others
472 .iter()
473 .fold(Zero::zero(), |acc: Balance, o| acc.saturating_add(o.value));
474
475 self.total = self.total.saturating_sub(total_others_head);
476
477 Self {
478 total: total_others_head.saturating_add(self.own),
479 own: self.own,
480 others: head_others,
481 }
482 }
483
484 pub fn into_pages(
487 self,
488 page_size: Page,
489 ) -> (PagedExposureMetadata<Balance>, Vec<ExposurePage<AccountId, Balance>>) {
490 let individual_chunks = self.others.chunks(page_size as usize);
491 let mut exposure_pages: Vec<ExposurePage<AccountId, Balance>> =
492 Vec::with_capacity(individual_chunks.len());
493
494 for chunk in individual_chunks {
495 let mut page_total: Balance = Zero::zero();
496 let mut others: Vec<IndividualExposure<AccountId, Balance>> =
497 Vec::with_capacity(chunk.len());
498 for individual in chunk.iter() {
499 page_total.saturating_accrue(individual.value);
500 others.push(IndividualExposure {
501 who: individual.who.clone(),
502 value: individual.value,
503 })
504 }
505 exposure_pages.push(ExposurePage { page_total, others });
506 }
507
508 (
509 PagedExposureMetadata {
510 total: self.total,
511 own: self.own,
512 nominator_count: self.others.len() as u32,
513 page_count: exposure_pages.len() as Page,
514 },
515 exposure_pages,
516 )
517 }
518}
519
520#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Debug, TypeInfo)]
522pub struct ExposurePage<AccountId, Balance: HasCompact> {
523 #[codec(compact)]
525 pub page_total: Balance,
526 pub others: Vec<IndividualExposure<AccountId, Balance>>,
528}
529
530impl<A, B: Default + HasCompact> Default for ExposurePage<A, B> {
531 fn default() -> Self {
532 ExposurePage { page_total: Default::default(), others: vec![] }
533 }
534}
535
536impl<A, B: HasCompact + Default + AddAssign + SubAssign + Clone> From<Vec<IndividualExposure<A, B>>>
538 for ExposurePage<A, B>
539{
540 fn from(exposures: Vec<IndividualExposure<A, B>>) -> Self {
541 exposures.into_iter().fold(ExposurePage::default(), |mut page, e| {
542 page.page_total += e.value.clone();
543 page.others.push(e);
544 page
545 })
546 }
547}
548
549#[derive(
555 PartialEq,
556 Eq,
557 PartialOrd,
558 Ord,
559 Clone,
560 Encode,
561 Decode,
562 Debug,
563 TypeInfo,
564 Default,
565 MaxEncodedLen,
566 Copy,
567)]
568pub struct PagedExposureMetadata<Balance: HasCompact + codec::MaxEncodedLen> {
569 #[codec(compact)]
571 pub total: Balance,
572 #[codec(compact)]
574 pub own: Balance,
575 pub nominator_count: u32,
577 pub page_count: Page,
579}
580
581impl<Balance> PagedExposureMetadata<Balance>
582where
583 Balance: HasCompact
584 + codec::MaxEncodedLen
585 + Add<Output = Balance>
586 + Sub<Output = Balance>
587 + sp_runtime::Saturating
588 + PartialEq
589 + Copy
590 + sp_runtime::traits::Debug,
591{
592 pub fn update_with<Max: sp_core::Get<u32>>(
597 self,
598 others_balance: Balance,
599 others_num: u32,
600 ) -> Self {
601 let page_limit = Max::get().max(1);
602 let new_nominator_count = self.nominator_count.saturating_add(others_num);
603 let new_page_count = new_nominator_count
604 .saturating_add(page_limit)
605 .saturating_sub(1)
606 .saturating_div(page_limit);
607
608 Self {
609 total: self.total.saturating_add(others_balance),
610 own: self.own,
611 nominator_count: new_nominator_count,
612 page_count: new_page_count,
613 }
614 }
615}
616
617#[derive(Clone, Debug)]
627pub struct Agent<T>(T);
628impl<T> From<T> for Agent<T> {
629 fn from(acc: T) -> Self {
630 Agent(acc)
631 }
632}
633
634impl<T> Agent<T> {
635 pub fn get(self) -> T {
636 self.0
637 }
638}
639
640#[derive(Clone, Debug)]
645pub struct Delegator<T>(T);
646impl<T> From<T> for Delegator<T> {
647 fn from(acc: T) -> Self {
648 Delegator(acc)
649 }
650}
651
652impl<T> Delegator<T> {
653 pub fn get(self) -> T {
654 self.0
655 }
656}
657
658pub trait DelegationInterface {
660 type Balance: Sub<Output = Self::Balance>
662 + Ord
663 + PartialEq
664 + Default
665 + Copy
666 + MaxEncodedLen
667 + FullCodec
668 + TypeInfo
669 + Saturating;
670
671 type AccountId: Clone + core::fmt::Debug;
673
674 fn agent_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
678
679 fn agent_transferable_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
682
683 fn delegator_balance(delegator: Delegator<Self::AccountId>) -> Option<Self::Balance>;
685
686 fn register_agent(
688 agent: Agent<Self::AccountId>,
689 reward_account: &Self::AccountId,
690 ) -> DispatchResult;
691
692 fn remove_agent(agent: Agent<Self::AccountId>) -> DispatchResult;
696
697 fn delegate(
699 delegator: Delegator<Self::AccountId>,
700 agent: Agent<Self::AccountId>,
701 amount: Self::Balance,
702 ) -> DispatchResult;
703
704 fn withdraw_delegation(
709 delegator: Delegator<Self::AccountId>,
710 agent: Agent<Self::AccountId>,
711 amount: Self::Balance,
712 num_slashing_spans: u32,
713 ) -> DispatchResult;
714
715 fn pending_slash(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
720
721 fn delegator_slash(
726 agent: Agent<Self::AccountId>,
727 delegator: Delegator<Self::AccountId>,
728 value: Self::Balance,
729 maybe_reporter: Option<Self::AccountId>,
730 ) -> DispatchResult;
731}
732
733pub trait DelegationMigrator {
736 type Balance: Sub<Output = Self::Balance>
738 + Ord
739 + PartialEq
740 + Default
741 + Copy
742 + MaxEncodedLen
743 + FullCodec
744 + TypeInfo
745 + Saturating;
746
747 type AccountId: Clone + core::fmt::Debug;
749
750 fn migrate_nominator_to_agent(
755 agent: Agent<Self::AccountId>,
756 reward_account: &Self::AccountId,
757 ) -> DispatchResult;
758
759 fn migrate_delegation(
764 agent: Agent<Self::AccountId>,
765 delegator: Delegator<Self::AccountId>,
766 value: Self::Balance,
767 ) -> DispatchResult;
768
769 #[cfg(feature = "runtime-benchmarks")]
773 fn force_kill_agent(agent: Agent<Self::AccountId>);
774}
775
776pub trait EraPayout<Balance> {
781 fn era_payout(
786 total_staked: Balance,
787 total_issuance: Balance,
788 era_duration_millis: u64,
789 ) -> (Balance, Balance);
790}
791
792impl<Balance: Default> EraPayout<Balance> for () {
793 fn era_payout(
794 _total_staked: Balance,
795 _total_issuance: Balance,
796 _era_duration_millis: u64,
797 ) -> (Balance, Balance) {
798 (Default::default(), Default::default())
799 }
800}
801
802#[derive(Debug, Clone, PartialEq, Eq)]
806pub struct StakerRewardResult<Balance> {
807 pub validator_payout: Balance,
809 pub nominator_payout: Balance,
811}
812
813pub trait StakerRewardCalculator<Balance> {
822 fn calculate_validator_incentive_weight(self_stake: Balance) -> Balance;
827
828 fn calculate_staker_reward(
830 validator_total_reward: Balance,
831 validator_commission: Perbill,
832 validator_own_stake: Balance,
833 total_exposure: Balance,
834 ) -> StakerRewardResult<Balance>;
835}
836
837impl<Balance: Default> StakerRewardCalculator<Balance> for () {
838 fn calculate_validator_incentive_weight(_self_stake: Balance) -> Balance {
839 Default::default()
840 }
841
842 fn calculate_staker_reward(
843 _validator_total_reward: Balance,
844 _validator_commission: Perbill,
845 _validator_own_stake: Balance,
846 _total_exposure: Balance,
847 ) -> StakerRewardResult<Balance> {
848 StakerRewardResult {
849 validator_payout: Default::default(),
850 nominator_payout: Default::default(),
851 }
852 }
853}
854
855sp_core::generate_feature_enabled_macro!(runtime_benchmarks_enabled, feature = "runtime-benchmarks", $);
856sp_core::generate_feature_enabled_macro!(std_or_benchmarks_enabled, any(feature = "std", feature = "runtime-benchmarks"), $);
857
858#[cfg(test)]
859mod tests {
860 use sp_core::ConstU32;
861
862 use super::*;
863
864 #[test]
865 fn update_with_works() {
866 let metadata = PagedExposureMetadata::<u32> {
867 total: 1000,
868 own: 0, nominator_count: 10,
870 page_count: 1,
871 };
872
873 assert_eq!(
874 metadata.update_with::<ConstU32<10>>(1, 1),
875 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 2 },
876 );
877
878 assert_eq!(
879 metadata.update_with::<ConstU32<5>>(1, 1),
880 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
881 );
882
883 assert_eq!(
884 metadata.update_with::<ConstU32<4>>(1, 1),
885 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
886 );
887
888 assert_eq!(
889 metadata.update_with::<ConstU32<1>>(1, 1),
890 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 11 },
891 );
892 }
893
894 #[test]
895 fn individual_exposures_to_exposure_works() {
896 let exposure_1 = IndividualExposure { who: 1, value: 10u32 };
897 let exposure_2 = IndividualExposure { who: 2, value: 20 };
898 let exposure_3 = IndividualExposure { who: 3, value: 30 };
899
900 let exposure_page: ExposurePage<u32, u32> = vec![exposure_1, exposure_2, exposure_3].into();
901
902 assert_eq!(
903 exposure_page,
904 ExposurePage { page_total: 60, others: vec![exposure_1, exposure_2, exposure_3] },
905 );
906 }
907
908 #[test]
909 fn empty_individual_exposures_to_exposure_works() {
910 let empty_exposures: Vec<IndividualExposure<u32, u32>> = vec![];
911
912 let exposure_page: ExposurePage<u32, u32> = empty_exposures.into();
913 assert_eq!(exposure_page, ExposurePage { page_total: 0, others: vec![] });
914 }
915
916 #[test]
917 fn exposure_split_others_works() {
918 let exposure = Exposure {
919 total: 100,
920 own: 20,
921 others: vec![
922 IndividualExposure { who: 1, value: 20u32 },
923 IndividualExposure { who: 2, value: 20 },
924 IndividualExposure { who: 3, value: 20 },
925 IndividualExposure { who: 4, value: 20 },
926 ],
927 };
928
929 let mut exposure_0 = exposure.clone();
930 let split_exposure = exposure_0.split_others(0);
933 assert_eq!(exposure_0, exposure);
934 assert_eq!(split_exposure, Exposure { total: 20, own: 20, others: vec![] });
935
936 let mut exposure_1 = exposure.clone();
937 let split_exposure = exposure_1.split_others(1);
939 assert_eq!(exposure_1.own, 20);
940 assert_eq!(exposure_1.total, 20 + 3 * 20);
941 assert_eq!(exposure_1.others.len(), 3);
942
943 assert_eq!(split_exposure.own, 20);
944 assert_eq!(split_exposure.total, 20 + 1 * 20);
945 assert_eq!(split_exposure.others.len(), 1);
946
947 let mut exposure_3 = exposure.clone();
948 let split_exposure = exposure_3.split_others(3);
951 assert_eq!(exposure_3.own, 20);
952 assert_eq!(exposure_3.total, 20 + 1 * 20);
953 assert_eq!(exposure_3.others.len(), 1);
954
955 assert_eq!(split_exposure.own, 20);
956 assert_eq!(split_exposure.total, 20 + 3 * 20);
957 assert_eq!(split_exposure.others.len(), 3);
958
959 let mut exposure_max = exposure.clone();
960 let split_exposure = exposure_max.split_others(u32::MAX);
964 assert_eq!(split_exposure, exposure);
965 assert_eq!(exposure_max, Exposure { total: 20, own: 20, others: vec![] });
966 }
967}