difftreelog
Merge pull request #784 from UniqueNetwork/fix/enable-foreign-assets-qtz-and-minor-fixes
in: master
Fix/enable foreign assets qtz and minor fixes
6 files changed
pallets/app-promotion/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # App Promotion pallet18//!19//! The pallet implements the mechanics of staking and sponsoring collections/contracts.20//!21//! - [`Config`]22//! - [`Pallet`]23//! - [`Error`]24//! - [`Event`]25//!26//! ## Overview27//! The App Promotion pallet allows fund holders to stake at a certain daily rate of return.28//! The mechanics implemented in the pallet allow it to act as a sponsor for collections / contracts,29//! the list of which is set by the pallet administrator.30//!31//!32//! ## Interface33//! The pallet provides interfaces for funds, collection/contract operations (see [types] module).3435//!36//! ### Dispatchable Functions37//! - [`set_admin_address`][`Pallet::set_admin_address`] - sets an address as the the admin.38//! - [`stake`][`Pallet::stake`] - stakes the amount of native tokens.39//! - [`unstake`][`Pallet::unstake`] - unstakes all stakes.40//! - [`sponsor_collection`][`Pallet::sponsor_collection`] - sets the pallet to be the sponsor for the collection.41//! - [`stop_sponsoring_collection`][`Pallet::stop_sponsoring_collection`] - removes the pallet as the sponsor for the collection.42//! - [`sponsor_contract`][`Pallet::sponsor_contract`] - sets the pallet to be the sponsor for the contract.43//! - [`stop_sponsoring_contract`][`Pallet::stop_sponsoring_contract`] - removes the pallet as the sponsor for the contract.44//! - [`payout_stakers`][`Pallet::payout_stakers`] - recalculates interest for the specified number of stakers.45//!4647// #![recursion_limit = "1024"]48#![cfg_attr(not(feature = "std"), no_std)]4950#[cfg(feature = "runtime-benchmarks")]51mod benchmarking;5253pub mod types;54pub mod weights;5556use sp_std::{57 vec::{Vec},58 vec,59 iter::Sum,60 borrow::ToOwned,61 cell::RefCell,62};63use sp_core::H160;64use codec::EncodeLike;65use pallet_balances::BalanceLock;66pub use types::*;6768use up_data_structs::CollectionId;6970use frame_support::{71 dispatch::{DispatchResult},72 traits::{73 Currency, Get, LockableCurrency, WithdrawReasons, tokens::Balance, ExistenceRequirement,74 },75 ensure,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83 Perbill,84 traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85 ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93 <<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97 use super::*;98 use frame_support::{99 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100 traits::ReservableCurrency,101 };102 use frame_system::pallet_prelude::*;103104 #[pallet::config]105 pub trait Config:106 frame_system::Config + pallet_evm::Config + pallet_configuration::Config107 {108 /// Type to interact with the native token109 type Currency: ExtendedLockableCurrency<Self::AccountId>110 + ReservableCurrency<Self::AccountId>;111112 /// Type for interacting with collections113 type CollectionHandler: CollectionHandler<114 AccountId = Self::AccountId,115 CollectionId = CollectionId,116 >;117118 /// Type for interacting with conrtacts119 type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121 /// `AccountId` for treasury122 type TreasuryAccountId: Get<Self::AccountId>;123124 /// The app's pallet id, used for deriving its sovereign account address.125 #[pallet::constant]126 type PalletId: Get<PalletId>;127128 /// In relay blocks.129 #[pallet::constant]130 type RecalculationInterval: Get<Self::BlockNumber>;131132 /// In parachain blocks.133 #[pallet::constant]134 type PendingInterval: Get<Self::BlockNumber>;135136 /// Rate of return for interval in blocks defined in `RecalculationInterval`.137 #[pallet::constant]138 type IntervalIncome: Get<Perbill>;139140 /// Decimals for the `Currency`.141 #[pallet::constant]142 type Nominal: Get<BalanceOf<Self>>;143144 /// Weight information for extrinsics in this pallet.145 type WeightInfo: WeightInfo;146147 // The relay block number provider148 type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150 /// Events compatible with [`frame_system::Config::Event`].151 type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152 }153154 #[pallet::pallet]155 #[pallet::generate_store(pub(super) trait Store)]156 pub struct Pallet<T>(_);157158 #[pallet::event]159 #[pallet::generate_deposit(fn deposit_event)]160 pub enum Event<T: Config> {161 /// Staking recalculation was performed162 ///163 /// # Arguments164 /// * AccountId: account of the staker.165 /// * Balance : recalculation base166 /// * Balance : total income167 StakingRecalculation(168 /// An recalculated staker169 T::AccountId,170 /// Base on which interest is calculated171 BalanceOf<T>,172 /// Amount of accrued interest173 BalanceOf<T>,174 ),175176 /// Staking was performed177 ///178 /// # Arguments179 /// * AccountId: account of the staker180 /// * Balance : staking amount181 Stake(T::AccountId, BalanceOf<T>),182183 /// Unstaking was performed184 ///185 /// # Arguments186 /// * AccountId: account of the staker187 /// * Balance : unstaking amount188 Unstake(T::AccountId, BalanceOf<T>),189190 /// The admin was set191 ///192 /// # Arguments193 /// * AccountId: account address of the admin194 SetAdmin(T::AccountId),195 }196197 #[pallet::error]198 pub enum Error<T> {199 /// Error due to action requiring admin to be set.200 AdminNotSet,201 /// No permission to perform an action.202 NoPermission,203 /// Insufficient funds to perform an action.204 NotSufficientFunds,205 /// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.206 PendingForBlockOverflow,207 /// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.208 SponsorNotSet,209 /// Errors caused by incorrect actions with a locked balance.210 IncorrectLockedBalanceOperation,211 }212213 /// Stores the total staked amount.214 #[pallet::storage]215 pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;216217 /// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.218 #[pallet::storage]219 pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;220221 /// Stores the amount of tokens staked by account in the blocknumber.222 ///223 /// * **Key1** - Staker account.224 /// * **Key2** - Relay block number when the stake was made.225 /// * **(Balance, BlockNumber)** - Balance of the stake.226 /// The number of the relay block in which we must perform the interest recalculation227 #[pallet::storage]228 pub type Staked<T: Config> = StorageNMap<229 Key = (230 Key<Blake2_128Concat, T::AccountId>,231 Key<Twox64Concat, T::BlockNumber>,232 ),233 Value = (BalanceOf<T>, T::BlockNumber),234 QueryKind = ValueQuery,235 >;236237 /// Stores amount of stakes for an `Account`.238 ///239 /// * **Key** - Staker account.240 /// * **Value** - Amount of stakes.241 #[pallet::storage]242 pub type StakesPerAccount<T: Config> =243 StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;244245 /// Stores amount of stakes for an `Account`.246 ///247 /// * **Key** - Staker account.248 /// * **Value** - Amount of stakes.249 #[pallet::storage]250 pub type PendingUnstake<T: Config> = StorageMap<251 _,252 Twox64Concat,253 T::BlockNumber,254 BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,255 ValueQuery,256 >;257258 /// Stores a key for record for which the revenue recalculation was performed.259 /// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.260 #[pallet::storage]261 #[pallet::getter(fn get_next_calculated_record)]262 pub type PreviousCalculatedRecord<T: Config> =263 StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;264265 #[pallet::hooks]266 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {267 /// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize268 /// implies the execution of a strictly limited number of relatively lightweight operations.269 /// A separate benchmark has been implemented to scale the weight depending on the number of pendings.270 fn on_initialize(current_block_number: T::BlockNumber) -> Weight271 where272 <T as frame_system::Config>::BlockNumber: From<u32>,273 {274 let block_pending = PendingUnstake::<T>::take(current_block_number);275 let counter = block_pending.len() as u32;276277 if !block_pending.is_empty() {278 block_pending.into_iter().for_each(|(staker, amount)| {279 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::unreserve(280 &staker, amount,281 );282 });283 }284285 <T as Config>::WeightInfo::on_initialize(counter)286 }287 }288289 #[pallet::call]290 impl<T: Config> Pallet<T>291 where292 T::BlockNumber: From<u32> + Into<u32>,293 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,294 {295 /// Sets an address as the the admin.296 ///297 /// # Permissions298 ///299 /// * Sudo300 ///301 /// # Arguments302 ///303 /// * `admin`: account of the new admin.304 #[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]305 pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {306 ensure_root(origin)?;307308 <Admin<T>>::set(Some(admin.as_sub().to_owned()));309310 Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));311312 Ok(())313 }314315 /// Stakes the amount of native tokens.316 /// Sets `amount` to the locked state.317 /// The maximum number of stakes for a staker is 10.318 ///319 /// # Arguments320 ///321 /// * `amount`: in native tokens.322 #[pallet::weight(<T as Config>::WeightInfo::stake())]323 pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {324 let staker_id = ensure_signed(staker)?;325326 ensure!(327 StakesPerAccount::<T>::get(&staker_id) < 10,328 Error::<T>::NoPermission329 );330331 ensure!(332 amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),333 ArithmeticError::Underflow334 );335 let config = <PalletConfiguration<T>>::get();336337 let balance =338 <<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);339340 // checks that we can lock `amount` on the `staker` account.341 <<T as Config>::Currency as Currency<T::AccountId>>::ensure_can_withdraw(342 &staker_id,343 amount,344 WithdrawReasons::all(),345 balance346 .checked_sub(&amount)347 .ok_or(ArithmeticError::Underflow)?,348 )?;349350 Self::add_lock_balance(&staker_id, amount)?;351352 let block_number = T::RelayBlockNumberProvider::current_block_number();353354 // Calculation of the number of recalculation periods,355 // after how much the first interest calculation should be performed for the stake356 let recalculate_after_interval: T::BlockNumber =357 if block_number % config.recalculation_interval == 0u32.into() {358 1u32.into()359 } else {360 2u32.into()361 };362363 // Сalculation of the number of the relay block364 // in which it is necessary to accrue remuneration for the stake.365 let recalc_block = (block_number / config.recalculation_interval366 + recalculate_after_interval)367 * config.recalculation_interval;368369 <Staked<T>>::insert((&staker_id, block_number), {370 let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));371 balance_and_recalc_block.0 = balance_and_recalc_block372 .0373 .checked_add(&amount)374 .ok_or(ArithmeticError::Overflow)?;375 balance_and_recalc_block.1 = recalc_block;376 balance_and_recalc_block377 });378379 <TotalStaked<T>>::set(380 <TotalStaked<T>>::get()381 .checked_add(&amount)382 .ok_or(ArithmeticError::Overflow)?,383 );384385 StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);386387 Self::deposit_event(Event::Stake(staker_id, amount));388389 Ok(())390 }391392 /// Unstakes all stakes.393 /// Moves the sum of all stakes to the `reserved` state.394 /// After the end of `PendingInterval` this sum becomes completely395 /// free for further use.396 #[pallet::weight(<T as Config>::WeightInfo::unstake())]397 pub fn unstake(staker: OriginFor<T>) -> DispatchResultWithPostInfo {398 let staker_id = ensure_signed(staker)?;399 let config = <PalletConfiguration<T>>::get();400401 // calculate block number where the sum would be free402 let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;403404 let mut pendings = <PendingUnstake<T>>::get(block);405406 // checks that we can do unreserve stakes in the block407 ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);408409 let mut total_stakes = 0u64;410411 let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))412 .map(|(_, (amount, _))| {413 total_stakes += 1;414 amount415 })416 .sum();417418 if total_staked.is_zero() {419 return Ok(None::<Weight>.into()); // TO-DO420 }421422 pendings423 .try_push((staker_id.clone(), total_staked))424 .map_err(|_| Error::<T>::PendingForBlockOverflow)?;425426 <PendingUnstake<T>>::insert(block, pendings);427428 Self::unlock_balance(&staker_id, total_staked)?;429430 <<T as Config>::Currency as ReservableCurrency<T::AccountId>>::reserve(431 &staker_id,432 total_staked,433 )?;434435 TotalStaked::<T>::set(436 TotalStaked::<T>::get()437 .checked_sub(&total_staked)438 .ok_or(ArithmeticError::Underflow)?,439 );440441 StakesPerAccount::<T>::remove(&staker_id);442443 Self::deposit_event(Event::Unstake(staker_id, total_staked));444445 Ok(None::<Weight>.into())446 }447448 /// Sets the pallet to be the sponsor for the collection.449 ///450 /// # Permissions451 ///452 /// * Pallet admin453 ///454 /// # Arguments455 ///456 /// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`457 #[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]458 pub fn sponsor_collection(459 admin: OriginFor<T>,460 collection_id: CollectionId,461 ) -> DispatchResult {462 let admin_id = ensure_signed(admin)?;463 ensure!(464 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,465 Error::<T>::NoPermission466 );467468 T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)469 }470471 /// Removes the pallet as the sponsor for the collection.472 /// Returns [`NoPermission`][`Error::NoPermission`]473 /// if the pallet wasn't the sponsor.474 ///475 /// # Permissions476 ///477 /// * Pallet admin478 ///479 /// # Arguments480 ///481 /// * `collection_id`: ID of the collection that is sponsored by `pallet_id`482 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]483 pub fn stop_sponsoring_collection(484 admin: OriginFor<T>,485 collection_id: CollectionId,486 ) -> DispatchResult {487 let admin_id = ensure_signed(admin)?;488489 ensure!(490 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,491 Error::<T>::NoPermission492 );493494 ensure!(495 T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?496 == Self::account_id(),497 <Error<T>>::NoPermission498 );499 T::CollectionHandler::remove_collection_sponsor(collection_id)500 }501502 /// Sets the pallet to be the sponsor for the contract.503 ///504 /// # Permissions505 ///506 /// * Pallet admin507 ///508 /// # Arguments509 ///510 /// * `contract_id`: the contract address that will be sponsored by `pallet_id`511 #[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]512 pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {513 let admin_id = ensure_signed(admin)?;514515 ensure!(516 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,517 Error::<T>::NoPermission518 );519520 T::ContractHandler::set_sponsor(521 T::CrossAccountId::from_sub(Self::account_id()),522 contract_id,523 )524 }525526 /// Removes the pallet as the sponsor for the contract.527 /// Returns [`NoPermission`][`Error::NoPermission`]528 /// if the pallet wasn't the sponsor.529 ///530 /// # Permissions531 ///532 /// * Pallet admin533 ///534 /// # Arguments535 ///536 /// * `contract_id`: the contract address that is sponsored by `pallet_id`537 #[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_contract())]538 pub fn stop_sponsoring_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {539 let admin_id = ensure_signed(admin)?;540541 ensure!(542 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,543 Error::<T>::NoPermission544 );545546 ensure!(547 T::ContractHandler::sponsor(contract_id)?548 .ok_or(<Error<T>>::SponsorNotSet)?549 .as_sub() == &Self::account_id(),550 <Error<T>>::NoPermission551 );552 T::ContractHandler::remove_contract_sponsor(contract_id)553 }554555 /// Recalculates interest for the specified number of stakers.556 /// If all stakers are not recalculated, the next call of the extrinsic557 /// will continue the recalculation, from those stakers for whom this558 /// was not perform in last call.559 ///560 /// # Permissions561 ///562 /// * Pallet admin563 ///564 /// # Arguments565 ///566 /// * `stakers_number`: the number of stakers for which recalculation will be performed567 #[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(20) as u32))]568 pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {569 let admin_id = ensure_signed(admin)?;570571 ensure!(572 admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,573 Error::<T>::NoPermission574 );575 let config = <PalletConfiguration<T>>::get();576577 let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);578579 ensure!(580 stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,581 Error::<T>::NoPermission582 );583584 // calculate the number of the current recalculation block,585 // this is necessary in order to understand which stakers we should calculate interest586 let current_recalc_block = Self::get_current_recalc_block(587 T::RelayBlockNumberProvider::current_block_number(),588 &config,589 );590591 // calculate the number of the next recalculation block,592 // this value is set for the stakers to whom the recalculation will be performed593 let next_recalc_block = current_recalc_block + config.recalculation_interval;594595 let mut storage_iterator = Self::get_next_calculated_key()596 .map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));597598 PreviousCalculatedRecord::<T>::set(None);599600 {601 let last_id = RefCell::new(None);602 let income_acc = RefCell::new(BalanceOf::<T>::default());603 let amount_acc = RefCell::new(BalanceOf::<T>::default());604605 // this closure is used to perform some of the actions if we break the loop because we reached the number of stakers for recalculation,606 // but there were unrecalculated records in the storage.607 let flush_stake = || -> DispatchResult {608 if let Some(last_id) = &*last_id.borrow() {609 if !income_acc.borrow().is_zero() {610 <<T as Config>::Currency as Currency<T::AccountId>>::transfer(611 &T::TreasuryAccountId::get(),612 last_id,613 *income_acc.borrow(),614 ExistenceRequirement::KeepAlive,615 )?;616617 Self::add_lock_balance(last_id, *income_acc.borrow())?;618 <TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {619 *staked = staked620 .checked_add(&*income_acc.borrow())621 .ok_or(ArithmeticError::Overflow)?;622 Ok(())623 })?;624625 Self::deposit_event(Event::StakingRecalculation(626 last_id.clone(),627 *amount_acc.borrow(),628 *income_acc.borrow(),629 ));630 }631632 *income_acc.borrow_mut() = BalanceOf::<T>::default();633 *amount_acc.borrow_mut() = BalanceOf::<T>::default();634 }635 Ok(())636 };637638 while let Some((639 (current_id, staked_block),640 (amount, next_recalc_block_for_stake),641 )) = storage_iterator.next()642 {643 if last_id.borrow().as_ref() != Some(¤t_id) {644 flush_stake()?;645 *last_id.borrow_mut() = Some(current_id.clone());646 stakers_number -= 1;647 };648 if current_recalc_block >= next_recalc_block_for_stake {649 *amount_acc.borrow_mut() += amount;650 Self::recalculate_and_insert_stake(651 ¤t_id,652 staked_block,653 next_recalc_block,654 amount,655 ((current_recalc_block - next_recalc_block_for_stake)656 / config.recalculation_interval)657 .into() + 1,658 &mut *income_acc.borrow_mut(),659 );660 }661662 if stakers_number == 0 {663 if storage_iterator.next().is_some() {664 PreviousCalculatedRecord::<T>::set(Some((current_id, staked_block)));665 }666 break;667 }668 }669 flush_stake()?;670 }671672 Ok(())673 }674 }675}676677impl<T: Config> Pallet<T> {678 /// The account address of the app promotion pot.679 ///680 /// This actually does computation. If you need to keep using it, then make sure you cache the681 /// value and only call this once.682 pub fn account_id() -> T::AccountId {683 T::PalletId::get().into_account_truncating()684 }685686 /// Unlocks the balance that was locked by the pallet.687 ///688 /// - `staker`: staker account.689 /// - `amount`: amount of unlocked funds.690 fn unlock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {691 let locked_balance = Self::get_locked_balance(staker)692 .map(|l| l.amount)693 .ok_or(<Error<T>>::IncorrectLockedBalanceOperation)?;694695 // It is understood that we cannot unlock more funds than were locked by staking.696 // Therefore, if implemented correctly, this error should not occur.697 Self::set_lock_unchecked(698 staker,699 locked_balance700 .checked_sub(&amount)701 .ok_or(ArithmeticError::Underflow)?,702 );703 Ok(())704 }705706 /// Adds the balance to locked by the pallet.707 ///708 /// - `staker`: staker account.709 /// - `amount`: amount of added locked funds.710 fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {711 Self::get_locked_balance(staker)712 .map_or(<BalanceOf<T>>::default(), |l| l.amount)713 .checked_add(&amount)714 .map(|new_lock| Self::set_lock_unchecked(staker, new_lock))715 .ok_or(ArithmeticError::Overflow.into())716 }717718 /// Sets the new state of a balance locked by the pallet.719 ///720 /// - `staker`: staker account.721 /// - `amount`: amount of locked funds.722 fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {723 if amount.is_zero() {724 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(725 LOCK_IDENTIFIER,726 &staker,727 );728 } else {729 <<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(730 LOCK_IDENTIFIER,731 staker,732 amount,733 WithdrawReasons::all(),734 )735 }736 }737738 /// Returns the balance locked by the pallet for the staker.739 ///740 /// - `staker`: staker account.741 pub fn get_locked_balance(742 staker: impl EncodeLike<T::AccountId>,743 ) -> Option<BalanceLock<BalanceOf<T>>> {744 <<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)745 .into_iter()746 .find(|l| l.id == LOCK_IDENTIFIER)747 }748749 /// Returns the total staked balance for the staker.750 ///751 /// - `staker`: staker account.752 pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {753 let staked = Staked::<T>::iter_prefix((staker,))754 .into_iter()755 .fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {756 acc + amount757 });758 if staked != <BalanceOf<T>>::default() {759 Some(staked)760 } else {761 None762 }763 }764765 /// Returns all relay block numbers when stake was made,766 /// the amount of the stake.767 ///768 /// - `staker`: staker account.769 pub fn total_staked_by_id_per_block(770 staker: impl EncodeLike<T::AccountId>,771 ) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {772 let mut staked = Staked::<T>::iter_prefix((staker,))773 .into_iter()774 .map(|(block, (amount, _))| (block, amount))775 .collect::<Vec<_>>();776 staked.sort_by_key(|(block, _)| *block);777 if !staked.is_empty() {778 Some(staked)779 } else {780 None781 }782 }783784 /// Returns the total staked balance for the staker.785 /// If `staker` is `None`, returns the total amount staked.786 /// - `staker`: staker account.787 pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {788 staker.map_or(Some(<TotalStaked<T>>::get()), |s| {789 Self::total_staked_by_id(s.as_sub())790 })791 }792793 // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {794 // Self::get_locked_balance(staker.as_sub())795 // .map(|l| l.amount)796 // .unwrap_or_default()797 // }798799 /// Returns all relay block numbers when stake was made,800 /// the amount of the stake.801 ///802 /// - `staker`: staker account.803 pub fn cross_id_total_staked_per_block(804 staker: T::CrossAccountId,805 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {806 Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()807 }808809 fn recalculate_and_insert_stake(810 staker: &T::AccountId,811 staked_block: T::BlockNumber,812 next_recalc_block: T::BlockNumber,813 base: BalanceOf<T>,814 iters: u32,815 income_acc: &mut BalanceOf<T>,816 ) {817 let income = Self::calculate_income(base, iters);818819 base.checked_add(&income).map(|res| {820 <Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));821 *income_acc += income;822 });823 }824825 fn calculate_income<I>(base: I, iters: u32) -> I826 where827 I: EncodeLike<BalanceOf<T>> + Balance,828 {829 let config = <PalletConfiguration<T>>::get();830 let mut income = base;831832 (0..iters).for_each(|_| income += config.interval_income * income);833834 income - base835 }836837 fn get_current_recalc_block(838 current_relay_block: T::BlockNumber,839 config: &PalletConfiguration<T>,840 ) -> T::BlockNumber {841 (current_relay_block / config.recalculation_interval) * config.recalculation_interval842 }843844 fn get_next_calculated_key() -> Option<Vec<u8>> {845 Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))846 }847}848849impl<T: Config> Pallet<T>850where851 <<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,852{853 /// Returns the amount reserved by the pending.854 /// If `staker` is `None`, returns the total pending.855 ///856 /// -`staker`: staker account.857 ///858 /// Since user funds are not transferred anywhere by staking, overflow protection is provided859 /// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,860 /// the staker must have more funds on his account than the maximum set for `Balance` type.861 pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {862 staker.map_or(863 PendingUnstake::<T>::iter_values()864 .flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))865 .sum(),866 |s| {867 PendingUnstake::<T>::iter_values()868 .flatten()869 .filter_map(|(id, amount)| {870 if id == *s.as_sub() {871 Some(amount)872 } else {873 None874 }875 })876 .sum()877 },878 )879 }880881 /// Returns all parachain block numbers when unreserve is expected,882 /// the amount of the unreserved funds.883 ///884 /// - `staker`: staker account.885 pub fn cross_id_pending_unstake_per_block(886 staker: T::CrossAccountId,887 ) -> Vec<(T::BlockNumber, BalanceOf<T>)> {888 let mut unsorted_res = vec![];889 PendingUnstake::<T>::iter().for_each(|(block, pendings)| {890 pendings.into_iter().for_each(|(id, amount)| {891 if id == *staker.as_sub() {892 unsorted_res.push((block, amount));893 };894 })895 });896897 unsorted_res.sort_by_key(|(block, _)| *block);898 unsorted_res899 }900}pallets/configuration/src/lib.rsdiffbeforeafterboth--- a/pallets/configuration/src/lib.rs
+++ b/pallets/configuration/src/lib.rs
@@ -52,7 +52,7 @@
type DefaultMinGasPrice: Get<u64>;
#[pallet::constant]
- type MaxOverridedAllowedLocations: Get<u32>;
+ type MaxXcmAllowedLocations: Get<u32>;
#[pallet::constant]
type AppPromotionDailyRate: Get<Perbill>;
#[pallet::constant]
@@ -77,7 +77,7 @@
#[pallet::storage]
pub type XcmAllowedLocationsOverride<T: Config> = StorageValue<
- Value = BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>,
+ Value = BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>,
QueryKind = OptionQuery,
>;
@@ -118,7 +118,7 @@
#[pallet::weight(T::DbWeight::get().writes(1))]
pub fn set_xcm_allowed_locations(
origin: OriginFor<T>,
- locations: Option<BoundedVec<MultiLocation, T::MaxOverridedAllowedLocations>>,
+ locations: Option<BoundedVec<MultiLocation, T::MaxXcmAllowedLocations>>,
) -> DispatchResult {
ensure_root(origin)?;
<XcmAllowedLocationsOverride<T>>::set(locations);
runtime/common/config/pallets/mod.rsdiffbeforeafterboth--- a/runtime/common/config/pallets/mod.rs
+++ b/runtime/common/config/pallets/mod.rs
@@ -106,7 +106,7 @@
impl pallet_configuration::Config for Runtime {
type DefaultWeightToFeeCoefficient = ConstU32<{ up_common::constants::WEIGHT_TO_FEE_COEFF }>;
type DefaultMinGasPrice = ConstU64<{ up_common::constants::MIN_GAS_PRICE }>;
- type MaxOverridedAllowedLocations = ConstU32<16>;
+ type MaxXcmAllowedLocations = ConstU32<16>;
type AppPromotionDailyRate = AppPromotionDailyRate;
type DayRelayBlocks = DayRelayBlocks;
}
runtime/common/construct_runtime/mod.rsdiffbeforeafterboth--- a/runtime/common/construct_runtime/mod.rs
+++ b/runtime/common/construct_runtime/mod.rs
@@ -82,7 +82,7 @@
#[runtimes(opal, quartz)]
AppPromotion: pallet_app_promotion::{Pallet, Call, Storage, Event<T>} = 73,
- #[runtimes(opal)]
+ #[runtimes(opal, quartz)]
ForeignAssets: pallet_foreign_assets::{Pallet, Call, Storage, Event<T>} = 80,
// Frontier
runtime/quartz/Cargo.tomldiffbeforeafterboth--- a/runtime/quartz/Cargo.toml
+++ b/runtime/quartz/Cargo.toml
@@ -169,7 +169,7 @@
"pallet-maintenance/std",
]
limit-testing = ['pallet-unique/limit-testing', 'up-data-structs/limit-testing']
-quartz-runtime = ['refungible', 'app-promotion']
+quartz-runtime = ['refungible', 'app-promotion', 'foreign-assets']
refungible = []
scheduler = []
tests/src/pallet-presence.test.tsdiffbeforeafterboth--- a/tests/src/pallet-presence.test.ts
+++ b/tests/src/pallet-presence.test.ts
@@ -80,6 +80,7 @@
requiredPallets.push(
refungible,
appPromotion,
+ foreignAssets,
);
} else if (chain.eq('UNIQUE')) {
// Insert Unique additional pallets here