git.delta.rocks / unique-network / refs/commits / 2eecdab55d8c

difftreelog

Merge pull request #907 from UniqueNetwork/feature/nft-transfer-correct-weight

Yaroslav Bolyukin2023-04-19parents: #6e3cf5e #ff11326.patch.diff
in: master
feat(weight): added benchs for decompose weight

23 files changed

modifiedCargo.lockdiffbeforeafterboth
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6262,7 +6262,7 @@
 
 [[package]]
 name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
 dependencies = [
  "ethereum",
  "evm-coder",
@@ -6558,7 +6558,7 @@
 
 [[package]]
 name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
@@ -6814,7 +6814,7 @@
 
 [[package]]
 name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
 dependencies = [
  "evm-coder",
  "frame-benchmarking",
modifiedpallets/app-promotion/src/lib.rsdiffbeforeafterboth
before · pallets/app-promotion/src/lib.rs
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, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83	Perbill,84	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85	ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97	use super::*;98	use frame_support::{99		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100		traits::ReservableCurrency, weights::Weight,101	};102	use frame_system::pallet_prelude::*;103104	#[pallet::config]105	pub trait Config:106		frame_system::Config + pallet_evm::Config + pallet_configuration::Config107	{108		/// Type to interact with the native token109		type Currency: ExtendedLockableCurrency<Self::AccountId>110			+ ReservableCurrency<Self::AccountId>;111112		/// Type for interacting with collections113		type CollectionHandler: CollectionHandler<114			AccountId = Self::AccountId,115			CollectionId = CollectionId,116		>;117118		/// Type for interacting with conrtacts119		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121		/// `AccountId` for treasury122		type TreasuryAccountId: Get<Self::AccountId>;123124		/// The app's pallet id, used for deriving its sovereign account address.125		#[pallet::constant]126		type PalletId: Get<PalletId>;127128		/// In relay blocks.129		#[pallet::constant]130		type RecalculationInterval: Get<Self::BlockNumber>;131132		/// In parachain blocks.133		#[pallet::constant]134		type PendingInterval: Get<Self::BlockNumber>;135136		/// Rate of return for interval in blocks defined in `RecalculationInterval`.137		#[pallet::constant]138		type IntervalIncome: Get<Perbill>;139140		/// Decimals for the `Currency`.141		#[pallet::constant]142		type Nominal: Get<BalanceOf<Self>>;143144		/// Weight information for extrinsics in this pallet.145		type WeightInfo: WeightInfo;146147		// The relay block number provider148		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150		/// Events compatible with [`frame_system::Config::Event`].151		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152	}153154	#[pallet::pallet]155	pub struct Pallet<T>(_);156157	#[pallet::event]158	#[pallet::generate_deposit(pub(super) fn deposit_event)]159	pub enum Event<T: Config> {160		/// Staking recalculation was performed161		///162		/// # Arguments163		/// * AccountId: account of the staker.164		/// * Balance : recalculation base165		/// * Balance : total income166		StakingRecalculation(167			/// An recalculated staker168			T::AccountId,169			/// Base on which interest is calculated170			BalanceOf<T>,171			/// Amount of accrued interest172			BalanceOf<T>,173		),174175		/// Staking was performed176		///177		/// # Arguments178		/// * AccountId: account of the staker179		/// * Balance : staking amount180		Stake(T::AccountId, BalanceOf<T>),181182		/// Unstaking was performed183		///184		/// # Arguments185		/// * AccountId: account of the staker186		/// * Balance : unstaking amount187		Unstake(T::AccountId, BalanceOf<T>),188189		/// The admin was set190		///191		/// # Arguments192		/// * AccountId: account address of the admin193		SetAdmin(T::AccountId),194	}195196	#[pallet::error]197	pub enum Error<T> {198		/// Error due to action requiring admin to be set.199		AdminNotSet,200		/// No permission to perform an action.201		NoPermission,202		/// Insufficient funds to perform an action.203		NotSufficientFunds,204		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.205		PendingForBlockOverflow,206		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.207		SponsorNotSet,208		/// Errors caused by incorrect actions with a locked balance.209		IncorrectLockedBalanceOperation,210		/// Errors caused by insufficient staked balance.211		InsufficientStakedBalance,212	}213214	/// Stores the total staked amount.215	#[pallet::storage]216	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;217218	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.219	#[pallet::storage]220	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;221222	/// Stores the amount of tokens staked by account in the blocknumber.223	///224	/// * **Key1** - Staker account.225	/// * **Key2** - Relay block number when the stake was made.226	/// * **(Balance, BlockNumber)** - Balance of the stake.227	/// The number of the relay block in which we must perform the interest recalculation228	#[pallet::storage]229	pub type Staked<T: Config> = StorageNMap<230		Key = (231			Key<Blake2_128Concat, T::AccountId>,232			Key<Twox64Concat, T::BlockNumber>,233		),234		Value = (BalanceOf<T>, T::BlockNumber),235		QueryKind = ValueQuery,236	>;237238	/// Stores number of stake records for an `Account`.239	///240	/// * **Key** - Staker account.241	/// * **Value** - Amount of stakes.242	#[pallet::storage]243	pub type StakesPerAccount<T: Config> =244		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;245246	/// Pending unstake records for an `Account`.247	///248	/// * **Key** - Staker account.249	/// * **Value** - Amount of stakes.250	#[pallet::storage]251	pub type PendingUnstake<T: Config> = StorageMap<252		_,253		Twox64Concat,254		T::BlockNumber,255		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,256		ValueQuery,257	>;258259	/// Stores a key for record for which the revenue recalculation was performed.260	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.261	#[pallet::storage]262	#[pallet::getter(fn get_next_calculated_record)]263	pub type PreviousCalculatedRecord<T: Config> =264		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;265266	#[pallet::storage]267	pub(crate) type UpgradedToReserves<T: Config> =268		StorageValue<Value = bool, QueryKind = ValueQuery>;269270	#[pallet::hooks]271	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {272		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize273		/// implies the execution of a strictly limited number of relatively lightweight operations.274		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.275		fn on_initialize(current_block_number: T::BlockNumber) -> Weight276		where277			<T as frame_system::Config>::BlockNumber: From<u32>,278		{279			let block_pending = PendingUnstake::<T>::take(current_block_number);280			let counter = block_pending.len() as u32;281282			if !block_pending.is_empty() {283				block_pending.into_iter().for_each(|(staker, amount)| {284					Self::get_locked_balance(&staker).map(|b| {285						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();286						Self::set_lock_unchecked(&staker, new_state);287					});288				});289			}290291			<T as Config>::WeightInfo::on_initialize(counter)292		}293294		fn on_runtime_upgrade() -> Weight {295			<UpgradedToReserves<T>>::kill();296297			T::DbWeight::get().reads_writes(0, 1)298		}299	}300301	#[pallet::call]302	impl<T: Config> Pallet<T>303	where304		T::BlockNumber: From<u32> + Into<u32>,305		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,306	{307		/// Sets an address as the the admin.308		///309		/// # Permissions310		///311		/// * Sudo312		///313		/// # Arguments314		///315		/// * `admin`: account of the new admin.316		#[pallet::call_index(0)]317		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]318		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {319			ensure_root(origin)?;320321			<Admin<T>>::set(Some(admin.as_sub().to_owned()));322323			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));324325			Ok(())326		}327328		/// Stakes the amount of native tokens.329		/// Sets `amount` to the locked state.330		/// The maximum number of stakes for a staker is 10.331		///332		/// # Arguments333		///334		/// * `amount`: in native tokens.335		#[pallet::call_index(1)]336		#[pallet::weight(<T as Config>::WeightInfo::stake())]337		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {338			let staker_id = ensure_signed(staker)?;339340			ensure!(341				StakesPerAccount::<T>::get(&staker_id) < 10,342				Error::<T>::NoPermission343			);344345			ensure!(346				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),347				ArithmeticError::Underflow348			);349			let config = <PalletConfiguration<T>>::get();350351			let balance =352				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);353354			// checks that we can lock `amount` on the `staker` account.355			ensure!(356				amount357					<= match Self::get_locked_balance(&staker_id) {358						Some(lock) => balance359							.checked_sub(&lock.amount)360							.ok_or(ArithmeticError::Underflow)?,361						None => balance,362					},363				ArithmeticError::Underflow364			);365366			Self::add_lock_balance(&staker_id, amount)?;367368			let block_number = T::RelayBlockNumberProvider::current_block_number();369370			// Calculation of the number of recalculation periods,371			// after how much the first interest calculation should be performed for the stake372			let recalculate_after_interval: T::BlockNumber =373				if block_number % config.recalculation_interval == 0u32.into() {374					1u32.into()375				} else {376					2u32.into()377				};378379			// Сalculation of the number of the relay block380			// in which it is necessary to accrue remuneration for the stake.381			let recalc_block = (block_number / config.recalculation_interval382				+ recalculate_after_interval)383				* config.recalculation_interval;384385			<Staked<T>>::insert((&staker_id, block_number), {386				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));387				balance_and_recalc_block.0 = balance_and_recalc_block388					.0389					.checked_add(&amount)390					.ok_or(ArithmeticError::Overflow)?;391				balance_and_recalc_block.1 = recalc_block;392				balance_and_recalc_block393			});394395			<TotalStaked<T>>::set(396				<TotalStaked<T>>::get()397					.checked_add(&amount)398					.ok_or(ArithmeticError::Overflow)?,399			);400401			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);402403			Self::deposit_event(Event::Stake(staker_id, amount));404405			Ok(())406		}407408		/// Unstakes all stakes.409		/// After the end of `PendingInterval` this sum becomes completely410		/// free for further use.411		#[pallet::call_index(2)]412		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]413		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {414			let staker_id = ensure_signed(staker)?;415416			Self::unstake_all_internal(staker_id)417		}418419		/// Unstakes the amount of balance for the staker.420		/// After the end of `PendingInterval` this sum becomes completely421		/// free for further use.422		///423		///  # Arguments424		///425		/// * `staker`: staker account.426		/// * `amount`: amount of unstaked funds.427		#[pallet::call_index(8)]428		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]429		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {430			let staker_id = ensure_signed(staker)?;431432			Self::unstake_partial_internal(staker_id, amount)433		}434435		/// Sets the pallet to be the sponsor for the collection.436		///437		/// # Permissions438		///439		/// * Pallet admin440		///441		/// # Arguments442		///443		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`444		#[pallet::call_index(3)]445		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]446		pub fn sponsor_collection(447			admin: OriginFor<T>,448			collection_id: CollectionId,449		) -> DispatchResult {450			let admin_id = ensure_signed(admin)?;451			ensure!(452				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,453				Error::<T>::NoPermission454			);455456			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)457		}458459		/// Removes the pallet as the sponsor for the collection.460		/// Returns [`NoPermission`][`Error::NoPermission`]461		/// if the pallet wasn't the sponsor.462		///463		/// # Permissions464		///465		/// * Pallet admin466		///467		/// # Arguments468		///469		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`470		#[pallet::call_index(4)]471		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]472		pub fn stop_sponsoring_collection(473			admin: OriginFor<T>,474			collection_id: CollectionId,475		) -> DispatchResult {476			let admin_id = ensure_signed(admin)?;477478			ensure!(479				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,480				Error::<T>::NoPermission481			);482483			ensure!(484				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?485					== Self::account_id(),486				<Error<T>>::NoPermission487			);488			T::CollectionHandler::remove_collection_sponsor(collection_id)489		}490491		/// Sets the pallet to be the sponsor for the contract.492		///493		/// # Permissions494		///495		/// * Pallet admin496		///497		/// # Arguments498		///499		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`500		#[pallet::call_index(5)]501		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]502		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {503			let admin_id = ensure_signed(admin)?;504505			ensure!(506				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,507				Error::<T>::NoPermission508			);509510			T::ContractHandler::set_sponsor(511				T::CrossAccountId::from_sub(Self::account_id()),512				contract_id,513			)514		}515516		/// Removes the pallet as the sponsor for the contract.517		/// Returns [`NoPermission`][`Error::NoPermission`]518		/// if the pallet wasn't the sponsor.519		///520		/// # Permissions521		///522		/// * Pallet admin523		///524		/// # Arguments525		///526		/// * `contract_id`: the contract address that is sponsored by `pallet_id`527		#[pallet::call_index(6)]528		#[pallet::weight(<T as Config>::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::call_index(7)]559		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]560		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {561			let admin_id = ensure_signed(admin)?;562563			ensure!(564				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565				Error::<T>::NoPermission566			);567			let config = <PalletConfiguration<T>>::get();568569			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);570571			ensure!(572				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,573				Error::<T>::NoPermission574			);575576			// calculate the number of the current recalculation block,577			// this is necessary in order to understand which stakers we should calculate interest578			let current_recalc_block = Self::get_current_recalc_block(579				T::RelayBlockNumberProvider::current_block_number(),580				&config,581			);582583			// calculate the number of the next recalculation block,584			// this value is set for the stakers to whom the recalculation will be performed585			let next_recalc_block = current_recalc_block + config.recalculation_interval;586587			let mut storage_iterator = Self::get_next_calculated_key()588				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));589590			PreviousCalculatedRecord::<T>::set(None);591592			{593				// Address handled in the last payout loop iteration (below)594				let last_id = RefCell::new(None);595				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration596				let mut last_staked_calculated_block = Default::default();597				// Reward balance for the address in the iteration598				let income_acc = RefCell::new(BalanceOf::<T>::default());599				// Staked balance for the address in the iteration (before stake is recalculated)600				let amount_acc = RefCell::new(BalanceOf::<T>::default());601602				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout603				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout604				// loop switches to handling the next staker address:605				//   1. Transfer full reward amount to the payee606				//   2. Lock the reward in staking lock607				//   3. Update TotalStaked amount608				//   4. Issue StakingRecalculation event609				let flush_stake = || -> DispatchResult {610					if let Some(last_id) = &*last_id.borrow() {611						if !income_acc.borrow().is_zero() {612							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(613								&T::TreasuryAccountId::get(),614								last_id,615								*income_acc.borrow(),616								ExistenceRequirement::KeepAlive,617							)?;618619							Self::add_lock_balance(last_id, *income_acc.borrow())?;620							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {621								*staked = staked622									.checked_add(&*income_acc.borrow())623									.ok_or(ArithmeticError::Overflow)?;624								Ok(())625							})?;626627							Self::deposit_event(Event::StakingRecalculation(628								last_id.clone(),629								*amount_acc.borrow(),630								*income_acc.borrow(),631							));632						}633634						*income_acc.borrow_mut() = BalanceOf::<T>::default();635						*amount_acc.borrow_mut() = BalanceOf::<T>::default();636					}637					Ok(())638				};639640				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation641				// iterations in one extrinsic call642				//643				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)644				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out645				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)646				while let Some((647					(current_id, staked_block),648					(amount, next_recalc_block_for_stake),649				)) = storage_iterator.next()650				{651					// last_id is not equal current_id when we switch to handling a new staker address652					// or just start handling the very first address. In the latter case last_id will be None and653					// flush_stake will do nothing654					if last_id.borrow().as_ref() != Some(&current_id) {655						if stakers_number > 0 {656							flush_stake()?;657							*last_id.borrow_mut() = Some(current_id.clone());658							stakers_number -= 1;659						}660						// Break out if we reached the address limit661						else {662							if let Some(staker) = &*last_id.borrow() {663								// Save the last calculated record to pick up in the next extrinsic call664								PreviousCalculatedRecord::<T>::set(Some((665									staker.clone(),666									last_staked_calculated_block,667								)));668							}669							break;670						};671					};672673					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount674					if current_recalc_block >= next_recalc_block_for_stake {675						*amount_acc.borrow_mut() += amount;676						Self::recalculate_and_insert_stake(677							&current_id,678							staked_block,679							next_recalc_block,680							amount,681							((current_recalc_block - next_recalc_block_for_stake)682								/ config.recalculation_interval)683								.into() + 1,684							&mut *income_acc.borrow_mut(),685						);686					}687					last_staked_calculated_block = staked_block;688				}689				flush_stake()?;690			}691692			Ok(())693		}694	}695}696697impl<T: Config> Pallet<T> {698	/// The account address of the app promotion pot.699	///700	/// This actually does computation. If you need to keep using it, then make sure you cache the701	/// value and only call this once.702	pub fn account_id() -> T::AccountId {703		T::PalletId::get().into_account_truncating()704	}705706	/// Unstakes the balance for the staker.707	///708	/// - `staker`: staker account.709	/// - `amount`: amount of unstaked funds.710	fn unstake_partial_internal(711		staker_id: T::AccountId,712		unstaked_balance: BalanceOf<T>,713	) -> DispatchResult {714		if unstaked_balance == Default::default() {715			return Ok(());716		}717718		let config = <PalletConfiguration<T>>::get();719720		// calculate block number where the sum would be free721		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;722723		let mut pendings = <PendingUnstake<T>>::get(unpending_block);724725		// checks that we can do unstake in the block726		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);727728		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();729730		let total_staked = stakes731			.iter()732			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {733				acc + *balance734			});735736		ensure!(737			unstaked_balance <= total_staked,738			<Error<T>>::InsufficientStakedBalance739		);740741		<TotalStaked<T>>::set(742			<TotalStaked<T>>::get()743				.checked_sub(&unstaked_balance)744				.ok_or(ArithmeticError::Underflow)?,745		);746747		stakes.sort_by_key(|(block, _)| *block);748749		let mut acc_amount = unstaked_balance;750		let mut will_deleted_stakes_count = 0u8;751752		let changed_stakes = stakes753			.into_iter()754			.map_while(|(block, (balance_per_block, _))| {755				if acc_amount == <BalanceOf<T>>::default() {756					return None;757				}758				if acc_amount < balance_per_block {759					let res = (block, balance_per_block - acc_amount);760					acc_amount = <BalanceOf<T>>::default();761					return Some(res);762				} else {763					acc_amount -= balance_per_block;764					will_deleted_stakes_count += 1;765					return Some((block, <BalanceOf<T>>::default()));766				}767			})768			.collect::<Vec<_>>();769770		pendings771			.try_push((staker_id.clone(), unstaked_balance))772			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;773774		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {775			*stakes = stakes776				.checked_sub(will_deleted_stakes_count)777				.ok_or(ArithmeticError::Underflow)?;778			Ok(())779		})?;780781		changed_stakes782			.into_iter()783			.for_each(|(staked_block, current_stake_state)| {784				if current_stake_state == Default::default() {785					<Staked<T>>::remove((&staker_id, staked_block));786				} else {787					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {788						*old_stake_state = current_stake_state789					});790				}791			});792793		<PendingUnstake<T>>::insert(unpending_block, pendings);794795		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));796797		Ok(())798	}799800	/// Adds the balance to locked by the pallet.801	///802	/// - `staker`: staker account.803	/// - `amount`: amount of added locked funds.804	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {805		Self::get_locked_balance(staker)806			.map_or(<BalanceOf<T>>::default(), |l| l.amount)807			.checked_add(&amount)808			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))809			.ok_or(ArithmeticError::Overflow.into())810	}811812	/// Sets the new state of a balance locked by the pallet.813	///814	/// - `staker`: staker account.815	/// - `amount`: amount of locked funds.816	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {817		if amount.is_zero() {818			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(819				LOCK_IDENTIFIER,820				&staker,821			);822		} else {823			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(824				LOCK_IDENTIFIER,825				staker,826				amount,827				WithdrawReasons::all(),828			)829		}830	}831832	/// Returns the balance locked by the pallet for the staker.833	///834	/// - `staker`: staker account.835	pub fn get_locked_balance(836		staker: impl EncodeLike<T::AccountId>,837	) -> Option<BalanceLock<BalanceOf<T>>> {838		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)839			.into_iter()840			.find(|l| l.id == LOCK_IDENTIFIER)841	}842843	/// Returns the total staked balance for the staker.844	///845	/// - `staker`: staker account.846	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {847		let staked = Staked::<T>::iter_prefix((staker,))848			.into_iter()849			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {850				acc + amount851			});852		if staked != <BalanceOf<T>>::default() {853			Some(staked)854		} else {855			None856		}857	}858859	/// Returns all relay block numbers when stake was made,860	/// the amount of the stake.861	///862	/// - `staker`: staker account.863	pub fn total_staked_by_id_per_block(864		staker: impl EncodeLike<T::AccountId>,865	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {866		let mut staked = Staked::<T>::iter_prefix((staker,))867			.into_iter()868			.map(|(block, (amount, _))| (block, amount))869			.collect::<Vec<_>>();870		staked.sort_by_key(|(block, _)| *block);871		if !staked.is_empty() {872			Some(staked)873		} else {874			None875		}876	}877878	/// Returns the total staked balance for the staker.879	/// If `staker` is `None`, returns the total amount staked.880	/// - `staker`: staker account.881	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {882		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {883			Self::total_staked_by_id(s.as_sub())884		})885	}886887	// pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {888	// 	Self::get_locked_balance(staker.as_sub())889	// 		.map(|l| l.amount)890	// 		.unwrap_or_default()891	// }892893	/// Returns all relay block numbers when stake was made,894	/// the amount of the stake.895	///896	/// - `staker`: staker account.897	pub fn cross_id_total_staked_per_block(898		staker: T::CrossAccountId,899	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {900		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()901	}902903	fn recalculate_and_insert_stake(904		staker: &T::AccountId,905		staked_block: T::BlockNumber,906		next_recalc_block: T::BlockNumber,907		base: BalanceOf<T>,908		iters: u32,909		income_acc: &mut BalanceOf<T>,910	) {911		let income = Self::calculate_income(base, iters);912913		base.checked_add(&income).map(|res| {914			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));915			*income_acc += income;916		});917	}918919	fn calculate_income<I>(base: I, iters: u32) -> I920	where921		I: EncodeLike<BalanceOf<T>> + Balance,922	{923		let config = <PalletConfiguration<T>>::get();924		let mut income = base;925926		(0..iters).for_each(|_| income += config.interval_income * income);927928		income - base929	}930931	/// Get relay block number rounded down to multiples of config.recalculation_interval.932	/// We need it to reward stakers in integer parts of recalculation_interval933	fn get_current_recalc_block(934		current_relay_block: T::BlockNumber,935		config: &PalletConfiguration<T>,936	) -> T::BlockNumber {937		(current_relay_block / config.recalculation_interval) * config.recalculation_interval938	}939940	fn get_next_calculated_key() -> Option<Vec<u8>> {941		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))942	}943}944945impl<T: Config> Pallet<T>946where947	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,948{949	/// Returns the amount reserved by the pending.950	/// If `staker` is `None`, returns the total pending.951	///952	/// -`staker`: staker account.953	///954	/// Since user funds are not transferred anywhere by staking, overflow protection is provided955	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,956	/// the staker must have more funds on his account than the maximum set for `Balance` type.957	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {958		staker.map_or(959			PendingUnstake::<T>::iter_values()960				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))961				.sum(),962			|s| {963				PendingUnstake::<T>::iter_values()964					.flatten()965					.filter_map(|(id, amount)| {966						if id == *s.as_sub() {967							Some(amount)968						} else {969							None970						}971					})972					.sum()973			},974		)975	}976977	/// Returns all parachain block numbers when unreserve is expected,978	/// the amount of the unreserved funds.979	///980	/// - `staker`: staker account.981	pub fn cross_id_pending_unstake_per_block(982		staker: T::CrossAccountId,983	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {984		let mut unsorted_res = vec![];985		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {986			pendings.into_iter().for_each(|(id, amount)| {987				if id == *staker.as_sub() {988					unsorted_res.push((block, amount));989				};990			})991		});992993		unsorted_res.sort_by_key(|(block, _)| *block);994		unsorted_res995	}996997	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {998		let config = <PalletConfiguration<T>>::get();9991000		// calculate block number where the sum would be free1001		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;10021003		let mut pendings = <PendingUnstake<T>>::get(block);10041005		// checks that we can do unstake in the block1006		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);10071008		let mut total_stakes = 0u64;10091010		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1011			.map(|(_, (amount, _))| {1012				total_stakes += 1;1013				amount1014			})1015			.sum();10161017		if total_staked.is_zero() {1018			return Ok(());1019		}10201021		pendings1022			.try_push((staker_id.clone(), total_staked))1023			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;10241025		<PendingUnstake<T>>::insert(block, pendings);10261027		TotalStaked::<T>::set(1028			TotalStaked::<T>::get()1029				.checked_sub(&total_staked)1030				.ok_or(ArithmeticError::Underflow)?,1031		);10321033		StakesPerAccount::<T>::remove(&staker_id);10341035		Self::deposit_event(Event::Unstake(staker_id, total_staked));10361037		Ok(())1038	}1039}
after · pallets/app-promotion/src/lib.rs
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, BoundedVec,76};7778use weights::WeightInfo;7980pub use pallet::*;81use pallet_evm::account::CrossAccountId;82use sp_runtime::{83	Perbill,84	traits::{BlockNumberProvider, CheckedAdd, CheckedSub, AccountIdConversion, Zero},85	ArithmeticError,86};8788pub const LOCK_IDENTIFIER: [u8; 8] = *b"appstake";8990const PENDING_LIMIT_PER_BLOCK: u32 = 3;9192type BalanceOf<T> =93	<<T as Config>::Currency as Currency<<T as frame_system::Config>::AccountId>>::Balance;9495#[frame_support::pallet]96pub mod pallet {97	use super::*;98	use frame_support::{99		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, PalletId,100		traits::ReservableCurrency, weights::Weight,101	};102	use frame_system::pallet_prelude::*;103104	#[pallet::config]105	pub trait Config:106		frame_system::Config + pallet_evm::Config + pallet_configuration::Config107	{108		/// Type to interact with the native token109		type Currency: ExtendedLockableCurrency<Self::AccountId>110			+ ReservableCurrency<Self::AccountId>;111112		/// Type for interacting with collections113		type CollectionHandler: CollectionHandler<114			AccountId = Self::AccountId,115			CollectionId = CollectionId,116		>;117118		/// Type for interacting with conrtacts119		type ContractHandler: ContractHandler<AccountId = Self::CrossAccountId, ContractId = H160>;120121		/// `AccountId` for treasury122		type TreasuryAccountId: Get<Self::AccountId>;123124		/// The app's pallet id, used for deriving its sovereign account address.125		#[pallet::constant]126		type PalletId: Get<PalletId>;127128		/// In relay blocks.129		#[pallet::constant]130		type RecalculationInterval: Get<Self::BlockNumber>;131132		/// In parachain blocks.133		#[pallet::constant]134		type PendingInterval: Get<Self::BlockNumber>;135136		/// Rate of return for interval in blocks defined in `RecalculationInterval`.137		#[pallet::constant]138		type IntervalIncome: Get<Perbill>;139140		/// Decimals for the `Currency`.141		#[pallet::constant]142		type Nominal: Get<BalanceOf<Self>>;143144		/// Weight information for extrinsics in this pallet.145		type WeightInfo: WeightInfo;146147		// The relay block number provider148		type RelayBlockNumberProvider: BlockNumberProvider<BlockNumber = Self::BlockNumber>;149150		/// Events compatible with [`frame_system::Config::Event`].151		type RuntimeEvent: IsType<<Self as frame_system::Config>::RuntimeEvent> + From<Event<Self>>;152	}153154	#[pallet::pallet]155	pub struct Pallet<T>(_);156157	#[pallet::event]158	#[pallet::generate_deposit(pub(super) fn deposit_event)]159	pub enum Event<T: Config> {160		/// Staking recalculation was performed161		///162		/// # Arguments163		/// * AccountId: account of the staker.164		/// * Balance : recalculation base165		/// * Balance : total income166		StakingRecalculation(167			/// An recalculated staker168			T::AccountId,169			/// Base on which interest is calculated170			BalanceOf<T>,171			/// Amount of accrued interest172			BalanceOf<T>,173		),174175		/// Staking was performed176		///177		/// # Arguments178		/// * AccountId: account of the staker179		/// * Balance : staking amount180		Stake(T::AccountId, BalanceOf<T>),181182		/// Unstaking was performed183		///184		/// # Arguments185		/// * AccountId: account of the staker186		/// * Balance : unstaking amount187		Unstake(T::AccountId, BalanceOf<T>),188189		/// The admin was set190		///191		/// # Arguments192		/// * AccountId: account address of the admin193		SetAdmin(T::AccountId),194	}195196	#[pallet::error]197	pub enum Error<T> {198		/// Error due to action requiring admin to be set.199		AdminNotSet,200		/// No permission to perform an action.201		NoPermission,202		/// Insufficient funds to perform an action.203		NotSufficientFunds,204		/// Occurs when a pending unstake cannot be added in this block. PENDING_LIMIT_PER_BLOCK` limits exceeded.205		PendingForBlockOverflow,206		/// The error is due to the fact that the collection/contract must already be sponsored in order to perform the action.207		SponsorNotSet,208		/// Errors caused by incorrect actions with a locked balance.209		IncorrectLockedBalanceOperation,210		/// Errors caused by insufficient staked balance.211		InsufficientStakedBalance,212	}213214	/// Stores the total staked amount.215	#[pallet::storage]216	pub type TotalStaked<T: Config> = StorageValue<Value = BalanceOf<T>, QueryKind = ValueQuery>;217218	/// Stores the `admin` account. Some extrinsics can only be executed if they were signed by `admin`.219	#[pallet::storage]220	pub type Admin<T: Config> = StorageValue<Value = T::AccountId, QueryKind = OptionQuery>;221222	/// Stores the amount of tokens staked by account in the blocknumber.223	///224	/// * **Key1** - Staker account.225	/// * **Key2** - Relay block number when the stake was made.226	/// * **(Balance, BlockNumber)** - Balance of the stake.227	/// The number of the relay block in which we must perform the interest recalculation228	#[pallet::storage]229	pub type Staked<T: Config> = StorageNMap<230		Key = (231			Key<Blake2_128Concat, T::AccountId>,232			Key<Twox64Concat, T::BlockNumber>,233		),234		Value = (BalanceOf<T>, T::BlockNumber),235		QueryKind = ValueQuery,236	>;237238	/// Stores number of stake records for an `Account`.239	///240	/// * **Key** - Staker account.241	/// * **Value** - Amount of stakes.242	#[pallet::storage]243	pub type StakesPerAccount<T: Config> =244		StorageMap<_, Blake2_128Concat, T::AccountId, u8, ValueQuery>;245246	/// Pending unstake records for an `Account`.247	///248	/// * **Key** - Staker account.249	/// * **Value** - Amount of stakes.250	#[pallet::storage]251	pub type PendingUnstake<T: Config> = StorageMap<252		_,253		Twox64Concat,254		T::BlockNumber,255		BoundedVec<(T::AccountId, BalanceOf<T>), ConstU32<PENDING_LIMIT_PER_BLOCK>>,256		ValueQuery,257	>;258259	/// Stores a key for record for which the revenue recalculation was performed.260	/// If `None`, then recalculation has not yet been performed or calculations have been completed for all stakers.261	#[pallet::storage]262	#[pallet::getter(fn get_next_calculated_record)]263	pub type PreviousCalculatedRecord<T: Config> =264		StorageValue<Value = (T::AccountId, T::BlockNumber), QueryKind = OptionQuery>;265266	#[pallet::storage]267	pub(crate) type UpgradedToReserves<T: Config> =268		StorageValue<Value = bool, QueryKind = ValueQuery>;269270	#[pallet::hooks]271	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {272		/// Block overflow is impossible due to the fact that the unstake algorithm in on_initialize273		/// implies the execution of a strictly limited number of relatively lightweight operations.274		/// A separate benchmark has been implemented to scale the weight depending on the number of pendings.275		fn on_initialize(current_block_number: T::BlockNumber) -> Weight276		where277			<T as frame_system::Config>::BlockNumber: From<u32>,278		{279			let block_pending = PendingUnstake::<T>::take(current_block_number);280			let counter = block_pending.len() as u32;281282			if !block_pending.is_empty() {283				block_pending.into_iter().for_each(|(staker, amount)| {284					Self::get_locked_balance(&staker).map(|b| {285						let new_state = b.amount.checked_sub(&amount).unwrap_or_default();286						Self::set_lock_unchecked(&staker, new_state);287					});288				});289			}290291			<T as Config>::WeightInfo::on_initialize(counter)292		}293294		fn on_runtime_upgrade() -> Weight {295			<UpgradedToReserves<T>>::kill();296297			T::DbWeight::get().reads_writes(0, 1)298		}299	}300301	#[pallet::call]302	impl<T: Config> Pallet<T>303	where304		T::BlockNumber: From<u32> + Into<u32>,305		<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum + From<u128>,306	{307		/// Sets an address as the the admin.308		///309		/// # Permissions310		///311		/// * Sudo312		///313		/// # Arguments314		///315		/// * `admin`: account of the new admin.316		#[pallet::call_index(0)]317		#[pallet::weight(<T as Config>::WeightInfo::set_admin_address())]318		pub fn set_admin_address(origin: OriginFor<T>, admin: T::CrossAccountId) -> DispatchResult {319			ensure_root(origin)?;320321			<Admin<T>>::set(Some(admin.as_sub().to_owned()));322323			Self::deposit_event(Event::SetAdmin(admin.as_sub().to_owned()));324325			Ok(())326		}327328		/// Stakes the amount of native tokens.329		/// Sets `amount` to the locked state.330		/// The maximum number of stakes for a staker is 10.331		///332		/// # Arguments333		///334		/// * `amount`: in native tokens.335		#[pallet::call_index(1)]336		#[pallet::weight(<T as Config>::WeightInfo::stake())]337		pub fn stake(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {338			let staker_id = ensure_signed(staker)?;339340			ensure!(341				StakesPerAccount::<T>::get(&staker_id) < 10,342				Error::<T>::NoPermission343			);344345			ensure!(346				amount >= <BalanceOf<T>>::from(100u128) * T::Nominal::get(),347				ArithmeticError::Underflow348			);349			let config = <PalletConfiguration<T>>::get();350351			let balance =352				<<T as Config>::Currency as Currency<T::AccountId>>::free_balance(&staker_id);353354			// checks that we can lock `amount` on the `staker` account.355			ensure!(356				amount357					<= match Self::get_locked_balance(&staker_id) {358						Some(lock) => balance359							.checked_sub(&lock.amount)360							.ok_or(ArithmeticError::Underflow)?,361						None => balance,362					},363				ArithmeticError::Underflow364			);365366			Self::add_lock_balance(&staker_id, amount)?;367368			let block_number = T::RelayBlockNumberProvider::current_block_number();369370			// Calculation of the number of recalculation periods,371			// after how much the first interest calculation should be performed for the stake372			let recalculate_after_interval: T::BlockNumber =373				if block_number % config.recalculation_interval == 0u32.into() {374					1u32.into()375				} else {376					2u32.into()377				};378379			// Сalculation of the number of the relay block380			// in which it is necessary to accrue remuneration for the stake.381			let recalc_block = (block_number / config.recalculation_interval382				+ recalculate_after_interval)383				* config.recalculation_interval;384385			<Staked<T>>::insert((&staker_id, block_number), {386				let mut balance_and_recalc_block = <Staked<T>>::get((&staker_id, block_number));387				balance_and_recalc_block.0 = balance_and_recalc_block388					.0389					.checked_add(&amount)390					.ok_or(ArithmeticError::Overflow)?;391				balance_and_recalc_block.1 = recalc_block;392				balance_and_recalc_block393			});394395			<TotalStaked<T>>::set(396				<TotalStaked<T>>::get()397					.checked_add(&amount)398					.ok_or(ArithmeticError::Overflow)?,399			);400401			StakesPerAccount::<T>::mutate(&staker_id, |stakes| *stakes += 1);402403			Self::deposit_event(Event::Stake(staker_id, amount));404405			Ok(())406		}407408		/// Unstakes all stakes.409		/// After the end of `PendingInterval` this sum becomes completely410		/// free for further use.411		#[pallet::call_index(2)]412		#[pallet::weight(<T as Config>::WeightInfo::unstake_all())]413		pub fn unstake_all(staker: OriginFor<T>) -> DispatchResult {414			let staker_id = ensure_signed(staker)?;415416			Self::unstake_all_internal(staker_id)417		}418419		/// Unstakes the amount of balance for the staker.420		/// After the end of `PendingInterval` this sum becomes completely421		/// free for further use.422		///423		///  # Arguments424		///425		/// * `staker`: staker account.426		/// * `amount`: amount of unstaked funds.427		#[pallet::call_index(8)]428		#[pallet::weight(<T as Config>::WeightInfo::unstake_partial())]429		pub fn unstake_partial(staker: OriginFor<T>, amount: BalanceOf<T>) -> DispatchResult {430			let staker_id = ensure_signed(staker)?;431432			Self::unstake_partial_internal(staker_id, amount)433		}434435		/// Sets the pallet to be the sponsor for the collection.436		///437		/// # Permissions438		///439		/// * Pallet admin440		///441		/// # Arguments442		///443		/// * `collection_id`: ID of the collection that will be sponsored by `pallet_id`444		#[pallet::call_index(3)]445		#[pallet::weight(<T as Config>::WeightInfo::sponsor_collection())]446		pub fn sponsor_collection(447			admin: OriginFor<T>,448			collection_id: CollectionId,449		) -> DispatchResult {450			let admin_id = ensure_signed(admin)?;451			ensure!(452				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,453				Error::<T>::NoPermission454			);455456			T::CollectionHandler::set_sponsor(Self::account_id(), collection_id)457		}458459		/// Removes the pallet as the sponsor for the collection.460		/// Returns [`NoPermission`][`Error::NoPermission`]461		/// if the pallet wasn't the sponsor.462		///463		/// # Permissions464		///465		/// * Pallet admin466		///467		/// # Arguments468		///469		/// * `collection_id`: ID of the collection that is sponsored by `pallet_id`470		#[pallet::call_index(4)]471		#[pallet::weight(<T as Config>::WeightInfo::stop_sponsoring_collection())]472		pub fn stop_sponsoring_collection(473			admin: OriginFor<T>,474			collection_id: CollectionId,475		) -> DispatchResult {476			let admin_id = ensure_signed(admin)?;477478			ensure!(479				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,480				Error::<T>::NoPermission481			);482483			ensure!(484				T::CollectionHandler::sponsor(collection_id)?.ok_or(<Error<T>>::SponsorNotSet)?485					== Self::account_id(),486				<Error<T>>::NoPermission487			);488			T::CollectionHandler::remove_collection_sponsor(collection_id)489		}490491		/// Sets the pallet to be the sponsor for the contract.492		///493		/// # Permissions494		///495		/// * Pallet admin496		///497		/// # Arguments498		///499		/// * `contract_id`: the contract address that will be sponsored by `pallet_id`500		#[pallet::call_index(5)]501		#[pallet::weight(<T as Config>::WeightInfo::sponsor_contract())]502		pub fn sponsor_contract(admin: OriginFor<T>, contract_id: H160) -> DispatchResult {503			let admin_id = ensure_signed(admin)?;504505			ensure!(506				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,507				Error::<T>::NoPermission508			);509510			T::ContractHandler::set_sponsor(511				T::CrossAccountId::from_sub(Self::account_id()),512				contract_id,513			)514		}515516		/// Removes the pallet as the sponsor for the contract.517		/// Returns [`NoPermission`][`Error::NoPermission`]518		/// if the pallet wasn't the sponsor.519		///520		/// # Permissions521		///522		/// * Pallet admin523		///524		/// # Arguments525		///526		/// * `contract_id`: the contract address that is sponsored by `pallet_id`527		#[pallet::call_index(6)]528		#[pallet::weight(<T as Config>::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::call_index(7)]559		#[pallet::weight(<T as Config>::WeightInfo::payout_stakers(stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS) as u32))]560		pub fn payout_stakers(admin: OriginFor<T>, stakers_number: Option<u8>) -> DispatchResult {561			let admin_id = ensure_signed(admin)?;562563			ensure!(564				admin_id == Admin::<T>::get().ok_or(Error::<T>::AdminNotSet)?,565				Error::<T>::NoPermission566			);567			let config = <PalletConfiguration<T>>::get();568569			let mut stakers_number = stakers_number.unwrap_or(DEFAULT_NUMBER_PAYOUTS);570571			ensure!(572				stakers_number <= config.max_stakers_per_calculation && stakers_number != 0,573				Error::<T>::NoPermission574			);575576			// calculate the number of the current recalculation block,577			// this is necessary in order to understand which stakers we should calculate interest578			let current_recalc_block = Self::get_current_recalc_block(579				T::RelayBlockNumberProvider::current_block_number(),580				&config,581			);582583			// calculate the number of the next recalculation block,584			// this value is set for the stakers to whom the recalculation will be performed585			let next_recalc_block = current_recalc_block + config.recalculation_interval;586587			let mut storage_iterator = Self::get_next_calculated_key()588				.map_or(Staked::<T>::iter(), |key| Staked::<T>::iter_from(key));589590			PreviousCalculatedRecord::<T>::set(None);591592			{593				// Address handled in the last payout loop iteration (below)594				let last_id = RefCell::new(None);595				// Block number (as a part of the key) for which calculation was performed in the last payout loop iteration596				let mut last_staked_calculated_block = Default::default();597				// Reward balance for the address in the iteration598				let income_acc = RefCell::new(BalanceOf::<T>::default());599				// Staked balance for the address in the iteration (before stake is recalculated)600				let amount_acc = RefCell::new(BalanceOf::<T>::default());601602				// This closure is used to finalize handling single staker address in each of the two conditions: (1) when we break out of the payout603				// loop because we reached the number of stakes for rewarding, (2) When all stakes by the single address are handled and the payout604				// loop switches to handling the next staker address:605				//   1. Transfer full reward amount to the payee606				//   2. Lock the reward in staking lock607				//   3. Update TotalStaked amount608				//   4. Issue StakingRecalculation event609				let flush_stake = || -> DispatchResult {610					if let Some(last_id) = &*last_id.borrow() {611						if !income_acc.borrow().is_zero() {612							<<T as Config>::Currency as Currency<T::AccountId>>::transfer(613								&T::TreasuryAccountId::get(),614								last_id,615								*income_acc.borrow(),616								ExistenceRequirement::KeepAlive,617							)?;618619							Self::add_lock_balance(last_id, *income_acc.borrow())?;620							<TotalStaked<T>>::try_mutate(|staked| -> DispatchResult {621								*staked = staked622									.checked_add(&*income_acc.borrow())623									.ok_or(ArithmeticError::Overflow)?;624								Ok(())625							})?;626627							Self::deposit_event(Event::StakingRecalculation(628								last_id.clone(),629								*amount_acc.borrow(),630								*income_acc.borrow(),631							));632						}633634						*income_acc.borrow_mut() = BalanceOf::<T>::default();635						*amount_acc.borrow_mut() = BalanceOf::<T>::default();636					}637					Ok(())638				};639640				// Reward payment loop. Should loop for no more than config.max_stakers_per_calculation641				// iterations in one extrinsic call642				//643				// stakers_number - keeps the remaining number of iterations (staker addresses to handle)644				// next_recalc_block_for_stake - is taken from the state and stores the starting relay block from which reward should be paid out645				// income_acc - stores the reward amount to pay to the staker address (accumulates over all address stake records)646				while let Some((647					(current_id, staked_block),648					(amount, next_recalc_block_for_stake),649				)) = storage_iterator.next()650				{651					// last_id is not equal current_id when we switch to handling a new staker address652					// or just start handling the very first address. In the latter case last_id will be None and653					// flush_stake will do nothing654					if last_id.borrow().as_ref() != Some(&current_id) {655						if stakers_number > 0 {656							flush_stake()?;657							*last_id.borrow_mut() = Some(current_id.clone());658							stakers_number -= 1;659						}660						// Break out if we reached the address limit661						else {662							if let Some(staker) = &*last_id.borrow() {663								// Save the last calculated record to pick up in the next extrinsic call664								PreviousCalculatedRecord::<T>::set(Some((665									staker.clone(),666									last_staked_calculated_block,667								)));668							}669							break;670						};671					};672673					// Increase accumulated reward for current address and update current staking record, i.e. (address, staked_block) -> amount674					if current_recalc_block >= next_recalc_block_for_stake {675						*amount_acc.borrow_mut() += amount;676						Self::recalculate_and_insert_stake(677							&current_id,678							staked_block,679							next_recalc_block,680							amount,681							((current_recalc_block - next_recalc_block_for_stake)682								/ config.recalculation_interval)683								.into() + 1,684							&mut *income_acc.borrow_mut(),685						);686					}687					last_staked_calculated_block = staked_block;688				}689				flush_stake()?;690			}691692			Ok(())693		}694	}695}696697impl<T: Config> Pallet<T> {698	/// The account address of the app promotion pot.699	///700	/// This actually does computation. If you need to keep using it, then make sure you cache the701	/// value and only call this once.702	pub fn account_id() -> T::AccountId {703		T::PalletId::get().into_account_truncating()704	}705706	/// Unstakes the balance for the staker.707	///708	/// - `staker`: staker account.709	/// - `amount`: amount of unstaked funds.710	fn unstake_partial_internal(711		staker_id: T::AccountId,712		unstaked_balance: BalanceOf<T>,713	) -> DispatchResult {714		if unstaked_balance == Default::default() {715			return Ok(());716		}717718		let config = <PalletConfiguration<T>>::get();719720		// calculate block number where the sum would be free721		let unpending_block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;722723		let mut pendings = <PendingUnstake<T>>::get(unpending_block);724725		// checks that we can do unstake in the block726		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);727728		let mut stakes = Staked::<T>::iter_prefix((&staker_id,)).collect::<Vec<_>>();729730		let total_staked = stakes731			.iter()732			.fold(<BalanceOf<T>>::default(), |acc, (_, (balance, _))| {733				acc + *balance734			});735736		ensure!(737			unstaked_balance <= total_staked,738			<Error<T>>::InsufficientStakedBalance739		);740741		<TotalStaked<T>>::set(742			<TotalStaked<T>>::get()743				.checked_sub(&unstaked_balance)744				.ok_or(ArithmeticError::Underflow)?,745		);746747		stakes.sort_by_key(|(block, _)| *block);748749		let mut acc_amount = unstaked_balance;750		let mut will_deleted_stakes_count = 0u8;751752		let changed_stakes = stakes753			.into_iter()754			.map_while(|(block, (balance_per_block, _))| {755				if acc_amount == <BalanceOf<T>>::default() {756					return None;757				}758				if acc_amount < balance_per_block {759					let res = (block, balance_per_block - acc_amount);760					acc_amount = <BalanceOf<T>>::default();761					return Some(res);762				} else {763					acc_amount -= balance_per_block;764					will_deleted_stakes_count += 1;765					return Some((block, <BalanceOf<T>>::default()));766				}767			})768			.collect::<Vec<_>>();769770		pendings771			.try_push((staker_id.clone(), unstaked_balance))772			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;773774		StakesPerAccount::<T>::try_mutate(&staker_id, |stakes| -> DispatchResult {775			*stakes = stakes776				.checked_sub(will_deleted_stakes_count)777				.ok_or(ArithmeticError::Underflow)?;778			Ok(())779		})?;780781		changed_stakes782			.into_iter()783			.for_each(|(staked_block, current_stake_state)| {784				if current_stake_state == Default::default() {785					<Staked<T>>::remove((&staker_id, staked_block));786				} else {787					<Staked<T>>::mutate((&staker_id, staked_block), |(old_stake_state, _)| {788						*old_stake_state = current_stake_state789					});790				}791			});792793		<PendingUnstake<T>>::insert(unpending_block, pendings);794795		Self::deposit_event(Event::Unstake(staker_id, unstaked_balance));796797		Ok(())798	}799800	/// Adds the balance to locked by the pallet.801	///802	/// - `staker`: staker account.803	/// - `amount`: amount of added locked funds.804	fn add_lock_balance(staker: &T::AccountId, amount: BalanceOf<T>) -> DispatchResult {805		Self::get_locked_balance(staker)806			.map_or(<BalanceOf<T>>::default(), |l| l.amount)807			.checked_add(&amount)808			.map(|new_lock| Self::set_lock_unchecked(staker, new_lock))809			.ok_or(ArithmeticError::Overflow.into())810	}811812	/// Sets the new state of a balance locked by the pallet.813	///814	/// - `staker`: staker account.815	/// - `amount`: amount of locked funds.816	fn set_lock_unchecked(staker: &T::AccountId, amount: BalanceOf<T>) {817		if amount.is_zero() {818			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::remove_lock(819				LOCK_IDENTIFIER,820				&staker,821			);822		} else {823			<<T as Config>::Currency as LockableCurrency<T::AccountId>>::set_lock(824				LOCK_IDENTIFIER,825				staker,826				amount,827				WithdrawReasons::all(),828			)829		}830	}831832	/// Returns the balance locked by the pallet for the staker.833	///834	/// - `staker`: staker account.835	pub fn get_locked_balance(836		staker: impl EncodeLike<T::AccountId>,837	) -> Option<BalanceLock<BalanceOf<T>>> {838		<<T as Config>::Currency as ExtendedLockableCurrency<T::AccountId>>::locks(staker)839			.into_iter()840			.find(|l| l.id == LOCK_IDENTIFIER)841	}842843	/// Returns the total staked balance for the staker.844	///845	/// - `staker`: staker account.846	pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {847		let staked = Staked::<T>::iter_prefix((staker,))848			.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {849				acc + amount850			});851		if staked != <BalanceOf<T>>::default() {852			Some(staked)853		} else {854			None855		}856	}857858	/// Returns all relay block numbers when stake was made,859	/// the amount of the stake.860	///861	/// - `staker`: staker account.862	pub fn total_staked_by_id_per_block(863		staker: impl EncodeLike<T::AccountId>,864	) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {865		let mut staked = Staked::<T>::iter_prefix((staker,))866			.map(|(block, (amount, _))| (block, amount))867			.collect::<Vec<_>>();868		staked.sort_by_key(|(block, _)| *block);869		if !staked.is_empty() {870			Some(staked)871		} else {872			None873		}874	}875876	/// Returns the total staked balance for the staker.877	/// If `staker` is `None`, returns the total amount staked.878	/// - `staker`: staker account.879	pub fn cross_id_total_staked(staker: Option<T::CrossAccountId>) -> Option<BalanceOf<T>> {880		staker.map_or(Some(<TotalStaked<T>>::get()), |s| {881			Self::total_staked_by_id(s.as_sub())882		})883	}884885	/// Returns all relay block numbers when stake was made,886	/// the amount of the stake.887	///888	/// - `staker`: staker account.889	pub fn cross_id_total_staked_per_block(890		staker: T::CrossAccountId,891	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {892		Self::total_staked_by_id_per_block(staker.as_sub()).unwrap_or_default()893	}894895	fn recalculate_and_insert_stake(896		staker: &T::AccountId,897		staked_block: T::BlockNumber,898		next_recalc_block: T::BlockNumber,899		base: BalanceOf<T>,900		iters: u32,901		income_acc: &mut BalanceOf<T>,902	) {903		let income = Self::calculate_income(base, iters);904905		base.checked_add(&income).map(|res| {906			<Staked<T>>::insert((staker, staked_block), (res, next_recalc_block));907			*income_acc += income;908		});909	}910911	fn calculate_income<I>(base: I, iters: u32) -> I912	where913		I: EncodeLike<BalanceOf<T>> + Balance,914	{915		let config = <PalletConfiguration<T>>::get();916		let mut income = base;917918		(0..iters).for_each(|_| income += config.interval_income * income);919920		income - base921	}922923	/// Get relay block number rounded down to multiples of config.recalculation_interval.924	/// We need it to reward stakers in integer parts of recalculation_interval925	fn get_current_recalc_block(926		current_relay_block: T::BlockNumber,927		config: &PalletConfiguration<T>,928	) -> T::BlockNumber {929		(current_relay_block / config.recalculation_interval) * config.recalculation_interval930	}931932	fn get_next_calculated_key() -> Option<Vec<u8>> {933		Self::get_next_calculated_record().map(|key| Staked::<T>::hashed_key_for(key))934	}935}936937impl<T: Config> Pallet<T>938where939	<<T as Config>::Currency as Currency<T::AccountId>>::Balance: Sum,940{941	/// Returns the amount reserved by the pending.942	/// If `staker` is `None`, returns the total pending.943	///944	/// -`staker`: staker account.945	///946	/// Since user funds are not transferred anywhere by staking, overflow protection is provided947	/// at the level of the associated type `Balance` of `Currency` trait. In order to overflow,948	/// the staker must have more funds on his account than the maximum set for `Balance` type.949	pub fn cross_id_pending_unstake(staker: Option<T::CrossAccountId>) -> BalanceOf<T> {950		staker.map_or(951			PendingUnstake::<T>::iter_values()952				.flat_map(|pendings| pendings.into_iter().map(|(_, amount)| amount))953				.sum(),954			|s| {955				PendingUnstake::<T>::iter_values()956					.flatten()957					.filter_map(|(id, amount)| {958						if id == *s.as_sub() {959							Some(amount)960						} else {961							None962						}963					})964					.sum()965			},966		)967	}968969	/// Returns all parachain block numbers when unreserve is expected,970	/// the amount of the unreserved funds.971	///972	/// - `staker`: staker account.973	pub fn cross_id_pending_unstake_per_block(974		staker: T::CrossAccountId,975	) -> Vec<(T::BlockNumber, BalanceOf<T>)> {976		let mut unsorted_res = vec![];977		PendingUnstake::<T>::iter().for_each(|(block, pendings)| {978			pendings.into_iter().for_each(|(id, amount)| {979				if id == *staker.as_sub() {980					unsorted_res.push((block, amount));981				};982			})983		});984985		unsorted_res.sort_by_key(|(block, _)| *block);986		unsorted_res987	}988989	fn unstake_all_internal(staker_id: T::AccountId) -> DispatchResult {990		let config = <PalletConfiguration<T>>::get();991992		// calculate block number where the sum would be free993		let block = <frame_system::Pallet<T>>::block_number() + config.pending_interval;994995		let mut pendings = <PendingUnstake<T>>::get(block);996997		// checks that we can do unstake in the block998		ensure!(!pendings.is_full(), Error::<T>::PendingForBlockOverflow);9991000		let mut total_stakes = 0u64;10011002		let total_staked: BalanceOf<T> = Staked::<T>::drain_prefix((&staker_id,))1003			.map(|(_, (amount, _))| {1004				total_stakes += 1;1005				amount1006			})1007			.sum();10081009		if total_staked.is_zero() {1010			return Ok(());1011		}10121013		pendings1014			.try_push((staker_id.clone(), total_staked))1015			.map_err(|_| Error::<T>::PendingForBlockOverflow)?;10161017		<PendingUnstake<T>>::insert(block, pendings);10181019		TotalStaked::<T>::set(1020			TotalStaked::<T>::get()1021				.checked_sub(&total_staked)1022				.ok_or(ArithmeticError::Underflow)?,1023		);10241025		StakesPerAccount::<T>::remove(&staker_id);10261027		Self::deposit_event(Event::Unstake(staker_id, total_staked));10281029		Ok(())1030	}1031}
modifiedpallets/common/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.14] - 2023-03-28
+
+### Added
+
+- Added benchmark to check if user is contained in AllowList (`check_accesslist()`).
+
 ## [0.1.13] - 2023-01-20
 
 ### Changed
