git.delta.rocks / unique-network / refs/commits / b69837dd758f

difftreelog

feat budgets

Yaroslav Bolyukin2022-04-07parent: #23942aa.patch.diff
in: master

19 files changed

modifiedpallets/common/src/lib.rsdiffbeforeafterboth
before · pallets/common/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#![cfg_attr(not(feature = "std"), no_std)]1819use core::ops::{Deref, DerefMut};20use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};21use sp_std::vec::Vec;22use pallet_evm::account::CrossAccountId;23use frame_support::{24	dispatch::{DispatchErrorWithPostInfo, DispatchResultWithPostInfo, Weight, PostDispatchInfo},25	ensure, fail,26	traits::{Imbalance, Get, Currency, WithdrawReasons, ExistenceRequirement},27	BoundedVec,28	weights::Pays,29};30use pallet_evm::GasWeightMapping;31use up_data_structs::{32	COLLECTION_NUMBER_LIMIT, Collection, CollectionId, CreateItemData, MAX_TOKEN_PREFIX_LENGTH,33	COLLECTION_ADMINS_LIMIT, MetaUpdatePermission, TokenId, CollectionStats, MAX_TOKEN_OWNERSHIP,34	CollectionMode, NFT_SPONSOR_TRANSFER_TIMEOUT, FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,35	REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT, MAX_SPONSOR_TIMEOUT, CUSTOM_DATA_LIMIT, CollectionLimits,36	CustomDataLimit, CreateCollectionData, SponsorshipState, CreateItemExData, SponsoringRateLimit,37};38pub use pallet::*;39use sp_core::H160;40use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};41#[cfg(feature = "runtime-benchmarks")]42pub mod benchmarking;43pub mod dispatch;44pub mod erc;45pub mod eth;4647#[must_use = "Should call submit_logs or save, otherwise some data will be lost for evm side"]48pub struct CollectionHandle<T: Config> {49	pub id: CollectionId,50	collection: Collection<T::AccountId>,51	pub recorder: SubstrateRecorder<T>,52}53impl<T: Config> WithRecorder<T> for CollectionHandle<T> {54	fn recorder(&self) -> &SubstrateRecorder<T> {55		&self.recorder56	}57	fn into_recorder(self) -> SubstrateRecorder<T> {58		self.recorder59	}60}61impl<T: Config> CollectionHandle<T> {62	pub fn new_with_gas_limit(id: CollectionId, gas_limit: u64) -> Option<Self> {63		<CollectionById<T>>::get(id).map(|collection| Self {64			id,65			collection,66			recorder: SubstrateRecorder::new(eth::collection_id_to_address(id), gas_limit),67		})68	}69	pub fn new(id: CollectionId) -> Option<Self> {70		Self::new_with_gas_limit(id, u64::MAX)71	}72	pub fn try_get(id: CollectionId) -> Result<Self, DispatchError> {73		Ok(Self::new(id).ok_or(<Error<T>>::CollectionNotFound)?)74	}75	pub fn log_mirrored(&self, log: impl evm_coder::ToLog) {76		self.recorder.log_mirrored(log)77	}78	pub fn log_direct(&self, log: impl evm_coder::ToLog) {79		self.recorder.log_direct(log)80	}81	pub fn consume_store_reads(&self, reads: u64) -> evm_coder::execution::Result<()> {82		self.recorder83			.consume_gas(T::GasWeightMapping::weight_to_gas(84				<T as frame_system::Config>::DbWeight::get()85					.read86					.saturating_mul(reads),87			))88	}89	pub fn consume_store_writes(&self, writes: u64) -> evm_coder::execution::Result<()> {90		self.recorder91			.consume_gas(T::GasWeightMapping::weight_to_gas(92				<T as frame_system::Config>::DbWeight::get()93					.write94					.saturating_mul(writes),95			))96	}97	pub fn submit_logs(self) {98		self.recorder.submit_logs()99	}100	pub fn save(self) -> DispatchResult {101		self.recorder.submit_logs();102		<CollectionById<T>>::insert(self.id, self.collection);103		Ok(())104	}105}106impl<T: Config> Deref for CollectionHandle<T> {107	type Target = Collection<T::AccountId>;108109	fn deref(&self) -> &Self::Target {110		&self.collection111	}112}113114impl<T: Config> DerefMut for CollectionHandle<T> {115	fn deref_mut(&mut self) -> &mut Self::Target {116		&mut self.collection117	}118}119120impl<T: Config> CollectionHandle<T> {121	pub fn check_is_owner(&self, subject: &T::CrossAccountId) -> DispatchResult {122		ensure!(*subject.as_sub() == self.owner, <Error<T>>::NoPermission);123		Ok(())124	}125	pub fn is_owner_or_admin(&self, subject: &T::CrossAccountId) -> bool {126		*subject.as_sub() == self.owner || <IsAdmin<T>>::get((self.id, subject))127	}128	pub fn check_is_owner_or_admin(&self, subject: &T::CrossAccountId) -> DispatchResult {129		ensure!(self.is_owner_or_admin(subject), <Error<T>>::NoPermission);130		Ok(())131	}132	pub fn ignores_allowance(&self, user: &T::CrossAccountId) -> bool {133		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)134	}135	pub fn ignores_owned_amount(&self, user: &T::CrossAccountId) -> bool {136		self.limits.owner_can_transfer() && self.is_owner_or_admin(user)137	}138	pub fn check_allowlist(&self, user: &T::CrossAccountId) -> DispatchResult {139		ensure!(140			<Allowlist<T>>::get((self.id, user)),141			<Error<T>>::AddressNotInAllowlist142		);143		Ok(())144	}145146	pub fn check_can_update_meta(147		&self,148		subject: &T::CrossAccountId,149		item_owner: &T::CrossAccountId,150	) -> DispatchResult {151		match self.meta_update_permission {152			MetaUpdatePermission::ItemOwner => {153				ensure!(subject == item_owner, <Error<T>>::NoPermission);154				Ok(())155			}156			MetaUpdatePermission::Admin => self.check_is_owner_or_admin(subject),157			MetaUpdatePermission::None => fail!(<Error<T>>::NoPermission),158		}159	}160}161162#[frame_support::pallet]163pub mod pallet {164	use super::*;165	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key};166	use pallet_evm::account;167	use dispatch::CollectionDispatch;168	use frame_support::{Blake2_128Concat, pallet_prelude::*, storage::Key, traits::StorageVersion};169	use frame_system::pallet_prelude::*;170	use frame_support::traits::Currency;171	use up_data_structs::{TokenId, mapping::TokenAddressMapping};172	use scale_info::TypeInfo;173	use up_evm_mapping::CrossAccountId;174175	#[pallet::config]176	pub trait Config:177		frame_system::Config + pallet_evm_coder_substrate::Config + TypeInfo + account::Config178	{179		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;180181		type Currency: Currency<Self::AccountId>;182183		#[pallet::constant]184		type CollectionCreationPrice: Get<185			<<Self as Config>::Currency as Currency<Self::AccountId>>::Balance,186		>;187		type CollectionDispatch: CollectionDispatch<Self>;188189		type TreasuryAccountId: Get<Self::AccountId>;190191		type EvmTokenAddressMapping: TokenAddressMapping<H160>;192		type CrossTokenAddressMapping: TokenAddressMapping<Self::CrossAccountId>;193	}194195	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);196197	#[pallet::pallet]198	#[pallet::storage_version(STORAGE_VERSION)]199	#[pallet::generate_store(pub(super) trait Store)]200	pub struct Pallet<T>(_);201202	#[pallet::extra_constants]203	impl<T: Config> Pallet<T> {204		pub fn collection_admins_limit() -> u32 {205			COLLECTION_ADMINS_LIMIT206		}207	}208209	#[pallet::event]210	#[pallet::generate_deposit(pub fn deposit_event)]211	pub enum Event<T: Config> {212		/// New collection was created213		///214		/// # Arguments215		///216		/// * collection_id: Globally unique identifier of newly created collection.217		///218		/// * mode: [CollectionMode] converted into u8.219		///220		/// * account_id: Collection owner.221		CollectionCreated(CollectionId, u8, T::AccountId),222223		/// New collection was destroyed224		///225		/// # Arguments226		///227		/// * collection_id: Globally unique identifier of collection.228		CollectionDestroyed(CollectionId),229230		/// New item was created.231		///232		/// # Arguments233		///234		/// * collection_id: Id of the collection where item was created.235		///236		/// * item_id: Id of an item. Unique within the collection.237		///238		/// * recipient: Owner of newly created item239		///240		/// * amount: Always 1 for NFT241		ItemCreated(CollectionId, TokenId, T::CrossAccountId, u128),242243		/// Collection item was burned.244		///245		/// # Arguments246		///247		/// * collection_id.248		///249		/// * item_id: Identifier of burned NFT.250		///251		/// * owner: which user has destroyed its tokens252		///253		/// * amount: Always 1 for NFT254		ItemDestroyed(CollectionId, TokenId, T::CrossAccountId, u128),255256		/// Item was transferred257		///258		/// * collection_id: Id of collection to which item is belong259		///260		/// * item_id: Id of an item261		///262		/// * sender: Original owner of item263		///264		/// * recipient: New owner of item265		///266		/// * amount: Always 1 for NFT267		Transfer(268			CollectionId,269			TokenId,270			T::CrossAccountId,271			T::CrossAccountId,272			u128,273		),274275		/// * collection_id276		///277		/// * item_id278		///279		/// * sender280		///281		/// * spender282		///283		/// * amount284		Approved(285			CollectionId,286			TokenId,287			T::CrossAccountId,288			T::CrossAccountId,289			u128,290		),291	}292293	#[pallet::error]294	pub enum Error<T> {295		/// This collection does not exist.296		CollectionNotFound,297		/// Sender parameter and item owner must be equal.298		MustBeTokenOwner,299		/// No permission to perform action300		NoPermission,301		/// Collection is not in mint mode.302		PublicMintingNotAllowed,303		/// Address is not in allow list.304		AddressNotInAllowlist,305306		/// Collection name can not be longer than 63 char.307		CollectionNameLimitExceeded,308		/// Collection description can not be longer than 255 char.309		CollectionDescriptionLimitExceeded,310		/// Token prefix can not be longer than 15 char.311		CollectionTokenPrefixLimitExceeded,312		/// Total collections bound exceeded.313		TotalCollectionsLimitExceeded,314		/// variable_data exceeded data limit.315		TokenVariableDataLimitExceeded,316		/// Exceeded max admin count317		CollectionAdminCountExceeded,318		/// Collection limit bounds per collection exceeded319		CollectionLimitBoundsExceeded,320		/// Tried to enable permissions which are only permitted to be disabled321		OwnerPermissionsCantBeReverted,322323		/// Collection settings not allowing items transferring324		TransferNotAllowed,325		/// Account token limit exceeded per collection326		AccountTokenLimitExceeded,327		/// Collection token limit exceeded328		CollectionTokenLimitExceeded,329		/// Metadata flag frozen330		MetadataFlagFrozen,331332		/// Item not exists.333		TokenNotFound,334		/// Item balance not enough.335		TokenValueTooLow,336		/// Requested value more than approved.337		ApprovedValueTooLow,338		/// Tried to approve more than owned339		CantApproveMoreThanOwned,340341		/// Can't transfer tokens to ethereum zero address342		AddressIsZero,343		/// Target collection doesn't supports this operation344		UnsupportedOperation,345346		/// Not sufficient founds to perform action347		NotSufficientFounds,348349		/// Collection has nesting disabled350		NestingIsDisabled,351		/// Only owner may nest tokens under this collection352		OnlyOwnerAllowedToNest,353		/// Only tokens from specific collections may nest tokens under this354		SourceCollectionIsNotAllowedToNest,355	}356357	#[pallet::storage]358	pub type CreatedCollectionCount<T> = StorageValue<Value = CollectionId, QueryKind = ValueQuery>;359	#[pallet::storage]360	pub type DestroyedCollectionCount<T> =361		StorageValue<Value = CollectionId, QueryKind = ValueQuery>;362363	/// Collection info364	#[pallet::storage]365	pub type CollectionById<T> = StorageMap<366		Hasher = Blake2_128Concat,367		Key = CollectionId,368		Value = Collection<<T as frame_system::Config>::AccountId>,369		QueryKind = OptionQuery,370	>;371372	#[pallet::storage]373	pub type AdminAmount<T> = StorageMap<374		Hasher = Blake2_128Concat,375		Key = CollectionId,376		Value = u32,377		QueryKind = ValueQuery,378	>;379380	/// List of collection admins381	#[pallet::storage]382	pub type IsAdmin<T: Config> = StorageNMap<383		Key = (384			Key<Blake2_128Concat, CollectionId>,385			Key<Blake2_128Concat, T::CrossAccountId>,386		),387		Value = bool,388		QueryKind = ValueQuery,389	>;390391	/// Allowlisted collection users392	#[pallet::storage]393	pub type Allowlist<T: Config> = StorageNMap<394		Key = (395			Key<Blake2_128Concat, CollectionId>,396			Key<Blake2_128Concat, T::CrossAccountId>,397		),398		Value = bool,399		QueryKind = ValueQuery,400	>;401402	/// Not used by code, exists only to provide some types to metadata403	#[pallet::storage]404	pub type DummyStorageValue<T> =405		StorageValue<Value = (CollectionStats, CollectionId, TokenId), QueryKind = OptionQuery>;406407	#[pallet::hooks]408	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {409		fn on_runtime_upgrade() -> Weight {410			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {411				use up_data_structs::{CollectionVersion1, CollectionVersion2};412				<CollectionById<T>>::translate_values::<CollectionVersion1<T::AccountId>, _>(|v| {413					Some(CollectionVersion2::from(v))414				});415			}416417			0418		}419	}420}421422impl<T: Config> Pallet<T> {423	/// Ethereum receiver 0x0000000000000000000000000000000000000000 is reserved, and shouldn't own tokens424	pub fn ensure_correct_receiver(receiver: &T::CrossAccountId) -> DispatchResult {425		ensure!(426			&T::CrossAccountId::from_eth(H160([0; 20])) != receiver,427			<Error<T>>::AddressIsZero428		);429		Ok(())430	}431	pub fn adminlist(collection: CollectionId) -> Vec<T::CrossAccountId> {432		<IsAdmin<T>>::iter_prefix((collection,))433			.map(|(a, _)| a)434			.collect()435	}436	pub fn allowlist(collection: CollectionId) -> Vec<T::CrossAccountId> {437		<Allowlist<T>>::iter_prefix((collection,))438			.map(|(a, _)| a)439			.collect()440	}441	pub fn allowed(collection: CollectionId, user: T::CrossAccountId) -> bool {442		<Allowlist<T>>::get((collection, user))443	}444	pub fn collection_stats() -> CollectionStats {445		let created = <CreatedCollectionCount<T>>::get();446		let destroyed = <DestroyedCollectionCount<T>>::get();447		CollectionStats {448			created: created.0,449			destroyed: destroyed.0,450			alive: created.0 - destroyed.0,451		}452	}453454	pub fn effective_collection_limits(collection: CollectionId) -> Option<CollectionLimits> {455		let collection = <CollectionById<T>>::get(collection);456		if collection.is_none() {457			return None;458		}459460		let collection = collection.unwrap();461		let limits = collection.limits;462		let effective_limits = CollectionLimits {463			account_token_ownership_limit: Some(limits.account_token_ownership_limit()),464			sponsored_data_size: Some(limits.sponsored_data_size()),465			sponsored_data_rate_limit: Some(466				limits467					.sponsored_data_rate_limit468					.unwrap_or(SponsoringRateLimit::SponsoringDisabled),469			),470			token_limit: Some(limits.token_limit()),471			sponsor_transfer_timeout: Some(limits.sponsor_transfer_timeout(472				match collection.mode {473					CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,474					CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,475					CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,476				},477			)),478			sponsor_approve_timeout: Some(limits.sponsor_approve_timeout()),479			owner_can_transfer: Some(limits.owner_can_transfer()),480			owner_can_destroy: Some(limits.owner_can_destroy()),481			transfers_enabled: Some(limits.transfers_enabled()),482		};483484		Some(effective_limits)485	}486}487488impl<T: Config> Pallet<T> {489	pub fn init_collection(490		owner: T::AccountId,491		data: CreateCollectionData<T::AccountId>,492	) -> Result<CollectionId, DispatchError> {493		{494			ensure!(495				data.token_prefix.len() <= MAX_TOKEN_PREFIX_LENGTH as usize,496				Error::<T>::CollectionTokenPrefixLimitExceeded497			);498		}499500		let created_count = <CreatedCollectionCount<T>>::get()501			.0502			.checked_add(1)503			.ok_or(ArithmeticError::Overflow)?;504		let destroyed_count = <DestroyedCollectionCount<T>>::get().0;505		let id = CollectionId(created_count);506507		// bound Total number of collections508		ensure!(509			created_count - destroyed_count <= COLLECTION_NUMBER_LIMIT,510			<Error<T>>::TotalCollectionsLimitExceeded511		);512513		// =========514515		let collection = Collection {516			owner: owner.clone(),517			name: data.name,518			mode: data.mode.clone(),519			mint_mode: false,520			access: data.access.unwrap_or_default(),521			description: data.description,522			token_prefix: data.token_prefix,523			offchain_schema: data.offchain_schema,524			schema_version: data.schema_version.unwrap_or_default(),525			sponsorship: data526				.pending_sponsor527				.map(SponsorshipState::Unconfirmed)528				.unwrap_or_default(),529			variable_on_chain_schema: data.variable_on_chain_schema,530			const_on_chain_schema: data.const_on_chain_schema,531			limits: data532				.limits533				.map(|limits| Self::clamp_limits(data.mode.clone(), &Default::default(), limits))534				.unwrap_or_else(|| Ok(CollectionLimits::default()))?,535			meta_update_permission: data.meta_update_permission.unwrap_or_default(),536		};537538		// Take a (non-refundable) deposit of collection creation539		{540			let mut imbalance =541				<<<T as Config>::Currency as Currency<T::AccountId>>::PositiveImbalance>::zero();542			imbalance.subsume(543				<<T as Config>::Currency as Currency<T::AccountId>>::deposit_creating(544					&T::TreasuryAccountId::get(),545					T::CollectionCreationPrice::get(),546				),547			);548			<T as Config>::Currency::settle(549				&owner,550				imbalance,551				WithdrawReasons::TRANSFER,552				ExistenceRequirement::KeepAlive,553			)554			.map_err(|_| Error::<T>::NotSufficientFounds)?;555		}556557		<CreatedCollectionCount<T>>::put(created_count);558		<Pallet<T>>::deposit_event(Event::CollectionCreated(id, data.mode.id(), owner.clone()));559		<CollectionById<T>>::insert(id, collection);560		Ok(id)561	}562563	pub fn destroy_collection(564		collection: CollectionHandle<T>,565		sender: &T::CrossAccountId,566	) -> DispatchResult {567		ensure!(568			collection.limits.owner_can_destroy(),569			<Error<T>>::NoPermission,570		);571		collection.check_is_owner(sender)?;572573		let destroyed_collections = <DestroyedCollectionCount<T>>::get()574			.0575			.checked_add(1)576			.ok_or(ArithmeticError::Overflow)?;577578		// =========579580		<DestroyedCollectionCount<T>>::put(destroyed_collections);581		<CollectionById<T>>::remove(collection.id);582		<AdminAmount<T>>::remove(collection.id);583		<IsAdmin<T>>::remove_prefix((collection.id,), None);584		<Allowlist<T>>::remove_prefix((collection.id,), None);585586		<Pallet<T>>::deposit_event(Event::CollectionDestroyed(collection.id));587		Ok(())588	}589590	pub fn toggle_allowlist(591		collection: &CollectionHandle<T>,592		sender: &T::CrossAccountId,593		user: &T::CrossAccountId,594		allowed: bool,595	) -> DispatchResult {596		collection.check_is_owner_or_admin(sender)?;597598		// =========599600		if allowed {601			<Allowlist<T>>::insert((collection.id, user), true);602		} else {603			<Allowlist<T>>::remove((collection.id, user));604		}605606		Ok(())607	}608609	pub fn toggle_admin(610		collection: &CollectionHandle<T>,611		sender: &T::CrossAccountId,612		user: &T::CrossAccountId,613		admin: bool,614	) -> DispatchResult {615		collection.check_is_owner_or_admin(sender)?;616617		let was_admin = <IsAdmin<T>>::get((collection.id, user));618		if was_admin == admin {619			return Ok(());620		}621		let amount = <AdminAmount<T>>::get(collection.id);622623		if admin {624			let amount = amount625				.checked_add(1)626				.ok_or(<Error<T>>::CollectionAdminCountExceeded)?;627			ensure!(628				amount <= Self::collection_admins_limit(),629				<Error<T>>::CollectionAdminCountExceeded,630			);631632			// =========633634			<AdminAmount<T>>::insert(collection.id, amount);635			<IsAdmin<T>>::insert((collection.id, user), true);636		} else {637			<AdminAmount<T>>::insert(collection.id, amount.saturating_sub(1));638			<IsAdmin<T>>::remove((collection.id, user));639		}640641		Ok(())642	}643644	pub fn clamp_limits(645		mode: CollectionMode,646		old_limit: &CollectionLimits,647		mut new_limit: CollectionLimits,648	) -> Result<CollectionLimits, DispatchError> {649		macro_rules! limit_default {650				($old:ident, $new:ident, $($field:ident $(($arg:expr))? => $check:expr),* $(,)?) => {{651					$(652						if let Some($new) = $new.$field {653							let $old = $old.$field($($arg)?);654							let _ = $new;655							let _ = $old;656							$check657						} else {658							$new.$field = $old.$field659						}660					)*661				}};662			}663664		limit_default!(old_limit, new_limit,665			account_token_ownership_limit => ensure!(666				new_limit <= MAX_TOKEN_OWNERSHIP,667				<Error<T>>::CollectionLimitBoundsExceeded,668			),669			sponsor_transfer_timeout(match mode {670				CollectionMode::NFT => NFT_SPONSOR_TRANSFER_TIMEOUT,671				CollectionMode::Fungible(_) => FUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,672				CollectionMode::ReFungible => REFUNGIBLE_SPONSOR_TRANSFER_TIMEOUT,673			}) => ensure!(674				new_limit <= MAX_SPONSOR_TIMEOUT,675				<Error<T>>::CollectionLimitBoundsExceeded,676			),677			sponsored_data_size => ensure!(678				new_limit <= CUSTOM_DATA_LIMIT,679				<Error<T>>::CollectionLimitBoundsExceeded,680			),681			token_limit => ensure!(682				old_limit >= new_limit && new_limit > 0,683				<Error<T>>::CollectionTokenLimitExceeded684			),685			owner_can_transfer => ensure!(686				old_limit || !new_limit,687				<Error<T>>::OwnerPermissionsCantBeReverted,688			),689			owner_can_destroy => ensure!(690				old_limit || !new_limit,691				<Error<T>>::OwnerPermissionsCantBeReverted,692			),693			sponsored_data_rate_limit => {},694			transfers_enabled => {},695		);696		Ok(new_limit)697	}698}699700#[macro_export]701macro_rules! unsupported {702	() => {703		Err(<Error<T>>::UnsupportedOperation.into())704	};705}706707/// Worst cases708pub trait CommonWeightInfo<CrossAccountId> {709	fn create_item() -> Weight;710	fn create_multiple_items(amount: u32) -> Weight;711	fn create_multiple_items_ex(cost: &CreateItemExData<CrossAccountId>) -> Weight;712	fn burn_item() -> Weight;713	fn transfer() -> Weight;714	fn approve() -> Weight;715	fn transfer_from() -> Weight;716	fn burn_from() -> Weight;717	fn set_variable_metadata(bytes: u32) -> Weight;718}719720pub trait CommonCollectionOperations<T: Config> {721	fn create_item(722		&self,723		sender: T::CrossAccountId,724		to: T::CrossAccountId,725		data: CreateItemData,726	) -> DispatchResultWithPostInfo;727	fn create_multiple_items(728		&self,729		sender: T::CrossAccountId,730		to: T::CrossAccountId,731		data: Vec<CreateItemData>,732	) -> DispatchResultWithPostInfo;733	fn create_multiple_items_ex(734		&self,735		sender: T::CrossAccountId,736		data: CreateItemExData<T::CrossAccountId>,737	) -> DispatchResultWithPostInfo;738	fn burn_item(739		&self,740		sender: T::CrossAccountId,741		token: TokenId,742		amount: u128,743	) -> DispatchResultWithPostInfo;744745	fn transfer(746		&self,747		sender: T::CrossAccountId,748		to: T::CrossAccountId,749		token: TokenId,750		amount: u128,751	) -> DispatchResultWithPostInfo;752	fn approve(753		&self,754		sender: T::CrossAccountId,755		spender: T::CrossAccountId,756		token: TokenId,757		amount: u128,758	) -> DispatchResultWithPostInfo;759	fn transfer_from(760		&self,761		sender: T::CrossAccountId,762		from: T::CrossAccountId,763		to: T::CrossAccountId,764		token: TokenId,765		amount: u128,766	) -> DispatchResultWithPostInfo;767	fn burn_from(768		&self,769		sender: T::CrossAccountId,770		from: T::CrossAccountId,771		token: TokenId,772		amount: u128,773	) -> DispatchResultWithPostInfo;774775	fn set_variable_metadata(776		&self,777		sender: T::CrossAccountId,778		token: TokenId,779		data: BoundedVec<u8, CustomDataLimit>,780	) -> DispatchResultWithPostInfo;781782	fn nest_token(783		&self,784		sender: T::CrossAccountId,785		from: (CollectionId, TokenId),786		under: TokenId,787	) -> DispatchResult;788789	fn account_tokens(&self, account: T::CrossAccountId) -> Vec<TokenId>;790	fn token_exists(&self, token: TokenId) -> bool;791	fn last_token_id(&self) -> TokenId;792793	fn token_owner(&self, token: TokenId) -> Option<T::CrossAccountId>;794	fn const_metadata(&self, token: TokenId) -> Vec<u8>;795	fn variable_metadata(&self, token: TokenId) -> Vec<u8>;796797	/// How many tokens collection contains (Applicable to nonfungible/refungible)798	fn collection_tokens(&self) -> u32;799	/// Amount of different tokens account has (Applicable to nonfungible/refungible)800	fn account_balance(&self, account: T::CrossAccountId) -> u32;801	/// Amount of specific token account have (Applicable to fungible/refungible)802	fn balance(&self, account: T::CrossAccountId, token: TokenId) -> u128;803	fn allowance(804		&self,805		sender: T::CrossAccountId,806		spender: T::CrossAccountId,807		token: TokenId,808	) -> u128;809}810811// Flexible enough for implementing CommonCollectionOperations812pub fn with_weight(res: DispatchResult, weight: Weight) -> DispatchResultWithPostInfo {813	let post_info = PostDispatchInfo {814		actual_weight: Some(weight),815		pays_fee: Pays::Yes,816	};817	match res {818		Ok(()) => Ok(post_info),819		Err(error) => Err(DispatchErrorWithPostInfo { post_info, error }),820	}821}
modifiedpallets/evm-coder-substrate/Cargo.tomldiffbeforeafterboth
--- a/pallets/evm-coder-substrate/Cargo.toml
+++ b/pallets/evm-coder-substrate/Cargo.toml
@@ -17,6 +17,7 @@
 frame-support = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
 frame-system = { default-features = false, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
 frame-benchmarking = { default-features = false, optional = true, git = "https://github.com/paritytech/substrate", branch = "polkadot-v0.9.20" }
+up-data-structs = { default-features = false, path = "../../primitives/data-structs" }
 
 [dependencies.codec]
 default-features = false
modifiedpallets/evm-coder-substrate/src/lib.rsdiffbeforeafterboth
--- a/pallets/evm-coder-substrate/src/lib.rs
+++ b/pallets/evm-coder-substrate/src/lib.rs
@@ -18,33 +18,43 @@
 
 #[cfg(not(feature = "std"))]
 extern crate alloc;
+#[cfg(not(feature = "std"))]
+use alloc::format;
+use frame_support::dispatch::Weight;
+
+use core::marker::PhantomData;
+use sp_std::cell::RefCell;
+use sp_std::vec::Vec;
+
+use frame_support::pallet_prelude::DispatchError;
+use frame_support::traits::PalletInfo;
+use frame_support::{ensure, sp_runtime::ModuleError};
+use up_data_structs::budget;
+use pallet_evm::{
+	ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,
+	PrecompileResult, runner::stack::MaybeMirroredLog,
+};
+use ethereum::TransactionV2;
+use sp_core::{H160, H256};
+use pallet_ethereum::EthereumTransactionSender;
 // #[cfg(feature = "runtime-benchmarks")]
 // pub mod benchmarking;
 
+use evm_coder::{
+	ToLog,
+	abi::{AbiReader, AbiWrite, AbiWriter},
+	execution::{self, Result},
+	types::{Msg, value},
+};
+
 pub use pallet::*;
 
 #[frame_support::pallet]
 pub mod pallet {
-	#[cfg(not(feature = "std"))]
-	use alloc::format;
+	use super::*;
 
-	use evm_coder::{
-		ToLog,
-		abi::{AbiReader, AbiWrite, AbiWriter},
-		execution::{self, Result},
-		types::{Msg, value},
-	};
-	use frame_support::{ensure, sp_runtime::ModuleError};
-	use pallet_evm::{
-		ExitError, ExitRevert, ExitSucceed, GasWeightMapping, PrecompileFailure, PrecompileOutput,
-		PrecompileResult, runner::stack::MaybeMirroredLog,
-	};
 	use frame_system::ensure_signed;
 	pub use frame_support::dispatch::DispatchResult;
-	use pallet_ethereum::EthereumTransactionSender;
-	use sp_std::cell::RefCell;
-	use sp_std::vec::Vec;
-	use sp_core::H160;
 	use frame_support::{pallet_prelude::*, traits::PalletInfo};
 	use frame_system::pallet_prelude::*;
 
@@ -76,214 +86,258 @@
 			Ok(())
 		}
 	}
