123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{vec::Vec, vec, iter::Sum, borrow::ToOwned, cell::RefCell};57use sp_core::H160;58use codec::EncodeLike;59pub use types::*;6061use up_data_structs::CollectionId;6263use frame_support::{64 dispatch::{DispatchResult},65 traits::{66 Get,67 tokens::Balance,68 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},69 },70 ensure, BoundedVec,71};7273use weights::WeightInfo;7475pub use pallet::*;76use pallet_evm::account::CrossAccountId;77use sp_runtime::{78 Perbill,79 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},80 ArithmeticError, DispatchError,81};8283const PENDING_LIMIT_PER_BLOCK: u32 = 3;8485type BalanceOf<T> =86 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;8788#[frame_support::pallet]89pub mod pallet {90 use super::*;91 use frame_support::{92 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,93 };94 use frame_system::pallet_prelude::*;95 use sp_runtime::DispatchError;9697 #[pallet::config]98 pub trait Config:99 frame_system::Config + pallet_evm::Config + pallet_configuration::Config100 {101 102 type Currency: MutateFreeze<Self::AccountId> + Mutate<Self::AccountId>;103104 105 type CollectionHandler: CollectionHandler<106 AccountId = Self::AccountId,107 CollectionId = CollectionId,108 >;109110 111 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;112113 114 type TreasuryAccountId: Get<Self::AccountId>;115116 117 #[pallet::constant]118 type PalletId: Get<PalletId>;119120 121 #[pallet::constant]122 type FreezeIdentifier: Get<123 <<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,124 >;125126 127 #[pallet::constant]128 type RecalculationInterval: Get<Self::BlockNumber>;129130 131 #[pallet::constant]132 type PendingInterval: Get<Self::BlockNumber>;133134 135 #[pallet::constant]136 type IntervalIncome: Get<Perbill>;137138 139 #[pallet::constant]140 type Nominal: Get<BalanceOf<Self>>;141142 143 type IsMaintenanceModeEnabled: Get<bool>;144145 146 type WeightInfo: WeightInfo;147148 149 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;150151 152 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;153 }154155 #[pallet::pallet]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 InsufficientStakedBalance,211 212 InconsistencyState,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::hooks]268 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {269 270 271 272 fn on_initialize(current_block_number: T::BlockNumber) -> Weight273 where274 <T as frame_system::Config>::BlockNumber: From<u32>,275 {276 if T::IsMaintenanceModeEnabled::get() {277 return T::DbWeight::get().reads_writes(1, 0);278 }279280 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 if let Some(b) = Self::get_frozen_balance(&staker) {286 let new_state = b.checked_sub(&amount).unwrap_or_default();287288 289 290 291 292 293 Self::set_freeze_unchecked(&staker, new_state);294 };295 });296 }297298 <T as Config>::WeightInfo::on_initialize(counter)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 Inspect<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 = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);353354 355 ensure!(356 amount357 <= match Self::get_frozen_balance(&staker_id) {358 Some(frozen_by_pallet) => balance359 .checked_sub(&frozen_by_pallet)360 .ok_or(ArithmeticError::Underflow)?,361 None => balance,362 },363 ArithmeticError::Underflow364 );365366 Self::add_freeze_balance(&staker_id, amount)?;367368 let block_number = T::RelayBlockNumberProvider::current_block_number();369370 371 372 let recalculate_after_interval: T::BlockNumber =373 if block_number % config.recalculation_interval == 0u32.into() {374 1u32.into()375 } else {376 2u32.into()377 };378379 380 381 let recalc_block = (block_number / config.recalculation_interval382 + recalculate_after_interval)383 * config.recalculation_interval;384385 <Staked<T>>::insert((&staker_id, block_number), {386 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));387 balance_and_recalc_block.0 = balance_and_recalc_block388 .0389 .checked_add(&amount)390 .ok_or(ArithmeticError::Overflow)?;391 balance_and_recalc_block.1 = recalc_block;392 balance_and_recalc_block393 });394395 <TotalStaked<T>>::set(396 <TotalStaked<T>>::get()397 .checked_add(&amount)398 .ok_or(ArithmeticError::Overflow)?,399 );400401 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);402403 Self::deposit_event(Event::Stake(staker_id, amount));404405 Ok(())406 }407408 409 410 411 #[pallet::call_index(2)]412 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]413 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {414 let staker_id = ensure_signed(staker)?;415416 Self::unstake_all_internal(staker_id)417 }418419 420 421 422 423 424 425 426 427 #[pallet::call_index(8)]428 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]429 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {430 let staker_id = ensure_signed(staker)?;431432 Self::unstake_partial_internal(staker_id, amount)433 }434435 436 437 438 439 440 441 442 443 444 #[pallet::call_index(3)]445 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]446 pub fn sponsor_collection(447 admin: OriginFor<T>,448 collection_id: CollectionId,449 ) -> DispatchResult {450 let admin_id = ensure_signed(admin)?;451 ensure!(452 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,453 Error::<T>::NoPermission454 );455456 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)457 }458459 460 461 462 463 464 465 466 467 468 469 470 #[pallet::call_index(4)]471 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]472 pub fn stop_sponsoring_collection(473 admin: OriginFor<T>,474 collection_id: CollectionId,475 ) -> DispatchResult {476 let admin_id = ensure_signed(admin)?;477478 ensure!(479 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,480 Error::<T>::NoPermission481 );482483 ensure!(484 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?485 == Self::account_id(),486 <Error<T>>::NoPermission487 );488 T::CollectionHandler::remove_collection_sponsor(collection_id)489 }490491 492 493 494 495 496 497 498 499 500 #[pallet::call_index(5)]501 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]502 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {503 let admin_id = ensure_signed(admin)?;504505 ensure!(506 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,507 Error::<T>::NoPermission508 );509510 T::ContractHandler::set_sponsor(511 T::CrossAccountId::from_sub(Self::account_id()),512 contract_id,513 )514 }515516 517 518 519 520 521 522 523 524 525 526 527 #[pallet::call_index(6)]528 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]529 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {530 let admin_id = ensure_signed(admin)?;531532 ensure!(533 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,534 Error::<T>::NoPermission535 );536537 ensure!(538 T::ContractHandler::sponsor(contract_id)?539 .ok_or(<Error<T>>::SponsorNotSet)?540 .as_sub() == &Self::account_id(),541 <Error<T>>::NoPermission542 );543 T::ContractHandler::remove_contract_sponsor(contract_id)544 }545546 547 548 549 550 551 552 553 554 555 556 557 558 #[pallet::call_index(7)]559 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]560 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {561 let admin_id = ensure_signed(admin)?;562563 ensure!(564 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565 Error::<T>::NoPermission566 );567 let config = <PalletConfiguration<T>>::get();568569 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);570571 ensure!(572 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,573 Error::<T>::NoPermission574 );575576 577 578 let current_recalc_block = Self::get_current_recalc_block(579 T::RelayBlockNumberProvider::current_block_number(),580 &config,581 );582583 584 585 let next_recalc_block = current_recalc_block + config.recalculation_interval;586587 let storage_iterator =588 Self::get_next_calculated_key().map_or(Staked::<T>::iter(), Staked::<T>::iter_from);589590 PreviousCalculatedRecord::<T>::set(None);591592 {593 594 let last_id = RefCell::new(None);595 596 let mut last_staked_calculated_block = Default::default();597 598 let income_acc = RefCell::new(BalanceOf::<T>::default());599 600 let amount_acc = RefCell::new(BalanceOf::<T>::default());601602 603 604 605 606 607 608 609 let flush_stake = || -> DispatchResult {610 if let Some(last_id) = &*last_id.borrow() {611 if !income_acc.borrow().is_zero() {612 613 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(614 &T::TreasuryAccountId::get(),615 last_id,616 *income_acc.borrow(),617 frame_support::traits::tokens::Preservation::Protect,618 )?;619620 Self::add_freeze_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 for ((current_id, staked_block), (amount, next_recalc_block_for_stake)) in648 storage_iterator649 {650 651 652 653 if last_id.borrow().as_ref() != Some(¤t_id) {654 if stakers_number > 0 {655 flush_stake()?;656 *last_id.borrow_mut() = Some(current_id.clone());657 stakers_number -= 1;658 }659 660 else {661 if let Some(staker) = &*last_id.borrow() {662 663 PreviousCalculatedRecord::<T>::set(Some((664 staker.clone(),665 last_staked_calculated_block,666 )));667 }668 break;669 };670 };671672 673 if current_recalc_block >= next_recalc_block_for_stake {674 *amount_acc.borrow_mut() += amount;675 Self::recalculate_and_insert_stake(676 ¤t_id,677 staked_block,678 next_recalc_block,679 amount,680 ((current_recalc_block - next_recalc_block_for_stake)681 / config.recalculation_interval)682 .into() + 1,683 &mut *income_acc.borrow_mut(),684 );685 }686 last_staked_calculated_block = staked_block;687 }688 flush_stake()?;689 }690691 Ok(())692 }693694 695 696 697 698 699 700 701 702 703 704 #[pallet::call_index(9)]705 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]706 pub fn force_unstake(707 origin: OriginFor<T>,708 pending_blocks: Vec<T::BlockNumber>,709 ) -> DispatchResult {710 ensure_root(origin)?;711712 ensure!(713 pending_blocks714 .iter()715 .all(|b| *b < <frame_system::Pallet<T>>::block_number()),716 <Error<T>>::NoPermission717 );718719 let mut pendings =720 Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());721 pending_blocks722 .into_iter()723 .for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));724725 pendings726 .into_iter()727 .try_for_each(|(staker, amount)| -> Result<(), DispatchError> {728 if let Some(b) = Self::get_frozen_balance(&staker) {729 let new_state = b.checked_sub(&amount).unwrap_or_default();730 Self::set_freeze_with_result(&staker, new_state)?;731 }732733 Ok(())734 })?;735736 Ok(())737 }738 }739}740741impl<T: Config> Pallet<T> {742 743 744 745 746 pub fn account_id() -> T::AccountId {747 T::PalletId::get().into_account_truncating()748 }749750 751 752 753 754 fn unstake_partial_internal(755 staker_id: T::AccountId,756 unstaked_balance: BalanceOf<T>,757 ) -> DispatchResult {758 if unstaked_balance == Default::default() {759 return Ok(());760 }761762 let config = <PalletConfiguration<T>>::get();763764 765 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;766767 let mut pendings = <PendingUnstake<T>>::get(unpending_block);768769 770 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);771772 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();773774 let total_staked = stakes775 .iter()776 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {777 acc + *balance778 });779780 ensure!(781 unstaked_balance <= total_staked,782 <Error<T>>::InsufficientStakedBalance783 );784785 <TotalStaked<T>>::set(786 <TotalStaked<T>>::get()787 .checked_sub(&unstaked_balance)788 .ok_or(ArithmeticError::Underflow)?,789 );790791 stakes.sort_by_key(|(block, _)| *block);792793 let mut acc_amount = unstaked_balance;794 let mut will_deleted_stakes_count = 0u8;795796 let changed_stakes = stakes797 .into_iter()798 .map_while(|(block, (balance_per_block, _))| {799 if acc_amount == <BalanceOf<T>>::default() {800 return None;801 }802 if acc_amount < balance_per_block {803 let res = (block, balance_per_block - acc_amount);804 acc_amount = <BalanceOf<T>>::default();805 Some(res)806 } else {807 acc_amount -= balance_per_block;808 will_deleted_stakes_count += 1;809 Some((block, <BalanceOf<T>>::default()))810 }811 })812 .collect::<Vec<_>>();813814 pendings815 .try_push((staker_id.clone(), unstaked_balance))816 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;817818 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {819 *stakes = stakes820 .checked_sub(will_deleted_stakes_count)821 .ok_or(ArithmeticError::Underflow)?;822 Ok(())823 })?;824825 changed_stakes826 .into_iter()827 .for_each(|(staked_block, current_stake_state)| {828 if current_stake_state == Default::default() {829 <Staked<T>>::remove((&staker_id, staked_block));830 } else {831 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {832 *old_stake_state = current_stake_state833 });834 }835 });836837 <PendingUnstake<T>>::insert(unpending_block, pendings);838839 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));840841 Ok(())842 }843844 845 846 847 848 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {849 Self::get_frozen_balance(staker)850 .unwrap_or_default()851 .checked_add(&amount)852 .map(|freeze| Self::set_freeze_with_result(staker, freeze))853 .ok_or::<DispatchError>(ArithmeticError::Overflow.into())?854 }855856 857 858 859 860 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {861 let _ = Self::set_freeze_with_result(staker, amount);862 }863864 865 866 867 868 fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {869 if amount.is_zero() {870 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(871 &T::FreezeIdentifier::get(),872 staker,873 )874 } else {875 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(876 &T::FreezeIdentifier::get(),877 staker,878 amount,879 )880 }881 }882883 884 885 886 pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {887 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(888 &T::FreezeIdentifier::get(),889 staker,890 );891892 if res == Zero::zero() {893 None894 } else {895 Some(res)896 }897 }898899 900 901 902 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {903 let staked = Staked::<T>::iter_prefix((staker,))904 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {905 acc + amount906 });907 if staked != <BalanceOf<T>>::default() {908 Some(staked)909 } else {910 None911 }912 }913914 915 916 917 918 pub fn total_staked_by_id_per_block(919 staker: impl EncodeLike<T::AccountId>,920 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {921 let mut staked = Staked::<T>::iter_prefix((staker,))922 .map(|(block, (amount, _))| (block, amount))923 .collect::<Vec<_>>();924 staked.sort_by_key(|(block, _)| *block);925 if !staked.is_empty() {926 Some(staked)927 } else {928 None929 }930 }931932 933 934 935 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {936 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {937 Self::total_staked_by_id(s.as_sub())938 })939 }940941 942 943 944 945 pub fn cross_id_total_staked_per_block(946 staker: T::CrossAccountId,947 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {948 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()949 }950951 fn recalculate_and_insert_stake(952 staker: &T::AccountId,953 staked_block: T::BlockNumber,954 next_recalc_block: T::BlockNumber,955 base: BalanceOf<T>,956 iters: u32,957 income_acc: &mut BalanceOf<T>,958 ) {959 let income = Self::calculate_income(base, iters);960961 if let Some(res) = base.checked_add(&income) {962 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));963 *income_acc += income;964 };965 }966967 fn calculate_income<I>(base: I, iters: u32) -> I968 where969 I: EncodeLike<BalanceOf<T>> + Balance,970 {971 let config = <PalletConfiguration<T>>::get();972 let mut income = base;973974 (0..iters).for_each(|_| income += config.interval_income * income);975976 income - base977 }978979 980 981 fn get_current_recalc_block(982 current_relay_block: T::BlockNumber,983 config: &PalletConfiguration<T>,984 ) -> T::BlockNumber {985 (current_relay_block / config.recalculation_interval) * config.recalculation_interval986 }987988 fn get_next_calculated_key() -> Option<Vec<u8>> {989 Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)990 }991}992993impl<T: Config> Pallet<T>994where995 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,996{997 998 999 1000 1001 1002 1003 1004 1005 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1006 staker.map_or(1007 PendingUnstake::<T>::iter_values()1008 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1009 .sum(),1010 |s| {1011 PendingUnstake::<T>::iter_values()1012 .flatten()1013 .filter_map(|(id, amount)| {1014 if id == *s.as_sub() {1015 Some(amount)1016 } else {1017 None1018 }1019 })1020 .sum()1021 },1022 )1023 }10241025 1026 1027 1028 1029 pub fn cross_id_pending_unstake_per_block(1030 staker: T::CrossAccountId,1031 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1032 let mut unsorted_res = vec![];1033 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1034 pendings.into_iter().for_each(|(id, amount)| {1035 if id == *staker.as_sub() {1036 unsorted_res.push((block, amount));1037 };1038 })1039 });10401041 unsorted_res.sort_by_key(|(block, _)| *block);1042 unsorted_res1043 }10441045 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1046 let config = <PalletConfiguration<T>>::get();10471048 1049 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10501051 let mut pendings = <PendingUnstake<T>>::get(block);10521053 1054 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10551056 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1057 .map(|(_, (amount, _))| amount)1058 .sum();10591060 if total_staked.is_zero() {1061 return Ok(());1062 }10631064 pendings1065 .try_push((staker_id.clone(), total_staked))1066 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;10671068 <PendingUnstake<T>>::insert(block, pendings);10691070 TotalStaked::<T>::set(1071 TotalStaked::<T>::get()1072 .checked_sub(&total_staked)1073 .ok_or(ArithmeticError::Underflow)?,1074 );10751076 StakesPerAccount::<T>::remove(&staker_id);10771078 Self::deposit_event(Event::Unstake(staker_id, total_staked));10791080 Ok(())1081 }1082}