modifiedpallets/common/Cargo.tomldiffbeforeafterboth
--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/common/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -22,8 +22,9 @@
 use frame_benchmarking::{benchmarks, account};
 use up_data_structs::{
 	CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,
-	PropertyValue, CollectionPermissions, NestingPermissions, MAX_COLLECTION_NAME_LENGTH,
-	MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
+	PropertyValue, CollectionPermissions, NestingPermissions, AccessMode,
+	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+	MAX_PROPERTIES_PER_ITEM,
 };
 use frame_support::{
 	traits::{Currency, Get},
@@ -193,4 +194,28 @@
 		<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
 		let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
 	}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}
+
+	check_accesslist{
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			sender: cross_from_sub(owner);
+		};
+
+		let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;
+			<Pallet<T>>::update_permissions(
+				&sender,
+				&mut collection_handle,
+				CollectionPermissions { access: Some(AccessMode::AllowList), ..Default::default() }
+			)?;
+
+		<Pallet<T>>::toggle_allowlist(
+				&collection,
+				&sender,
+				&sender,
+				true,
+			)?;
+
+		assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);
+
+	}: {collection_handle.check_allowlist(&sender)?;}
 }
addedpallets/common/src/helpers.rsdiffbeforeafterboth
--- /dev/null
+++ b/pallets/common/src/helpers.rs
@@ -0,0 +1,30 @@
+//! # Helpers module
+//!
+//! The module contains helpers.
+//!
+use frame_support::{
+	pallet_prelude::DispatchResultWithPostInfo,
+	weights::Weight,
+	dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo},
+};
+
+/// Add weight for a `DispatchResultWithPostInfo`
+///
+/// - `target`: DispatchResultWithPostInfo to which weight will be added
+/// - `additional_weight`: Weight to be added
+pub fn add_weight_to_post_info(target: &mut DispatchResultWithPostInfo, additional_weight: Weight) {
+	match target {
+		Ok(PostDispatchInfo {
+			actual_weight: Some(weight),
+			..
+		})
+		| Err(DispatchErrorWithPostInfo {
+			post_info: PostDispatchInfo {
+				actual_weight: Some(weight),
+				..
+			},
+			..
+		}) => *weight += additional_weight,
+		_ => {}
+	}
+}
modifiedpallets/common/src/lib.rsdiffbeforeafterboth
--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -92,9 +92,9 @@
 pub mod dispatch;
 pub mod erc;
 pub mod eth;
