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 pub struct Pallet<T>(_);156157 #[pallet::event]158 #[pallet::generate_deposit(pub(super) fn deposit_event)]159 pub enum Event<T: Config> {160 161 162 163 164 165 166 StakingRecalculation(167 168 T::AccountId,169 170 BalanceOf<T>,171 172 BalanceOf<T>,173 ),174175 176 177 178 179 180 Stake(T::AccountId, BalanceOf<T>),181182 183 184 185 186 187 Unstake(T::AccountId, BalanceOf<T>),188189 190 191 192 193 SetAdmin(T::AccountId),194 }195196 #[pallet::error]197 pub enum Error<T> {198 199 AdminNotSet,200 201 NoPermission,202 203 NotSufficientFunds,204 205 PendingForBlockOverflow,206 207 SponsorNotSet,208 209 IncorrectLockedBalanceOperation,210 211 InsufficientStakedBalance,212 }213214 215 #[pallet::storage]216 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;217218 219 #[pallet::storage]220 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;221222 223 224 225 226 227 228 #[pallet::storage]229 pub type Staked<T: Config> = StorageNMap<230 Key = (231 Key<Blake2_128Concat, T::AccountId>,232 Key<Twox64Concat, T::BlockNumber>,233 ),234 Value = (BalanceOf<T>, T::BlockNumber),235 QueryKind = ValueQuery,236 >;237238 239 240 241 242 #[pallet::storage]243 pub type StakesPerAccount<T: Config> =244 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;245246 247 248 249 250 #[pallet::storage]251 pub type PendingUnstake<T: Config> = StorageMap<252 _,253 Twox64Concat,254 T::BlockNumber,255 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,256 ValueQuery,257 >;258259 260 261 #[pallet::storage]262 #[pallet::getter(fn get_next_calculated_record)]263 pub type PreviousCalculatedRecord<T: Config> =264 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;265266 #[pallet::hooks]267 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {268 269 270 271 fn on_initialize(current_block_number: T::BlockNumber) -> Weight272 where273 <T as frame_system::Config>::BlockNumber: From<u32>,274 {275 let block_pending = PendingUnstake::<T>::take(current_block_number);276 let counter = block_pending.len() as u32;277278 if !block_pending.is_empty() {279 block_pending.into_iter().for_each(|(staker, amount)| {280 Self::get_locked_balance(&staker).map(|b| {281 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();282 Self::set_lock_unchecked(&staker, new_state);283 });284 });285 }286287 <T as Config>::WeightInfo::on_initialize(counter)288 }289 }290291 #[pallet::call]292 impl<T: Config> Pallet<T>293 where294 T::BlockNumber: From<u32> + Into<u32>,295 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,296 {297 298 299 300 301 302 303 304 305 306 #[pallet::call_index(0)]307 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]308 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {309 ensure_root(origin)?;310311 <Admin<T>>::set(Some(admin.as_sub().to_owned()));312313 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));314315 Ok(())316 }317318 319 320 321 322 323 324 325 #[pallet::call_index(1)]326 #[pallet::weight(<T as Config>::WeightInfo::stake())]327 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {328 let staker_id = ensure_signed(staker)?;329330 ensure!(331 StakesPerAccount::<T>::get(&staker_id) < 10,332 Error::<T>::NoPermission333 );334335 ensure!(336 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),337 ArithmeticError::Underflow338 );339 let config = <PalletConfiguration<T>>::get();340341 let balance =342 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);343344 345 ensure!(346 amount347 <= match Self::get_locked_balance(&staker_id) {348 Some(lock) => balance349 .checked_sub(&lock.amount)350 .ok_or(ArithmeticError::Underflow)?,351 None => balance,352 },353 ArithmeticError::Underflow354 );355356 Self::add_lock_balance(&staker_id, amount)?;357358 let block_number = T::RelayBlockNumberProvider::current_block_number();359360 361 362 let recalculate_after_interval: T::BlockNumber =363 if block_number % config.recalculation_interval == 0u32.into() {364 1u32.into()365 } else {366 2u32.into()367 };368369 370 371 let recalc_block = (block_number / config.recalculation_interval372 + recalculate_after_interval)373 * config.recalculation_interval;374375 <Staked<T>>::insert((&staker_id, block_number), {376 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));377 balance_and_recalc_block.0 = balance_and_recalc_block378 .0379 .checked_add(&amount)380 .ok_or(ArithmeticError::Overflow)?;381 balance_and_recalc_block.1 = recalc_block;382 balance_and_recalc_block383 });384385 <TotalStaked<T>>::set(386 <TotalStaked<T>>::get()387 .checked_add(&amount)388 .ok_or(ArithmeticError::Overflow)?,389 );390391 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);392393 Self::deposit_event(Event::Stake(staker_id, amount));394395 Ok(())396 }397398 399 400 401 #[pallet::call_index(2)]402 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]403 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {404 let staker_id = ensure_signed(staker)?;405406 Self::unstake_all_internal(staker_id)407 }408409 410 411 412 413 414 415 416 417 #[pallet::call_index(8)]418 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]419 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {420 let staker_id = ensure_signed(staker)?;421422 Self::unstake_partial_internal(staker_id, amount)423 }424425 426 427 428 429 430 431 432 433 434 #[pallet::call_index(3)]435 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]436 pub fn sponsor_collection(437 admin: OriginFor<T>,438 collection_id: CollectionId,439 ) -> DispatchResult {440 let admin_id = ensure_signed(admin)?;441 ensure!(442 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,443 Error::<T>::NoPermission444 );445446 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)447 }448449 450 451 452 453 454 455 456 457 458 459 460 #[pallet::call_index(4)]461 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]462 pub fn stop_sponsoring_collection(463 admin: OriginFor<T>,464 collection_id: CollectionId,465 ) -> DispatchResult {466 let admin_id = ensure_signed(admin)?;467468 ensure!(469 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,470 Error::<T>::NoPermission471 );472473 ensure!(474 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?475 == Self::account_id(),476 <Error<T>>::NoPermission477 );478 T::CollectionHandler::remove_collection_sponsor(collection_id)479 }480481 482 483 484 485 486 487 488 489 490 #[pallet::call_index(5)]491 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]492 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {493 let admin_id = ensure_signed(admin)?;494495 ensure!(496 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,497 Error::<T>::NoPermission498 );499500 T::ContractHandler::set_sponsor(501 T::CrossAccountId::from_sub(Self::account_id()),502 contract_id,503 )504 }505506 507 508 509 510 511 512 513 514 515 516 517 #[pallet::call_index(6)]518 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]519 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {520 let admin_id = ensure_signed(admin)?;521522 ensure!(523 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,524 Error::<T>::NoPermission525 );526527 ensure!(528 T::ContractHandler::sponsor(contract_id)?529 .ok_or(<Error<T>>::SponsorNotSet)?530 .as_sub() == &Self::account_id(),531 <Error<T>>::NoPermission532 );533 T::ContractHandler::remove_contract_sponsor(contract_id)534 }535536 537 538 539 540 541 542 543 544 545 546 547 548 #[pallet::call_index(7)]549 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]550 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {551 let admin_id = ensure_signed(admin)?;552553 ensure!(554 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,555 Error::<T>::NoPermission556 );557 let config = <PalletConfiguration<T>>::get();558559 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);560561 ensure!(562 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,563 Error::<T>::NoPermission564 );565566 567 568 let current_recalc_block = Self::get_current_recalc_block(569 T::RelayBlockNumberProvider::current_block_number(),570 &config,571 );572573 574 575 let next_recalc_block = current_recalc_block + config.recalculation_interval;576577 let mut storage_iterator = Self::get_next_calculated_key()578 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));579580 PreviousCalculatedRecord::<T>::set(None);581582 {583 584 let last_id = RefCell::new(None);585 586 let mut last_staked_calculated_block = Default::default();587 588 let income_acc = RefCell::new(BalanceOf::<T>::default());589 590 let amount_acc = RefCell::new(BalanceOf::<T>::default());591592 593 594 595 596 597 598 599 let flush_stake = || -> DispatchResult {600 if let Some(last_id) = &*last_id.borrow() {601 if !income_acc.borrow().is_zero() {602 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(603 &T::TreasuryAccountId::get(),604 last_id,605 *income_acc.borrow(),606 ExistenceRequirement::KeepAlive,607 )?;608609 Self::add_lock_balance(last_id, *income_acc.borrow())?;610 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {611 *staked = staked612 .checked_add(&*income_acc.borrow())613 .ok_or(ArithmeticError::Overflow)?;614 Ok(())615 })?;616617 Self::deposit_event(Event::StakingRecalculation(618 last_id.clone(),619 *amount_acc.borrow(),620 *income_acc.borrow(),621 ));622 }623624 *income_acc.borrow_mut() = BalanceOf::<T>::default();625 *amount_acc.borrow_mut() = BalanceOf::<T>::default();626 }627 Ok(())628 };629630 631 632 633 634 635 636 while let Some((637 (current_id, staked_block),638 (amount, next_recalc_block_for_stake),639 )) = storage_iterator.next()640 {641 642 643 644 if last_id.borrow().as_ref() != Some(¤t_id) {645 if stakers_number > 0 {646 flush_stake()?;647 *last_id.borrow_mut() = Some(current_id.clone());648 stakers_number -= 1;649 }650 651 else {652 if let Some(staker) = &*last_id.borrow() {653 654 PreviousCalculatedRecord::<T>::set(Some((655 staker.clone(),656 last_staked_calculated_block,657 )));658 }659 break;660 };661 };662663 664 if current_recalc_block >= next_recalc_block_for_stake {665 *amount_acc.borrow_mut() += amount;666 Self::recalculate_and_insert_stake(667 ¤t_id,668 staked_block,669 next_recalc_block,670 amount,671 ((current_recalc_block - next_recalc_block_for_stake)672 / config.recalculation_interval)673 .into() + 1,674 &mut *income_acc.borrow_mut(),675 );676 }677 last_staked_calculated_block = staked_block;678 }679 flush_stake()?;680 }681682 Ok(())683 }684 }685}686687impl<T: Config> Pallet<T> {688 689 690 691 692 pub fn account_id() -> T::AccountId {693 T::PalletId::get().into_account_truncating()694 }695696 697 698 699 700 fn unstake_partial_internal(701 staker_id: T::AccountId,702 unstaked_balance: BalanceOf<T>,703 ) -> DispatchResult {704 if unstaked_balance == Default::default() {705 return Ok(());706 }707708 let config = <PalletConfiguration<T>>::get();709710 711 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;712713 let mut pendings = <PendingUnstake<T>>::get(unpending_block);714715 716 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);717718 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();719720 let total_staked = stakes721 .iter()722 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {723 acc + *balance724 });725726 ensure!(727 unstaked_balance <= total_staked,728 <Error<T>>::InsufficientStakedBalance729 );730731 <TotalStaked<T>>::set(732 <TotalStaked<T>>::get()733 .checked_sub(&unstaked_balance)734 .ok_or(ArithmeticError::Underflow)?,735 );736737 stakes.sort_by_key(|(block, _)| *block);738739 let mut acc_amount = unstaked_balance;740 let mut will_deleted_stakes_count = 0u8;741742 let changed_stakes = stakes743 .into_iter()744 .map_while(|(block, (balance_per_block, _))| {745 if acc_amount == <BalanceOf<T>>::default() {746 return None;747 }748 if acc_amount < balance_per_block {749 let res = (block, balance_per_block - acc_amount);750 acc_amount = <BalanceOf<T>>::default();751 return Some(res);752 } else {753 acc_amount -= balance_per_block;754 will_deleted_stakes_count += 1;755 return Some((block, <BalanceOf<T>>::default()));756 }757 })758 .collect::<Vec<_>>();759760 pendings761 .try_push((staker_id.clone(), unstaked_balance))762 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;763764 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {765 *stakes = stakes766 .checked_sub(will_deleted_stakes_count)767 .ok_or(ArithmeticError::Underflow)?;768 Ok(())769 })?;770771 changed_stakes772 .into_iter()773 .for_each(|(staked_block, current_stake_state)| {774 if current_stake_state == Default::default() {775 <Staked<T>>::remove((&staker_id, staked_block));776 } else {777 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {778 *old_stake_state = current_stake_state779 });780 }781 });782783 <PendingUnstake<T>>::insert(unpending_block, pendings);784785 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));786787 Ok(())788 }789790 791 792 793 794 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {795 Self::get_locked_balance(staker)796 .map_or(<BalanceOf<T>>::default(), |l| l.amount)797 .checked_add(&amount)798 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))799 .ok_or(ArithmeticError::Overflow.into())800 }801802 803 804 805 806 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {807 if amount.is_zero() {808 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(809 LOCK_IDENTIFIER,810 &staker,811 );812 } else {813 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(814 LOCK_IDENTIFIER,815 staker,816 amount,817 WithdrawReasons::all(),818 )819 }820 }821822 823 824 825 pub fn get_locked_balance(826 staker: impl EncodeLike<T::AccountId>,827 ) -> Option<BalanceLock<BalanceOf<T>>> {828 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)829 .into_iter()830 .find(|l| l.id == LOCK_IDENTIFIER)831 }832833 834 835 836 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {837 let staked = Staked::<T>::iter_prefix((staker,))838 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {839 acc + amount840 });841 if staked != <BalanceOf<T>>::default() {842 Some(staked)843 } else {844 None845 }846 }847848 849 850 851 852 pub fn total_staked_by_id_per_block(853 staker: impl EncodeLike<T::AccountId>,854 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {855 let mut staked = Staked::<T>::iter_prefix((staker,))856 .map(|(block, (amount, _))| (block, amount))857 .collect::<Vec<_>>();858 staked.sort_by_key(|(block, _)| *block);859 if !staked.is_empty() {860 Some(staked)861 } else {862 None863 }864 }865866 867 868 869 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {870 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {871 Self::total_staked_by_id(s.as_sub())872 })873 }874875 876 877 878 879 pub fn cross_id_total_staked_per_block(880 staker: T::CrossAccountId,881 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {882 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()883 }884885 fn recalculate_and_insert_stake(886 staker: &T::AccountId,887 staked_block: T::BlockNumber,888 next_recalc_block: T::BlockNumber,889 base: BalanceOf<T>,890 iters: u32,891 income_acc: &mut BalanceOf<T>,892 ) {893 let income = Self::calculate_income(base, iters);894895 base.checked_add(&income).map(|res| {896 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));897 *income_acc += income;898 });899 }900901 fn calculate_income<I>(base: I, iters: u32) -> I902 where903 I: EncodeLike<BalanceOf<T>> + Balance,904 {905 let config = <PalletConfiguration<T>>::get();906 let mut income = base;907908 (0..iters).for_each(|_| income += config.interval_income * income);909910 income - base911 }912913 914 915 fn get_current_recalc_block(916 current_relay_block: T::BlockNumber,917 config: &PalletConfiguration<T>,918 ) -> T::BlockNumber {919 (current_relay_block / config.recalculation_interval) * config.recalculation_interval920 }921922 fn get_next_calculated_key() -> Option<Vec<u8>> {923 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))924 }925}926927impl<T: Config> Pallet<T>928where929 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,930{931 932 933 934 935 936 937 938 939 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {940 staker.map_or(941 PendingUnstake::<T>::iter_values()942 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))943 .sum(),944 |s| {945 PendingUnstake::<T>::iter_values()946 .flatten()947 .filter_map(|(id, amount)| {948 if id == *s.as_sub() {949 Some(amount)950 } else {951 None952 }953 })954 .sum()955 },956 )957 }958959 960 961 962 963 pub fn cross_id_pending_unstake_per_block(964 staker: T::CrossAccountId,965 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {966 let mut unsorted_res = vec![];967 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {968 pendings.into_iter().for_each(|(id, amount)| {969 if id == *staker.as_sub() {970 unsorted_res.push((block, amount));971 };972 })973 });974975 unsorted_res.sort_by_key(|(block, _)| *block);976 unsorted_res977 }978979 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {980 let config = <PalletConfiguration<T>>::get();981982 983 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;984985 let mut pendings = <PendingUnstake<T>>::get(block);986987 988 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);989990 let mut total_stakes = 0u64;991992 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))993 .map(|(_, (amount, _))| {994 total_stakes += 1;995 amount996 })997 .sum();998999 if total_staked.is_zero() {1000 return Ok(());1001 }10021003 pendings1004 .try_push((staker_id.clone(), total_staked))1005 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;10061007 <PendingUnstake<T>>::insert(block, pendings);10081009 TotalStaked::<T>::set(1010 TotalStaked::<T>::get()1011 .checked_sub(&total_staked)1012 .ok_or(ArithmeticError::Underflow)?,1013 );10141015 StakesPerAccount::<T>::remove(&staker_id);10161017 Self::deposit_event(Event::Unstake(staker_id, total_staked));10181019 Ok(())1020 }1021}