difftreelog
fix format
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,100 pallet_prelude::{*, ValueQuery, StorageValue},101 storage::Key,102 PalletId,103 traits::ReservableCurrency,104 weights::Weight,105 };106 use frame_system::pallet_prelude::*;107108 #[pallet::config]109 pub trait Config:110 frame_system::Config + pallet_evm::Config + pallet_configuration::Config111 {112 /// Type to interact with the native token113 type Currency: ExtendedLockableCurrency<Self::AccountId>114 + ReservableCurrency<Self::AccountId>;115116 /// Type for interacting with collections117 type CollectionHandler: CollectionHandler<118 AccountId = Self::AccountId,119 CollectionId = CollectionId,120 >;121122 /// Type for interacting with conrtacts123 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;124125 /// `AccountId` for treasury126 type TreasuryAccountId: Get<Self::AccountId>;127128 /// The app's pallet id, used for deriving its sovereign account address.129 #[pallet::constant]130 type PalletId: Get<PalletId>;131132 /// In relay blocks.133 #[pallet::constant]134 type RecalculationInterval: Get<Self::BlockNumber>;135136 /// In parachain blocks.137 #[pallet::constant]138 type PendingInterval: Get<Self::BlockNumber>;139140 /// Rate of return for interval in blocks defined in `RecalculationInterval`.141 #[pallet::constant]142 type IntervalIncome: Get<Perbill>;143144 /// Decimals for the `Currency`.145 #[pallet::constant]146 type Nominal: Get<BalanceOf<Self>>;147148 /// Weight information for extrinsics in this pallet.149 type WeightInfo: WeightInfo;150151 // The relay block number provider152 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;153154 /// Events compatible with [`frame_system::Config::Event`].155 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;156 }157158 #[pallet::pallet]159 #[pallet::generate_store(pub(super) trait Store)]160 pub struct Pallet<T>(_);161162 #[pallet::event]163 #[pallet::generate_deposit(fn deposit_event)]164 pub enum Event<T: Config> {165 /// Staking recalculation was performed166 ///167 /// # Arguments168 /// * AccountId: account of the staker.169 /// * Balance : recalculation base170 /// * Balance : total income171 StakingRecalculation(172 /// An recalculated staker173 T::AccountId,174 /// Base on which interest is calculated175 BalanceOf<T>,176 /// Amount of accrued interest177 BalanceOf<T>,178 ),179180 /// Staking was performed181 ///182 /// # Arguments183 /// * AccountId: account of the staker184 /// * Balance : staking amount185 Stake(T::AccountId, BalanceOf<T>),186187 /// Unstaking was performed188 ///189 /// # Arguments190 /// * AccountId: account of the staker191 /// * Balance : unstaking amount192 Unstake(T::AccountId, BalanceOf<T>),193194 /// The admin was set195 ///196 /// # Arguments197 /// * AccountId: account address of the admin198 SetAdmin(T::AccountId),199 }200201 #[pallet::error]202 pub enum Error<T> {203 /// Error due to action requiring admin to be set.204 AdminNotSet,205 /// No permission to perform an action.206 NoPermission,207 /// Insufficient funds to perform an action.208 NotSufficientFunds,209 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.210 PendingForBlockOverflow,211 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.212 SponsorNotSet,213 /// Errors caused by incorrect actions with a locked balance.214 IncorrectLockedBalanceOperation,215 }216217 /// Stores the total staked amount.218 #[pallet::storage]219 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;220221 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.222 #[pallet::storage]223 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;224225 /// Stores the amount of tokens staked by account in the blocknumber.226 ///227 /// * **Key1** - Staker account.228 /// * **Key2** - Relay block number when the stake was made.229 /// * **(Balance, BlockNumber)** - Balance of the stake.230 /// The number of the relay block in which we must perform the interest recalculation231 #[pallet::storage]232 pub type Staked<T: Config> = StorageNMap<233 Key = (234 Key<Blake2_128Concat, T::AccountId>,235 Key<Twox64Concat, T::BlockNumber>,236 ),237 Value = (BalanceOf<T>, T::BlockNumber),238 QueryKind = ValueQuery,239 >;240241 /// Stores amount of stakes for an `Account`.242 ///243 /// * **Key** - Staker account.244 /// * **Value** - Amount of stakes.245 #[pallet::storage]246 pub type StakesPerAccount<T: Config> =247 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;248249 /// Stores amount of stakes for an `Account`.250 ///251 /// * **Key** - Staker account.252 /// * **Value** - Amount of stakes.253 #[pallet::storage]254 pub type PendingUnstake<T: Config> = StorageMap<255 _,256 Twox64Concat,257 T::BlockNumber,258 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,259 ValueQuery,260 >;261262 /// Stores a key for record for which the revenue recalculation was performed.263 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.264 #[pallet::storage]265 #[pallet::getter(fn get_next_calculated_record)]266 pub type PreviousCalculatedRecord<T: Config> =267 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;268269 #[pallet::storage]270 pub(crate) type IsMigrated<T: Config> = StorageValue<Value = bool, QueryKind = ValueQuery>;271272 #[pallet::hooks]273 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {274 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize275 /// implies the execution of a strictly limited number of relatively lightweight operations.276 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.277 fn on_initialize(current_block_number: T::BlockNumber) -> Weight278 where279 <T as frame_system::Config>::BlockNumber: From<u32>,280 {281 let block_pending = PendingUnstake::<T>::take(current_block_number);282 let counter = block_pending.len() as u32;283284 if !block_pending.is_empty() {285 block_pending.into_iter().for_each(|(staker, amount)| {286 Self::get_locked_balance(&staker).map(|b| {287 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();288 Self::set_lock_unchecked(&staker, new_state);289 });290 });291 }292293 <T as Config>::WeightInfo::on_initialize(counter)294 }295296 fn on_runtime_upgrade() -> Weight {297 let mut consumed_weight = Weight::zero();298 let mut add_weight = |reads, writes, weight| {299 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);300 consumed_weight += weight;301 };302303 if <IsMigrated<T>>::get() {304 add_weight(1, 0, Weight::zero());305 return consumed_weight;306 } else {307 add_weight(1, 1, Weight::zero());308 <IsMigrated<T>>::set(true);309 }310 <PendingUnstake<T>>::drain().for_each(|(_, v)| {311 add_weight(1, 1, Weight::zero());312 v.into_iter().for_each(|(staker, amount)| {313 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(314 &staker, amount,315 );316 add_weight(1, 1, Weight::zero());317 });318 });319320 consumed_weight321 }322323 #[cfg(feature = "try-runtime")]324 fn pre_upgrade() -> Result<Vec<u8>, &'static str> {325 use sp_std::collections::btree_map::BTreeMap;326 if <IsMigrated<T>>::get() {327 return Ok(Default::default());328 }329 // Staker -> (total amount of reserved balance, reserved by promotion);330 let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =331 BTreeMap::new();332333 <PendingUnstake<T>>::iter().for_each(|(_, v)| {334 v.into_iter().for_each(|(staker, amount)| {335 if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {336 *reserved_balance += amount;337 } else {338 let total_reserve = <<T as Config>::Currency as ReservableCurrency<339 T::AccountId,340 >>::reserved_balance(&staker);341 pre_state.insert(staker, (total_reserve, amount));342 }343 })344 });345346 Ok(pre_state.encode())347 }348349 #[cfg(feature = "try-runtime")]350 fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {351 use sp_std::collections::btree_map::BTreeMap;352353 if <IsMigrated<T>>::get() {354 return Ok(());355 }356 357 ensure!(358 <PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,359 "pendingUnstake storage isn't empty"360 );361 362 let mut is_ok = true;363364 let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =365 Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;366 for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {367 let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<368 T::AccountId,369 >>::reserved_balance(&staker);370 if new_state_reserve != total_reserved - reserved_by_promo {371 is_ok = false;372 log::error!(373 "Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",374 staker, new_state_reserve, total_reserved, reserved_by_promo375 );376 }377 }378379 if is_ok {380 Ok(())381 } else {382 Err("Incorrect balance for some of stakers... See logs")383 }384 }385 }386387 #[pallet::call]388 impl<T: Config> Pallet<T>389 where390 T::BlockNumber: From<u32> + Into<u32>,391 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,392 {393 /// Sets an address as the the admin.394 ///395 /// # Permissions396 ///397 /// * Sudo398 ///399 /// # Arguments400 ///401 /// * `admin`: account of the new admin.402 #[pallet::call_index(0)]403 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]404 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {405 ensure_root(origin)?;406407 <Admin<T>>::set(Some(admin.as_sub().to_owned()));408409 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));410411 Ok(())412 }413414 /// Stakes the amount of native tokens.415 /// Sets `amount` to the locked state.416 /// The maximum number of stakes for a staker is 10.417 ///418 /// # Arguments419 ///420 /// * `amount`: in native tokens.421 #[pallet::call_index(1)]422 #[pallet::weight(<T as Config>::WeightInfo::stake())]423 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {424 let staker_id = ensure_signed(staker)?;425426 ensure!(427 StakesPerAccount::<T>::get(&staker_id) < 10,428 Error::<T>::NoPermission429 );430431 ensure!(432 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),433 ArithmeticError::Underflow434 );435 let config = <PalletConfiguration<T>>::get();436437 let balance =438 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);439440 // checks that we can lock `amount` on the `staker` account.441 ensure!(442 amount443 <= match Self::get_locked_balance(&staker_id) {444 Some(lock) => balance445 .checked_sub(&lock.amount)446 .ok_or(ArithmeticError::Underflow)?,447 None => balance,448 },449 ArithmeticError::Underflow450 );451452 Self::add_lock_balance(&staker_id, amount)?;453454 let block_number = T::RelayBlockNumberProvider::current_block_number();455456 // Calculation of the number of recalculation periods,457 // after how much the first interest calculation should be performed for the stake458 let recalculate_after_interval: T::BlockNumber =459 if block_number % config.recalculation_interval == 0u32.into() {460 1u32.into()461 } else {462 2u32.into()463 };464465 // Сalculation of the number of the relay block466 // in which it is necessary to accrue remuneration for the stake.467 let recalc_block = (block_number / config.recalculation_interval468 + recalculate_after_interval)469 * config.recalculation_interval;470471 <Staked<T>>::insert((&staker_id, block_number), {472 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));473 balance_and_recalc_block.0 = balance_and_recalc_block474 .0475 .checked_add(&amount)476 .ok_or(ArithmeticError::Overflow)?;477 balance_and_recalc_block.1 = recalc_block;478 balance_and_recalc_block479 });480481 <TotalStaked<T>>::set(482 <TotalStaked<T>>::get()483 .checked_add(&amount)484 .ok_or(ArithmeticError::Overflow)?,485 );486487 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);488489 Self::deposit_event(Event::Stake(staker_id, amount));490491 Ok(())492 }493494 /// Unstakes all stakes.495 /// Moves the sum of all stakes to the `reserved` state.496 /// After the end of `PendingInterval` this sum becomes completely497 /// free for further use.498 #[pallet::call_index(2)]499 #[pallet::weight(<T as Config>::WeightInfo::unstake())]500 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {501 let staker_id = ensure_signed(staker)?;502 let config = <PalletConfiguration<T>>::get();503504 // calculate block number where the sum would be free505 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;506507 let mut pendings = <PendingUnstake<T>>::get(block);508509 // checks that we can do unreserve stakes in the block510 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);511512 let mut total_stakes = 0u64;513514 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))515 .map(|(_, (amount, _))| {516 total_stakes += 1;517 amount518 })519 .sum();520521 if total_staked.is_zero() {522 return Ok(None::<Weight>.into()); // TO-DO523 }524525 pendings526 .try_push((staker_id.clone(), total_staked))527 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;528529 <PendingUnstake<T>>::insert(block, pendings);530531532 TotalStaked::<T>::set(533 TotalStaked::<T>::get()534 .checked_sub(&total_staked)535 .ok_or(ArithmeticError::Underflow)?,536 );537538 StakesPerAccount::<T>::remove(&staker_id);539540 Self::deposit_event(Event::Unstake(staker_id, total_staked));541542 Ok(None::<Weight>.into())543 }544545 /// Sets the pallet to be the sponsor for the collection.546 ///547 /// # Permissions548 ///549 /// * Pallet admin550 ///551 /// # Arguments552 ///553 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`554 #[pallet::call_index(3)]555 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]556 pub fn sponsor_collection(557 admin: OriginFor<T>,558 collection_id: CollectionId,559 ) -> DispatchResult {560 let admin_id = ensure_signed(admin)?;561 ensure!(562 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,563 Error::<T>::NoPermission564 );565566 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)567 }568569 /// Removes the pallet as the sponsor for the collection.570 /// Returns [`NoPermission`][`Error::NoPermission`]571 /// if the pallet wasn't the sponsor.572 ///573 /// # Permissions574 ///575 /// * Pallet admin576 ///577 /// # Arguments578 ///579 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`580 #[pallet::call_index(4)]581 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]582 pub fn stop_sponsoring_collection(583 admin: OriginFor<T>,584 collection_id: CollectionId,585 ) -> DispatchResult {586 let admin_id = ensure_signed(admin)?;587588 ensure!(589 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,590 Error::<T>::NoPermission591 );592593 ensure!(594 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?595 == Self::account_id(),596 <Error<T>>::NoPermission597 );598 T::CollectionHandler::remove_collection_sponsor(collection_id)599 }600601 /// Sets the pallet to be the sponsor for the contract.602 ///603 /// # Permissions604 ///605 /// * Pallet admin606 ///607 /// # Arguments608 ///609 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`610 #[pallet::call_index(5)]611 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]612 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {613 let admin_id = ensure_signed(admin)?;614615 ensure!(616 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,617 Error::<T>::NoPermission618 );619620 T::ContractHandler::set_sponsor(621 T::CrossAccountId::from_sub(Self::account_id()),622 contract_id,623 )624 }625626 /// Removes the pallet as the sponsor for the contract.627 /// Returns [`NoPermission`][`Error::NoPermission`]628 /// if the pallet wasn't the sponsor.629 ///630 /// # Permissions631 ///632 /// * Pallet admin633 ///634 /// # Arguments635 ///636 /// * `contract_id`: the contract address that is sponsored by `pallet_id`637 #[pallet::call_index(6)]638 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]639 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {640 let admin_id = ensure_signed(admin)?;641642 ensure!(643 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,644 Error::<T>::NoPermission645 );646647 ensure!(648 T::ContractHandler::sponsor(contract_id)?649 .ok_or(<Error<T>>::SponsorNotSet)?650 .as_sub() == &Self::account_id(),651 <Error<T>>::NoPermission652 );653 T::ContractHandler::remove_contract_sponsor(contract_id)654 }655656 /// Recalculates interest for the specified number of stakers.657 /// If all stakers are not recalculated, the next call of the extrinsic658 /// will continue the recalculation, from those stakers for whom this659 /// was not perform in last call.660 ///661 /// # Permissions662 ///663 /// * Pallet admin664 ///665 /// # Arguments666 ///667 /// * `stakers_number`: the number of stakers for which recalculation will be performed668 #[pallet::call_index(7)]669 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]670 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {671 let admin_id = ensure_signed(admin)?;672673 ensure!(674 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,675 Error::<T>::NoPermission676 );677 let config = <PalletConfiguration<T>>::get();678679 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);680681 ensure!(682 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,683 Error::<T>::NoPermission684 );685686 // calculate the number of the current recalculation block,687 // this is necessary in order to understand which stakers we should calculate interest688 let current_recalc_block = Self::get_current_recalc_block(689 T::RelayBlockNumberProvider::current_block_number(),690 &config,691 );692693 // calculate the number of the next recalculation block,694 // this value is set for the stakers to whom the recalculation will be performed695 let next_recalc_block = current_recalc_block + config.recalculation_interval;696697 let mut storage_iterator = Self::get_next_calculated_key()698 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));699700 PreviousCalculatedRecord::<T>::set(None);701702 {703 // Address handled in the last payout loop iteration (below)704 let last_id = RefCell::new(None);705 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration706 let mut last_staked_calculated_block = Default::default();707 // Reward balance for the address in the iteration708 let income_acc = RefCell::new(BalanceOf::<T>::default());709 // Staked balance for the address in the iteration (before stake is recalculated)710 let amount_acc = RefCell::new(BalanceOf::<T>::default());711712 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout713 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout714 // loop switches to handling the next staker address:715 // 1. Transfer full reward amount to the payee716 // 2. Lock the reward in staking lock717 // 3. Update TotalStaked amount718 // 4. Issue StakingRecalculation event719 let flush_stake = || -> DispatchResult {720 if let Some(last_id) = &*last_id.borrow() {721 if !income_acc.borrow().is_zero() {722 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(723 &T::TreasuryAccountId::get(),724 last_id,725 *income_acc.borrow(),726 ExistenceRequirement::KeepAlive,727 )?;728729 Self::add_lock_balance(last_id, *income_acc.borrow())?;730 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {731 *staked = staked732 .checked_add(&*income_acc.borrow())733 .ok_or(ArithmeticError::Overflow)?;734 Ok(())735 })?;736737 Self::deposit_event(Event::StakingRecalculation(738 last_id.clone(),739 *amount_acc.borrow(),740 *income_acc.borrow(),741 ));742 }743744 *income_acc.borrow_mut() = BalanceOf::<T>::default();745 *amount_acc.borrow_mut() = BalanceOf::<T>::default();746 }747 Ok(())748 };749750 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation751 // iterations in one extrinsic call752 //753 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)754 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out755 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)756 while let Some((757 (current_id, staked_block),758 (amount, next_recalc_block_for_stake),759 )) = storage_iterator.next()760 {761 // last_id is not equal current_id when we switch to handling a new staker address762 // or just start handling the very first address. In the latter case last_id will be None and763 // flush_stake will do nothing764 if last_id.borrow().as_ref() != Some(¤t_id) {765 if stakers_number > 0 {766 flush_stake()?;767 *last_id.borrow_mut() = Some(current_id.clone());768 stakers_number -= 1;769 }770 // Break out if we reached the address limit771 else {772 if let Some(staker) = &*last_id.borrow() {773 // Save the last calculated record to pick up in the next extrinsic call774 PreviousCalculatedRecord::<T>::set(Some((775 staker.clone(),776 last_staked_calculated_block,777 )));778 }779 break;780 };781 };782783 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount784 if current_recalc_block >= next_recalc_block_for_stake {785 *amount_acc.borrow_mut() += amount;786 Self::recalculate_and_insert_stake(787 ¤t_id,788 staked_block,789 next_recalc_block,790 amount,791 ((current_recalc_block - next_recalc_block_for_stake)792 / config.recalculation_interval)793 .into() + 1,794 &mut *income_acc.borrow_mut(),795 );796 }797 last_staked_calculated_block = staked_block;798 }799 flush_stake()?;800 }801802 Ok(())803 }804 }805}806807impl<T: Config> Pallet<T> {808 /// The account address of the app promotion pot.809 ///810 /// This actually does computation. If you need to keep using it, then make sure you cache the811 /// value and only call this once.812 pub fn account_id() -> T::AccountId {813 T::PalletId::get().into_account_truncating()814 }815816 // /// Unlocks the balance that was locked by the pallet.817 // ///818 // /// - `staker`: staker account.819 // /// - `amount`: amount of unlocked funds.820 // fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {821 // let locked_balance = Self::get_locked_balance(staker)822 // .map(|l| l.amount)823 // .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;824825 // // It is understood that we cannot unlock more funds than were locked by staking.826 // // Therefore, if implemented correctly, this error should not occur.827 // Self::set_lock_unchecked(828 // staker,829 // locked_balance830 // .checked_sub(&amount)831 // .ok_or(ArithmeticError::Underflow)?,832 // );833 // Ok(())834 // }835836 /// Adds the balance to locked by the pallet.837 ///838 /// - `staker`: staker account.839 /// - `amount`: amount of added locked funds.840 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {841 Self::get_locked_balance(staker)842 .map_or(<BalanceOf<T>>::default(), |l| l.amount)843 .checked_add(&amount)844 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))845 .ok_or(ArithmeticError::Overflow.into())846 }847848 /// Sets the new state of a balance locked by the pallet.849 ///850 /// - `staker`: staker account.851 /// - `amount`: amount of locked funds.852 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {853 if amount.is_zero() {854 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(855 LOCK_IDENTIFIER,856 &staker,857 );858 } else {859 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(860 LOCK_IDENTIFIER,861 staker,862 amount,863 WithdrawReasons::all(),864 )865 }866 }867868 /// Returns the balance locked by the pallet for the staker.869 ///870 /// - `staker`: staker account.871 pub fn get_locked_balance(872 staker: impl EncodeLike<T::AccountId>,873 ) -> Option<BalanceLock<BalanceOf<T>>> {874 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)875 .into_iter()876 .find(|l| l.id == LOCK_IDENTIFIER)877 }878879 /// Returns the total staked balance for the staker.880 ///881 /// - `staker`: staker account.882 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {883 let staked = Staked::<T>::iter_prefix((staker,))884 .into_iter()885 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {886 acc + amount887 });888 if staked != <BalanceOf<T>>::default() {889 Some(staked)890 } else {891 None892 }893 }894895 /// Returns all relay block numbers when stake was made,896 /// the amount of the stake.897 ///898 /// - `staker`: staker account.899 pub fn total_staked_by_id_per_block(900 staker: impl EncodeLike<T::AccountId>,901 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {902 let mut staked = Staked::<T>::iter_prefix((staker,))903 .into_iter()904 .map(|(block, (amount, _))| (block, amount))905 .collect::<Vec<_>>();906 staked.sort_by_key(|(block, _)| *block);907 if !staked.is_empty() {908 Some(staked)909 } else {910 None911 }912 }913914 /// Returns the total staked balance for the staker.915 /// If `staker` is `None`, returns the total amount staked.916 /// - `staker`: staker account.917 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {918 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {919 Self::total_staked_by_id(s.as_sub())920 })921 }922923 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {924 // Self::get_locked_balance(staker.as_sub())925 // .map(|l| l.amount)926 // .unwrap_or_default()927 // }928929 /// Returns all relay block numbers when stake was made,930 /// the amount of the stake.931 ///932 /// - `staker`: staker account.933 pub fn cross_id_total_staked_per_block(934 staker: T::CrossAccountId,935 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {936 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()937 }938939 fn recalculate_and_insert_stake(940 staker: &T::AccountId,941 staked_block: T::BlockNumber,942 next_recalc_block: T::BlockNumber,943 base: BalanceOf<T>,944 iters: u32,945 income_acc: &mut BalanceOf<T>,946 ) {947 let income = Self::calculate_income(base, iters);948949 base.checked_add(&income).map(|res| {950 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));951 *income_acc += income;952 });953 }954955 fn calculate_income<I>(base: I, iters: u32) -> I956 where957 I: EncodeLike<BalanceOf<T>> + Balance,958 {959 let config = <PalletConfiguration<T>>::get();960 let mut income = base;961962 (0..iters).for_each(|_| income += config.interval_income * income);963964 income - base965 }966967 /// Get relay block number rounded down to multiples of config.recalculation_interval.968 /// We need it to reward stakers in integer parts of recalculation_interval969 fn get_current_recalc_block(970 current_relay_block: T::BlockNumber,971 config: &PalletConfiguration<T>,972 ) -> T::BlockNumber {973 (current_relay_block / config.recalculation_interval) * config.recalculation_interval974 }975976 fn get_next_calculated_key() -> Option<Vec<u8>> {977 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))978 }979}980981impl<T: Config> Pallet<T>982where983 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,984{985 /// Returns the amount reserved by the pending.986 /// If `staker` is `None`, returns the total pending.987 ///988 /// -`staker`: staker account.989 ///990 /// Since user funds are not transferred anywhere by staking, overflow protection is provided991 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,992 /// the staker must have more funds on his account than the maximum set for `Balance` type.993 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {994 staker.map_or(995 PendingUnstake::<T>::iter_values()996 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))997 .sum(),998 |s| {999 PendingUnstake::<T>::iter_values()1000 .flatten()1001 .filter_map(|(id, amount)| {1002 if id == *s.as_sub() {1003 Some(amount)1004 } else {1005 None1006 }1007 })1008 .sum()1009 },1010 )1011 }10121013 /// Returns all parachain block numbers when unreserve is expected,1014 /// the amount of the unreserved funds.1015 ///1016 /// - `staker`: staker account.1017 pub fn cross_id_pending_unstake_per_block(1018 staker: T::CrossAccountId,1019 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1020 let mut unsorted_res = vec![];1021 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1022 pendings.into_iter().for_each(|(id, amount)| {1023 if id == *staker.as_sub() {1024 unsorted_res.push((block, amount));1025 };1026 })1027 });10281029 unsorted_res.sort_by_key(|(block, _)| *block);1030 unsorted_res1031 }1032}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, 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 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::storage]266 pub(crate) type IsMigrated<T: Config> = StorageValue<Value = bool, QueryKind = ValueQuery>;267268 #[pallet::hooks]269 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {270 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize271 /// implies the execution of a strictly limited number of relatively lightweight operations.272 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.273 fn on_initialize(current_block_number: T::BlockNumber) -> Weight274 where275 <T as frame_system::Config>::BlockNumber: From<u32>,276 {277 let block_pending = PendingUnstake::<T>::take(current_block_number);278 let counter = block_pending.len() as u32;279280 if !block_pending.is_empty() {281 block_pending.into_iter().for_each(|(staker, amount)| {282 Self::get_locked_balance(&staker).map(|b| {283 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();284 Self::set_lock_unchecked(&staker, new_state);285 });286 });287 }288289 <T as Config>::WeightInfo::on_initialize(counter)290 }291292 fn on_runtime_upgrade() -> Weight {293 let mut consumed_weight = Weight::zero();294 let mut add_weight = |reads, writes, weight| {295 consumed_weight += T::DbWeight::get().reads_writes(reads, writes);296 consumed_weight += weight;297 };298299 if <IsMigrated<T>>::get() {300 add_weight(1, 0, Weight::zero());301 return consumed_weight;302 } else {303 add_weight(1, 1, Weight::zero());304 <IsMigrated<T>>::set(true);305 }306 <PendingUnstake<T>>::drain().for_each(|(_, v)| {307 add_weight(1, 1, Weight::zero());308 v.into_iter().for_each(|(staker, amount)| {309 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(310 &staker, amount,311 );312 add_weight(1, 1, Weight::zero());313 });314 });315316 consumed_weight317 }318319 #[cfg(feature = "try-runtime")]320 fn pre_upgrade() -> Result<Vec<u8>, &'static str> {321 use sp_std::collections::btree_map::BTreeMap;322 if <IsMigrated<T>>::get() {323 return Ok(Default::default());324 }325 // Staker -> (total amount of reserved balance, reserved by promotion);326 let mut pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =327 BTreeMap::new();328329 <PendingUnstake<T>>::iter().for_each(|(_, v)| {330 v.into_iter().for_each(|(staker, amount)| {331 if let Some((_, reserved_balance)) = pre_state.get_mut(&staker) {332 *reserved_balance += amount;333 } else {334 let total_reserve = <<T as Config>::Currency as ReservableCurrency<335 T::AccountId,336 >>::reserved_balance(&staker);337 pre_state.insert(staker, (total_reserve, amount));338 }339 })340 });341342 Ok(pre_state.encode())343 }344345 #[cfg(feature = "try-runtime")]346 fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {347 use sp_std::collections::btree_map::BTreeMap;348349 if <IsMigrated<T>>::get() {350 return Ok(());351 }352353 ensure!(354 <PendingUnstake<T>>::iter().collect::<Vec<_>>().len() == 0,355 "pendingUnstake storage isn't empty"356 );357358 let mut is_ok = true;359360 let pre_state: BTreeMap<T::AccountId, (BalanceOf<T>, BalanceOf<T>)> =361 Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;362 for (staker, (total_reserved, reserved_by_promo)) in pre_state.into_iter() {363 let new_state_reserve = <<T as Config>::Currency as ReservableCurrency<364 T::AccountId,365 >>::reserved_balance(&staker);366 if new_state_reserve != total_reserved - reserved_by_promo {367 is_ok = false;368 log::error!(369 "Incorrect reserved balance for {:?}. New balance: {:?}. Before runtime upgrade: total reserve - {:?}, reserved by promo - {:?}",370 staker, new_state_reserve, total_reserved, reserved_by_promo371 );372 }373 }374375 if is_ok {376 Ok(())377 } else {378 Err("Incorrect balance for some of stakers... See logs")379 }380 }381 }382383 #[pallet::call]384 impl<T: Config> Pallet<T>385 where386 T::BlockNumber: From<u32> + Into<u32>,387 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,388 {389 /// Sets an address as the the admin.390 ///391 /// # Permissions392 ///393 /// * Sudo394 ///395 /// # Arguments396 ///397 /// * `admin`: account of the new admin.398 #[pallet::call_index(0)]399 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]400 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {401 ensure_root(origin)?;402403 <Admin<T>>::set(Some(admin.as_sub().to_owned()));404405 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));406407 Ok(())408 }409410 /// Stakes the amount of native tokens.411 /// Sets `amount` to the locked state.412 /// The maximum number of stakes for a staker is 10.413 ///414 /// # Arguments415 ///416 /// * `amount`: in native tokens.417 #[pallet::call_index(1)]418 #[pallet::weight(<T as Config>::WeightInfo::stake())]419 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {420 let staker_id = ensure_signed(staker)?;421422 ensure!(423 StakesPerAccount::<T>::get(&staker_id) < 10,424 Error::<T>::NoPermission425 );426427 ensure!(428 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),429 ArithmeticError::Underflow430 );431 let config = <PalletConfiguration<T>>::get();432433 let balance =434 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);435436 // checks that we can lock `amount` on the `staker` account.437 ensure!(438 amount439 <= match Self::get_locked_balance(&staker_id) {440 Some(lock) => balance441 .checked_sub(&lock.amount)442 .ok_or(ArithmeticError::Underflow)?,443 None => balance,444 },445 ArithmeticError::Underflow446 );447448 Self::add_lock_balance(&staker_id, amount)?;449450 let block_number = T::RelayBlockNumberProvider::current_block_number();451452 // Calculation of the number of recalculation periods,453 // after how much the first interest calculation should be performed for the stake454 let recalculate_after_interval: T::BlockNumber =455 if block_number % config.recalculation_interval == 0u32.into() {456 1u32.into()457 } else {458 2u32.into()459 };460461 // Сalculation of the number of the relay block462 // in which it is necessary to accrue remuneration for the stake.463 let recalc_block = (block_number / config.recalculation_interval464 + recalculate_after_interval)465 * config.recalculation_interval;466467 <Staked<T>>::insert((&staker_id, block_number), {468 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));469 balance_and_recalc_block.0 = balance_and_recalc_block470 .0471 .checked_add(&amount)472 .ok_or(ArithmeticError::Overflow)?;473 balance_and_recalc_block.1 = recalc_block;474 balance_and_recalc_block475 });476477 <TotalStaked<T>>::set(478 <TotalStaked<T>>::get()479 .checked_add(&amount)480 .ok_or(ArithmeticError::Overflow)?,481 );482483 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);484485 Self::deposit_event(Event::Stake(staker_id, amount));486487 Ok(())488 }489490 /// Unstakes all stakes.491 /// Moves the sum of all stakes to the `reserved` state.492 /// After the end of `PendingInterval` this sum becomes completely493 /// free for further use.494 #[pallet::call_index(2)]495 #[pallet::weight(<T as Config>::WeightInfo::unstake())]496 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {497 let staker_id = ensure_signed(staker)?;498 let config = <PalletConfiguration<T>>::get();499500 // calculate block number where the sum would be free501 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;502503 let mut pendings = <PendingUnstake<T>>::get(block);504505 // checks that we can do unreserve stakes in the block506 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);507508 let mut total_stakes = 0u64;509510 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))511 .map(|(_, (amount, _))| {512 total_stakes += 1;513 amount514 })515 .sum();516517 if total_staked.is_zero() {518 return Ok(None::<Weight>.into()); // TO-DO519 }520521 pendings522 .try_push((staker_id.clone(), total_staked))523 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;524525 <PendingUnstake<T>>::insert(block, pendings);526527 TotalStaked::<T>::set(528 TotalStaked::<T>::get()529 .checked_sub(&total_staked)530 .ok_or(ArithmeticError::Underflow)?,531 );532533 StakesPerAccount::<T>::remove(&staker_id);534535 Self::deposit_event(Event::Unstake(staker_id, total_staked));536537 Ok(None::<Weight>.into())538 }539540 /// Sets the pallet to be the sponsor for the collection.541 ///542 /// # Permissions543 ///544 /// * Pallet admin545 ///546 /// # Arguments547 ///548 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`549 #[pallet::call_index(3)]550 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]551 pub fn sponsor_collection(552 admin: OriginFor<T>,553 collection_id: CollectionId,554 ) -> DispatchResult {555 let admin_id = ensure_signed(admin)?;556 ensure!(557 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,558 Error::<T>::NoPermission559 );560561 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)562 }563564 /// Removes the pallet as the sponsor for the collection.565 /// Returns [`NoPermission`][`Error::NoPermission`]566 /// if the pallet wasn't the sponsor.567 ///568 /// # Permissions569 ///570 /// * Pallet admin571 ///572 /// # Arguments573 ///574 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`575 #[pallet::call_index(4)]576 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]577 pub fn stop_sponsoring_collection(578 admin: OriginFor<T>,579 collection_id: CollectionId,580 ) -> DispatchResult {581 let admin_id = ensure_signed(admin)?;582583 ensure!(584 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,585 Error::<T>::NoPermission586 );587588 ensure!(589 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?590 == Self::account_id(),591 <Error<T>>::NoPermission592 );593 T::CollectionHandler::remove_collection_sponsor(collection_id)594 }595596 /// Sets the pallet to be the sponsor for the contract.597 ///598 /// # Permissions599 ///600 /// * Pallet admin601 ///602 /// # Arguments603 ///604 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`605 #[pallet::call_index(5)]606 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]607 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {608 let admin_id = ensure_signed(admin)?;609610 ensure!(611 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,612 Error::<T>::NoPermission613 );614615 T::ContractHandler::set_sponsor(616 T::CrossAccountId::from_sub(Self::account_id()),617 contract_id,618 )619 }620621 /// Removes the pallet as the sponsor for the contract.622 /// Returns [`NoPermission`][`Error::NoPermission`]623 /// if the pallet wasn't the sponsor.624 ///625 /// # Permissions626 ///627 /// * Pallet admin628 ///629 /// # Arguments630 ///631 /// * `contract_id`: the contract address that is sponsored by `pallet_id`632 #[pallet::call_index(6)]633 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]634 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {635 let admin_id = ensure_signed(admin)?;636637 ensure!(638 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,639 Error::<T>::NoPermission640 );641642 ensure!(643 T::ContractHandler::sponsor(contract_id)?644 .ok_or(<Error<T>>::SponsorNotSet)?645 .as_sub() == &Self::account_id(),646 <Error<T>>::NoPermission647 );648 T::ContractHandler::remove_contract_sponsor(contract_id)649 }650651 /// Recalculates interest for the specified number of stakers.652 /// If all stakers are not recalculated, the next call of the extrinsic653 /// will continue the recalculation, from those stakers for whom this654 /// was not perform in last call.655 ///656 /// # Permissions657 ///658 /// * Pallet admin659 ///660 /// # Arguments661 ///662 /// * `stakers_number`: the number of stakers for which recalculation will be performed663 #[pallet::call_index(7)]664 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]665 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {666 let admin_id = ensure_signed(admin)?;667668 ensure!(669 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,670 Error::<T>::NoPermission671 );672 let config = <PalletConfiguration<T>>::get();673674 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);675676 ensure!(677 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,678 Error::<T>::NoPermission679 );680681 // calculate the number of the current recalculation block,682 // this is necessary in order to understand which stakers we should calculate interest683 let current_recalc_block = Self::get_current_recalc_block(684 T::RelayBlockNumberProvider::current_block_number(),685 &config,686 );687688 // calculate the number of the next recalculation block,689 // this value is set for the stakers to whom the recalculation will be performed690 let next_recalc_block = current_recalc_block + config.recalculation_interval;691692 let mut storage_iterator = Self::get_next_calculated_key()693 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));694695 PreviousCalculatedRecord::<T>::set(None);696697 {698 // Address handled in the last payout loop iteration (below)699 let last_id = RefCell::new(None);700 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration701 let mut last_staked_calculated_block = Default::default();702 // Reward balance for the address in the iteration703 let income_acc = RefCell::new(BalanceOf::<T>::default());704 // Staked balance for the address in the iteration (before stake is recalculated)705 let amount_acc = RefCell::new(BalanceOf::<T>::default());706707 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout708 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout709 // loop switches to handling the next staker address:710 // 1. Transfer full reward amount to the payee711 // 2. Lock the reward in staking lock712 // 3. Update TotalStaked amount713 // 4. Issue StakingRecalculation event714 let flush_stake = || -> DispatchResult {715 if let Some(last_id) = &*last_id.borrow() {716 if !income_acc.borrow().is_zero() {717 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(718 &T::TreasuryAccountId::get(),719 last_id,720 *income_acc.borrow(),721 ExistenceRequirement::KeepAlive,722 )?;723724 Self::add_lock_balance(last_id, *income_acc.borrow())?;725 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {726 *staked = staked727 .checked_add(&*income_acc.borrow())728 .ok_or(ArithmeticError::Overflow)?;729 Ok(())730 })?;731732 Self::deposit_event(Event::StakingRecalculation(733 last_id.clone(),734 *amount_acc.borrow(),735 *income_acc.borrow(),736 ));737 }738739 *income_acc.borrow_mut() = BalanceOf::<T>::default();740 *amount_acc.borrow_mut() = BalanceOf::<T>::default();741 }742 Ok(())743 };744745 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation746 // iterations in one extrinsic call747 //748 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)749 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out750 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)751 while let Some((752 (current_id, staked_block),753 (amount, next_recalc_block_for_stake),754 )) = storage_iterator.next()755 {756 // last_id is not equal current_id when we switch to handling a new staker address757 // or just start handling the very first address. In the latter case last_id will be None and758 // flush_stake will do nothing759 if last_id.borrow().as_ref() != Some(¤t_id) {760 if stakers_number > 0 {761 flush_stake()?;762 *last_id.borrow_mut() = Some(current_id.clone());763 stakers_number -= 1;764 }765 // Break out if we reached the address limit766 else {767 if let Some(staker) = &*last_id.borrow() {768 // Save the last calculated record to pick up in the next extrinsic call769 PreviousCalculatedRecord::<T>::set(Some((770 staker.clone(),771 last_staked_calculated_block,772 )));773 }774 break;775 };776 };777778 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount779 if current_recalc_block >= next_recalc_block_for_stake {780 *amount_acc.borrow_mut() += amount;781 Self::recalculate_and_insert_stake(782 ¤t_id,783 staked_block,784 next_recalc_block,785 amount,786 ((current_recalc_block - next_recalc_block_for_stake)787 / config.recalculation_interval)788 .into() + 1,789 &mut *income_acc.borrow_mut(),790 );791 }792 last_staked_calculated_block = staked_block;793 }794 flush_stake()?;795 }796797 Ok(())798 }799 }800}801802impl<T: Config> Pallet<T> {803 /// The account address of the app promotion pot.804 ///805 /// This actually does computation. If you need to keep using it, then make sure you cache the806 /// value and only call this once.807 pub fn account_id() -> T::AccountId {808 T::PalletId::get().into_account_truncating()809 }810811 // /// Unlocks the balance that was locked by the pallet.812 // ///813 // /// - `staker`: staker account.814 // /// - `amount`: amount of unlocked funds.815 // fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {816 // let locked_balance = Self::get_locked_balance(staker)817 // .map(|l| l.amount)818 // .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;819820 // // It is understood that we cannot unlock more funds than were locked by staking.821 // // Therefore, if implemented correctly, this error should not occur.822 // Self::set_lock_unchecked(823 // staker,824 // locked_balance825 // .checked_sub(&amount)826 // .ok_or(ArithmeticError::Underflow)?,827 // );828 // Ok(())829 // }830831 /// Adds the balance to locked by the pallet.832 ///833 /// - `staker`: staker account.834 /// - `amount`: amount of added locked funds.835 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {836 Self::get_locked_balance(staker)837 .map_or(<BalanceOf<T>>::default(), |l| l.amount)838 .checked_add(&amount)839 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))840 .ok_or(ArithmeticError::Overflow.into())841 }842843 /// Sets the new state of a balance locked by the pallet.844 ///845 /// - `staker`: staker account.846 /// - `amount`: amount of locked funds.847 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {848 if amount.is_zero() {849 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(850 LOCK_IDENTIFIER,851 &staker,852 );853 } else {854 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(855 LOCK_IDENTIFIER,856 staker,857 amount,858 WithdrawReasons::all(),859 )860 }861 }862863 /// Returns the balance locked by the pallet for the staker.864 ///865 /// - `staker`: staker account.866 pub fn get_locked_balance(867 staker: impl EncodeLike<T::AccountId>,868 ) -> Option<BalanceLock<BalanceOf<T>>> {869 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)870 .into_iter()871 .find(|l| l.id == LOCK_IDENTIFIER)872 }873874 /// Returns the total staked balance for the staker.875 ///876 /// - `staker`: staker account.877 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {878 let staked = Staked::<T>::iter_prefix((staker,))879 .into_iter()880 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {881 acc + amount882 });883 if staked != <BalanceOf<T>>::default() {884 Some(staked)885 } else {886 None887 }888 }889890 /// Returns all relay block numbers when stake was made,891 /// the amount of the stake.892 ///893 /// - `staker`: staker account.894 pub fn total_staked_by_id_per_block(895 staker: impl EncodeLike<T::AccountId>,896 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {897 let mut staked = Staked::<T>::iter_prefix((staker,))898 .into_iter()899 .map(|(block, (amount, _))| (block, amount))900 .collect::<Vec<_>>();901 staked.sort_by_key(|(block, _)| *block);902 if !staked.is_empty() {903 Some(staked)904 } else {905 None906 }907 }908909 /// Returns the total staked balance for the staker.910 /// If `staker` is `None`, returns the total amount staked.911 /// - `staker`: staker account.912 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {913 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {914 Self::total_staked_by_id(s.as_sub())915 })916 }917918 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {919 // Self::get_locked_balance(staker.as_sub())920 // .map(|l| l.amount)921 // .unwrap_or_default()922 // }923924 /// Returns all relay block numbers when stake was made,925 /// the amount of the stake.926 ///927 /// - `staker`: staker account.928 pub fn cross_id_total_staked_per_block(929 staker: T::CrossAccountId,930 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {931 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()932 }933934 fn recalculate_and_insert_stake(935 staker: &T::AccountId,936 staked_block: T::BlockNumber,937 next_recalc_block: T::BlockNumber,938 base: BalanceOf<T>,939 iters: u32,940 income_acc: &mut BalanceOf<T>,941 ) {942 let income = Self::calculate_income(base, iters);943944 base.checked_add(&income).map(|res| {945 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));946 *income_acc += income;947 });948 }949950 fn calculate_income<I>(base: I, iters: u32) -> I951 where952 I: EncodeLike<BalanceOf<T>> + Balance,953 {954 let config = <PalletConfiguration<T>>::get();955 let mut income = base;956957 (0..iters).for_each(|_| income += config.interval_income * income);958959 income - base960 }961962 /// Get relay block number rounded down to multiples of config.recalculation_interval.963 /// We need it to reward stakers in integer parts of recalculation_interval964 fn get_current_recalc_block(965 current_relay_block: T::BlockNumber,966 config: &PalletConfiguration<T>,967 ) -> T::BlockNumber {968 (current_relay_block / config.recalculation_interval) * config.recalculation_interval969 }970971 fn get_next_calculated_key() -> Option<Vec<u8>> {972 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))973 }974}975976impl<T: Config> Pallet<T>977where978 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,979{980 /// Returns the amount reserved by the pending.981 /// If `staker` is `None`, returns the total pending.982 ///983 /// -`staker`: staker account.984 ///985 /// Since user funds are not transferred anywhere by staking, overflow protection is provided986 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,987 /// the staker must have more funds on his account than the maximum set for `Balance` type.988 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {989 staker.map_or(990 PendingUnstake::<T>::iter_values()991 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))992 .sum(),993 |s| {994 PendingUnstake::<T>::iter_values()995 .flatten()996 .filter_map(|(id, amount)| {997 if id == *s.as_sub() {998 Some(amount)999 } else {1000 None1001 }1002 })1003 .sum()1004 },1005 )1006 }10071008 /// Returns all parachain block numbers when unreserve is expected,1009 /// the amount of the unreserved funds.1010 ///1011 /// - `staker`: staker account.1012 pub fn cross_id_pending_unstake_per_block(1013 staker: T::CrossAccountId,1014 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1015 let mut unsorted_res = vec![];1016 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1017 pendings.into_iter().for_each(|(id, amount)| {1018 if id == *staker.as_sub() {1019 unsorted_res.push((block, amount));1020 };1021 })1022 });10231024 unsorted_res.sort_by_key(|(block, _)| *block);1025 unsorted_res1026 }1027}