123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency, weights::Weight,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config:106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config107 {108 109 type Currency: ExtendedLockableCurrency<Self::AccountId>110 + ReservableCurrency<Self::AccountId>;111112 113 type CollectionHandler: CollectionHandler<114 AccountId = Self::AccountId,115 CollectionId = CollectionId,116 >;117118 119 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121 122 type TreasuryAccountId: Get<Self::AccountId>;123124 125 #[pallet::constant]126 type PalletId: Get<PalletId>;127128 129 #[pallet::constant]130 type RecalculationInterval: Get<Self::BlockNumber>;131132 133 #[pallet::constant]134 type PendingInterval: Get<Self::BlockNumber>;135136 137 #[pallet::constant]138 type IntervalIncome: Get<Perbill>;139140 141 #[pallet::constant]142 type Nominal: Get<BalanceOf<Self>>;143144 145 type WeightInfo: WeightInfo;146147 148 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150 151 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152 }153154 #[pallet::pallet]155 #[pallet::generate_store(pub(super) trait Store)]156 pub struct Pallet<T>(_);157158 #[pallet::event]159 #[pallet::generate_deposit(pub(super) fn deposit_event)]160 pub enum Event<T: Config> {161 162 163 164 165 166 167 StakingRecalculation(168 169 T::AccountId,170 171 BalanceOf<T>,172 173 BalanceOf<T>,174 ),175176 177 178 179 180 181 Stake(T::AccountId, BalanceOf<T>),182183 184 185 186 187 188 Unstake(T::AccountId, BalanceOf<T>),189190 191 192 193 194 SetAdmin(T::AccountId),195 }196197 #[pallet::error]198 pub enum Error<T> {199 200 AdminNotSet,201 202 NoPermission,203 204 NotSufficientFunds,205 206 PendingForBlockOverflow,207 208 SponsorNotSet,209 210 IncorrectLockedBalanceOperation,211 212 InsufficientStakedBalance,213 }214215 216 #[pallet::storage]217 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;218219 220 #[pallet::storage]221 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;222223 224 225 226 227 228 229 #[pallet::storage]230 pub type Staked<T: Config> = StorageNMap<231 Key = (232 Key<Blake2_128Concat, T::AccountId>,233 Key<Twox64Concat, T::BlockNumber>,234 ),235 Value = (BalanceOf<T>, T::BlockNumber),236 QueryKind = ValueQuery,237 >;238239 240 241 242 243 #[pallet::storage]244 pub type StakesPerAccount<T: Config> =245 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;246247 248 249 250 251 #[pallet::storage]252 pub type PendingUnstake<T: Config> = StorageMap<253 _,254 Twox64Concat,255 T::BlockNumber,256 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,257 ValueQuery,258 >;259260 261 262 #[pallet::storage]263 #[pallet::getter(fn get_next_calculated_record)]264 pub type PreviousCalculatedRecord<T: Config> =265 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;266267 #[pallet::storage]268 pub(crate) type UpgradedToReserves<T: Config> =269 StorageValue<Value = bool, QueryKind = ValueQuery>;270271 #[pallet::hooks]272 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273 274 275 276 fn on_initialize(current_block_number: T::BlockNumber) -> Weight277 where278 <T as frame_system::Config>::BlockNumber: From<u32>,279 {280 let block_pending = PendingUnstake::<T>::take(current_block_number);281 let counter = block_pending.len() as u32;282283 if !block_pending.is_empty() {284 block_pending.into_iter().for_each(|(staker, amount)| {285 Self::get_locked_balance(&staker).map(|b| {286 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();287 Self::set_lock_unchecked(&staker, new_state);288 });289 });290 }291292 <T as Config>::WeightInfo::on_initialize(counter)293 }294295 fn on_runtime_upgrade() -> Weight {296 <UpgradedToReserves<T>>::kill();297298 T::DbWeight::get().reads_writes(0, 1)299 }300 }301302 #[pallet::call]303 impl<T: Config> Pallet<T>304 where305 T::BlockNumber: From<u32> + Into<u32>,306 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,307 {308 309 310 311 312 313 314 315 316 317 #[pallet::call_index(0)]318 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]319 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {320 ensure_root(origin)?;321322 <Admin<T>>::set(Some(admin.as_sub().to_owned()));323324 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));325326 Ok(())327 }328329 330 331 332 333 334 335 336 #[pallet::call_index(1)]337 #[pallet::weight(<T as Config>::WeightInfo::stake())]338 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {339 let staker_id = ensure_signed(staker)?;340341 ensure!(342 StakesPerAccount::<T>::get(&staker_id) < 10,343 Error::<T>::NoPermission344 );345346 ensure!(347 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),348 ArithmeticError::Underflow349 );350 let config = <PalletConfiguration<T>>::get();351352 let balance =353 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);354355 356 ensure!(357 amount358 <= match Self::get_locked_balance(&staker_id) {359 Some(lock) => balance360 .checked_sub(&lock.amount)361 .ok_or(ArithmeticError::Underflow)?,362 None => balance,363 },364 ArithmeticError::Underflow365 );366367 Self::add_lock_balance(&staker_id, amount)?;368369 let block_number = T::RelayBlockNumberProvider::current_block_number();370371 372 373 let recalculate_after_interval: T::BlockNumber =374 if block_number % config.recalculation_interval == 0u32.into() {375 1u32.into()376 } else {377 2u32.into()378 };379380 381 382 let recalc_block = (block_number / config.recalculation_interval383 + recalculate_after_interval)384 * config.recalculation_interval;385386 <Staked<T>>::insert((&staker_id, block_number), {387 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));388 balance_and_recalc_block.0 = balance_and_recalc_block389 .0390 .checked_add(&amount)391 .ok_or(ArithmeticError::Overflow)?;392 balance_and_recalc_block.1 = recalc_block;393 balance_and_recalc_block394 });395396 <TotalStaked<T>>::set(397 <TotalStaked<T>>::get()398 .checked_add(&amount)399 .ok_or(ArithmeticError::Overflow)?,400 );401402 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);403404 Self::deposit_event(Event::Stake(staker_id, amount));405406 Ok(())407 }408409 410 411 412 #[pallet::call_index(2)]413 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]414 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {415 let staker_id = ensure_signed(staker)?;416417 Self::unstake_all_internal(staker_id)418 }419420 421 422 423 424 425 426 427 428 #[pallet::call_index(8)]429 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]430 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {431 let staker_id = ensure_signed(staker)?;432433 Self::unstake_partial_internal(staker_id, amount)434 }435436 437 438 439 440 441 442 443 444 445 #[pallet::call_index(3)]446 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]447 pub fn sponsor_collection(448 admin: OriginFor<T>,449 collection_id: CollectionId,450 ) -> DispatchResult {451 let admin_id = ensure_signed(admin)?;452 ensure!(453 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,454 Error::<T>::NoPermission455 );456457 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)458 }459460 461 462 463 464 465 466 467 468 469 470 471 #[pallet::call_index(4)]472 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]473 pub fn stop_sponsoring_collection(474 admin: OriginFor<T>,475 collection_id: CollectionId,476 ) -> DispatchResult {477 let admin_id = ensure_signed(admin)?;478479 ensure!(480 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,481 Error::<T>::NoPermission482 );483484 ensure!(485 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?486 == Self::account_id(),487 <Error<T>>::NoPermission488 );489 T::CollectionHandler::remove_collection_sponsor(collection_id)490 }491492 493 494 495 496 497 498 499 500 501 #[pallet::call_index(5)]502 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]503 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {504 let admin_id = ensure_signed(admin)?;505506 ensure!(507 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,508 Error::<T>::NoPermission509 );510511 T::ContractHandler::set_sponsor(512 T::CrossAccountId::from_sub(Self::account_id()),513 contract_id,514 )515 }516517 518 519 520 521 522 523 524 525 526 527 528 #[pallet::call_index(6)]529 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]530 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {531 let admin_id = ensure_signed(admin)?;532533 ensure!(534 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,535 Error::<T>::NoPermission536 );537538 ensure!(539 T::ContractHandler::sponsor(contract_id)?540 .ok_or(<Error<T>>::SponsorNotSet)?541 .as_sub() == &Self::account_id(),542 <Error<T>>::NoPermission543 );544 T::ContractHandler::remove_contract_sponsor(contract_id)545 }546547 548 549 550 551 552 553 554 555 556 557 558 559 #[pallet::call_index(7)]560 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]561 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {562 let admin_id = ensure_signed(admin)?;563564 ensure!(565 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,566 Error::<T>::NoPermission567 );568 let config = <PalletConfiguration<T>>::get();569570 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);571572 ensure!(573 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,574 Error::<T>::NoPermission575 );576577 578 579 let current_recalc_block = Self::get_current_recalc_block(580 T::RelayBlockNumberProvider::current_block_number(),581 &config,582 );583584 585 586 let next_recalc_block = current_recalc_block + config.recalculation_interval;587588 let mut storage_iterator = Self::get_next_calculated_key()589 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));590591 PreviousCalculatedRecord::<T>::set(None);592593 {594 595 let last_id = RefCell::new(None);596 597 let mut last_staked_calculated_block = Default::default();598 599 let income_acc = RefCell::new(BalanceOf::<T>::default());600 601 let amount_acc = RefCell::new(BalanceOf::<T>::default());602603 604 605 606 607 608 609 610 let flush_stake = || -> DispatchResult {611 if let Some(last_id) = &*last_id.borrow() {612 if !income_acc.borrow().is_zero() {613 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(614 &T::TreasuryAccountId::get(),615 last_id,616 *income_acc.borrow(),617 ExistenceRequirement::KeepAlive,618 )?;619620 Self::add_lock_balance(last_id, *income_acc.borrow())?;621 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {622 *staked = staked623 .checked_add(&*income_acc.borrow())624 .ok_or(ArithmeticError::Overflow)?;625 Ok(())626 })?;627628 Self::deposit_event(Event::StakingRecalculation(629 last_id.clone(),630 *amount_acc.borrow(),631 *income_acc.borrow(),632 ));633 }634635 *income_acc.borrow_mut() = BalanceOf::<T>::default();636 *amount_acc.borrow_mut() = BalanceOf::<T>::default();637 }638 Ok(())639 };640641 642 643 644 645 646 647 while let Some((648 (current_id, staked_block),649 (amount, next_recalc_block_for_stake),650 )) = storage_iterator.next()651 {652 653 654 655 if last_id.borrow().as_ref() != Some(¤t_id) {656 if stakers_number > 0 {657 flush_stake()?;658 *last_id.borrow_mut() = Some(current_id.clone());659 stakers_number -= 1;660 }661 662 else {663 if let Some(staker) = &*last_id.borrow() {664 665 PreviousCalculatedRecord::<T>::set(Some((666 staker.clone(),667 last_staked_calculated_block,668 )));669 }670 break;671 };672 };673674 675 if current_recalc_block >= next_recalc_block_for_stake {676 *amount_acc.borrow_mut() += amount;677 Self::recalculate_and_insert_stake(678 ¤t_id,679 staked_block,680 next_recalc_block,681 amount,682 ((current_recalc_block - next_recalc_block_for_stake)683 / config.recalculation_interval)684 .into() + 1,685 &mut *income_acc.borrow_mut(),686 );687 }688 last_staked_calculated_block = staked_block;689 }690 flush_stake()?;691 }692693 Ok(())694 }695 }696}697698impl<T: Config> Pallet<T> {699 700 701 702 703 pub fn account_id() -> T::AccountId {704 T::PalletId::get().into_account_truncating()705 }706707 708 709 710 711 fn unstake_partial_internal(712 staker_id: T::AccountId,713 unstaked_balance: BalanceOf<T>,714 ) -> DispatchResult {715 if unstaked_balance == Default::default() {716 return Ok(());717 }718719 let config = <PalletConfiguration<T>>::get();720721 722 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;723724 let mut pendings = <PendingUnstake<T>>::get(unpending_block);725726 727 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);728729 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();730731 let total_staked = stakes732 .iter()733 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {734 acc + *balance735 });736737 ensure!(738 unstaked_balance <= total_staked,739 <Error<T>>::InsufficientStakedBalance740 );741742 <TotalStaked<T>>::set(743 <TotalStaked<T>>::get()744 .checked_sub(&unstaked_balance)745 .ok_or(ArithmeticError::Underflow)?,746 );747748 stakes.sort_by_key(|(block, _)| *block);749750 let mut acc_amount = unstaked_balance;751 let mut will_deleted_stakes_count = 0u8;752753 let changed_stakes = stakes754 .into_iter()755 .map_while(|(block, (balance_per_block, _))| {756 if acc_amount == <BalanceOf<T>>::default() {757 return None;758 }759 if acc_amount < balance_per_block {760 let res = (block, balance_per_block - acc_amount);761 acc_amount = <BalanceOf<T>>::default();762 return Some(res);763 } else {764 acc_amount -= balance_per_block;765 will_deleted_stakes_count += 1;766 return Some((block, <BalanceOf<T>>::default()));767 }768 })769 .collect::<Vec<_>>();770771 pendings772 .try_push((staker_id.clone(), unstaked_balance))773 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;774775 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {776 *stakes = stakes777 .checked_sub(will_deleted_stakes_count)778 .ok_or(ArithmeticError::Underflow)?;779 Ok(())780 })?;781782 changed_stakes783 .into_iter()784 .for_each(|(staked_block, current_stake_state)| {785 if current_stake_state == Default::default() {786 <Staked<T>>::remove((&staker_id, staked_block));787 } else {788 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {789 *old_stake_state = current_stake_state790 });791 }792 });793794 <PendingUnstake<T>>::insert(unpending_block, pendings);795796 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));797798 Ok(())799 }800801 802 803 804 805 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {806 Self::get_locked_balance(staker)807 .map_or(<BalanceOf<T>>::default(), |l| l.amount)808 .checked_add(&amount)809 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))810 .ok_or(ArithmeticError::Overflow.into())811 }812813 814 815 816 817 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {818 if amount.is_zero() {819 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(820 LOCK_IDENTIFIER,821 &staker,822 );823 } else {824 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(825 LOCK_IDENTIFIER,826 staker,827 amount,828 WithdrawReasons::all(),829 )830 }831 }832833 834 835 836 pub fn get_locked_balance(837 staker: impl EncodeLike<T::AccountId>,838 ) -> Option<BalanceLock<BalanceOf<T>>> {839 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)840 .into_iter()841 .find(|l| l.id == LOCK_IDENTIFIER)842 }843844 845 846 847 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {848 let staked = Staked::<T>::iter_prefix((staker,))849 .into_iter()850 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {851 acc + amount852 });853 if staked != <BalanceOf<T>>::default() {854 Some(staked)855 } else {856 None857 }858 }859860 861 862 863 864 pub fn total_staked_by_id_per_block(865 staker: impl EncodeLike<T::AccountId>,866 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {867 let mut staked = Staked::<T>::iter_prefix((staker,))868 .into_iter()869 .map(|(block, (amount, _))| (block, amount))870 .collect::<Vec<_>>();871 staked.sort_by_key(|(block, _)| *block);872 if !staked.is_empty() {873 Some(staked)874 } else {875 None876 }877 }878879 880 881 882 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {883 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {884 Self::total_staked_by_id(s.as_sub())885 })886 }887888 889 890 891 892 893894 895 896 897 898 pub fn cross_id_total_staked_per_block(899 staker: T::CrossAccountId,900 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {901 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()902 }903904 fn recalculate_and_insert_stake(905 staker: &T::AccountId,906 staked_block: T::BlockNumber,907 next_recalc_block: T::BlockNumber,908 base: BalanceOf<T>,909 iters: u32,910 income_acc: &mut BalanceOf<T>,911 ) {912 let income = Self::calculate_income(base, iters);913914 base.checked_add(&income).map(|res| {915 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));916 *income_acc += income;917 });918 }919920 fn calculate_income<I>(base: I, iters: u32) -> I921 where922 I: EncodeLike<BalanceOf<T>> + Balance,923 {924 let config = <PalletConfiguration<T>>::get();925 let mut income = base;926927 (0..iters).for_each(|_| income += config.interval_income * income);928929 income - base930 }931932 933 934 fn get_current_recalc_block(935 current_relay_block: T::BlockNumber,936 config: &PalletConfiguration<T>,937 ) -> T::BlockNumber {938 (current_relay_block / config.recalculation_interval) * config.recalculation_interval939 }940941 fn get_next_calculated_key() -> Option<Vec<u8>> {942 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))943 }944}945946impl<T: Config> Pallet<T>947where948 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,949{950 951 952 953 954 955 956 957 958 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {959 staker.map_or(960 PendingUnstake::<T>::iter_values()961 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))962 .sum(),963 |s| {964 PendingUnstake::<T>::iter_values()965 .flatten()966 .filter_map(|(id, amount)| {967 if id == *s.as_sub() {968 Some(amount)969 } else {970 None971 }972 })973 .sum()974 },975 )976 }977978 979 980 981 982 pub fn cross_id_pending_unstake_per_block(983 staker: T::CrossAccountId,984 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {985 let mut unsorted_res = vec![];986 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {987 pendings.into_iter().for_each(|(id, amount)| {988 if id == *staker.as_sub() {989 unsorted_res.push((block, amount));990 };991 })992 });993994 unsorted_res.sort_by_key(|(block, _)| *block);995 unsorted_res996 }997998 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {999 let config = <PalletConfiguration<T>>::get();10001001 1002 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10031004 let mut pendings = <PendingUnstake<T>>::get(block);10051006 1007 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10081009 let mut total_stakes = 0u64;10101011 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1012 .map(|(_, (amount, _))| {1013 total_stakes += 1;1014 amount1015 })1016 .sum();10171018 if total_staked.is_zero() {1019 return Ok(());1020 }10211022 pendings1023 .try_push((staker_id.clone(), total_staked))1024 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;10251026 <PendingUnstake<T>>::insert(block, pendings);10271028 TotalStaked::<T>::set(1029 TotalStaked::<T>::get()1030 .checked_sub(&total_staked)1031 .ok_or(ArithmeticError::Underflow)?,1032 );10331034 StakesPerAccount::<T>::remove(&staker_id);10351036 Self::deposit_event(Event::Unstake(staker_id, total_staked));10371038 Ok(())1039 }1040}