+pub mod helpers;
 #[allow(missing_docs)]
 pub mod weights;
-
 /// Weight info.
 pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
 
modifiedpallets/common/src/weights.rsdiffbeforeafterboth
--- a/pallets/common/src/weights.rs
+++ b/pallets/common/src/weights.rs
@@ -36,6 +36,7 @@
 pub trait WeightInfo {
 	fn set_collection_properties(b: u32, ) -> Weight;
 	fn delete_collection_properties(b: u32, ) -> Weight;
+	fn check_accesslist() -> Weight;
 }
 
 /// Weights for pallet_common using the Substrate node and recommended hardware.
@@ -69,6 +70,16 @@
 			.saturating_add(T::DbWeight::get().reads(1_u64))
 			.saturating_add(T::DbWeight::get().writes(1_u64))
 	}
+	/// Storage: Common Allowlist (r:1 w:0)
+	/// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+	fn check_accesslist() -> Weight {
+		// Proof Size summary in bytes:
+		//  Measured:  `340`
+		//  Estimated: `2545`
+		// Minimum execution time: 2_887_000 picoseconds.
+		Weight::from_parts(3_072_000, 2545)
+			.saturating_add(T::DbWeight::get().reads(1_u64))
+	}
 }
 
 // For backwards compatibility and tests
