difftreelog
Breaking: migration to `Fungible` traits in app-promotion pallet
in: master
Migration from `Currency` traits to `Fungible` ones in constraints for `Config::Currency` associated type.
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6125,7 +6125,7 @@
[[package]]
name = "pallet-app-promotion"
-version = "0.1.6"
+version = "0.2.0"
dependencies = [
"frame-benchmarking",
"frame-support",
pallets/app-promotion/CHANGELOG.mddiffbeforeafterboth--- a/pallets/app-promotion/CHANGELOG.md
+++ b/pallets/app-promotion/CHANGELOG.md
@@ -3,6 +3,13 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+## [0.2.0] - 2023-05-19
+
+### Changed
+
+- **Breaking:** migration from `Currency` traits to `Fungible` ones in constraints
+ for `Config::Currency` associated type.
+
## [0.1.6] - 2023-04-19
- ### Fixed
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.6'
+version = '0.2.0'
[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, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency, weights::Weight,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config:106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config107 {108 /// 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 pub struct Pallet<T>(_);156157 #[pallet::event]158 #[pallet::generate_deposit(pub(super) fn deposit_event)]159 pub enum Event<T: Config> {160 /// Staking recalculation was performed161 ///162 /// # Arguments163 /// * AccountId: account of the staker.164 /// * Balance : recalculation base165 /// * Balance : total income166 StakingRecalculation(167 /// An recalculated staker168 T::AccountId,169 /// Base on which interest is calculated170 BalanceOf<T>,171 /// Amount of accrued interest172 BalanceOf<T>,173 ),174175 /// Staking was performed176 ///177 /// # Arguments178 /// * AccountId: account of the staker179 /// * Balance : staking amount180 Stake(T::AccountId, BalanceOf<T>),181182 /// Unstaking was performed183 ///184 /// # Arguments185 /// * AccountId: account of the staker186 /// * Balance : unstaking amount187 Unstake(T::AccountId, BalanceOf<T>),188189 /// The admin was set190 ///191 /// # Arguments192 /// * AccountId: account address of the admin193 SetAdmin(T::AccountId),194 }195196 #[pallet::error]197 pub enum Error<T> {198 /// Error due to action requiring admin to be set.199 AdminNotSet,200 /// No permission to perform an action.201 NoPermission,202 /// Insufficient funds to perform an action.203 NotSufficientFunds,204 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.205 PendingForBlockOverflow,206 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.207 SponsorNotSet,208 /// Errors caused by incorrect actions with a locked balance.209 IncorrectLockedBalanceOperation,210 /// Errors caused by insufficient staked balance.211 InsufficientStakedBalance,212 }213214 /// Stores the total staked amount.215 #[pallet::storage]216 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;217218 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.219 #[pallet::storage]220 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;221222 /// Stores the amount of tokens staked by account in the blocknumber.223 ///224 /// * **Key1** - Staker account.225 /// * **Key2** - Relay block number when the stake was made.226 /// * **(Balance, BlockNumber)** - Balance of the stake.227 /// The number of the relay block in which we must perform the interest recalculation228 #[pallet::storage]229 pub type Staked<T: Config> = StorageNMap<230 Key = (231 Key<Blake2_128Concat, T::AccountId>,232 Key<Twox64Concat, T::BlockNumber>,233 ),234 Value = (BalanceOf<T>, T::BlockNumber),235 QueryKind = ValueQuery,236 >;237238 /// Stores number of stake records for an `Account`.239 ///240 /// * **Key** - Staker account.241 /// * **Value** - Amount of stakes.242 #[pallet::storage]243 pub type StakesPerAccount<T: Config> =244 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;245246 /// Pending unstake records for an `Account`.247 ///248 /// * **Key** - Staker account.249 /// * **Value** - Amount of stakes.250 #[pallet::storage]251 pub type PendingUnstake<T: Config> = StorageMap<252 _,253 Twox64Concat,254 T::BlockNumber,255 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,256 ValueQuery,257 >;258259 /// Stores a key for record for which the revenue recalculation was performed.260 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.261 #[pallet::storage]262 #[pallet::getter(fn get_next_calculated_record)]263 pub type PreviousCalculatedRecord<T: Config> =264 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;265266 #[pallet::hooks]267 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {268 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize269 /// implies the execution of a strictly limited number of relatively lightweight operations.270 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.271 fn on_initialize(current_block_number: T::BlockNumber) -> Weight272 where273 <T as frame_system::Config>::BlockNumber: From<u32>,274 {275 let block_pending = PendingUnstake::<T>::take(current_block_number);276 let counter = block_pending.len() as u32;277278 if !block_pending.is_empty() {279 block_pending.into_iter().for_each(|(staker, amount)| {280 Self::get_locked_balance(&staker).map(|b| {281 let new_state = b.amount.checked_sub(&amount).unwrap_or_default();282 Self::set_lock_unchecked(&staker, new_state);283 });284 });285 }286287 <T as Config>::WeightInfo::on_initialize(counter)288 }289 }290291 #[pallet::call]292 impl<T: Config> Pallet<T>293 where294 T::BlockNumber: From<u32> + Into<u32>,295 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,296 {297 /// Sets an address as the the admin.298 ///299 /// # Permissions300 ///301 /// * Sudo302 ///303 /// # Arguments304 ///305 /// * `admin`: account of the new admin.306 #[pallet::call_index(0)]307 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]308 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {309 ensure_root(origin)?;310311 <Admin<T>>::set(Some(admin.as_sub().to_owned()));312313 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));314315 Ok(())316 }317318 /// Stakes the amount of native tokens.319 /// Sets `amount` to the locked state.320 /// The maximum number of stakes for a staker is 10.321 ///322 /// # Arguments323 ///324 /// * `amount`: in native tokens.325 #[pallet::call_index(1)]326 #[pallet::weight(<T as Config>::WeightInfo::stake())]327 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {328 let staker_id = ensure_signed(staker)?;329330 ensure!(331 StakesPerAccount::<T>::get(&staker_id) < 10,332 Error::<T>::NoPermission333 );334335 ensure!(336 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),337 ArithmeticError::Underflow338 );339 let config = <PalletConfiguration<T>>::get();340341 let balance =342 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);343344 // checks that we can lock `amount` on the `staker` account.345 ensure!(346 amount347 <= match Self::get_locked_balance(&staker_id) {348 Some(lock) => balance349 .checked_sub(&lock.amount)350 .ok_or(ArithmeticError::Underflow)?,351 None => balance,352 },353 ArithmeticError::Underflow354 );355356 Self::add_lock_balance(&staker_id, amount)?;357358 let block_number = T::RelayBlockNumberProvider::current_block_number();359360 // Calculation of the number of recalculation periods,361 // after how much the first interest calculation should be performed for the stake362 let recalculate_after_interval: T::BlockNumber =363 if block_number % config.recalculation_interval == 0u32.into() {364 1u32.into()365 } else {366 2u32.into()367 };368369 // Сalculation of the number of the relay block370 // in which it is necessary to accrue remuneration for the stake.371 let recalc_block = (block_number / config.recalculation_interval372 + recalculate_after_interval)373 * config.recalculation_interval;374375 <Staked<T>>::insert((&staker_id, block_number), {376 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));377 balance_and_recalc_block.0 = balance_and_recalc_block378 .0379 .checked_add(&amount)380 .ok_or(ArithmeticError::Overflow)?;381 balance_and_recalc_block.1 = recalc_block;382 balance_and_recalc_block383 });384385 <TotalStaked<T>>::set(386 <TotalStaked<T>>::get()387 .checked_add(&amount)388 .ok_or(ArithmeticError::Overflow)?,389 );390391 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);392393 Self::deposit_event(Event::Stake(staker_id, amount));394395 Ok(())396 }397398 /// Unstakes all stakes.399 /// After the end of `PendingInterval` this sum becomes completely400 /// free for further use.401 #[pallet::call_index(2)]402 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]403 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {404 let staker_id = ensure_signed(staker)?;405406 Self::unstake_all_internal(staker_id)407 }408409 /// Unstakes the amount of balance for the staker.410 /// After the end of `PendingInterval` this sum becomes completely411 /// free for further use.412 ///413 /// # Arguments414 ///415 /// * `staker`: staker account.416 /// * `amount`: amount of unstaked funds.417 #[pallet::call_index(8)]418 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]419 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {420 let staker_id = ensure_signed(staker)?;421422 Self::unstake_partial_internal(staker_id, amount)423 }424425 /// Sets the pallet to be the sponsor for the collection.426 ///427 /// # Permissions428 ///429 /// * Pallet admin430 ///431 /// # Arguments432 ///433 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`434 #[pallet::call_index(3)]435 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]436 pub fn sponsor_collection(437 admin: OriginFor<T>,438 collection_id: CollectionId,439 ) -> DispatchResult {440 let admin_id = ensure_signed(admin)?;441 ensure!(442 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,443 Error::<T>::NoPermission444 );445446 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)447 }448449 /// Removes the pallet as the sponsor for the collection.450 /// Returns [`NoPermission`][`Error::NoPermission`]451 /// if the pallet wasn't the sponsor.452 ///453 /// # Permissions454 ///455 /// * Pallet admin456 ///457 /// # Arguments458 ///459 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`460 #[pallet::call_index(4)]461 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]462 pub fn stop_sponsoring_collection(463 admin: OriginFor<T>,464 collection_id: CollectionId,465 ) -> DispatchResult {466 let admin_id = ensure_signed(admin)?;467468 ensure!(469 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,470 Error::<T>::NoPermission471 );472473 ensure!(474 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?475 == Self::account_id(),476 <Error<T>>::NoPermission477 );478 T::CollectionHandler::remove_collection_sponsor(collection_id)479 }480481 /// Sets the pallet to be the sponsor for the contract.482 ///483 /// # Permissions484 ///485 /// * Pallet admin486 ///487 /// # Arguments488 ///489 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`490 #[pallet::call_index(5)]491 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]492 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {493 let admin_id = ensure_signed(admin)?;494495 ensure!(496 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,497 Error::<T>::NoPermission498 );499500 T::ContractHandler::set_sponsor(501 T::CrossAccountId::from_sub(Self::account_id()),502 contract_id,503 )504 }505506 /// Removes the pallet as the sponsor for the contract.507 /// Returns [`NoPermission`][`Error::NoPermission`]508 /// if the pallet wasn't the sponsor.509 ///510 /// # Permissions511 ///512 /// * Pallet admin513 ///514 /// # Arguments515 ///516 /// * `contract_id`: the contract address that is sponsored by `pallet_id`517 #[pallet::call_index(6)]518 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]519 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {520 let admin_id = ensure_signed(admin)?;521522 ensure!(523 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,524 Error::<T>::NoPermission525 );526527 ensure!(528 T::ContractHandler::sponsor(contract_id)?529 .ok_or(<Error<T>>::SponsorNotSet)?530 .as_sub() == &Self::account_id(),531 <Error<T>>::NoPermission532 );533 T::ContractHandler::remove_contract_sponsor(contract_id)534 }535536 /// Recalculates interest for the specified number of stakers.537 /// If all stakers are not recalculated, the next call of the extrinsic538 /// will continue the recalculation, from those stakers for whom this539 /// was not perform in last call.540 ///541 /// # Permissions542 ///543 /// * Pallet admin544 ///545 /// # Arguments546 ///547 /// * `stakers_number`: the number of stakers for which recalculation will be performed548 #[pallet::call_index(7)]549 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]550 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {551 let admin_id = ensure_signed(admin)?;552553 ensure!(554 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,555 Error::<T>::NoPermission556 );557 let config = <PalletConfiguration<T>>::get();558559 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);560561 ensure!(562 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,563 Error::<T>::NoPermission564 );565566 // calculate the number of the current recalculation block,567 // this is necessary in order to understand which stakers we should calculate interest568 let current_recalc_block = Self::get_current_recalc_block(569 T::RelayBlockNumberProvider::current_block_number(),570 &config,571 );572573 // calculate the number of the next recalculation block,574 // this value is set for the stakers to whom the recalculation will be performed575 let next_recalc_block = current_recalc_block + config.recalculation_interval;576577 let mut storage_iterator = Self::get_next_calculated_key()578 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));579580 PreviousCalculatedRecord::<T>::set(None);581582 {583 // Address handled in the last payout loop iteration (below)584 let last_id = RefCell::new(None);585 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration586 let mut last_staked_calculated_block = Default::default();587 // Reward balance for the address in the iteration588 let income_acc = RefCell::new(BalanceOf::<T>::default());589 // Staked balance for the address in the iteration (before stake is recalculated)590 let amount_acc = RefCell::new(BalanceOf::<T>::default());591592 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout593 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout594 // loop switches to handling the next staker address:595 // 1. Transfer full reward amount to the payee596 // 2. Lock the reward in staking lock597 // 3. Update TotalStaked amount598 // 4. Issue StakingRecalculation event599 let flush_stake = || -> DispatchResult {600 if let Some(last_id) = &*last_id.borrow() {601 if !income_acc.borrow().is_zero() {602 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(603 &T::TreasuryAccountId::get(),604 last_id,605 *income_acc.borrow(),606 ExistenceRequirement::KeepAlive,607 )?;608609 Self::add_lock_balance(last_id, *income_acc.borrow())?;610 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {611 *staked = staked612 .checked_add(&*income_acc.borrow())613 .ok_or(ArithmeticError::Overflow)?;614 Ok(())615 })?;616617 Self::deposit_event(Event::StakingRecalculation(618 last_id.clone(),619 *amount_acc.borrow(),620 *income_acc.borrow(),621 ));622 }623624 *income_acc.borrow_mut() = BalanceOf::<T>::default();625 *amount_acc.borrow_mut() = BalanceOf::<T>::default();626 }627 Ok(())628 };629630 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation631 // iterations in one extrinsic call632 //633 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)634 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out635 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)636 while let Some((637 (current_id, staked_block),638 (amount, next_recalc_block_for_stake),639 )) = storage_iterator.next()640 {641 // last_id is not equal current_id when we switch to handling a new staker address642 // or just start handling the very first address. In the latter case last_id will be None and643 // flush_stake will do nothing644 if last_id.borrow().as_ref() != Some(¤t_id) {645 if stakers_number > 0 {646 flush_stake()?;647 *last_id.borrow_mut() = Some(current_id.clone());648 stakers_number -= 1;649 }650 // Break out if we reached the address limit651 else {652 if let Some(staker) = &*last_id.borrow() {653 // Save the last calculated record to pick up in the next extrinsic call654 PreviousCalculatedRecord::<T>::set(Some((655 staker.clone(),656 last_staked_calculated_block,657 )));658 }659 break;660 };661 };662663 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount664 if current_recalc_block >= next_recalc_block_for_stake {665 *amount_acc.borrow_mut() += amount;666 Self::recalculate_and_insert_stake(667 ¤t_id,668 staked_block,669 next_recalc_block,670 amount,671 ((current_recalc_block - next_recalc_block_for_stake)672 / config.recalculation_interval)673 .into() + 1,674 &mut *income_acc.borrow_mut(),675 );676 }677 last_staked_calculated_block = staked_block;678 }679 flush_stake()?;680 }681682 Ok(())683 }684 }685}686687impl<T: Config> Pallet<T> {688 /// The account address of the app promotion pot.689 ///690 /// This actually does computation. If you need to keep using it, then make sure you cache the691 /// value and only call this once.692 pub fn account_id() -> T::AccountId {693 T::PalletId::get().into_account_truncating()694 }695696 /// Unstakes the balance for the staker.697 ///698 /// - `staker`: staker account.699 /// - `amount`: amount of unstaked funds.700 fn unstake_partial_internal(701 staker_id: T::AccountId,702 unstaked_balance: BalanceOf<T>,703 ) -> DispatchResult {704 if unstaked_balance == Default::default() {705 return Ok(());706 }707708 let config = <PalletConfiguration<T>>::get();709710 // calculate block number where the sum would be free711 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;712713 let mut pendings = <PendingUnstake<T>>::get(unpending_block);714715 // checks that we can do unstake in the block716 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);717718 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();719720 let total_staked = stakes721 .iter()722 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {723 acc + *balance724 });725726 ensure!(727 unstaked_balance <= total_staked,728 <Error<T>>::InsufficientStakedBalance729 );730731 <TotalStaked<T>>::set(732 <TotalStaked<T>>::get()733 .checked_sub(&unstaked_balance)734 .ok_or(ArithmeticError::Underflow)?,735 );736737 stakes.sort_by_key(|(block, _)| *block);738739 let mut acc_amount = unstaked_balance;740 let mut will_deleted_stakes_count = 0u8;741742 let changed_stakes = stakes743 .into_iter()744 .map_while(|(block, (balance_per_block, _))| {745 if acc_amount == <BalanceOf<T>>::default() {746 return None;747 }748 if acc_amount < balance_per_block {749 let res = (block, balance_per_block - acc_amount);750 acc_amount = <BalanceOf<T>>::default();751 return Some(res);752 } else {753 acc_amount -= balance_per_block;754 will_deleted_stakes_count += 1;755 return Some((block, <BalanceOf<T>>::default()));756 }757 })758 .collect::<Vec<_>>();759760 pendings761 .try_push((staker_id.clone(), unstaked_balance))762 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;763764 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {765 *stakes = stakes766 .checked_sub(will_deleted_stakes_count)767 .ok_or(ArithmeticError::Underflow)?;768 Ok(())769 })?;770771 changed_stakes772 .into_iter()773 .for_each(|(staked_block, current_stake_state)| {774 if current_stake_state == Default::default() {775 <Staked<T>>::remove((&staker_id, staked_block));776 } else {777 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {778 *old_stake_state = current_stake_state779 });780 }781 });782783 <PendingUnstake<T>>::insert(unpending_block, pendings);784785 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));786787 Ok(())788 }789790 /// Adds the balance to locked by the pallet.791 ///792 /// - `staker`: staker account.793 /// - `amount`: amount of added locked funds.794 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {795 Self::get_locked_balance(staker)796 .map_or(<BalanceOf<T>>::default(), |l| l.amount)797 .checked_add(&amount)798 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))799 .ok_or(ArithmeticError::Overflow.into())800 }801802 /// Sets the new state of a balance locked by the pallet.803 ///804 /// - `staker`: staker account.805 /// - `amount`: amount of locked funds.806 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {807 if amount.is_zero() {808 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(809 LOCK_IDENTIFIER,810 &staker,811 );812 } else {813 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(814 LOCK_IDENTIFIER,815 staker,816 amount,817 WithdrawReasons::all(),818 )819 }820 }821822 /// Returns the balance locked by the pallet for the staker.823 ///824 /// - `staker`: staker account.825 pub fn get_locked_balance(826 staker: impl EncodeLike<T::AccountId>,827 ) -> Option<BalanceLock<BalanceOf<T>>> {828 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)829 .into_iter()830 .find(|l| l.id == LOCK_IDENTIFIER)831 }832833 /// Returns the total staked balance for the staker.834 ///835 /// - `staker`: staker account.836 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {837 let staked = Staked::<T>::iter_prefix((staker,))838 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {839 acc + amount840 });841 if staked != <BalanceOf<T>>::default() {842 Some(staked)843 } else {844 None845 }846 }847848 /// Returns all relay block numbers when stake was made,849 /// the amount of the stake.850 ///851 /// - `staker`: staker account.852 pub fn total_staked_by_id_per_block(853 staker: impl EncodeLike<T::AccountId>,854 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {855 let mut staked = Staked::<T>::iter_prefix((staker,))856 .map(|(block, (amount, _))| (block, amount))857 .collect::<Vec<_>>();858 staked.sort_by_key(|(block, _)| *block);859 if !staked.is_empty() {860 Some(staked)861 } else {862 None863 }864 }865866 /// Returns the total staked balance for the staker.867 /// If `staker` is `None`, returns the total amount staked.868 /// - `staker`: staker account.869 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {870 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {871 Self::total_staked_by_id(s.as_sub())872 })873 }874875 /// Returns all relay block numbers when stake was made,876 /// the amount of the stake.877 ///878 /// - `staker`: staker account.879 pub fn cross_id_total_staked_per_block(880 staker: T::CrossAccountId,881 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {882 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()883 }884885 fn recalculate_and_insert_stake(886 staker: &T::AccountId,887 staked_block: T::BlockNumber,888 next_recalc_block: T::BlockNumber,889 base: BalanceOf<T>,890 iters: u32,891 income_acc: &mut BalanceOf<T>,892 ) {893 let income = Self::calculate_income(base, iters);894895 base.checked_add(&income).map(|res| {896 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));897 *income_acc += income;898 });899 }900901 fn calculate_income<I>(base: I, iters: u32) -> I902 where903 I: EncodeLike<BalanceOf<T>> + Balance,904 {905 let config = <PalletConfiguration<T>>::get();906 let mut income = base;907908 (0..iters).for_each(|_| income += config.interval_income * income);909910 income - base911 }912913 /// Get relay block number rounded down to multiples of config.recalculation_interval.914 /// We need it to reward stakers in integer parts of recalculation_interval915 fn get_current_recalc_block(916 current_relay_block: T::BlockNumber,917 config: &PalletConfiguration<T>,918 ) -> T::BlockNumber {919 (current_relay_block / config.recalculation_interval) * config.recalculation_interval920 }921922 fn get_next_calculated_key() -> Option<Vec<u8>> {923 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))924 }925}926927impl<T: Config> Pallet<T>928where929 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,930{931 /// Returns the amount reserved by the pending.932 /// If `staker` is `None`, returns the total pending.933 ///934 /// -`staker`: staker account.935 ///936 /// Since user funds are not transferred anywhere by staking, overflow protection is provided937 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,938 /// the staker must have more funds on his account than the maximum set for `Balance` type.939 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {940 staker.map_or(941 PendingUnstake::<T>::iter_values()942 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))943 .sum(),944 |s| {945 PendingUnstake::<T>::iter_values()946 .flatten()947 .filter_map(|(id, amount)| {948 if id == *s.as_sub() {949 Some(amount)950 } else {951 None952 }953 })954 .sum()955 },956 )957 }958959 /// Returns all parachain block numbers when unreserve is expected,960 /// the amount of the unreserved funds.961 ///962 /// - `staker`: staker account.963 pub fn cross_id_pending_unstake_per_block(964 staker: T::CrossAccountId,965 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {966 let mut unsorted_res = vec![];967 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {968 pendings.into_iter().for_each(|(id, amount)| {969 if id == *staker.as_sub() {970 unsorted_res.push((block, amount));971 };972 })973 });974975 unsorted_res.sort_by_key(|(block, _)| *block);976 unsorted_res977 }978979 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {980 let config = <PalletConfiguration<T>>::get();981982 // calculate block number where the sum would be free983 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;984985 let mut pendings = <PendingUnstake<T>>::get(block);986987 // checks that we can do unstake in the block988 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);989990 let mut total_stakes = 0u64;991992 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))993 .map(|(_, (amount, _))| {994 total_stakes += 1;995 amount996 })997 .sum();998999 if total_staked.is_zero() {1000 return Ok(());1001 }10021003 pendings1004 .try_push((staker_id.clone(), total_staked))1005 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;10061007 <PendingUnstake<T>>::insert(block, pendings);10081009 TotalStaked::<T>::set(1010 TotalStaked::<T>::get()1011 .checked_sub(&total_staked)1012 .ok_or(ArithmeticError::Underflow)?,1013 );10141015 StakesPerAccount::<T>::remove(&staker_id);10161017 Self::deposit_event(Event::Unstake(staker_id, total_staked));10181019 Ok(())1020 }1021}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 Get, LockableCurrency,74 tokens::Balance,75 fungible::{Inspect, InspectFreeze, Mutate, MutateFreeze},76 },77 ensure, BoundedVec,78};7980use weights::WeightInfo;8182pub use pallet::*;83use pallet_evm::account::CrossAccountId;84use sp_runtime::{85 Perbill,86 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},87 ArithmeticError,88};8990pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";9192const PENDING_LIMIT_PER_BLOCK: u32 = 3;9394type BalanceOf<T> =95 <<T as Config>::Currency as Inspect<<T as frame_system::Config>::AccountId>>::Balance;9697#[frame_support::pallet]98pub mod pallet {99 use super::*;100 use frame_support::{101 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId, weights::Weight,102 };103 use frame_system::pallet_prelude::*;104use sp_runtime::DispatchError;105106 #[pallet::config]107 pub trait Config:108 frame_system::Config + pallet_evm::Config + pallet_configuration::Config109 {110 /// Type to interact with the native token111 type Currency: MutateFreeze<Self::AccountId>112 + Mutate<Self::AccountId> 113 + ExtendedLockableCurrency<Self::AccountId, Balance = <<Self as Config>::Currency as Inspect<Self::AccountId>>::Balance>;114115 /// Type for interacting with collections116 type CollectionHandler: CollectionHandler<117 AccountId = Self::AccountId,118 CollectionId = CollectionId,119 >;120121 /// Type for interacting with conrtacts122 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;123124 /// `AccountId` for treasury125 type TreasuryAccountId: Get<Self::AccountId>;126127 /// The app's pallet id, used for deriving its sovereign account address.128 #[pallet::constant]129 type PalletId: Get<PalletId>;130131 /// Freeze identifier used by the pallet132 #[pallet::constant]133 type FreezeIdentifier: Get<<<Self as Config>::Currency as InspectFreeze<Self::AccountId>>::Id>;134135 /// In relay blocks.136 #[pallet::constant]137 type RecalculationInterval: Get<Self::BlockNumber>;138139 /// In parachain blocks.140 #[pallet::constant]141 type PendingInterval: Get<Self::BlockNumber>;142143 /// Rate of return for interval in blocks defined in `RecalculationInterval`.144 #[pallet::constant]145 type IntervalIncome: Get<Perbill>;146147 /// Decimals for the `Currency`.148 #[pallet::constant]149 type Nominal: Get<BalanceOf<Self>>;150151 /// Weight information for extrinsics in this pallet.152 type WeightInfo: WeightInfo;153154 // The relay block number provider155 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;156157 /// Events compatible with [`frame_system::Config::Event`].158 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;159 }160161 #[pallet::pallet]162 pub struct Pallet<T>(_);163164 #[pallet::event]165 #[pallet::generate_deposit(pub(super) fn deposit_event)]166 pub enum Event<T: Config> {167 /// Staking recalculation was performed168 ///169 /// # Arguments170 /// * AccountId: account of the staker.171 /// * Balance : recalculation base172 /// * Balance : total income173 StakingRecalculation(174 /// An recalculated staker175 T::AccountId,176 /// Base on which interest is calculated177 BalanceOf<T>,178 /// Amount of accrued interest179 BalanceOf<T>,180 ),181182 /// Staking was performed183 ///184 /// # Arguments185 /// * AccountId: account of the staker186 /// * Balance : staking amount187 Stake(T::AccountId, BalanceOf<T>),188189 /// Unstaking was performed190 ///191 /// # Arguments192 /// * AccountId: account of the staker193 /// * Balance : unstaking amount194 Unstake(T::AccountId, BalanceOf<T>),195196 /// The admin was set197 ///198 /// # Arguments199 /// * AccountId: account address of the admin200 SetAdmin(T::AccountId),201 }202203 #[pallet::error]204 pub enum Error<T> {205 /// Error due to action requiring admin to be set.206 AdminNotSet,207 /// No permission to perform an action.208 NoPermission,209 /// Insufficient funds to perform an action.210 NotSufficientFunds,211 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.212 PendingForBlockOverflow,213 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.214 SponsorNotSet,215 /// 216 IncorrectLockedBalanceOperation,217 /// Errors caused by insufficient staked balance.218 InsufficientStakedBalance,219 /// Errors caused by incorrect state of a staker in context of the pallet.220 InconsistencyState221 }222223 /// Stores the total staked amount.224 #[pallet::storage]225 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;226227 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.228 #[pallet::storage]229 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;230231 /// Stores the amount of tokens staked by account in the blocknumber.232 ///233 /// * **Key1** - Staker account.234 /// * **Key2** - Relay block number when the stake was made.235 /// * **(Balance, BlockNumber)** - Balance of the stake.236 /// The number of the relay block in which we must perform the interest recalculation237 #[pallet::storage]238 pub type Staked<T: Config> = StorageNMap<239 Key = (240 Key<Blake2_128Concat, T::AccountId>,241 Key<Twox64Concat, T::BlockNumber>,242 ),243 Value = (BalanceOf<T>, T::BlockNumber),244 QueryKind = ValueQuery,245 >;246247 /// Stores number of stake records for an `Account`.248 ///249 /// * **Key** - Staker account.250 /// * **Value** - Amount of stakes.251 #[pallet::storage]252 pub type StakesPerAccount<T: Config> =253 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;254255 /// Pending unstake records for an `Account`.256 ///257 /// * **Key** - Staker account.258 /// * **Value** - Amount of stakes.259 #[pallet::storage]260 pub type PendingUnstake<T: Config> = StorageMap<261 _,262 Twox64Concat,263 T::BlockNumber,264 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,265 ValueQuery,266 >;267268 /// Stores a key for record for which the revenue recalculation was performed.269 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.270 #[pallet::storage]271 #[pallet::getter(fn get_next_calculated_record)]272 pub type PreviousCalculatedRecord<T: Config> =273 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;274275 // #[pallet::storage]276 // pub(crate) type UpgradedToFreezes<T: Config> =277 // StorageValue<Value = bool, QueryKind = ValueQuery>;278279 #[pallet::hooks]280 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {281 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize282 /// implies the execution of a strictly limited number of relatively lightweight operations.283 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.284 fn on_initialize(current_block_number: T::BlockNumber) -> Weight285 where286 <T as frame_system::Config>::BlockNumber: From<u32>,287 {288 let block_pending = PendingUnstake::<T>::take(current_block_number);289 let counter = block_pending.len() as u32;290291 if !block_pending.is_empty() {292 block_pending.into_iter().for_each(|(staker, amount)| {293 Self::get_freezed_balance(&staker).map(|b| {294 let new_state = b.checked_sub(&amount).unwrap_or_default();295 Self::set_freeze_unchecked(&staker, new_state);296 });297 });298 }299300 <T as Config>::WeightInfo::on_initialize(counter)301 }302303 // fn on_runtime_upgrade() -> Weight {304 // use scale_info::prelude::collections::HashSet;305 // let mut consumed_weight = Weight::zero();306 // let mut add_weight = |reads, writes, weight| {307 // consumed_weight += T::DbWeight::get().reads_writes(reads, writes);308 // consumed_weight += weight;309 // };310311 // let mut stakes_unstakes = vec![];312313 // if <UpgradedToFreezes<T>>::get() {314 // add_weight(1, 0, Weight::zero());315 // return consumed_weight;316 // } else {317 // add_weight(1, 1, Weight::zero());318 // <UpgradedToFreezes<T>>::set(true);319 // }320 // <Staked<T>>::iter_keys().for_each(|(staker_id, _)| {321 // add_weight(1, 0, Weight::zero());322 // stakes_unstakes.push(staker_id);323 // });324325 // <PendingUnstake<T>>::iter().for_each(|(_, v)| {326 // add_weight(1, 0, Weight::zero());327 // v.into_iter().for_each(|(staker, _)| {328 // stakes_unstakes.push(staker);329 // });330 // });331332 // // filter duplicated id.333 // stakes_unstakes = stakes_unstakes334 // .into_iter()335 // .map(|key| key)336 // .collect::<HashSet<_>>()337 // .into_iter()338 // .collect();339340 // stakes_unstakes341 // .map(|a| (a, <Pallet<T>>::get_locked_balance(&a).amount))342 // .for_each(|(staker, amount)| {343 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(344 // LOCK_IDENTIFIER,345 // &staker,346 // );347 // <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(348 // &<T as Config>::FreezeIdentifier::get(),349 // &staker,350 // amount,351 // );352 // add_weight(1, 2, Weight::zero())353 // });354355 // consumed_weight356 // }357358 // #[cfg(feature = "try-runtime")]359 // fn pre_upgrade() -> Result<Vec<u8>, &'static str> {360 // use sp_std::collections::btree_map::BTreeMap;361 // if <UpgradedToFreezes<T>>::get() {362 // return Ok(Default::default());363 // }364 // // Staker -> (total (stakes and unstakes) locked by promotion);365 // let mut pre_state: BTreeMap<T::AccountId, BalanceOf<T>> = BTreeMap::new();366367 // <Staked<T>>::iter().for_each(|((staker, _), (amount, _))| {368 // if let Some(locked_balance) = pre_state.get_mut(&staker) {369 // *locked_balance += amount;370 // } else {371 // pre_state.insert(staker, amount);372 // }373 // });374375 // <PendingUnstake<T>>::iter().for_each(|(_, v)| {376 // v.into_iter().for_each(|(staker, amount)| {377 // if let Some(locked_balance) = pre_state.get_mut(&staker) {378 // *locked_balance += amount;379 // } else {380 // pre_state.insert(staker, amount);381 // }382 // })383 // });384385 // Ok(pre_state.encode())386 // }387388 // #[cfg(feature = "try-runtime")]389 // fn post_upgrade(pre_state: Vec<u8>) -> Result<(), &'static str> {390 // use sp_std::collections::btree_map::BTreeMap;391392 // if <UpgradedToFreezes<T>>::get() {393 // return Ok(());394 // }395396 // let mut is_ok = true;397398 // let pre_state: BTreeMap<T::AccountId, BalanceOf<T>> =399 // Decode::decode(&mut &pre_state[..]).map_err(|_| "failed to decode pre_state")?;400 // for (staker, freezed_by_promo) in pre_state.into_iter() {401 // let storage_freeze_state = <<T as Config>::Currency as InspectFreeze<402 // T::AccountId,403 // >>::balance_frozen(404 // &<T as Config>::FreezeIdentifier::get(), staker405 // );406 // if storage_freeze_state != freezed_by_promo {407 // is_ok = false;408 // log::error!(409 // "Incorrect freezed balance for {:?}. New balance: {:?}. Before runtime upgrade: locked by promo - {:?}",410 // staker, storage_freeze_state, freezed_by_promo411 // );412 // }413414 // if !<Pallet<T>>::get_locked_balance(&staker).amount.is_zero() {415 // is_ok = false;416 // log::error!(417 // "Incorrect(non-zero) locked by app promo balance for {:?}",418 // staker419 // );420 // }421 // }422423 // if is_ok {424 // Ok(())425 // } else {426 // Err("Incorrect balance for some of stakers... See logs")427 // }428 // }429 }430431 #[pallet::call]432 impl<T: Config> Pallet<T>433 where434 T::BlockNumber: From<u32> + Into<u32>,435 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum + From<u128>,436 {437 /// Sets an address as the the admin.438 ///439 /// # Permissions440 ///441 /// * Sudo442 ///443 /// # Arguments444 ///445 /// * `admin`: account of the new admin.446 #[pallet::call_index(0)]447 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]448 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {449 ensure_root(origin)?;450451 <Admin<T>>::set(Some(admin.as_sub().to_owned()));452453 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));454455 Ok(())456 }457458 /// Stakes the amount of native tokens.459 /// Sets `amount` to the locked state.460 /// The maximum number of stakes for a staker is 10.461 ///462 /// # Arguments463 ///464 /// * `amount`: in native tokens.465 #[pallet::call_index(1)]466 #[pallet::weight(<T as Config>::WeightInfo::stake())]467 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {468 let staker_id = ensure_signed(staker)?;469470 ensure!(471 StakesPerAccount::<T>::get(&staker_id) < 10,472 Error::<T>::NoPermission473 );474475 ensure!(476 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),477 ArithmeticError::Underflow478 );479 let config = <PalletConfiguration<T>>::get();480481 let balance = <<T as Config>::Currency as Inspect<T::AccountId>>::balance(&staker_id);482483 // checks that we can freeze `amount` on the `staker` account.484 ensure!(485 amount486 <= match Self::get_freezed_balance(&staker_id) {487 Some(freezed_by_pallet) => balance488 .checked_sub(&freezed_by_pallet)489 .ok_or(ArithmeticError::Underflow)?,490 None => balance,491 },492 ArithmeticError::Underflow493 );494495 Self::add_freeze_balance(&staker_id, amount)?;496497 let block_number = T::RelayBlockNumberProvider::current_block_number();498499 // Calculation of the number of recalculation periods,500 // after how much the first interest calculation should be performed for the stake501 let recalculate_after_interval: T::BlockNumber =502 if block_number % config.recalculation_interval == 0u32.into() {503 1u32.into()504 } else {505 2u32.into()506 };507508 // Сalculation of the number of the relay block509 // in which it is necessary to accrue remuneration for the stake.510 let recalc_block = (block_number / config.recalculation_interval511 + recalculate_after_interval)512 * config.recalculation_interval;513514 <Staked<T>>::insert((&staker_id, block_number), {515 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));516 balance_and_recalc_block.0 = balance_and_recalc_block517 .0518 .checked_add(&amount)519 .ok_or(ArithmeticError::Overflow)?;520 balance_and_recalc_block.1 = recalc_block;521 balance_and_recalc_block522 });523524 <TotalStaked<T>>::set(525 <TotalStaked<T>>::get()526 .checked_add(&amount)527 .ok_or(ArithmeticError::Overflow)?,528 );529530 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);531532 Self::deposit_event(Event::Stake(staker_id, amount));533534 Ok(())535 }536537 /// Unstakes all stakes.538 /// After the end of `PendingInterval` this sum becomes completely539 /// free for further use.540 #[pallet::call_index(2)]541 #[pallet::weight(<T as Config>::WeightInfo::unstake_all())]542 pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {543 let staker_id = ensure_signed(staker)?;544545 Self::unstake_all_internal(staker_id)546 }547548 /// Unstakes the amount of balance for the staker.549 /// After the end of `PendingInterval` this sum becomes completely550 /// free for further use.551 ///552 /// # Arguments553 ///554 /// * `staker`: staker account.555 /// * `amount`: amount of unstaked funds.556 #[pallet::call_index(8)]557 #[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]558 pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {559 let staker_id = ensure_signed(staker)?;560561 Self::unstake_partial_internal(staker_id, amount)562 }563564 /// Sets the pallet to be the sponsor for the collection.565 ///566 /// # Permissions567 ///568 /// * Pallet admin569 ///570 /// # Arguments571 ///572 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`573 #[pallet::call_index(3)]574 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]575 pub fn sponsor_collection(576 admin: OriginFor<T>,577 collection_id: CollectionId,578 ) -> DispatchResult {579 let admin_id = ensure_signed(admin)?;580 ensure!(581 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,582 Error::<T>::NoPermission583 );584585 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)586 }587588 /// Removes the pallet as the sponsor for the collection.589 /// Returns [`NoPermission`][`Error::NoPermission`]590 /// if the pallet wasn't the sponsor.591 ///592 /// # Permissions593 ///594 /// * Pallet admin595 ///596 /// # Arguments597 ///598 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`599 #[pallet::call_index(4)]600 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]601 pub fn stop_sponsoring_collection(602 admin: OriginFor<T>,603 collection_id: CollectionId,604 ) -> DispatchResult {605 let admin_id = ensure_signed(admin)?;606607 ensure!(608 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,609 Error::<T>::NoPermission610 );611612 ensure!(613 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?614 == Self::account_id(),615 <Error<T>>::NoPermission616 );617 T::CollectionHandler::remove_collection_sponsor(collection_id)618 }619620 /// Sets the pallet to be the sponsor for the contract.621 ///622 /// # Permissions623 ///624 /// * Pallet admin625 ///626 /// # Arguments627 ///628 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`629 #[pallet::call_index(5)]630 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]631 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {632 let admin_id = ensure_signed(admin)?;633634 ensure!(635 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,636 Error::<T>::NoPermission637 );638639 T::ContractHandler::set_sponsor(640 T::CrossAccountId::from_sub(Self::account_id()),641 contract_id,642 )643 }644645 /// Removes the pallet as the sponsor for the contract.646 /// Returns [`NoPermission`][`Error::NoPermission`]647 /// if the pallet wasn't the sponsor.648 ///649 /// # Permissions650 ///651 /// * Pallet admin652 ///653 /// # Arguments654 ///655 /// * `contract_id`: the contract address that is sponsored by `pallet_id`656 #[pallet::call_index(6)]657 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]658 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {659 let admin_id = ensure_signed(admin)?;660661 ensure!(662 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,663 Error::<T>::NoPermission664 );665666 ensure!(667 T::ContractHandler::sponsor(contract_id)?668 .ok_or(<Error<T>>::SponsorNotSet)?669 .as_sub() == &Self::account_id(),670 <Error<T>>::NoPermission671 );672 T::ContractHandler::remove_contract_sponsor(contract_id)673 }674675 /// Recalculates interest for the specified number of stakers.676 /// If all stakers are not recalculated, the next call of the extrinsic677 /// will continue the recalculation, from those stakers for whom this678 /// was not perform in last call.679 ///680 /// # Permissions681 ///682 /// * Pallet admin683 ///684 /// # Arguments685 ///686 /// * `stakers_number`: the number of stakers for which recalculation will be performed687 #[pallet::call_index(7)]688 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]689 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {690 let admin_id = ensure_signed(admin)?;691692 ensure!(693 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,694 Error::<T>::NoPermission695 );696 let config = <PalletConfiguration<T>>::get();697698 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);699700 ensure!(701 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,702 Error::<T>::NoPermission703 );704705 // calculate the number of the current recalculation block,706 // this is necessary in order to understand which stakers we should calculate interest707 let current_recalc_block = Self::get_current_recalc_block(708 T::RelayBlockNumberProvider::current_block_number(),709 &config,710 );711712 // calculate the number of the next recalculation block,713 // this value is set for the stakers to whom the recalculation will be performed714 let next_recalc_block = current_recalc_block + config.recalculation_interval;715716 let mut storage_iterator = Self::get_next_calculated_key()717 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));718719 PreviousCalculatedRecord::<T>::set(None);720721 {722 // Address handled in the last payout loop iteration (below)723 let last_id = RefCell::new(None);724 // Block number (as a part of the key) for which calculation was performed in the last payout loop iteration725 let mut last_staked_calculated_block = Default::default();726 // Reward balance for the address in the iteration727 let income_acc = RefCell::new(BalanceOf::<T>::default());728 // Staked balance for the address in the iteration (before stake is recalculated)729 let amount_acc = RefCell::new(BalanceOf::<T>::default());730731 // This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout732 // loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout733 // loop switches to handling the next staker address:734 // 1. Transfer full reward amount to the payee735 // 2. Lock the reward in staking lock736 // 3. Update TotalStaked amount737 // 4. Issue StakingRecalculation event738 let flush_stake = || -> DispatchResult {739 if let Some(last_id) = &*last_id.borrow() {740 if !income_acc.borrow().is_zero() {741 <<T as Config>::Currency as Mutate<T::AccountId>>::transfer(742 &T::TreasuryAccountId::get(),743 last_id,744 *income_acc.borrow(),745 frame_support::traits::tokens::Preservation::Protect,746 )?;747748 Self::add_freeze_balance(last_id, *income_acc.borrow())?;749 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {750 *staked = staked751 .checked_add(&*income_acc.borrow())752 .ok_or(ArithmeticError::Overflow)?;753 Ok(())754 })?;755756 Self::deposit_event(Event::StakingRecalculation(757 last_id.clone(),758 *amount_acc.borrow(),759 *income_acc.borrow(),760 ));761 }762763 *income_acc.borrow_mut() = BalanceOf::<T>::default();764 *amount_acc.borrow_mut() = BalanceOf::<T>::default();765 }766 Ok(())767 };768769 // Reward payment loop. Should loop for no more than config.max_stakers_per_calculation770 // iterations in one extrinsic call771 //772 // stakers_number - keeps the remaining number of iterations (staker addresses to handle)773 // next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out774 // income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)775 while let Some((776 (current_id, staked_block),777 (amount, next_recalc_block_for_stake),778 )) = storage_iterator.next()779 {780 // last_id is not equal current_id when we switch to handling a new staker address781 // or just start handling the very first address. In the latter case last_id will be None and782 // flush_stake will do nothing783 if last_id.borrow().as_ref() != Some(¤t_id) {784 if stakers_number > 0 {785 flush_stake()?;786 *last_id.borrow_mut() = Some(current_id.clone());787 stakers_number -= 1;788 }789 // Break out if we reached the address limit790 else {791 if let Some(staker) = &*last_id.borrow() {792 // Save the last calculated record to pick up in the next extrinsic call793 PreviousCalculatedRecord::<T>::set(Some((794 staker.clone(),795 last_staked_calculated_block,796 )));797 }798 break;799 };800 };801802 // Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount803 if current_recalc_block >= next_recalc_block_for_stake {804 *amount_acc.borrow_mut() += amount;805 Self::recalculate_and_insert_stake(806 ¤t_id,807 staked_block,808 next_recalc_block,809 amount,810 ((current_recalc_block - next_recalc_block_for_stake)811 / config.recalculation_interval)812 .into() + 1,813 &mut *income_acc.borrow_mut(),814 );815 }816 last_staked_calculated_block = staked_block;817 }818 flush_stake()?;819 }820821 Ok(())822 }823824 /// Migrates lock state into freeze one825 ///826 /// # Arguments827 ///828 /// * `origin`: Must be `Signed`.829 /// * `stakers`: Accounts to be upgraded.830 #[pallet::call_index(9)]831 #[pallet::weight(T::DbWeight::get().reads_writes(2, 2) * stakers.len() as u64)]832 pub fn upgrade_accounts(833 origin: OriginFor<T>,834 stakers: Vec<T::AccountId>,835 ) -> DispatchResult {836 ensure_signed(origin)?;837838 stakers.into_iter().try_for_each(|s| -> Result<_, DispatchError> {839 if let Some(lock) = Self::get_locked_balance(&s) {840 841 if let Some(_) = Self::get_freezed_balance(&s) {842 return Err(Error::<T>::InconsistencyState.into())843 }844 845 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(846 LOCK_IDENTIFIER,847 &s,848 );849850 Self::set_freeze_unchecked(&s, lock.amount);851 Ok(())852 } else {853 Ok(())854 }855 })?;856 857 Ok(())858 }859 }860}861862impl<T: Config> Pallet<T> {863 /// The account address of the app promotion pot.864 ///865 /// This actually does computation. If you need to keep using it, then make sure you cache the866 /// value and only call this once.867 pub fn account_id() -> T::AccountId {868 T::PalletId::get().into_account_truncating()869 }870871 /// Unstakes the balance for the staker.872 ///873 /// - `staker`: staker account.874 /// - `amount`: amount of unstaked funds.875 fn unstake_partial_internal(876 staker_id: T::AccountId,877 unstaked_balance: BalanceOf<T>,878 ) -> DispatchResult {879 if unstaked_balance == Default::default() {880 return Ok(());881 }882883 let config = <PalletConfiguration<T>>::get();884885 // calculate block number where the sum would be free886 let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;887888 let mut pendings = <PendingUnstake<T>>::get(unpending_block);889890 // checks that we can do unstake in the block891 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);892893 let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();894895 let total_staked = stakes896 .iter()897 .fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {898 acc + *balance899 });900901 ensure!(902 unstaked_balance <= total_staked,903 <Error<T>>::InsufficientStakedBalance904 );905906 <TotalStaked<T>>::set(907 <TotalStaked<T>>::get()908 .checked_sub(&unstaked_balance)909 .ok_or(ArithmeticError::Underflow)?,910 );911912 stakes.sort_by_key(|(block, _)| *block);913914 let mut acc_amount = unstaked_balance;915 let mut will_deleted_stakes_count = 0u8;916917 let changed_stakes = stakes918 .into_iter()919 .map_while(|(block, (balance_per_block, _))| {920 if acc_amount == <BalanceOf<T>>::default() {921 return None;922 }923 if acc_amount < balance_per_block {924 let res = (block, balance_per_block - acc_amount);925 acc_amount = <BalanceOf<T>>::default();926 return Some(res);927 } else {928 acc_amount -= balance_per_block;929 will_deleted_stakes_count += 1;930 return Some((block, <BalanceOf<T>>::default()));931 }932 })933 .collect::<Vec<_>>();934935 pendings936 .try_push((staker_id.clone(), unstaked_balance))937 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;938939 StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {940 *stakes = stakes941 .checked_sub(will_deleted_stakes_count)942 .ok_or(ArithmeticError::Underflow)?;943 Ok(())944 })?;945946 changed_stakes947 .into_iter()948 .for_each(|(staked_block, current_stake_state)| {949 if current_stake_state == Default::default() {950 <Staked<T>>::remove((&staker_id, staked_block));951 } else {952 <Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {953 *old_stake_state = current_stake_state954 });955 }956 });957958 <PendingUnstake<T>>::insert(unpending_block, pendings);959960 Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));961962 Ok(())963 }964965 /// Adds the balance to locked by the pallet.966 ///967 /// - `staker`: staker account.968 /// - `amount`: amount of added locked funds.969 // fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {970 // Self::get_locked_balance(staker)971 // .map_or(<BalanceOf<T>>::default(), |l| l.amount)972 // .checked_add(&amount)973 // .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))974 // .ok_or(ArithmeticError::Overflow.into())975 // }976977 /// Adds the balance to freezed by the pallet.978 ///979 /// - `staker`: staker account.980 /// - `amount`: amount of added freezed funds.981 fn add_freeze_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {982 Self::get_freezed_balance(staker)983 .unwrap_or_default()984 .checked_add(&amount)985 .map(|freeze| Self::set_freeze_unchecked(staker, freeze))986 .ok_or(ArithmeticError::Overflow.into())987 }988989 /// Sets the new state of a balance locked by the pallet.990 ///991 /// - `staker`: staker account.992 /// - `amount`: amount of locked funds.993 // fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {994 // if amount.is_zero() {995 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(996 // LOCK_IDENTIFIER,997 // &staker,998 // );999 // } else {1000 // <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(1001 // LOCK_IDENTIFIER,1002 // staker,1003 // amount,1004 // WithdrawReasons::all(),1005 // )1006 // }1007 // }10081009 /// Sets the new state of a balance freezed by the pallet.1010 ///1011 /// - `staker`: staker account.1012 /// - `amount`: amount of freezed funds.1013 fn set_freeze_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {1014 if amount.is_zero() {1015 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::thaw(1016 &T::FreezeIdentifier::get(),1017 &staker,1018 );1019 } else {1020 <<T as Config>::Currency as MutateFreeze<T::AccountId>>::set_freeze(1021 &T::FreezeIdentifier::get(),1022 staker,1023 amount,1024 );1025 }1026 }10271028 /// Returns the balance locked by the pallet for the staker.1029 ///1030 /// - `staker`: staker account.1031 pub fn get_locked_balance(1032 staker: impl EncodeLike<T::AccountId>,1033 ) -> Option<BalanceLock<BalanceOf<T>>> {1034 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)1035 .into_iter()1036 .find(|l| l.id == LOCK_IDENTIFIER)1037 }10381039 /// Returns the balance freezed by the pallet for the staker.1040 ///1041 /// - `staker`: staker account.1042 pub fn get_freezed_balance(staker: &T::AccountId) -> Option<BalanceOf<T>> {1043 let res = <<T as Config>::Currency as InspectFreeze<T::AccountId>>::balance_frozen(1044 &T::FreezeIdentifier::get(),1045 staker,1046 );10471048 if res == Zero::zero() {1049 None1050 } else {1051 Some(res)1052 }1053 }10541055 /// Returns the total staked balance for the staker.1056 ///1057 /// - `staker`: staker account.1058 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {1059 let staked = Staked::<T>::iter_prefix((staker,))1060 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {1061 acc + amount1062 });1063 if staked != <BalanceOf<T>>::default() {1064 Some(staked)1065 } else {1066 None1067 }1068 }10691070 /// Returns all relay block numbers when stake was made,1071 /// the amount of the stake.1072 ///1073 /// - `staker`: staker account.1074 pub fn total_staked_by_id_per_block(1075 staker: impl EncodeLike<T::AccountId>,1076 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {1077 let mut staked = Staked::<T>::iter_prefix((staker,))1078 .map(|(block, (amount, _))| (block, amount))1079 .collect::<Vec<_>>();1080 staked.sort_by_key(|(block, _)| *block);1081 if !staked.is_empty() {1082 Some(staked)1083 } else {1084 None1085 }1086 }10871088 /// Returns the total staked balance for the staker.1089 /// If `staker` is `None`, returns the total amount staked.1090 /// - `staker`: staker account.1091 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {1092 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {1093 Self::total_staked_by_id(s.as_sub())1094 })1095 }10961097 /// Returns all relay block numbers when stake was made,1098 /// the amount of the stake.1099 ///1100 /// - `staker`: staker account.1101 pub fn cross_id_total_staked_per_block(1102 staker: T::CrossAccountId,1103 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1104 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()1105 }11061107 fn recalculate_and_insert_stake(1108 staker: &T::AccountId,1109 staked_block: T::BlockNumber,1110 next_recalc_block: T::BlockNumber,1111 base: BalanceOf<T>,1112 iters: u32,1113 income_acc: &mut BalanceOf<T>,1114 ) {1115 let income = Self::calculate_income(base, iters);11161117 base.checked_add(&income).map(|res| {1118 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));1119 *income_acc += income;1120 });1121 }11221123 fn calculate_income<I>(base: I, iters: u32) -> I1124 where1125 I: EncodeLike<BalanceOf<T>> + Balance,1126 {1127 let config = <PalletConfiguration<T>>::get();1128 let mut income = base;11291130 (0..iters).for_each(|_| income += config.interval_income * income);11311132 income - base1133 }11341135 /// Get relay block number rounded down to multiples of config.recalculation_interval.1136 /// We need it to reward stakers in integer parts of recalculation_interval1137 fn get_current_recalc_block(1138 current_relay_block: T::BlockNumber,1139 config: &PalletConfiguration<T>,1140 ) -> T::BlockNumber {1141 (current_relay_block / config.recalculation_interval) * config.recalculation_interval1142 }11431144 fn get_next_calculated_key() -> Option<Vec<u8>> {1145 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))1146 }1147}11481149impl<T: Config> Pallet<T>1150where1151 <<T as Config>::Currency as Inspect<T::AccountId>>::Balance: Sum,1152{1153 /// Returns the amount reserved by the pending.1154 /// If `staker` is `None`, returns the total pending.1155 ///1156 /// -`staker`: staker account.1157 ///1158 /// Since user funds are not transferred anywhere by staking, overflow protection is provided1159 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,1160 /// the staker must have more funds on his account than the maximum set for `Balance` type.1161 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {1162 staker.map_or(1163 PendingUnstake::<T>::iter_values()1164 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))1165 .sum(),1166 |s| {1167 PendingUnstake::<T>::iter_values()1168 .flatten()1169 .filter_map(|(id, amount)| {1170 if id == *s.as_sub() {1171 Some(amount)1172 } else {1173 None1174 }1175 })1176 .sum()1177 },1178 )1179 }11801181 /// Returns all parachain block numbers when unreserve is expected,1182 /// the amount of the unreserved funds.1183 ///1184 /// - `staker`: staker account.1185 pub fn cross_id_pending_unstake_per_block(1186 staker: T::CrossAccountId,1187 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {1188 let mut unsorted_res = vec![];1189 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {1190 pendings.into_iter().for_each(|(id, amount)| {1191 if id == *staker.as_sub() {1192 unsorted_res.push((block, amount));1193 };1194 })1195 });11961197 unsorted_res.sort_by_key(|(block, _)| *block);1198 unsorted_res1199 }12001201 fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {1202 let config = <PalletConfiguration<T>>::get();12031204 // calculate block number where the sum would be free1205 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;12061207 let mut pendings = <PendingUnstake<T>>::get(block);12081209 // checks that we can do unstake in the block1210 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);12111212 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1213 .map(|(_, (amount, _))| amount)1214 .sum();12151216 if total_staked.is_zero() {1217 return Ok(());1218 }12191220 pendings1221 .try_push((staker_id.clone(), total_staked))1222 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;12231224 <PendingUnstake<T>>::insert(block, pendings);12251226 TotalStaked::<T>::set(1227 TotalStaked::<T>::get()1228 .checked_sub(&total_staked)1229 .ok_or(ArithmeticError::Underflow)?,1230 );12311232 StakesPerAccount::<T>::remove(&staker_id);12331234 Self::deposit_event(Event::Unstake(staker_id, total_staked));12351236 Ok(())1237 }1238}pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -420,7 +420,6 @@
#[frame_support::pallet]
pub mod pallet {
- use core::marker::PhantomData;
use super::*;
use dispatch::CollectionDispatch;
pallets/nonfungible/src/lib.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -151,7 +151,6 @@
use frame_support::{
Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,
};
- use frame_system::pallet_prelude::*;
use up_data_structs::{CollectionId, TokenId};
use super::weights::WeightInfo;