+}
 
-	// From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L284
-	pub const G_SLOAD_WORD: u64 = 800;
-	pub const G_SSTORE_WORD: u64 = 20000;
+// From instabul hardfork configuration: https://github.com/rust-blockchain/evm/blob/fd4fd6acc0ca3208d6770fdb3ba407c94cdf97c6/runtime/src/lib.rs#L284
+pub const G_SLOAD_WORD: u64 = 800;
+pub const G_SSTORE_WORD: u64 = 20000;
 
-	#[derive(Default)]
-	pub struct SubstrateRecorder<T: Config> {
-		contract: H160,
-		logs: RefCell<Vec<MaybeMirroredLog>>,
-		initial_gas: u64,
-		gas_limit: RefCell<u64>,
-		_phantom: PhantomData<*const T>,
+pub fn generate_transaction() -> TransactionV2 {
+	use ethereum::{TransactionV0, TransactionAction, TransactionSignature};
+	TransactionV2::Legacy(TransactionV0 {
+		nonce: 0.into(),
+		gas_price: 0.into(),
+		gas_limit: 0.into(),
+		action: TransactionAction::Call(H160([0; 20])),
+		value: 0.into(),
+		// zero selector, this transaction always has same sender, so all data should be acquired from logs
+		input: Vec::from([0, 0, 0, 0]),
+		// if v is not 27 - then we need to pass some other validity checks
+		signature: TransactionSignature::new(27, H256([0x88; 32]), H256([0x88; 32])).unwrap(),
+	})
+}
+
+pub struct GasCallsBudget<'r, T: Config> {
+	recorder: &'r SubstrateRecorder<T>,
+	gas_per_call: u64,
+}
+impl<T: Config> budget::Budget for GasCallsBudget<'_, T> {
+	fn consume_custom(&self, calls: u32) -> bool {
+		let (gas, overflown) = (calls as u64).overflowing_add(self.gas_per_call);
+		if overflown {
+			return false;
+		}
+		self.recorder.consume_gas(gas).is_ok()
 	}