@@ -101,5 +112,15 @@
 			.saturating_add(RocksDbWeight::get().reads(1_u64))
 			.saturating_add(RocksDbWeight::get().writes(1_u64))
 	}
+	/// Storage: Common Allowlist (r:1 w:0)
+	/// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+	fn check_accesslist() -> Weight {
+		// Proof Size summary in bytes:
+		//  Measured:  `340`
+		//  Estimated: `2545`
+		// Minimum execution time: 2_887_000 picoseconds.
+		Weight::from_parts(3_072_000, 2545)
+			.saturating_add(RocksDbWeight::get().reads(1_u64))
+	}
 }
 
modifiedpallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth
--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -452,7 +452,8 @@
 					&T::CrossAccountId::from_sub(dest.clone()),
 					amount.into(),
 					&Value::new(0),
-				)?;
+				)
+				.map_err(|e| e.error)?;
 
 				Ok(amount)
 			}
modifiedpallets/fungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.11] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
 ## [0.1.10] - 2023-02-01
 
 ### Added
modifiedpallets/fungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -66,7 +66,7 @@
 		<Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200), &Unlimited)?;
 	}: {<Pallet<T>>::burn(&collection, &burner, 100)?}
 
-	transfer {
+	transfer_raw {
 		bench_init!{
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub; sender: cross_sub; to: cross_sub;
@@ -92,14 +92,22 @@
 		<Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
 	}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, &spender, 100)?}
 
