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 WeightInfo: WeightInfo;158159 160 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;161162 163 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;164 }165166 #[pallet::pallet]167 pub struct Pallet<T>(_);168169 #[pallet::event]170 #[pallet::generate_deposit(pub(super) fn deposit_event)]171 pub enum Event<T: Config> {172 173 174 175 176 177 178 StakingRecalculation(179 180 T::AccountId,181 182 BalanceOf<T>,183 184 BalanceOf<T>,185 ),186187 188 189 190 191 192 Stake(T::AccountId, BalanceOf<T>),193194 195 196 197 198 199 Unstake(T::AccountId, BalanceOf<T>),200201 202 203 204 205 SetAdmin(T::AccountId),206 }207208 #[pallet::error]209 pub enum Error<T> {210 211 AdminNotSet,212 213 NoPermission,214 215 NotSufficientFunds,216 217 PendingForBlockOverflow,218 219 SponsorNotSet,220 221 InsufficientStakedBalance,222 223 InconsistencyState,224 }225226 227 #[pallet::storage]228 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;229230 231 #[pallet::storage]232 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;233234 235 236 237 238 239 240 #[pallet::storage]241 pub type Staked<T: Config> = StorageNMap<242 Key = (243 Key<Blake2_128Concat, T::AccountId>,244 Key<Twox64Concat, T::BlockNumber>,245 ),246 Value = (BalanceOf<T>, T::BlockNumber),247 QueryKind = ValueQuery,248 >;249250 251 252 253 254 #[pallet::storage]255 pub type StakesPerAccount<T: Config> =256 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;257258 259 260 261 262 #[pallet::storage]263 pub type PendingUnstake<T: Config> = StorageMap<264 _,265 Twox64Concat,266 T::BlockNumber,267 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,268 ValueQuery,269 >;270271 272 273 #[pallet::storage]274 #[pallet::getter(fn get_next_calculated_record)]275 pub type PreviousCalculatedRecord<T: Config> =276 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;277278 279 280 281282 #[pallet::hooks]283 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {284 285 286 287 fn on_initialize(current_block_number: T::BlockNumber) -> Weight288 where289 <T as frame_system::Config>::BlockNumber: From<u32>,290 {291 let block_pending = PendingUnstake::<T>::take(current_block_number);292 let counter = block_pending.len() as u32;293294 if !block_pending.is_empty() {295 block_pending.into_iter().for_each(|(staker, amount)| {296 Self::get_frozen_balance(&staker).map(|b| {297 let new_state = b.checked_sub(&amount).unwrap_or_default();298 Self::set_freeze_unchecked(&staker, new_state);299 });300 });301 }302303 <T as Config>::WeightInfo::on_initialize(counter)304 }305306 307 308 309 310 311 312 313314 315316 317 318 319 320 321 322 323 324 325 326 327328 329 330 331 332 333 334335 336 337 338 339 340 341 342343 344 345 346 347 348 349 350 351 352 353 354 355 356 357358 359 360361 362 363 364 365 366 367 368 369370 371 372 373 374 375 376 377378 379 380 381 382 383 384 385 386 387388 389 390391 392 393 394395 396 397 398399 400401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416417 418 419 420 421 422 423 424 425426 427 428 429 430 431 432 }433434 #[pallet::call]435 impl<T: Config> Pallet<T>436 where437 T::BlockNumber: From<u32> + Into<u32>,438 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,439 {440 441 442 443 444 445 446 447 448 449 #[pallet::call_index(0)]450 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]451 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {452 ensure_root(origin)?;453454 <Admin<T>>::set(Some(admin.as_sub().to_owned()));455456 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));457458 Ok(())459 }460461 462 463 464 465 466 467 468 #[pallet::call_index(1)]469 #[pallet::weight(<T as Config>::WeightInfo::stake())]470 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {471 let staker_id = ensure_signed(staker)?;472473 ensure!(474 StakesPerAccount::<T>::get(&staker_id) < 10,475 Error::<T>::NoPermission476 );477478 ensure!(479 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),480 ArithmeticError::Underflow481 );482 let config = <PalletConfiguration<T>>::get();483484 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);485486 487 ensure!(488 amount489 <= match Self::get_frozen_balance(&staker_id) {490 Some(frozen_by_pallet) => balance491 .checked_sub(&frozen_by_pallet)492 .ok_or(ArithmeticError::Underflow)?,493 None => balance,494 },495 ArithmeticError::Underflow496 );497498 Self::add_freeze_balance(&staker_id, amount)?;499500 let block_number = T::RelayBlockNumberProvider::current_block_number();501502 503 504 let recalculate_after_interval: T::BlockNumber =505 if block_number % config.recalculation_interval == 0u32.into() {506 1u32.into()507 } else {508 2u32.into()509 };510511 512 513 let recalc_block = (block_number / config.recalculation_interval514 + recalculate_after_interval)515 * config.recalculation_interval;516517 <Staked<T>>::insert((&staker_id, block_number), {518 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));519 balance_and_recalc_block.0 = balance_and_recalc_block520 .0521 .checked_add(&amount)522 .ok_or(ArithmeticError::Overflow)?;523 balance_and_recalc_block.1 = recalc_block;524 balance_and_recalc_block525 });526527 <TotalStaked<T>>::set(528 <TotalStaked<T>>::get()529 .checked_add(&amount)530 .ok_or(ArithmeticError::Overflow)?,531 );532533 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);534535 Self::deposit_event(Event::Stake(staker_id, amount));536537 Ok(())538 }539540 541 542 543 #[pallet::call_index(2)]544 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]545 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {546 let staker_id = ensure_signed(staker)?;547548 Self::unstake_all_internal(staker_id)549 }550551 552 553 554 555 556 557 558 559 #[pallet::call_index(8)]560 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]561 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {562 let staker_id = ensure_signed(staker)?;563564 Self::unstake_partial_internal(staker_id, amount)565 }566567 568 569 570 571 572 573 574 575 576 #[pallet::call_index(3)]577 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]578 pub fn sponsor_collection(579 admin: OriginFor<T>,580 collection_id: CollectionId,581 ) -> DispatchResult {582 let admin_id = ensure_signed(admin)?;583 ensure!(584 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,585 Error::<T>::NoPermission586 );587588 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)589 }590591 592 593 594 595 596 597 598 599 600 601 602 #[pallet::call_index(4)]603 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]604 pub fn stop_sponsoring_collection(605 admin: OriginFor<T>,606 collection_id: CollectionId,607 ) -> DispatchResult {608 let admin_id = ensure_signed(admin)?;609610 ensure!(611 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,612 Error::<T>::NoPermission613 );614615 ensure!(616 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?617 == Self::account_id(),618 <Error<T>>::NoPermission619 );620 T::CollectionHandler::remove_collection_sponsor(collection_id)621 }622623 624 625 626 627 628 629 630 631 632 #[pallet::call_index(5)]633 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]634 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {635 let admin_id = ensure_signed(admin)?;636637 ensure!(638 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,639 Error::<T>::NoPermission640 );641642 T::ContractHandler::set_sponsor(643 T::CrossAccountId::from_sub(Self::account_id()),644 contract_id,645 )646 }647648 649 650 651 652 653 654 655 656 657 658 659 #[pallet::call_index(6)]660 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]661 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {662 let admin_id = ensure_signed(admin)?;663664 ensure!(665 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,666 Error::<T>::NoPermission667 );668669 ensure!(670 T::ContractHandler::sponsor(contract_id)?671 .ok_or(<Error<T>>::SponsorNotSet)?672 .as_sub() == &Self::account_id(),673 <Error<T>>::NoPermission674 );675 T::ContractHandler::remove_contract_sponsor(contract_id)676 }677678 679 680 681 682 683 684 685 686 687 688 689 690 #[pallet::call_index(7)]691 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]692 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {693 let admin_id = ensure_signed(admin)?;694695 ensure!(696 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,697 Error::<T>::NoPermission698 );699 let config = <PalletConfiguration<T>>::get();700701 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);702703 ensure!(704 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,705 Error::<T>::NoPermission706 );707708 709 710 let current_recalc_block = Self::get_current_recalc_block(711 T::RelayBlockNumberProvider::current_block_number(),712 &config,713 );714715 716 717 let next_recalc_block = current_recalc_block + config.recalculation_interval;718719 let mut storage_iterator = Self::get_next_calculated_key()720 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));721722 PreviousCalculatedRecord::<T>::set(None);723724 {725 726 let last_id = RefCell::new(None);727 728 let mut last_staked_calculated_block = Default::default();729 730 let income_acc = RefCell::new(BalanceOf::<T>::default());731 732 let amount_acc = RefCell::new(BalanceOf::<T>::default());733734 735 736 737 738 739 740 741 let flush_stake = || -> DispatchResult {742 if let Some(last_id) = &*last_id.borrow() {743 if !income_acc.borrow().is_zero() {744 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(745 &T::TreasuryAccountId::get(),746 last_id,747 *income_acc.borrow(),748 frame_support::traits::tokens::Preservation::Protect,749 )?;750751 Self::add_freeze_balance(last_id, *income_acc.borrow())?;752 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {753 *staked = staked754 .checked_add(&*income_acc.borrow())755 .ok_or(ArithmeticError::Overflow)?;756 Ok(())757 })?;758759 Self::deposit_event(Event::StakingRecalculation(760 last_id.clone(),761 *amount_acc.borrow(),762 *income_acc.borrow(),763 ));764 }765766 *income_acc.borrow_mut() = BalanceOf::<T>::default();767 *amount_acc.borrow_mut() = BalanceOf::<T>::default();768 }769 Ok(())770 };771772 773 774 775 776 777 778 while let Some((779 (current_id, staked_block),780 (amount, next_recalc_block_for_stake),781 )) = storage_iterator.next()782 {783 784 785 786 if last_id.borrow().as_ref() != Some(¤t_id) {787 if stakers_number > 0 {788 flush_stake()?;789 *last_id.borrow_mut() = Some(current_id.clone());790 stakers_number -= 1;791 }792 793 else {794 if let Some(staker) = &*last_id.borrow() {795 796 PreviousCalculatedRecord::<T>::set(Some((797 staker.clone(),798 last_staked_calculated_block,799 )));800 }801 break;802 };803 };804805 806 if current_recalc_block >= next_recalc_block_for_stake {807 *amount_acc.borrow_mut() += amount;808 Self::recalculate_and_insert_stake(809 ¤t_id,810 staked_block,811 next_recalc_block,812 amount,813 ((current_recalc_block - next_recalc_block_for_stake)814 / config.recalculation_interval)815 .into() + 1,816 &mut *income_acc.borrow_mut(),817 );818 }819 last_staked_calculated_block = staked_block;820 }821 flush_stake()?;822 }823824 Ok(())825 }826827 828 829 830 831 832 833 834 835 836 837 #[pallet::call_index(9)]838 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]839 pub fn upgrade_accounts(840 origin: OriginFor<T>,841 stakers: Vec<T::AccountId>,842 ) -> DispatchResult {843 ensure_root(origin)?;844845 stakers846 .into_iter()847 .try_for_each(|s| -> Result<_, DispatchError> {848 if let Some(BalanceLock { amount, .. }) = Self::get_locked_balance(&s) {849 if let Some(_) = Self::get_frozen_balance(&s) {850 return Err(Error::<T>::InconsistencyState.into());851 }852853 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(854 LOCK_IDENTIFIER,855 &s,856 );857858 Self::set_freeze_with_result(&s, amount)?;859 Ok(())860 } else {861 Ok(())862 }863 })?;864865 Ok(())866 }867 }868}869870impl<T: Config> Pallet<T> {871 872 873 874 875 pub fn account_id() -> T::AccountId {876 T::PalletId::get().into_account_truncating()877 }878879 880 881 882 883 fn unstake_partial_internal(884 staker_id: T::AccountId,885 unstaked_balance: BalanceOf<T>,886 ) -> DispatchResult {887 if unstaked_balance == Default::default() {888 return Ok(());889 }890891 let config = <PalletConfiguration<T>>::get();892893 894 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;895896 let mut pendings = <PendingUnstake<T>>::get(unpending_block);897898 899 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);900901 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();902903 let total_staked = stakes904 .iter()905 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {906 acc + *balance907 });908909 ensure!(910 unstaked_balance <= total_staked,911 <Error<T>>::InsufficientStakedBalance912 );913914 <TotalStaked<T>>::set(915 <TotalStaked<T>>::get()916 .checked_sub(&unstaked_balance)917 .ok_or(ArithmeticError::Underflow)?,918 );919920 stakes.sort_by_key(|(block, _)| *block);921922 let mut acc_amount = unstaked_balance;923 let mut will_deleted_stakes_count = 0u8;924925 let changed_stakes = stakes926 .into_iter()927 .map_while(|(block, (balance_per_block, _))| {928 if acc_amount == <BalanceOf<T>>::default() {929 return None;930 }931 if acc_amount < balance_per_block {932 let res = (block, balance_per_block - acc_amount);933 acc_amount = <BalanceOf<T>>::default();934 return Some(res);935 } else {936 acc_amount -= balance_per_block;937 will_deleted_stakes_count += 1;938 return Some((block, <BalanceOf<T>>::default()));939 }940 })941 .collect::<Vec<_>>();942943 pendings944 .try_push((staker_id.clone(), unstaked_balance))945 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;946947 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {948 *stakes = stakes949 .checked_sub(will_deleted_stakes_count)950 .ok_or(ArithmeticError::Underflow)?;951 Ok(())952 })?;953954 changed_stakes955 .into_iter()956 .for_each(|(staked_block, current_stake_state)| {957 if current_stake_state == Default::default() {958 <Staked<T>>::remove((&staker_id, staked_block));959 } else {960 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {961 *old_stake_state = current_stake_state962 });963 }964 });965966 <PendingUnstake<T>>::insert(unpending_block, pendings);967968 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));969970 Ok(())971 }972973 974 975 976 977 978 979 980 981 982 983 984985 986 987 988 989 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {990 Self::get_frozen_balance(staker)991 .unwrap_or_default()992 .checked_add(&amount)993 .map(|freeze| Self::set_freeze_with_result(staker, freeze))994 .ok_or::<DispatchError>(ArithmeticError::Overflow.into())?995 }996997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 10161017 1018 1019 1020 1021 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1022 Self::set_freeze_with_result(staker, amount);1023 }10241025 1026 1027 1028 1029 fn set_freeze_with_result(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {1030 if amount.is_zero() {1031 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1032 &T::FreezeIdentifier::get(),1033 &staker,1034 )1035 } else {1036 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1037 &T::FreezeIdentifier::get(),1038 staker,1039 amount,1040 )1041 }1042 }10431044 1045 1046 1047 pub fn get_locked_balance(1048 staker: impl EncodeLike<T::AccountId>,1049 ) -> Option<BalanceLock<BalanceOf<T>>> {1050 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1051 .into_iter()1052 .find(|l| l.id == LOCK_IDENTIFIER)1053 }10541055 1056 1057 1058 pub fn get_frozen_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1059 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1060 &T::FreezeIdentifier::get(),1061 staker,1062 );10631064 if res == Zero::zero() {1065 None1066 } else {1067 Some(res)1068 }1069 }10701071 1072 1073 1074 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1075 let staked = Staked::<T>::iter_prefix((staker,))1076 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1077 acc + amount1078 });1079 if staked != <BalanceOf<T>>::default() {1080 Some(staked)1081 } else {1082 None1083 }1084 }10851086 1087 1088 1089 1090 pub fn total_staked_by_id_per_block(1091 staker: impl EncodeLike<T::AccountId>,1092 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1093 let mut staked = Staked::<T>::iter_prefix((staker,))1094 .map(|(block, (amount, _))| (block, amount))1095 .collect::<Vec<_>>();1096 staked.sort_by_key(|(block, _)| *block);1097 if !staked.is_empty() {1098 Some(staked)1099 } else {1100 None1101 }1102 }11031104 1105 1106 1107 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1108 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1109 Self::total_staked_by_id(s.as_sub())1110 })1111 }11121113 1114 1115 1116 1117 pub fn cross_id_total_staked_per_block(1118 staker: T::CrossAccountId,1119 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1120 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1121 }11221123 fn recalculate_and_insert_stake(1124 staker: &T::AccountId,1125 staked_block: T::BlockNumber,1126 next_recalc_block: T::BlockNumber,1127 base: BalanceOf<T>,1128 iters: u32,1129 income_acc: &mut BalanceOf<T>,1130 ) {1131 let income = Self::calculate_income(base, iters);11321133 base.checked_add(&income).map(|res| {1134 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1135 *income_acc += income;1136 });1137 }11381139 fn calculate_income<I>(base: I, iters: u32) -> I1140 where1141 I: EncodeLike<BalanceOf<T>> + Balance,1142 {1143 let config = <PalletConfiguration<T>>::get();1144 let mut income = base;11451146 (0..iters).for_each(|_| income += config.interval_income * income);11471148 income - base1149 }11501151 1152 1153 fn get_current_recalc_block(1154 current_relay_block: T::BlockNumber,1155 config: &PalletConfiguration<T>,1156 ) -> T::BlockNumber {1157 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1158 }11591160 fn get_next_calculated_key() -> Option<Vec<u8>> {1161 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1162 }1163}11641165impl<T: Config> Pallet<T>1166where1167 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1168{1169 1170 1171 1172 1173 1174 1175 1176 1177 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1178 staker.map_or(1179 PendingUnstake::<T>::iter_values()1180 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1181 .sum(),1182 |s| {1183 PendingUnstake::<T>::iter_values()1184 .flatten()1185 .filter_map(|(id, amount)| {1186 if id == *s.as_sub() {1187 Some(amount)1188 } else {1189 None1190 }1191 })1192 .sum()1193 },1194 )1195 }11961197 1198 1199 1200 1201 pub fn cross_id_pending_unstake_per_block(1202 staker: T::CrossAccountId,1203 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1204 let mut unsorted_res = vec![];1205 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1206 pendings.into_iter().for_each(|(id, amount)| {1207 if id == *staker.as_sub() {1208 unsorted_res.push((block, amount));1209 };1210 })1211 });12121213 unsorted_res.sort_by_key(|(block, _)| *block);1214 unsorted_res1215 }12161217 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1218 let config = <PalletConfiguration<T>>::get();12191220 1221 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12221223 let mut pendings = <PendingUnstake<T>>::get(block);12241225 1226 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12271228 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1229 .map(|(_, (amount, _))| amount)1230 .sum();12311232 if total_staked.is_zero() {1233 return Ok(());1234 }12351236 pendings1237 .try_push((staker_id.clone(), total_staked))1238 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;12391240 <PendingUnstake<T>>::insert(block, pendings);12411242 TotalStaked::<T>::set(1243 TotalStaked::<T>::get()1244 .checked_sub(&total_staked)1245 .ok_or(ArithmeticError::Underflow)?,1246 );12471248 StakesPerAccount::<T>::remove(&staker_id);12491250 Self::deposit_event(Event::Unstake(staker_id, total_staked));12511252 Ok(())1253 }1254}