+}
 
-	impl<T: Config> SubstrateRecorder<T> {
-		pub fn new(contract: H160, gas_limit: u64) -> Self {
-			Self {
-				contract,
-				logs: RefCell::new(Vec::new()),
-				initial_gas: gas_limit,
-				gas_limit: RefCell::new(gas_limit),
-				_phantom: PhantomData,
-			}
+#[derive(Default)]
+pub struct SubstrateRecorder<T: Config> {
+	contract: H160,
+	logs: RefCell<Vec<MaybeMirroredLog>>,
+	initial_gas: u64,
+	gas_limit: RefCell<u64>,
+	_phantom: PhantomData<*const T>,
+}
+
+impl<T: Config> SubstrateRecorder<T> {
+	pub fn new(contract: H160, gas_limit: u64) -> Self {
+		Self {
+			contract,
+			logs: RefCell::new(Vec::new()),
+			initial_gas: gas_limit,
+			gas_limit: RefCell::new(gas_limit),
+			_phantom: PhantomData,
 		}
+	}
+
+	pub fn is_empty(&self) -> bool {
+		self.logs.borrow().is_empty()
+	}
+	// Logs emitted with log_direct appear as substrate evm.Log event
+	pub fn log_direct(&self, log: impl ToLog) {
+		self.logs
+			.borrow_mut()
+			.push(MaybeMirroredLog::direct(log.to_log(self.contract)))
+	}
+	/// If log already has substrate equivalent - then we don't need to emit evm.Log
+	pub fn log_mirrored(&self, log: impl ToLog) {
+		self.logs
+			.borrow_mut()
+			.push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))
+	}
+	pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {
+		self.logs.into_inner()
+	}
 
-		pub fn is_empty(&self) -> bool {
-			self.logs.borrow().is_empty()
-		}
-		// Logs emitted with log_direct appear as substrate evm.Log event
-		pub fn log_direct(&self, log: impl ToLog) {
-			self.logs
-				.borrow_mut()
-				.push(MaybeMirroredLog::direct(log.to_log(self.contract)))
-		}
-		/// If log already has substrate equivalent - then we don't need to emit evm.Log
-		pub fn log_mirrored(&self, log: impl ToLog) {
-			self.logs
-				.borrow_mut()
-				.push(MaybeMirroredLog::mirrored(log.to_log(self.contract)))
+	pub fn gas_left(&self) -> u64 {
+		*self.gas_limit.borrow()
+	}
+	pub fn gas_calls_budget(&self, gas_per_call: u64) -> GasCallsBudget<T> {
+		GasCallsBudget {
+			recorder: self,
+			gas_per_call,
 		}
-		pub fn retrieve_logs(self) -> Vec<MaybeMirroredLog> {
-			self.logs.into_inner()
+	}
+	pub fn weight_calls_budget(&self, weight_per_call: Weight) -> GasCallsBudget<T> {
+		GasCallsBudget {
+			recorder: self,
+			gas_per_call: T::GasWeightMapping::weight_to_gas(weight_per_call),
 		}
+	}
+	pub fn consume_sload_sub(&self) -> DispatchResult {
+		self.consume_gas_sub(G_SLOAD_WORD)
+	}
+	pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
+		self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
+	}
+	pub fn consume_sstore_sub(&self) -> DispatchResult {
+		self.consume_gas_sub(G_SSTORE_WORD)
+	}
+	pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
+		ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
+		let mut gas_limit = self.gas_limit.borrow_mut();
+		ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);
+		*gas_limit -= gas;
+		Ok(())
+	}
 