-	transfer_from {
+	check_allowed_raw {
 		bench_init!{
 			owner: sub; collection: collection(owner);
-			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
 		};
 		<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
+	}: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, 200, &Unlimited)?;}
+
+	set_allowance_unchecked_raw {
+		bench_init!{
+			owner: sub; collection: collection(owner);
+			owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+		};
+		<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
+	}: {<Pallet<T>>::set_allowance_unchecked(&collection, &sender, &spender, 200);}
 
 	burn_from {
 		bench_init!{
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -22,7 +22,7 @@
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
-	weights::WeightInfo as _,
+	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
 };
 use pallet_structure::Error as StructureError;
 use sp_runtime::ArithmeticError;
@@ -78,7 +78,7 @@
 	}
 
 	fn transfer() -> Weight {
-		<SelfWeightOf<T>>::transfer()
+		<SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
 	}
 
 	fn approve() -> Weight {
@@ -90,7 +90,9 @@
 	}
 
 	fn transfer_from() -> Weight {
-		<SelfWeightOf<T>>::transfer_from()
+		Self::transfer()
+			+ <SelfWeightOf<T>>::check_allowed_raw()
+			+ <SelfWeightOf<T>>::set_allowance_unchecked_raw()
 	}
 
 	fn burn_from() -> Weight {
@@ -232,10 +234,7 @@
 			<Error<T>>::FungibleItemsHaveNoId
 		);
 
