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(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 }212213 214 #[pallet::storage]215 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;216217 218 #[pallet::storage]219 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;220221 222 223 224 225 226 227 #[pallet::storage]228 pub type Staked<T: Config> = StorageNMap<229 Key = (230 Key<Blake2_128Concat, T::AccountId>,231 Key<Twox64Concat, T::BlockNumber>,232 ),233 Value = (BalanceOf<T>, T::BlockNumber),234 QueryKind = ValueQuery,235 >;236237 238 239 240 241 #[pallet::storage]242 pub type StakesPerAccount<T: Config> =243 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;244245 246 247 248 249 #[pallet::storage]250 pub type PendingUnstake<T: Config> = StorageMap<251 _,252 Twox64Concat,253 T::BlockNumber,254 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,255 ValueQuery,256 >;257258 259 260 #[pallet::storage]261 #[pallet::getter(fn get_next_calculated_record)]262 pub type PreviousCalculatedRecord<T: Config> =263 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;264265 #[pallet::storage]266 pub(crate) type UpgradedToReserves<T: Config> =267 StorageValue<Value = bool, QueryKind = ValueQuery>;268269 #[pallet::hooks]270 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {271 272 273 274 fn on_initialize(current_block_number: T::BlockNumber) -> Weight275 where276 <T as frame_system::Config>::BlockNumber: From<u32>,277 {278 let block_pending = PendingUnstake::<T>::take(current_block_number);279 let counter = block_pending.len() as u32;280281 if !block_pending.is_empty() {282 block_pending.into_iter().for_each(|(staker, amount)| {283 Self::get_locked_balance(&staker).map(|b| {284 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();285 Self::set_lock_unchecked(&staker, new_state);286 });287 });288 }289290 <T as Config>::WeightInfo::on_initialize(counter)291 }292293 fn on_runtime_upgrade() -> Weight {294 let mut consumed_weight = Weight::zero();295 let mut add_weight = |reads, writes, weight| {296 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);297 consumed_weight += weight;298 };299300 if <UpgradedToReserves<T>>::get() {301 add_weight(1, 0, Weight::zero());302 return consumed_weight;303 } else {304 add_weight(1, 1, Weight::zero());305 <UpgradedToReserves<T>>::set(true);306 }307 <PendingUnstake<T>>::drain().for_each(|(_, v)| {308 add_weight(1, 1, Weight::zero());309 v.into_iter().for_each(|(staker, amount)| {310 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(311 &staker, amount,312 );313 add_weight(1, 1, Weight::zero());314 });315 });316317 consumed_weight318 }319320 #[cfg(feature = "try-runtime")]321 fn pre_upgrade() -> Result<Vec<u8>, &'static str> {322 use sp_std::collections::btree_map::BTreeMap;323 if <UpgradedToReserves<T>>::get() {324 return Ok(Default::default());325 }326 327 let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =328 BTreeMap::new();329330 <PendingUnstake<T>>::iter().for_each(|(_, v)| {331 v.into_iter().for_each(|(staker, amount)| {332 if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {333 *reserved_balance += amount;334 } else {335 let total_reserve = <<T as Config>::Currency as ReservableCurrency<336 T::AccountId,337 >>::reserved_balance(&staker);338 pre_state.insert(staker, (total_reserve, amount));339 }340 })341 });342343 Ok(pre_state.encode())344 }345346 #[cfg(feature = "try-runtime")]347 fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {348 use sp_std::collections::btree_map::BTreeMap;349350 if <UpgradedToReserves<T>>::get() {351 return Ok(());352 }353354 ensure!(355 <PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,356 "pendingUnstake storage isn't empty"357 );358359 let mut is_ok = true;360361 let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =362 Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;363 for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {364 let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<365 T::AccountId,366 >>::reserved_balance(&staker);367 if new_state_reserve != total_reserved - reserved_by_promo {368 is_ok = false;369 log::error!(370 "Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",371 staker, new_state_reserve, total_reserved, reserved_by_promo372 );373 }374 }375376 if is_ok {377 Ok(())378 } else {379 Err("Incorrect balance for some of stakers... See logs")380 }381 }382 }383384 #[pallet::call]385 impl<T: Config> Pallet<T>386 where387 T::BlockNumber: From<u32> + Into<u32>,388 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,389 {390 391 392 393 394 395 396 397 398 399 #[pallet::call_index(0)]400 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]401 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {402 ensure_root(origin)?;403404 <Admin<T>>::set(Some(admin.as_sub().to_owned()));405406 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));407408 Ok(())409 }410411 412 413 414 415 416 417 418 #[pallet::call_index(1)]419 #[pallet::weight(<T as Config>::WeightInfo::stake())]420 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {421 let staker_id = ensure_signed(staker)?;422423 ensure!(424 StakesPerAccount::<T>::get(&staker_id) < 10,425 Error::<T>::NoPermission426 );427428 ensure!(429 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),430 ArithmeticError::Underflow431 );432 let config = <PalletConfiguration<T>>::get();433434 let balance =435 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);436437 438 ensure!(439 amount440 <= match Self::get_locked_balance(&staker_id) {441 Some(lock) => balance442 .checked_sub(&lock.amount)443 .ok_or(ArithmeticError::Underflow)?,444 None => balance,445 },446 ArithmeticError::Underflow447 );448449 Self::add_lock_balance(&staker_id, amount)?;450451 let block_number = T::RelayBlockNumberProvider::current_block_number();452453 454 455 let recalculate_after_interval: T::BlockNumber =456 if block_number % config.recalculation_interval == 0u32.into() {457 1u32.into()458 } else {459 2u32.into()460 };461462 463 464 let recalc_block = (block_number / config.recalculation_interval465 + recalculate_after_interval)466 * config.recalculation_interval;467468 <Staked<T>>::insert((&staker_id, block_number), {469 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));470 balance_and_recalc_block.0 = balance_and_recalc_block471 .0472 .checked_add(&amount)473 .ok_or(ArithmeticError::Overflow)?;474 balance_and_recalc_block.1 = recalc_block;475 balance_and_recalc_block476 });477478 <TotalStaked<T>>::set(479 <TotalStaked<T>>::get()480 .checked_add(&amount)481 .ok_or(ArithmeticError::Overflow)?,482 );483484 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);485486 Self::deposit_event(Event::Stake(staker_id, amount));487488 Ok(())489 }490491 492 493 494 495 #[pallet::call_index(2)]496 #[pallet::weight(<T as Config>::WeightInfo::unstake())]497 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResultWithPostInfo {498 let staker_id = ensure_signed(staker)?;499 let config = <PalletConfiguration<T>>::get();500501 502 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;503504 let mut pendings = <PendingUnstake<T>>::get(block);505506 507 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);508509 let mut total_stakes = 0u64;510511 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))512 .map(|(_, (amount, _))| {513 total_stakes += 1;514 amount515 })516 .sum();517518 if total_staked.is_zero() {519 return Ok(None::<Weight>.into()); 520 }521522 pendings523 .try_push((staker_id.clone(), total_staked))524 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;525526 <PendingUnstake<T>>::insert(block, pendings);527528 TotalStaked::<T>::set(529 TotalStaked::<T>::get()530 .checked_sub(&total_staked)531 .ok_or(ArithmeticError::Underflow)?,532 );533534 StakesPerAccount::<T>::remove(&staker_id);535536 Self::deposit_event(Event::Unstake(staker_id, total_staked));537538 Ok(None::<Weight>.into())539 }540541 542 543 544 545 #[pallet::call_index(8)]546 #[pallet::weight(<T as Config>::WeightInfo::unstake())]547 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {548 let staker_id = ensure_signed(staker)?;549 let config = <PalletConfiguration<T>>::get();550551 552 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;553554 let mut pendings = <PendingUnstake<T>>::get(block);555556 557 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);558559 Self::partial_unstake(&staker_id, amount, pendings, block)?;560561 let mut total_stakes = 0u64;562563 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))564 .map(|(_, (amount, _))| {565 total_stakes += 1;566 amount567 })568 .sum();569570 if total_staked.is_zero() {571 return Ok(()); 572 }573574 575 576 577578 579580 581 582 583 584 585586 587588 Self::deposit_event(Event::Unstake(staker_id, total_staked));589590 Ok(())591 }592593 594 595 596 597 598 599 600 601 602 #[pallet::call_index(3)]603 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]604 pub fn sponsor_collection(605 admin: OriginFor<T>,606 collection_id: CollectionId,607 ) -> DispatchResult {608 let admin_id = ensure_signed(admin)?;609 ensure!(610 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,611 Error::<T>::NoPermission612 );613614 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)615 }616617 618 619 620 621 622 623 624 625 626 627 628 #[pallet::call_index(4)]629 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]630 pub fn stop_sponsoring_collection(631 admin: OriginFor<T>,632 collection_id: CollectionId,633 ) -> DispatchResult {634 let admin_id = ensure_signed(admin)?;635636 ensure!(637 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,638 Error::<T>::NoPermission639 );640641 ensure!(642 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?643 == Self::account_id(),644 <Error<T>>::NoPermission645 );646 T::CollectionHandler::remove_collection_sponsor(collection_id)647 }648649 650 651 652 653 654 655 656 657 658 #[pallet::call_index(5)]659 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]660 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {661 let admin_id = ensure_signed(admin)?;662663 ensure!(664 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,665 Error::<T>::NoPermission666 );667668 T::ContractHandler::set_sponsor(669 T::CrossAccountId::from_sub(Self::account_id()),670 contract_id,671 )672 }673674 675 676 677 678 679 680 681 682 683 684 685 #[pallet::call_index(6)]686 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]687 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {688 let admin_id = ensure_signed(admin)?;689690 ensure!(691 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,692 Error::<T>::NoPermission693 );694695 ensure!(696 T::ContractHandler::sponsor(contract_id)?697 .ok_or(<Error<T>>::SponsorNotSet)?698 .as_sub() == &Self::account_id(),699 <Error<T>>::NoPermission700 );701 T::ContractHandler::remove_contract_sponsor(contract_id)702 }703704 705 706 707 708 709 710 711 712 713 714 715 716 #[pallet::call_index(7)]717 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]718 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {719 let admin_id = ensure_signed(admin)?;720721 ensure!(722 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,723 Error::<T>::NoPermission724 );725 let config = <PalletConfiguration<T>>::get();726727 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);728729 ensure!(730 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,731 Error::<T>::NoPermission732 );733734 735 736 let current_recalc_block = Self::get_current_recalc_block(737 T::RelayBlockNumberProvider::current_block_number(),738 &config,739 );740741 742 743 let next_recalc_block = current_recalc_block + config.recalculation_interval;744745 let mut storage_iterator = Self::get_next_calculated_key()746 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));747748 PreviousCalculatedRecord::<T>::set(None);749750 {751 752 let last_id = RefCell::new(None);753 754 let mut last_staked_calculated_block = Default::default();755 756 let income_acc = RefCell::new(BalanceOf::<T>::default());757 758 let amount_acc = RefCell::new(BalanceOf::<T>::default());759760 761 762 763 764 765 766 767 let flush_stake = || -> DispatchResult {768 if let Some(last_id) = &*last_id.borrow() {769 if !income_acc.borrow().is_zero() {770 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(771 &T::TreasuryAccountId::get(),772 last_id,773 *income_acc.borrow(),774 ExistenceRequirement::KeepAlive,775 )?;776777 Self::add_lock_balance(last_id, *income_acc.borrow())?;778 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {779 *staked = staked780 .checked_add(&*income_acc.borrow())781 .ok_or(ArithmeticError::Overflow)?;782 Ok(())783 })?;784785 Self::deposit_event(Event::StakingRecalculation(786 last_id.clone(),787 *amount_acc.borrow(),788 *income_acc.borrow(),789 ));790 }791792 *income_acc.borrow_mut() = BalanceOf::<T>::default();793 *amount_acc.borrow_mut() = BalanceOf::<T>::default();794 }795 Ok(())796 };797798 799 800 801 802 803 804 while let Some((805 (current_id, staked_block),806 (amount, next_recalc_block_for_stake),807 )) = storage_iterator.next()808 {809 810 811 812 if last_id.borrow().as_ref() != Some(¤t_id) {813 if stakers_number > 0 {814 flush_stake()?;815 *last_id.borrow_mut() = Some(current_id.clone());816 stakers_number -= 1;817 }818 819 else {820 if let Some(staker) = &*last_id.borrow() {821 822 PreviousCalculatedRecord::<T>::set(Some((823 staker.clone(),824 last_staked_calculated_block,825 )));826 }827 break;828 };829 };830831 832 if current_recalc_block >= next_recalc_block_for_stake {833 *amount_acc.borrow_mut() += amount;834 Self::recalculate_and_insert_stake(835 ¤t_id,836 staked_block,837 next_recalc_block,838 amount,839 ((current_recalc_block - next_recalc_block_for_stake)840 / config.recalculation_interval)841 .into() + 1,842 &mut *income_acc.borrow_mut(),843 );844 }845 last_staked_calculated_block = staked_block;846 }847 flush_stake()?;848 }849850 Ok(())851 }852 }853}854855impl<T: Config> Pallet<T> {856 857 858 859 860 pub fn account_id() -> T::AccountId {861 T::PalletId::get().into_account_truncating()862 }863864 fn partial_unstake(865 staker_id: &T::AccountId,866 unstaked_balance: BalanceOf<T>,867 mut pendings: BoundedVec<868 (T::AccountId, BalanceOf<T>),869 sp_core::ConstU32<PENDING_LIMIT_PER_BLOCK>,870 >,871 pending_block: T::BlockNumber,872 ) -> DispatchResult {873 if unstaked_balance == Default::default() {874 return Ok(());875 }876877 let mut stakes = Staked::<T>::iter_prefix((staker_id,)).collect::<Vec<_>>();878879 let total_staked = stakes880 .iter()881 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {882 acc + *balance883 });884885 ensure!(total_staked >= unstaked_balance, ArithmeticError::Underflow);886887 <TotalStaked<T>>::set(888 <TotalStaked<T>>::get()889 .checked_sub(&unstaked_balance)890 .ok_or(ArithmeticError::Underflow)?,891 );892893 stakes.sort_by_key(|(block, _)| *block);894895 let mut acc_amount = unstaked_balance;896 let mut will_deleted_stakes_count = 0u8;897898 let changed_stakes = stakes899 .into_iter()900 .map_while(|(block, (balance_per_block, recalc_block))| {901 if acc_amount == <BalanceOf<T>>::default() {902 return None;903 }904 if acc_amount <= balance_per_block {905 let res = (block, (balance_per_block - acc_amount, recalc_block));906 acc_amount = <BalanceOf<T>>::default();907 return Some(res);908 } else {909 acc_amount -= balance_per_block;910 will_deleted_stakes_count += 1;911 return Some((block, (<BalanceOf<T>>::default(), recalc_block)));912 }913 })914 .collect::<Vec<_>>();915916 pendings917 .try_push((staker_id.clone(), unstaked_balance))918 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;919920 StakesPerAccount::<T>::try_mutate(staker_id, |stakes| -> DispatchResult {921 *stakes = stakes922 .checked_div(will_deleted_stakes_count)923 .ok_or(ArithmeticError::Underflow)?;924 Ok(())925 })?;926927 changed_stakes928 .iter()929 .for_each(|(staked_block, (current_stake_state, _))| {930 if current_stake_state == &Default::default() {931 <Staked<T>>::remove((staker_id, staked_block));932 } else {933 <Staked<T>>::mutate((staker_id, staked_block), |(old_stake_state, _)| {934 *old_stake_state = *current_stake_state935 });936 }937 });938939 <PendingUnstake<T>>::insert(pending_block, pendings);940941 Ok(())942 }943944 945 946 947 948 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {949 Self::get_locked_balance(staker)950 .map_or(<BalanceOf<T>>::default(), |l| l.amount)951 .checked_add(&amount)952 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))953 .ok_or(ArithmeticError::Overflow.into())954 }955956 957 958 959 960 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {961 if amount.is_zero() {962 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(963 LOCK_IDENTIFIER,964 &staker,965 );966 } else {967 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(968 LOCK_IDENTIFIER,969 staker,970 amount,971 WithdrawReasons::all(),972 )973 }974 }975976 977 978 979 pub fn get_locked_balance(980 staker: impl EncodeLike<T::AccountId>,981 ) -> Option<BalanceLock<BalanceOf<T>>> {982 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)983 .into_iter()984 .find(|l| l.id == LOCK_IDENTIFIER)985 }986987 988 989 990 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {991 let staked = Staked::<T>::iter_prefix((staker,))992 .into_iter()993 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {994 acc + amount995 });996 if staked != <BalanceOf<T>>::default() {997 Some(staked)998 } else {999 None1000 }1001 }10021003 1004 1005 1006 1007 pub fn total_staked_by_id_per_block(1008 staker: impl EncodeLike<T::AccountId>,1009 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1010 let mut staked = Staked::<T>::iter_prefix((staker,))1011 .into_iter()1012 .map(|(block, (amount, _))| (block, amount))1013 .collect::<Vec<_>>();1014 staked.sort_by_key(|(block, _)| *block);1015 if !staked.is_empty() {1016 Some(staked)1017 } else {1018 None1019 }1020 }10211022 1023 1024 1025 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1026 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1027 Self::total_staked_by_id(s.as_sub())1028 })1029 }10301031 1032 1033 1034 1035 10361037 1038 1039 1040 1041 pub fn cross_id_total_staked_per_block(1042 staker: T::CrossAccountId,1043 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1044 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1045 }10461047 fn recalculate_and_insert_stake(1048 staker: &T::AccountId,1049 staked_block: T::BlockNumber,1050 next_recalc_block: T::BlockNumber,1051 base: BalanceOf<T>,1052 iters: u32,1053 income_acc: &mut BalanceOf<T>,1054 ) {1055 let income = Self::calculate_income(base, iters);10561057 base.checked_add(&income).map(|res| {1058 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1059 *income_acc += income;1060 });1061 }10621063 fn calculate_income<I>(base: I, iters: u32) -> I1064 where1065 I: EncodeLike<BalanceOf<T>> + Balance,1066 {1067 let config = <PalletConfiguration<T>>::get();1068 let mut income = base;10691070 (0..iters).for_each(|_| income += config.interval_income * income);10711072 income - base1073 }10741075 1076 1077 fn get_current_recalc_block(1078 current_relay_block: T::BlockNumber,1079 config: &PalletConfiguration<T>,1080 ) -> T::BlockNumber {1081 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1082 }10831084 fn get_next_calculated_key() -> Option<Vec<u8>> {1085 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1086 }1087}10881089impl<T: Config> Pallet<T>1090where1091 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,1092{1093 1094 1095 1096 1097 1098 1099 1100 1101 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1102 staker.map_or(1103 PendingUnstake::<T>::iter_values()1104 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1105 .sum(),1106 |s| {1107 PendingUnstake::<T>::iter_values()1108 .flatten()1109 .filter_map(|(id, amount)| {1110 if id == *s.as_sub() {1111 Some(amount)1112 } else {1113 None1114 }1115 })1116 .sum()1117 },1118 )1119 }11201121 1122 1123 1124 1125 pub fn cross_id_pending_unstake_per_block(1126 staker: T::CrossAccountId,1127 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1128 let mut unsorted_res = vec![];1129 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1130 pendings.into_iter().for_each(|(id, amount)| {1131 if id == *staker.as_sub() {1132 unsorted_res.push((block, amount));1133 };1134 })1135 });11361137 unsorted_res.sort_by_key(|(block, _)| *block);1138 unsorted_res1139 }1140}