-		pub fn gas_left(&self) -> u64 {
-			*self.gas_limit.borrow()
+	pub fn consume_sload(&self) -> Result<()> {
+		self.consume_gas(G_SLOAD_WORD)
+	}
+	pub fn consume_sstore(&self) -> Result<()> {
+		self.consume_gas(G_SSTORE_WORD)
+	}
+	pub fn consume_gas(&self, gas: u64) -> Result<()> {
+		if gas == u64::MAX {
+			return Err(execution::Error::Error(ExitError::OutOfGas));
 		}
-		pub fn consume_sload_sub(&self) -> DispatchResult {
-			self.consume_gas_sub(G_SLOAD_WORD)
+		let mut gas_limit = self.gas_limit.borrow_mut();
+		if gas > *gas_limit {
+			return Err(execution::Error::Error(ExitError::OutOfGas));
 		}
-		pub fn consume_sstores_sub(&self, amount: usize) -> DispatchResult {
-			self.consume_gas_sub(G_SSTORE_WORD.saturating_mul(amount as u64))
-		}
-		pub fn consume_sstore_sub(&self) -> DispatchResult {
-			self.consume_gas_sub(G_SSTORE_WORD)
-		}
-		pub fn consume_gas_sub(&self, gas: u64) -> DispatchResult {
-			ensure!(gas != u64::MAX, Error::<T>::OutOfGas);
-			let mut gas_limit = self.gas_limit.borrow_mut();
-			ensure!(gas <= *gas_limit, Error::<T>::OutOfGas);
-			*gas_limit -= gas;
-			Ok(())
-		}
+		*gas_limit -= gas;
+		Ok(())
+	}
+	pub fn return_gas(&self, gas: u64) {
+		let mut gas_limit = self.gas_limit.borrow_mut();
+		*gas_limit += gas;
+	}
 
-		pub fn consume_sload(&self) -> Result<()> {
-			self.consume_gas(G_SLOAD_WORD)
-		}
-		pub fn consume_sstore(&self) -> Result<()> {
-			self.consume_gas(G_SSTORE_WORD)
-		}
-		pub fn consume_gas(&self, gas: u64) -> Result<()> {
-			if gas == u64::MAX {
-				return Err(execution::Error::Error(ExitError::OutOfGas));
-			}
-			let mut gas_limit = self.gas_limit.borrow_mut();
-			if gas > *gas_limit {
-				return Err(execution::Error::Error(ExitError::OutOfGas));
-			}
-			*gas_limit -= gas;
-			Ok(())
-		}
-		pub fn return_gas(&self, gas: u64) {
-			let mut gas_limit = self.gas_limit.borrow_mut();
-			*gas_limit += gas;
-		}
+	pub fn evm_to_precompile_output(
+		self,
+		result: evm_coder::execution::Result<Option<AbiWriter>>,
+	) -> Option<PrecompileResult> {
+		use evm_coder::execution::Error;
+		Some(match result {
+			Ok(Some(v)) => Ok(PrecompileOutput {
+				exit_status: ExitSucceed::Returned,
+				cost: self.initial_gas - self.gas_left(),
+				// TODO: preserve mirroring status
+				logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),
+				output: v.finish(),
+			}),
+			Ok(None) => return None,
+			Err(Error::Revert(e)) => {
+				let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
+				(&e as &str).abi_write(&mut writer);
 
-		pub fn evm_to_precompile_output(
-			self,
-			result: evm_coder::execution::Result<Option<AbiWriter>>,
-		) -> Option<PrecompileResult> {
-			use evm_coder::execution::Error;
-			Some(match result {
-				Ok(Some(v)) => Ok(PrecompileOutput {
-					exit_status: ExitSucceed::Returned,
+				Err(PrecompileFailure::Revert {
+					exit_status: ExitRevert::Reverted,
 					cost: self.initial_gas - self.gas_left(),
-					// TODO: preserve mirroring status
-					logs: self.retrieve_logs().into_iter().map(|l| l.log).collect(),
-					output: v.finish(),
-				}),
-				Ok(None) => return None,
-				Err(Error::Revert(e)) => {
-					let mut writer = AbiWriter::new_call(evm_coder::fn_selector!(Error(string)));
-					(&e as &str).abi_write(&mut writer);
+					output: writer.finish(),
+				})
+			}
+			Err(Error::Fatal(f)) => Err(f.into()),
+			Err(Error::Error(e)) => Err(e.into()),
+		})
+	}
 
-					Err(PrecompileFailure::Revert {
-						exit_status: ExitRevert::Reverted,
-						cost: self.initial_gas - self.gas_left(),
-						output: writer.finish(),
-					})
-				}
-				Err(Error::Fatal(f)) => Err(f.into()),
-				Err(Error::Error(e)) => Err(e.into()),
-			})
+	pub fn submit_logs(self) {
+		let logs = self.retrieve_logs();
+		if logs.is_empty() {
+			return;
 		}
+		T::EthereumTransactionSender::submit_logs_transaction(
+			Default::default(),
+			generate_transaction(),
+			logs,
+		)
+	}
+}
 
-		pub fn submit_logs(self) {
-			let logs = self.retrieve_logs();
-			if logs.is_empty() {
-				return;
+pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {
+	use evm_coder::execution::Error as ExError;
+	match err {
+		DispatchError::Module(ModuleError { index, error, .. })
+			if index
+				== T::PalletInfo::index::<Pallet<T>>()
+					.expect("evm-coder-substrate is a pallet, which should be added to runtime")
+					as u8 =>
+		{
+			match error {
+				v if v == Error::<T>::OutOfGas.as_u8() => ExError::Error(ExitError::OutOfGas),
+				v if v == Error::<T>::OutOfFund.as_u8() => ExError::Error(ExitError::OutOfFund),
+				_ => unreachable!("this pallet only defines two possible errors"),
 			}
-			T::EthereumTransactionSender::submit_logs_transaction(Default::default(), logs)
 		}
+		DispatchError::Module(ModuleError {
+			message: Some(msg), ..
+		}) => ExError::Revert(msg.into()),
+		DispatchError::Module(ModuleError { index, error, .. }) => {
+			ExError::Revert(format!("error {} in pallet {}", error, index))
+		}
+		e => ExError::Revert(format!("substrate error: {:?}", e)),
 	}
+}
+
+pub trait WithRecorder<T: Config> {
+	fn recorder(&self) -> &SubstrateRecorder<T>;
+	fn into_recorder(self) -> SubstrateRecorder<T>;
+}
 
-	pub fn dispatch_to_evm<T: Config>(err: DispatchError) -> evm_coder::execution::Error {
-		use evm_coder::execution::Error as ExError;
-		match err {
-			DispatchError::Module(ModuleError { index, error, .. })
-				if index
-					== T::PalletInfo::index::<Pallet<T>>()
-						.expect("evm-coder-substrate is a pallet, which should be added to runtime")
-						as u8 =>
-			{
-				let mut read = &error as &[u8];
-				match Error::<T>::decode(&mut read) {
-					Ok(Error::<T>::OutOfGas) => ExError::Error(ExitError::OutOfGas),
-					Ok(Error::<T>::OutOfFund) => ExError::Error(ExitError::OutOfFund),
-					_ => unreachable!("this pallet only defines two possible errors"),
-				}
-			}
-			DispatchError::Module(ModuleError {
-				message: Some(msg), ..
-			}) => ExError::Revert(msg.into()),
-			DispatchError::Module(ModuleError { index, error, .. }) => {
-				ExError::Revert(format!("error {:?} in pallet {}", error, index))
-			}
-			e => ExError::Revert(format!("substrate error: {:?}", e)),
-		}
-	}
+/// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm
+pub fn call<
+	T: Config,
+	C: evm_coder::Call + evm_coder::Weighted,
+	E: evm_coder::Callable<C> + WithRecorder<T>,
+>(
+	caller: H160,
+	mut e: E,
+	value: value,
+	input: &[u8],
+) -> Option<PrecompileResult> {
+	let result = call_internal(caller, &mut e, value, input);
+	e.into_recorder().evm_to_precompile_output(result)
+}
 
-	pub trait WithRecorder<T: Config> {
-		fn recorder(&self) -> &SubstrateRecorder<T>;
-		fn into_recorder(self) -> SubstrateRecorder<T>;
+fn call_internal<
+	T: Config,
+	C: evm_coder::Call + evm_coder::Weighted,
+	E: evm_coder::Callable<C> + WithRecorder<T>,
+>(
+	caller: H160,
+	e: &mut E,
+	value: value,
+	input: &[u8],
+) -> evm_coder::execution::Result<Option<AbiWriter>> {
+	let (selector, mut reader) = AbiReader::new_call(input)?;
+	let call = C::parse(selector, &mut reader)?;
+	if call.is_none() {
+		return Ok(None);
 	}
+	let call = call.unwrap();
 
-	/// Helper to simplify implementing bridge between evm-coder definitions and pallet-evm
-	pub fn call<
-		T: Config,
-		C: evm_coder::Call + evm_coder::Weighted,
-		E: evm_coder::Callable<C> + WithRecorder<T>,
-	>(
-		caller: H160,
-		mut e: E,
-		value: value,
-		input: &[u8],
-	) -> Option<PrecompileResult> {
-		let result = call_internal(caller, &mut e, value, input);
-		e.into_recorder().evm_to_precompile_output(result)
-	}
+	let dispatch_info = call.weight();
+	e.recorder()
+		.consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;
 
-	fn call_internal<
-		T: Config,
-		C: evm_coder::Call + evm_coder::Weighted,
-		E: evm_coder::Callable<C> + WithRecorder<T>,
-	>(
-		caller: H160,
-		e: &mut E,
-		value: value,
-		input: &[u8],
-	) -> evm_coder::execution::Result<Option<AbiWriter>> {
-		let (selector, mut reader) = AbiReader::new_call(input)?;
-		let call = C::parse(selector, &mut reader)?;
-		if call.is_none() {
-			return Ok(None);
+	match e.call(Msg {
+		call,
+		caller,
+		value,
+	}) {
+		Ok(v) => {
+			let unspent = v.post_info.calc_unspent(&dispatch_info);
+			e.recorder()
+				.return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+			Ok(Some(v.data))
 		}
-		let call = call.unwrap();
-
-		let dispatch_info = call.weight();
-		e.recorder()
-			.consume_gas(T::GasWeightMapping::weight_to_gas(dispatch_info.weight))?;
-
-		match e.call(Msg {
-			call,
-			caller,
-			value,
-		}) {
-			Ok(v) => {
-				let unspent = v.post_info.calc_unspent(&dispatch_info);
-				e.recorder()
-					.return_gas(T::GasWeightMapping::weight_to_gas(unspent));
-				Ok(Some(v.data))
-			}
-			Err(v) => {
-				let unspent = v.post_info.calc_unspent(&dispatch_info);
-				e.recorder()
-					.return_gas(T::GasWeightMapping::weight_to_gas(unspent));
-				Err(v.data)
-			}
+		Err(v) => {
+			let unspent = v.post_info.calc_unspent(&dispatch_info);
+			e.recorder()
+				.return_gas(T::GasWeightMapping::weight_to_gas(unspent));
+			Err(v.data)
 		}
 	}
 }
modifiedpallets/fungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
 use sp_std::prelude::*;
 use pallet_common::benchmarking::create_collection_raw;
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, budget::Unlimited};
 use pallet_common::bench_init;
 
 const SEED: u32 = 1;
@@ -52,7 +52,7 @@
 			bench_init!(to: cross_sub(i););
 			(to, 200)
 		}).collect::<BTreeMap<_, _>>().try_into().unwrap();
-	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)}
+	}: {<Pallet<T>>::create_multiple_items(&collection, &sender, data)?}
 
 	burn_item {
 		bench_init!{
@@ -85,7 +85,7 @@
 		};
 		<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
 
 	burn_from {
 		bench_init!{
@@ -94,5 +94,5 @@
 		};
 		<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200))?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &burner, 200)?;