-		with_weight(
-			<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),
-			<CommonWeights<T>>::transfer(),
-		)
+		<Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget)
 	}
 
 	fn approve(
@@ -289,10 +288,7 @@
 			<Error<T>>::FungibleItemsHaveNoId
 		);
 
-		with_weight(
-			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),
-			<CommonWeights<T>>::transfer_from(),
-		)
+		<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget)
 	}
 
 	fn burn_from(
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -26,6 +26,7 @@
 	CollectionHandle,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
 	eth::CrossAddress,
+	CommonWeightInfo as _,
 };
 use sp_std::vec::Vec;
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -39,7 +40,7 @@
 
 use crate::{
 	Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply, SelfWeightOf,
-	weights::WeightInfo,
+	weights::WeightInfo, common::CommonWeights,
 };
 
 frontier_contract! {
@@ -99,7 +100,7 @@
 		let balance = <Balance<T>>::get((self.id, owner));
 		Ok(balance.into())
 	}
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
@@ -112,7 +113,7 @@
 		Ok(true)
 	}
 
-	#[weight(<SelfWeightOf<T>>::transfer_from())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from(
 		&mut self,
 		caller: Caller,
@@ -129,7 +130,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(true)
 	}
 	#[weight(<SelfWeightOf<T>>::approve())]
