difftreelog
fix the behaviour of the `payoutStakers` extrinsic in which only one stake is calculated for the last processed staker.
in: master
1 file changed
pallets/app-promotion/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![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,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,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 /// Type to interact with the native token109 type Currency: ExtendedLockableCurrency<Self::AccountId>110 + ReservableCurrency<Self::AccountId>;111112 /// Type for interacting with collections113 type CollectionHandler: CollectionHandler<114 AccountId = Self::AccountId,115 CollectionId = CollectionId,116 >;117118 /// Type for interacting with conrtacts119 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121 /// `AccountId` for treasury122 type TreasuryAccountId: Get<Self::AccountId>;123124 /// The app's pallet id, used for deriving its sovereign account address.125 #[pallet::constant]126 type PalletId: Get<PalletId>;127128 /// In relay blocks.129 #[pallet::constant]130 type RecalculationInterval: Get<Self::BlockNumber>;131132 /// In parachain blocks.133 #[pallet::constant]134 type PendingInterval: Get<Self::BlockNumber>;135136 /// Rate of return for interval in blocks defined in `RecalculationInterval`.137 #[pallet::constant]138 type IntervalIncome: Get<Perbill>;139140 /// Decimals for the `Currency`.141 #[pallet::constant]142 type Nominal: Get<BalanceOf<Self>>;143144 /// Weight information for extrinsics in this pallet.145 type WeightInfo: WeightInfo;146147 // The relay block number provider148 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150 /// Events compatible with [`frame_system::Config::Event`].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 /// Staking recalculation was performed162 ///163 /// # Arguments164 /// * AccountId: account of the staker.165 /// * Balance : recalculation base166 /// * Balance : total income167 StakingRecalculation(168 /// An recalculated staker169 T::AccountId,170 /// Base on which interest is calculated171 BalanceOf<T>,172 /// Amount of accrued interest173 BalanceOf<T>,174 ),175176 /// Staking was performed177 ///178 /// # Arguments179 /// * AccountId: account of the staker180 /// * Balance : staking amount181 Stake(T::AccountId, BalanceOf<T>),182183 /// Unstaking was performed184 ///185 /// # Arguments186 /// * AccountId: account of the staker187 /// * Balance : unstaking amount188 Unstake(T::AccountId, BalanceOf<T>),189190 /// The admin was set191 ///192 /// # Arguments193 /// * AccountId: account address of the admin194 SetAdmin(T::AccountId),195 }196197 #[pallet::error]198 pub enum Error<T> {199 /// Error due to action requiring admin to be set.200 AdminNotSet,201 /// No permission to perform an action.202 NoPermission,203 /// Insufficient funds to perform an action.204 NotSufficientFunds,205 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.206 PendingForBlockOverflow,207 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.208 SponsorNotSet,209 /// Errors caused by incorrect actions with a locked balance.210 IncorrectLockedBalanceOperation,211 }212213 /// Stores the total staked amount.214 #[pallet::storage]215 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;216217 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.218 #[pallet::storage]219 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;220221 /// Stores the amount of tokens staked by account in the blocknumber.222 ///223 /// * **Key1** - Staker account.224 /// * **Key2** - Relay block number when the stake was made.225 /// * **(Balance, BlockNumber)** - Balance of the stake.226 /// The number of the relay block in which we must perform the interest recalculation227 #[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 /// Stores amount of stakes for an `Account`.238 ///239 /// * **Key** - Staker account.240 /// * **Value** - Amount of stakes.241 #[pallet::storage]242 pub type StakesPerAccount<T: Config> =243 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;244245 /// Stores amount of stakes for an `Account`.246 ///247 /// * **Key** - Staker account.248 /// * **Value** - Amount of stakes.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 /// Stores a key for record for which the revenue recalculation was performed.259 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.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::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize268 /// implies the execution of a strictly limited number of relatively lightweight operations.269 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.270 fn on_initialize(current_block_number: T::BlockNumber) -> Weight271 where272 <T as frame_system::Config>::BlockNumber: From<u32>,273 {274 let block_pending = PendingUnstake::<T>::take(current_block_number);275 let counter = block_pending.len() as u32;276277 if !block_pending.is_empty() {278 block_pending.into_iter().for_each(|(staker, amount)| {279 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(280 &staker, amount,281 );282 });283 }284285 <T as Config>::WeightInfo::on_initialize(counter)286 }287 }288289 #[pallet::call]290 impl<T: Config> Pallet<T>291 where292 T::BlockNumber: From<u32> + Into<u32>,293 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,294 {295 /// Sets an address as the the admin.296 ///297 /// # Permissions298 ///299 /// * Sudo300 ///301 /// # Arguments302 ///303 /// * `admin`: account of the new admin.304 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]305 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {306 ensure_root(origin)?;307308 <Admin<T>>::set(Some(admin.as_sub().to_owned()));309310 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));311312 Ok(())313 }314315 /// Stakes the amount of native tokens.316 /// Sets `amount` to the locked state.317 /// The maximum number of stakes for a staker is 10.318 ///319 /// # Arguments320 ///321 /// * `amount`: in native tokens.322 #[pallet::weight(<T as Config>::WeightInfo::stake())]323 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {324 let staker_id = ensure_signed(staker)?;325326 ensure!(327 StakesPerAccount::<T>::get(&staker_id) < 10,328 Error::<T>::NoPermission329 );330331 ensure!(332 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),333 ArithmeticError::Underflow334 );335 let config = <PalletConfiguration<T>>::get();336337 let balance =338 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);339340 // checks that we can lock `amount` on the `staker` account.341 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(342 &staker_id,343 amount,344 WithdrawReasons::all(),345 balance346 .checked_sub(&amount)347 .ok_or(ArithmeticError::Underflow)?,348 )?;349350 Self::add_lock_balance(&staker_id, amount)?;351352 let block_number = T::RelayBlockNumberProvider::current_block_number();353354 // Calculation of the number of recalculation periods,355 // after how much the first interest calculation should be performed for the stake356 let recalculate_after_interval: T::BlockNumber =357 if block_number % config.recalculation_interval == 0u32.into() {358 1u32.into()359 } else {360 2u32.into()361 };362363 // Сalculation of the number of the relay block364 // in which it is necessary to accrue remuneration for the stake.365 let recalc_block = (block_number / config.recalculation_interval366 + recalculate_after_interval)367 * config.recalculation_interval;368369 <Staked<T>>::insert((&staker_id, block_number), {370 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));371 balance_and_recalc_block.0 = balance_and_recalc_block372 .0373 .checked_add(&amount)374 .ok_or(ArithmeticError::Overflow)?;375 balance_and_recalc_block.1 = recalc_block;376 balance_and_recalc_block377 });378379 <TotalStaked<T>>::set(380 <TotalStaked<T>>::get()381 .checked_add(&amount)382 .ok_or(ArithmeticError::Overflow)?,383 );384385 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);386387 Self::deposit_event(Event::Stake(staker_id, amount));388389 Ok(())390 }391392 /// Unstakes all stakes.393 /// Moves the sum of all stakes to the `reserved` state.394 /// After the end of `PendingInterval` this sum becomes completely395 /// free for further use.396 #[pallet::weight(<T as Config>::WeightInfo::unstake())]397 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {398 let staker_id = ensure_signed(staker)?;399 let config = <PalletConfiguration<T>>::get();400401 // calculate block number where the sum would be free402 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;403404 let mut pendings = <PendingUnstake<T>>::get(block);405406 // checks that we can do unreserve stakes in the block407 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);408409 let mut total_stakes = 0u64;410411 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))412 .map(|(_, (amount, _))| {413 total_stakes += 1;414 amount415 })416 .sum();417418 if total_staked.is_zero() {419 return Ok(None::<Weight>.into()); // TO-DO420 }421422 pendings423 .try_push((staker_id.clone(), total_staked))424 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;425426 <PendingUnstake<T>>::insert(block, pendings);427428 Self::unlock_balance(&staker_id, total_staked)?;429430 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(431 &staker_id,432 total_staked,433 )?;434435 TotalStaked::<T>::set(436 TotalStaked::<T>::get()437 .checked_sub(&total_staked)438 .ok_or(ArithmeticError::Underflow)?,439 );440441 StakesPerAccount::<T>::remove(&staker_id);442443 Self::deposit_event(Event::Unstake(staker_id, total_staked));444445 Ok(None::<Weight>.into())446 }447448 /// Sets the pallet to be the sponsor for the collection.449 ///450 /// # Permissions451 ///452 /// * Pallet admin453 ///454 /// # Arguments455 ///456 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`457 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]458 pub fn sponsor_collection(459 admin: OriginFor<T>,460 collection_id: CollectionId,461 ) -> DispatchResult {462 let admin_id = ensure_signed(admin)?;463 ensure!(464 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,465 Error::<T>::NoPermission466 );467468 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)469 }470471 /// Removes the pallet as the sponsor for the collection.472 /// Returns [`NoPermission`][`Error::NoPermission`]473 /// if the pallet wasn't the sponsor.474 ///475 /// # Permissions476 ///477 /// * Pallet admin478 ///479 /// # Arguments480 ///481 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`482 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]483 pub fn stop_sponsoring_collection(484 admin: OriginFor<T>,485 collection_id: CollectionId,486 ) -> DispatchResult {487 let admin_id = ensure_signed(admin)?;488489 ensure!(490 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,491 Error::<T>::NoPermission492 );493494 ensure!(495 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?496 == Self::account_id(),497 <Error<T>>::NoPermission498 );499 T::CollectionHandler::remove_collection_sponsor(collection_id)500 }501502 /// Sets the pallet to be the sponsor for the contract.503 ///504 /// # Permissions505 ///506 /// * Pallet admin507 ///508 /// # Arguments509 ///510 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`511 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]512 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {513 let admin_id = ensure_signed(admin)?;514515 ensure!(516 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,517 Error::<T>::NoPermission518 );519520 T::ContractHandler::set_sponsor(521 T::CrossAccountId::from_sub(Self::account_id()),522 contract_id,523 )524 }525526 /// Removes the pallet as the sponsor for the contract.527 /// Returns [`NoPermission`][`Error::NoPermission`]528 /// if the pallet wasn't the sponsor.529 ///530 /// # Permissions531 ///532 /// * Pallet admin533 ///534 /// # Arguments535 ///536 /// * `contract_id`: the contract address that is sponsored by `pallet_id`537 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]538 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {539 let admin_id = ensure_signed(admin)?;540541 ensure!(542 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,543 Error::<T>::NoPermission544 );545546 ensure!(547 T::ContractHandler::sponsor(contract_id)?548 .ok_or(<Error<T>>::SponsorNotSet)?549 .as_sub() == &Self::account_id(),550 <Error<T>>::NoPermission551 );552 T::ContractHandler::remove_contract_sponsor(contract_id)553 }554555 /// Recalculates interest for the specified number of stakers.556 /// If all stakers are not recalculated, the next call of the extrinsic557 /// will continue the recalculation, from those stakers for whom this558 /// was not perform in last call.559 ///560 /// # Permissions561 ///562 /// * Pallet admin563 ///564 /// # Arguments565 ///566 /// * `stakers_number`: the number of stakers for which recalculation will be performed567 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]568 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {569 let admin_id = ensure_signed(admin)?;570571 ensure!(572 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,573 Error::<T>::NoPermission574 );575 let config = <PalletConfiguration<T>>::get();576577 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);578579 ensure!(580 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,581 Error::<T>::NoPermission582 );583584 // calculate the number of the current recalculation block,585 // this is necessary in order to understand which stakers we should calculate interest586 let current_recalc_block = Self::get_current_recalc_block(587 T::RelayBlockNumberProvider::current_block_number(),588 &config,589 );590591 // calculate the number of the next recalculation block,592 // this value is set for the stakers to whom the recalculation will be performed593 let next_recalc_block = current_recalc_block + config.recalculation_interval;594595 let mut storage_iterator = Self::get_next_calculated_key()596 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));597598 PreviousCalculatedRecord::<T>::set(None);599600 {601 // Address handled in the last payout loop iteration (below)602 let last_id = RefCell::new(None);603 // Reward balance for the address in the iteration604 let income_acc = RefCell::new(BalanceOf::<T>::default());605 // Staked balance for the address in the iteration (before stake is recalculated)606 let amount_acc = RefCell::new(BalanceOf::<T>::default());607608 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout609 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout610 // loop switches to handling the next staker address:611 // 1. Transfer full reward amount to the payee612 // 2. Lock the reward in staking lock613 // 3. Update TotalStaked amount614 // 4. Issue StakingRecalculation event615 let flush_stake = || -> DispatchResult {616 if let Some(last_id) = &*last_id.borrow() {617 if !income_acc.borrow().is_zero() {618 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(619 &T::TreasuryAccountId::get(),620 last_id,621 *income_acc.borrow(),622 ExistenceRequirement::KeepAlive,623 )?;624625 Self::add_lock_balance(last_id, *income_acc.borrow())?;626 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {627 *staked = staked628 .checked_add(&*income_acc.borrow())629 .ok_or(ArithmeticError::Overflow)?;630 Ok(())631 })?;632633 Self::deposit_event(Event::StakingRecalculation(634 last_id.clone(),635 *amount_acc.borrow(),636 *income_acc.borrow(),637 ));638 }639640 *income_acc.borrow_mut() = BalanceOf::<T>::default();641 *amount_acc.borrow_mut() = BalanceOf::<T>::default();642 }643 Ok(())644 };645646 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation647 // iterations in one extrinsic call648 //649 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)650 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out651 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)652 while let Some((653 (current_id, staked_block),654 (amount, next_recalc_block_for_stake),655 )) = storage_iterator.next()656 {657 // last_id is not equal current_id when we switch to handling a new staker address658 // or just start handling the very first address. In the latter case last_id will be None and659 // flush_stake will do nothing660 if last_id.borrow().as_ref() != Some(¤t_id) {661 flush_stake()?;662 *last_id.borrow_mut() = Some(current_id.clone());663 stakers_number -= 1;664 };665666 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount667 if current_recalc_block >= next_recalc_block_for_stake {668 *amount_acc.borrow_mut() += amount;669 Self::recalculate_and_insert_stake(670 ¤t_id,671 staked_block,672 next_recalc_block,673 amount,674 ((current_recalc_block - next_recalc_block_for_stake)675 / config.recalculation_interval)676 .into() + 1,677 &mut *income_acc.borrow_mut(),678 );679 }680681 // Break out if we reached the address limit682 if stakers_number == 0 {683 if storage_iterator.next().is_some() {684 // Save the last calculated record to pick up in the next extrinsic call685 PreviousCalculatedRecord::<T>::set(Some((current_id, staked_block)));686 }687 break;688 }689 }690 flush_stake()?;691 }692693 Ok(())694 }695 }696}697698impl<T: Config> Pallet<T> {699 /// The account address of the app promotion pot.700 ///701 /// This actually does computation. If you need to keep using it, then make sure you cache the702 /// value and only call this once.703 pub fn account_id() -> T::AccountId {704 T::PalletId::get().into_account_truncating()705 }706707 /// Unlocks the balance that was locked by the pallet.708 ///709 /// - `staker`: staker account.710 /// - `amount`: amount of unlocked funds.711 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {712 let locked_balance = Self::get_locked_balance(staker)713 .map(|l| l.amount)714 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;715716 // It is understood that we cannot unlock more funds than were locked by staking.717 // Therefore, if implemented correctly, this error should not occur.718 Self::set_lock_unchecked(719 staker,720 locked_balance721 .checked_sub(&amount)722 .ok_or(ArithmeticError::Underflow)?,723 );724 Ok(())725 }726727 /// Adds the balance to locked by the pallet.728 ///729 /// - `staker`: staker account.730 /// - `amount`: amount of added locked funds.731 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {732 Self::get_locked_balance(staker)733 .map_or(<BalanceOf<T>>::default(), |l| l.amount)734 .checked_add(&amount)735 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))736 .ok_or(ArithmeticError::Overflow.into())737 }738739 /// Sets the new state of a balance locked by the pallet.740 ///741 /// - `staker`: staker account.742 /// - `amount`: amount of locked funds.743 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {744 if amount.is_zero() {745 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(746 LOCK_IDENTIFIER,747 &staker,748 );749 } else {750 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(751 LOCK_IDENTIFIER,752 staker,753 amount,754 WithdrawReasons::all(),755 )756 }757 }758759 /// Returns the balance locked by the pallet for the staker.760 ///761 /// - `staker`: staker account.762 pub fn get_locked_balance(763 staker: impl EncodeLike<T::AccountId>,764 ) -> Option<BalanceLock<BalanceOf<T>>> {765 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)766 .into_iter()767 .find(|l| l.id == LOCK_IDENTIFIER)768 }769770 /// Returns the total staked balance for the staker.771 ///772 /// - `staker`: staker account.773 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {774 let staked = Staked::<T>::iter_prefix((staker,))775 .into_iter()776 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {777 acc + amount778 });779 if staked != <BalanceOf<T>>::default() {780 Some(staked)781 } else {782 None783 }784 }785786 /// Returns all relay block numbers when stake was made,787 /// the amount of the stake.788 ///789 /// - `staker`: staker account.790 pub fn total_staked_by_id_per_block(791 staker: impl EncodeLike<T::AccountId>,792 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {793 let mut staked = Staked::<T>::iter_prefix((staker,))794 .into_iter()795 .map(|(block, (amount, _))| (block, amount))796 .collect::<Vec<_>>();797 staked.sort_by_key(|(block, _)| *block);798 if !staked.is_empty() {799 Some(staked)800 } else {801 None802 }803 }804805 /// Returns the total staked balance for the staker.806 /// If `staker` is `None`, returns the total amount staked.807 /// - `staker`: staker account.808 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {809 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {810 Self::total_staked_by_id(s.as_sub())811 })812 }813814 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {815 // Self::get_locked_balance(staker.as_sub())816 // .map(|l| l.amount)817 // .unwrap_or_default()818 // }819820 /// Returns all relay block numbers when stake was made,821 /// the amount of the stake.822 ///823 /// - `staker`: staker account.824 pub fn cross_id_total_staked_per_block(825 staker: T::CrossAccountId,826 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {827 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()828 }829830 fn recalculate_and_insert_stake(831 staker: &T::AccountId,832 staked_block: T::BlockNumber,833 next_recalc_block: T::BlockNumber,834 base: BalanceOf<T>,835 iters: u32,836 income_acc: &mut BalanceOf<T>,837 ) {838 let income = Self::calculate_income(base, iters);839840 base.checked_add(&income).map(|res| {841 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));842 *income_acc += income;843 });844 }845846 fn calculate_income<I>(base: I, iters: u32) -> I847 where848 I: EncodeLike<BalanceOf<T>> + Balance,849 {850 let config = <PalletConfiguration<T>>::get();851 let mut income = base;852853 (0..iters).for_each(|_| income += config.interval_income * income);854855 income - base856 }857858 /// Get relay block number rounded down to multiples of config.recalculation_interval.859 /// We need it to reward stakers in integer parts of recalculation_interval860 fn get_current_recalc_block(861 current_relay_block: T::BlockNumber,862 config: &PalletConfiguration<T>,863 ) -> T::BlockNumber {864 (current_relay_block / config.recalculation_interval) * config.recalculation_interval865 }866867 fn get_next_calculated_key() -> Option<Vec<u8>> {868 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))869 }870}871872impl<T: Config> Pallet<T>873where874 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,875{876 /// Returns the amount reserved by the pending.877 /// If `staker` is `None`, returns the total pending.878 ///879 /// -`staker`: staker account.880 ///881 /// Since user funds are not transferred anywhere by staking, overflow protection is provided882 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,883 /// the staker must have more funds on his account than the maximum set for `Balance` type.884 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {885 staker.map_or(886 PendingUnstake::<T>::iter_values()887 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))888 .sum(),889 |s| {890 PendingUnstake::<T>::iter_values()891 .flatten()892 .filter_map(|(id, amount)| {893 if id == *s.as_sub() {894 Some(amount)895 } else {896 None897 }898 })899 .sum()900 },901 )902 }903904 /// Returns all parachain block numbers when unreserve is expected,905 /// the amount of the unreserved funds.906 ///907 /// - `staker`: staker account.908 pub fn cross_id_pending_unstake_per_block(909 staker: T::CrossAccountId,910 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {911 let mut unsorted_res = vec![];912 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {913 pendings.into_iter().for_each(|(id, amount)| {914 if id == *staker.as_sub() {915 unsorted_res.push((block, amount));916 };917 })918 });919920 unsorted_res.sort_by_key(|(block, _)| *block);921 unsorted_res922 }923}