-	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, 100)?}
+	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, 100, &Unlimited)?}
 }
modifiedpallets/fungible/src/common.rsdiffbeforeafterboth
--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CreateItemExData};
+use up_data_structs::{TokenId, CreateItemExData, budget::Budget};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::ArithmeticError;
 use sp_std::{vec::Vec, vec};
@@ -189,6 +189,7 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(
 			token == TokenId::default(),
@@ -196,7 +197,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount),
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),
 			<CommonWeights<T>>::transfer_from(),
 		)
 	}
@@ -207,6 +208,7 @@
 		from: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(
 			token == TokenId::default(),
@@ -214,7 +216,7 @@
 		);
 
 		with_weight(
-			<Pallet<T>>::burn_from(self, &sender, &from, amount),
+			<Pallet<T>>::burn_from(self, &sender, &from, amount, nesting_budget),
 			<CommonWeights<T>>::burn_from(),
 		)
 	}
modifiedpallets/fungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -23,6 +23,7 @@
 use sp_std::vec::Vec;
 use pallet_evm::account::CrossAccountId;
 use pallet_evm_coder_substrate::{call, dispatch_to_evm};
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
 
 use crate::{
 	Allowance, Balance, Config, FungibleHandle, Pallet, SelfWeightOf, TotalSupply,
@@ -96,8 +97,11 @@
 		let from = T::CrossAccountId::from_eth(from);
 		let to = T::CrossAccountId::from_eth(to);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount)
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
@@ -127,8 +131,12 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let from = T::CrossAccountId::from_eth(from);
 		let amount = amount.try_into().map_err(|_| "amount overflow")?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::burn_from(self, &caller, &from, amount).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::burn_from(self, &caller, &from, amount, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
 		Ok(true)
 	}
 }
modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -21,6 +21,7 @@
 use pallet_evm::account::CrossAccountId;
 use up_data_structs::{
 	AccessMode, CollectionId, TokenId, CreateCollectionData, mapping::TokenAddressMapping,
+	budget::Budget,
 };
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
@@ -361,6 +362,7 @@
 		spender: &T::CrossAccountId,
 		from: &T::CrossAccountId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> Result<Option<u128>, DispatchError> {
 		if spender.conv_eq(from) {
 			return Ok(None);
@@ -372,7 +374,12 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,
+				<PalletStructure<T>>::indirectly_owned(
+					spender.clone(),
+					source.0,
+					source.1,
+					nesting_budget
+				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
 			);
 			return Ok(None);
@@ -394,8 +401,9 @@
 		from: &T::CrossAccountId,
 		to: &T::CrossAccountId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let allowance = Self::check_allowed(collection, spender, from, amount)?;
+		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
 
 		// =========
 
@@ -411,8 +419,9 @@
 		spender: &T::CrossAccountId,
 		from: &T::CrossAccountId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let allowance = Self::check_allowed(collection, spender, from, amount)?;
+		let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
 
 		// =========
 
modifiedpallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
 use sp_std::prelude::*;
 use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
 use pallet_common::bench_init;
 use core::convert::TryInto;
 
@@ -115,7 +115,7 @@
 		};
 		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)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
 
 	burn_from {
 		bench_init!{
@@ -124,7 +124,7 @@
 		};
 		let item = create_max_item(&collection, &owner, sender.clone())?;
 		<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&burner))?;