@@ -201,7 +202,7 @@
 		let budget = self
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
-		<Pallet<T>>::create_item(&self, &caller, (to, amount), &budget)
+		<Pallet<T>>::create_item(self, &caller, (to, amount), &budget)
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
@@ -289,7 +290,7 @@
 		Ok(true)
 	}
 
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = to.into_sub_cross_account::<T>()?;
@@ -302,7 +303,7 @@
 		Ok(true)
 	}
 
-	#[weight(<SelfWeightOf<T>>::transfer_from())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from_cross(
 		&mut self,
 		caller: Caller,
@@ -319,7 +320,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(true)
 	}
 
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -80,7 +80,11 @@
 
 use core::ops::Deref;
 use evm_coder::ToLog;
-use frame_support::ensure;
+use frame_support::{
+	ensure,
+	pallet_prelude::{DispatchResultWithPostInfo, Pays},
+	dispatch::PostDispatchInfo,
+};
 use pallet_evm::account::CrossAccountId;
 use up_data_structs::{
 	AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
@@ -88,7 +92,8 @@
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
-	eth::collection_id_to_address,
+	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
+	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
 };
 use pallet_evm::Pallet as PalletEvm;
 use pallet_structure::Pallet as PalletStructure;
@@ -96,7 +101,7 @@
 use sp_core::H160;
 use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
 use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
-
+use weights::WeightInfo;
 pub use pallet::*;
 
 use crate::erc::ERC20Events;
@@ -389,18 +394,20 @@
 		to: &T::CrossAccountId,
 		amount: u128,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed,
 		);
 
+		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();
+
 		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
+			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;
 		}
 		<PalletCommon<T>>::ensure_correct_receiver(to)?;
-
 		let balance_from = <Balance<T>>::get((collection.id, from))
 			.checked_sub(amount)
 			.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -451,7 +458,11 @@
 			to.clone(),
 			amount,
 		));
-		Ok(())
+
+		Ok(PostDispatchInfo {
+			actual_weight: Some(actual_weight),
+			pays_fee: Pays::Yes,
+		})
 	}
 
 	/// Minting tokens for multiple IDs.
@@ -464,8 +475,8 @@
 		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		let total_supply = data
-			.iter()
-			.map(|(_, v)| *v)
+			.values()
+			.copied()
 			.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {
 				acc.checked_add(v)
 			})
@@ -718,7 +729,6 @@
 	/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
 	/// The owner should set allowance for the spender to transfer pieces.
 	///	See [`set_allowance`][`Pallet::set_allowance`] for more details.
-
 	pub fn transfer_from(
 		collection: &FungibleHandle<T>,
 		spender: &T::CrossAccountId,
@@ -726,16 +736,23 @@
 		to: &T::CrossAccountId,
 		amount: u128,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
 
 		// =========
 
-		Self::transfer(collection, from, to, amount, nesting_budget)?;
+		let mut result = Self::transfer(collection, from, to, amount, nesting_budget);
+		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());
+		result?;
+
 		if let Some(allowance) = allowance {
 			Self::set_allowance_unchecked(collection, from, spender, allowance);
+			add_weight_to_post_info(
+				&mut result,
+				<SelfWeightOf<T>>::set_allowance_unchecked_raw(),
+			)
 		}
-		Ok(())
+		result
 	}
 
 	/// Burn fungible tokens from the account.
modifiedpallets/fungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -37,10 +37,11 @@
 	fn create_item() -> Weight;
 	fn create_multiple_items_ex(b: u32, ) -> Weight;
 	fn burn_item() -> Weight;
-	fn transfer() -> Weight;
+	fn transfer_raw() -> Weight;
 	fn approve() -> Weight;
 	fn approve_from() -> Weight;
-	fn transfer_from() -> Weight;
+	fn check_allowed_raw() -> Weight;
+	fn set_allowance_unchecked_raw() -> Weight;
 	fn burn_from() -> Weight;
 }
 
@@ -94,12 +95,12 @@
 	}
 	/// Storage: Fungible Balance (r:2 w:2)
 	/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
-	fn transfer() -> Weight {
+	fn transfer_raw() -> Weight {
 		// Proof Size summary in bytes:
 		//  Measured:  `182`
 		//  Estimated: `5104`
-		// Minimum execution time: 13_832_000 picoseconds.
-		Weight::from_parts(14_064_000, 5104)
+		// Minimum execution time: 6_678_000 picoseconds.
+		Weight::from_parts(7_151_000, 5104)
 			.saturating_add(T::DbWeight::get().reads(2_u64))
 			.saturating_add(T::DbWeight::get().writes(2_u64))
 	}
@@ -129,19 +130,26 @@
 			.saturating_add(T::DbWeight::get().reads(1_u64))
 			.saturating_add(T::DbWeight::get().writes(1_u64))
 	}
-	/// Storage: Fungible Allowance (r:1 w:1)
+	/// Storage: Fungible Allowance (r:1 w:0)
 	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
-	/// Storage: Fungible Balance (r:2 w:2)
-	/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
-	fn transfer_from() -> Weight {
+	fn check_allowed_raw() -> Weight {
 		// Proof Size summary in bytes:
-		//  Measured:  `300`
-		//  Estimated: `7672`
-		// Minimum execution time: 21_667_000 picoseconds.
-		Weight::from_parts(22_166_000, 7672)
-			.saturating_add(T::DbWeight::get().reads(3_u64))
-			.saturating_add(T::DbWeight::get().writes(3_u64))
+		//  Measured:  `210`
+		//  Estimated: `2568`
+		// Minimum execution time: 2_842_000 picoseconds.
+		Weight::from_parts(3_077_000, 2568)
+			.saturating_add(T::DbWeight::get().reads(1_u64))
 	}
+	/// Storage: Fungible Allowance (r:0 w:1)
+	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+	fn set_allowance_unchecked_raw() -> Weight {
+		// Proof Size summary in bytes:
+		//  Measured:  `0`
+		//  Estimated: `0`
+		// Minimum execution time: 2_532_000 picoseconds.
+		Weight::from_parts(2_680_000, 0)
+			.saturating_add(T::DbWeight::get().writes(1_u64))
+	}
 	/// Storage: Fungible Allowance (r:1 w:1)
 	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
 	/// Storage: Fungible TotalSupply (r:1 w:1)
@@ -208,12 +216,12 @@
 	}
 	/// Storage: Fungible Balance (r:2 w:2)
 	/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
-	fn transfer() -> Weight {
+	fn transfer_raw() -> Weight {
 		// Proof Size summary in bytes:
 		//  Measured:  `182`
 		//  Estimated: `5104`
-		// Minimum execution time: 13_832_000 picoseconds.
-		Weight::from_parts(14_064_000, 5104)
+		// Minimum execution time: 6_678_000 picoseconds.
+		Weight::from_parts(7_151_000, 5104)
 			.saturating_add(RocksDbWeight::get().reads(2_u64))
 			.saturating_add(RocksDbWeight::get().writes(2_u64))
 	}
@@ -243,18 +251,25 @@
 			.saturating_add(RocksDbWeight::get().reads(1_u64))
 			.saturating_add(RocksDbWeight::get().writes(1_u64))
 	}
-	/// Storage: Fungible Allowance (r:1 w:1)
+	/// Storage: Fungible Allowance (r:1 w:0)
 	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
-	/// Storage: Fungible Balance (r:2 w:2)
-	/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
-	fn transfer_from() -> Weight {
+	fn check_allowed_raw() -> Weight {
 		// Proof Size summary in bytes:
-		//  Measured:  `300`
-		//  Estimated: `7672`
-		// Minimum execution time: 21_667_000 picoseconds.
-		Weight::from_parts(22_166_000, 7672)
-			.saturating_add(RocksDbWeight::get().reads(3_u64))
-			.saturating_add(RocksDbWeight::get().writes(3_u64))
+		//  Measured:  `210`
+		//  Estimated: `2568`
+		// Minimum execution time: 2_842_000 picoseconds.
+		Weight::from_parts(3_077_000, 2568)
+			.saturating_add(RocksDbWeight::get().reads(1_u64))
+	}
+	/// Storage: Fungible Allowance (r:0 w:1)
+	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+	fn set_allowance_unchecked_raw() -> Weight {
+		// Proof Size summary in bytes:
+		//  Measured:  `0`
+		//  Estimated: `0`
+		// Minimum execution time: 2_532_000 picoseconds.
+		Weight::from_parts(2_680_000, 0)
+			.saturating_add(RocksDbWeight::get().writes(1_u64))
 	}
 	/// Storage: Fungible Allowance (r:1 w:1)
 	/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
modifiedpallets/nonfungible/CHANGELOG.mddiffbeforeafterboth
--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,12 @@
 
 <!-- bureaucrate goes here -->
 
+## [0.1.14] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
 ## [0.1.13] - 2023-01-20
 
 ### Fixed
modifiedpallets/nonfungible/Cargo.tomldiffbeforeafterboth
--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -2,7 +2,7 @@
 edition = "2021"
 license = "GPLv3"
 name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
 
 [dependencies]
 # Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -121,7 +121,7 @@
 		}
 	}: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?}
 
