difftreelog
fix native ft nesting
in: master
6 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6969,6 +6969,7 @@
"frame-benchmarking",
"frame-support",
"frame-system",
+ "pallet-balances",
"pallet-common",
"pallet-evm",
"pallet-evm-coder-substrate",
pallets/balances-adapter/src/lib.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/lib.rs
+++ b/pallets/balances-adapter/src/lib.rs
@@ -148,24 +148,6 @@
.map_err(|_| sp_runtime::ArithmeticError::Overflow)?,
ExistenceRequirement::AllowDeath,
)?;
-
- <PalletStructure<T>>::nest_if_sent_to_token(
- from.clone(),
- to,
- NATIVE_FUNGIBLE_COLLECTION_ID,
- TokenId::default(),
- nesting_budget,
- )?;
-
- let balance_from: u128 =
- <T as Config>::Currency::free_balance(from.as_sub()).into();
- if balance_from == 0 {
- <PalletStructure<T>>::unnest_if_nested(
- from,
- NATIVE_FUNGIBLE_COLLECTION_ID,
- TokenId::default(),
- );
- }
};
Ok(PostDispatchInfo {
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -12,6 +12,7 @@
frame-benchmarking = { workspace = true, optional = true }
frame-support = { workspace = true }
frame-system = { workspace = true }
+pallet-balances = { workspace = true }
pallet-common = { workspace = true }
pallet-evm = { workspace = true }
pallet-evm-coder-substrate = { workspace = true }
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//! Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//! an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//! it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//! attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//! with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//! Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,105 PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Token data, stored independently from other data used to describe it135/// for the convenience of database access. Notably contains the owner account address.136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139 #[version(..2)]140 pub const_data: BoundedVec<u8, CustomDataLimit>,141142 #[version(..2)]143 pub variable_data: BoundedVec<u8, CustomDataLimit>,144145 pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150 use super::*;151 use frame_support::{152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153 };154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 /// Not Nonfungible item data used to mint in Nonfungible collection.160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 /// Used amount > 1 with NFT162 NonfungibleItemsHaveNoAmount,163 /// Unable to burn NFT with children164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::Config170 + pallet_common::Config171 + pallet_structure::Config172 + pallet_evm::Config173 + pallet_balances::Config174 {175 type WeightInfo: WeightInfo;176 }177178 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);179180 #[pallet::pallet]181 #[pallet::storage_version(STORAGE_VERSION)]182 pub struct Pallet<T>(_);183184 /// Total amount of minted tokens in a collection.185 #[pallet::storage]186 pub type TokensMinted<T: Config> =187 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;188189 /// Amount of burnt tokens in a collection.190 #[pallet::storage]191 pub type TokensBurnt<T: Config> =192 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;193194 /// Token data, used to partially describe a token.195 #[pallet::storage]196 pub type TokenData<T: Config> = StorageNMap<197 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),198 Value = ItemData<T::CrossAccountId>,199 QueryKind = OptionQuery,200 >;201202 /// Map of key-value pairs, describing the metadata of a token.203 #[pallet::storage]204 #[pallet::getter(fn token_properties)]205 pub type TokenProperties<T: Config> = StorageNMap<206 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),207 Value = TokenPropertiesT,208 QueryKind = ValueQuery,209 >;210211 /// Custom data of a token that is serialized to bytes,212 /// primarily reserved for on-chain operations,213 /// normally obscured from the external users.214 ///215 /// Auxiliary properties are slightly different from216 /// usual [`TokenProperties`] due to an unlimited number217 /// and separately stored and written-to key-value pairs.218 ///219 /// Currently unused.220 #[pallet::storage]221 #[pallet::getter(fn token_aux_property)]222 pub type TokenAuxProperties<T: Config> = StorageNMap<223 Key = (224 Key<Twox64Concat, CollectionId>,225 Key<Twox64Concat, TokenId>,226 Key<Twox64Concat, PropertyScope>,227 Key<Twox64Concat, PropertyKey>,228 ),229 Value = AuxPropertyValue,230 QueryKind = OptionQuery,231 >;232233 /// Used to enumerate tokens owned by account.234 #[pallet::storage]235 pub type Owned<T: Config> = StorageNMap<236 Key = (237 Key<Twox64Concat, CollectionId>,238 Key<Blake2_128Concat, T::CrossAccountId>,239 Key<Twox64Concat, TokenId>,240 ),241 Value = bool,242 QueryKind = ValueQuery,243 >;244245 /// Used to enumerate token's children.246 #[pallet::storage]247 #[pallet::getter(fn token_children)]248 pub type TokenChildren<T: Config> = StorageNMap<249 Key = (250 Key<Twox64Concat, CollectionId>,251 Key<Twox64Concat, TokenId>,252 Key<Twox64Concat, (CollectionId, TokenId)>,253 ),254 Value = bool,255 QueryKind = ValueQuery,256 >;257258 /// Amount of tokens owned by an account in a collection.259 #[pallet::storage]260 pub type AccountBalance<T: Config> = StorageNMap<261 Key = (262 Key<Twox64Concat, CollectionId>,263 Key<Blake2_128Concat, T::CrossAccountId>,264 ),265 Value = u32,266 QueryKind = ValueQuery,267 >;268269 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.270 #[pallet::storage]271 pub type Allowance<T: Config> = StorageNMap<272 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),273 Value = T::CrossAccountId,274 QueryKind = OptionQuery,275 >;276277 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.278 #[pallet::storage]279 pub type CollectionAllowance<T: Config> = StorageNMap<280 Key = (281 Key<Twox64Concat, CollectionId>,282 Key<Blake2_128Concat, T::CrossAccountId>,283 Key<Blake2_128Concat, T::CrossAccountId>,284 ),285 Value = bool,286 QueryKind = ValueQuery,287 >;288289 #[pallet::genesis_config]290 pub struct GenesisConfig<T>(PhantomData<T>);291292 #[cfg(feature = "std")]293 impl<T: Config> Default for GenesisConfig<T> {294 fn default() -> Self {295 Self(Default::default())296 }297 }298299 #[pallet::genesis_build]300 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {301 fn build(&self) {302 StorageVersion::new(1).put::<Pallet<T>>();303 }304 }305}306307pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);308impl<T: Config> NonfungibleHandle<T> {309 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {310 Self(inner)311 }312 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {313 self.0314 }315 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {316 &mut self.0317 }318}319320impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {321 fn recorder(&self) -> &SubstrateRecorder<T> {322 self.0.recorder()323 }324 fn into_recorder(self) -> SubstrateRecorder<T> {325 self.0.into_recorder()326 }327}328impl<T: Config> Deref for NonfungibleHandle<T> {329 type Target = pallet_common::CollectionHandle<T>;330331 fn deref(&self) -> &Self::Target {332 &self.0333 }334}335336impl<T: Config> Pallet<T> {337 /// Get number of NFT tokens in collection.338 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {339 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)340 }341342 /// Check that NFT token exists.343 ///344 /// - `token`: Token ID.345 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {346 <TokenData<T>>::contains_key((collection.id, token))347 }348349 /// Set the token property with the scope.350 ///351 /// - `property`: Contains key-value pair.352 pub fn set_scoped_token_property(353 collection_id: CollectionId,354 token_id: TokenId,355 scope: PropertyScope,356 property: Property,357 ) -> DispatchResult {358 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {359 properties.try_scoped_set(scope, property.key, property.value)360 })361 .map_err(<CommonError<T>>::from)?;362363 Ok(())364 }365366 /// Batch operation to set multiple properties with the same scope.367 pub fn set_scoped_token_properties(368 collection_id: CollectionId,369 token_id: TokenId,370 scope: PropertyScope,371 properties: impl Iterator<Item = Property>,372 ) -> DispatchResult {373 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {374 stored_properties.try_scoped_set_from_iter(scope, properties)375 })376 .map_err(<CommonError<T>>::from)?;377378 Ok(())379 }380381 /// Add or edit auxiliary data for the property.382 ///383 /// - `f`: function that adds or edits auxiliary data.384 pub fn try_mutate_token_aux_property<R, E>(385 collection_id: CollectionId,386 token_id: TokenId,387 scope: PropertyScope,388 key: PropertyKey,389 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,390 ) -> Result<R, E> {391 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)392 }393394 /// Remove auxiliary data for the property.395 pub fn remove_token_aux_property(396 collection_id: CollectionId,397 token_id: TokenId,398 scope: PropertyScope,399 key: PropertyKey,400 ) {401 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));402 }403404 /// Get all auxiliary data in a given scope.405 ///406 /// Returns iterator over Property Key - Data pairs.407 pub fn iterate_token_aux_properties(408 collection_id: CollectionId,409 token_id: TokenId,410 scope: PropertyScope,411 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {412 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))413 }414415 /// Get ID of the last minted token416 pub fn current_token_id(collection_id: CollectionId) -> TokenId {417 TokenId(<TokensMinted<T>>::get(collection_id))418 }419}420421// unchecked calls skips any permission checks422impl<T: Config> Pallet<T> {423 /// Create NFT collection424 ///425 /// `init_collection` will take non-refundable deposit for collection creation.426 ///427 /// - `data`: Contains settings for collection limits and permissions.428 pub fn init_collection(429 owner: T::CrossAccountId,430 payer: T::CrossAccountId,431 data: CreateCollectionData<T::AccountId>,432 flags: CollectionFlags,433 ) -> Result<CollectionId, DispatchError> {434 <PalletCommon<T>>::init_collection(owner, payer, data, flags)435 }436437 /// Destroy NFT collection438 ///439 /// `destroy_collection` will throw error if collection contains any tokens.440 /// Only owner can destroy collection.441 pub fn destroy_collection(442 collection: NonfungibleHandle<T>,443 sender: &T::CrossAccountId,444 ) -> DispatchResult {445 let id = collection.id;446447 if Self::collection_has_tokens(id) {448 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());449 }450451 // =========452453 PalletCommon::destroy_collection(collection.0, sender)?;454455 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);456 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);457 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);458 <TokensMinted<T>>::remove(id);459 <TokensBurnt<T>>::remove(id);460 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);461 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);462 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);463 Ok(())464 }465466 /// Burn NFT token467 ///468 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token469 /// if the token is nested.470 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.471 /// Also removes all corresponding properties and auxiliary properties.472 ///473 /// - `token`: Token that should be burned474 /// - `collection`: Collection that contains the token475 pub fn burn(476 collection: &NonfungibleHandle<T>,477 sender: &T::CrossAccountId,478 token: TokenId,479 ) -> DispatchResult {480 let token_data =481 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;482 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);483484 if collection.permissions.access() == AccessMode::AllowList {485 collection.check_allowlist(sender)?;486 }487488 if Self::token_has_children(collection.id, token) {489 return Err(<Error<T>>::CantBurnNftWithChildren.into());490 }491492 let burnt = <TokensBurnt<T>>::get(collection.id)493 .checked_add(1)494 .ok_or(ArithmeticError::Overflow)?;495496 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))497 .checked_sub(1)498 .ok_or(ArithmeticError::Overflow)?;499500 // =========501502 if balance == 0 {503 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));504 } else {505 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);506 }507508 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);509510 <Owned<T>>::remove((collection.id, &token_data.owner, token));511 <TokensBurnt<T>>::insert(collection.id, burnt);512 <TokenData<T>>::remove((collection.id, token));513 <TokenProperties<T>>::remove((collection.id, token));514 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);515 let old_spender = <Allowance<T>>::take((collection.id, token));516517 if let Some(old_spender) = old_spender {518 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(519 collection.id,520 token,521 token_data.owner.clone(),522 old_spender,523 0,524 ));525 }526527 <PalletEvm<T>>::deposit_log(528 ERC721Events::Transfer {529 from: *token_data.owner.as_eth(),530 to: H160::default(),531 token_id: token.into(),532 }533 .to_log(collection_id_to_address(collection.id)),534 );535 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(536 collection.id,537 token,538 token_data.owner,539 1,540 ));541 Ok(())542 }543544 /// Same as [`burn`] but burns all the tokens that are nested in the token first545 ///546 /// - `self_budget`: Limit for searching children in depth.547 /// - `breadth_budget`: Limit of breadth of searching children.548 ///549 /// [`burn`]: struct.Pallet.html#method.burn550 #[transactional]551 pub fn burn_recursively(552 collection: &NonfungibleHandle<T>,553 sender: &T::CrossAccountId,554 token: TokenId,555 self_budget: &dyn Budget,556 breadth_budget: &dyn Budget,557 ) -> DispatchResultWithPostInfo {558 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);559560 let current_token_account =561 T::CrossTokenAddressMapping::token_to_address(collection.id, token);562563 let mut weight = Weight::zero();564565 // This method is transactional, if user in fact doesn't have permissions to remove token -566 // tokens removed here will be restored after rejected transaction567 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {568 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);569 let PostDispatchInfo { actual_weight, .. } =570 <PalletStructure<T>>::burn_item_recursively(571 current_token_account.clone(),572 collection,573 token,574 self_budget,575 breadth_budget,576 )?;577 if let Some(actual_weight) = actual_weight {578 weight = weight.saturating_add(actual_weight);579 }580 }581582 Self::burn(collection, sender, token)?;583 DispatchResultWithPostInfo::Ok(PostDispatchInfo {584 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),585 pays_fee: Pays::Yes,586 })587 }588589 /// A batch operation to add, edit or remove properties for a token.590 ///591 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.592 /// - `is_token_create`: Indicates that method is called during token initialization.593 /// Allows to bypass ownership check.594 ///595 /// All affected properties should have `mutable` permission596 /// to be **deleted** or to be **set more than once**,597 /// and the sender should have permission to edit those properties.598 ///599 /// This function fires an event for each property change.600 /// In case of an error, all the changes (including the events) will be reverted601 /// since the function is transactional.602 #[transactional]603 fn modify_token_properties(604 collection: &NonfungibleHandle<T>,605 sender: &T::CrossAccountId,606 token_id: TokenId,607 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,608 is_token_create: bool,609 nesting_budget: &dyn Budget,610 ) -> DispatchResult {611 let is_token_owner = || {612 let is_owned = <PalletStructure<T>>::check_indirectly_owned(613 sender.clone(),614 collection.id,615 token_id,616 None,617 nesting_budget,618 )?;619620 Ok(is_owned)621 };622623 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));624625 <PalletCommon<T>>::modify_token_properties(626 collection,627 sender,628 token_id,629 properties_updates,630 is_token_create,631 stored_properties,632 is_token_owner,633 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),634 erc::ERC721TokenEvent::TokenChanged {635 token_id: token_id.into(),636 }637 .to_log(T::ContractAddress::get()),638 )639 }640641 /// Batch operation to add or edit properties for the token642 ///643 /// Same as [`modify_token_properties`] but doesn't allow to remove properties644 ///645 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties646 pub fn set_token_properties(647 collection: &NonfungibleHandle<T>,648 sender: &T::CrossAccountId,649 token_id: TokenId,650 properties: impl Iterator<Item = Property>,651 is_token_create: bool,652 nesting_budget: &dyn Budget,653 ) -> DispatchResult {654 Self::modify_token_properties(655 collection,656 sender,657 token_id,658 properties.map(|p| (p.key, Some(p.value))),659 is_token_create,660 nesting_budget,661 )662 }663664 /// Add or edit single property for the token665 ///666 /// Calls [`set_token_properties`] internally667 ///668 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties669 pub fn set_token_property(670 collection: &NonfungibleHandle<T>,671 sender: &T::CrossAccountId,672 token_id: TokenId,673 property: Property,674 nesting_budget: &dyn Budget,675 ) -> DispatchResult {676 let is_token_create = false;677678 Self::set_token_properties(679 collection,680 sender,681 token_id,682 [property].into_iter(),683 is_token_create,684 nesting_budget,685 )686 }687688 /// Batch operation to remove properties from the token689 ///690 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties691 ///692 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties693 pub fn delete_token_properties(694 collection: &NonfungibleHandle<T>,695 sender: &T::CrossAccountId,696 token_id: TokenId,697 property_keys: impl Iterator<Item = PropertyKey>,698 nesting_budget: &dyn Budget,699 ) -> DispatchResult {700 let is_token_create = false;701702 Self::modify_token_properties(703 collection,704 sender,705 token_id,706 property_keys.into_iter().map(|key| (key, None)),707 is_token_create,708 nesting_budget,709 )710 }711712 /// Remove single property from the token713 ///714 /// Calls [`delete_token_properties`] internally715 ///716 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties717 pub fn delete_token_property(718 collection: &NonfungibleHandle<T>,719 sender: &T::CrossAccountId,720 token_id: TokenId,721 property_key: PropertyKey,722 nesting_budget: &dyn Budget,723 ) -> DispatchResult {724 Self::delete_token_properties(725 collection,726 sender,727 token_id,728 [property_key].into_iter(),729 nesting_budget,730 )731 }732733 /// Add or edit properties for the collection734 pub fn set_collection_properties(735 collection: &NonfungibleHandle<T>,736 sender: &T::CrossAccountId,737 properties: Vec<Property>,738 ) -> DispatchResult {739 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())740 }741742 /// Remove properties from the collection743 pub fn delete_collection_properties(744 collection: &CollectionHandle<T>,745 sender: &T::CrossAccountId,746 property_keys: Vec<PropertyKey>,747 ) -> DispatchResult {748 <PalletCommon<T>>::delete_collection_properties(749 collection,750 sender,751 property_keys.into_iter(),752 )753 }754755 /// Set property permissions for the token.756 ///757 /// Sender should be the owner or admin of token's collection.758 pub fn set_token_property_permissions(759 collection: &CollectionHandle<T>,760 sender: &T::CrossAccountId,761 property_permissions: Vec<PropertyKeyPermission>,762 ) -> DispatchResult {763 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)764 }765766 /// Set property permissions for the token with scope.767 ///768 /// Sender should be the owner or admin of token's collection.769 pub fn set_scoped_token_property_permissions(770 collection: &CollectionHandle<T>,771 sender: &T::CrossAccountId,772 scope: PropertyScope,773 property_permissions: Vec<PropertyKeyPermission>,774 ) -> DispatchResult {775 <PalletCommon<T>>::set_scoped_token_property_permissions(776 collection,777 sender,778 scope,779 property_permissions,780 )781 }782783 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {784 <PalletCommon<T>>::property_permissions(collection_id)785 }786787 pub fn check_token_immediate_ownership(788 collection: &NonfungibleHandle<T>,789 token: TokenId,790 possible_owner: &T::CrossAccountId,791 ) -> DispatchResult {792 let token_data =793 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;794 ensure!(795 &token_data.owner == possible_owner,796 <CommonError<T>>::NoPermission797 );798 Ok(())799 }800801 /// Transfer NFT token from one account to another.802 ///803 /// `from` account stops being the owner and `to` account becomes the owner of the token.804 /// If `to` is token than `to` becomes owner of the token and the token become nested.805 /// Unnests token from previous parent if it was nested before.806 /// Removes allowance for the token if there was any.807 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.808 ///809 /// - `nesting_budget`: Limit for token nesting depth810 pub fn transfer(811 collection: &NonfungibleHandle<T>,812 from: &T::CrossAccountId,813 to: &T::CrossAccountId,814 token: TokenId,815 nesting_budget: &dyn Budget,816 ) -> DispatchResultWithPostInfo {817 ensure!(818 collection.limits.transfers_enabled(),819 <CommonError<T>>::TransferNotAllowed820 );821822 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();823 let token_data =824 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;825 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);826827 if collection.permissions.access() == AccessMode::AllowList {828 collection.check_allowlist(from)?;829 collection.check_allowlist(to)?;830 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;831 }832 <PalletCommon<T>>::ensure_correct_receiver(to)?;833834 let balance_from = <AccountBalance<T>>::get((collection.id, from))835 .checked_sub(1)836 .ok_or(<CommonError<T>>::TokenValueTooLow)?;837 let balance_to = if from != to {838 let balance_to = <AccountBalance<T>>::get((collection.id, to))839 .checked_add(1)840 .ok_or(ArithmeticError::Overflow)?;841842 ensure!(843 balance_to < collection.limits.account_token_ownership_limit(),844 <CommonError<T>>::AccountTokenLimitExceeded,845 );846847 Some(balance_to)848 } else {849 None850 };851852 <PalletStructure<T>>::nest_if_sent_to_token(853 from.clone(),854 to,855 collection.id,856 token,857 nesting_budget,858 )?;859860 // =========861862 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);863864 <TokenData<T>>::insert(865 (collection.id, token),866 ItemData {867 owner: to.clone(),868 ..token_data869 },870 );871872 if let Some(balance_to) = balance_to {873 // from != to874 if balance_from == 0 {875 <AccountBalance<T>>::remove((collection.id, from));876 } else {877 <AccountBalance<T>>::insert((collection.id, from), balance_from);878 }879 <AccountBalance<T>>::insert((collection.id, to), balance_to);880 <Owned<T>>::remove((collection.id, from, token));881 <Owned<T>>::insert((collection.id, to, token), true);882 }883 Self::set_allowance_unchecked(collection, from, token, None, true);884885 <PalletEvm<T>>::deposit_log(886 ERC721Events::Transfer {887 from: *from.as_eth(),888 to: *to.as_eth(),889 token_id: token.into(),890 }891 .to_log(collection_id_to_address(collection.id)),892 );893 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(894 collection.id,895 token,896 from.clone(),897 to.clone(),898 1,899 ));900901 Ok(PostDispatchInfo {902 actual_weight: Some(actual_weight),903 pays_fee: Pays::Yes,904 })905 }906907 /// Batch operation to mint multiple NFT tokens.908 ///909 /// The sender should be the owner/admin of the collection or collection should be configured910 /// to allow public minting.911 /// Throws if amount of tokens reached it's limit for the collection or if caller reached912 /// token ownership limit.913 ///914 /// - `data`: Contains list of token properties and users who will become the owners of the915 /// corresponging tokens.916 /// - `nesting_budget`: Limit for token nesting depth917 pub fn create_multiple_items(918 collection: &NonfungibleHandle<T>,919 sender: &T::CrossAccountId,920 data: Vec<CreateItemData<T>>,921 nesting_budget: &dyn Budget,922 ) -> DispatchResult {923 if !collection.is_owner_or_admin(sender) {924 ensure!(925 collection.permissions.mint_mode(),926 <CommonError<T>>::PublicMintingNotAllowed927 );928 collection.check_allowlist(sender)?;929930 for item in data.iter() {931 collection.check_allowlist(&item.owner)?;932 }933 }934935 for data in data.iter() {936 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;937 }938939 let first_token = <TokensMinted<T>>::get(collection.id);940 let tokens_minted = first_token941 .checked_add(data.len() as u32)942 .ok_or(ArithmeticError::Overflow)?;943 ensure!(944 tokens_minted <= collection.limits.token_limit(),945 <CommonError<T>>::CollectionTokenLimitExceeded946 );947948 let mut balances = BTreeMap::new();949 for data in &data {950 let balance = balances951 .entry(&data.owner)952 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));953 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;954955 ensure!(956 *balance <= collection.limits.account_token_ownership_limit(),957 <CommonError<T>>::AccountTokenLimitExceeded,958 );959 }960961 for (i, data) in data.iter().enumerate() {962 let token = TokenId(first_token + i as u32 + 1);963964 <PalletStructure<T>>::check_nesting(965 sender.clone(),966 &data.owner,967 collection.id,968 token,969 nesting_budget,970 )?;971 }972973 // =========974975 with_transaction(|| {976 for (i, data) in data.iter().enumerate() {977 let token = first_token + i as u32 + 1;978979 <TokenData<T>>::insert(980 (collection.id, token),981 ItemData {982 // const_data: data.const_data.clone(),983 owner: data.owner.clone(),984 },985 );986987 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(988 &data.owner,989 collection.id,990 TokenId(token),991 );992993 if let Err(e) = Self::set_token_properties(994 collection,995 sender,996 TokenId(token),997 data.properties.clone().into_iter(),998 true,999 nesting_budget,1000 ) {1001 return TransactionOutcome::Rollback(Err(e));1002 }1003 }1004 TransactionOutcome::Commit(Ok(()))1005 })?;10061007 <TokensMinted<T>>::insert(collection.id, tokens_minted);1008 for (account, balance) in balances {1009 <AccountBalance<T>>::insert((collection.id, account), balance);1010 }1011 for (i, data) in data.into_iter().enumerate() {1012 let token = first_token + i as u32 + 1;1013 <Owned<T>>::insert((collection.id, &data.owner, token), true);10141015 <PalletEvm<T>>::deposit_log(1016 ERC721Events::Transfer {1017 from: H160::default(),1018 to: *data.owner.as_eth(),1019 token_id: token.into(),1020 }1021 .to_log(collection_id_to_address(collection.id)),1022 );1023 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1024 collection.id,1025 TokenId(token),1026 data.owner.clone(),1027 1,1028 ));1029 }1030 Ok(())1031 }10321033 pub fn set_allowance_unchecked(1034 collection: &NonfungibleHandle<T>,1035 sender: &T::CrossAccountId,1036 token: TokenId,1037 spender: Option<&T::CrossAccountId>,1038 assume_implicit_eth: bool,1039 ) {1040 if let Some(spender) = spender {1041 let old_spender = <Allowance<T>>::get((collection.id, token));1042 <Allowance<T>>::insert((collection.id, token), spender);1043 // In ERC721 there is only one possible approved user of token, so we set1044 // approved user to spender1045 <PalletEvm<T>>::deposit_log(1046 ERC721Events::Approval {1047 owner: *sender.as_eth(),1048 approved: *spender.as_eth(),1049 token_id: token.into(),1050 }1051 .to_log(collection_id_to_address(collection.id)),1052 );1053 // In Unique chain, any token can have any amount of approved users, so we need to1054 // set allowance of old owner to 0, and allowance of new owner to 11055 if old_spender.as_ref() != Some(spender) {1056 if let Some(old_owner) = old_spender {1057 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1058 collection.id,1059 token,1060 sender.clone(),1061 old_owner,1062 0,1063 ));1064 }1065 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1066 collection.id,1067 token,1068 sender.clone(),1069 spender.clone(),1070 1,1071 ));1072 }1073 } else {1074 let old_spender = <Allowance<T>>::take((collection.id, token));1075 if !assume_implicit_eth {1076 // In ERC721 there is only one possible approved user of token, so we set1077 // approved user to zero address1078 <PalletEvm<T>>::deposit_log(1079 ERC721Events::Approval {1080 owner: *sender.as_eth(),1081 approved: H160::default(),1082 token_id: token.into(),1083 }1084 .to_log(collection_id_to_address(collection.id)),1085 );1086 }1087 // In Unique chain, any token can have any amount of approved users, so we need to1088 // set allowance of old owner to 01089 if let Some(old_spender) = old_spender {1090 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1091 collection.id,1092 token,1093 sender.clone(),1094 old_spender,1095 0,1096 ));1097 }1098 }1099 }11001101 pub fn get_allowance(1102 collection: &NonfungibleHandle<T>,1103 token_id: TokenId,1104 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1105 ensure!(1106 <TokenData<T>>::get((collection.id, token_id)).is_some(),1107 <CommonError<T>>::TokenNotFound1108 );1109 Ok(<Allowance<T>>::get((collection.id, token_id)))1110 }11111112 /// Set allowance for the spender to `transfer` or `burn` sender's token.1113 ///1114 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1115 pub fn set_allowance(1116 collection: &NonfungibleHandle<T>,1117 sender: &T::CrossAccountId,1118 token: TokenId,1119 spender: Option<&T::CrossAccountId>,1120 ) -> DispatchResult {1121 if collection.permissions.access() == AccessMode::AllowList {1122 collection.check_allowlist(sender)?;1123 if let Some(spender) = spender {1124 collection.check_allowlist(spender)?;1125 }1126 }11271128 if let Some(spender) = spender {1129 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1130 }11311132 let token_data =1133 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1134 if &token_data.owner != sender {1135 ensure!(1136 collection.ignores_owned_amount(sender),1137 <CommonError<T>>::CantApproveMoreThanOwned1138 );1139 }11401141 // =========11421143 Self::set_allowance_unchecked(collection, sender, token, spender, false);1144 Ok(())1145 }11461147 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1148 ///1149 /// - `from`: Address of sender's eth mirror.1150 /// - `to`: Adress of spender.1151 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1152 pub fn set_allowance_from(1153 collection: &NonfungibleHandle<T>,1154 sender: &T::CrossAccountId,1155 from: &T::CrossAccountId,1156 token: TokenId,1157 to: Option<&T::CrossAccountId>,1158 ) -> DispatchResult {1159 if collection.permissions.access() == AccessMode::AllowList {1160 collection.check_allowlist(sender)?;1161 collection.check_allowlist(from)?;1162 if let Some(to) = to {1163 collection.check_allowlist(to)?;1164 }1165 }11661167 if let Some(to) = to {1168 <PalletCommon<T>>::ensure_correct_receiver(to)?;1169 }11701171 ensure!(1172 sender.conv_eq(from),1173 <CommonError<T>>::AddressIsNotEthMirror1174 );11751176 let token_data =1177 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1178 if token_data.owner != *from {1179 ensure!(1180 collection.limits.owner_can_transfer()1181 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1182 <CommonError<T>>::CantApproveMoreThanOwned1183 );1184 }11851186 // =========11871188 Self::set_allowance_unchecked(collection, from, token, to, false);1189 Ok(())1190 }11911192 /// Checks allowance for the spender to use the token.1193 fn check_allowed(1194 collection: &NonfungibleHandle<T>,1195 spender: &T::CrossAccountId,1196 from: &T::CrossAccountId,1197 token: TokenId,1198 nesting_budget: &dyn Budget,1199 ) -> DispatchResult {1200 if spender.conv_eq(from) {1201 return Ok(());1202 }1203 if collection.permissions.access() == AccessMode::AllowList {1204 // `from`, `to` checked in [`transfer`]1205 collection.check_allowlist(spender)?;1206 }12071208 if collection.ignores_token_restrictions(spender) {1209 return Ok(());1210 }12111212 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1213 ensure!(1214 <PalletStructure<T>>::check_indirectly_owned(1215 spender.clone(),1216 source.0,1217 source.1,1218 None,1219 nesting_budget1220 )?,1221 <CommonError<T>>::ApprovedValueTooLow,1222 );1223 return Ok(());1224 }1225 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1226 return Ok(());1227 }1228 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1229 return Ok(());1230 }12311232 Err(<CommonError<T>>::ApprovedValueTooLow.into())1233 }12341235 /// Transfer NFT token from one account to another.1236 ///1237 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1238 /// The owner should set allowance for the spender to transfer token.1239 ///1240 /// [`transfer`]: struct.Pallet.html#method.transfer1241 pub fn transfer_from(1242 collection: &NonfungibleHandle<T>,1243 spender: &T::CrossAccountId,1244 from: &T::CrossAccountId,1245 to: &T::CrossAccountId,1246 token: TokenId,1247 nesting_budget: &dyn Budget,1248 ) -> DispatchResultWithPostInfo {1249 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12501251 // =========12521253 // Allowance is reset in [`transfer`]1254 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1255 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1256 result1257 }12581259 /// Burn NFT token for `from` account.1260 ///1261 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1262 /// set allowance for the spender to burn token.1263 ///1264 /// [`burn`]: struct.Pallet.html#method.burn1265 pub fn burn_from(1266 collection: &NonfungibleHandle<T>,1267 spender: &T::CrossAccountId,1268 from: &T::CrossAccountId,1269 token: TokenId,1270 nesting_budget: &dyn Budget,1271 ) -> DispatchResult {1272 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12731274 // =========12751276 Self::burn(collection, from, token)1277 }12781279 /// Check that `from` token could be nested in `under` token.1280 ///1281 pub fn check_nesting(1282 handle: &NonfungibleHandle<T>,1283 sender: T::CrossAccountId,1284 from: (CollectionId, TokenId),1285 under: TokenId,1286 nesting_budget: &dyn Budget,1287 ) -> DispatchResult {1288 let nesting = handle.permissions.nesting();12891290 #[cfg(not(feature = "runtime-benchmarks"))]1291 let permissive = false;1292 #[cfg(feature = "runtime-benchmarks")]1293 let permissive = nesting.permissive;12941295 if permissive {1296 ensure!(1297 <TokenData<T>>::contains_key((handle.id, under)),1298 <CommonError<T>>::TokenNotFound1299 );1300 } else if nesting.token_owner1301 && <PalletStructure<T>>::check_indirectly_owned(1302 sender.clone(),1303 handle.id,1304 under,1305 Some(from),1306 nesting_budget,1307 )? {1308 // Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1309 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1310 // token existence and ouroboros checks are done in `get_checked_topmost_owner`1311 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1312 handle.id,1313 under,1314 Some(from),1315 nesting_budget,1316 )?1317 .ok_or(<CommonError<T>>::TokenNotFound)?;1318 } else {1319 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1320 }13211322 if let Some(whitelist) = &nesting.restricted {1323 ensure!(1324 whitelist.contains(&from.0),1325 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1326 );1327 }1328 Ok(())1329 }13301331 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1332 if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1333 <TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1334 }1335 }13361337 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1338 if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1339 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1340 }1341 }13421343 fn collection_has_tokens(collection_id: CollectionId) -> bool {1344 <TokenData<T>>::iter_prefix((collection_id,))1345 .next()1346 .is_some()1347 }13481349 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1350 let address = T::CrossTokenAddressMapping::token_to_address(collection_id, token_id);1351 let balance = <pallet_balances::Pallet<T>>::free_balance(address.as_sub());13521353 balance > T::Balance::default()1354 || <TokenChildren<T>>::iter_prefix((collection_id, token_id))1355 .next()1356 .is_some()1357 }13581359 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1360 let mut tokens: Vec<_> = vec![];13611362 let address = T::CrossTokenAddressMapping::token_to_address(collection_id, token_id);1363 let balance = <pallet_balances::Pallet<T>>::free_balance(address.as_sub());1364 if balance > T::Balance::default() {1365 tokens.push(TokenChild {1366 token: TokenId(0),1367 collection: pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID,1368 })1369 }13701371 tokens.extend(1372 <TokenChildren<T>>::iter_prefix((collection_id, token_id)).map(1373 |((child_collection_id, child_id), _)| TokenChild {1374 collection: child_collection_id,1375 token: child_id,1376 },1377 ),1378 );13791380 tokens1381 }13821383 /// Mint single NFT token.1384 ///1385 /// Delegated to [`create_multiple_items`]1386 ///1387 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1388 pub fn create_item(1389 collection: &NonfungibleHandle<T>,1390 sender: &T::CrossAccountId,1391 data: CreateItemData<T>,1392 nesting_budget: &dyn Budget,1393 ) -> DispatchResult {1394 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1395 }13961397 /// Sets or unsets the approval of a given operator.1398 ///1399 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1400 /// - `owner`: Token owner1401 /// - `operator`: Operator1402 /// - `approve`: Should operator status be granted or revoked?1403 pub fn set_allowance_for_all(1404 collection: &NonfungibleHandle<T>,1405 owner: &T::CrossAccountId,1406 operator: &T::CrossAccountId,1407 approve: bool,1408 ) -> DispatchResult {1409 <PalletCommon<T>>::set_allowance_for_all(1410 collection,1411 owner,1412 operator,1413 approve,1414 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1415 ERC721Events::ApprovalForAll {1416 owner: *owner.as_eth(),1417 operator: *operator.as_eth(),1418 approved: approve,1419 }1420 .to_log(collection_id_to_address(collection.id)),1421 )1422 }14231424 /// Tells whether the given `owner` approves the `operator`.1425 pub fn allowance_for_all(1426 collection: &NonfungibleHandle<T>,1427 owner: &T::CrossAccountId,1428 operator: &T::CrossAccountId,1429 ) -> bool {1430 <CollectionAllowance<T>>::get((collection.id, owner, operator))1431 }14321433 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1434 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1435 properties.recompute_consumed_space();1436 });14371438 Ok(())1439 }1440}tests/src/eth/nesting/nest.test.tsdiffbeforeafterboth--- a/tests/src/eth/nesting/nest.test.ts
+++ b/tests/src/eth/nesting/nest.test.ts
@@ -248,7 +248,7 @@
{mode: 'ft' as const},
{mode: 'native ft' as const},
].map(testCase => {
- itEth(`Disallow nest into collection without nesting permission [${testCase.mode}]`, async ({helper}) => {
+ itEth(`Disallow nest into collection without nesting permission [${testCase.mode}] (except for native fungible collection)`, async ({helper}) => {
const owner = await helper.eth.createAccountWithBalance(donor);
const {collectionId: targetCollectionId, contract: targetContract} = await createNestingCollection(helper, owner);
await targetContract.methods.setCollectionNesting(false).send({from: owner});
@@ -259,7 +259,11 @@
const targetTokenId = mintingTargetTokenIdResult.events.Transfer.returnValues.tokenId;
const targetTokenAddress = helper.ethAddress.fromTokenId(targetCollectionId, targetTokenId);
- await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ if (testCase.mode === 'ft') {
+ await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.rejectedWith('UserIsNotAllowedToNest');
+ } else {
+ await expect(ftContract.methods.transfer(targetTokenAddress, 10n).call({from: owner})).to.be.not.rejected;
+ }
});
});
});
tests/src/sub/nesting/nesting.negative.test.tsdiffbeforeafterboth--- a/tests/src/sub/nesting/nesting.negative.test.ts
+++ b/tests/src/sub/nesting/nesting.negative.test.ts
@@ -58,7 +58,7 @@
{mode: 'ft'},
{mode: 'nativeFt'},
].map(testCase => {
- itSub(`Owner cannot nest [${testCase.mode}] if nesting is disabled`, async ({helper}) => {
+ itSub(`Owner cannot nest [${testCase.mode}] if nesting is disabled (except for native fungible collection)`, async ({helper}) => {
// Create default collection, permissions are not set:
const aliceNFTCollection = await helper.nft.mintCollection(alice);
const targetToken = await aliceNFTCollection.mintToken(alice);
@@ -66,15 +66,22 @@
const collectionForNesting = testCase.mode === 'ft' ? await helper.ft.mintCollection(alice) : helper.ft.getCollectionObject(0);
// Alice cannot create immediately nested tokens:
- await expect(testCase.mode === 'ft'
- ? collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())
- : collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+ if (testCase.mode === 'ft') {
+ await expect(collectionForNesting.mint(alice, 100n, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+ } else {
+ await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 100n)).to.be.not.rejected;
+ }
// Alice can't mint and nest tokens:
if (testCase.mode === 'ft') {
await collectionForNesting.mint(alice, 100n);
}
- await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+
+ if (testCase.mode === 'ft') {
+ await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.rejectedWith('common.UserIsNotAllowedToNest');
+ } else {
+ await expect(collectionForNesting.transfer(alice, targetToken.nestingAccount(), 50n)).to.be.not.rejected;
+ }
});
});
@@ -84,7 +91,7 @@
{mode: 'ft' as const},
{mode: 'native ft' as const},
].map(testCase => {
- itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens`, async ({helper}) => {
+ itSub(`Non-owner and non-admin cannot nest ${testCase.mode.toUpperCase()} in someone else's tokens (except for native fungible collection)`, async ({helper}) => {
const targetCollection = await helper.nft.mintCollection(alice, {permissions:
{nesting: {tokenOwner: true, collectionAdmin: true}},
});
@@ -118,7 +125,7 @@
case 'nft':
case 'rft': await expect(nestedTokenBob!.transfer(bob, targetToken.nestingAccount())).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
case 'ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
- case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.rejectedWith('common.UserIsNotAllowedToNest'); break;
+ case 'native ft': await expect((nestedCollectionBob as UniqueFTCollection).transfer(bob, targetToken.nestingAccount(), 100n)).to.be.not.rejected; break;
}
});
});
@@ -143,7 +150,7 @@
});
});
- itSub.ifWithPallets('Cannot nest in non existing token', [Pallets.ReFungible], async ({helper}) => {
+ itSub.ifWithPallets('Cannot nest in non existing token (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {
const collection = await helper.nft.mintCollection(alice);
// To avoid UserIsNotAllowedToNest error
await helper.collection.setPermissions(alice, collection.collectionId, {nesting: {collectionAdmin: true}});
@@ -179,7 +186,7 @@
await expect(nft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
await expect(rft.transfer(alice, testCase.token.nestingAccount())).to.be.rejectedWith(testCase.error);
await expect(ftCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);
- await expect(nativeFtCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.rejectedWith(testCase.error);
+ await expect(nativeFtCollectionForNesting.transfer(alice, testCase.token.nestingAccount(), 50n)).to.be.not.rejected;
}
});
@@ -200,7 +207,7 @@
await expect(nft.transfer(alice, {Ethereum: futureCollectionAddress})).to.be.rejectedWith('CantNestTokenUnderCollection');
});
- itEth.ifWithPallets('Cannot nest in RFT or FT', [Pallets.ReFungible], async ({helper}) => {
+ itEth.ifWithPallets('Cannot nest in RFT or FT (except for native fungible collection)', [Pallets.ReFungible], async ({helper}) => {
// Create default collection, permissions are not set:
const rftCollection = await helper.rft.mintCollection(alice);
const ftCollection = await helper.ft.mintCollection(alice);
@@ -220,15 +227,15 @@
const nestedToken2 = await collectionForNesting.mintToken(alice);
await expect(nestedToken2.nest(alice, rftToken)).to.be.rejectedWith('refungible.RefungibleDisallowsNesting');
await expect(ftCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(ftCollection.collectionId, 0)})).to.be.rejectedWith('fungible.FungibleDisallowsNesting');
- await expect(nativeFtCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.rejectedWith('common.UnsupportedOperation');
+ await expect(nativeFtCollection.transfer(alice, {Ethereum: helper.ethAddress.fromTokenId(nativeFtCollection.collectionId, 0)})).to.be.not.rejected;
});
- itSub('Cannot nest in restricted collection if collection is not in the list', async ({helper}) => {
+ itSub('Cannot nest in restricted collection if collection is not in the list (except native fungible collection)', async ({helper}) => {
const {collectionId: allowedCollectionId} = await helper.nft.mintCollection(alice);
const notAllowedCollectionNFT = await helper.nft.mintCollection(alice);
const notAllowedCollectionRFT = await helper.rft.mintCollection(alice);
const notAllowedCollectionFT = await helper.ft.mintCollection(alice);
- const notAllowedCollectionNativeFT = helper.ft.getCollectionObject(0);
+ const allowedCollectionNativeFT = helper.ft.getCollectionObject(0);
// Collection restricted to allowedCollectionId
const restrictedCollectionA = await helper.nft.mintCollection(alice, {permissions:
@@ -253,8 +260,8 @@
await expect(notAllowedCollectionRFT.mintToken(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenA.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
await expect(notAllowedCollectionFT.mint(alice, 100n, targetTokenB.nestingAccount())).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- await expect(notAllowedCollectionNativeFT.transfer(alice, targetTokenA.nestingAccount(), 100n)).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
- await expect(notAllowedCollectionNativeFT.transfer(alice, targetTokenB.nestingAccount(), 100n)).to.be.rejectedWith(/common\.SourceCollectionIsNotAllowedToNest/);
+ await expect(allowedCollectionNativeFT.transfer(alice, targetTokenA.nestingAccount(), 100n)).to.be.not.rejected;
+ await expect(allowedCollectionNativeFT.transfer(alice, targetTokenB.nestingAccount(), 100n)).to.be.not.rejected;
});
itSub('Cannot create nesting chains greater than 5', async ({helper}) => {