-	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item)?}
+	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, &Unlimited)?}
 
 	set_variable_metadata {
 		let b in 0..CUSTOM_DATA_LIMIT;
modifiedpallets/nonfungible/src/common.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -17,7 +17,7 @@
 use core::marker::PhantomData;
 
 use frame_support::{dispatch::DispatchResultWithPostInfo, ensure, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId};
+use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CollectionId, budget::Budget};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
 use sp_std::vec::Vec;
@@ -192,12 +192,13 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token),
+				<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
 				<CommonWeights<T>>::transfer_from(),
 			)
 		} else {
@@ -211,12 +212,13 @@
 		from: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
 
 		if amount == 1 {
 			with_weight(
-				<Pallet<T>>::burn_from(self, &sender, &from, token),
+				<Pallet<T>>::burn_from(self, &sender, &from, token, nesting_budget),
 				<CommonWeights<T>>::burn_from(),
 			)
 		} else {
modifiedpallets/nonfungible/src/erc.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -30,6 +30,7 @@
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_evm_coder_substrate::call;
+use pallet_structure::{SelfWeightOf as StructureWeight, weights::WeightInfo as _};
 
 use crate::{
 	AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
@@ -180,8 +181,11 @@
 		let from = T::CrossAccountId::from_eth(from);
 		let to = T::CrossAccountId::from_eth(to);
 		let token = token_id.try_into()?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token)
+		<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
 			.map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
@@ -350,8 +354,12 @@
 		let caller = T::CrossAccountId::from_eth(caller);
 		let from = T::CrossAccountId::from_eth(from);
 		let token = token_id.try_into()?;
+		let budget = self
+			.recorder
+			.weight_calls_budget(<StructureWeight<T>>::find_parent());
 
-		<Pallet<T>>::burn_from(self, &caller, &from, token).map_err(dispatch_to_evm::<T>)?;
+		<Pallet<T>>::burn_from(self, &caller, &from, token, &budget)
+			.map_err(dispatch_to_evm::<T>)?;
 		Ok(())
 	}
 
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -20,7 +20,7 @@
 use frame_support::{BoundedVec, ensure, fail};
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,
-	mapping::TokenAddressMapping, NestingRule,
+	mapping::TokenAddressMapping, NestingRule, budget::Budget,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -511,6 +511,7 @@
 		spender: &T::CrossAccountId,
 		from: &T::CrossAccountId,
 		token: TokenId,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
 		if spender.conv_eq(from) {
 			return Ok(());
@@ -522,7 +523,12 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,
+				<PalletStructure<T>>::indirectly_owned(
+					spender.clone(),
+					source.0,
+					source.1,
+					nesting_budget
+				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
 			);
 			return Ok(());
@@ -543,8 +549,9 @@
 		from: &T::CrossAccountId,
 		to: &T::CrossAccountId,
 		token: TokenId,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::check_allowed(collection, spender, from, token)?;
+		Self::check_allowed(collection, spender, from, token, nesting_budget)?;
 
 		// =========
 
@@ -557,8 +564,9 @@
 		spender: &T::CrossAccountId,
 		from: &T::CrossAccountId,
 		token: TokenId,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		Self::check_allowed(collection, spender, from, token)?;
+		Self::check_allowed(collection, spender, from, token, nesting_budget)?;
 
 		// =========
 
modifiedpallets/refungible/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/refungible/src/benchmarking.rs
+++ b/pallets/refungible/src/benchmarking.rs
@@ -20,7 +20,7 @@
 use sp_std::prelude::*;
 use pallet_common::benchmarking::{create_collection_raw, create_data, create_var_data};
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT};
+use up_data_structs::{CollectionMode, MAX_ITEMS_PER_BATCH, CUSTOM_DATA_LIMIT, budget::Unlimited};
 use pallet_common::bench_init;
 use core::convert::TryInto;
 use core::iter::IntoIterator;
@@ -165,7 +165,7 @@
 		};
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100, &Unlimited)?}
 	// Target account is created
 	transfer_from_creating {
 		bench_init!{
@@ -174,7 +174,7 @@
 		};
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 100)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 100, &Unlimited)?}
 	// Source account is destroyed
 	transfer_from_removing {
 		bench_init!{
@@ -183,7 +183,7 @@
 		};
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200), (receiver.clone(), 200)])?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200, &Unlimited)?}
 	// Source account destroyed, target created
 	transfer_from_creating_removing {
 		bench_init!{
@@ -192,7 +192,7 @@
 		};
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &spender, item, 200)?;
-	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200)?}
+	}: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, 200, &Unlimited)?}
 
 	// Both source account and token is destroyed
 	burn_from {
@@ -202,7 +202,7 @@
 		};
 		let item = create_max_item(&collection, &owner, [(sender.clone(), 200)])?;
 		<Pallet<T>>::set_allowance(&collection, &sender, &burner, item, 200)?;
-	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200)?}
+	}: {<Pallet<T>>::burn_from(&collection, &burner, &sender, item, 200, &Unlimited)?}
 
 	set_variable_metadata {
 		let b in 0..CUSTOM_DATA_LIMIT;
modifiedpallets/refungible/src/common.rsdiffbeforeafterboth
--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -18,7 +18,9 @@
 
 use sp_std::collections::btree_map::BTreeMap;
 use frame_support::{dispatch::DispatchResultWithPostInfo, fail, weights::Weight, BoundedVec};
-use up_data_structs::{TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData};
+use up_data_structs::{
+	TokenId, CustomDataLimit, CreateItemExData, CreateRefungibleExData, budget::Budget,
+};
 use pallet_common::{CommonCollectionOperations, CommonWeightInfo, with_weight};
 use sp_runtime::DispatchError;
 use sp_std::{vec::Vec, vec};
@@ -210,9 +212,10 @@
 		to: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount),
