difftreelog
feat(app-promo) removed storage used for migration
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, 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 /// 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 number of stake records 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 /// Pending unstake records 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::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 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize272 /// implies the execution of a strictly limited number of relatively lightweight operations.273 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.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 <UpgradedToReserves<T>>::kill();295296 T::DbWeight::get().reads_writes(0, 1)297 }298 }299300 #[pallet::call]301 impl<T: Config> Pallet<T>302 where303 T::BlockNumber: From<u32> + Into<u32>,304 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,305 {306 /// Sets an address as the the admin.307 ///308 /// # Permissions309 ///310 /// * Sudo311 ///312 /// # Arguments313 ///314 /// * `admin`: account of the new admin.315 #[pallet::call_index(0)]316 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]317 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {318 ensure_root(origin)?;319320 <Admin<T>>::set(Some(admin.as_sub().to_owned()));321322 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));323324 Ok(())325 }326327 /// Stakes the amount of native tokens.328 /// Sets `amount` to the locked state.329 /// The maximum number of stakes for a staker is 10.330 ///331 /// # Arguments332 ///333 /// * `amount`: in native tokens.334 #[pallet::call_index(1)]335 #[pallet::weight(<T as Config>::WeightInfo::stake())]336 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {337 let staker_id = ensure_signed(staker)?;338339 ensure!(340 StakesPerAccount::<T>::get(&staker_id) < 10,341 Error::<T>::NoPermission342 );343344 ensure!(345 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),346 ArithmeticError::Underflow347 );348 let config = <PalletConfiguration<T>>::get();349350 let balance =351 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);352353 // checks that we can lock `amount` on the `staker` account.354 ensure!(355 amount356 <= match Self::get_locked_balance(&staker_id) {357 Some(lock) => balance358 .checked_sub(&lock.amount)359 .ok_or(ArithmeticError::Underflow)?,360 None => balance,361 },362 ArithmeticError::Underflow363 );364365 Self::add_lock_balance(&staker_id, amount)?;366367 let block_number = T::RelayBlockNumberProvider::current_block_number();368369 // Calculation of the number of recalculation periods,370 // after how much the first interest calculation should be performed for the stake371 let recalculate_after_interval: T::BlockNumber =372 if block_number % config.recalculation_interval == 0u32.into() {373 1u32.into()374 } else {375 2u32.into()376 };377378 // Сalculation of the number of the relay block379 // in which it is necessary to accrue remuneration for the stake.380 let recalc_block = (block_number / config.recalculation_interval381 + recalculate_after_interval)382 * config.recalculation_interval;383384 <Staked<T>>::insert((&staker_id, block_number), {385 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));386 balance_and_recalc_block.0 = balance_and_recalc_block387 .0388 .checked_add(&amount)389 .ok_or(ArithmeticError::Overflow)?;390 balance_and_recalc_block.1 = recalc_block;391 balance_and_recalc_block392 });393394 <TotalStaked<T>>::set(395 <TotalStaked<T>>::get()396 .checked_add(&amount)397 .ok_or(ArithmeticError::Overflow)?,398 );399400 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);401402 Self::deposit_event(Event::Stake(staker_id, amount));403404 Ok(())405 }406407 /// Unstakes all stakes.408 /// Moves the sum of all stakes to the `reserved` state.409 /// After the end of `PendingInterval` this sum becomes completely410 /// free for further use.411 #[pallet::call_index(2)]412 #[pallet::weight(<T as Config>::WeightInfo::unstake())]413 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {414 let staker_id = ensure_signed(staker)?;415 let config = <PalletConfiguration<T>>::get();416417 // calculate block number where the sum would be free418 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;419420 let mut pendings = <PendingUnstake<T>>::get(block);421422 // checks that we can do unreserve stakes in the block423 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);424425 let mut total_stakes = 0u64;426427 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))428 .map(|(_, (amount, _))| {429 total_stakes += 1;430 amount431 })432 .sum();433434 if total_staked.is_zero() {435 return Ok(None::<Weight>.into()); // TO-DO436 }437438 pendings439 .try_push((staker_id.clone(), total_staked))440 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;441442 <PendingUnstake<T>>::insert(block, pendings);443444 TotalStaked::<T>::set(445 TotalStaked::<T>::get()446 .checked_sub(&total_staked)447 .ok_or(ArithmeticError::Underflow)?,448 );449450 StakesPerAccount::<T>::remove(&staker_id);451452 Self::deposit_event(Event::Unstake(staker_id, total_staked));453454 Ok(None::<Weight>.into())455 }456457 /// Sets the pallet to be the sponsor for the collection.458 ///459 /// # Permissions460 ///461 /// * Pallet admin462 ///463 /// # Arguments464 ///465 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`466 #[pallet::call_index(3)]467 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]468 pub fn sponsor_collection(469 admin: OriginFor<T>,470 collection_id: CollectionId,471 ) -> DispatchResult {472 let admin_id = ensure_signed(admin)?;473 ensure!(474 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,475 Error::<T>::NoPermission476 );477478 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)479 }480481 /// Removes the pallet as the sponsor for the collection.482 /// Returns [`NoPermission`][`Error::NoPermission`]483 /// if the pallet wasn't the sponsor.484 ///485 /// # Permissions486 ///487 /// * Pallet admin488 ///489 /// # Arguments490 ///491 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`492 #[pallet::call_index(4)]493 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]494 pub fn stop_sponsoring_collection(495 admin: OriginFor<T>,496 collection_id: CollectionId,497 ) -> DispatchResult {498 let admin_id = ensure_signed(admin)?;499500 ensure!(501 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,502 Error::<T>::NoPermission503 );504505 ensure!(506 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?507 == Self::account_id(),508 <Error<T>>::NoPermission509 );510 T::CollectionHandler::remove_collection_sponsor(collection_id)511 }512513 /// Sets the pallet to be the sponsor for the contract.514 ///515 /// # Permissions516 ///517 /// * Pallet admin518 ///519 /// # Arguments520 ///521 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`522 #[pallet::call_index(5)]523 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]524 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {525 let admin_id = ensure_signed(admin)?;526527 ensure!(528 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,529 Error::<T>::NoPermission530 );531532 T::ContractHandler::set_sponsor(533 T::CrossAccountId::from_sub(Self::account_id()),534 contract_id,535 )536 }537538 /// Removes the pallet as the sponsor for the contract.539 /// Returns [`NoPermission`][`Error::NoPermission`]540 /// if the pallet wasn't the sponsor.541 ///542 /// # Permissions543 ///544 /// * Pallet admin545 ///546 /// # Arguments547 ///548 /// * `contract_id`: the contract address that is sponsored by `pallet_id`549 #[pallet::call_index(6)]550 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]551 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {552 let admin_id = ensure_signed(admin)?;553554 ensure!(555 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,556 Error::<T>::NoPermission557 );558559 ensure!(560 T::ContractHandler::sponsor(contract_id)?561 .ok_or(<Error<T>>::SponsorNotSet)?562 .as_sub() == &Self::account_id(),563 <Error<T>>::NoPermission564 );565 T::ContractHandler::remove_contract_sponsor(contract_id)566 }567568 /// Recalculates interest for the specified number of stakers.569 /// If all stakers are not recalculated, the next call of the extrinsic570 /// will continue the recalculation, from those stakers for whom this571 /// was not perform in last call.572 ///573 /// # Permissions574 ///575 /// * Pallet admin576 ///577 /// # Arguments578 ///579 /// * `stakers_number`: the number of stakers for which recalculation will be performed580 #[pallet::call_index(7)]581 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]582 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {583 let admin_id = ensure_signed(admin)?;584585 ensure!(586 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,587 Error::<T>::NoPermission588 );589 let config = <PalletConfiguration<T>>::get();590591 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);592593 ensure!(594 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,595 Error::<T>::NoPermission596 );597598 // calculate the number of the current recalculation block,599 // this is necessary in order to understand which stakers we should calculate interest600 let current_recalc_block = Self::get_current_recalc_block(601 T::RelayBlockNumberProvider::current_block_number(),602 &config,603 );604605 // calculate the number of the next recalculation block,606 // this value is set for the stakers to whom the recalculation will be performed607 let next_recalc_block = current_recalc_block + config.recalculation_interval;608609 let mut storage_iterator = Self::get_next_calculated_key()610 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));611612 PreviousCalculatedRecord::<T>::set(None);613614 {615 // Address handled in the last payout loop iteration (below)616 let last_id = RefCell::new(None);617 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration618 let mut last_staked_calculated_block = Default::default();619 // Reward balance for the address in the iteration620 let income_acc = RefCell::new(BalanceOf::<T>::default());621 // Staked balance for the address in the iteration (before stake is recalculated)622 let amount_acc = RefCell::new(BalanceOf::<T>::default());623624 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout625 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout626 // loop switches to handling the next staker address:627 // 1. Transfer full reward amount to the payee628 // 2. Lock the reward in staking lock629 // 3. Update TotalStaked amount630 // 4. Issue StakingRecalculation event631 let flush_stake = || -> DispatchResult {632 if let Some(last_id) = &*last_id.borrow() {633 if !income_acc.borrow().is_zero() {634 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(635 &T::TreasuryAccountId::get(),636 last_id,637 *income_acc.borrow(),638 ExistenceRequirement::KeepAlive,639 )?;640641 Self::add_lock_balance(last_id, *income_acc.borrow())?;642 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {643 *staked = staked644 .checked_add(&*income_acc.borrow())645 .ok_or(ArithmeticError::Overflow)?;646 Ok(())647 })?;648649 Self::deposit_event(Event::StakingRecalculation(650 last_id.clone(),651 *amount_acc.borrow(),652 *income_acc.borrow(),653 ));654 }655656 *income_acc.borrow_mut() = BalanceOf::<T>::default();657 *amount_acc.borrow_mut() = BalanceOf::<T>::default();658 }659 Ok(())660 };661662 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation663 // iterations in one extrinsic call664 //665 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)666 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out667 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)668 while let Some((669 (current_id, staked_block),670 (amount, next_recalc_block_for_stake),671 )) = storage_iterator.next()672 {673 // last_id is not equal current_id when we switch to handling a new staker address674 // or just start handling the very first address. In the latter case last_id will be None and675 // flush_stake will do nothing676 if last_id.borrow().as_ref() != Some(¤t_id) {677 if stakers_number > 0 {678 flush_stake()?;679 *last_id.borrow_mut() = Some(current_id.clone());680 stakers_number -= 1;681 }682 // Break out if we reached the address limit683 else {684 if let Some(staker) = &*last_id.borrow() {685 // Save the last calculated record to pick up in the next extrinsic call686 PreviousCalculatedRecord::<T>::set(Some((687 staker.clone(),688 last_staked_calculated_block,689 )));690 }691 break;692 };693 };694695 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount696 if current_recalc_block >= next_recalc_block_for_stake {697 *amount_acc.borrow_mut() += amount;698 Self::recalculate_and_insert_stake(699 ¤t_id,700 staked_block,701 next_recalc_block,702 amount,703 ((current_recalc_block - next_recalc_block_for_stake)704 / config.recalculation_interval)705 .into() + 1,706 &mut *income_acc.borrow_mut(),707 );708 }709 last_staked_calculated_block = staked_block;710 }711 flush_stake()?;712 }713714 Ok(())715 }716 }717}718719impl<T: Config> Pallet<T> {720 /// The account address of the app promotion pot.721 ///722 /// This actually does computation. If you need to keep using it, then make sure you cache the723 /// value and only call this once.724 pub fn account_id() -> T::AccountId {725 T::PalletId::get().into_account_truncating()726 }727728 /// Adds the balance to locked by the pallet.729 ///730 /// - `staker`: staker account.731 /// - `amount`: amount of added locked funds.732 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {733 Self::get_locked_balance(staker)734 .map_or(<BalanceOf<T>>::default(), |l| l.amount)735 .checked_add(&amount)736 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))737 .ok_or(ArithmeticError::Overflow.into())738 }739740 /// Sets the new state of a balance locked by the pallet.741 ///742 /// - `staker`: staker account.743 /// - `amount`: amount of locked funds.744 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {745 if amount.is_zero() {746 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(747 LOCK_IDENTIFIER,748 &staker,749 );750 } else {751 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(752 LOCK_IDENTIFIER,753 staker,754 amount,755 WithdrawReasons::all(),756 )757 }758 }759760 /// Returns the balance locked by the pallet for the staker.761 ///762 /// - `staker`: staker account.763 pub fn get_locked_balance(764 staker: impl EncodeLike<T::AccountId>,765 ) -> Option<BalanceLock<BalanceOf<T>>> {766 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)767 .into_iter()768 .find(|l| l.id == LOCK_IDENTIFIER)769 }770771 /// Returns the total staked balance for the staker.772 ///773 /// - `staker`: staker account.774 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {775 let staked = Staked::<T>::iter_prefix((staker,))776 .into_iter()777 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {778 acc + amount779 });780 if staked != <BalanceOf<T>>::default() {781 Some(staked)782 } else {783 None784 }785 }786787 /// Returns all relay block numbers when stake was made,788 /// the amount of the stake.789 ///790 /// - `staker`: staker account.791 pub fn total_staked_by_id_per_block(792 staker: impl EncodeLike<T::AccountId>,793 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {794 let mut staked = Staked::<T>::iter_prefix((staker,))795 .into_iter()796 .map(|(block, (amount, _))| (block, amount))797 .collect::<Vec<_>>();798 staked.sort_by_key(|(block, _)| *block);799 if !staked.is_empty() {800 Some(staked)801 } else {802 None803 }804 }805806 /// Returns the total staked balance for the staker.807 /// If `staker` is `None`, returns the total amount staked.808 /// - `staker`: staker account.809 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {810 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {811 Self::total_staked_by_id(s.as_sub())812 })813 }814815 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {816 // Self::get_locked_balance(staker.as_sub())817 // .map(|l| l.amount)818 // .unwrap_or_default()819 // }820821 /// Returns all relay block numbers when stake was made,822 /// the amount of the stake.823 ///824 /// - `staker`: staker account.825 pub fn cross_id_total_staked_per_block(826 staker: T::CrossAccountId,827 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {828 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()829 }830831 fn recalculate_and_insert_stake(832 staker: &T::AccountId,833 staked_block: T::BlockNumber,834 next_recalc_block: T::BlockNumber,835 base: BalanceOf<T>,836 iters: u32,837 income_acc: &mut BalanceOf<T>,838 ) {839 let income = Self::calculate_income(base, iters);840841 base.checked_add(&income).map(|res| {842 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));843 *income_acc += income;844 });845 }846847 fn calculate_income<I>(base: I, iters: u32) -> I848 where849 I: EncodeLike<BalanceOf<T>> + Balance,850 {851 let config = <PalletConfiguration<T>>::get();852 let mut income = base;853854 (0..iters).for_each(|_| income += config.interval_income * income);855856 income - base857 }858859 /// Get relay block number rounded down to multiples of config.recalculation_interval.860 /// We need it to reward stakers in integer parts of recalculation_interval861 fn get_current_recalc_block(862 current_relay_block: T::BlockNumber,863 config: &PalletConfiguration<T>,864 ) -> T::BlockNumber {865 (current_relay_block / config.recalculation_interval) * config.recalculation_interval866 }867868 fn get_next_calculated_key() -> Option<Vec<u8>> {869 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))870 }871}872873impl<T: Config> Pallet<T>874where875 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,876{877 /// Returns the amount reserved by the pending.878 /// If `staker` is `None`, returns the total pending.879 ///880 /// -`staker`: staker account.881 ///882 /// Since user funds are not transferred anywhere by staking, overflow protection is provided883 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,884 /// the staker must have more funds on his account than the maximum set for `Balance` type.885 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {886 staker.map_or(887 PendingUnstake::<T>::iter_values()888 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))889 .sum(),890 |s| {891 PendingUnstake::<T>::iter_values()892 .flatten()893 .filter_map(|(id, amount)| {894 if id == *s.as_sub() {895 Some(amount)896 } else {897 None898 }899 })900 .sum()901 },902 )903 }904905 /// Returns all parachain block numbers when unreserve is expected,906 /// the amount of the unreserved funds.907 ///908 /// - `staker`: staker account.909 pub fn cross_id_pending_unstake_per_block(910 staker: T::CrossAccountId,911 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {912 let mut unsorted_res = vec![];913 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {914 pendings.into_iter().for_each(|(id, amount)| {915 if id == *staker.as_sub() {916 unsorted_res.push((block, amount));917 };918 })919 });920921 unsorted_res.sort_by_key(|(block, _)| *block);922 unsorted_res923 }924}