difftreelog
Merge pull request #579 from UniqueNetwork/doc/app-promotion
in: master
added `doc` to app promotion
16 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -5733,7 +5733,7 @@
[[package]]
name = "pallet-evm-contract-helpers"
-version = "0.2.0"
+version = "0.3.0"
dependencies = [
"ethereum",
"evm-coder",
@@ -12316,7 +12316,7 @@
[[package]]
name = "unique-rpc"
-version = "0.1.1"
+version = "0.1.2"
dependencies = [
"app-promotion-rpc",
"fc-db",
node/cli/CHANGELOG.mddiffbeforeafterboth--- a/node/cli/CHANGELOG.md
+++ b/node/cli/CHANGELOG.md
@@ -1,4 +1,10 @@
<!-- bureaucrate goes here -->
+
+## [v0.9.27] 2022-09-08
+
+### Added
+- Support RPC for `AppPromotion` pallet.
+
## [v0.9.27] 2022-08-16
### Other changes
node/rpc/CHANGELOG.mddiffbeforeafterboth--- a/node/rpc/CHANGELOG.md
+++ b/node/rpc/CHANGELOG.md
@@ -1,4 +1,9 @@
<!-- bureaucrate goes here -->
+## [v0.1.2] 2022-09-08
+
+### Added
+- Support RPC for `AppPromotion` pallet.
+
## [v0.1.1] 2022-08-16
### Other changes
node/rpc/Cargo.tomldiffbeforeafterboth--- a/node/rpc/Cargo.toml
+++ b/node/rpc/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "unique-rpc"
-version = "0.1.1"
+version = "0.1.2"
authors = ['Unique Network <support@uniquenetwork.io>']
license = 'GPLv3'
edition = "2021"
pallets/app-promotion/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/benchmarking.rs
+++ b/pallets/app-promotion/src/benchmarking.rs
@@ -112,6 +112,7 @@
let share = Perbill::from_rational(1u32, 20);
let _ = <T as Config>::Currency::make_free_balance_be(&caller, Perbill::from_rational(1u32, 2) * BalanceOf::<T>::max_value());
(0..10).map(|_| {
+ // used to change block number
<frame_system::Pallet<T>>::finalize();
PromototionPallet::<T>::stake(RawOrigin::Signed(caller.clone()).into(), share * <T as Config>::Currency::total_balance(&caller))
}).collect::<Result<Vec<_>, _>>()?;
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 promotion18//!19//! The app promotion pallet is designed to ... .20//!21//! ## Interface22//!23//! ### Dispatchable Functions24//!2526// #![recursion_limit = "1024"]27#![cfg_attr(not(feature = "std"), no_std)]2829#[cfg(feature = "runtime-benchmarks")]30mod benchmarking;3132pub mod types;33pub mod weights;3435use sp_std::{36 vec::{Vec},37 vec,38 iter::Sum,39 borrow::ToOwned,40 cell::RefCell,41};42use sp_core::H160;43use codec::EncodeLike;44use pallet_balances::BalanceLock;45pub use types::*;4647use up_data_structs::CollectionId;4849use frame_support::{50 dispatch::{DispatchResult},51 traits::{52 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,53 },54 ensure,55};5657use weights::WeightInfo;5859pub use pallet::*;60use pallet_evm::account::CrossAccountId;61use sp_runtime::{62 Perbill,63 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},64 ArithmeticError,65};6667pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";6869const PENDING_LIMIT_PER_BLOCK: u32 = 3;7071type BalanceOf<T> =72 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;7374#[frame_support::pallet]75pub mod pallet {76 use super::*;77 use frame_support::{78 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,79 traits::ReservableCurrency,80 };81 use frame_system::pallet_prelude::*;8283 #[pallet::config]84 pub trait Config: frame_system::Config + pallet_evm::account::Config {85 /// Type to interact with the native token86 type Currency: ExtendedLockableCurrency<Self::AccountId>87 + ReservableCurrency<Self::AccountId>;8889 /// Type for interacting with collections90 type CollectionHandler: CollectionHandler<91 AccountId = Self::AccountId,92 CollectionId = CollectionId,93 >;9495 /// Type for interacting with conrtacts96 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;9798 /// ID for treasury99 type TreasuryAccountId: Get<Self::AccountId>;100101 /// The app's pallet id, used for deriving its sovereign account ID.102 #[pallet::constant]103 type PalletId: Get<PalletId>;104105 /// In relay blocks.106 #[pallet::constant]107 type RecalculationInterval: Get<Self::BlockNumber>;108109 /// In parachain blocks.110 #[pallet::constant]111 type PendingInterval: Get<Self::BlockNumber>;112113 /// Rate of return for interval in blocks defined in `RecalculationInterval`.114 #[pallet::constant]115 type IntervalIncome: Get<Perbill>;116117 /// Decimals for the `Currency`.118 #[pallet::constant]119 type Nominal: Get<BalanceOf<Self>>;120121 /// Weight information for extrinsics in this pallet.122 type WeightInfo: WeightInfo;123124 // The relay block number provider125 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;126127 /// Events compatible with [`frame_system::Config::Event`].128 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;129 }130131 #[pallet::pallet]132 #[pallet::generate_store(pub(super) trait Store)]133 pub struct Pallet<T>(_);134135 #[pallet::event]136 #[pallet::generate_deposit(fn deposit_event)]137 pub enum Event<T: Config> {138 /// Staking recalculation was performed139 ///140 /// # Arguments141 /// * AccountId: ID of the staker.142 /// * Balance : recalculation base143 /// * Balance : total income144 StakingRecalculation(145 /// An recalculated staker146 T::AccountId,147 /// Base on which interest is calculated148 BalanceOf<T>,149 /// Amount of accrued interest150 BalanceOf<T>,151 ),152153 /// Staking was performed154 ///155 /// # Arguments156 /// * AccountId: ID of the staker157 /// * Balance : staking amount158 Stake(T::AccountId, BalanceOf<T>),159160 /// Unstaking was performed161 ///162 /// # Arguments163 /// * AccountId: ID of the staker164 /// * Balance : unstaking amount165 Unstake(T::AccountId, BalanceOf<T>),166167 /// The admin was set168 ///169 /// # Arguments170 /// * AccountId: ID of the admin171 SetAdmin(T::AccountId),172 }173174 #[pallet::error]175 pub enum Error<T> {176 /// Error due to action requiring admin to be set.177 AdminNotSet,178 /// No permission to perform an action.179 NoPermission,180 /// Insufficient funds to perform an action.181 NotSufficientFunds,182 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.183 PendingForBlockOverflow,184 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.185 SponsorNotSet,186 /// Errors caused by incorrect actions with a locked balance.187 IncorrectLockedBalanceOperation,188 }189190 #[pallet::storage]191 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;192193 #[pallet::storage]194 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;195196 /// Amount of tokens staked by account in the blocknumber.197 #[pallet::storage]198 pub type Staked<T: Config> = StorageNMap<199 Key = (200 Key<Blake2_128Concat, T::AccountId>,201 Key<Twox64Concat, T::BlockNumber>,202 ),203 Value = (BalanceOf<T>, T::BlockNumber),204 QueryKind = ValueQuery,205 >;206 /// Amount of stakes for an Account207 #[pallet::storage]208 pub type StakesPerAccount<T: Config> =209 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;210211 #[pallet::storage]212 pub type PendingUnstake<T: Config> = StorageMap<213 _,214 Twox64Concat,215 T::BlockNumber,216 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,217 ValueQuery,218 >;219220 /// Stores a key for record for which the next revenue recalculation would be performed.221 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.222 #[pallet::storage]223 #[pallet::getter(fn get_next_calculated_record)]224 pub type NextCalculatedRecord<T: Config> =225 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;226227 #[pallet::hooks]228 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {229 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize230 /// implies the execution of a strictly limited number of relatively lightweight operations.231 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.232 fn on_initialize(current_block_number: T::BlockNumber) -> Weight233 where234 <T as frame_system::Config>::BlockNumber: From<u32>,235 {236 let block_pending = PendingUnstake::<T>::take(current_block_number);237 let counter = block_pending.len() as u32;238239 if !block_pending.is_empty() {240 block_pending.into_iter().for_each(|(staker, amount)| {241 <T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);242 });243 }244245 T::WeightInfo::on_initialize(counter)246 }247 }248249 #[pallet::call]250 impl<T: Config> Pallet<T>251 where252 T::BlockNumber: From<u32> + Into<u32>,253 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,254 {255 #[pallet::weight(T::WeightInfo::set_admin_address())]256 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {257 ensure_root(origin)?;258259 <Admin<T>>::set(Some(admin.as_sub().to_owned()));260261 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));262263 Ok(())264 }265266 #[pallet::weight(T::WeightInfo::stake())]267 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {268 let staker_id = ensure_signed(staker)?;269270 ensure!(271 StakesPerAccount::<T>::get(&staker_id) < 10,272 Error::<T>::NoPermission273 );274275 ensure!(276 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),277 ArithmeticError::Underflow278 );279280 let balance =281 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);282283 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(284 &staker_id,285 amount,286 WithdrawReasons::all(),287 balance288 .checked_sub(&amount)289 .ok_or(ArithmeticError::Underflow)?,290 )?;291292 Self::add_lock_balance(&staker_id, amount)?;293294 let block_number = T::RelayBlockNumberProvider::current_block_number();295296 let recalculate_after_interval: T::BlockNumber =297 if block_number % T::RecalculationInterval::get() == 0u32.into() {298 1u32.into()299 } else {300 2u32.into()301 };302303 let recalc_block = (block_number / T::RecalculationInterval::get()304 + recalculate_after_interval)305 * T::RecalculationInterval::get();306307 <Staked<T>>::insert((&staker_id, block_number), {308 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));309 balance_and_recalc_block.0 = balance_and_recalc_block310 .0311 .checked_add(&amount)312 .ok_or(ArithmeticError::Overflow)?;313 balance_and_recalc_block.1 = recalc_block;314 balance_and_recalc_block315 });316317 <TotalStaked<T>>::set(318 <TotalStaked<T>>::get()319 .checked_add(&amount)320 .ok_or(ArithmeticError::Overflow)?,321 );322323 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);324325 Self::deposit_event(Event::Stake(staker_id, amount));326327 Ok(())328 }329330 #[pallet::weight(T::WeightInfo::unstake())]331 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {332 let staker_id = ensure_signed(staker)?;333 let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();334 let mut pendings = <PendingUnstake<T>>::get(block);335336 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);337338 let mut total_stakes = 0u64;339340 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))341 .map(|(_, (amount, _))| {342 total_stakes += 1;343 amount344 })345 .sum();346347 if total_staked.is_zero() {348 return Ok(None.into()); // TO-DO349 }350351 pendings352 .try_push((staker_id.clone(), total_staked))353 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;354355 <PendingUnstake<T>>::insert(block, pendings);356357 Self::unlock_balance(&staker_id, total_staked)?;358359 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;360361 TotalStaked::<T>::set(362 TotalStaked::<T>::get()363 .checked_sub(&total_staked)364 .ok_or(ArithmeticError::Underflow)?,365 );366367 StakesPerAccount::<T>::remove(&staker_id);368369 Self::deposit_event(Event::Unstake(staker_id, total_staked));370371 Ok(None.into())372 }373374 #[pallet::weight(T::WeightInfo::sponsor_collection())]375 pub fn sponsor_collection(376 admin: OriginFor<T>,377 collection_id: CollectionId,378 ) -> DispatchResult {379 let admin_id = ensure_signed(admin)?;380 ensure!(381 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,382 Error::<T>::NoPermission383 );384385 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)386 }387 #[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]388 pub fn stop_sponsoring_collection(389 admin: OriginFor<T>,390 collection_id: CollectionId,391 ) -> DispatchResult {392 let admin_id = ensure_signed(admin)?;393394 ensure!(395 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,396 Error::<T>::NoPermission397 );398399 ensure!(400 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?401 == Self::account_id(),402 <Error<T>>::NoPermission403 );404 T::CollectionHandler::remove_collection_sponsor(collection_id)405 }406407 #[pallet::weight(T::WeightInfo::sponsor_contract())]408 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {409 let admin_id = ensure_signed(admin)?;410411 ensure!(412 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,413 Error::<T>::NoPermission414 );415416 T::ContractHandler::set_sponsor(417 T::CrossAccountId::from_sub(Self::account_id()),418 contract_id,419 )420 }421422 #[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]423 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {424 let admin_id = ensure_signed(admin)?;425426 ensure!(427 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,428 Error::<T>::NoPermission429 );430431 ensure!(432 T::ContractHandler::sponsor(contract_id)?433 .ok_or(<Error<T>>::SponsorNotSet)?434 .as_sub() == &Self::account_id(),435 <Error<T>>::NoPermission436 );437 T::ContractHandler::remove_contract_sponsor(contract_id)438 }439440 #[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]441 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {442 let admin_id = ensure_signed(admin)?;443444 ensure!(445 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,446 Error::<T>::NoPermission447 );448449 let current_recalc_block =450 Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());451 let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();452453 let mut storage_iterator = Self::get_next_calculated_key()454 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));455456 NextCalculatedRecord::<T>::set(None);457458 // {459 // let mut stakers_number = stakers_number.unwrap_or(20);460 // let mut last_id = admin_id;461 // let mut income_acc = BalanceOf::<T>::default();462 // let mut amount_acc = BalanceOf::<T>::default();463464 // while let Some((465 // (current_id, staked_block),466 // (amount, next_recalc_block_for_stake),467 // )) = storage_iterator.next()468 // {469 // if last_id != current_id {470 // if income_acc != BalanceOf::<T>::default() {471 // <T::Currency as Currency<T::AccountId>>::transfer(472 // &T::TreasuryAccountId::get(),473 // &last_id,474 // income_acc,475 // ExistenceRequirement::KeepAlive,476 // )477 // .and_then(|_| Self::add_lock_balance(&last_id, income_acc))?;478479 // Self::deposit_event(Event::StakingRecalculation(480 // last_id, amount, income_acc,481 // ));482 // }483484 // if stakers_number == 0 {485 // NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));486 // break;487 // }488 // stakers_number -= 1;489 // income_acc = BalanceOf::<T>::default();490 // last_id = current_id;491 // };492 // if current_recalc_block >= next_recalc_block_for_stake {493 // Self::recalculate_and_insert_stake(494 // &last_id,495 // staked_block,496 // next_recalc_block,497 // amount,498 // ((current_recalc_block - next_recalc_block_for_stake)499 // / T::RecalculationInterval::get())500 // .into() + 1,501 // &mut income_acc,502 // );503 // }504 // }505 // }506507 {508 let mut stakers_number = stakers_number.unwrap_or(20);509 let last_id = RefCell::new(None);510 let income_acc = RefCell::new(BalanceOf::<T>::default());511 let amount_acc = RefCell::new(BalanceOf::<T>::default());512513 let flush_stake = || -> DispatchResult {514 if let Some(last_id) = &*last_id.borrow() {515 if !income_acc.borrow().is_zero() {516 <T::Currency as Currency<T::AccountId>>::transfer(517 &T::TreasuryAccountId::get(),518 last_id,519 *income_acc.borrow(),520 ExistenceRequirement::KeepAlive,521 )522 .and_then(|_| {523 Self::add_lock_balance(last_id, *income_acc.borrow())?;524 <TotalStaked<T>>::try_mutate(|staked| {525 staked526 .checked_add(&*income_acc.borrow())527 .ok_or(ArithmeticError::Overflow.into())528 })529 })?;530531 Self::deposit_event(Event::StakingRecalculation(532 last_id.clone(),533 *amount_acc.borrow(),534 *income_acc.borrow(),535 ));536 }537538 *income_acc.borrow_mut() = BalanceOf::<T>::default();539 *amount_acc.borrow_mut() = BalanceOf::<T>::default();540 }541 Ok(())542 };543544 while let Some((545 (current_id, staked_block),546 (amount, next_recalc_block_for_stake),547 )) = storage_iterator.next()548 {549 if stakers_number == 0 {550 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));551 break;552 }553 if last_id.borrow().as_ref() != Some(¤t_id) {554 flush_stake()?;555 *last_id.borrow_mut() = Some(current_id.clone());556 stakers_number -= 1;557 };558 if current_recalc_block >= next_recalc_block_for_stake {559 *amount_acc.borrow_mut() += amount;560 Self::recalculate_and_insert_stake(561 ¤t_id,562 staked_block,563 next_recalc_block,564 amount,565 ((current_recalc_block - next_recalc_block_for_stake)566 / T::RecalculationInterval::get())567 .into() + 1,568 &mut *income_acc.borrow_mut(),569 );570 }571 }572 flush_stake()?;573 }574575 Ok(())576 }577 }578}579580impl<T: Config> Pallet<T> {581 pub fn account_id() -> T::AccountId {582 T::PalletId::get().into_account_truncating()583 }584585 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {586 let locked_balance = Self::get_locked_balance(staker)587 .map(|l| l.amount)588 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;589590 // It is understood that we cannot unlock more funds than were locked by staking.591 // Therefore, if implemented correctly, this error should not occur.592 Self::set_lock_unchecked(593 staker,594 locked_balance595 .checked_sub(&amount)596 .ok_or(ArithmeticError::Underflow)?,597 );598 Ok(())599 }600601 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {602 Self::get_locked_balance(staker)603 .map_or(<BalanceOf<T>>::default(), |l| l.amount)604 .checked_add(&amount)605 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))606 .ok_or(ArithmeticError::Overflow.into())607 }608609 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {610 if amount.is_zero() {611 <T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);612 } else {613 <T::Currency as LockableCurrency<T::AccountId>>::set_lock(614 LOCK_IDENTIFIER,615 staker,616 amount,617 WithdrawReasons::all(),618 )619 }620 }621622 pub fn get_locked_balance(623 staker: impl EncodeLike<T::AccountId>,624 ) -> Option<BalanceLock<BalanceOf<T>>> {625 <T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)626 .into_iter()627 .find(|l| l.id == LOCK_IDENTIFIER)628 }629630 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {631 let staked = Staked::<T>::iter_prefix((staker,))632 .into_iter()633 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {634 acc + amount635 });636 if staked != <BalanceOf<T>>::default() {637 Some(staked)638 } else {639 None640 }641 }642643 pub fn total_staked_by_id_per_block(644 staker: impl EncodeLike<T::AccountId>,645 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {646 let mut staked = Staked::<T>::iter_prefix((staker,))647 .into_iter()648 .map(|(block, (amount, _))| (block, amount))649 .collect::<Vec<_>>();650 staked.sort_by_key(|(block, _)| *block);651 if !staked.is_empty() {652 Some(staked)653 } else {654 None655 }656 }657658 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {659 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {660 Self::total_staked_by_id(s.as_sub())661 })662 }663664 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {665 // Self::get_locked_balance(staker.as_sub())666 // .map(|l| l.amount)667 // .unwrap_or_default()668 // }669670 pub fn cross_id_total_staked_per_block(671 staker: T::CrossAccountId,672 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {673 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()674 }675676 fn recalculate_and_insert_stake(677 staker: &T::AccountId,678 staked_block: T::BlockNumber,679 next_recalc_block: T::BlockNumber,680 base: BalanceOf<T>,681 iters: u32,682 income_acc: &mut BalanceOf<T>,683 ) {684 let income = Self::calculate_income(base, iters);685686 base.checked_add(&income).map(|res| {687 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));688 *income_acc += income;689 });690 }691692 fn calculate_income<I>(base: I, iters: u32) -> I693 where694 I: EncodeLike<BalanceOf<T>> + Balance,695 {696 let mut income = base;697698 (0..iters).for_each(|_| income += T::IntervalIncome::get() * income);699700 income - base701 }702703 fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {704 (current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()705 }706707 // fn get_next_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {708 // Self::get_current_recalc_block(current_relay_block) + T::RecalculationInterval::get()709 // }710711 fn get_next_calculated_key() -> Option<Vec<u8>> {712 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))713 }714}715716impl<T: Config> Pallet<T>717where718 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,719{720 /// Since user funds are not transferred anywhere by staking, overflow protection is provided721 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,722 /// the staker must have more funds on his account than the maximum set for `Balance` type.723 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {724 staker.map_or(725 PendingUnstake::<T>::iter_values()726 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))727 .sum(),728 |s| {729 PendingUnstake::<T>::iter_values()730 .flatten()731 .filter_map(|(id, amount)| {732 if id == *s.as_sub() {733 Some(amount)734 } else {735 None736 }737 })738 .sum()739 },740 )741 }742743 pub fn cross_id_pending_unstake_per_block(744 staker: T::CrossAccountId,745 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {746 let mut unsorted_res = vec![];747 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {748 pendings.into_iter().for_each(|(id, amount)| {749 if id == *staker.as_sub() {750 unsorted_res.push((block, amount));751 };752 })753 });754755 unsorted_res.sort_by_key(|(block, _)| *block);756 unsorted_res757 }758}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//! 31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config: frame_system::Config + pallet_evm::account::Config {106 /// Type to interact with the native token107 type Currency: ExtendedLockableCurrency<Self::AccountId>108 + ReservableCurrency<Self::AccountId>;109110 /// Type for interacting with collections111 type CollectionHandler: CollectionHandler<112 AccountId = Self::AccountId,113 CollectionId = CollectionId,114 >;115116 /// Type for interacting with conrtacts117 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;118119 /// `AccountId` for treasury120 type TreasuryAccountId: Get<Self::AccountId>;121122 /// The app's pallet id, used for deriving its sovereign account address.123 #[pallet::constant]124 type PalletId: Get<PalletId>;125126 /// In relay blocks.127 #[pallet::constant]128 type RecalculationInterval: Get<Self::BlockNumber>;129130 /// In parachain blocks.131 #[pallet::constant]132 type PendingInterval: Get<Self::BlockNumber>;133134 /// Rate of return for interval in blocks defined in `RecalculationInterval`.135 #[pallet::constant]136 type IntervalIncome: Get<Perbill>;137138 /// Decimals for the `Currency`.139 #[pallet::constant]140 type Nominal: Get<BalanceOf<Self>>;141142 /// Weight information for extrinsics in this pallet.143 type WeightInfo: WeightInfo;144145 // The relay block number provider146 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;147148 /// Events compatible with [`frame_system::Config::Event`].149 type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;150 }151152 #[pallet::pallet]153 #[pallet::generate_store(pub(super) trait Store)]154 pub struct Pallet<T>(_);155156 #[pallet::event]157 #[pallet::generate_deposit(fn deposit_event)]158 pub enum Event<T: Config> {159 /// Staking recalculation was performed160 ///161 /// # Arguments162 /// * AccountId: account of the staker.163 /// * Balance : recalculation base164 /// * Balance : total income165 StakingRecalculation(166 /// An recalculated staker167 T::AccountId,168 /// Base on which interest is calculated169 BalanceOf<T>,170 /// Amount of accrued interest171 BalanceOf<T>,172 ),173174 /// Staking was performed175 ///176 /// # Arguments177 /// * AccountId: account of the staker178 /// * Balance : staking amount179 Stake(T::AccountId, BalanceOf<T>),180181 /// Unstaking was performed182 ///183 /// # Arguments184 /// * AccountId: account of the staker185 /// * Balance : unstaking amount186 Unstake(T::AccountId, BalanceOf<T>),187188 /// The admin was set189 ///190 /// # Arguments191 /// * AccountId: account address of the admin192 SetAdmin(T::AccountId),193 }194195 #[pallet::error]196 pub enum Error<T> {197 /// Error due to action requiring admin to be set.198 AdminNotSet,199 /// No permission to perform an action.200 NoPermission,201 /// Insufficient funds to perform an action.202 NotSufficientFunds,203 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.204 PendingForBlockOverflow,205 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.206 SponsorNotSet,207 /// Errors caused by incorrect actions with a locked balance.208 IncorrectLockedBalanceOperation,209 }210211 /// Stores the total staked amount.212 #[pallet::storage]213 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;214215 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.216 #[pallet::storage]217 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;218219 /// Stores the amount of tokens staked by account in the blocknumber.220 ///221 /// * **Key1** - Staker account.222 /// * **Key2** - Relay block number when the stake was made.223 /// * **(Balance, BlockNumber)** - Balance of the stake.224 /// The number of the relay block in which we must perform the interest recalculation225 #[pallet::storage]226 pub type Staked<T: Config> = StorageNMap<227 Key = (228 Key<Blake2_128Concat, T::AccountId>,229 Key<Twox64Concat, T::BlockNumber>,230 ),231 Value = (BalanceOf<T>, T::BlockNumber),232 QueryKind = ValueQuery,233 >;234235 /// Stores amount of stakes for an `Account`.236 ///237 /// * **Key** - Staker account.238 /// * **Value** - Amount of stakes.239 #[pallet::storage]240 pub type StakesPerAccount<T: Config> =241 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;242243 /// Stores amount of stakes for an `Account`.244 ///245 /// * **Key** - Staker account.246 /// * **Value** - Amount of stakes.247 #[pallet::storage]248 pub type PendingUnstake<T: Config> = StorageMap<249 _,250 Twox64Concat,251 T::BlockNumber,252 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,253 ValueQuery,254 >;255256 /// Stores a key for record for which the next revenue recalculation would be performed.257 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.258 #[pallet::storage]259 #[pallet::getter(fn get_next_calculated_record)]260 pub type NextCalculatedRecord<T: Config> =261 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;262263 #[pallet::hooks]264 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {265 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize266 /// implies the execution of a strictly limited number of relatively lightweight operations.267 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.268 fn on_initialize(current_block_number: T::BlockNumber) -> Weight269 where270 <T as frame_system::Config>::BlockNumber: From<u32>,271 {272 let block_pending = PendingUnstake::<T>::take(current_block_number);273 let counter = block_pending.len() as u32;274275 if !block_pending.is_empty() {276 block_pending.into_iter().for_each(|(staker, amount)| {277 <T::Currency as ReservableCurrency<T::AccountId>>::unreserve(&staker, amount);278 });279 }280281 T::WeightInfo::on_initialize(counter)282 }283 }284285 #[pallet::call]286 impl<T: Config> Pallet<T>287 where288 T::BlockNumber: From<u32> + Into<u32>,289 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,290 {291 /// Sets an address as the the admin.292 ///293 /// # Permissions294 ///295 /// * Sudo296 ///297 /// # Arguments298 ///299 /// * `admin`: account of the new admin.300 #[pallet::weight(T::WeightInfo::set_admin_address())]301 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {302 ensure_root(origin)?;303304 <Admin<T>>::set(Some(admin.as_sub().to_owned()));305306 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));307308 Ok(())309 }310311 /// Stakes the amount of native tokens.312 /// Sets `amount` to the locked state.313 /// The maximum number of stakes for a staker is 10.314 ///315 /// # Arguments316 ///317 /// * `amount`: in native tokens.318 #[pallet::weight(T::WeightInfo::stake())]319 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {320 let staker_id = ensure_signed(staker)?;321322 ensure!(323 StakesPerAccount::<T>::get(&staker_id) < 10,324 Error::<T>::NoPermission325 );326327 ensure!(328 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),329 ArithmeticError::Underflow330 );331332 let balance =333 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);334335 // checks that we can lock `amount` on the `staker` account.336 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(337 &staker_id,338 amount,339 WithdrawReasons::all(),340 balance341 .checked_sub(&amount)342 .ok_or(ArithmeticError::Underflow)?,343 )?;344345 Self::add_lock_balance(&staker_id, amount)?;346347 let block_number = T::RelayBlockNumberProvider::current_block_number();348349 // Calculation of the number of recalculation periods,350 // after how much the first interest calculation should be performed for the stake351 let recalculate_after_interval: T::BlockNumber =352 if block_number % T::RecalculationInterval::get() == 0u32.into() {353 1u32.into()354 } else {355 2u32.into()356 };357358 // Сalculation of the number of the relay block359 // in which it is necessary to accrue remuneration for the stake.360 let recalc_block = (block_number / T::RecalculationInterval::get()361 + recalculate_after_interval)362 * T::RecalculationInterval::get();363364 <Staked<T>>::insert((&staker_id, block_number), {365 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));366 balance_and_recalc_block.0 = balance_and_recalc_block367 .0368 .checked_add(&amount)369 .ok_or(ArithmeticError::Overflow)?;370 balance_and_recalc_block.1 = recalc_block;371 balance_and_recalc_block372 });373374 <TotalStaked<T>>::set(375 <TotalStaked<T>>::get()376 .checked_add(&amount)377 .ok_or(ArithmeticError::Overflow)?,378 );379380 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);381382 Self::deposit_event(Event::Stake(staker_id, amount));383384 Ok(())385 }386387 /// Unstakes all stakes.388 /// Moves the sum of all stakes to the `reserved` state.389 /// After the end of `PendingInterval` this sum becomes completely390 /// free for further use.391 #[pallet::weight(T::WeightInfo::unstake())]392 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {393 let staker_id = ensure_signed(staker)?;394395 // calculate block number where the sum would be free396 let block = <frame_system::Pallet<T>>::block_number() + T::PendingInterval::get();397398 let mut pendings = <PendingUnstake<T>>::get(block);399400 // checks that we can do unreserve stakes in the block401 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);402403 let mut total_stakes = 0u64;404405 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))406 .map(|(_, (amount, _))| {407 total_stakes += 1;408 amount409 })410 .sum();411412 if total_staked.is_zero() {413 return Ok(None.into()); // TO-DO414 }415416 pendings417 .try_push((staker_id.clone(), total_staked))418 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;419420 <PendingUnstake<T>>::insert(block, pendings);421422 Self::unlock_balance(&staker_id, total_staked)?;423424 <T::Currency as ReservableCurrency<T::AccountId>>::reserve(&staker_id, total_staked)?;425426 TotalStaked::<T>::set(427 TotalStaked::<T>::get()428 .checked_sub(&total_staked)429 .ok_or(ArithmeticError::Underflow)?,430 );431432 StakesPerAccount::<T>::remove(&staker_id);433434 Self::deposit_event(Event::Unstake(staker_id, total_staked));435436 Ok(None.into())437 }438439 /// Sets the pallet to be the sponsor for the collection.440 ///441 /// # Permissions442 ///443 /// * Pallet admin444 ///445 /// # Arguments446 ///447 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`448 #[pallet::weight(T::WeightInfo::sponsor_collection())]449 pub fn sponsor_collection(450 admin: OriginFor<T>,451 collection_id: CollectionId,452 ) -> DispatchResult {453 let admin_id = ensure_signed(admin)?;454 ensure!(455 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,456 Error::<T>::NoPermission457 );458459 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)460 }461462 /// Removes the pallet as the sponsor for the collection.463 /// Returns [`NoPermission`][`Error::NoPermission`]464 /// if the pallet wasn't the sponsor.465 ///466 /// # Permissions467 ///468 /// * Pallet admin469 ///470 /// # Arguments471 ///472 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`473 #[pallet::weight(T::WeightInfo::stop_sponsoring_collection())]474 pub fn stop_sponsoring_collection(475 admin: OriginFor<T>,476 collection_id: CollectionId,477 ) -> DispatchResult {478 let admin_id = ensure_signed(admin)?;479480 ensure!(481 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,482 Error::<T>::NoPermission483 );484485 ensure!(486 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?487 == Self::account_id(),488 <Error<T>>::NoPermission489 );490 T::CollectionHandler::remove_collection_sponsor(collection_id)491 }492493 /// Sets the pallet to be the sponsor for the contract.494 ///495 /// # Permissions496 ///497 /// * Pallet admin498 ///499 /// # Arguments500 ///501 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`502 #[pallet::weight(T::WeightInfo::sponsor_contract())]503 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {504 let admin_id = ensure_signed(admin)?;505506 ensure!(507 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,508 Error::<T>::NoPermission509 );510511 T::ContractHandler::set_sponsor(512 T::CrossAccountId::from_sub(Self::account_id()),513 contract_id,514 )515 }516517 /// Removes the pallet as the sponsor for the contract.518 /// Returns [`NoPermission`][`Error::NoPermission`]519 /// if the pallet wasn't the sponsor.520 ///521 /// # Permissions522 ///523 /// * Pallet admin524 ///525 /// # Arguments526 ///527 /// * `contract_id`: the contract address that is sponsored by `pallet_id`528 #[pallet::weight(T::WeightInfo::stop_sponsoring_contract())]529 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {530 let admin_id = ensure_signed(admin)?;531532 ensure!(533 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,534 Error::<T>::NoPermission535 );536537 ensure!(538 T::ContractHandler::sponsor(contract_id)?539 .ok_or(<Error<T>>::SponsorNotSet)?540 .as_sub() == &Self::account_id(),541 <Error<T>>::NoPermission542 );543 T::ContractHandler::remove_contract_sponsor(contract_id)544 }545546 /// Recalculates interest for the specified number of stakers.547 /// If all stakers are not recalculated, the next call of the extrinsic548 /// will continue the recalculation, from those stakers for whom this549 /// was not perform in last call.550 ///551 /// # Permissions552 ///553 /// * Pallet admin554 ///555 /// # Arguments556 ///557 /// * `stakers_number`: the number of stakers for which recalculation will be performed558 #[pallet::weight(T::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]559 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {560 let admin_id = ensure_signed(admin)?;561562 ensure!(563 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,564 Error::<T>::NoPermission565 );566567 // calculate the number of the current recalculation block,568 // this is necessary in order to understand which stakers we should calculate interest569 let current_recalc_block =570 Self::get_current_recalc_block(T::RelayBlockNumberProvider::current_block_number());571572 // calculate the number of the next recalculation block,573 // this value is set for the stakers to whom the recalculation will be performed574 let next_recalc_block = current_recalc_block + T::RecalculationInterval::get();575576 let mut storage_iterator = Self::get_next_calculated_key()577 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));578579 NextCalculatedRecord::<T>::set(None);580581 {582 let mut stakers_number = stakers_number.unwrap_or(20);583 let last_id = RefCell::new(None);584 let income_acc = RefCell::new(BalanceOf::<T>::default());585 let amount_acc = RefCell::new(BalanceOf::<T>::default());586587 // this closure is used to perform some of the actions if we break the loop because we reached the number of stakers for recalculation,588 // but there were unrecalculated records in the storage.589 let flush_stake = || -> DispatchResult {590 if let Some(last_id) = &*last_id.borrow() {591 if !income_acc.borrow().is_zero() {592 <T::Currency as Currency<T::AccountId>>::transfer(593 &T::TreasuryAccountId::get(),594 last_id,595 *income_acc.borrow(),596 ExistenceRequirement::KeepAlive,597 )598 .and_then(|_| {599 Self::add_lock_balance(last_id, *income_acc.borrow())?;600 <TotalStaked<T>>::try_mutate(|staked| {601 staked602 .checked_add(&*income_acc.borrow())603 .ok_or(ArithmeticError::Overflow.into())604 })605 })?;606607 Self::deposit_event(Event::StakingRecalculation(608 last_id.clone(),609 *amount_acc.borrow(),610 *income_acc.borrow(),611 ));612 }613614 *income_acc.borrow_mut() = BalanceOf::<T>::default();615 *amount_acc.borrow_mut() = BalanceOf::<T>::default();616 }617 Ok(())618 };619620 while let Some((621 (current_id, staked_block),622 (amount, next_recalc_block_for_stake),623 )) = storage_iterator.next()624 {625 if stakers_number == 0 {626 NextCalculatedRecord::<T>::set(Some((current_id, staked_block)));627 break;628 }629 if last_id.borrow().as_ref() != Some(¤t_id) {630 flush_stake()?;631 *last_id.borrow_mut() = Some(current_id.clone());632 stakers_number -= 1;633 };634 if current_recalc_block >= next_recalc_block_for_stake {635 *amount_acc.borrow_mut() += amount;636 Self::recalculate_and_insert_stake(637 ¤t_id,638 staked_block,639 next_recalc_block,640 amount,641 ((current_recalc_block - next_recalc_block_for_stake)642 / T::RecalculationInterval::get())643 .into() + 1,644 &mut *income_acc.borrow_mut(),645 );646 }647 }648 flush_stake()?;649 }650651 Ok(())652 }653 }654}655656impl<T: Config> Pallet<T> {657 /// The account address of the app promotion pot.658 ///659 /// This actually does computation. If you need to keep using it, then make sure you cache the660 /// value and only call this once.661 pub fn account_id() -> T::AccountId {662 T::PalletId::get().into_account_truncating()663 }664665 /// Unlocks the balance that was locked by the pallet.666 ///667 /// - `staker`: staker account.668 /// - `amount`: amount of unlocked funds.669 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {670 let locked_balance = Self::get_locked_balance(staker)671 .map(|l| l.amount)672 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;673674 // It is understood that we cannot unlock more funds than were locked by staking.675 // Therefore, if implemented correctly, this error should not occur.676 Self::set_lock_unchecked(677 staker,678 locked_balance679 .checked_sub(&amount)680 .ok_or(ArithmeticError::Underflow)?,681 );682 Ok(())683 }684685 /// Adds the balance to locked by the pallet.686 ///687 /// - `staker`: staker account.688 /// - `amount`: amount of added locked funds.689 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {690 Self::get_locked_balance(staker)691 .map_or(<BalanceOf<T>>::default(), |l| l.amount)692 .checked_add(&amount)693 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))694 .ok_or(ArithmeticError::Overflow.into())695 }696697 /// Sets the new state of a balance locked by the pallet.698 ///699 /// - `staker`: staker account.700 /// - `amount`: amount of locked funds.701 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {702 if amount.is_zero() {703 <T::Currency as LockableCurrency<T::AccountId>>::remove_lock(LOCK_IDENTIFIER, &staker);704 } else {705 <T::Currency as LockableCurrency<T::AccountId>>::set_lock(706 LOCK_IDENTIFIER,707 staker,708 amount,709 WithdrawReasons::all(),710 )711 }712 }713714 /// Returns the balance locked by the pallet for the staker.715 ///716 /// - `staker`: staker account.717 pub fn get_locked_balance(718 staker: impl EncodeLike<T::AccountId>,719 ) -> Option<BalanceLock<BalanceOf<T>>> {720 <T::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)721 .into_iter()722 .find(|l| l.id == LOCK_IDENTIFIER)723 }724725 /// Returns the total staked balance for the staker.726 ///727 /// - `staker`: staker account.728 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {729 let staked = Staked::<T>::iter_prefix((staker,))730 .into_iter()731 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {732 acc + amount733 });734 if staked != <BalanceOf<T>>::default() {735 Some(staked)736 } else {737 None738 }739 }740741 /// Returns all relay block numbers when stake was made,742 /// the amount of the stake.743 ///744 /// - `staker`: staker account.745 pub fn total_staked_by_id_per_block(746 staker: impl EncodeLike<T::AccountId>,747 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {748 let mut staked = Staked::<T>::iter_prefix((staker,))749 .into_iter()750 .map(|(block, (amount, _))| (block, amount))751 .collect::<Vec<_>>();752 staked.sort_by_key(|(block, _)| *block);753 if !staked.is_empty() {754 Some(staked)755 } else {756 None757 }758 }759760 /// Returns the total staked balance for the staker.761 /// If `staker` is `None`, returns the total amount staked.762 /// - `staker`: staker account.763 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {764 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {765 Self::total_staked_by_id(s.as_sub())766 })767 }768769 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {770 // Self::get_locked_balance(staker.as_sub())771 // .map(|l| l.amount)772 // .unwrap_or_default()773 // }774775 /// Returns all relay block numbers when stake was made,776 /// the amount of the stake.777 ///778 /// - `staker`: staker account.779 pub fn cross_id_total_staked_per_block(780 staker: T::CrossAccountId,781 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {782 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()783 }784785 fn recalculate_and_insert_stake(786 staker: &T::AccountId,787 staked_block: T::BlockNumber,788 next_recalc_block: T::BlockNumber,789 base: BalanceOf<T>,790 iters: u32,791 income_acc: &mut BalanceOf<T>,792 ) {793 let income = Self::calculate_income(base, iters);794795 base.checked_add(&income).map(|res| {796 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));797 *income_acc += income;798 });799 }800801 fn calculate_income<I>(base: I, iters: u32) -> I802 where803 I: EncodeLike<BalanceOf<T>> + Balance,804 {805 let mut income = base;806807 (0..iters).for_each(|_| income += T::IntervalIncome::get() * income);808809 income - base810 }811812 fn get_current_recalc_block(current_relay_block: T::BlockNumber) -> T::BlockNumber {813 (current_relay_block / T::RecalculationInterval::get()) * T::RecalculationInterval::get()814 }815816 fn get_next_calculated_key() -> Option<Vec<u8>> {817 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))818 }819}820821impl<T: Config> Pallet<T>822where823 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,824{825 /// Returns the amount reserved by the pending.826 /// If `staker` is `None`, returns the total pending.827 ///828 /// -`staker`: staker account.829 ///830 /// Since user funds are not transferred anywhere by staking, overflow protection is provided831 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,832 /// the staker must have more funds on his account than the maximum set for `Balance` type.833 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {834 staker.map_or(835 PendingUnstake::<T>::iter_values()836 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))837 .sum(),838 |s| {839 PendingUnstake::<T>::iter_values()840 .flatten()841 .filter_map(|(id, amount)| {842 if id == *s.as_sub() {843 Some(amount)844 } else {845 None846 }847 })848 .sum()849 },850 )851 }852853 /// Returns all parachain block numbers when unreserve is expected,854 /// the amount of the unreserved funds.855 ///856 /// - `staker`: staker account.857 pub fn cross_id_pending_unstake_per_block(858 staker: T::CrossAccountId,859 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {860 let mut unsorted_res = vec![];861 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {862 pendings.into_iter().for_each(|(id, amount)| {863 if id == *staker.as_sub() {864 unsorted_res.push((block, amount));865 };866 })867 });868869 unsorted_res.sort_by_key(|(block, _)| *block);870 unsorted_res871 }872}pallets/app-promotion/src/types.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/types.rs
+++ b/pallets/app-promotion/src/types.rs
@@ -9,7 +9,10 @@
use sp_std::borrow::ToOwned;
use pallet_evm_contract_helpers::{Pallet as EvmHelpersPallet, Config as EvmHelpersConfig};
+/// This trait was defined because `LockableCurrency`
+/// has no way to know the state of the lock for an account.
pub trait ExtendedLockableCurrency<AccountId: Parameter>: LockableCurrency<AccountId> {
+ /// Returns lock balance for an account. Allows to determine the cause of the lock.
fn locks<KArg>(who: KArg) -> WeakBoundedVec<BalanceLock<Self::Balance>, Self::MaxLocks>
where
KArg: EncodeLike<AccountId>;
@@ -25,18 +28,28 @@
Self::locks(who)
}
}
-
+/// Trait for interacting with collections.
pub trait CollectionHandler {
type CollectionId;
type AccountId;
+ /// Sets sponsor for a collection.
+ ///
+ /// - `sponsor_id`: the account of the sponsor-to-be.
+ /// - `collection_id`: ID of the modified collection.
fn set_sponsor(
sponsor_id: Self::AccountId,
collection_id: Self::CollectionId,
) -> DispatchResult;
+ /// Removes sponsor for a collection.
+ ///
+ /// - `collection_id`: ID of the modified collection.
fn remove_collection_sponsor(collection_id: Self::CollectionId) -> DispatchResult;
+ /// Retuns the current sponsor for a collection if one is set.
+ ///
+ /// - `collection_id`: ID of the collection.
fn sponsor(collection_id: Self::CollectionId)
-> Result<Option<Self::AccountId>, DispatchError>;
}
@@ -66,18 +79,28 @@
.map(|acc| acc.to_owned()))
}
}
-
+/// Trait for interacting with contracts.
pub trait ContractHandler {
type ContractId;
type AccountId;
+ /// Sets sponsor for a contract.
+ ///
+ /// - `sponsor_id`: the account of the sponsor-to-be.
+ /// - `contract_address`: the address of the modified contract.
fn set_sponsor(
sponsor_id: Self::AccountId,
contract_address: Self::ContractId,
) -> DispatchResult;
+ /// Removes sponsor for a contract.
+ ///
+ /// - `contract_address`: the address of the modified contract.
fn remove_contract_sponsor(contract_address: Self::ContractId) -> DispatchResult;
+ /// Retuns the current sponsor for a contract if one is set.
+ ///
+ /// - `contract_address`: the contract address.
fn sponsor(
contract_address: Self::ContractId,
) -> Result<Option<Self::AccountId>, DispatchError>;
pallets/evm-contract-helpers/CHANGELOG.mddiffbeforeafterboth--- a/pallets/evm-contract-helpers/CHANGELOG.md
+++ b/pallets/evm-contract-helpers/CHANGELOG.md
@@ -2,29 +2,35 @@
All notable changes to this project will be documented in this file.
+## [v0.3.0] 2022-09-05
+
+### Added
+
+- Methods `force_set_sponsor` , `force_remove_sponsor` to be able to administer sponsorships with other pallets. Added to implement `AppPromotion` pallet logic.
+
## [v0.2.0] - 2022-08-19
### Added
- - Set arbitrary evm address as contract sponsor.
- - Ability to remove current sponsor.
+- Set arbitrary evm address as contract sponsor.
+- Ability to remove current sponsor.
### Removed
- - Remove methods
- + sponsoring_enabled
- + toggle_sponsoring
- ### Changed
+- Remove methods
+ - sponsoring_enabled
+ - toggle_sponsoring
- - Change `toggle_sponsoring` to `self_sponsored_enable`.
+### Changed
+- Change `toggle_sponsoring` to `self_sponsored_enable`.
## [v0.1.2] 2022-08-16
### Other changes
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
\ No newline at end of file
+- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
pallets/evm-contract-helpers/Cargo.tomldiffbeforeafterboth--- a/pallets/evm-contract-helpers/Cargo.toml
+++ b/pallets/evm-contract-helpers/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "pallet-evm-contract-helpers"
-version = "0.2.0"
+version = "0.3.0"
license = "GPLv3"
edition = "2021"
pallets/evm-contract-helpers/src/lib.rsdiffbeforeafterboth--- a/pallets/evm-contract-helpers/src/lib.rs
+++ b/pallets/evm-contract-helpers/src/lib.rs
@@ -216,9 +216,10 @@
Ok(())
}
- /// TO-DO
- ///
+ /// Force set `sponsor` for `contract`.
///
+ /// Differs from `set_sponsor` in that confirmation
+ /// from the sponsor is not required.
pub fn force_set_sponsor(
contract_address: H160,
sponsor: &T::CrossAccountId,
@@ -269,9 +270,10 @@
Self::force_remove_sponsor(contract_address)
}
- /// TO-DO
- ///
+ /// Force remove `sponsor` for `contract`.
///
+ /// Differs from `remove_sponsor` in that
+ /// it doesn't require consent from the `owner` of the contract.
pub fn force_remove_sponsor(contract_address: H160) -> DispatchResult {
Sponsoring::<T>::remove(contract_address);
pallets/unique/CHANGELOG.mddiffbeforeafterboth--- a/pallets/unique/CHANGELOG.md
+++ b/pallets/unique/CHANGELOG.md
@@ -4,7 +4,7 @@
<!-- bureaucrate goes here -->
-## [v0.1.4] 2022-09-5
+## [v0.1.4] 2022-09-05
### Added
pallets/unique/src/lib.rsdiffbeforeafterboth--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -1105,6 +1105,15 @@
}
impl<T: Config> Pallet<T> {
+ /// Force set `sponsor` for `collection`.
+ ///
+ /// Differs from [`set_collection_sponsor`][`Pallet::set_collection_sponsor`] in that confirmation
+ /// from the `sponsor` is not required.
+ ///
+ /// # Arguments
+ ///
+ /// * `sponsor`: ID of the account of the sponsor-to-be.
+ /// * `collection_id`: ID of the modified collection.
pub fn force_set_sponsor(sponsor: T::AccountId, collection_id: CollectionId) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_internal()?;
@@ -1125,6 +1134,14 @@
target_collection.save()
}
+ /// Force remove `sponsor` for `collection`.
+ ///
+ /// Differs from `remove_sponsor` in that
+ /// it doesn't require consent from the `owner` of the collection.
+ ///
+ /// # Arguments
+ ///
+ /// * `collection_id`: ID of the modified collection.
pub fn force_remove_collection_sponsor(collection_id: CollectionId) -> DispatchResult {
let mut target_collection = <CollectionHandle<T>>::try_get(collection_id)?;
target_collection.check_is_internal()?;
primitives/common/CHANGELOG.mddiffbeforeafterboth--- a/primitives/common/CHANGELOG.md
+++ b/primitives/common/CHANGELOG.md
@@ -1,4 +1,9 @@
<!-- bureaucrate goes here -->
+## [v0.9.27] 2022-09-08
+
+### Added
+- Relay block constants. In particular, it is necessary to add the `AppPromotion` pallet at runtime.
+
## [v0.9.25] 2022-08-16
### Other changes
runtime/opal/CHANGELOG.mddiffbeforeafterboth--- a/runtime/opal/CHANGELOG.md
+++ b/runtime/opal/CHANGELOG.md
@@ -3,16 +3,23 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+
+## [v0.9.27] 2022-09-08
+
+### Added
+
+- `AppPromotion` pallet to runtime.
+
## [v0.9.27] 2022-08-16
### Bugfixes
-- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
+- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
### Other changes
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
+- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
runtime/quartz/CHANGELOG.mddiffbeforeafterboth--- a/runtime/quartz/CHANGELOG.md
+++ b/runtime/quartz/CHANGELOG.md
@@ -3,17 +3,23 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+
+## [v0.9.27] 2022-09-08
+
+### Added
+
+- `AppPromotion` pallet to runtime.
+
## [v0.9.27] 2022-08-16
### Bugfixes
-- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
+- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
### Other changes
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
-
+- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
runtime/unique/CHANGELOG.mddiffbeforeafterboth--- a/runtime/unique/CHANGELOG.md
+++ b/runtime/unique/CHANGELOG.md
@@ -3,16 +3,23 @@
All notable changes to this project will be documented in this file.
<!-- bureaucrate goes here -->
+
+## [v0.9.27] 2022-09-08
+
+### Added
+
+- `AppPromotion` pallet to runtime.
+
## [v0.9.27] 2022-08-16
### Bugfixes
-- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
+- Add missing config keys 74f532ac28dce15c15e7d576c074a58eba658c08
### Other changes
-- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
+- build: Upgrade polkadot to v0.9.27 2c498572636f2b34d53b1c51b7283a761a7dc90a
-- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
+- build: Upgrade polkadot to v0.9.26 85515e54c4ca1b82a2630034e55dcc804c643bf8
-- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b
+- build: Upgrade polkadot to v0.9.25 cdfb9bdc7b205ff1b5134f034ef9973d769e5e6b