123456789101112131415161718192021222324252627282930313233343536373839404142434445464748#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency, weights::Weight,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config:106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config107 {108 109 type Currency: ExtendedLockableCurrency<Self::AccountId>110 + ReservableCurrency<Self::AccountId>;111112 113 type CollectionHandler: CollectionHandler<114 AccountId = Self::AccountId,115 CollectionId = CollectionId,116 >;117118 119 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121 122 type TreasuryAccountId: Get<Self::AccountId>;123124 125 #[pallet::constant]126 type PalletId: Get<PalletId>;127128 129 #[pallet::constant]130 type RecalculationInterval: Get<Self::BlockNumber>;131132 133 #[pallet::constant]134 type PendingInterval: Get<Self::BlockNumber>;135136 137 #[pallet::constant]138 type IntervalIncome: Get<Perbill>;139140 141 #[pallet::constant]142 type Nominal: Get<BalanceOf<Self>>;143144 145 type WeightInfo: WeightInfo;146147 148 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150 151 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152 }153154 #[pallet::pallet]155 #[pallet::generate_store(pub(super) trait Store)]156 pub struct Pallet<T>(_);157158 #[pallet::event]159 #[pallet::generate_deposit(pub(super) fn deposit_event)]160 pub enum Event<T: Config> {161 162 163 164 165 166 167 StakingRecalculation(168 169 T::AccountId,170 171 BalanceOf<T>,172 173 BalanceOf<T>,174 ),175176 177 178 179 180 181 Stake(T::AccountId, BalanceOf<T>),182183 184 185 186 187 188 Unstake(T::AccountId, BalanceOf<T>),189190 191 192 193 194 SetAdmin(T::AccountId),195 }196197 #[pallet::error]198 pub enum Error<T> {199 200 AdminNotSet,201 202 NoPermission,203 204 NotSufficientFunds,205 206 PendingForBlockOverflow,207 208 SponsorNotSet,209 210 IncorrectLockedBalanceOperation,211 212 InsufficientStakedBalance,213 }214215 216 #[pallet::storage]217 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;218219 220 #[pallet::storage]221 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;222223 224 225 226 227 228 229 #[pallet::storage]230 pub type Staked<T: Config> = StorageNMap<231 Key = (232 Key<Blake2_128Concat, T::AccountId>,233 Key<Twox64Concat, T::BlockNumber>,234 ),235 Value = (BalanceOf<T>, T::BlockNumber),236 QueryKind = ValueQuery,237 >;238239 240 241 242 243 #[pallet::storage]244 pub type StakesPerAccount<T: Config> =245 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;246247 248 249 250 251 #[pallet::storage]252 pub type PendingUnstake<T: Config> = StorageMap<253 _,254 Twox64Concat,255 T::BlockNumber,256 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,257 ValueQuery,258 >;259260 261 262 #[pallet::storage]263 #[pallet::getter(fn get_next_calculated_record)]264 pub type PreviousCalculatedRecord<T: Config> =265 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;266267 #[pallet::storage]268 pub(crate) type UpgradedToReserves<T: Config> =269 StorageValue<Value = bool, QueryKind = ValueQuery>;270271 #[pallet::hooks]272 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {273 274 275 276 fn on_initialize(current_block_number: T::BlockNumber) -> Weight277 where278 <T as frame_system::Config>::BlockNumber: From<u32>,279 {280 let block_pending = PendingUnstake::<T>::take(current_block_number);281 let counter = block_pending.len() as u32;282283 if !block_pending.is_empty() {284 block_pending.into_iter().for_each(|(staker, amount)| {285 Self::get_locked_balance(&staker).map(|b| {286 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();287 Self::set_lock_unchecked(&staker, new_state);288 });289 });290 }291292 <T as Config>::WeightInfo::on_initialize(counter)293 }294295 fn on_runtime_upgrade() -> Weight {296 let mut consumed_weight = Weight::zero();297 let mut add_weight = |reads, writes, weight| {298 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);299 consumed_weight += weight;300 };301302 if <UpgradedToReserves<T>>::get() {303 add_weight(1, 0, Weight::zero());304 return consumed_weight;305 } else {306 add_weight(1, 1, Weight::zero());307 <UpgradedToReserves<T>>::set(true);308 }309 <PendingUnstake<T>>::drain().for_each(|(_, v)| {310 add_weight(1, 1, Weight::zero());311 v.into_iter().for_each(|(staker, amount)| {312 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(313 &staker, amount,314 );315 add_weight(1, 1, Weight::zero());316 });317 });318319 consumed_weight320 }321322 #[cfg(feature = "try-runtime")]323 fn pre_upgrade() -> Result<Vec<u8>, &'static str> {324 use sp_std::collections::btree_map::BTreeMap;325 if <UpgradedToReserves<T>>::get() {326 return Ok(Default::default());327 }328 329 let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =330 BTreeMap::new();331332 <PendingUnstake<T>>::iter().for_each(|(_, v)| {333 v.into_iter().for_each(|(staker, amount)| {334 if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {335 *reserved_balance += amount;336 } else {337 let total_reserve = <<T as Config>::Currency as ReservableCurrency<338 T::AccountId,339 >>::reserved_balance(&staker);340 pre_state.insert(staker, (total_reserve, amount));341 }342 })343 });344345 Ok(pre_state.encode())346 }347348 #[cfg(feature = "try-runtime")]349 fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {350 use sp_std::collections::btree_map::BTreeMap;351352 if <UpgradedToReserves<T>>::get() {353 return Ok(());354 }355356 ensure!(357 <PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,358 "pendingUnstake storage isn't empty"359 );360361 let mut is_ok = true;362363 let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =364 Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;365 for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {366 let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<367 T::AccountId,368 >>::reserved_balance(&staker);369 if new_state_reserve != total_reserved - reserved_by_promo {370 is_ok = false;371 log::error!(372 "Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",373 staker, new_state_reserve, total_reserved, reserved_by_promo374 );375 }376 }377378 if is_ok {379 Ok(())380 } else {381 Err("Incorrect balance for some of stakers... See logs")382 }383 }384 }385386 #[pallet::call]387 impl<T: Config> Pallet<T>388 where389 T::BlockNumber: From<u32> + Into<u32>,390 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,391 {392 393 394 395 396 397 398 399 400 401 #[pallet::call_index(0)]402 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]403 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {404 ensure_root(origin)?;405406 <Admin<T>>::set(Some(admin.as_sub().to_owned()));407408 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));409410 Ok(())411 }412413 414 415 416 417 418 419 420 #[pallet::call_index(1)]421 #[pallet::weight(<T as Config>::WeightInfo::stake())]422 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {423 let staker_id = ensure_signed(staker)?;424425 ensure!(426 StakesPerAccount::<T>::get(&staker_id) < 10,427 Error::<T>::NoPermission428 );429430 ensure!(431 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),432 ArithmeticError::Underflow433 );434 let config = <PalletConfiguration<T>>::get();435436 let balance =437 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);438439 440 ensure!(441 amount442 <= match Self::get_locked_balance(&staker_id) {443 Some(lock) => balance444 .checked_sub(&lock.amount)445 .ok_or(ArithmeticError::Underflow)?,446 None => balance,447 },448 ArithmeticError::Underflow449 );450451 Self::add_lock_balance(&staker_id, amount)?;452453 let block_number = T::RelayBlockNumberProvider::current_block_number();454455 456 457 let recalculate_after_interval: T::BlockNumber =458 if block_number % config.recalculation_interval == 0u32.into() {459 1u32.into()460 } else {461 2u32.into()462 };463464 465 466 let recalc_block = (block_number / config.recalculation_interval467 + recalculate_after_interval)468 * config.recalculation_interval;469470 <Staked<T>>::insert((&staker_id, block_number), {471 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));472 balance_and_recalc_block.0 = balance_and_recalc_block473 .0474 .checked_add(&amount)475 .ok_or(ArithmeticError::Overflow)?;476 balance_and_recalc_block.1 = recalc_block;477 balance_and_recalc_block478 });479480 <TotalStaked<T>>::set(481 <TotalStaked<T>>::get()482 .checked_add(&amount)483 .ok_or(ArithmeticError::Overflow)?,484 );485486 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);487488 Self::deposit_event(Event::Stake(staker_id, amount));489490 Ok(())491 }492493 494 495 496 #[pallet::call_index(2)]497 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]498 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {499 let staker_id = ensure_signed(staker)?;500501 Self::unstake_all_internal(staker_id)502 }503504 505 506 507 508 509 510 511 512 #[pallet::call_index(8)]513 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]514 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {515 let staker_id = ensure_signed(staker)?;516517 Self::unstake_partial_internal(staker_id, amount)518 }519520 521 522 523 524 525 526 527 528 529 #[pallet::call_index(3)]530 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]531 pub fn sponsor_collection(532 admin: OriginFor<T>,533 collection_id: CollectionId,534 ) -> DispatchResult {535 let admin_id = ensure_signed(admin)?;536 ensure!(537 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,538 Error::<T>::NoPermission539 );540541 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)542 }543544 545 546 547 548 549 550 551 552 553 554 555 #[pallet::call_index(4)]556 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]557 pub fn stop_sponsoring_collection(558 admin: OriginFor<T>,559 collection_id: CollectionId,560 ) -> 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 );567568 ensure!(569 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?570 == Self::account_id(),571 <Error<T>>::NoPermission572 );573 T::CollectionHandler::remove_collection_sponsor(collection_id)574 }575576 577 578 579 580 581 582 583 584 585 #[pallet::call_index(5)]586 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]587 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {588 let admin_id = ensure_signed(admin)?;589590 ensure!(591 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,592 Error::<T>::NoPermission593 );594595 T::ContractHandler::set_sponsor(596 T::CrossAccountId::from_sub(Self::account_id()),597 contract_id,598 )599 }600601 602 603 604 605 606 607 608 609 610 611 612 #[pallet::call_index(6)]613 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]614 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {615 let admin_id = ensure_signed(admin)?;616617 ensure!(618 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,619 Error::<T>::NoPermission620 );621622 ensure!(623 T::ContractHandler::sponsor(contract_id)?624 .ok_or(<Error<T>>::SponsorNotSet)?625 .as_sub() == &Self::account_id(),626 <Error<T>>::NoPermission627 );628 T::ContractHandler::remove_contract_sponsor(contract_id)629 }630631 632 633 634 635 636 637 638 639 640 641 642 643 #[pallet::call_index(7)]644 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]645 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {646 let admin_id = ensure_signed(admin)?;647648 ensure!(649 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,650 Error::<T>::NoPermission651 );652 let config = <PalletConfiguration<T>>::get();653654 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);655656 ensure!(657 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,658 Error::<T>::NoPermission659 );660661 662 663 let current_recalc_block = Self::get_current_recalc_block(664 T::RelayBlockNumberProvider::current_block_number(),665 &config,666 );667668 669 670 let next_recalc_block = current_recalc_block + config.recalculation_interval;671672 let mut storage_iterator = Self::get_next_calculated_key()673 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));674675 PreviousCalculatedRecord::<T>::set(None);676677 {678 679 let last_id = RefCell::new(None);680 681 let mut last_staked_calculated_block = Default::default();682 683 let income_acc = RefCell::new(BalanceOf::<T>::default());684 685 let amount_acc = RefCell::new(BalanceOf::<T>::default());686687 688 689 690 691 692 693 694 let flush_stake = || -> DispatchResult {695 if let Some(last_id) = &*last_id.borrow() {696 if !income_acc.borrow().is_zero() {697 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(698 &T::TreasuryAccountId::get(),699 last_id,700 *income_acc.borrow(),701 ExistenceRequirement::KeepAlive,702 )?;703704 Self::add_lock_balance(last_id, *income_acc.borrow())?;705 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {706 *staked = staked707 .checked_add(&*income_acc.borrow())708 .ok_or(ArithmeticError::Overflow)?;709 Ok(())710 })?;711712 Self::deposit_event(Event::StakingRecalculation(713 last_id.clone(),714 *amount_acc.borrow(),715 *income_acc.borrow(),716 ));717 }718719 *income_acc.borrow_mut() = BalanceOf::<T>::default();720 *amount_acc.borrow_mut() = BalanceOf::<T>::default();721 }722 Ok(())723 };724725 726 727 728 729 730 731 while let Some((732 (current_id, staked_block),733 (amount, next_recalc_block_for_stake),734 )) = storage_iterator.next()735 {736 737 738 739 if last_id.borrow().as_ref() != Some(¤t_id) {740 if stakers_number > 0 {741 flush_stake()?;742 *last_id.borrow_mut() = Some(current_id.clone());743 stakers_number -= 1;744 }745 746 else {747 if let Some(staker) = &*last_id.borrow() {748 749 PreviousCalculatedRecord::<T>::set(Some((750 staker.clone(),751 last_staked_calculated_block,752 )));753 }754 break;755 };756 };757758 759 if current_recalc_block >= next_recalc_block_for_stake {760 *amount_acc.borrow_mut() += amount;761 Self::recalculate_and_insert_stake(762 ¤t_id,763 staked_block,764 next_recalc_block,765 amount,766 ((current_recalc_block - next_recalc_block_for_stake)767 / config.recalculation_interval)768 .into() + 1,769 &mut *income_acc.borrow_mut(),770 );771 }772 last_staked_calculated_block = staked_block;773 }774 flush_stake()?;775 }776777 Ok(())778 }779 }780}781782impl<T: Config> Pallet<T> {783 784 785 786 787 pub fn account_id() -> T::AccountId {788 T::PalletId::get().into_account_truncating()789 }790791 792 793 794 795 fn unstake_partial_internal(796 staker_id: T::AccountId,797 unstaked_balance: BalanceOf<T>,798 ) -> DispatchResult {799 if unstaked_balance == Default::default() {800 return Ok(());801 }802803 let config = <PalletConfiguration<T>>::get();804805 806 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;807808 let mut pendings = <PendingUnstake<T>>::get(unpending_block);809810 811 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);812813 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();814815 let total_staked = stakes816 .iter()817 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {818 acc + *balance819 });820821 ensure!(822 unstaked_balance <= total_staked,823 <Error<T>>::InsufficientStakedBalance824 );825826 <TotalStaked<T>>::set(827 <TotalStaked<T>>::get()828 .checked_sub(&unstaked_balance)829 .ok_or(ArithmeticError::Underflow)?,830 );831832 stakes.sort_by_key(|(block, _)| *block);833834 let mut acc_amount = unstaked_balance;835 let mut will_deleted_stakes_count = 0u8;836837 let changed_stakes = stakes838 .into_iter()839 .map_while(|(block, (balance_per_block, _))| {840 if acc_amount == <BalanceOf<T>>::default() {841 return None;842 }843 if acc_amount < balance_per_block {844 let res = (block, balance_per_block - acc_amount);845 acc_amount = <BalanceOf<T>>::default();846 return Some(res);847 } else {848 acc_amount -= balance_per_block;849 will_deleted_stakes_count += 1;850 return Some((block, <BalanceOf<T>>::default()));851 }852 })853 .collect::<Vec<_>>();854855 pendings856 .try_push((staker_id.clone(), unstaked_balance))857 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;858859 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {860 *stakes = stakes861 .checked_sub(will_deleted_stakes_count)862 .ok_or(ArithmeticError::Underflow)?;863 Ok(())864 })?;865866 changed_stakes867 .into_iter()868 .for_each(|(staked_block, current_stake_state)| {869 if current_stake_state == Default::default() {870 <Staked<T>>::remove((&staker_id, staked_block));871 } else {872 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {873 *old_stake_state = current_stake_state874 });875 }876 });877878 <PendingUnstake<T>>::insert(unpending_block, pendings);879880 Self::deposit_event(Event::Unstake(staker_id, total_staked));881882 Ok(())883 }884885 886 887 888 889 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {890 Self::get_locked_balance(staker)891 .map_or(<BalanceOf<T>>::default(), |l| l.amount)892 .checked_add(&amount)893 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))894 .ok_or(ArithmeticError::Overflow.into())895 }896897 898 899 900 901 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {902 if amount.is_zero() {903 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(904 LOCK_IDENTIFIER,905 &staker,906 );907 } else {908 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(909 LOCK_IDENTIFIER,910 staker,911 amount,912 WithdrawReasons::all(),913 )914 }915 }916917 918 919 920 pub fn get_locked_balance(921 staker: impl EncodeLike<T::AccountId>,922 ) -> Option<BalanceLock<BalanceOf<T>>> {923 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)924 .into_iter()925 .find(|l| l.id == LOCK_IDENTIFIER)926 }927928 929 930 931 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {932 let staked = Staked::<T>::iter_prefix((staker,))933 .into_iter()934 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {935 acc + amount936 });937 if staked != <BalanceOf<T>>::default() {938 Some(staked)939 } else {940 None941 }942 }943944 945 946 947 948 pub fn total_staked_by_id_per_block(949 staker: impl EncodeLike<T::AccountId>,950 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {951 let mut staked = Staked::<T>::iter_prefix((staker,))952 .into_iter()953 .map(|(block, (amount, _))| (block, amount))954 .collect::<Vec<_>>();955 staked.sort_by_key(|(block, _)| *block);956 if !staked.is_empty() {957 Some(staked)958 } else {959 None960 }961 }962963 964 965 966 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {967 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {968 Self::total_staked_by_id(s.as_sub())969 })970 }971972 973 974 975 976 977978 979 980 981 982 pub fn cross_id_total_staked_per_block(983 staker: T::CrossAccountId,984 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {985 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()986 }987988 fn recalculate_and_insert_stake(989 staker: &T::AccountId,990 staked_block: T::BlockNumber,991 next_recalc_block: T::BlockNumber,992 base: BalanceOf<T>,993 iters: u32,994 income_acc: &mut BalanceOf<T>,995 ) {996 let income = Self::calculate_income(base, iters);997998 base.checked_add(&income).map(|res| {999 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1000 *income_acc += income;1001 });1002 }10031004 fn calculate_income<I>(base: I, iters: u32) -> I1005 where1006 I: EncodeLike<BalanceOf<T>> + Balance,1007 {1008 let config = <PalletConfiguration<T>>::get();1009 let mut income = base;10101011 (0..iters).for_each(|_| income += config.interval_income * income);10121013 income - base1014 }10151016 1017 1018 fn get_current_recalc_block(1019 current_relay_block: T::BlockNumber,1020 config: &PalletConfiguration<T>,1021 ) -> T::BlockNumber {1022 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1023 }10241025 fn get_next_calculated_key() -> Option<Vec<u8>> {1026 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1027 }1028}10291030impl<T: Config> Pallet<T>1031where1032 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1033{1034 1035 1036 1037 1038 1039 1040 1041 1042 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1043 staker.map_or(1044 PendingUnstake::<T>::iter_values()1045 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1046 .sum(),1047 |s| {1048 PendingUnstake::<T>::iter_values()1049 .flatten()1050 .filter_map(|(id, amount)| {1051 if id == *s.as_sub() {1052 Some(amount)1053 } else {1054 None1055 }1056 })1057 .sum()1058 },1059 )1060 }10611062 1063 1064 1065 1066 pub fn cross_id_pending_unstake_per_block(1067 staker: T::CrossAccountId,1068 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1069 let mut unsorted_res = vec![];1070 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1071 pendings.into_iter().for_each(|(id, amount)| {1072 if id == *staker.as_sub() {1073 unsorted_res.push((block, amount));1074 };1075 })1076 });10771078 unsorted_res.sort_by_key(|(block, _)| *block);1079 unsorted_res1080 }10811082 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1083 let config = <PalletConfiguration<T>>::get();10841085 1086 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10871088 let mut pendings = <PendingUnstake<T>>::get(block);10891090 1091 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10921093 let mut total_stakes = 0u64;10941095 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1096 .map(|(_, (amount, _))| {1097 total_stakes += 1;1098 amount1099 })1100 .sum();11011102 if total_staked.is_zero() {1103 return Ok(());1104 }11051106 pendings1107 .try_push((staker_id.clone(), total_staked))1108 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;11091110 <PendingUnstake<T>>::insert(block, pendings);11111112 TotalStaked::<T>::set(1113 TotalStaked::<T>::get()1114 .checked_sub(&total_staked)1115 .ok_or(ArithmeticError::Underflow)?,1116 );11171118 StakesPerAccount::<T>::remove(&staker_id);11191120 Self::deposit_event(Event::Unstake(staker_id, total_staked));11211122 Ok(())1123 }1124}