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

difftreelog

fix warnings

Igor Kozyrev2022-02-17parent: #4664e20.patch.diff
in: master

4 files changed

modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -2,7 +2,7 @@
 
 use core::ops::Deref;
 use frame_support::{ensure};
-use up_data_structs::{AccessMode, Collection, CollectionId, TokenId, CreateCollectionData};
+use up_data_structs::{AccessMode, CollectionId, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,
 };
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/nonfungible/src/lib.rs
+++ b/pallets/nonfungible/src/lib.rs
@@ -2,9 +2,7 @@
 
 use erc::ERC721Events;
 use frame_support::{BoundedVec, ensure};
-use up_data_structs::{
-	AccessMode, Collection, CollectionId, CustomDataLimit, TokenId, CreateCollectionData,
-};
+use up_data_structs::{AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData};
 use pallet_common::{
 	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, account::CrossAccountId,
 };
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
before · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5	AccessMode, Collection, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId,6	CreateCollectionData,7};8use pallet_common::{9	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,10};11use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};12use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};13use core::ops::Deref;14use codec::{Encode, Decode, MaxEncodedLen};15use scale_info::TypeInfo;1617pub use pallet::*;18#[cfg(feature = "runtime-benchmarks")]19pub mod benchmarking;20pub mod common;21pub mod erc;22pub mod weights;23pub struct CreateItemData<T: Config> {24	pub const_data: BoundedVec<u8, CustomDataLimit>,25	pub variable_data: BoundedVec<u8, CustomDataLimit>,26	pub users: BTreeMap<T::CrossAccountId, u128>,27}28pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2930#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]31pub struct ItemData {32	pub const_data: BoundedVec<u8, CustomDataLimit>,33	pub variable_data: BoundedVec<u8, CustomDataLimit>,34}3536#[frame_support::pallet]37pub mod pallet {38	use super::*;39	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};40	use up_data_structs::{CollectionId, TokenId};41	use super::weights::WeightInfo;4243	#[pallet::error]44	pub enum Error<T> {45		/// Not Refungible item data used to mint in Refungible collection.46		NotRefungibleDataUsedToMintFungibleCollectionToken,47		/// Maximum refungibility exceeded48		WrongRefungiblePieces,49	}5051	#[pallet::config]52	pub trait Config: frame_system::Config + pallet_common::Config {53		type WeightInfo: WeightInfo;54	}5556	#[pallet::pallet]57	#[pallet::generate_store(pub(super) trait Store)]58	pub struct Pallet<T>(_);5960	#[pallet::storage]61	pub type TokensMinted<T: Config> =62		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;63	#[pallet::storage]64	pub type TokensBurnt<T: Config> =65		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6667	#[pallet::storage]68	pub type TokenData<T: Config> = StorageNMap<69		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),70		Value = ItemData,71		QueryKind = ValueQuery,72	>;7374	#[pallet::storage]75	pub type TotalSupply<T: Config> = StorageNMap<76		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),77		Value = u128,78		QueryKind = ValueQuery,79	>;8081	/// Used to enumerate tokens owned by account82	#[pallet::storage]83	pub type Owned<T: Config> = StorageNMap<84		Key = (85			Key<Twox64Concat, CollectionId>,86			Key<Blake2_128Concat, T::CrossAccountId>,87			Key<Twox64Concat, TokenId>,88		),89		Value = bool,90		QueryKind = ValueQuery,91	>;9293	#[pallet::storage]94	pub type AccountBalance<T: Config> = StorageNMap<95		Key = (96			Key<Twox64Concat, CollectionId>,97			// Owner98			Key<Blake2_128Concat, T::CrossAccountId>,99		),100		Value = u32,101		QueryKind = ValueQuery,102	>;103104	#[pallet::storage]105	pub type Balance<T: Config> = StorageNMap<106		Key = (107			Key<Twox64Concat, CollectionId>,108			Key<Twox64Concat, TokenId>,109			// Owner110			Key<Blake2_128Concat, T::CrossAccountId>,111		),112		Value = u128,113		QueryKind = ValueQuery,114	>;115116	#[pallet::storage]117	pub type Allowance<T: Config> = StorageNMap<118		Key = (119			Key<Twox64Concat, CollectionId>,120			Key<Twox64Concat, TokenId>,121			// Owner122			Key<Blake2_128, T::CrossAccountId>,123			// Spender124			Key<Blake2_128Concat, T::CrossAccountId>,125		),126		Value = u128,127		QueryKind = ValueQuery,128	>;129}130131pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);132impl<T: Config> RefungibleHandle<T> {133	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {134		Self(inner)135	}136	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {137		self.0138	}139}140impl<T: Config> Deref for RefungibleHandle<T> {141	type Target = pallet_common::CollectionHandle<T>;142143	fn deref(&self) -> &Self::Target {144		&self.0145	}146}147148impl<T: Config> Pallet<T> {149	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {150		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)151	}152	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {153		<TotalSupply<T>>::contains_key((collection.id, token))154	}155}156157// unchecked calls skips any permission checks158impl<T: Config> Pallet<T> {159	pub fn init_collection(160		owner: T::AccountId,161		data: CreateCollectionData<T::AccountId>,162	) -> Result<CollectionId, DispatchError> {163		<PalletCommon<T>>::init_collection(owner, data)164	}165	pub fn destroy_collection(166		collection: RefungibleHandle<T>,167		sender: &T::CrossAccountId,168	) -> DispatchResult {169		let id = collection.id;170171		// =========172173		PalletCommon::destroy_collection(collection.0, sender)?;174175		<TokensMinted<T>>::remove(id);176		<TokensBurnt<T>>::remove(id);177		<TokenData<T>>::remove_prefix((id,), None);178		<TotalSupply<T>>::remove_prefix((id,), None);179		<Balance<T>>::remove_prefix((id,), None);180		<Allowance<T>>::remove_prefix((id,), None);181		<Owned<T>>::remove_prefix((id,), None);182		<AccountBalance<T>>::remove_prefix((id,), None);183		Ok(())184	}185186	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {187		let burnt = <TokensBurnt<T>>::get(collection.id)188			.checked_add(1)189			.ok_or(ArithmeticError::Overflow)?;190191		<TokensBurnt<T>>::insert(collection.id, burnt);192		<TokenData<T>>::remove((collection.id, token_id));193		<TotalSupply<T>>::remove((collection.id, token_id));194		<Balance<T>>::remove_prefix((collection.id, token_id), None);195		<Allowance<T>>::remove_prefix((collection.id, token_id), None);196		// TODO: ERC721 transfer event197		Ok(())198	}199200	pub fn burn(201		collection: &RefungibleHandle<T>,202		owner: &T::CrossAccountId,203		token: TokenId,204		amount: u128,205	) -> DispatchResult {206		let total_supply = <TotalSupply<T>>::get((collection.id, token))207			.checked_sub(amount)208			.ok_or(<CommonError<T>>::TokenValueTooLow)?;209210		// This was probally last owner of this token?211		if total_supply == 0 {212			// Ensure user actually owns this amount213			ensure!(214				<Balance<T>>::get((collection.id, token, owner)) == amount,215				<CommonError<T>>::TokenValueTooLow216			);217			let account_balance = <AccountBalance<T>>::get((collection.id, owner))218				.checked_sub(1)219				// Should not occur220				.ok_or(ArithmeticError::Underflow)?;221222			// =========223224			<Owned<T>>::remove((collection.id, owner, token));225			<AccountBalance<T>>::insert((collection.id, owner), account_balance);226			Self::burn_token(collection, token)?;227			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(228				collection.id,229				token,230				owner.clone(),231				amount,232			));233			return Ok(());234		}235236		let balance = <Balance<T>>::get((collection.id, token, owner))237			.checked_sub(amount)238			.ok_or(<CommonError<T>>::TokenValueTooLow)?;239		let account_balance = if balance == 0 {240			<AccountBalance<T>>::get((collection.id, owner))241				.checked_sub(1)242				// Should not occur243				.ok_or(ArithmeticError::Underflow)?244		} else {245			0246		};247248		// =========249250		if balance == 0 {251			<Owned<T>>::remove((collection.id, owner, token));252			<Balance<T>>::remove((collection.id, token, owner));253			<AccountBalance<T>>::insert((collection.id, owner), account_balance);254		} else {255			<Balance<T>>::insert((collection.id, token, owner), balance);256		}257		<TotalSupply<T>>::insert((collection.id, token), total_supply);258		// TODO: ERC20 transfer event259		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(260			collection.id,261			token,262			owner.clone(),263			amount,264		));265		Ok(())266	}267268	pub fn transfer(269		collection: &RefungibleHandle<T>,270		from: &T::CrossAccountId,271		to: &T::CrossAccountId,272		token: TokenId,273		amount: u128,274	) -> DispatchResult {275		ensure!(276			collection.limits.transfers_enabled(),277			<CommonError<T>>::TransferNotAllowed278		);279280		if collection.access == AccessMode::AllowList {281			collection.check_allowlist(from)?;282			collection.check_allowlist(to)?;283		}284		<PalletCommon<T>>::ensure_correct_receiver(to)?;285286		let balance_from = <Balance<T>>::get((collection.id, token, from))287			.checked_sub(amount)288			.ok_or(<CommonError<T>>::TokenValueTooLow)?;289		let mut create_target = false;290		let from_to_differ = from != to;291		let balance_to = if from != to {292			let old_balance = <Balance<T>>::get((collection.id, token, to));293			if old_balance == 0 {294				create_target = true;295			}296			Some(297				old_balance298					.checked_add(amount)299					.ok_or(ArithmeticError::Overflow)?,300			)301		} else {302			None303		};304305		let account_balance_from = if balance_from == 0 {306			Some(307				<AccountBalance<T>>::get((collection.id, from))308					.checked_sub(1)309					// Should not occur310					.ok_or(ArithmeticError::Underflow)?,311			)312		} else {313			None314		};315		// Account data is created in token, AccountBalance should be increased316		// But only if from != to as we shouldn't check overflow in this case317		let account_balance_to = if create_target && from_to_differ {318			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))319				.checked_add(1)320				.ok_or(ArithmeticError::Overflow)?;321			ensure!(322				account_balance_to < collection.limits.account_token_ownership_limit(),323				<CommonError<T>>::AccountTokenLimitExceeded,324			);325326			Some(account_balance_to)327		} else {328			None329		};330331		// =========332333		if let Some(balance_to) = balance_to {334			// from != to335			if balance_from == 0 {336				<Balance<T>>::remove((collection.id, token, from));337			} else {338				<Balance<T>>::insert((collection.id, token, from), balance_from);339			}340			<Balance<T>>::insert((collection.id, token, to), balance_to);341			if let Some(account_balance_from) = account_balance_from {342				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);343				<Owned<T>>::remove((collection.id, from, token));344			}345			if let Some(account_balance_to) = account_balance_to {346				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);347				<Owned<T>>::insert((collection.id, to, token), true);348			}349		}350351		// TODO: ERC20 transfer event352		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(353			collection.id,354			token,355			from.clone(),356			to.clone(),357			amount,358		));359		Ok(())360	}361362	pub fn create_multiple_items(363		collection: &RefungibleHandle<T>,364		sender: &T::CrossAccountId,365		data: Vec<CreateItemData<T>>,366	) -> DispatchResult {367		if !collection.is_owner_or_admin(sender) {368			ensure!(369				collection.mint_mode,370				<CommonError<T>>::PublicMintingNotAllowed371			);372			collection.check_allowlist(sender)?;373374			for item in data.iter() {375				for user in item.users.keys() {376					collection.check_allowlist(user)?;377				}378			}379		}380381		for item in data.iter() {382			for (owner, _) in item.users.iter() {383				<PalletCommon<T>>::ensure_correct_receiver(owner)?;384			}385		}386387		// Total pieces per tokens388		let totals = data389			.iter()390			.map(|data| {391				Ok(data392					.users393					.iter()394					.map(|u| u.1)395					.try_fold(0u128, |acc, v| acc.checked_add(*v))396					.ok_or(ArithmeticError::Overflow)?)397			})398			.collect::<Result<Vec<_>, DispatchError>>()?;399		for total in &totals {400			ensure!(401				*total <= MAX_REFUNGIBLE_PIECES,402				<Error<T>>::WrongRefungiblePieces403			);404		}405406		let first_token_id = <TokensMinted<T>>::get(collection.id);407		let tokens_minted = first_token_id408			.checked_add(data.len() as u32)409			.ok_or(ArithmeticError::Overflow)?;410		ensure!(411			tokens_minted < collection.limits.token_limit(),412			<CommonError<T>>::CollectionTokenLimitExceeded413		);414415		let mut balances = BTreeMap::new();416		for data in &data {417			for owner in data.users.keys() {418				let balance = balances419					.entry(owner)420					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));421				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;422423				ensure!(424					*balance <= collection.limits.account_token_ownership_limit(),425					<CommonError<T>>::AccountTokenLimitExceeded,426				);427			}428		}429430		// =========431432		<TokensMinted<T>>::insert(collection.id, tokens_minted);433		for (account, balance) in balances {434			<AccountBalance<T>>::insert((collection.id, account), balance);435		}436		for (i, token) in data.into_iter().enumerate() {437			let token_id = first_token_id + i as u32 + 1;438			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);439440			<TokenData<T>>::insert(441				(collection.id, token_id),442				ItemData {443					const_data: token.const_data,444					variable_data: token.variable_data,445				},446			);447			for (user, amount) in token.users.into_iter() {448				if amount == 0 {449					continue;450				}451				<Balance<T>>::insert((collection.id, token_id, &user), amount);452				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);453				// TODO: ERC20 transfer event454				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(455					collection.id,456					TokenId(token_id),457					user,458					amount,459				));460			}461		}462		Ok(())463	}464465	pub fn set_allowance_unchecked(466		collection: &RefungibleHandle<T>,467		sender: &T::CrossAccountId,468		spender: &T::CrossAccountId,469		token: TokenId,470		amount: u128,471	) {472		if amount == 0 {473			<Allowance<T>>::remove((collection.id, token, sender, spender));474		} else {475			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);476		}477		// TODO: ERC20 approval event478		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(479			collection.id,480			token,481			sender.clone(),482			spender.clone(),483			amount,484		))485	}486487	pub fn set_allowance(488		collection: &RefungibleHandle<T>,489		sender: &T::CrossAccountId,490		spender: &T::CrossAccountId,491		token: TokenId,492		amount: u128,493	) -> DispatchResult {494		if collection.access == AccessMode::AllowList {495			collection.check_allowlist(sender)?;496			collection.check_allowlist(spender)?;497		}498499		<PalletCommon<T>>::ensure_correct_receiver(spender)?;500501		if <Balance<T>>::get((collection.id, token, sender)) < amount {502			ensure!(503				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),504				<CommonError<T>>::CantApproveMoreThanOwned505			);506		}507508		// =========509510		Self::set_allowance_unchecked(collection, sender, spender, token, amount);511		Ok(())512	}513514	pub fn transfer_from(515		collection: &RefungibleHandle<T>,516		spender: &T::CrossAccountId,517		from: &T::CrossAccountId,518		to: &T::CrossAccountId,519		token: TokenId,520		amount: u128,521	) -> DispatchResult {522		if spender.conv_eq(from) {523			return Self::transfer(collection, from, to, token, amount);524		}525		if collection.access == AccessMode::AllowList {526			// `from`, `to` checked in [`transfer`]527			collection.check_allowlist(spender)?;528		}529530		let allowance =531			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);532		if allowance.is_none() {533			ensure!(534				collection.ignores_allowance(spender),535				<CommonError<T>>::ApprovedValueTooLow536			);537		}538539		// =========540541		Self::transfer(collection, from, to, token, amount)?;542		if let Some(allowance) = allowance {543			Self::set_allowance_unchecked(collection, from, spender, token, allowance);544		}545		Ok(())546	}547548	pub fn burn_from(549		collection: &RefungibleHandle<T>,550		spender: &T::CrossAccountId,551		from: &T::CrossAccountId,552		token: TokenId,553		amount: u128,554	) -> DispatchResult {555		if spender.conv_eq(from) {556			return Self::burn(collection, from, token, amount);557		}558		if collection.access == AccessMode::AllowList {559			// `from` checked in [`burn`]560			collection.check_allowlist(spender)?;561		}562563		let allowance =564			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);565		if allowance.is_none() {566			ensure!(567				collection.ignores_allowance(spender),568				<CommonError<T>>::ApprovedValueTooLow569			);570		}571572		// =========573574		Self::burn(collection, from, token, amount)?;575		if let Some(allowance) = allowance {576			Self::set_allowance_unchecked(collection, from, spender, token, allowance);577		}578		Ok(())579	}580581	pub fn set_variable_metadata(582		collection: &RefungibleHandle<T>,583		sender: &T::CrossAccountId,584		token: TokenId,585		data: BoundedVec<u8, CustomDataLimit>,586	) -> DispatchResult {587		collection.check_can_update_meta(588			sender,589			&T::CrossAccountId::from_sub(collection.owner.clone()),590		)?;591592		let token_data = <TokenData<T>>::get((collection.id, token));593594		// =========595596		<TokenData<T>>::insert(597			(collection.id, token),598			ItemData {599				variable_data: data,600				..token_data601			},602		);603		Ok(())604	}605606	/// Delegated to `create_multiple_items`607	pub fn create_item(608		collection: &RefungibleHandle<T>,609		sender: &T::CrossAccountId,610		data: CreateItemData<T>,611	) -> DispatchResult {612		Self::create_multiple_items(collection, sender, vec![data])613	}614}
after · pallets/refungible/src/lib.rs
1#![cfg_attr(not(feature = "std"), no_std)]23use frame_support::{ensure, BoundedVec};4use up_data_structs::{5	AccessMode, CollectionId, CustomDataLimit, MAX_REFUNGIBLE_PIECES, TokenId, CreateCollectionData,6};7use pallet_common::{8	Error as CommonError, Event as CommonEvent, Pallet as PalletCommon, account::CrossAccountId,9};10use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};11use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};12use core::ops::Deref;13use codec::{Encode, Decode, MaxEncodedLen};14use scale_info::TypeInfo;1516pub use pallet::*;17#[cfg(feature = "runtime-benchmarks")]18pub mod benchmarking;19pub mod common;20pub mod erc;21pub mod weights;22pub struct CreateItemData<T: Config> {23	pub const_data: BoundedVec<u8, CustomDataLimit>,24	pub variable_data: BoundedVec<u8, CustomDataLimit>,25	pub users: BTreeMap<T::CrossAccountId, u128>,26}27pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;2829#[derive(Encode, Decode, Default, TypeInfo, MaxEncodedLen)]30pub struct ItemData {31	pub const_data: BoundedVec<u8, CustomDataLimit>,32	pub variable_data: BoundedVec<u8, CustomDataLimit>,33}3435#[frame_support::pallet]36pub mod pallet {37	use super::*;38	use frame_support::{Blake2_128, Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key};39	use up_data_structs::{CollectionId, TokenId};40	use super::weights::WeightInfo;4142	#[pallet::error]43	pub enum Error<T> {44		/// Not Refungible item data used to mint in Refungible collection.45		NotRefungibleDataUsedToMintFungibleCollectionToken,46		/// Maximum refungibility exceeded47		WrongRefungiblePieces,48	}4950	#[pallet::config]51	pub trait Config: frame_system::Config + pallet_common::Config {52		type WeightInfo: WeightInfo;53	}5455	#[pallet::pallet]56	#[pallet::generate_store(pub(super) trait Store)]57	pub struct Pallet<T>(_);5859	#[pallet::storage]60	pub type TokensMinted<T: Config> =61		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;62	#[pallet::storage]63	pub type TokensBurnt<T: Config> =64		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;6566	#[pallet::storage]67	pub type TokenData<T: Config> = StorageNMap<68		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),69		Value = ItemData,70		QueryKind = ValueQuery,71	>;7273	#[pallet::storage]74	pub type TotalSupply<T: Config> = StorageNMap<75		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),76		Value = u128,77		QueryKind = ValueQuery,78	>;7980	/// Used to enumerate tokens owned by account81	#[pallet::storage]82	pub type Owned<T: Config> = StorageNMap<83		Key = (84			Key<Twox64Concat, CollectionId>,85			Key<Blake2_128Concat, T::CrossAccountId>,86			Key<Twox64Concat, TokenId>,87		),88		Value = bool,89		QueryKind = ValueQuery,90	>;9192	#[pallet::storage]93	pub type AccountBalance<T: Config> = StorageNMap<94		Key = (95			Key<Twox64Concat, CollectionId>,96			// Owner97			Key<Blake2_128Concat, T::CrossAccountId>,98		),99		Value = u32,100		QueryKind = ValueQuery,101	>;102103	#[pallet::storage]104	pub type Balance<T: Config> = StorageNMap<105		Key = (106			Key<Twox64Concat, CollectionId>,107			Key<Twox64Concat, TokenId>,108			// Owner109			Key<Blake2_128Concat, T::CrossAccountId>,110		),111		Value = u128,112		QueryKind = ValueQuery,113	>;114115	#[pallet::storage]116	pub type Allowance<T: Config> = StorageNMap<117		Key = (118			Key<Twox64Concat, CollectionId>,119			Key<Twox64Concat, TokenId>,120			// Owner121			Key<Blake2_128, T::CrossAccountId>,122			// Spender123			Key<Blake2_128Concat, T::CrossAccountId>,124		),125		Value = u128,126		QueryKind = ValueQuery,127	>;128}129130pub struct RefungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);131impl<T: Config> RefungibleHandle<T> {132	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {133		Self(inner)134	}135	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {136		self.0137	}138}139impl<T: Config> Deref for RefungibleHandle<T> {140	type Target = pallet_common::CollectionHandle<T>;141142	fn deref(&self) -> &Self::Target {143		&self.0144	}145}146147impl<T: Config> Pallet<T> {148	pub fn total_supply(collection: &RefungibleHandle<T>) -> u32 {149		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)150	}151	pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {152		<TotalSupply<T>>::contains_key((collection.id, token))153	}154}155156// unchecked calls skips any permission checks157impl<T: Config> Pallet<T> {158	pub fn init_collection(159		owner: T::AccountId,160		data: CreateCollectionData<T::AccountId>,161	) -> Result<CollectionId, DispatchError> {162		<PalletCommon<T>>::init_collection(owner, data)163	}164	pub fn destroy_collection(165		collection: RefungibleHandle<T>,166		sender: &T::CrossAccountId,167	) -> DispatchResult {168		let id = collection.id;169170		// =========171172		PalletCommon::destroy_collection(collection.0, sender)?;173174		<TokensMinted<T>>::remove(id);175		<TokensBurnt<T>>::remove(id);176		<TokenData<T>>::remove_prefix((id,), None);177		<TotalSupply<T>>::remove_prefix((id,), None);178		<Balance<T>>::remove_prefix((id,), None);179		<Allowance<T>>::remove_prefix((id,), None);180		<Owned<T>>::remove_prefix((id,), None);181		<AccountBalance<T>>::remove_prefix((id,), None);182		Ok(())183	}184185	pub fn burn_token(collection: &RefungibleHandle<T>, token_id: TokenId) -> DispatchResult {186		let burnt = <TokensBurnt<T>>::get(collection.id)187			.checked_add(1)188			.ok_or(ArithmeticError::Overflow)?;189190		<TokensBurnt<T>>::insert(collection.id, burnt);191		<TokenData<T>>::remove((collection.id, token_id));192		<TotalSupply<T>>::remove((collection.id, token_id));193		<Balance<T>>::remove_prefix((collection.id, token_id), None);194		<Allowance<T>>::remove_prefix((collection.id, token_id), None);195		// TODO: ERC721 transfer event196		Ok(())197	}198199	pub fn burn(200		collection: &RefungibleHandle<T>,201		owner: &T::CrossAccountId,202		token: TokenId,203		amount: u128,204	) -> DispatchResult {205		let total_supply = <TotalSupply<T>>::get((collection.id, token))206			.checked_sub(amount)207			.ok_or(<CommonError<T>>::TokenValueTooLow)?;208209		// This was probally last owner of this token?210		if total_supply == 0 {211			// Ensure user actually owns this amount212			ensure!(213				<Balance<T>>::get((collection.id, token, owner)) == amount,214				<CommonError<T>>::TokenValueTooLow215			);216			let account_balance = <AccountBalance<T>>::get((collection.id, owner))217				.checked_sub(1)218				// Should not occur219				.ok_or(ArithmeticError::Underflow)?;220221			// =========222223			<Owned<T>>::remove((collection.id, owner, token));224			<AccountBalance<T>>::insert((collection.id, owner), account_balance);225			Self::burn_token(collection, token)?;226			<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(227				collection.id,228				token,229				owner.clone(),230				amount,231			));232			return Ok(());233		}234235		let balance = <Balance<T>>::get((collection.id, token, owner))236			.checked_sub(amount)237			.ok_or(<CommonError<T>>::TokenValueTooLow)?;238		let account_balance = if balance == 0 {239			<AccountBalance<T>>::get((collection.id, owner))240				.checked_sub(1)241				// Should not occur242				.ok_or(ArithmeticError::Underflow)?243		} else {244			0245		};246247		// =========248249		if balance == 0 {250			<Owned<T>>::remove((collection.id, owner, token));251			<Balance<T>>::remove((collection.id, token, owner));252			<AccountBalance<T>>::insert((collection.id, owner), account_balance);253		} else {254			<Balance<T>>::insert((collection.id, token, owner), balance);255		}256		<TotalSupply<T>>::insert((collection.id, token), total_supply);257		// TODO: ERC20 transfer event258		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(259			collection.id,260			token,261			owner.clone(),262			amount,263		));264		Ok(())265	}266267	pub fn transfer(268		collection: &RefungibleHandle<T>,269		from: &T::CrossAccountId,270		to: &T::CrossAccountId,271		token: TokenId,272		amount: u128,273	) -> DispatchResult {274		ensure!(275			collection.limits.transfers_enabled(),276			<CommonError<T>>::TransferNotAllowed277		);278279		if collection.access == AccessMode::AllowList {280			collection.check_allowlist(from)?;281			collection.check_allowlist(to)?;282		}283		<PalletCommon<T>>::ensure_correct_receiver(to)?;284285		let balance_from = <Balance<T>>::get((collection.id, token, from))286			.checked_sub(amount)287			.ok_or(<CommonError<T>>::TokenValueTooLow)?;288		let mut create_target = false;289		let from_to_differ = from != to;290		let balance_to = if from != to {291			let old_balance = <Balance<T>>::get((collection.id, token, to));292			if old_balance == 0 {293				create_target = true;294			}295			Some(296				old_balance297					.checked_add(amount)298					.ok_or(ArithmeticError::Overflow)?,299			)300		} else {301			None302		};303304		let account_balance_from = if balance_from == 0 {305			Some(306				<AccountBalance<T>>::get((collection.id, from))307					.checked_sub(1)308					// Should not occur309					.ok_or(ArithmeticError::Underflow)?,310			)311		} else {312			None313		};314		// Account data is created in token, AccountBalance should be increased315		// But only if from != to as we shouldn't check overflow in this case316		let account_balance_to = if create_target && from_to_differ {317			let account_balance_to = <AccountBalance<T>>::get((collection.id, to))318				.checked_add(1)319				.ok_or(ArithmeticError::Overflow)?;320			ensure!(321				account_balance_to < collection.limits.account_token_ownership_limit(),322				<CommonError<T>>::AccountTokenLimitExceeded,323			);324325			Some(account_balance_to)326		} else {327			None328		};329330		// =========331332		if let Some(balance_to) = balance_to {333			// from != to334			if balance_from == 0 {335				<Balance<T>>::remove((collection.id, token, from));336			} else {337				<Balance<T>>::insert((collection.id, token, from), balance_from);338			}339			<Balance<T>>::insert((collection.id, token, to), balance_to);340			if let Some(account_balance_from) = account_balance_from {341				<AccountBalance<T>>::insert((collection.id, from), account_balance_from);342				<Owned<T>>::remove((collection.id, from, token));343			}344			if let Some(account_balance_to) = account_balance_to {345				<AccountBalance<T>>::insert((collection.id, to), account_balance_to);346				<Owned<T>>::insert((collection.id, to, token), true);347			}348		}349350		// TODO: ERC20 transfer event351		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(352			collection.id,353			token,354			from.clone(),355			to.clone(),356			amount,357		));358		Ok(())359	}360361	pub fn create_multiple_items(362		collection: &RefungibleHandle<T>,363		sender: &T::CrossAccountId,364		data: Vec<CreateItemData<T>>,365	) -> DispatchResult {366		if !collection.is_owner_or_admin(sender) {367			ensure!(368				collection.mint_mode,369				<CommonError<T>>::PublicMintingNotAllowed370			);371			collection.check_allowlist(sender)?;372373			for item in data.iter() {374				for user in item.users.keys() {375					collection.check_allowlist(user)?;376				}377			}378		}379380		for item in data.iter() {381			for (owner, _) in item.users.iter() {382				<PalletCommon<T>>::ensure_correct_receiver(owner)?;383			}384		}385386		// Total pieces per tokens387		let totals = data388			.iter()389			.map(|data| {390				Ok(data391					.users392					.iter()393					.map(|u| u.1)394					.try_fold(0u128, |acc, v| acc.checked_add(*v))395					.ok_or(ArithmeticError::Overflow)?)396			})397			.collect::<Result<Vec<_>, DispatchError>>()?;398		for total in &totals {399			ensure!(400				*total <= MAX_REFUNGIBLE_PIECES,401				<Error<T>>::WrongRefungiblePieces402			);403		}404405		let first_token_id = <TokensMinted<T>>::get(collection.id);406		let tokens_minted = first_token_id407			.checked_add(data.len() as u32)408			.ok_or(ArithmeticError::Overflow)?;409		ensure!(410			tokens_minted < collection.limits.token_limit(),411			<CommonError<T>>::CollectionTokenLimitExceeded412		);413414		let mut balances = BTreeMap::new();415		for data in &data {416			for owner in data.users.keys() {417				let balance = balances418					.entry(owner)419					.or_insert_with(|| <AccountBalance<T>>::get((collection.id, owner)));420				*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;421422				ensure!(423					*balance <= collection.limits.account_token_ownership_limit(),424					<CommonError<T>>::AccountTokenLimitExceeded,425				);426			}427		}428429		// =========430431		<TokensMinted<T>>::insert(collection.id, tokens_minted);432		for (account, balance) in balances {433			<AccountBalance<T>>::insert((collection.id, account), balance);434		}435		for (i, token) in data.into_iter().enumerate() {436			let token_id = first_token_id + i as u32 + 1;437			<TotalSupply<T>>::insert((collection.id, token_id), totals[i]);438439			<TokenData<T>>::insert(440				(collection.id, token_id),441				ItemData {442					const_data: token.const_data,443					variable_data: token.variable_data,444				},445			);446			for (user, amount) in token.users.into_iter() {447				if amount == 0 {448					continue;449				}450				<Balance<T>>::insert((collection.id, token_id, &user), amount);451				<Owned<T>>::insert((collection.id, &user, TokenId(token_id)), true);452				// TODO: ERC20 transfer event453				<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(454					collection.id,455					TokenId(token_id),456					user,457					amount,458				));459			}460		}461		Ok(())462	}463464	pub fn set_allowance_unchecked(465		collection: &RefungibleHandle<T>,466		sender: &T::CrossAccountId,467		spender: &T::CrossAccountId,468		token: TokenId,469		amount: u128,470	) {471		if amount == 0 {472			<Allowance<T>>::remove((collection.id, token, sender, spender));473		} else {474			<Allowance<T>>::insert((collection.id, token, sender, spender), amount);475		}476		// TODO: ERC20 approval event477		<PalletCommon<T>>::deposit_event(CommonEvent::Approved(478			collection.id,479			token,480			sender.clone(),481			spender.clone(),482			amount,483		))484	}485486	pub fn set_allowance(487		collection: &RefungibleHandle<T>,488		sender: &T::CrossAccountId,489		spender: &T::CrossAccountId,490		token: TokenId,491		amount: u128,492	) -> DispatchResult {493		if collection.access == AccessMode::AllowList {494			collection.check_allowlist(sender)?;495			collection.check_allowlist(spender)?;496		}497498		<PalletCommon<T>>::ensure_correct_receiver(spender)?;499500		if <Balance<T>>::get((collection.id, token, sender)) < amount {501			ensure!(502				collection.ignores_owned_amount(sender) && Self::token_exists(collection, token),503				<CommonError<T>>::CantApproveMoreThanOwned504			);505		}506507		// =========508509		Self::set_allowance_unchecked(collection, sender, spender, token, amount);510		Ok(())511	}512513	pub fn transfer_from(514		collection: &RefungibleHandle<T>,515		spender: &T::CrossAccountId,516		from: &T::CrossAccountId,517		to: &T::CrossAccountId,518		token: TokenId,519		amount: u128,520	) -> DispatchResult {521		if spender.conv_eq(from) {522			return Self::transfer(collection, from, to, token, amount);523		}524		if collection.access == AccessMode::AllowList {525			// `from`, `to` checked in [`transfer`]526			collection.check_allowlist(spender)?;527		}528529		let allowance =530			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);531		if allowance.is_none() {532			ensure!(533				collection.ignores_allowance(spender),534				<CommonError<T>>::ApprovedValueTooLow535			);536		}537538		// =========539540		Self::transfer(collection, from, to, token, amount)?;541		if let Some(allowance) = allowance {542			Self::set_allowance_unchecked(collection, from, spender, token, allowance);543		}544		Ok(())545	}546547	pub fn burn_from(548		collection: &RefungibleHandle<T>,549		spender: &T::CrossAccountId,550		from: &T::CrossAccountId,551		token: TokenId,552		amount: u128,553	) -> DispatchResult {554		if spender.conv_eq(from) {555			return Self::burn(collection, from, token, amount);556		}557		if collection.access == AccessMode::AllowList {558			// `from` checked in [`burn`]559			collection.check_allowlist(spender)?;560		}561562		let allowance =563			<Allowance<T>>::get((collection.id, token, from, &spender)).checked_sub(amount);564		if allowance.is_none() {565			ensure!(566				collection.ignores_allowance(spender),567				<CommonError<T>>::ApprovedValueTooLow568			);569		}570571		// =========572573		Self::burn(collection, from, token, amount)?;574		if let Some(allowance) = allowance {575			Self::set_allowance_unchecked(collection, from, spender, token, allowance);576		}577		Ok(())578	}579580	pub fn set_variable_metadata(581		collection: &RefungibleHandle<T>,582		sender: &T::CrossAccountId,583		token: TokenId,584		data: BoundedVec<u8, CustomDataLimit>,585	) -> DispatchResult {586		collection.check_can_update_meta(587			sender,588			&T::CrossAccountId::from_sub(collection.owner.clone()),589		)?;590591		let token_data = <TokenData<T>>::get((collection.id, token));592593		// =========594595		<TokenData<T>>::insert(596			(collection.id, token),597			ItemData {598				variable_data: data,599				..token_data600			},601		);602		Ok(())603	}604605	/// Delegated to `create_multiple_items`606	pub fn create_item(607		collection: &RefungibleHandle<T>,608		sender: &T::CrossAccountId,609		data: CreateItemData<T>,610	) -> DispatchResult {611		Self::create_multiple_items(collection, sender, vec![data])612	}613}
modifiedpallets/unique/src/lib.rsdiffbeforeafterboth
--- a/pallets/unique/src/lib.rs
+++ b/pallets/unique/src/lib.rs
@@ -38,8 +38,8 @@
 use up_data_structs::{
 	MAX_DECIMAL_POINTS, VARIABLE_ON_CHAIN_SCHEMA_LIMIT, CONST_ON_CHAIN_SCHEMA_LIMIT,
 	OFFCHAIN_SCHEMA_LIMIT, MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH,
-	MAX_TOKEN_PREFIX_LENGTH, AccessMode, Collection, CreateItemData, CollectionLimits,
-	CollectionId, CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
+	MAX_TOKEN_PREFIX_LENGTH, AccessMode, CreateItemData, CollectionLimits, CollectionId,
+	CollectionMode, TokenId, SchemaVersion, SponsorshipState, MetaUpdatePermission,
 	CreateCollectionData, CustomDataLimit,
 };
 use pallet_common::{