git.delta.rocks / unique-network / refs/commits / 101a18907270

difftreelog

fix unnest tokens on transfer

Daniel Shiposha2022-05-27parent: #79ec93e.patch.diff
in: master

3 files changed

modifiedpallets/fungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -256,6 +256,11 @@
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					TokenId::default()
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, from), balance_from);
 			}
modifiedpallets/nonfungible/src/lib.rsdiffbeforeafterboth
before · pallets/nonfungible/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 erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25	PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30	eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55	#[version(..2)]56	pub const_data: BoundedVec<u8, CustomDataLimit>,5758	#[version(..2)]59	pub variable_data: BoundedVec<u8, CustomDataLimit>,6061	pub owner: CrossAccountId,62}6364#[frame_support::pallet]65pub mod pallet {66	use super::*;67	use frame_support::{68		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,69	};70	use frame_system::pallet_prelude::*;71	use up_data_structs::{CollectionId, TokenId};72	use super::weights::WeightInfo;7374	#[pallet::error]75	pub enum Error<T> {76		/// Not Nonfungible item data used to mint in Nonfungible collection.77		NotNonfungibleDataUsedToMintFungibleCollectionToken,78		/// Used amount > 1 with NFT79		NonfungibleItemsHaveNoAmount,80		/// Unable to burn NFT with children81		CantBurnNftWithChildren,82	}8384	#[pallet::config]85	pub trait Config:86		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config87	{88		type WeightInfo: WeightInfo;89	}9091	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);9293	#[pallet::pallet]94	#[pallet::storage_version(STORAGE_VERSION)]95	#[pallet::generate_store(pub(super) trait Store)]96	pub struct Pallet<T>(_);9798	#[pallet::storage]99	pub type TokensMinted<T: Config> =100		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101	#[pallet::storage]102	pub type TokensBurnt<T: Config> =103		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;104105	#[pallet::storage]106	pub type TokenData<T: Config> = StorageNMap<107		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),108		Value = ItemData<T::CrossAccountId>,109		QueryKind = OptionQuery,110	>;111112	#[pallet::storage]113	#[pallet::getter(fn token_properties)]114	pub type TokenProperties<T: Config> = StorageNMap<115		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),116		Value = Properties,117		QueryKind = ValueQuery,118		OnEmpty = up_data_structs::TokenProperties,119	>;120121	/// Used to enumerate tokens owned by account122	#[pallet::storage]123	pub type Owned<T: Config> = StorageNMap<124		Key = (125			Key<Twox64Concat, CollectionId>,126			Key<Blake2_128Concat, T::CrossAccountId>,127			Key<Twox64Concat, TokenId>,128		),129		Value = bool,130		QueryKind = ValueQuery,131	>;132133	/// Used to enumerate token's children134	#[pallet::storage]135	#[pallet::getter(fn token_children)]136	pub type TokenChildren<T: Config> = StorageNMap<137		Key = (138			Key<Twox64Concat, CollectionId>,139			Key<Twox64Concat, TokenId>,140			Key<Twox64Concat, (CollectionId, TokenId)>,141		),142		Value = bool,143		QueryKind = ValueQuery,144	>;145146	#[pallet::storage]147	pub type AccountBalance<T: Config> = StorageNMap<148		Key = (149			Key<Twox64Concat, CollectionId>,150			Key<Blake2_128Concat, T::CrossAccountId>,151		),152		Value = u32,153		QueryKind = ValueQuery,154	>;155156	#[pallet::storage]157	pub type Allowance<T: Config> = StorageNMap<158		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),159		Value = T::CrossAccountId,160		QueryKind = OptionQuery,161	>;162163	#[pallet::hooks]164	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {165		fn on_runtime_upgrade() -> Weight {166			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {167				let mut had_consts = BTreeSet::new();168				<TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {169					let mut props = vec![];170					if !v.const_data.is_empty() {171						props.push(Property {172							key: b"_old_constData".to_vec().try_into().unwrap(),173							value: v.const_data.clone().into_inner().try_into().expect("const too long"),174						});175						had_consts.insert(collection);176					}177					if !v.variable_data.is_empty() {178						props.push(Property {179							key: b"_old_variableData".to_vec().try_into().unwrap(),180							value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),181						})182					}183					if !props.is_empty() {184						Self::set_scoped_token_properties(185							collection,186							token,187							PropertyScope::None,188							props.into_iter(),189						).expect("existing token data exceeds property storage");190					}191					Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))192				});193				for collection in had_consts {194					<PalletCommon<T>>::set_property_permission_unchecked(195						collection,196						PropertyKeyPermission {197							key: b"_old_constData".to_vec().try_into().unwrap(),198							permission: PropertyPermission {199								mutable: false,200								collection_admin: true,201								token_owner: false,202							},203						}204					).expect("failed to configure permission");205				}206			}207208			0209		}210	}211}212213pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);214impl<T: Config> NonfungibleHandle<T> {215	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {216		Self(inner)217	}218	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {219		self.0220	}221	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {222		&mut self.0223	}224}225impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {226	fn recorder(&self) -> &SubstrateRecorder<T> {227		self.0.recorder()228	}229	fn into_recorder(self) -> SubstrateRecorder<T> {230		self.0.into_recorder()231	}232}233impl<T: Config> Deref for NonfungibleHandle<T> {234	type Target = pallet_common::CollectionHandle<T>;235236	fn deref(&self) -> &Self::Target {237		&self.0238	}239}240241impl<T: Config> Pallet<T> {242	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {243		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)244	}245	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {246		<TokenData<T>>::contains_key((collection.id, token))247	}248249	pub fn set_scoped_token_property(250		collection_id: CollectionId,251		token_id: TokenId,252		scope: PropertyScope,253		property: Property,254	) -> DispatchResult {255		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {256			properties.try_scoped_set(scope, property.key, property.value)257		})258		.map_err(<CommonError<T>>::from)?;259260		Ok(())261	}262263	pub fn set_scoped_token_properties(264		collection_id: CollectionId,265		token_id: TokenId,266		scope: PropertyScope,267		properties: impl Iterator<Item=Property>,268	) -> DispatchResult {269		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {270			stored_properties.try_scoped_set_from_iter(scope, properties)271		})272		.map_err(<CommonError<T>>::from)?;273274		Ok(())275	}276277	pub fn current_token_id(collection_id: CollectionId) -> TokenId {278		TokenId(<TokensMinted<T>>::get(collection_id))279	}280}281282// unchecked calls skips any permission checks283impl<T: Config> Pallet<T> {284	pub fn init_collection(285		owner: T::AccountId,286		data: CreateCollectionData<T::AccountId>,287	) -> Result<CollectionId, DispatchError> {288		<PalletCommon<T>>::init_collection(owner, data)289	}290	pub fn destroy_collection(291		collection: NonfungibleHandle<T>,292		sender: &T::CrossAccountId,293	) -> DispatchResult {294		let id = collection.id;295296		if Self::collection_has_tokens(id) {297			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());298		}299300		// =========301302		PalletCommon::destroy_collection(collection.0, sender)?;303304		<TokenData<T>>::remove_prefix((id,), None);305		<TokenChildren<T>>::remove_prefix((id,), None);306		<Owned<T>>::remove_prefix((id,), None);307		<TokensMinted<T>>::remove(id);308		<TokensBurnt<T>>::remove(id);309		<Allowance<T>>::remove_prefix((id,), None);310		<AccountBalance<T>>::remove_prefix((id,), None);311		Ok(())312	}313314	pub fn burn(315		collection: &NonfungibleHandle<T>,316		sender: &T::CrossAccountId,317		token: TokenId,318	) -> DispatchResult {319		let token_data =320			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;321		ensure!(322			&token_data.owner == sender323				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),324			<CommonError<T>>::NoPermission325		);326327		if collection.permissions.access() == AccessMode::AllowList {328			collection.check_allowlist(sender)?;329		}330331		if Self::token_has_children(collection.id, token) {332			return Err(<Error<T>>::CantBurnNftWithChildren.into());333		}334335		let burnt = <TokensBurnt<T>>::get(collection.id)336			.checked_add(1)337			.ok_or(ArithmeticError::Overflow)?;338339		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))340			.checked_sub(1)341			.ok_or(ArithmeticError::Overflow)?;342343		if balance == 0 {344			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));345		} else {346			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);347		}348349		if let Some(owner) = T::CrossTokenAddressMapping::address_to_token(&token_data.owner) {350			Self::unnest(owner, (collection.id, token));351		}352353		// =========354355		<Owned<T>>::remove((collection.id, &token_data.owner, token));356		<TokensBurnt<T>>::insert(collection.id, burnt);357		<TokenData<T>>::remove((collection.id, token));358		<TokenProperties<T>>::remove((collection.id, token));359		let old_spender = <Allowance<T>>::take((collection.id, token));360361		if let Some(old_spender) = old_spender {362			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(363				collection.id,364				token,365				sender.clone(),366				old_spender,367				0,368			));369		}370371		<PalletEvm<T>>::deposit_log(372			ERC721Events::Transfer {373				from: *token_data.owner.as_eth(),374				to: H160::default(),375				token_id: token.into(),376			}377			.to_log(collection_id_to_address(collection.id)),378		);379		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(380			collection.id,381			token,382			token_data.owner,383			1,384		));385		Ok(())386	}387388	pub fn set_token_property(389		collection: &NonfungibleHandle<T>,390		sender: &T::CrossAccountId,391		token_id: TokenId,392		property: Property,393	) -> DispatchResult {394		Self::check_token_change_permission(collection, sender, token_id, &property.key)?;395396		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {397			let property = property.clone();398			properties.try_set(property.key, property.value)399		})400		.map_err(<CommonError<T>>::from)?;401402		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(403			collection.id,404			token_id,405			property.key,406		));407408		Ok(())409	}410411	#[transactional]412	pub fn set_token_properties(413		collection: &NonfungibleHandle<T>,414		sender: &T::CrossAccountId,415		token_id: TokenId,416		properties: Vec<Property>,417	) -> DispatchResult {418		for property in properties {419			Self::set_token_property(collection, sender, token_id, property)?;420		}421422		Ok(())423	}424425	pub fn delete_token_property(426		collection: &NonfungibleHandle<T>,427		sender: &T::CrossAccountId,428		token_id: TokenId,429		property_key: PropertyKey,430	) -> DispatchResult {431		Self::check_token_change_permission(collection, sender, token_id, &property_key)?;432433		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {434			properties.remove(&property_key)435		})436		.map_err(<CommonError<T>>::from)?;437438		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(439			collection.id,440			token_id,441			property_key,442		));443444		Ok(())445	}446447	fn check_token_change_permission(448		collection: &NonfungibleHandle<T>,449		sender: &T::CrossAccountId,450		token_id: TokenId,451		property_key: &PropertyKey,452	) -> DispatchResult {453		let permission = <PalletCommon<T>>::property_permissions(collection.id)454			.get(property_key)455			.cloned()456			.unwrap_or_else(PropertyPermission::none);457458		let token_data = <TokenData<T>>::get((collection.id, token_id))459			.ok_or(<CommonError<T>>::TokenNotFound)?;460461		let check_token_owner = || -> DispatchResult {462			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);463			Ok(())464		};465466		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))467			.get(property_key)468			.is_some();469470		match permission {471			PropertyPermission { mutable: false, .. } if is_property_exists => {472				Err(<CommonError<T>>::NoPermission.into())473			}474475			PropertyPermission {476				collection_admin,477				token_owner,478				..479			} => {480				let mut check_result = Err(<CommonError<T>>::NoPermission.into());481482				if collection_admin {483					check_result = collection.check_is_owner_or_admin(sender);484				}485486				if token_owner {487					check_result.or_else(|_| check_token_owner())488				} else {489					check_result490				}491			}492		}493	}494495	#[transactional]496	pub fn delete_token_properties(497		collection: &NonfungibleHandle<T>,498		sender: &T::CrossAccountId,499		token_id: TokenId,500		property_keys: Vec<PropertyKey>,501	) -> DispatchResult {502		for key in property_keys {503			Self::delete_token_property(collection, sender, token_id, key)?;504		}505506		Ok(())507	}508509	pub fn set_collection_properties(510		collection: &NonfungibleHandle<T>,511		sender: &T::CrossAccountId,512		properties: Vec<Property>,513	) -> DispatchResult {514		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)515	}516517	pub fn delete_collection_properties(518		collection: &CollectionHandle<T>,519		sender: &T::CrossAccountId,520		property_keys: Vec<PropertyKey>,521	) -> DispatchResult {522		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)523	}524525	pub fn set_property_permissions(526		collection: &CollectionHandle<T>,527		sender: &T::CrossAccountId,528		property_permissions: Vec<PropertyKeyPermission>,529	) -> DispatchResult {530		<PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)531	}532533	pub fn set_property_permission(534		collection: &CollectionHandle<T>,535		sender: &T::CrossAccountId,536		permission: PropertyKeyPermission,537	) -> DispatchResult {538		<PalletCommon<T>>::set_property_permission(collection, sender, permission)539	}540541	pub fn transfer(542		collection: &NonfungibleHandle<T>,543		from: &T::CrossAccountId,544		to: &T::CrossAccountId,545		token: TokenId,546		nesting_budget: &dyn Budget,547	) -> DispatchResult {548		ensure!(549			collection.limits.transfers_enabled(),550			<CommonError<T>>::TransferNotAllowed551		);552553		let token_data =554			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;555		// TODO: require sender to be token, owner, require admins to go through transfer_from556		ensure!(557			&token_data.owner == from558				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),559			<CommonError<T>>::NoPermission560		);561562		if collection.permissions.access() == AccessMode::AllowList {563			collection.check_allowlist(from)?;564			collection.check_allowlist(to)?;565		}566		<PalletCommon<T>>::ensure_correct_receiver(to)?;567568		let balance_from = <AccountBalance<T>>::get((collection.id, from))569			.checked_sub(1)570			.ok_or(<CommonError<T>>::TokenValueTooLow)?;571		let balance_to = if from != to {572			let balance_to = <AccountBalance<T>>::get((collection.id, to))573				.checked_add(1)574				.ok_or(ArithmeticError::Overflow)?;575576			ensure!(577				balance_to < collection.limits.account_token_ownership_limit(),578				<CommonError<T>>::AccountTokenLimitExceeded,579			);580581			Some(balance_to)582		} else {583			None584		};585586		<PalletStructure<T>>::nest_if_sent_to_token(587			from.clone(),588			to,589			collection.id,590			token,591			nesting_budget592		)?;593594		// =========595596		<TokenData<T>>::insert(597			(collection.id, token),598			ItemData {599				owner: to.clone(),600				..token_data601			},602		);603604		if let Some(balance_to) = balance_to {605			// from != to606			if balance_from == 0 {607				<AccountBalance<T>>::remove((collection.id, from));608			} else {609				<AccountBalance<T>>::insert((collection.id, from), balance_from);610			}611			<AccountBalance<T>>::insert((collection.id, to), balance_to);612			<Owned<T>>::remove((collection.id, from, token));613			<Owned<T>>::insert((collection.id, to, token), true);614		}615		Self::set_allowance_unchecked(collection, from, token, None, true);616617		<PalletEvm<T>>::deposit_log(618			ERC721Events::Transfer {619				from: *from.as_eth(),620				to: *to.as_eth(),621				token_id: token.into(),622			}623			.to_log(collection_id_to_address(collection.id)),624		);625		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(626			collection.id,627			token,628			from.clone(),629			to.clone(),630			1,631		));632		Ok(())633	}634635	pub fn create_multiple_items(636		collection: &NonfungibleHandle<T>,637		sender: &T::CrossAccountId,638		data: Vec<CreateItemData<T>>,639		nesting_budget: &dyn Budget,640	) -> DispatchResult {641		if !collection.is_owner_or_admin(sender) {642			ensure!(643				collection.permissions.mint_mode(),644				<CommonError<T>>::PublicMintingNotAllowed645			);646			collection.check_allowlist(sender)?;647648			for item in data.iter() {649				collection.check_allowlist(&item.owner)?;650			}651		}652653		for data in data.iter() {654			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;655		}656657		let first_token = <TokensMinted<T>>::get(collection.id);658		let tokens_minted = first_token659			.checked_add(data.len() as u32)660			.ok_or(ArithmeticError::Overflow)?;661		ensure!(662			tokens_minted <= collection.limits.token_limit(),663			<CommonError<T>>::CollectionTokenLimitExceeded664		);665666		let mut balances = BTreeMap::new();667		for data in &data {668			let balance = balances669				.entry(&data.owner)670				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));671			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;672673			ensure!(674				*balance <= collection.limits.account_token_ownership_limit(),675				<CommonError<T>>::AccountTokenLimitExceeded,676			);677		}678679		for (i, data) in data.iter().enumerate() {680			let token = TokenId(first_token + i as u32 + 1);681682			<PalletStructure<T>>::check_nesting(683				sender.clone(),684				&data.owner,685				collection.id,686				token,687				nesting_budget,688			)?;689		}690691		// =========692693		with_transaction(|| {694			for (i, data) in data.iter().enumerate() {695				let token = first_token + i as u32 + 1;696697				<TokenData<T>>::insert(698					(collection.id, token),699					ItemData {700						// const_data: data.const_data.clone(),701						owner: data.owner.clone(),702					},703				);704705				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));706707				if let Err(e) = Self::set_token_properties(708					collection,709					sender,710					TokenId(token),711					data.properties.clone().into_inner(),712				) {713					return TransactionOutcome::Rollback(Err(e));714				}715			}716			TransactionOutcome::Commit(Ok(()))717		})?;718719		<TokensMinted<T>>::insert(collection.id, tokens_minted);720		for (account, balance) in balances {721			<AccountBalance<T>>::insert((collection.id, account), balance);722		}723		for (i, data) in data.into_iter().enumerate() {724			let token = first_token + i as u32 + 1;725			<Owned<T>>::insert((collection.id, &data.owner, token), true);726727			<PalletEvm<T>>::deposit_log(728				ERC721Events::Transfer {729					from: H160::default(),730					to: *data.owner.as_eth(),731					token_id: token.into(),732				}733				.to_log(collection_id_to_address(collection.id)),734			);735			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(736				collection.id,737				TokenId(token),738				data.owner.clone(),739				1,740			));741		}742		Ok(())743	}744745	pub fn set_allowance_unchecked(746		collection: &NonfungibleHandle<T>,747		sender: &T::CrossAccountId,748		token: TokenId,749		spender: Option<&T::CrossAccountId>,750		assume_implicit_eth: bool,751	) {752		if let Some(spender) = spender {753			let old_spender = <Allowance<T>>::get((collection.id, token));754			<Allowance<T>>::insert((collection.id, token), spender);755			// In ERC721 there is only one possible approved user of token, so we set756			// approved user to spender757			<PalletEvm<T>>::deposit_log(758				ERC721Events::Approval {759					owner: *sender.as_eth(),760					approved: *spender.as_eth(),761					token_id: token.into(),762				}763				.to_log(collection_id_to_address(collection.id)),764			);765			// In Unique chain, any token can have any amount of approved users, so we need to766			// set allowance of old owner to 0, and allowance of new owner to 1767			if old_spender.as_ref() != Some(spender) {768				if let Some(old_owner) = old_spender {769					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(770						collection.id,771						token,772						sender.clone(),773						old_owner,774						0,775					));776				}777				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(778					collection.id,779					token,780					sender.clone(),781					spender.clone(),782					1,783				));784			}785		} else {786			let old_spender = <Allowance<T>>::take((collection.id, token));787			if !assume_implicit_eth {788				// In ERC721 there is only one possible approved user of token, so we set789				// approved user to zero address790				<PalletEvm<T>>::deposit_log(791					ERC721Events::Approval {792						owner: *sender.as_eth(),793						approved: H160::default(),794						token_id: token.into(),795					}796					.to_log(collection_id_to_address(collection.id)),797				);798			}799			// In Unique chain, any token can have any amount of approved users, so we need to800			// set allowance of old owner to 0801			if let Some(old_spender) = old_spender {802				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(803					collection.id,804					token,805					sender.clone(),806					old_spender,807					0,808				));809			}810		}811	}812813	pub fn set_allowance(814		collection: &NonfungibleHandle<T>,815		sender: &T::CrossAccountId,816		token: TokenId,817		spender: Option<&T::CrossAccountId>,818	) -> DispatchResult {819		if collection.permissions.access() == AccessMode::AllowList {820			collection.check_allowlist(sender)?;821			if let Some(spender) = spender {822				collection.check_allowlist(spender)?;823			}824		}825826		if let Some(spender) = spender {827			<PalletCommon<T>>::ensure_correct_receiver(spender)?;828		}829		let token_data =830			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;831		if &token_data.owner != sender {832			ensure!(833				collection.ignores_owned_amount(sender),834				<CommonError<T>>::CantApproveMoreThanOwned835			);836		}837838		// =========839840		Self::set_allowance_unchecked(collection, sender, token, spender, false);841		Ok(())842	}843844	fn check_allowed(845		collection: &NonfungibleHandle<T>,846		spender: &T::CrossAccountId,847		from: &T::CrossAccountId,848		token: TokenId,849		nesting_budget: &dyn Budget,850	) -> DispatchResult {851		if spender.conv_eq(from) {852			return Ok(());853		}854		if collection.permissions.access() == AccessMode::AllowList {855			// `from`, `to` checked in [`transfer`]856			collection.check_allowlist(spender)?;857		}858		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {859			// TODO: should collection owner be allowed to perform this transfer?860			ensure!(861				<PalletStructure<T>>::check_indirectly_owned(862					spender.clone(),863					source.0,864					source.1,865					None,866					nesting_budget867				)?,868				<CommonError<T>>::ApprovedValueTooLow,869			);870			return Ok(());871		}872		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {873			return Ok(());874		}875		ensure!(876			collection.ignores_allowance(spender),877			<CommonError<T>>::ApprovedValueTooLow878		);879		Ok(())880	}881882	pub fn transfer_from(883		collection: &NonfungibleHandle<T>,884		spender: &T::CrossAccountId,885		from: &T::CrossAccountId,886		to: &T::CrossAccountId,887		token: TokenId,888		nesting_budget: &dyn Budget,889	) -> DispatchResult {890		Self::check_allowed(collection, spender, from, token, nesting_budget)?;891892		// =========893894		// Allowance is reset in [`transfer`]895		Self::transfer(collection, from, to, token, nesting_budget)896	}897898	pub fn burn_from(899		collection: &NonfungibleHandle<T>,900		spender: &T::CrossAccountId,901		from: &T::CrossAccountId,902		token: TokenId,903		nesting_budget: &dyn Budget,904	) -> DispatchResult {905		Self::check_allowed(collection, spender, from, token, nesting_budget)?;906907		// =========908909		Self::burn(collection, from, token)910	}911912	pub fn check_nesting(913		handle: &NonfungibleHandle<T>,914		sender: T::CrossAccountId,915		from: (CollectionId, TokenId),916		under: TokenId,917		nesting_budget: &dyn Budget,918	) -> DispatchResult {919		fn ensure_sender_allowed<T: Config>(920			collection: CollectionId,921			token: TokenId,922			for_nest: (CollectionId, TokenId),923			sender: T::CrossAccountId,924			budget: &dyn Budget,925		) -> DispatchResult {926			ensure!(927				<PalletStructure<T>>::check_indirectly_owned(928					sender,929					collection,930					token,931					Some(for_nest),932					budget933				)?,934				<CommonError<T>>::OnlyOwnerAllowedToNest,935			);936			Ok(())937		}938		match handle.permissions.nesting() {939			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),940			NestingRule::Owner => {941				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?942			}943			NestingRule::OwnerRestricted(whitelist) => {944				ensure!(945					whitelist.contains(&from.0),946					<CommonError<T>>::SourceCollectionIsNotAllowedToNest947				);948				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?949			}950		}951		Ok(())952	}953954	fn nest(955		under: (CollectionId, TokenId),956		to_nest: (CollectionId, TokenId),957	) {958		<TokenChildren<T>>::insert(959			(under.0, under.1, (to_nest.0, to_nest.1)),960			true961		);962	}963964	fn unnest(965		under: (CollectionId, TokenId),966		to_unnest: (CollectionId, TokenId),967	) {968		<TokenChildren<T>>::remove(969			(under.0, under.1, to_unnest)970		);971	}972973	fn collection_has_tokens(collection_id: CollectionId) -> bool {974		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()975	}976977	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {978		<TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()979	}980981	/// Delegated to `create_multiple_items`982	pub fn create_item(983		collection: &NonfungibleHandle<T>,984		sender: &T::CrossAccountId,985		data: CreateItemData<T>,986		nesting_budget: &dyn Budget,987	) -> DispatchResult {988		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)989	}990}
after · pallets/nonfungible/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 erc::ERC721Events;20use evm_coder::ToLog;21use frame_support::{BoundedVec, ensure, fail, transactional, storage::with_transaction};22use up_data_structs::{23	AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,24	mapping::TokenAddressMapping, NestingRule, budget::Budget, Property, PropertyPermission,25	PropertyKey, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty,26};27use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};28use pallet_common::{29	Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,30	eth::collection_id_to_address,31};32use pallet_structure::Pallet as PalletStructure;33use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};34use sp_core::H160;35use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};36use sp_std::{vec::Vec, vec, collections::btree_set::BTreeSet};37use core::ops::Deref;38use sp_std::collections::btree_map::BTreeMap;39use codec::{Encode, Decode, MaxEncodedLen};40use scale_info::TypeInfo;4142pub use pallet::*;43#[cfg(feature = "runtime-benchmarks")]44pub mod benchmarking;45pub mod common;46pub mod erc;47pub mod weights;4849pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;50pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;5152#[struct_versioning::versioned(version = 2, upper)]53#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]54pub struct ItemData<CrossAccountId> {55	#[version(..2)]56	pub const_data: BoundedVec<u8, CustomDataLimit>,5758	#[version(..2)]59	pub variable_data: BoundedVec<u8, CustomDataLimit>,6061	pub owner: CrossAccountId,62}6364#[frame_support::pallet]65pub mod pallet {66	use super::*;67	use frame_support::{68		Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,69	};70	use frame_system::pallet_prelude::*;71	use up_data_structs::{CollectionId, TokenId};72	use super::weights::WeightInfo;7374	#[pallet::error]75	pub enum Error<T> {76		/// Not Nonfungible item data used to mint in Nonfungible collection.77		NotNonfungibleDataUsedToMintFungibleCollectionToken,78		/// Used amount > 1 with NFT79		NonfungibleItemsHaveNoAmount,80		/// Unable to burn NFT with children81		CantBurnNftWithChildren,82	}8384	#[pallet::config]85	pub trait Config:86		frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config87	{88		type WeightInfo: WeightInfo;89	}9091	const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);9293	#[pallet::pallet]94	#[pallet::storage_version(STORAGE_VERSION)]95	#[pallet::generate_store(pub(super) trait Store)]96	pub struct Pallet<T>(_);9798	#[pallet::storage]99	pub type TokensMinted<T: Config> =100		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;101	#[pallet::storage]102	pub type TokensBurnt<T: Config> =103		StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;104105	#[pallet::storage]106	pub type TokenData<T: Config> = StorageNMap<107		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),108		Value = ItemData<T::CrossAccountId>,109		QueryKind = OptionQuery,110	>;111112	#[pallet::storage]113	#[pallet::getter(fn token_properties)]114	pub type TokenProperties<T: Config> = StorageNMap<115		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),116		Value = Properties,117		QueryKind = ValueQuery,118		OnEmpty = up_data_structs::TokenProperties,119	>;120121	/// Used to enumerate tokens owned by account122	#[pallet::storage]123	pub type Owned<T: Config> = StorageNMap<124		Key = (125			Key<Twox64Concat, CollectionId>,126			Key<Blake2_128Concat, T::CrossAccountId>,127			Key<Twox64Concat, TokenId>,128		),129		Value = bool,130		QueryKind = ValueQuery,131	>;132133	/// Used to enumerate token's children134	#[pallet::storage]135	#[pallet::getter(fn token_children)]136	pub type TokenChildren<T: Config> = StorageNMap<137		Key = (138			Key<Twox64Concat, CollectionId>,139			Key<Twox64Concat, TokenId>,140			Key<Twox64Concat, (CollectionId, TokenId)>,141		),142		Value = bool,143		QueryKind = ValueQuery,144	>;145146	#[pallet::storage]147	pub type AccountBalance<T: Config> = StorageNMap<148		Key = (149			Key<Twox64Concat, CollectionId>,150			Key<Blake2_128Concat, T::CrossAccountId>,151		),152		Value = u32,153		QueryKind = ValueQuery,154	>;155156	#[pallet::storage]157	pub type Allowance<T: Config> = StorageNMap<158		Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),159		Value = T::CrossAccountId,160		QueryKind = OptionQuery,161	>;162163	#[pallet::hooks]164	impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {165		fn on_runtime_upgrade() -> Weight {166			if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {167				let mut had_consts = BTreeSet::new();168				<TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(|(collection, token), v| {169					let mut props = vec![];170					if !v.const_data.is_empty() {171						props.push(Property {172							key: b"_old_constData".to_vec().try_into().unwrap(),173							value: v.const_data.clone().into_inner().try_into().expect("const too long"),174						});175						had_consts.insert(collection);176					}177					if !v.variable_data.is_empty() {178						props.push(Property {179							key: b"_old_variableData".to_vec().try_into().unwrap(),180							value: v.variable_data.clone().into_inner().try_into().expect("variable too long"),181						})182					}183					if !props.is_empty() {184						Self::set_scoped_token_properties(185							collection,186							token,187							PropertyScope::None,188							props.into_iter(),189						).expect("existing token data exceeds property storage");190					}191					Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))192				});193				for collection in had_consts {194					<PalletCommon<T>>::set_property_permission_unchecked(195						collection,196						PropertyKeyPermission {197							key: b"_old_constData".to_vec().try_into().unwrap(),198							permission: PropertyPermission {199								mutable: false,200								collection_admin: true,201								token_owner: false,202							},203						}204					).expect("failed to configure permission");205				}206			}207208			0209		}210	}211}212213pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);214impl<T: Config> NonfungibleHandle<T> {215	pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {216		Self(inner)217	}218	pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {219		self.0220	}221	pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {222		&mut self.0223	}224}225impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {226	fn recorder(&self) -> &SubstrateRecorder<T> {227		self.0.recorder()228	}229	fn into_recorder(self) -> SubstrateRecorder<T> {230		self.0.into_recorder()231	}232}233impl<T: Config> Deref for NonfungibleHandle<T> {234	type Target = pallet_common::CollectionHandle<T>;235236	fn deref(&self) -> &Self::Target {237		&self.0238	}239}240241impl<T: Config> Pallet<T> {242	pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {243		<TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)244	}245	pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {246		<TokenData<T>>::contains_key((collection.id, token))247	}248249	pub fn set_scoped_token_property(250		collection_id: CollectionId,251		token_id: TokenId,252		scope: PropertyScope,253		property: Property,254	) -> DispatchResult {255		TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {256			properties.try_scoped_set(scope, property.key, property.value)257		})258		.map_err(<CommonError<T>>::from)?;259260		Ok(())261	}262263	pub fn set_scoped_token_properties(264		collection_id: CollectionId,265		token_id: TokenId,266		scope: PropertyScope,267		properties: impl Iterator<Item=Property>,268	) -> DispatchResult {269		TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {270			stored_properties.try_scoped_set_from_iter(scope, properties)271		})272		.map_err(<CommonError<T>>::from)?;273274		Ok(())275	}276277	pub fn current_token_id(collection_id: CollectionId) -> TokenId {278		TokenId(<TokensMinted<T>>::get(collection_id))279	}280}281282// unchecked calls skips any permission checks283impl<T: Config> Pallet<T> {284	pub fn init_collection(285		owner: T::AccountId,286		data: CreateCollectionData<T::AccountId>,287	) -> Result<CollectionId, DispatchError> {288		<PalletCommon<T>>::init_collection(owner, data)289	}290	pub fn destroy_collection(291		collection: NonfungibleHandle<T>,292		sender: &T::CrossAccountId,293	) -> DispatchResult {294		let id = collection.id;295296		if Self::collection_has_tokens(id) {297			return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());298		}299300		// =========301302		PalletCommon::destroy_collection(collection.0, sender)?;303304		<TokenData<T>>::remove_prefix((id,), None);305		<TokenChildren<T>>::remove_prefix((id,), None);306		<Owned<T>>::remove_prefix((id,), None);307		<TokensMinted<T>>::remove(id);308		<TokensBurnt<T>>::remove(id);309		<Allowance<T>>::remove_prefix((id,), None);310		<AccountBalance<T>>::remove_prefix((id,), None);311		Ok(())312	}313314	pub fn burn(315		collection: &NonfungibleHandle<T>,316		sender: &T::CrossAccountId,317		token: TokenId,318	) -> DispatchResult {319		let token_data =320			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;321		ensure!(322			&token_data.owner == sender323				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(sender)),324			<CommonError<T>>::NoPermission325		);326327		if collection.permissions.access() == AccessMode::AllowList {328			collection.check_allowlist(sender)?;329		}330331		if Self::token_has_children(collection.id, token) {332			return Err(<Error<T>>::CantBurnNftWithChildren.into());333		}334335		let burnt = <TokensBurnt<T>>::get(collection.id)336			.checked_add(1)337			.ok_or(ArithmeticError::Overflow)?;338339		let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))340			.checked_sub(1)341			.ok_or(ArithmeticError::Overflow)?;342343		// =========344345		if balance == 0 {346			<AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));347		} else {348			<AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);349		}350351		<PalletStructure<T>>::unnest_if_nested(352			&token_data.owner,353			collection.id,354			token355		);356357		<Owned<T>>::remove((collection.id, &token_data.owner, token));358		<TokensBurnt<T>>::insert(collection.id, burnt);359		<TokenData<T>>::remove((collection.id, token));360		<TokenProperties<T>>::remove((collection.id, token));361		let old_spender = <Allowance<T>>::take((collection.id, token));362363		if let Some(old_spender) = old_spender {364			<PalletCommon<T>>::deposit_event(CommonEvent::Approved(365				collection.id,366				token,367				sender.clone(),368				old_spender,369				0,370			));371		}372373		<PalletEvm<T>>::deposit_log(374			ERC721Events::Transfer {375				from: *token_data.owner.as_eth(),376				to: H160::default(),377				token_id: token.into(),378			}379			.to_log(collection_id_to_address(collection.id)),380		);381		<PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(382			collection.id,383			token,384			token_data.owner,385			1,386		));387		Ok(())388	}389390	pub fn set_token_property(391		collection: &NonfungibleHandle<T>,392		sender: &T::CrossAccountId,393		token_id: TokenId,394		property: Property,395	) -> DispatchResult {396		Self::check_token_change_permission(collection, sender, token_id, &property.key)?;397398		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {399			let property = property.clone();400			properties.try_set(property.key, property.value)401		})402		.map_err(<CommonError<T>>::from)?;403404		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(405			collection.id,406			token_id,407			property.key,408		));409410		Ok(())411	}412413	#[transactional]414	pub fn set_token_properties(415		collection: &NonfungibleHandle<T>,416		sender: &T::CrossAccountId,417		token_id: TokenId,418		properties: Vec<Property>,419	) -> DispatchResult {420		for property in properties {421			Self::set_token_property(collection, sender, token_id, property)?;422		}423424		Ok(())425	}426427	pub fn delete_token_property(428		collection: &NonfungibleHandle<T>,429		sender: &T::CrossAccountId,430		token_id: TokenId,431		property_key: PropertyKey,432	) -> DispatchResult {433		Self::check_token_change_permission(collection, sender, token_id, &property_key)?;434435		<TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {436			properties.remove(&property_key)437		})438		.map_err(<CommonError<T>>::from)?;439440		<PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(441			collection.id,442			token_id,443			property_key,444		));445446		Ok(())447	}448449	fn check_token_change_permission(450		collection: &NonfungibleHandle<T>,451		sender: &T::CrossAccountId,452		token_id: TokenId,453		property_key: &PropertyKey,454	) -> DispatchResult {455		let permission = <PalletCommon<T>>::property_permissions(collection.id)456			.get(property_key)457			.cloned()458			.unwrap_or_else(PropertyPermission::none);459460		let token_data = <TokenData<T>>::get((collection.id, token_id))461			.ok_or(<CommonError<T>>::TokenNotFound)?;462463		let check_token_owner = || -> DispatchResult {464			ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);465			Ok(())466		};467468		let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))469			.get(property_key)470			.is_some();471472		match permission {473			PropertyPermission { mutable: false, .. } if is_property_exists => {474				Err(<CommonError<T>>::NoPermission.into())475			}476477			PropertyPermission {478				collection_admin,479				token_owner,480				..481			} => {482				let mut check_result = Err(<CommonError<T>>::NoPermission.into());483484				if collection_admin {485					check_result = collection.check_is_owner_or_admin(sender);486				}487488				if token_owner {489					check_result.or_else(|_| check_token_owner())490				} else {491					check_result492				}493			}494		}495	}496497	#[transactional]498	pub fn delete_token_properties(499		collection: &NonfungibleHandle<T>,500		sender: &T::CrossAccountId,501		token_id: TokenId,502		property_keys: Vec<PropertyKey>,503	) -> DispatchResult {504		for key in property_keys {505			Self::delete_token_property(collection, sender, token_id, key)?;506		}507508		Ok(())509	}510511	pub fn set_collection_properties(512		collection: &NonfungibleHandle<T>,513		sender: &T::CrossAccountId,514		properties: Vec<Property>,515	) -> DispatchResult {516		<PalletCommon<T>>::set_collection_properties(collection, sender, properties)517	}518519	pub fn delete_collection_properties(520		collection: &CollectionHandle<T>,521		sender: &T::CrossAccountId,522		property_keys: Vec<PropertyKey>,523	) -> DispatchResult {524		<PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)525	}526527	pub fn set_property_permissions(528		collection: &CollectionHandle<T>,529		sender: &T::CrossAccountId,530		property_permissions: Vec<PropertyKeyPermission>,531	) -> DispatchResult {532		<PalletCommon<T>>::set_property_permissions(collection, sender, property_permissions)533	}534535	pub fn set_property_permission(536		collection: &CollectionHandle<T>,537		sender: &T::CrossAccountId,538		permission: PropertyKeyPermission,539	) -> DispatchResult {540		<PalletCommon<T>>::set_property_permission(collection, sender, permission)541	}542543	pub fn transfer(544		collection: &NonfungibleHandle<T>,545		from: &T::CrossAccountId,546		to: &T::CrossAccountId,547		token: TokenId,548		nesting_budget: &dyn Budget,549	) -> DispatchResult {550		ensure!(551			collection.limits.transfers_enabled(),552			<CommonError<T>>::TransferNotAllowed553		);554555		let token_data =556			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;557		// TODO: require sender to be token, owner, require admins to go through transfer_from558		ensure!(559			&token_data.owner == from560				|| (collection.limits.owner_can_transfer() && collection.is_owner_or_admin(from)),561			<CommonError<T>>::NoPermission562		);563564		if collection.permissions.access() == AccessMode::AllowList {565			collection.check_allowlist(from)?;566			collection.check_allowlist(to)?;567		}568		<PalletCommon<T>>::ensure_correct_receiver(to)?;569570		let balance_from = <AccountBalance<T>>::get((collection.id, from))571			.checked_sub(1)572			.ok_or(<CommonError<T>>::TokenValueTooLow)?;573		let balance_to = if from != to {574			let balance_to = <AccountBalance<T>>::get((collection.id, to))575				.checked_add(1)576				.ok_or(ArithmeticError::Overflow)?;577578			ensure!(579				balance_to < collection.limits.account_token_ownership_limit(),580				<CommonError<T>>::AccountTokenLimitExceeded,581			);582583			Some(balance_to)584		} else {585			None586		};587588		<PalletStructure<T>>::nest_if_sent_to_token(589			from.clone(),590			to,591			collection.id,592			token,593			nesting_budget594		)?;595596		// =========597598		<PalletStructure<T>>::unnest_if_nested(599			from,600			collection.id,601			token602		);603604		<TokenData<T>>::insert(605			(collection.id, token),606			ItemData {607				owner: to.clone(),608				..token_data609			},610		);611612		if let Some(balance_to) = balance_to {613			// from != to614			if balance_from == 0 {615				<AccountBalance<T>>::remove((collection.id, from));616			} else {617				<AccountBalance<T>>::insert((collection.id, from), balance_from);618			}619			<AccountBalance<T>>::insert((collection.id, to), balance_to);620			<Owned<T>>::remove((collection.id, from, token));621			<Owned<T>>::insert((collection.id, to, token), true);622		}623		Self::set_allowance_unchecked(collection, from, token, None, true);624625		<PalletEvm<T>>::deposit_log(626			ERC721Events::Transfer {627				from: *from.as_eth(),628				to: *to.as_eth(),629				token_id: token.into(),630			}631			.to_log(collection_id_to_address(collection.id)),632		);633		<PalletCommon<T>>::deposit_event(CommonEvent::Transfer(634			collection.id,635			token,636			from.clone(),637			to.clone(),638			1,639		));640		Ok(())641	}642643	pub fn create_multiple_items(644		collection: &NonfungibleHandle<T>,645		sender: &T::CrossAccountId,646		data: Vec<CreateItemData<T>>,647		nesting_budget: &dyn Budget,648	) -> DispatchResult {649		if !collection.is_owner_or_admin(sender) {650			ensure!(651				collection.permissions.mint_mode(),652				<CommonError<T>>::PublicMintingNotAllowed653			);654			collection.check_allowlist(sender)?;655656			for item in data.iter() {657				collection.check_allowlist(&item.owner)?;658			}659		}660661		for data in data.iter() {662			<PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;663		}664665		let first_token = <TokensMinted<T>>::get(collection.id);666		let tokens_minted = first_token667			.checked_add(data.len() as u32)668			.ok_or(ArithmeticError::Overflow)?;669		ensure!(670			tokens_minted <= collection.limits.token_limit(),671			<CommonError<T>>::CollectionTokenLimitExceeded672		);673674		let mut balances = BTreeMap::new();675		for data in &data {676			let balance = balances677				.entry(&data.owner)678				.or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));679			*balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;680681			ensure!(682				*balance <= collection.limits.account_token_ownership_limit(),683				<CommonError<T>>::AccountTokenLimitExceeded,684			);685		}686687		for (i, data) in data.iter().enumerate() {688			let token = TokenId(first_token + i as u32 + 1);689690			<PalletStructure<T>>::check_nesting(691				sender.clone(),692				&data.owner,693				collection.id,694				token,695				nesting_budget,696			)?;697		}698699		// =========700701		with_transaction(|| {702			for (i, data) in data.iter().enumerate() {703				let token = first_token + i as u32 + 1;704705				<TokenData<T>>::insert(706					(collection.id, token),707					ItemData {708						// const_data: data.const_data.clone(),709						owner: data.owner.clone(),710					},711				);712713				<PalletStructure<T>>::nest_if_sent_to_token_unchecked(&data.owner, collection.id, TokenId(token));714715				if let Err(e) = Self::set_token_properties(716					collection,717					sender,718					TokenId(token),719					data.properties.clone().into_inner(),720				) {721					return TransactionOutcome::Rollback(Err(e));722				}723			}724			TransactionOutcome::Commit(Ok(()))725		})?;726727		<TokensMinted<T>>::insert(collection.id, tokens_minted);728		for (account, balance) in balances {729			<AccountBalance<T>>::insert((collection.id, account), balance);730		}731		for (i, data) in data.into_iter().enumerate() {732			let token = first_token + i as u32 + 1;733			<Owned<T>>::insert((collection.id, &data.owner, token), true);734735			<PalletEvm<T>>::deposit_log(736				ERC721Events::Transfer {737					from: H160::default(),738					to: *data.owner.as_eth(),739					token_id: token.into(),740				}741				.to_log(collection_id_to_address(collection.id)),742			);743			<PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(744				collection.id,745				TokenId(token),746				data.owner.clone(),747				1,748			));749		}750		Ok(())751	}752753	pub fn set_allowance_unchecked(754		collection: &NonfungibleHandle<T>,755		sender: &T::CrossAccountId,756		token: TokenId,757		spender: Option<&T::CrossAccountId>,758		assume_implicit_eth: bool,759	) {760		if let Some(spender) = spender {761			let old_spender = <Allowance<T>>::get((collection.id, token));762			<Allowance<T>>::insert((collection.id, token), spender);763			// In ERC721 there is only one possible approved user of token, so we set764			// approved user to spender765			<PalletEvm<T>>::deposit_log(766				ERC721Events::Approval {767					owner: *sender.as_eth(),768					approved: *spender.as_eth(),769					token_id: token.into(),770				}771				.to_log(collection_id_to_address(collection.id)),772			);773			// In Unique chain, any token can have any amount of approved users, so we need to774			// set allowance of old owner to 0, and allowance of new owner to 1775			if old_spender.as_ref() != Some(spender) {776				if let Some(old_owner) = old_spender {777					<PalletCommon<T>>::deposit_event(CommonEvent::Approved(778						collection.id,779						token,780						sender.clone(),781						old_owner,782						0,783					));784				}785				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(786					collection.id,787					token,788					sender.clone(),789					spender.clone(),790					1,791				));792			}793		} else {794			let old_spender = <Allowance<T>>::take((collection.id, token));795			if !assume_implicit_eth {796				// In ERC721 there is only one possible approved user of token, so we set797				// approved user to zero address798				<PalletEvm<T>>::deposit_log(799					ERC721Events::Approval {800						owner: *sender.as_eth(),801						approved: H160::default(),802						token_id: token.into(),803					}804					.to_log(collection_id_to_address(collection.id)),805				);806			}807			// In Unique chain, any token can have any amount of approved users, so we need to808			// set allowance of old owner to 0809			if let Some(old_spender) = old_spender {810				<PalletCommon<T>>::deposit_event(CommonEvent::Approved(811					collection.id,812					token,813					sender.clone(),814					old_spender,815					0,816				));817			}818		}819	}820821	pub fn set_allowance(822		collection: &NonfungibleHandle<T>,823		sender: &T::CrossAccountId,824		token: TokenId,825		spender: Option<&T::CrossAccountId>,826	) -> DispatchResult {827		if collection.permissions.access() == AccessMode::AllowList {828			collection.check_allowlist(sender)?;829			if let Some(spender) = spender {830				collection.check_allowlist(spender)?;831			}832		}833834		if let Some(spender) = spender {835			<PalletCommon<T>>::ensure_correct_receiver(spender)?;836		}837		let token_data =838			<TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;839		if &token_data.owner != sender {840			ensure!(841				collection.ignores_owned_amount(sender),842				<CommonError<T>>::CantApproveMoreThanOwned843			);844		}845846		// =========847848		Self::set_allowance_unchecked(collection, sender, token, spender, false);849		Ok(())850	}851852	fn check_allowed(853		collection: &NonfungibleHandle<T>,854		spender: &T::CrossAccountId,855		from: &T::CrossAccountId,856		token: TokenId,857		nesting_budget: &dyn Budget,858	) -> DispatchResult {859		if spender.conv_eq(from) {860			return Ok(());861		}862		if collection.permissions.access() == AccessMode::AllowList {863			// `from`, `to` checked in [`transfer`]864			collection.check_allowlist(spender)?;865		}866		if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {867			// TODO: should collection owner be allowed to perform this transfer?868			ensure!(869				<PalletStructure<T>>::check_indirectly_owned(870					spender.clone(),871					source.0,872					source.1,873					None,874					nesting_budget875				)?,876				<CommonError<T>>::ApprovedValueTooLow,877			);878			return Ok(());879		}880		if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {881			return Ok(());882		}883		ensure!(884			collection.ignores_allowance(spender),885			<CommonError<T>>::ApprovedValueTooLow886		);887		Ok(())888	}889890	pub fn transfer_from(891		collection: &NonfungibleHandle<T>,892		spender: &T::CrossAccountId,893		from: &T::CrossAccountId,894		to: &T::CrossAccountId,895		token: TokenId,896		nesting_budget: &dyn Budget,897	) -> DispatchResult {898		Self::check_allowed(collection, spender, from, token, nesting_budget)?;899900		// =========901902		// Allowance is reset in [`transfer`]903		Self::transfer(collection, from, to, token, nesting_budget)904	}905906	pub fn burn_from(907		collection: &NonfungibleHandle<T>,908		spender: &T::CrossAccountId,909		from: &T::CrossAccountId,910		token: TokenId,911		nesting_budget: &dyn Budget,912	) -> DispatchResult {913		Self::check_allowed(collection, spender, from, token, nesting_budget)?;914915		// =========916917		Self::burn(collection, from, token)918	}919920	pub fn check_nesting(921		handle: &NonfungibleHandle<T>,922		sender: T::CrossAccountId,923		from: (CollectionId, TokenId),924		under: TokenId,925		nesting_budget: &dyn Budget,926	) -> DispatchResult {927		fn ensure_sender_allowed<T: Config>(928			collection: CollectionId,929			token: TokenId,930			for_nest: (CollectionId, TokenId),931			sender: T::CrossAccountId,932			budget: &dyn Budget,933		) -> DispatchResult {934			ensure!(935				<PalletStructure<T>>::check_indirectly_owned(936					sender,937					collection,938					token,939					Some(for_nest),940					budget941				)?,942				<CommonError<T>>::OnlyOwnerAllowedToNest,943			);944			Ok(())945		}946		match handle.permissions.nesting() {947			NestingRule::Disabled => fail!(<CommonError<T>>::NestingIsDisabled),948			NestingRule::Owner => {949				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?950			}951			NestingRule::OwnerRestricted(whitelist) => {952				ensure!(953					whitelist.contains(&from.0),954					<CommonError<T>>::SourceCollectionIsNotAllowedToNest955				);956				ensure_sender_allowed::<T>(handle.id, under, from, sender, nesting_budget)?957			}958		}959		Ok(())960	}961962	fn nest(963		under: (CollectionId, TokenId),964		to_nest: (CollectionId, TokenId),965	) {966		<TokenChildren<T>>::insert(967			(under.0, under.1, (to_nest.0, to_nest.1)),968			true969		);970	}971972	fn unnest(973		under: (CollectionId, TokenId),974		to_unnest: (CollectionId, TokenId),975	) {976		<TokenChildren<T>>::remove(977			(under.0, under.1, to_unnest)978		);979	}980981	fn collection_has_tokens(collection_id: CollectionId) -> bool {982		<TokenData<T>>::iter_prefix((collection_id,)).next().is_some()983	}984985	fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {986		<TokenChildren<T>>::iter_prefix((collection_id, token_id)).next().is_some()987	}988989	/// Delegated to `create_multiple_items`990	pub fn create_item(991		collection: &NonfungibleHandle<T>,992		sender: &T::CrossAccountId,993		data: CreateItemData<T>,994		nesting_budget: &dyn Budget,995	) -> DispatchResult {996		Self::create_multiple_items(collection, sender, vec![data], nesting_budget)997	}998}
modifiedpallets/refungible/src/lib.rsdiffbeforeafterboth
--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -395,6 +395,11 @@
 			// from != to
 			if balance_from == 0 {
 				<Balance<T>>::remove((collection.id, token, from));
+				<PalletStructure<T>>::unnest_if_nested(
+					from,
+					collection.id,
+					token
+				);
 			} else {
 				<Balance<T>>::insert((collection.id, token, from), balance_from);
 			}