difftreelog
Merge pull request #800 from UniqueNetwork/fix/payout-stakers
in: master
Fix/payout stakers
4 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5549,7 +5549,7 @@
[[package]]
name = "pallet-app-promotion"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"frame-benchmarking",
"frame-support",
pallets/app-promotion/CHANGELOG.mddiffbeforeafterboth--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -4,6 +4,13 @@
<!-- bureaucrate goes here -->
+## [0.1.2] - 2022-12-20
+
+### Fixed
+
+- The behaviour of the `payoutStakers` extrinsic
+ in which only one stake is calculated for the last processed staker.
+
## [0.1.1] - 2022-12-13
### Added
pallets/app-promotion/Cargo.tomldiffbeforeafterboth--- a/pallets/app-promotion/Cargo.toml
+++ b/pallets/app-promotion/Cargo.toml
@@ -9,7 +9,7 @@
license = 'GPLv3'
name = 'pallet-app-promotion'
repository = 'https://github.com/UniqueNetwork/unique-chain'
-version = '0.1.1'
+version = '0.1.2'
[package.metadata.docs.rs]
targets = ['x86_64-unknown-linux-gnu']
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::call_index(0)]305 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]306 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {307 ensure_root(origin)?;308309 <Admin<T>>::set(Some(admin.as_sub().to_owned()));310311 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));312313 Ok(())314 }315316 /// Stakes the amount of native tokens.317 /// Sets `amount` to the locked state.318 /// The maximum number of stakes for a staker is 10.319 ///320 /// # Arguments321 ///322 /// * `amount`: in native tokens.323 #[pallet::call_index(1)]324 #[pallet::weight(<T as Config>::WeightInfo::stake())]325 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {326 let staker_id = ensure_signed(staker)?;327328 ensure!(329 StakesPerAccount::<T>::get(&staker_id) < 10,330 Error::<T>::NoPermission331 );332333 ensure!(334 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),335 ArithmeticError::Underflow336 );337 let config = <PalletConfiguration<T>>::get();338339 let balance =340 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);341342 // checks that we can lock `amount` on the `staker` account.343 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(344 &staker_id,345 amount,346 WithdrawReasons::all(),347 balance348 .checked_sub(&amount)349 .ok_or(ArithmeticError::Underflow)?,350 )?;351352 Self::add_lock_balance(&staker_id, amount)?;353354 let block_number = T::RelayBlockNumberProvider::current_block_number();355356 // Calculation of the number of recalculation periods,357 // after how much the first interest calculation should be performed for the stake358 let recalculate_after_interval: T::BlockNumber =359 if block_number % config.recalculation_interval == 0u32.into() {360 1u32.into()361 } else {362 2u32.into()363 };364365 // Сalculation of the number of the relay block366 // in which it is necessary to accrue remuneration for the stake.367 let recalc_block = (block_number / config.recalculation_interval368 + recalculate_after_interval)369 * config.recalculation_interval;370371 <Staked<T>>::insert((&staker_id, block_number), {372 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));373 balance_and_recalc_block.0 = balance_and_recalc_block374 .0375 .checked_add(&amount)376 .ok_or(ArithmeticError::Overflow)?;377 balance_and_recalc_block.1 = recalc_block;378 balance_and_recalc_block379 });380381 <TotalStaked<T>>::set(382 <TotalStaked<T>>::get()383 .checked_add(&amount)384 .ok_or(ArithmeticError::Overflow)?,385 );386387 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);388389 Self::deposit_event(Event::Stake(staker_id, amount));390391 Ok(())392 }393394 /// Unstakes all stakes.395 /// Moves the sum of all stakes to the `reserved` state.396 /// After the end of `PendingInterval` this sum becomes completely397 /// free for further use.398 #[pallet::call_index(2)]399 #[pallet::weight(<T as Config>::WeightInfo::unstake())]400 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {401 let staker_id = ensure_signed(staker)?;402 let config = <PalletConfiguration<T>>::get();403404 // calculate block number where the sum would be free405 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;406407 let mut pendings = <PendingUnstake<T>>::get(block);408409 // checks that we can do unreserve stakes in the block410 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);411412 let mut total_stakes = 0u64;413414 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))415 .map(|(_, (amount, _))| {416 total_stakes += 1;417 amount418 })419 .sum();420421 if total_staked.is_zero() {422 return Ok(None::<Weight>.into()); // TO-DO423 }424425 pendings426 .try_push((staker_id.clone(), total_staked))427 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;428429 <PendingUnstake<T>>::insert(block, pendings);430431 Self::unlock_balance(&staker_id, total_staked)?;432433 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(434 &staker_id,435 total_staked,436 )?;437438 TotalStaked::<T>::set(439 TotalStaked::<T>::get()440 .checked_sub(&total_staked)441 .ok_or(ArithmeticError::Underflow)?,442 );443444 StakesPerAccount::<T>::remove(&staker_id);445446 Self::deposit_event(Event::Unstake(staker_id, total_staked));447448 Ok(None::<Weight>.into())449 }450451 /// Sets the pallet to be the sponsor for the collection.452 ///453 /// # Permissions454 ///455 /// * Pallet admin456 ///457 /// # Arguments458 ///459 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`460 #[pallet::call_index(3)]461 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]462 pub fn sponsor_collection(463 admin: OriginFor<T>,464 collection_id: CollectionId,465 ) -> DispatchResult {466 let admin_id = ensure_signed(admin)?;467 ensure!(468 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,469 Error::<T>::NoPermission470 );471472 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)473 }474475 /// Removes the pallet as the sponsor for the collection.476 /// Returns [`NoPermission`][`Error::NoPermission`]477 /// if the pallet wasn't the sponsor.478 ///479 /// # Permissions480 ///481 /// * Pallet admin482 ///483 /// # Arguments484 ///485 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`486 #[pallet::call_index(4)]487 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]488 pub fn stop_sponsoring_collection(489 admin: OriginFor<T>,490 collection_id: CollectionId,491 ) -> DispatchResult {492 let admin_id = ensure_signed(admin)?;493494 ensure!(495 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,496 Error::<T>::NoPermission497 );498499 ensure!(500 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?501 == Self::account_id(),502 <Error<T>>::NoPermission503 );504 T::CollectionHandler::remove_collection_sponsor(collection_id)505 }506507 /// Sets the pallet to be the sponsor for the contract.508 ///509 /// # Permissions510 ///511 /// * Pallet admin512 ///513 /// # Arguments514 ///515 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`516 #[pallet::call_index(5)]517 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]518 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {519 let admin_id = ensure_signed(admin)?;520521 ensure!(522 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,523 Error::<T>::NoPermission524 );525526 T::ContractHandler::set_sponsor(527 T::CrossAccountId::from_sub(Self::account_id()),528 contract_id,529 )530 }531532 /// Removes the pallet as the sponsor for the contract.533 /// Returns [`NoPermission`][`Error::NoPermission`]534 /// if the pallet wasn't the sponsor.535 ///536 /// # Permissions537 ///538 /// * Pallet admin539 ///540 /// # Arguments541 ///542 /// * `contract_id`: the contract address that is sponsored by `pallet_id`543 #[pallet::call_index(6)]544 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]545 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {546 let admin_id = ensure_signed(admin)?;547548 ensure!(549 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,550 Error::<T>::NoPermission551 );552553 ensure!(554 T::ContractHandler::sponsor(contract_id)?555 .ok_or(<Error<T>>::SponsorNotSet)?556 .as_sub() == &Self::account_id(),557 <Error<T>>::NoPermission558 );559 T::ContractHandler::remove_contract_sponsor(contract_id)560 }561562 /// Recalculates interest for the specified number of stakers.563 /// If all stakers are not recalculated, the next call of the extrinsic564 /// will continue the recalculation, from those stakers for whom this565 /// was not perform in last call.566 ///567 /// # Permissions568 ///569 /// * Pallet admin570 ///571 /// # Arguments572 ///573 /// * `stakers_number`: the number of stakers for which recalculation will be performed574 #[pallet::call_index(7)]575 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]576 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {577 let admin_id = ensure_signed(admin)?;578579 ensure!(580 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,581 Error::<T>::NoPermission582 );583 let config = <PalletConfiguration<T>>::get();584585 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);586587 ensure!(588 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,589 Error::<T>::NoPermission590 );591592 // calculate the number of the current recalculation block,593 // this is necessary in order to understand which stakers we should calculate interest594 let current_recalc_block = Self::get_current_recalc_block(595 T::RelayBlockNumberProvider::current_block_number(),596 &config,597 );598599 // calculate the number of the next recalculation block,600 // this value is set for the stakers to whom the recalculation will be performed601 let next_recalc_block = current_recalc_block + config.recalculation_interval;602603 let mut storage_iterator = Self::get_next_calculated_key()604 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));605606 PreviousCalculatedRecord::<T>::set(None);607608 {609 // Address handled in the last payout loop iteration (below)610 let last_id = RefCell::new(None);611 // Reward balance for the address in the iteration612 let income_acc = RefCell::new(BalanceOf::<T>::default());613 // Staked balance for the address in the iteration (before stake is recalculated)614 let amount_acc = RefCell::new(BalanceOf::<T>::default());615616 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout617 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout618 // loop switches to handling the next staker address:619 // 1. Transfer full reward amount to the payee620 // 2. Lock the reward in staking lock621 // 3. Update TotalStaked amount622 // 4. Issue StakingRecalculation event623 let flush_stake = || -> DispatchResult {624 if let Some(last_id) = &*last_id.borrow() {625 if !income_acc.borrow().is_zero() {626 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(627 &T::TreasuryAccountId::get(),628 last_id,629 *income_acc.borrow(),630 ExistenceRequirement::KeepAlive,631 )?;632633 Self::add_lock_balance(last_id, *income_acc.borrow())?;634 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {635 *staked = staked636 .checked_add(&*income_acc.borrow())637 .ok_or(ArithmeticError::Overflow)?;638 Ok(())639 })?;640641 Self::deposit_event(Event::StakingRecalculation(642 last_id.clone(),643 *amount_acc.borrow(),644 *income_acc.borrow(),645 ));646 }647648 *income_acc.borrow_mut() = BalanceOf::<T>::default();649 *amount_acc.borrow_mut() = BalanceOf::<T>::default();650 }651 Ok(())652 };653654 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation655 // iterations in one extrinsic call656 //657 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)658 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out659 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)660 while let Some((661 (current_id, staked_block),662 (amount, next_recalc_block_for_stake),663 )) = storage_iterator.next()664 {665 // last_id is not equal current_id when we switch to handling a new staker address666 // or just start handling the very first address. In the latter case last_id will be None and667 // flush_stake will do nothing668 if last_id.borrow().as_ref() != Some(¤t_id) {669 flush_stake()?;670 *last_id.borrow_mut() = Some(current_id.clone());671 stakers_number -= 1;672 };673674 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount675 if current_recalc_block >= next_recalc_block_for_stake {676 *amount_acc.borrow_mut() += amount;677 Self::recalculate_and_insert_stake(678 ¤t_id,679 staked_block,680 next_recalc_block,681 amount,682 ((current_recalc_block - next_recalc_block_for_stake)683 / config.recalculation_interval)684 .into() + 1,685 &mut *income_acc.borrow_mut(),686 );687 }688689 // Break out if we reached the address limit690 if stakers_number == 0 {691 if storage_iterator.next().is_some() {692 // Save the last calculated record to pick up in the next extrinsic call693 PreviousCalculatedRecord::<T>::set(Some((current_id, staked_block)));694 }695 break;696 }697 }698 flush_stake()?;699 }700701 Ok(())702 }703 }704}705706impl<T: Config> Pallet<T> {707 /// The account address of the app promotion pot.708 ///709 /// This actually does computation. If you need to keep using it, then make sure you cache the710 /// value and only call this once.711 pub fn account_id() -> T::AccountId {712 T::PalletId::get().into_account_truncating()713 }714715 /// Unlocks the balance that was locked by the pallet.716 ///717 /// - `staker`: staker account.718 /// - `amount`: amount of unlocked funds.719 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {720 let locked_balance = Self::get_locked_balance(staker)721 .map(|l| l.amount)722 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;723724 // It is understood that we cannot unlock more funds than were locked by staking.725 // Therefore, if implemented correctly, this error should not occur.726 Self::set_lock_unchecked(727 staker,728 locked_balance729 .checked_sub(&amount)730 .ok_or(ArithmeticError::Underflow)?,731 );732 Ok(())733 }734735 /// Adds the balance to locked by the pallet.736 ///737 /// - `staker`: staker account.738 /// - `amount`: amount of added locked funds.739 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {740 Self::get_locked_balance(staker)741 .map_or(<BalanceOf<T>>::default(), |l| l.amount)742 .checked_add(&amount)743 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))744 .ok_or(ArithmeticError::Overflow.into())745 }746747 /// Sets the new state of a balance locked by the pallet.748 ///749 /// - `staker`: staker account.750 /// - `amount`: amount of locked funds.751 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {752 if amount.is_zero() {753 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(754 LOCK_IDENTIFIER,755 &staker,756 );757 } else {758 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(759 LOCK_IDENTIFIER,760 staker,761 amount,762 WithdrawReasons::all(),763 )764 }765 }766767 /// Returns the balance locked by the pallet for the staker.768 ///769 /// - `staker`: staker account.770 pub fn get_locked_balance(771 staker: impl EncodeLike<T::AccountId>,772 ) -> Option<BalanceLock<BalanceOf<T>>> {773 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)774 .into_iter()775 .find(|l| l.id == LOCK_IDENTIFIER)776 }777778 /// Returns the total staked balance for the staker.779 ///780 /// - `staker`: staker account.781 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {782 let staked = Staked::<T>::iter_prefix((staker,))783 .into_iter()784 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {785 acc + amount786 });787 if staked != <BalanceOf<T>>::default() {788 Some(staked)789 } else {790 None791 }792 }793794 /// Returns all relay block numbers when stake was made,795 /// the amount of the stake.796 ///797 /// - `staker`: staker account.798 pub fn total_staked_by_id_per_block(799 staker: impl EncodeLike<T::AccountId>,800 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {801 let mut staked = Staked::<T>::iter_prefix((staker,))802 .into_iter()803 .map(|(block, (amount, _))| (block, amount))804 .collect::<Vec<_>>();805 staked.sort_by_key(|(block, _)| *block);806 if !staked.is_empty() {807 Some(staked)808 } else {809 None810 }811 }812813 /// Returns the total staked balance for the staker.814 /// If `staker` is `None`, returns the total amount staked.815 /// - `staker`: staker account.816 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {817 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {818 Self::total_staked_by_id(s.as_sub())819 })820 }821822 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {823 // Self::get_locked_balance(staker.as_sub())824 // .map(|l| l.amount)825 // .unwrap_or_default()826 // }827828 /// Returns all relay block numbers when stake was made,829 /// the amount of the stake.830 ///831 /// - `staker`: staker account.832 pub fn cross_id_total_staked_per_block(833 staker: T::CrossAccountId,834 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {835 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()836 }837838 fn recalculate_and_insert_stake(839 staker: &T::AccountId,840 staked_block: T::BlockNumber,841 next_recalc_block: T::BlockNumber,842 base: BalanceOf<T>,843 iters: u32,844 income_acc: &mut BalanceOf<T>,845 ) {846 let income = Self::calculate_income(base, iters);847848 base.checked_add(&income).map(|res| {849 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));850 *income_acc += income;851 });852 }853854 fn calculate_income<I>(base: I, iters: u32) -> I855 where856 I: EncodeLike<BalanceOf<T>> + Balance,857 {858 let config = <PalletConfiguration<T>>::get();859 let mut income = base;860861 (0..iters).for_each(|_| income += config.interval_income * income);862863 income - base864 }865866 /// Get relay block number rounded down to multiples of config.recalculation_interval.867 /// We need it to reward stakers in integer parts of recalculation_interval868 fn get_current_recalc_block(869 current_relay_block: T::BlockNumber,870 config: &PalletConfiguration<T>,871 ) -> T::BlockNumber {872 (current_relay_block / config.recalculation_interval) * config.recalculation_interval873 }874875 fn get_next_calculated_key() -> Option<Vec<u8>> {876 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))877 }878}879880impl<T: Config> Pallet<T>881where882 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,883{884 /// Returns the amount reserved by the pending.885 /// If `staker` is `None`, returns the total pending.886 ///887 /// -`staker`: staker account.888 ///889 /// Since user funds are not transferred anywhere by staking, overflow protection is provided890 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,891 /// the staker must have more funds on his account than the maximum set for `Balance` type.892 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {893 staker.map_or(894 PendingUnstake::<T>::iter_values()895 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))896 .sum(),897 |s| {898 PendingUnstake::<T>::iter_values()899 .flatten()900 .filter_map(|(id, amount)| {901 if id == *s.as_sub() {902 Some(amount)903 } else {904 None905 }906 })907 .sum()908 },909 )910 }911912 /// Returns all parachain block numbers when unreserve is expected,913 /// the amount of the unreserved funds.914 ///915 /// - `staker`: staker account.916 pub fn cross_id_pending_unstake_per_block(917 staker: T::CrossAccountId,918 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {919 let mut unsorted_res = vec![];920 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {921 pendings.into_iter().for_each(|(id, amount)| {922 if id == *staker.as_sub() {923 unsorted_res.push((block, amount));924 };925 })926 });927928 unsorted_res.sort_by_key(|(block, _)| *block);929 unsorted_res930 }931}1// 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::call_index(0)]305 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]306 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {307 ensure_root(origin)?;308309 <Admin<T>>::set(Some(admin.as_sub().to_owned()));310311 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));312313 Ok(())314 }315316 /// Stakes the amount of native tokens.317 /// Sets `amount` to the locked state.318 /// The maximum number of stakes for a staker is 10.319 ///320 /// # Arguments321 ///322 /// * `amount`: in native tokens.323 #[pallet::call_index(1)]324 #[pallet::weight(<T as Config>::WeightInfo::stake())]325 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {326 let staker_id = ensure_signed(staker)?;327328 ensure!(329 StakesPerAccount::<T>::get(&staker_id) < 10,330 Error::<T>::NoPermission331 );332333 ensure!(334 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),335 ArithmeticError::Underflow336 );337 let config = <PalletConfiguration<T>>::get();338339 let balance =340 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);341342 // checks that we can lock `amount` on the `staker` account.343 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(344 &staker_id,345 amount,346 WithdrawReasons::all(),347 balance348 .checked_sub(&amount)349 .ok_or(ArithmeticError::Underflow)?,350 )?;351352 Self::add_lock_balance(&staker_id, amount)?;353354 let block_number = T::RelayBlockNumberProvider::current_block_number();355356 // Calculation of the number of recalculation periods,357 // after how much the first interest calculation should be performed for the stake358 let recalculate_after_interval: T::BlockNumber =359 if block_number % config.recalculation_interval == 0u32.into() {360 1u32.into()361 } else {362 2u32.into()363 };364365 // Сalculation of the number of the relay block366 // in which it is necessary to accrue remuneration for the stake.367 let recalc_block = (block_number / config.recalculation_interval368 + recalculate_after_interval)369 * config.recalculation_interval;370371 <Staked<T>>::insert((&staker_id, block_number), {372 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));373 balance_and_recalc_block.0 = balance_and_recalc_block374 .0375 .checked_add(&amount)376 .ok_or(ArithmeticError::Overflow)?;377 balance_and_recalc_block.1 = recalc_block;378 balance_and_recalc_block379 });380381 <TotalStaked<T>>::set(382 <TotalStaked<T>>::get()383 .checked_add(&amount)384 .ok_or(ArithmeticError::Overflow)?,385 );386387 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);388389 Self::deposit_event(Event::Stake(staker_id, amount));390391 Ok(())392 }393394 /// Unstakes all stakes.395 /// Moves the sum of all stakes to the `reserved` state.396 /// After the end of `PendingInterval` this sum becomes completely397 /// free for further use.398 #[pallet::call_index(2)]399 #[pallet::weight(<T as Config>::WeightInfo::unstake())]400 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {401 let staker_id = ensure_signed(staker)?;402 let config = <PalletConfiguration<T>>::get();403404 // calculate block number where the sum would be free405 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;406407 let mut pendings = <PendingUnstake<T>>::get(block);408409 // checks that we can do unreserve stakes in the block410 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);411412 let mut total_stakes = 0u64;413414 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))415 .map(|(_, (amount, _))| {416 total_stakes += 1;417 amount418 })419 .sum();420421 if total_staked.is_zero() {422 return Ok(None::<Weight>.into()); // TO-DO423 }424425 pendings426 .try_push((staker_id.clone(), total_staked))427 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;428429 <PendingUnstake<T>>::insert(block, pendings);430431 Self::unlock_balance(&staker_id, total_staked)?;432433 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(434 &staker_id,435 total_staked,436 )?;437438 TotalStaked::<T>::set(439 TotalStaked::<T>::get()440 .checked_sub(&total_staked)441 .ok_or(ArithmeticError::Underflow)?,442 );443444 StakesPerAccount::<T>::remove(&staker_id);445446 Self::deposit_event(Event::Unstake(staker_id, total_staked));447448 Ok(None::<Weight>.into())449 }450451 /// Sets the pallet to be the sponsor for the collection.452 ///453 /// # Permissions454 ///455 /// * Pallet admin456 ///457 /// # Arguments458 ///459 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`460 #[pallet::call_index(3)]461 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]462 pub fn sponsor_collection(463 admin: OriginFor<T>,464 collection_id: CollectionId,465 ) -> DispatchResult {466 let admin_id = ensure_signed(admin)?;467 ensure!(468 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,469 Error::<T>::NoPermission470 );471472 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)473 }474475 /// Removes the pallet as the sponsor for the collection.476 /// Returns [`NoPermission`][`Error::NoPermission`]477 /// if the pallet wasn't the sponsor.478 ///479 /// # Permissions480 ///481 /// * Pallet admin482 ///483 /// # Arguments484 ///485 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`486 #[pallet::call_index(4)]487 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]488 pub fn stop_sponsoring_collection(489 admin: OriginFor<T>,490 collection_id: CollectionId,491 ) -> DispatchResult {492 let admin_id = ensure_signed(admin)?;493494 ensure!(495 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,496 Error::<T>::NoPermission497 );498499 ensure!(500 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?501 == Self::account_id(),502 <Error<T>>::NoPermission503 );504 T::CollectionHandler::remove_collection_sponsor(collection_id)505 }506507 /// Sets the pallet to be the sponsor for the contract.508 ///509 /// # Permissions510 ///511 /// * Pallet admin512 ///513 /// # Arguments514 ///515 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`516 #[pallet::call_index(5)]517 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]518 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {519 let admin_id = ensure_signed(admin)?;520521 ensure!(522 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,523 Error::<T>::NoPermission524 );525526 T::ContractHandler::set_sponsor(527 T::CrossAccountId::from_sub(Self::account_id()),528 contract_id,529 )530 }531532 /// Removes the pallet as the sponsor for the contract.533 /// Returns [`NoPermission`][`Error::NoPermission`]534 /// if the pallet wasn't the sponsor.535 ///536 /// # Permissions537 ///538 /// * Pallet admin539 ///540 /// # Arguments541 ///542 /// * `contract_id`: the contract address that is sponsored by `pallet_id`543 #[pallet::call_index(6)]544 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]545 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {546 let admin_id = ensure_signed(admin)?;547548 ensure!(549 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,550 Error::<T>::NoPermission551 );552553 ensure!(554 T::ContractHandler::sponsor(contract_id)?555 .ok_or(<Error<T>>::SponsorNotSet)?556 .as_sub() == &Self::account_id(),557 <Error<T>>::NoPermission558 );559 T::ContractHandler::remove_contract_sponsor(contract_id)560 }561562 /// Recalculates interest for the specified number of stakers.563 /// If all stakers are not recalculated, the next call of the extrinsic564 /// will continue the recalculation, from those stakers for whom this565 /// was not perform in last call.566 ///567 /// # Permissions568 ///569 /// * Pallet admin570 ///571 /// # Arguments572 ///573 /// * `stakers_number`: the number of stakers for which recalculation will be performed574 #[pallet::call_index(7)]575 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]576 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {577 let admin_id = ensure_signed(admin)?;578579 ensure!(580 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,581 Error::<T>::NoPermission582 );583 let config = <PalletConfiguration<T>>::get();584585 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);586587 ensure!(588 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,589 Error::<T>::NoPermission590 );591592 // calculate the number of the current recalculation block,593 // this is necessary in order to understand which stakers we should calculate interest594 let current_recalc_block = Self::get_current_recalc_block(595 T::RelayBlockNumberProvider::current_block_number(),596 &config,597 );598599 // calculate the number of the next recalculation block,600 // this value is set for the stakers to whom the recalculation will be performed601 let next_recalc_block = current_recalc_block + config.recalculation_interval;602603 let mut storage_iterator = Self::get_next_calculated_key()604 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));605606 PreviousCalculatedRecord::<T>::set(None);607608 {609 // Address handled in the last payout loop iteration (below)610 let last_id = RefCell::new(None);611 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration612 let mut last_staked_calculated_block = Default::default();613 // Reward balance for the address in the iteration614 let income_acc = RefCell::new(BalanceOf::<T>::default());615 // Staked balance for the address in the iteration (before stake is recalculated)616 let amount_acc = RefCell::new(BalanceOf::<T>::default());617618 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout619 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout620 // loop switches to handling the next staker address:621 // 1. Transfer full reward amount to the payee622 // 2. Lock the reward in staking lock623 // 3. Update TotalStaked amount624 // 4. Issue StakingRecalculation event625 let flush_stake = || -> DispatchResult {626 if let Some(last_id) = &*last_id.borrow() {627 if !income_acc.borrow().is_zero() {628 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(629 &T::TreasuryAccountId::get(),630 last_id,631 *income_acc.borrow(),632 ExistenceRequirement::KeepAlive,633 )?;634635 Self::add_lock_balance(last_id, *income_acc.borrow())?;636 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {637 *staked = staked638 .checked_add(&*income_acc.borrow())639 .ok_or(ArithmeticError::Overflow)?;640 Ok(())641 })?;642643 Self::deposit_event(Event::StakingRecalculation(644 last_id.clone(),645 *amount_acc.borrow(),646 *income_acc.borrow(),647 ));648 }649650 *income_acc.borrow_mut() = BalanceOf::<T>::default();651 *amount_acc.borrow_mut() = BalanceOf::<T>::default();652 }653 Ok(())654 };655656 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation657 // iterations in one extrinsic call658 //659 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)660 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out661 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)662 while let Some((663 (current_id, staked_block),664 (amount, next_recalc_block_for_stake),665 )) = storage_iterator.next()666 {667 // last_id is not equal current_id when we switch to handling a new staker address668 // or just start handling the very first address. In the latter case last_id will be None and669 // flush_stake will do nothing670 if last_id.borrow().as_ref() != Some(¤t_id) {671 if stakers_number > 0 {672 flush_stake()?;673 *last_id.borrow_mut() = Some(current_id.clone());674 stakers_number -= 1;675 }676 // Break out if we reached the address limit677 else {678 if let Some(staker) = &*last_id.borrow() {679 // Save the last calculated record to pick up in the next extrinsic call680 PreviousCalculatedRecord::<T>::set(Some((681 staker.clone(),682 last_staked_calculated_block,683 )));684 }685 break;686 };687 };688689 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount690 if current_recalc_block >= next_recalc_block_for_stake {691 *amount_acc.borrow_mut() += amount;692 Self::recalculate_and_insert_stake(693 ¤t_id,694 staked_block,695 next_recalc_block,696 amount,697 ((current_recalc_block - next_recalc_block_for_stake)698 / config.recalculation_interval)699 .into() + 1,700 &mut *income_acc.borrow_mut(),701 );702 }703 last_staked_calculated_block = staked_block;704 }705 flush_stake()?;706 }707708 Ok(())709 }710 }711}712713impl<T: Config> Pallet<T> {714 /// The account address of the app promotion pot.715 ///716 /// This actually does computation. If you need to keep using it, then make sure you cache the717 /// value and only call this once.718 pub fn account_id() -> T::AccountId {719 T::PalletId::get().into_account_truncating()720 }721722 /// Unlocks the balance that was locked by the pallet.723 ///724 /// - `staker`: staker account.725 /// - `amount`: amount of unlocked funds.726 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {727 let locked_balance = Self::get_locked_balance(staker)728 .map(|l| l.amount)729 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;730731 // It is understood that we cannot unlock more funds than were locked by staking.732 // Therefore, if implemented correctly, this error should not occur.733 Self::set_lock_unchecked(734 staker,735 locked_balance736 .checked_sub(&amount)737 .ok_or(ArithmeticError::Underflow)?,738 );739 Ok(())740 }741742 /// Adds the balance to locked by the pallet.743 ///744 /// - `staker`: staker account.745 /// - `amount`: amount of added locked funds.746 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {747 Self::get_locked_balance(staker)748 .map_or(<BalanceOf<T>>::default(), |l| l.amount)749 .checked_add(&amount)750 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))751 .ok_or(ArithmeticError::Overflow.into())752 }753754 /// Sets the new state of a balance locked by the pallet.755 ///756 /// - `staker`: staker account.757 /// - `amount`: amount of locked funds.758 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {759 if amount.is_zero() {760 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(761 LOCK_IDENTIFIER,762 &staker,763 );764 } else {765 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(766 LOCK_IDENTIFIER,767 staker,768 amount,769 WithdrawReasons::all(),770 )771 }772 }773774 /// Returns the balance locked by the pallet for the staker.775 ///776 /// - `staker`: staker account.777 pub fn get_locked_balance(778 staker: impl EncodeLike<T::AccountId>,779 ) -> Option<BalanceLock<BalanceOf<T>>> {780 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)781 .into_iter()782 .find(|l| l.id == LOCK_IDENTIFIER)783 }784785 /// Returns the total staked balance for the staker.786 ///787 /// - `staker`: staker account.788 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {789 let staked = Staked::<T>::iter_prefix((staker,))790 .into_iter()791 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {792 acc + amount793 });794 if staked != <BalanceOf<T>>::default() {795 Some(staked)796 } else {797 None798 }799 }800801 /// Returns all relay block numbers when stake was made,802 /// the amount of the stake.803 ///804 /// - `staker`: staker account.805 pub fn total_staked_by_id_per_block(806 staker: impl EncodeLike<T::AccountId>,807 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {808 let mut staked = Staked::<T>::iter_prefix((staker,))809 .into_iter()810 .map(|(block, (amount, _))| (block, amount))811 .collect::<Vec<_>>();812 staked.sort_by_key(|(block, _)| *block);813 if !staked.is_empty() {814 Some(staked)815 } else {816 None817 }818 }819820 /// Returns the total staked balance for the staker.821 /// If `staker` is `None`, returns the total amount staked.822 /// - `staker`: staker account.823 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {824 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {825 Self::total_staked_by_id(s.as_sub())826 })827 }828829 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {830 // Self::get_locked_balance(staker.as_sub())831 // .map(|l| l.amount)832 // .unwrap_or_default()833 // }834835 /// Returns all relay block numbers when stake was made,836 /// the amount of the stake.837 ///838 /// - `staker`: staker account.839 pub fn cross_id_total_staked_per_block(840 staker: T::CrossAccountId,841 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {842 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()843 }844845 fn recalculate_and_insert_stake(846 staker: &T::AccountId,847 staked_block: T::BlockNumber,848 next_recalc_block: T::BlockNumber,849 base: BalanceOf<T>,850 iters: u32,851 income_acc: &mut BalanceOf<T>,852 ) {853 let income = Self::calculate_income(base, iters);854855 base.checked_add(&income).map(|res| {856 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));857 *income_acc += income;858 });859 }860861 fn calculate_income<I>(base: I, iters: u32) -> I862 where863 I: EncodeLike<BalanceOf<T>> + Balance,864 {865 let config = <PalletConfiguration<T>>::get();866 let mut income = base;867868 (0..iters).for_each(|_| income += config.interval_income * income);869870 income - base871 }872873 /// Get relay block number rounded down to multiples of config.recalculation_interval.874 /// We need it to reward stakers in integer parts of recalculation_interval875 fn get_current_recalc_block(876 current_relay_block: T::BlockNumber,877 config: &PalletConfiguration<T>,878 ) -> T::BlockNumber {879 (current_relay_block / config.recalculation_interval) * config.recalculation_interval880 }881882 fn get_next_calculated_key() -> Option<Vec<u8>> {883 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))884 }885}886887impl<T: Config> Pallet<T>888where889 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,890{891 /// Returns the amount reserved by the pending.892 /// If `staker` is `None`, returns the total pending.893 ///894 /// -`staker`: staker account.895 ///896 /// Since user funds are not transferred anywhere by staking, overflow protection is provided897 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,898 /// the staker must have more funds on his account than the maximum set for `Balance` type.899 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {900 staker.map_or(901 PendingUnstake::<T>::iter_values()902 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))903 .sum(),904 |s| {905 PendingUnstake::<T>::iter_values()906 .flatten()907 .filter_map(|(id, amount)| {908 if id == *s.as_sub() {909 Some(amount)910 } else {911 None912 }913 })914 .sum()915 },916 )917 }918919 /// Returns all parachain block numbers when unreserve is expected,920 /// the amount of the unreserved funds.921 ///922 /// - `staker`: staker account.923 pub fn cross_id_pending_unstake_per_block(924 staker: T::CrossAccountId,925 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {926 let mut unsorted_res = vec![];927 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {928 pendings.into_iter().for_each(|(id, amount)| {929 if id == *staker.as_sub() {930 unsorted_res.push((block, amount));931 };932 })933 });934935 unsorted_res.sort_by_key(|(block, _)| *block);936 unsorted_res937 }938}