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,
33};
34
35pub mod offence;
36
37pub mod currency_to_vote;
38
39pub type SessionIndex = u32;
41
42pub type EraIndex = u32;
44
45pub type Page = u32;
47#[derive(Clone, Debug)]
52pub enum StakingAccount<AccountId> {
53 Stash(AccountId),
54 Controller(AccountId),
55}
56
57#[cfg(feature = "std")]
58impl<AccountId> From<AccountId> for StakingAccount<AccountId> {
59 fn from(account: AccountId) -> Self {
60 StakingAccount::Stash(account)
61 }
62}
63
64#[derive(Debug, TypeInfo)]
66#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize, PartialEq, Eq, Clone))]
67pub enum StakerStatus<AccountId> {
68 Idle,
70 Validator,
72 Nominator(Vec<AccountId>),
74}
75
76#[derive(Debug, Clone, Copy, Eq, PartialEq, Default)]
79pub struct Stake<Balance> {
80 pub total: Balance,
90 pub active: Balance,
93}
94
95#[impl_trait_for_tuples::impl_for_tuples(10)]
101pub trait OnStakingUpdate<AccountId, Balance> {
102 fn on_stake_update(_who: &AccountId, _prev_stake: Option<Stake<Balance>>) {}
107
108 fn on_nominator_add(_who: &AccountId) {}
112
113 fn on_nominator_update(_who: &AccountId, _prev_nominations: Vec<AccountId>) {}
119
120 fn on_nominator_remove(_who: &AccountId, _nominations: Vec<AccountId>) {}
125
126 fn on_validator_add(_who: &AccountId) {}
130
131 fn on_validator_update(_who: &AccountId) {}
135
136 fn on_validator_remove(_who: &AccountId) {}
138
139 fn on_unstake(_who: &AccountId) {}
141
142 fn on_slash(
150 _stash: &AccountId,
151 _slashed_active: Balance,
152 _slashed_unlocking: &BTreeMap<EraIndex, Balance>,
153 _slashed_total: Balance,
154 ) {
155 }
156
157 fn on_withdraw(_stash: &AccountId, _amount: Balance) {}
159}
160
161pub trait StakingInterface {
166 type Balance: Sub<Output = Self::Balance>
168 + Ord
169 + PartialEq
170 + Default
171 + Copy
172 + MaxEncodedLen
173 + FullCodec
174 + TypeInfo
175 + Saturating;
176
177 type AccountId: Clone + core::fmt::Debug;
179
180 type CurrencyToVote: CurrencyToVote<Self::Balance>;
182
183 fn minimum_nominator_bond() -> Self::Balance;
188
189 fn minimum_validator_bond() -> Self::Balance;
191
192 fn stash_by_ctrl(controller: &Self::AccountId) -> Result<Self::AccountId, DispatchError>;
199
200 fn bonding_duration() -> EraIndex;
204
205 fn nominator_bonding_duration() -> EraIndex {
216 Self::bonding_duration()
217 }
218
219 fn current_era() -> EraIndex;
223
224 fn stake(who: &Self::AccountId) -> Result<Stake<Self::Balance>, DispatchError>;
226
227 fn total_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
229 Self::stake(who).map(|s| s.total)
230 }
231
232 fn active_stake(who: &Self::AccountId) -> Result<Self::Balance, DispatchError> {
234 Self::stake(who).map(|s| s.active)
235 }
236
237 fn is_unbonding(who: &Self::AccountId) -> Result<bool, DispatchError> {
239 Self::stake(who).map(|s| s.active != s.total)
240 }
241
242 fn fully_unbond(who: &Self::AccountId) -> DispatchResult {
244 Self::unbond(who, Self::stake(who)?.active)
245 }
246
247 fn bond(who: &Self::AccountId, value: Self::Balance, payee: &Self::AccountId)
249 -> DispatchResult;
250
251 fn nominate(who: &Self::AccountId, validators: Vec<Self::AccountId>) -> DispatchResult;
253
254 fn chill(who: &Self::AccountId) -> DispatchResult;
256
257 fn bond_extra(who: &Self::AccountId, extra: Self::Balance) -> DispatchResult;
261
262 fn unbond(stash: &Self::AccountId, value: Self::Balance) -> DispatchResult;
272
273 fn set_payee(stash: &Self::AccountId, reward_acc: &Self::AccountId) -> DispatchResult;
275
276 fn withdraw_unbonded(
280 stash: Self::AccountId,
281 num_slashing_spans: u32,
282 ) -> Result<bool, DispatchError>;
283
284 fn desired_validator_count() -> u32;
286
287 fn election_ongoing() -> bool;
289
290 fn force_unstake(who: Self::AccountId) -> DispatchResult;
292
293 fn is_exposed_in_era(who: &Self::AccountId, era: &EraIndex) -> bool;
295
296 fn status(who: &Self::AccountId) -> Result<StakerStatus<Self::AccountId>, DispatchError>;
298
299 fn is_validator(who: &Self::AccountId) -> bool {
301 Self::status(who).map(|s| matches!(s, StakerStatus::Validator)).unwrap_or(false)
302 }
303
304 fn is_virtual_staker(who: &Self::AccountId) -> bool;
310
311 fn nominations(who: &Self::AccountId) -> Option<Vec<Self::AccountId>> {
313 match Self::status(who) {
314 Ok(StakerStatus::Nominator(t)) => Some(t),
315 _ => None,
316 }
317 }
318
319 fn slash_reward_fraction() -> Perbill;
321
322 #[cfg(feature = "runtime-benchmarks")]
323 fn max_exposure_page_size() -> Page;
324
325 #[cfg(feature = "runtime-benchmarks")]
326 fn add_era_stakers(
327 current_era: &EraIndex,
328 stash: &Self::AccountId,
329 exposures: Vec<(Self::AccountId, Self::Balance)>,
330 );
331
332 #[cfg(feature = "runtime-benchmarks")]
333 fn set_current_era(era: EraIndex);
334}
335
336pub trait StakingUnchecked: StakingInterface {
341 fn migrate_to_virtual_staker(who: &Self::AccountId) -> DispatchResult;
345
346 fn virtual_bond(
352 keyless_who: &Self::AccountId,
353 value: Self::Balance,
354 payee: &Self::AccountId,
355 ) -> DispatchResult;
356
357 #[cfg(feature = "runtime-benchmarks")]
361 fn migrate_to_direct_staker(who: &Self::AccountId);
362}
363
364#[derive(
366 PartialEq,
367 Eq,
368 PartialOrd,
369 Ord,
370 Clone,
371 Encode,
372 Decode,
373 DecodeWithMemTracking,
374 Debug,
375 TypeInfo,
376 Copy,
377)]
378pub struct IndividualExposure<AccountId, Balance: HasCompact> {
379 pub who: AccountId,
381 #[codec(compact)]
383 pub value: Balance,
384}
385
386#[derive(
388 PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, DecodeWithMemTracking, Debug, TypeInfo,
389)]
390pub struct Exposure<AccountId, Balance: HasCompact> {
391 #[codec(compact)]
393 pub total: Balance,
394 #[codec(compact)]
396 pub own: Balance,
397 pub others: Vec<IndividualExposure<AccountId, Balance>>,
399}
400
401impl<AccountId, Balance: Default + HasCompact> Default for Exposure<AccountId, Balance> {
402 fn default() -> Self {
403 Self { total: Default::default(), own: Default::default(), others: vec![] }
404 }
405}
406
407impl<
408 AccountId: Clone,
409 Balance: HasCompact + AtLeast32BitUnsigned + Copy + codec::MaxEncodedLen,
410 > Exposure<AccountId, Balance>
411{
412 pub fn split_others(&mut self, n_others: u32) -> Self {
420 let head_others: Vec<_> =
421 self.others.drain(..(n_others as usize).min(self.others.len())).collect();
422
423 let total_others_head: Balance = head_others
424 .iter()
425 .fold(Zero::zero(), |acc: Balance, o| acc.saturating_add(o.value));
426
427 self.total = self.total.saturating_sub(total_others_head);
428
429 Self {
430 total: total_others_head.saturating_add(self.own),
431 own: self.own,
432 others: head_others,
433 }
434 }
435
436 pub fn into_pages(
439 self,
440 page_size: Page,
441 ) -> (PagedExposureMetadata<Balance>, Vec<ExposurePage<AccountId, Balance>>) {
442 let individual_chunks = self.others.chunks(page_size as usize);
443 let mut exposure_pages: Vec<ExposurePage<AccountId, Balance>> =
444 Vec::with_capacity(individual_chunks.len());
445
446 for chunk in individual_chunks {
447 let mut page_total: Balance = Zero::zero();
448 let mut others: Vec<IndividualExposure<AccountId, Balance>> =
449 Vec::with_capacity(chunk.len());
450 for individual in chunk.iter() {
451 page_total.saturating_accrue(individual.value);
452 others.push(IndividualExposure {
453 who: individual.who.clone(),
454 value: individual.value,
455 })
456 }
457 exposure_pages.push(ExposurePage { page_total, others });
458 }
459
460 (
461 PagedExposureMetadata {
462 total: self.total,
463 own: self.own,
464 nominator_count: self.others.len() as u32,
465 page_count: exposure_pages.len() as Page,
466 },
467 exposure_pages,
468 )
469 }
470}
471
472#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Encode, Decode, Debug, TypeInfo)]
474pub struct ExposurePage<AccountId, Balance: HasCompact> {
475 #[codec(compact)]
477 pub page_total: Balance,
478 pub others: Vec<IndividualExposure<AccountId, Balance>>,
480}
481
482impl<A, B: Default + HasCompact> Default for ExposurePage<A, B> {
483 fn default() -> Self {
484 ExposurePage { page_total: Default::default(), others: vec![] }
485 }
486}
487
488impl<A, B: HasCompact + Default + AddAssign + SubAssign + Clone> From<Vec<IndividualExposure<A, B>>>
490 for ExposurePage<A, B>
491{
492 fn from(exposures: Vec<IndividualExposure<A, B>>) -> Self {
493 exposures.into_iter().fold(ExposurePage::default(), |mut page, e| {
494 page.page_total += e.value.clone();
495 page.others.push(e);
496 page
497 })
498 }
499}
500
501#[derive(
507 PartialEq,
508 Eq,
509 PartialOrd,
510 Ord,
511 Clone,
512 Encode,
513 Decode,
514 Debug,
515 TypeInfo,
516 Default,
517 MaxEncodedLen,
518 Copy,
519)]
520pub struct PagedExposureMetadata<Balance: HasCompact + codec::MaxEncodedLen> {
521 #[codec(compact)]
523 pub total: Balance,
524 #[codec(compact)]
526 pub own: Balance,
527 pub nominator_count: u32,
529 pub page_count: Page,
531}
532
533impl<Balance> PagedExposureMetadata<Balance>
534where
535 Balance: HasCompact
536 + codec::MaxEncodedLen
537 + Add<Output = Balance>
538 + Sub<Output = Balance>
539 + sp_runtime::Saturating
540 + PartialEq
541 + Copy
542 + sp_runtime::traits::Debug,
543{
544 pub fn update_with<Max: sp_core::Get<u32>>(
549 self,
550 others_balance: Balance,
551 others_num: u32,
552 ) -> Self {
553 let page_limit = Max::get().max(1);
554 let new_nominator_count = self.nominator_count.saturating_add(others_num);
555 let new_page_count = new_nominator_count
556 .saturating_add(page_limit)
557 .saturating_sub(1)
558 .saturating_div(page_limit);
559
560 Self {
561 total: self.total.saturating_add(others_balance),
562 own: self.own,
563 nominator_count: new_nominator_count,
564 page_count: new_page_count,
565 }
566 }
567}
568
569#[derive(Clone, Debug)]
579pub struct Agent<T>(T);
580impl<T> From<T> for Agent<T> {
581 fn from(acc: T) -> Self {
582 Agent(acc)
583 }
584}
585
586impl<T> Agent<T> {
587 pub fn get(self) -> T {
588 self.0
589 }
590}
591
592#[derive(Clone, Debug)]
597pub struct Delegator<T>(T);
598impl<T> From<T> for Delegator<T> {
599 fn from(acc: T) -> Self {
600 Delegator(acc)
601 }
602}
603
604impl<T> Delegator<T> {
605 pub fn get(self) -> T {
606 self.0
607 }
608}
609
610pub trait DelegationInterface {
612 type Balance: Sub<Output = Self::Balance>
614 + Ord
615 + PartialEq
616 + Default
617 + Copy
618 + MaxEncodedLen
619 + FullCodec
620 + TypeInfo
621 + Saturating;
622
623 type AccountId: Clone + core::fmt::Debug;
625
626 fn agent_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
630
631 fn agent_transferable_balance(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
634
635 fn delegator_balance(delegator: Delegator<Self::AccountId>) -> Option<Self::Balance>;
637
638 fn register_agent(
640 agent: Agent<Self::AccountId>,
641 reward_account: &Self::AccountId,
642 ) -> DispatchResult;
643
644 fn remove_agent(agent: Agent<Self::AccountId>) -> DispatchResult;
648
649 fn delegate(
651 delegator: Delegator<Self::AccountId>,
652 agent: Agent<Self::AccountId>,
653 amount: Self::Balance,
654 ) -> DispatchResult;
655
656 fn withdraw_delegation(
661 delegator: Delegator<Self::AccountId>,
662 agent: Agent<Self::AccountId>,
663 amount: Self::Balance,
664 num_slashing_spans: u32,
665 ) -> DispatchResult;
666
667 fn pending_slash(agent: Agent<Self::AccountId>) -> Option<Self::Balance>;
672
673 fn delegator_slash(
678 agent: Agent<Self::AccountId>,
679 delegator: Delegator<Self::AccountId>,
680 value: Self::Balance,
681 maybe_reporter: Option<Self::AccountId>,
682 ) -> DispatchResult;
683}
684
685pub trait DelegationMigrator {
688 type Balance: Sub<Output = Self::Balance>
690 + Ord
691 + PartialEq
692 + Default
693 + Copy
694 + MaxEncodedLen
695 + FullCodec
696 + TypeInfo
697 + Saturating;
698
699 type AccountId: Clone + core::fmt::Debug;
701
702 fn migrate_nominator_to_agent(
707 agent: Agent<Self::AccountId>,
708 reward_account: &Self::AccountId,
709 ) -> DispatchResult;
710
711 fn migrate_delegation(
716 agent: Agent<Self::AccountId>,
717 delegator: Delegator<Self::AccountId>,
718 value: Self::Balance,
719 ) -> DispatchResult;
720
721 #[cfg(feature = "runtime-benchmarks")]
725 fn force_kill_agent(agent: Agent<Self::AccountId>);
726}
727
728sp_core::generate_feature_enabled_macro!(runtime_benchmarks_enabled, feature = "runtime-benchmarks", $);
729
730#[cfg(test)]
731mod tests {
732 use sp_core::ConstU32;
733
734 use super::*;
735
736 #[test]
737 fn update_with_works() {
738 let metadata = PagedExposureMetadata::<u32> {
739 total: 1000,
740 own: 0, nominator_count: 10,
742 page_count: 1,
743 };
744
745 assert_eq!(
746 metadata.update_with::<ConstU32<10>>(1, 1),
747 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 2 },
748 );
749
750 assert_eq!(
751 metadata.update_with::<ConstU32<5>>(1, 1),
752 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
753 );
754
755 assert_eq!(
756 metadata.update_with::<ConstU32<4>>(1, 1),
757 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 3 },
758 );
759
760 assert_eq!(
761 metadata.update_with::<ConstU32<1>>(1, 1),
762 PagedExposureMetadata { total: 1001, own: 0, nominator_count: 11, page_count: 11 },
763 );
764 }
765
766 #[test]
767 fn individual_exposures_to_exposure_works() {
768 let exposure_1 = IndividualExposure { who: 1, value: 10u32 };
769 let exposure_2 = IndividualExposure { who: 2, value: 20 };
770 let exposure_3 = IndividualExposure { who: 3, value: 30 };
771
772 let exposure_page: ExposurePage<u32, u32> = vec![exposure_1, exposure_2, exposure_3].into();
773
774 assert_eq!(
775 exposure_page,
776 ExposurePage { page_total: 60, others: vec![exposure_1, exposure_2, exposure_3] },
777 );
778 }
779
780 #[test]
781 fn empty_individual_exposures_to_exposure_works() {
782 let empty_exposures: Vec<IndividualExposure<u32, u32>> = vec![];
783
784 let exposure_page: ExposurePage<u32, u32> = empty_exposures.into();
785 assert_eq!(exposure_page, ExposurePage { page_total: 0, others: vec![] });
786 }
787
788 #[test]
789 fn exposure_split_others_works() {
790 let exposure = Exposure {
791 total: 100,
792 own: 20,
793 others: vec![
794 IndividualExposure { who: 1, value: 20u32 },
795 IndividualExposure { who: 2, value: 20 },
796 IndividualExposure { who: 3, value: 20 },
797 IndividualExposure { who: 4, value: 20 },
798 ],
799 };
800
801 let mut exposure_0 = exposure.clone();
802 let split_exposure = exposure_0.split_others(0);
805 assert_eq!(exposure_0, exposure);
806 assert_eq!(split_exposure, Exposure { total: 20, own: 20, others: vec![] });
807
808 let mut exposure_1 = exposure.clone();
809 let split_exposure = exposure_1.split_others(1);
811 assert_eq!(exposure_1.own, 20);
812 assert_eq!(exposure_1.total, 20 + 3 * 20);
813 assert_eq!(exposure_1.others.len(), 3);
814
815 assert_eq!(split_exposure.own, 20);
816 assert_eq!(split_exposure.total, 20 + 1 * 20);
817 assert_eq!(split_exposure.others.len(), 1);
818
819 let mut exposure_3 = exposure.clone();
820 let split_exposure = exposure_3.split_others(3);
823 assert_eq!(exposure_3.own, 20);
824 assert_eq!(exposure_3.total, 20 + 1 * 20);
825 assert_eq!(exposure_3.others.len(), 1);
826
827 assert_eq!(split_exposure.own, 20);
828 assert_eq!(split_exposure.total, 20 + 3 * 20);
829 assert_eq!(split_exposure.others.len(), 3);
830
831 let mut exposure_max = exposure.clone();
832 let split_exposure = exposure_max.split_others(u32::MAX);
836 assert_eq!(split_exposure, exposure);
837 assert_eq!(exposure_max, Exposure { total: 20, own: 20, others: vec![] });
838 }
839}