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 Get, LockableCurrency,74 tokens::Balance,75 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76 },77 ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85 Perbill,86 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87 ArithmeticError, DispatchError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99 use super::*;100 use frame_support::{101 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102 };103 use frame_system::pallet_prelude::*;104 use sp_runtime::DispatchError;105106 #[pallet::config]107 pub trait Config:108 frame_system::Config + pallet_evm::Config + pallet_configuration::Config109 {110 111 type Currency: MutateFreeze<Self::AccountId>112 + Mutate<Self::AccountId>113 + ExtendedLockableCurrency<114 Self::AccountId,115 Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance,116 >;117118 119 type CollectionHandler: CollectionHandler<120 AccountId = Self::AccountId,121 CollectionId = CollectionId,122 >;123124 125 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;126127 128 type TreasuryAccountId: Get<Self::AccountId>;129130 131 #[pallet::constant]132 type PalletId: Get<PalletId>;133134 135 #[pallet::constant]136 type FreezeIdentifier: Get<137 <<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id,138 >;139140 141 #[pallet::constant]142 type RecalculationInterval: Get<Self::BlockNumber>;143144 145 #[pallet::constant]146 type PendingInterval: Get<Self::BlockNumber>;147148 149 #[pallet::constant]150 type IntervalIncome: Get<Perbill>;151152 153 #[pallet::constant]154 type Nominal: Get<BalanceOf<Self>>;155156 157 type IsMaintenanceModeEnabled: Get<bool>;158159 160 type WeightInfo: WeightInfo;161162 163 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;164165 166 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;167 }168169 #[pallet::pallet]170 pub struct Pallet<T>(_);171172 #[pallet::event]173 #[pallet::generate_deposit(pub(super) fn deposit_event)]174 pub enum Event<T: Config> {175 176 177 178 179 180 181 StakingRecalculation(182 183 T::AccountId,184 185 BalanceOf<T>,186 187 BalanceOf<T>,188 ),189190 191 192 193 194 195 Stake(T::AccountId, BalanceOf<T>),196197 198 199 200 201 202 Unstake(T::AccountId, BalanceOf<T>),203204 205 206 207 208 SetAdmin(T::AccountId),209 }210211 #[pallet::error]212 pub enum Error<T> {213 214 AdminNotSet,215 216 NoPermission,217 218 NotSufficientFunds,219 220 PendingForBlockOverflow,221 222 SponsorNotSet,223 224 InsufficientStakedBalance,225 226 InconsistencyState,227 }228229 230 #[pallet::storage]231 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;232233 234 #[pallet::storage]235 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;236237 238 239 240 241 242 243 #[pallet::storage]244 pub type Staked<T: Config> = StorageNMap<245 Key = (246 Key<Blake2_128Concat, T::AccountId>,247 Key<Twox64Concat, T::BlockNumber>,248 ),249 Value = (BalanceOf<T>, T::BlockNumber),250 QueryKind = ValueQuery,251 >;252253 254 255 256 257 #[pallet::storage]258 pub type StakesPerAccount<T: Config> =259 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;260261 262 263 264 265 #[pallet::storage]266 pub type PendingUnstake<T: Config> = StorageMap<267 _,268 Twox64Concat,269 T::BlockNumber,270 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,271 ValueQuery,272 >;273274 275 276 #[pallet::storage]277 #[pallet::getter(fn get_next_calculated_record)]278 pub type PreviousCalculatedRecord<T: Config> =279 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;280281 #[pallet::hooks]282 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {283 284 285 286 fn on_initialize(current_block_number: T::BlockNumber) -> Weight287 where288 <T as frame_system::Config>::BlockNumber: From<u32>,289 {290 if T::IsMaintenanceModeEnabled::get() {291 return T::DbWeight::get().reads_writes(1, 0);292 }293294 let block_pending = PendingUnstake::<T>::take(current_block_number);295 let counter = block_pending.len() as u32;296297 if !block_pending.is_empty() {298 block_pending.into_iter().for_each(|(staker, amount)| {299 Self::get_frozen_balance(&staker).map(|b| {300 let new_state = b.checked_sub(&amount).unwrap_or_default();301302 303 304 305 306 307 Self::set_freeze_unchecked(&staker, new_state);308 });309 });310 }311312 <T as Config>::WeightInfo::on_initialize(counter)313 }314 }315316 #[pallet::call]317 impl<T: Config> Pallet<T>318 where319 T::BlockNumber: From<u32> + Into<u32>,320 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,321 {322 323 324 325 326 327 328 329 330 331 #[pallet::call_index(0)]332 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]333 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {334 ensure_root(origin)?;335336 <Admin<T>>::set(Some(admin.as_sub().to_owned()));337338 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));339340 Ok(())341 }342343 344 345 346 347 348 349 350 #[pallet::call_index(1)]351 #[pallet::weight(<T as Config>::WeightInfo::stake())]352 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {353 let staker_id = ensure_signed(staker)?;354355 ensure!(356 StakesPerAccount::<T>::get(&staker_id) < 10,357 Error::<T>::NoPermission358 );359360 ensure!(361 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),362 ArithmeticError::Underflow363 );364 let config = <PalletConfiguration<T>>::get();365366 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);367368 369 ensure!(370 amount371 <= match Self::get_frozen_balance(&staker_id) {372 Some(frozen_by_pallet) => balance373 .checked_sub(&frozen_by_pallet)374 .ok_or(ArithmeticError::Underflow)?,375 None => balance,376 },377 ArithmeticError::Underflow378 );379380 Self::add_freeze_balance(&staker_id, amount)?;381382 let block_number = T::RelayBlockNumberProvider::current_block_number();383384 385 386 let recalculate_after_interval: T::BlockNumber =387 if block_number % config.recalculation_interval == 0u32.into() {388 1u32.into()389 } else {390 2u32.into()391 };392393 394 395 let recalc_block = (block_number / config.recalculation_interval396 + recalculate_after_interval)397 * config.recalculation_interval;398399 <Staked<T>>::insert((&staker_id, block_number), {400 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));401 balance_and_recalc_block.0 = balance_and_recalc_block402 .0403 .checked_add(&amount)404 .ok_or(ArithmeticError::Overflow)?;405 balance_and_recalc_block.1 = recalc_block;406 balance_and_recalc_block407 });408409 <TotalStaked<T>>::set(410 <TotalStaked<T>>::get()411 .checked_add(&amount)412 .ok_or(ArithmeticError::Overflow)?,413 );414415 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);416417 Self::deposit_event(Event::Stake(staker_id, amount));418419 Ok(())420 }421422 423 424 425 #[pallet::call_index(2)]426 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]427 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {428 let staker_id = ensure_signed(staker)?;429430 Self::unstake_all_internal(staker_id)431 }432433 434 435 436 437 438 439 440 441 #[pallet::call_index(8)]442 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]443 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {444 let staker_id = ensure_signed(staker)?;445446 Self::unstake_partial_internal(staker_id, amount)447 }448449 450 451 452 453 454 455 456 457 458 #[pallet::call_index(3)]459 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]460 pub fn sponsor_collection(461 admin: OriginFor<T>,462 collection_id: CollectionId,463 ) -> DispatchResult {464 let admin_id = ensure_signed(admin)?;465 ensure!(466 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,467 Error::<T>::NoPermission468 );469470 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)471 }472473 474 475 476 477 478 479 480 481 482 483 484 #[pallet::call_index(4)]485 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]486 pub fn stop_sponsoring_collection(487 admin: OriginFor<T>,488 collection_id: CollectionId,489 ) -> DispatchResult {490 let admin_id = ensure_signed(admin)?;491492 ensure!(493 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,494 Error::<T>::NoPermission495 );496497 ensure!(498 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?499 == Self::account_id(),500 <Error<T>>::NoPermission501 );502 T::CollectionHandler::remove_collection_sponsor(collection_id)503 }504505 506 507 508 509 510 511 512 513 514 #[pallet::call_index(5)]515 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]516 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {517 let admin_id = ensure_signed(admin)?;518519 ensure!(520 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,521 Error::<T>::NoPermission522 );523524 T::ContractHandler::set_sponsor(525 T::CrossAccountId::from_sub(Self::account_id()),526 contract_id,527 )528 }529530 531 532 533 534 535 536 537 538 539 540 541 #[pallet::call_index(6)]542 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]543 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {544 let admin_id = ensure_signed(admin)?;545546 ensure!(547 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,548 Error::<T>::NoPermission549 );550551 ensure!(552 T::ContractHandler::sponsor(contract_id)?553 .ok_or(<Error<T>>::SponsorNotSet)?554 .as_sub() == &Self::account_id(),555 <Error<T>>::NoPermission556 );557 T::ContractHandler::remove_contract_sponsor(contract_id)558 }559560 561 562 563 564 565 566 567 568 569 570 571 572 #[pallet::call_index(7)]573 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]574 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {575 let admin_id = ensure_signed(admin)?;576577 ensure!(578 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,579 Error::<T>::NoPermission580 );581 let config = <PalletConfiguration<T>>::get();582583 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);584585 ensure!(586 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,587 Error::<T>::NoPermission588 );589590 591 592 let current_recalc_block = Self::get_current_recalc_block(593 T::RelayBlockNumberProvider::current_block_number(),594 &config,595 );596597 598 599 let next_recalc_block = current_recalc_block + config.recalculation_interval;600601 let mut storage_iterator = Self::get_next_calculated_key()602 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));603604 PreviousCalculatedRecord::<T>::set(None);605606 {607 608 let last_id = RefCell::new(None);609 610 let mut last_staked_calculated_block = Default::default();611 612 let income_acc = RefCell::new(BalanceOf::<T>::default());613 614 let amount_acc = RefCell::new(BalanceOf::<T>::default());615616 617 618 619 620 621 622 623 let flush_stake = || -> DispatchResult {624 if let Some(last_id) = &*last_id.borrow() {625 if !income_acc.borrow().is_zero() {626 627 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(628 &T::TreasuryAccountId::get(),629 last_id,630 *income_acc.borrow(),631 frame_support::traits::tokens::Preservation::Protect,632 )?;633634 Self::add_freeze_balance(last_id, *income_acc.borrow())?;635 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {636 *staked = staked637 .checked_add(&*income_acc.borrow())638 .ok_or(ArithmeticError::Overflow)?;639 Ok(())640 })?;641642 Self::deposit_event(Event::StakingRecalculation(643 last_id.clone(),644 *amount_acc.borrow(),645 *income_acc.borrow(),646 ));647 }648649 *income_acc.borrow_mut() = BalanceOf::<T>::default();650 *amount_acc.borrow_mut() = BalanceOf::<T>::default();651 }652 Ok(())653 };654655 656 657 658 659 660 661 while let Some((662 (current_id, staked_block),663 (amount, next_recalc_block_for_stake),664 )) = storage_iterator.next()665 {666 667 668 669 if last_id.borrow().as_ref() != Some(¤t_id) {670 if stakers_number > 0 {671 flush_stake()?;672 *last_id.borrow_mut() = Some(current_id.clone());673 stakers_number -= 1;674 }675 676 else {677 if let Some(staker) = &*last_id.borrow() {678 679 PreviousCalculatedRecord::<T>::set(Some((680 staker.clone(),681 last_staked_calculated_block,682 )));683 }684 break;685 };686 };687688 689 if current_recalc_block >= next_recalc_block_for_stake {690 *amount_acc.borrow_mut() += amount;691 Self::recalculate_and_insert_stake(692 ¤t_id,693 staked_block,694 next_recalc_block,695 amount,696 ((current_recalc_block - next_recalc_block_for_stake)697 / config.recalculation_interval)698 .into() + 1,699 &mut *income_acc.borrow_mut(),700 );701 }702 last_staked_calculated_block = staked_block;703 }704 flush_stake()?;705 }706707 Ok(())708 }709710 711 712 713 714 715 716 717 718 719 720 #[pallet::call_index(9)]721 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]722 pub fn upgrade_accounts(723 origin: OriginFor<T>,724 stakers: Vec<T::AccountId>,725 ) -> DispatchResult {726 ensure_root(origin)?;727728 stakers729 .into_iter()730 .try_for_each(|s| -> Result<_, DispatchError> {731 if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {732 if Self::get_frozen_balance(&s).is_some() {733 return Err(Error::<T>::InconsistencyState.into());734 }735736 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(737 LOCK_IDENTIFIER,738 &s,739 );740741 Self::set_freeze_with_result(&s, amount)?;742 Ok(())743 } else {744 Ok(())745 }746 })?;747748 Ok(())749 }750751 752 753 754 755 756 757 758 759 760 761 #[pallet::call_index(10)]762 #[pallet::weight(<T as Config>::WeightInfo::on_initialize(PENDING_LIMIT_PER_BLOCK*pending_blocks.len() as u32))]763 pub fn force_unstake(764 origin: OriginFor<T>,765 pending_blocks: Vec<T::BlockNumber>,766 ) -> DispatchResult {767 ensure_root(origin)?;768769 ensure!(770 pending_blocks771 .iter()772 .all(|b| *b < <frame_system::Pallet<T>>::block_number()),773 <Error<T>>::NoPermission774 );775776 let mut pendings =777 Vec::with_capacity(PENDING_LIMIT_PER_BLOCK as usize * pending_blocks.len());778 pending_blocks779 .into_iter()780 .for_each(|b| pendings.append(&mut PendingUnstake::<T>::take(b).into_inner()));781782 pendings783 .into_iter()784 .try_for_each(|(staker, amount)| -> Result<(), DispatchError> {785 if let Some(b) = Self::get_frozen_balance(&staker) {786 let new_state = b.checked_sub(&amount).unwrap_or_default();787 Self::set_freeze_with_result(&staker, new_state)?;788 }789790 Ok(())791 })?;792793 Ok(())794 }795 }796}797798impl<T: Config> Pallet<T> {799 800 801 802 803 pub fn account_id() -> T::AccountId {804 T::PalletId::get().into_account_truncating()805 }806807 808 809 810 811 fn unstake_partial_internal(812 staker_id: T::AccountId,813 unstaked_balance: BalanceOf<T>,814 ) -> DispatchResult {815 if unstaked_balance == Default::default() {816 return Ok(());817 }818819 let config = <PalletConfiguration<T>>::get();820821 822 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;823824 let mut pendings = <PendingUnstake<T>>::get(unpending_block);825826 827 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);828829 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();830831 let total_staked = stakes832 .iter()833 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {834 acc + *balance835 });836837 ensure!(838 unstaked_balance <= total_staked,839 <Error<T>>::InsufficientStakedBalance840 );841842 <TotalStaked<T>>::set(843 <TotalStaked<T>>::get()844 .checked_sub(&unstaked_balance)845 .ok_or(ArithmeticError::Underflow)?,846 );847848 stakes.sort_by_key(|(block, _)| *block);849850 let mut acc_amount = unstaked_balance;851 let mut will_deleted_stakes_count = 0u8;852853 let changed_stakes = stakes854 .into_iter()855 .map_while(|(block, (balance_per_block, _))| {856 if acc_amount == <BalanceOf<T>>::default() {857 return None;858 }859 if acc_amount < balance_per_block {860 let res = (block, balance_per_block - acc_amount);861 acc_amount = <BalanceOf<T>>::default();862 return Some(res);863 } else {864 acc_amount -= balance_per_block;865 will_deleted_stakes_count += 1;866 return Some((block, <BalanceOf<T>>::default()));867 }868 })869 .collect::<Vec<_>>();870871 pendings872 .try_push((staker_id.clone(), unstaked_balance))873 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;874875 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {876 *stakes = stakes877 .checked_sub(will_deleted_stakes_count)878 .ok_or(ArithmeticError::Underflow)?;879 Ok(())880 })?;881882 changed_stakes883 .into_iter()884 .for_each(|(staked_block, current_stake_state)| {885 if current_stake_state == Default::default() {886 <Staked<T>>::remove((&staker_id, staked_block));887 } else {888 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {889 *old_stake_state = current_stake_state890 });891 }892 });893894 <PendingUnstake<T>>::insert(unpending_block, pendings);895896 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));897898 Ok(())899 }900901 902 903 904 905 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {906 Self::get_frozen_balance(staker)907 .unwrap_or_default()908 .checked_add(&amount)909 .map(|freeze| Self::set_freeze_with_result(staker, freeze))910 .ok_or::<DispatchError>(ArithmeticError::Overflow.into())?911 }912913 914 915 916 917 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {918 let _ = Self::set_freeze_with_result(staker, amount);919 }920921 922 923 924 925 fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {926 if amount.is_zero() {927 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(928 &T::FreezeIdentifier::get(),929 &staker,930 )931 } else {932 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(933 &T::FreezeIdentifier::get(),934 staker,935 amount,936 )937 }938 }939940 941 942 943 pub fn get_locked_balance(944 staker: impl EncodeLike<T::AccountId>,945 ) -> Option<BalanceLock<BalanceOf<T>>> {946 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)947 .into_iter()948 .find(|l| l.id == LOCK_IDENTIFIER)949 }950951 952 953 954 pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {955 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(956 &T::FreezeIdentifier::get(),957 staker,958 );959960 if res == Zero::zero() {961 None962 } else {963 Some(res)964 }965 }966967 968 969 970 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {971 let staked = Staked::<T>::iter_prefix((staker,))972 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {973 acc + amount974 });975 if staked != <BalanceOf<T>>::default() {976 Some(staked)977 } else {978 None979 }980 }981982 983 984 985 986 pub fn total_staked_by_id_per_block(987 staker: impl EncodeLike<T::AccountId>,988 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {989 let mut staked = Staked::<T>::iter_prefix((staker,))990 .map(|(block, (amount, _))| (block, amount))991 .collect::<Vec<_>>();992 staked.sort_by_key(|(block, _)| *block);993 if !staked.is_empty() {994 Some(staked)995 } else {996 None997 }998 }9991000 1001 1002 1003 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1004 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1005 Self::total_staked_by_id(s.as_sub())1006 })1007 }10081009 1010 1011 1012 1013 pub fn cross_id_total_staked_per_block(1014 staker: T::CrossAccountId,1015 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1016 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1017 }10181019 fn recalculate_and_insert_stake(1020 staker: &T::AccountId,1021 staked_block: T::BlockNumber,1022 next_recalc_block: T::BlockNumber,1023 base: BalanceOf<T>,1024 iters: u32,1025 income_acc: &mut BalanceOf<T>,1026 ) {1027 let income = Self::calculate_income(base, iters);10281029 base.checked_add(&income).map(|res| {1030 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1031 *income_acc += income;1032 });1033 }10341035 fn calculate_income<I>(base: I, iters: u32) -> I1036 where1037 I: EncodeLike<BalanceOf<T>> + Balance,1038 {1039 let config = <PalletConfiguration<T>>::get();1040 let mut income = base;10411042 (0..iters).for_each(|_| income += config.interval_income * income);10431044 income - base1045 }10461047 1048 1049 fn get_current_recalc_block(1050 current_relay_block: T::BlockNumber,1051 config: &PalletConfiguration<T>,1052 ) -> T::BlockNumber {1053 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1054 }10551056 fn get_next_calculated_key() -> Option<Vec<u8>> {1057 Self::get_next_calculated_record().map(Staked::<T>::hashed_key_for)1058 }1059}10601061impl<T: Config> Pallet<T>1062where1063 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1064{1065 1066 1067 1068 1069 1070 1071 1072 1073 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1074 staker.map_or(1075 PendingUnstake::<T>::iter_values()1076 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1077 .sum(),1078 |s| {1079 PendingUnstake::<T>::iter_values()1080 .flatten()1081 .filter_map(|(id, amount)| {1082 if id == *s.as_sub() {1083 Some(amount)1084 } else {1085 None1086 }1087 })1088 .sum()1089 },1090 )1091 }10921093 1094 1095 1096 1097 pub fn cross_id_pending_unstake_per_block(1098 staker: T::CrossAccountId,1099 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1100 let mut unsorted_res = vec![];1101 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1102 pendings.into_iter().for_each(|(id, amount)| {1103 if id == *staker.as_sub() {1104 unsorted_res.push((block, amount));1105 };1106 })1107 });11081109 unsorted_res.sort_by_key(|(block, _)| *block);1110 unsorted_res1111 }11121113 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1114 let config = <PalletConfiguration<T>>::get();11151116 1117 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;11181119 let mut pendings = <PendingUnstake<T>>::get(block);11201121 1122 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);11231124 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1125 .map(|(_, (amount, _))| amount)1126 .sum();11271128 if total_staked.is_zero() {1129 return Ok(());1130 }11311132 pendings1133 .try_push((staker_id.clone(), total_staked))1134 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;11351136 <PendingUnstake<T>>::insert(block, pendings);11371138 TotalStaked::<T>::set(1139 TotalStaked::<T>::get()1140 .checked_sub(&total_staked)1141 .ok_or(ArithmeticError::Underflow)?,1142 );11431144 StakesPerAccount::<T>::remove(&staker_id);11451146 Self::deposit_event(Event::Unstake(staker_id, total_staked));11471148 Ok(())1149 }1150}