+			<Pallet<T>>::transfer_from(self, &sender, &from, &to, token, amount, nesting_budget),
 			<CommonWeights<T>>::transfer_from(),
 		)
 	}
@@ -223,9 +226,10 @@
 		from: T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResultWithPostInfo {
 		with_weight(
-			<Pallet<T>>::burn_from(self, &sender, &from, token, amount),
+			<Pallet<T>>::burn_from(self, &sender, &from, token, amount, nesting_budget),
 			<CommonWeights<T>>::burn_from(),
 		)
 	}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -19,7 +19,7 @@
 use frame_support::{ensure, BoundedVec};
 use up_data_structs::{
 	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,
-	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping,
+	CreateCollectionData, CreateRefungibleExData, mapping::TokenAddressMapping, budget::Budget,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -544,6 +544,7 @@
 		from: &T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> Result<Option<u128>, DispatchError> {
 		if spender.conv_eq(from) {
 			return Ok(None);
@@ -555,7 +556,12 @@
 		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {
 			// TODO: should collection owner be allowed to perform this transfer?
 			ensure!(
-				<PalletStructure<T>>::indirectly_owned(spender.clone(), source.0, source.1, 1)?,
+				<PalletStructure<T>>::indirectly_owned(
+					spender.clone(),
+					source.0,
+					source.1,
+					nesting_budget
+				)?,
 				<CommonError<T>>::ApprovedValueTooLow,
 			);
 			return Ok(None);
@@ -578,8 +584,10 @@
 		to: &T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let allowance = Self::check_allowed(collection, spender, from, token, amount)?;
+		let allowance =
+			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;
 
 		// =========
 
@@ -596,8 +604,10 @@
 		from: &T::CrossAccountId,
 		token: TokenId,
 		amount: u128,
+		nesting_budget: &dyn Budget,
 	) -> DispatchResult {
-		let allowance = Self::check_allowed(collection, spender, from, token, amount)?;
+		let allowance =
+			Self::check_allowed(collection, spender, from, token, amount, nesting_budget)?;
 
 		// =========
 
modifiedpallets/structure/src/lib.rsdiffbeforeafterboth
--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -6,8 +6,14 @@
 use frame_support::fail;
 pub use pallet::*;
 use pallet_common::{dispatch::CollectionDispatch, CollectionHandle};
-use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping};
+use up_data_structs::{CollectionId, TokenId, mapping::TokenAddressMapping, budget::Budget};
 
+#[cfg(feature = "runtime-benchmarks")]
+pub mod benchmarking;
+pub mod weights;
+
+pub type SelfWeightOf<T> = <T as crate::Config>::WeightInfo;
+
 #[frame_support::pallet]
 pub mod pallet {
 	use frame_support::Parameter;
@@ -35,6 +41,7 @@
 
 	#[pallet::config]
 	pub trait Config: frame_system::Config + pallet_common::Config {
+		type WeightInfo: weights::WeightInfo;
 		type Event: IsType<<Self as frame_system::Config>::Event> + From<Event<Self>>;
 		type Call: Parameter + UnfilteredDispatchable<Origin = Self::Origin> + GetDispatchInfo;
 	}
@@ -127,10 +134,10 @@
 	pub fn find_topmost_owner(
 		collection: CollectionId,
 		token: TokenId,
-		max_depth: u32,
+		budget: &dyn Budget,
 	) -> Result<T::CrossAccountId, DispatchError> {
 		let owner = Self::parent_chain(collection, token)
-			.take(max_depth as usize)
+			.take_while(|_| budget.consume())
 			.find(|p| matches!(p, Ok(Parent::Normal(_) | Parent::TokenNotFound)))
 			.ok_or(<Error<T>>::DepthLimit)??;
 
@@ -145,7 +152,7 @@
 		user: T::CrossAccountId,
 		collection: CollectionId,
 		token: TokenId,
-		max_depth: u32,
+		budget: &dyn Budget,
 	) -> Result<bool, DispatchError> {
 		let target_parent = match T::CrossTokenAddressMapping::address_to_token(&user) {
 			Some((collection, token)) => Parent::Token(collection, token),
@@ -153,7 +160,7 @@
 		};
 
 		Ok(Self::parent_chain(collection, token)
-			.take(max_depth as usize)
+			.take_while(|_| budget.consume())
 			.any(|parent| Ok(&target_parent) == parent.as_ref()))
 	}
 }
modifiedpallets/unique/src/benchmarking.rsdiffbeforeafterboth
--- a/pallets/unique/src/benchmarking.rs
+++ b/pallets/unique/src/benchmarking.rs
@@ -19,8 +19,8 @@
 use super::*;
 use crate::Pallet;
 use frame_system::RawOrigin;
+use frame_support::traits::{tokens::currency::Currency, Get};
 use frame_benchmarking::{benchmarks, account};
-use up_data_structs::*;
 use sp_runtime::DispatchError;
 use pallet_common::benchmarking::{create_data, create_var_data, create_u16_data};
 
@@ -173,6 +173,7 @@
 			owner_can_transfer: Some(true),
 			sponsored_data_rate_limit: None,
 			transfers_enabled: Some(true),
+			nesting_rule: None,
 		};
 	}: set_collection_limits(RawOrigin::Signed(caller.clone()), collection, cl)
 
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -43,7 +43,7 @@
 	MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
 	AccessMode, CreateItemData, CollectionLimits, CollectionId, CollectionMode, TokenId,
 	SchemaVersion, SponsorshipState, MetaUpdatePermission, CreateCollectionData, CustomDataLimit,
-	CreateItemExData,
+	CreateItemExData, budget,
 };
 use pallet_evm::account::CrossAccountId;
 use pallet_common::{
@@ -807,8 +807,9 @@
 		#[transactional]
 		pub fn burn_from(origin, collection_id: CollectionId, from: T::CrossAccountId, item_id: TokenId, value: u128) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+			let budget = budget::Value::new(2);
 
-			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value))
+			dispatch_call::<T, _>(collection_id, |d| d.burn_from(sender, from, item_id, value, &budget))
 		}
 
 		/// Change ownership of the token.
@@ -888,8 +889,9 @@
 		#[transactional]
 		pub fn transfer_from(origin, from: T::CrossAccountId, recipient: T::CrossAccountId, collection_id: CollectionId, item_id: TokenId, value: u128 ) -> DispatchResultWithPostInfo {
 			let sender = T::CrossAccountId::from_sub(ensure_signed(origin)?);
+			let budget = budget::Value::new(2);
 
-			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value))
+			dispatch_call::<T, _>(collection_id, |d| d.transfer_from(sender, from, recipient, item_id, value, &budget))
 		}
 
 		/// Set off-chain data schema.
addedprimitives/data-structs/src/budget.rsdiffbeforeafterboth
--- /dev/null
+++ b/primitives/data-structs/src/budget.rs
@@ -0,0 +1,38 @@
+use core::cell::Cell;
+
+pub trait Budget {
+	/// Returns true while not exceeded
+	fn consume(&self) -> bool {
+		self.consume_custom(1)
+	}
+	/// Returns true while not exceeded
+	/// Implementations should use interior mutabilitiy
+	fn consume_custom(&self, calls: u32) -> bool;
+}
+
+pub struct Unlimited;
+impl Budget for Unlimited {
+	fn consume_custom(&self, _calls: u32) -> bool {
+		true
+	}
+}
+
+pub struct Value(Cell<u32>);
+impl Value {
+	pub fn new(v: u32) -> Self {
+		Self(Cell::new(v))
+	}
+	pub fn refund(self) -> u32 {
+		self.0.get()
+	}
+}
+impl Budget for Value {
+	fn consume_custom(&self, calls: u32) -> bool {
+		let (result, overflown) = self.0.get().overflowing_sub(calls);
+		if overflown {
+			return false;
+		}
+		self.0.set(result);
+		true
+	}
+}
modifiedprimitives/data-structs/src/lib.rsdiffbeforeafterboth
--- a/primitives/data-structs/src/lib.rs
+++ b/primitives/data-structs/src/lib.rs
@@ -35,6 +35,7 @@
 use scale_info::TypeInfo;
 
 mod bounded;
+pub mod budget;
 pub mod mapping;
 mod migration;