-	transfer {
+	transfer_raw {
 		bench_init!{
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;
@@ -146,14 +146,14 @@
 		let item = create_max_item(&collection, &owner, owner_eth.clone())?;
 	}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, item, Some(&spender))?}
 
-	transfer_from {
+	check_allowed_raw {
 		bench_init!{
 			owner: sub; collection: collection(owner);
 			owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
 		};
 		let item = create_max_item(&collection, &owner, sender.clone())?;
 		<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
+	}: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, item, &Unlimited)?}
 
 	burn_from {
 		bench_init!{
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,7 +23,7 @@
 };
 use pallet_common::{
 	CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
-	weights::WeightInfo as _,
+	weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
 };
 use sp_runtime::DispatchError;
 use sp_std::{vec::Vec, vec};
@@ -91,7 +91,7 @@
 	}
 
 	fn transfer() -> Weight {
-		<SelfWeightOf<T>>::transfer()
+		<SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
 	}
 
 	fn approve() -> Weight {
@@ -103,7 +103,7 @@
 	}
 
 	fn transfer_from() -> Weight {
-		<SelfWeightOf<T>>::transfer_from()
+		Self::transfer() + <SelfWeightOf<T>>::check_allowed_raw()
 	}
 
 	fn burn_from() -> Weight {
@@ -325,10 +325,7 @@
 	) -> DispatchResultWithPostInfo {
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 		if amount == 1 {
-			with_weight(
-				<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
-				<CommonWeights<T>>::transfer(),
-			)
+			<Pallet<T>>::transfer(self, &from, &to, token, nesting_budget)
 		} else {
 			<Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
 			Ok(().into())
@@ -386,10 +383,7 @@
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 
 		if amount == 1 {
-			with_weight(
-				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
-				<CommonWeights<T>>::transfer_from(),
-			)
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget)
 		} else {
 			<Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
 
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -39,6 +39,7 @@
 	CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
 	erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
 	eth::{self, TokenUri},
+	CommonWeightInfo,
 };
 use pallet_evm::{account::CrossAccountId, PrecompileHandle};
 use pallet_evm_coder_substrate::call;
@@ -47,7 +48,7 @@
 
 use crate::{
 	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
-	TokenProperties, SelfWeightOf, weights::WeightInfo,
+	TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,
 };
 
 /// Nft events.
@@ -458,7 +459,7 @@
 	/// @param from The current owner of the NFT
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer_from())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from(
 		&mut self,
 		caller: Caller,
@@ -475,7 +476,7 @@
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
 		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -824,7 +825,7 @@
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {
 		let caller = T::CrossAccountId::from_eth(caller);
 		let to = T::CrossAccountId::from_eth(to);
@@ -833,7 +834,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -842,7 +844,7 @@
 	///  is the zero address. Throws if `tokenId` is not a valid NFT.
 	/// @param to The new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer())]
 	fn transfer_cross(
 		&mut self,
 		caller: Caller,
@@ -856,7 +858,8 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
@@ -866,7 +869,7 @@
 	/// @param from Cross acccount address of current owner
 	/// @param to Cross acccount address of new owner
 	/// @param tokenId The NFT to transfer
-	#[weight(<SelfWeightOf<T>>::transfer())]
+	#[weight(<CommonWeights<T>>::transfer_from())]
 	fn transfer_from_cross(
 		&mut self,
 		caller: Caller,
@@ -882,7 +885,7 @@
 			.recorder
 			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 		Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)
-			.map_err(dispatch_to_evm::<T>)?;
+			.map_err(|e| dispatch_to_evm::<T>(e.error))?;
 		Ok(())
 	}
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -108,7 +108,8 @@
 use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,
-	eth::collection_id_to_address,
+	eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
+	weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
 };
 use pallet_structure::{Pallet as PalletStructure, Error as StructureError};
 use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};
@@ -802,12 +803,13 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		ensure!(
 			collection.limits.transfers_enabled(),
 			<CommonError<T>>::TransferNotAllowed
 		);
 
+		let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();
 		let token_data =
 			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;
 		ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);
@@ -815,6 +817,7 @@
 		if collection.permissions.access() == AccessMode::AllowList {
 			collection.check_allowlist(from)?;
 			collection.check_allowlist(to)?;
+			actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;
 		}
 		<PalletCommon<T>>::ensure_correct_receiver(to)?;
 
@@ -884,7 +887,11 @@
 			to.clone(),
 			1,
 		));
-		Ok(())
+
+		Ok(PostDispatchInfo {
+			actual_weight: Some(actual_weight),
+			pays_fee: Pays::Yes,
+		})
 	}
 
 	/// Batch operation to mint multiple NFT tokens.
@@ -1228,13 +1235,15 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		nesting_budget: &dyn Budget,
-	) -> DispatchResult {
+	) -> DispatchResultWithPostInfo {
 		Self::check_allowed(collection, spender, from, token, nesting_budget)?;
 
 		// =========
 
 		// Allowance is reset in [`transfer`]
-		Self::transfer(collection, from, to, token, nesting_budget)
+		let mut result = Self::transfer(collection, from, to, token, nesting_budget);
+		add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());
+		result
 	}
 
 	/// Burn NFT token for `from` account.
modifiedpallets/nonfungible/src/weights.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -40,10 +40,10 @@
 	fn burn_item() -> Weight;
 	fn burn_recursively_self_raw() -> Weight;
 	fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
-	fn transfer() -> Weight;
+	fn transfer_raw() -> Weight;
 	fn approve() -> Weight;
 	fn approve_from() -> Weight;
-	fn transfer_from() -> Weight;
+	fn check_allowed_raw() -> Weight;
 	fn burn_from() -> Weight;
 	fn set_token_property_permissions(b: u32, ) -> Weight;
 	fn set_token_properties(b: u32, ) -> Weight;
@@ -217,12 +217,12 @@
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
 	/// Storage: Nonfungible Owned (r:0 w:2)
 	/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
-	fn transfer() -> Weight {
+	fn transfer_raw() -> Weight {
 		// Proof Size summary in bytes:
 		//  Measured:  `412`
 		//  Estimated: `10144`
-		// Minimum execution time: 18_629_000 picoseconds.
-		Weight::from_parts(18_997_000, 10144)
+		// Minimum execution time: 9_307_000 picoseconds.
+		Weight::from_parts(10_108_000, 10144)
 			.saturating_add(T::DbWeight::get().reads(4_u64))
 			.saturating_add(T::DbWeight::get().writes(5_u64))
 	}
@@ -252,22 +252,15 @@
 			.saturating_add(T::DbWeight::get().reads(2_u64))
 			.saturating_add(T::DbWeight::get().writes(1_u64))
 	}
-	/// Storage: Nonfungible Allowance (r:1 w:1)
+	/// Storage: Nonfungible Allowance (r:1 w:0)
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
-	/// Storage: Nonfungible TokenData (r:1 w:1)
-	/// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
-	/// Storage: Nonfungible AccountBalance (r:2 w:2)
-	/// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
-	/// Storage: Nonfungible Owned (r:0 w:2)
-	/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
-	fn transfer_from() -> Weight {
+	fn check_allowed_raw() -> Weight {
 		// Proof Size summary in bytes:
-		//  Measured:  `527`
-		//  Estimated: `10144`
-		// Minimum execution time: 24_919_000 picoseconds.
-		Weight::from_parts(25_333_000, 10144)
-			.saturating_add(T::DbWeight::get().reads(4_u64))
-			.saturating_add(T::DbWeight::get().writes(6_u64))
+		//  Measured:  `394`
+		//  Estimated: `2532`
+		// Minimum execution time: 2_668_000 picoseconds.
+		Weight::from_parts(2_877_000, 2532)
+			.saturating_add(T::DbWeight::get().reads(1_u64))
 	}
 	/// Storage: Nonfungible Allowance (r:1 w:1)
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
@@ -543,12 +536,12 @@
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
 	/// Storage: Nonfungible Owned (r:0 w:2)
 	/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
-	fn transfer() -> Weight {
+	fn transfer_raw() -> Weight {
 		// Proof Size summary in bytes:
 		//  Measured:  `412`
 		//  Estimated: `10144`
-		// Minimum execution time: 18_629_000 picoseconds.
-		Weight::from_parts(18_997_000, 10144)
+		// Minimum execution time: 9_307_000 picoseconds.
+		Weight::from_parts(10_108_000, 10144)
 			.saturating_add(RocksDbWeight::get().reads(4_u64))
 			.saturating_add(RocksDbWeight::get().writes(5_u64))
 	}
@@ -578,22 +571,15 @@
 			.saturating_add(RocksDbWeight::get().reads(2_u64))
 			.saturating_add(RocksDbWeight::get().writes(1_u64))
 	}
-	/// Storage: Nonfungible Allowance (r:1 w:1)
+	/// Storage: Nonfungible Allowance (r:1 w:0)
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
-	/// Storage: Nonfungible TokenData (r:1 w:1)
-	/// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
-	/// Storage: Nonfungible AccountBalance (r:2 w:2)
-	/// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
-	/// Storage: Nonfungible Owned (r:0 w:2)
-	/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
-	fn transfer_from() -> Weight {
+	fn check_allowed_raw() -> Weight {
 		// Proof Size summary in bytes:
-		//  Measured:  `527`
-		//  Estimated: `10144`
-		// Minimum execution time: 24_919_000 picoseconds.
-		Weight::from_parts(25_333_000, 10144)
-			.saturating_add(RocksDbWeight::get().reads(4_u64))
-			.saturating_add(RocksDbWeight::get().writes(6_u64))
+		//  Measured:  `394`
+		//  Estimated: `2532`
+		// Minimum execution time: 2_668_000 picoseconds.
+		Weight::from_parts(2_877_000, 2532)
+			.saturating_add(RocksDbWeight::get().reads(1_u64))
 	}
 	/// Storage: Nonfungible Allowance (r:1 w:1)
 	/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)