difftreelog
doc: minor style + structure error descriptions refactoring
in: master
2 files changed
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 weights::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission, PropertyKey,105 PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue,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,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::H160;116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Token data, stored independently from other data used to describe it134/// for the convenience of database access. Notably contains the owner account address.135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;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::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 #[pallet::generate_store(pub(super) trait Store)]179 pub struct Pallet<T>(_);180181 /// Total amount of minted tokens in a collection.182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 /// Amount of burnt tokens in a collection.187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 /// Token data, used to partially describe a token.192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 /// Map of key-value pairs, describing the metadata of a token.200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = Properties,205 QueryKind = ValueQuery,206 OnEmpty = up_data_structs::TokenProperties,207 >;208209 /// Custom data of a token that is serialized to bytes, 210 /// primarily reserved for on-chain operations, 211 /// normally obscured from the external users.212 /// 213 /// Auxiliary properties are slightly different from 214 /// usual [`TokenProperties`] due to an unlimited number 215 /// and separately stored and written-to key-value pairs.216 /// 217 /// Currently used to store RMRK data.218 #[pallet::storage]219 #[pallet::getter(fn token_aux_property)]220 pub type TokenAuxProperties<T: Config> = StorageNMap<221 Key = (222 Key<Twox64Concat, CollectionId>,223 Key<Twox64Concat, TokenId>,224 Key<Twox64Concat, PropertyScope>,225 Key<Twox64Concat, PropertyKey>,226 ),227 Value = AuxPropertyValue,228 QueryKind = OptionQuery,229 >;230231 /// Used to enumerate tokens owned by account.232 #[pallet::storage]233 pub type Owned<T: Config> = StorageNMap<234 Key = (235 Key<Twox64Concat, CollectionId>,236 Key<Blake2_128Concat, T::CrossAccountId>,237 Key<Twox64Concat, TokenId>,238 ),239 Value = bool,240 QueryKind = ValueQuery,241 >;242243 /// Used to enumerate token's children.244 #[pallet::storage]245 #[pallet::getter(fn token_children)]246 pub type TokenChildren<T: Config> = StorageNMap<247 Key = (248 Key<Twox64Concat, CollectionId>,249 Key<Twox64Concat, TokenId>,250 Key<Twox64Concat, (CollectionId, TokenId)>,251 ),252 Value = bool,253 QueryKind = ValueQuery,254 >;255256 /// Amount of tokens owned by an account in a collection.257 #[pallet::storage]258 pub type AccountBalance<T: Config> = StorageNMap<259 Key = (260 Key<Twox64Concat, CollectionId>,261 Key<Blake2_128Concat, T::CrossAccountId>,262 ),263 Value = u32,264 QueryKind = ValueQuery,265 >;266267 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.268 #[pallet::storage]269 pub type Allowance<T: Config> = StorageNMap<270 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),271 Value = T::CrossAccountId,272 QueryKind = OptionQuery,273 >;274275 /// Upgrade from the old schema to properties.276 #[pallet::hooks]277 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {278 fn on_runtime_upgrade() -> Weight {279 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {280 let mut had_consts = BTreeSet::new();281 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(282 |(collection, token), v| {283 let mut props = vec![];284 if !v.const_data.is_empty() {285 props.push(Property {286 key: b"_old_constData".to_vec().try_into().unwrap(),287 value: v288 .const_data289 .clone()290 .into_inner()291 .try_into()292 .expect("const too long"),293 });294 had_consts.insert(collection);295 }296 if !v.variable_data.is_empty() {297 props.push(Property {298 key: b"_old_variableData".to_vec().try_into().unwrap(),299 value: v300 .variable_data301 .clone()302 .into_inner()303 .try_into()304 .expect("variable too long"),305 })306 }307 if !props.is_empty() {308 Self::set_scoped_token_properties(309 collection,310 token,311 PropertyScope::None,312 props.into_iter(),313 )314 .expect("existing token data exceeds property storage");315 }316 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))317 },318 );319 for collection in had_consts {320 <PalletCommon<T>>::set_property_permission_unchecked(321 collection,322 PropertyKeyPermission {323 key: b"_old_constData".to_vec().try_into().unwrap(),324 permission: PropertyPermission {325 mutable: false,326 collection_admin: true,327 token_owner: false,328 },329 },330 )331 .expect("failed to configure permission");332 }333 }334335 0336 }337 }338}339340pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);341impl<T: Config> NonfungibleHandle<T> {342 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {343 Self(inner)344 }345 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {346 self.0347 }348 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {349 &mut self.0350 }351}352impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {353 fn recorder(&self) -> &SubstrateRecorder<T> {354 self.0.recorder()355 }356 fn into_recorder(self) -> SubstrateRecorder<T> {357 self.0.into_recorder()358 }359}360impl<T: Config> Deref for NonfungibleHandle<T> {361 type Target = pallet_common::CollectionHandle<T>;362363 fn deref(&self) -> &Self::Target {364 &self.0365 }366}367368impl<T: Config> Pallet<T> {369 /// Get number of NFT tokens in collection.370 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {371 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)372 }373374 /// Check that NFT token exists.375 ///376 /// - `token`: Token ID.377 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {378 <TokenData<T>>::contains_key((collection.id, token))379 }380381 /// Set the token property with the scope.382 ///383 /// - `property`: Contains key-value pair.384 pub fn set_scoped_token_property(385 collection_id: CollectionId,386 token_id: TokenId,387 scope: PropertyScope,388 property: Property,389 ) -> DispatchResult {390 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {391 properties.try_scoped_set(scope, property.key, property.value)392 })393 .map_err(<CommonError<T>>::from)?;394395 Ok(())396 }397398 /// Batch operation to set multiple properties with the same scope.399 pub fn set_scoped_token_properties(400 collection_id: CollectionId,401 token_id: TokenId,402 scope: PropertyScope,403 properties: impl Iterator<Item = Property>,404 ) -> DispatchResult {405 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {406 stored_properties.try_scoped_set_from_iter(scope, properties)407 })408 .map_err(<CommonError<T>>::from)?;409410 Ok(())411 }412413 /// Add or edit auxiliary data for the property.414 ///415 /// - `f`: function that adds or edits auxiliary data.416 pub fn try_mutate_token_aux_property<R, E>(417 collection_id: CollectionId,418 token_id: TokenId,419 scope: PropertyScope,420 key: PropertyKey,421 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,422 ) -> Result<R, E> {423 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)424 }425426 /// Remove auxiliary data for the property.427 pub fn remove_token_aux_property(428 collection_id: CollectionId,429 token_id: TokenId,430 scope: PropertyScope,431 key: PropertyKey,432 ) {433 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));434 }435436 /// Get all auxiliary data in a given scope.437 ///438 /// Returns iterator over Property Key - Data pairs.439 pub fn iterate_token_aux_properties(440 collection_id: CollectionId,441 token_id: TokenId,442 scope: PropertyScope,443 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {444 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))445 }446447 /// Get ID of the last minted token448 pub fn current_token_id(collection_id: CollectionId) -> TokenId {449 TokenId(<TokensMinted<T>>::get(collection_id))450 }451}452453// unchecked calls skips any permission checks454impl<T: Config> Pallet<T> {455 /// Create NFT collection456 ///457 /// `init_collection` will take non-refundable deposit for collection creation.458 ///459 /// - `data`: Contains settings for collection limits and permissions.460 pub fn init_collection(461 owner: T::CrossAccountId,462 data: CreateCollectionData<T::AccountId>,463 is_external: bool,464 ) -> Result<CollectionId, DispatchError> {465 <PalletCommon<T>>::init_collection(owner, data, is_external)466 }467468 /// Destroy NFT collection469 ///470 /// `destroy_collection` will throw error if collection contains any tokens.471 /// Only owner can destroy collection.472 pub fn destroy_collection(473 collection: NonfungibleHandle<T>,474 sender: &T::CrossAccountId,475 ) -> DispatchResult {476 let id = collection.id;477478 if Self::collection_has_tokens(id) {479 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());480 }481482 // =========483484 PalletCommon::destroy_collection(collection.0, sender)?;485486 <TokenData<T>>::remove_prefix((id,), None);487 <TokenChildren<T>>::remove_prefix((id,), None);488 <Owned<T>>::remove_prefix((id,), None);489 <TokensMinted<T>>::remove(id);490 <TokensBurnt<T>>::remove(id);491 <Allowance<T>>::remove_prefix((id,), None);492 <AccountBalance<T>>::remove_prefix((id,), None);493 Ok(())494 }495496 /// Burn NFT token497 ///498 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token499 /// if the token is nested.500 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.501 /// Also removes all corresponding properties and auxiliary properties.502 ///503 /// - `token`: Token that should be burned504 /// - `collection`: Collection that contains the token505 pub fn burn(506 collection: &NonfungibleHandle<T>,507 sender: &T::CrossAccountId,508 token: TokenId,509 ) -> DispatchResult {510 let token_data =511 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;512 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);513514 if collection.permissions.access() == AccessMode::AllowList {515 collection.check_allowlist(sender)?;516 }517518 if Self::token_has_children(collection.id, token) {519 return Err(<Error<T>>::CantBurnNftWithChildren.into());520 }521522 let burnt = <TokensBurnt<T>>::get(collection.id)523 .checked_add(1)524 .ok_or(ArithmeticError::Overflow)?;525526 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))527 .checked_sub(1)528 .ok_or(ArithmeticError::Overflow)?;529530 // =========531532 if balance == 0 {533 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));534 } else {535 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);536 }537538 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);539540 <Owned<T>>::remove((collection.id, &token_data.owner, token));541 <TokensBurnt<T>>::insert(collection.id, burnt);542 <TokenData<T>>::remove((collection.id, token));543 <TokenProperties<T>>::remove((collection.id, token));544 <TokenAuxProperties<T>>::remove_prefix((collection.id, token), None);545 let old_spender = <Allowance<T>>::take((collection.id, token));546547 if let Some(old_spender) = old_spender {548 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(549 collection.id,550 token,551 token_data.owner.clone(),552 old_spender,553 0,554 ));555 }556557 <PalletEvm<T>>::deposit_log(558 ERC721Events::Transfer {559 from: *token_data.owner.as_eth(),560 to: H160::default(),561 token_id: token.into(),562 }563 .to_log(collection_id_to_address(collection.id)),564 );565 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(566 collection.id,567 token,568 token_data.owner,569 1,570 ));571 Ok(())572 }573574 /// Same as [`burn`] but burns all the tokens that are nested in the token first575 ///576 /// - `self_budget`: Limit for searching children in depth.577 /// - `breadth_budget`: Limit of breadth of searching children.578 ///579 /// [`burn`]: struct.Pallet.html#method.burn580 #[transactional]581 pub fn burn_recursively(582 collection: &NonfungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 self_budget: &dyn Budget,586 breadth_budget: &dyn Budget,587 ) -> DispatchResultWithPostInfo {588 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);589590 let current_token_account =591 T::CrossTokenAddressMapping::token_to_address(collection.id, token);592593 let mut weight = 0 as Weight;594595 // This method is transactional, if user in fact doesn't have permissions to remove token -596 // tokens removed here will be restored after rejected transaction597 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {598 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);599 let PostDispatchInfo { actual_weight, .. } =600 <PalletStructure<T>>::burn_item_recursively(601 current_token_account.clone(),602 collection,603 token,604 self_budget,605 breadth_budget,606 )?;607 if let Some(actual_weight) = actual_weight {608 weight = weight.saturating_add(actual_weight);609 }610 }611612 Self::burn(collection, sender, token)?;613 DispatchResultWithPostInfo::Ok(PostDispatchInfo {614 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),615 pays_fee: Pays::Yes,616 })617 }618619 /// Batch operation to add, edit or remove properties for the token620 ///621 /// All affected properties should have mutable permission and sender should have622 /// permission to edit those properties.623 ///624 /// - `nesting_budget`: Limit for searching parents in depth to check ownership.625 /// - `is_token_create`: Indicates that method is called during token initialization.626 /// Allows to bypass ownership check.627 #[transactional]628 fn modify_token_properties(629 collection: &NonfungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,633 is_token_create: bool,634 nesting_budget: &dyn Budget,635 ) -> DispatchResult {636 let mut collection_admin_status = None;637 let mut token_owner_result = None;638639 let mut is_collection_admin =640 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));641642 let mut is_token_owner = || {643 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {644 let is_owned = <PalletStructure<T>>::check_indirectly_owned(645 sender.clone(),646 collection.id,647 token_id,648 None,649 nesting_budget,650 )?;651652 Ok(is_owned)653 })654 };655656 for (key, value) in properties {657 let permission = <PalletCommon<T>>::property_permissions(collection.id)658 .get(&key)659 .cloned()660 .unwrap_or_else(PropertyPermission::none);661662 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))663 .get(&key)664 .is_some();665666 match permission {667 PropertyPermission { mutable: false, .. } if is_property_exists => {668 return Err(<CommonError<T>>::NoPermission.into());669 }670671 PropertyPermission {672 collection_admin,673 token_owner,674 ..675 } => {676 //TODO: investigate threats during public minting.677 if is_token_create && (collection_admin || token_owner) && value.is_some() {678 // Pass679 } else if collection_admin && is_collection_admin() {680 // Pass681 } else if token_owner && is_token_owner()? {682 // Pass683 } else {684 fail!(<CommonError<T>>::NoPermission);685 }686 }687 }688689 match value {690 Some(value) => {691 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {692 properties.try_set(key.clone(), value)693 })694 .map_err(<CommonError<T>>::from)?;695696 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(697 collection.id,698 token_id,699 key,700 ));701 }702 None => {703 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {704 properties.remove(&key)705 })706 .map_err(<CommonError<T>>::from)?;707708 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(709 collection.id,710 token_id,711 key,712 ));713 }714 }715 }716717 Ok(())718 }719720 /// Batch operation to add or edit properties for the token721 ///722 /// Same as [`modify_token_properties`] but doesn't allow to remove properties723 ///724 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties725 pub fn set_token_properties(726 collection: &NonfungibleHandle<T>,727 sender: &T::CrossAccountId,728 token_id: TokenId,729 properties: impl Iterator<Item = Property>,730 is_token_create: bool,731 nesting_budget: &dyn Budget,732 ) -> DispatchResult {733 Self::modify_token_properties(734 collection,735 sender,736 token_id,737 properties.map(|p| (p.key, Some(p.value))),738 is_token_create,739 nesting_budget,740 )741 }742743 /// Add or edit single property for the token744 ///745 /// Calls [`set_token_properties`] internally746 ///747 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties748 pub fn set_token_property(749 collection: &NonfungibleHandle<T>,750 sender: &T::CrossAccountId,751 token_id: TokenId,752 property: Property,753 nesting_budget: &dyn Budget,754 ) -> DispatchResult {755 let is_token_create = false;756757 Self::set_token_properties(758 collection,759 sender,760 token_id,761 [property].into_iter(),762 is_token_create,763 nesting_budget,764 )765 }766767 /// Batch operation to remove properties from the token768 ///769 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties770 ///771 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties772 pub fn delete_token_properties(773 collection: &NonfungibleHandle<T>,774 sender: &T::CrossAccountId,775 token_id: TokenId,776 property_keys: impl Iterator<Item = PropertyKey>,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 let is_token_create = false;780781 Self::modify_token_properties(782 collection,783 sender,784 token_id,785 property_keys.into_iter().map(|key| (key, None)),786 is_token_create,787 nesting_budget,788 )789 }790791 /// Remove single property from the token792 ///793 /// Calls [`delete_token_properties`] internally794 ///795 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties796 pub fn delete_token_property(797 collection: &NonfungibleHandle<T>,798 sender: &T::CrossAccountId,799 token_id: TokenId,800 property_key: PropertyKey,801 nesting_budget: &dyn Budget,802 ) -> DispatchResult {803 Self::delete_token_properties(804 collection,805 sender,806 token_id,807 [property_key].into_iter(),808 nesting_budget,809 )810 }811812 /// Add or edit properties for the collection813 pub fn set_collection_properties(814 collection: &NonfungibleHandle<T>,815 sender: &T::CrossAccountId,816 properties: Vec<Property>,817 ) -> DispatchResult {818 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)819 }820821 /// Remove properties from the collection822 pub fn delete_collection_properties(823 collection: &CollectionHandle<T>,824 sender: &T::CrossAccountId,825 property_keys: Vec<PropertyKey>,826 ) -> DispatchResult {827 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)828 }829830 /// Set property permissions for the token.831 ///832 /// Sender should be the owner or admin of token's collection.833 pub fn set_token_property_permissions(834 collection: &CollectionHandle<T>,835 sender: &T::CrossAccountId,836 property_permissions: Vec<PropertyKeyPermission>,837 ) -> DispatchResult {838 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)839 }840841 /// Set property permissions for the collection.842 ///843 /// Sender should be the owner or admin of the collection.844 pub fn set_property_permission(845 collection: &CollectionHandle<T>,846 sender: &T::CrossAccountId,847 permission: PropertyKeyPermission,848 ) -> DispatchResult {849 <PalletCommon<T>>::set_property_permission(collection, sender, permission)850 }851852 /// Transfer NFT token from one account to another.853 ///854 /// `from` account stops being the owner and `to` account becomes the owner of the token.855 /// If `to` is token than `to` becomes owner of the token and the token become nested.856 /// Unnests token from previous parent if it was nested before.857 /// Removes allowance for the token if there was any.858 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.859 ///860 /// - `nesting_budget`: Limit for token nesting depth861 pub fn transfer(862 collection: &NonfungibleHandle<T>,863 from: &T::CrossAccountId,864 to: &T::CrossAccountId,865 token: TokenId,866 nesting_budget: &dyn Budget,867 ) -> DispatchResult {868 ensure!(869 collection.limits.transfers_enabled(),870 <CommonError<T>>::TransferNotAllowed871 );872873 let token_data =874 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;875 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);876877 if collection.permissions.access() == AccessMode::AllowList {878 collection.check_allowlist(from)?;879 collection.check_allowlist(to)?;880 }881 <PalletCommon<T>>::ensure_correct_receiver(to)?;882883 let balance_from = <AccountBalance<T>>::get((collection.id, from))884 .checked_sub(1)885 .ok_or(<CommonError<T>>::TokenValueTooLow)?;886 let balance_to = if from != to {887 let balance_to = <AccountBalance<T>>::get((collection.id, to))888 .checked_add(1)889 .ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 balance_to < collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895896 Some(balance_to)897 } else {898 None899 };900901 <PalletStructure<T>>::nest_if_sent_to_token(902 from.clone(),903 to,904 collection.id,905 token,906 nesting_budget,907 )?;908909 // =========910911 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);912913 <TokenData<T>>::insert(914 (collection.id, token),915 ItemData {916 owner: to.clone(),917 ..token_data918 },919 );920921 if let Some(balance_to) = balance_to {922 // from != to923 if balance_from == 0 {924 <AccountBalance<T>>::remove((collection.id, from));925 } else {926 <AccountBalance<T>>::insert((collection.id, from), balance_from);927 }928 <AccountBalance<T>>::insert((collection.id, to), balance_to);929 <Owned<T>>::remove((collection.id, from, token));930 <Owned<T>>::insert((collection.id, to, token), true);931 }932 Self::set_allowance_unchecked(collection, from, token, None, true);933934 <PalletEvm<T>>::deposit_log(935 ERC721Events::Transfer {936 from: *from.as_eth(),937 to: *to.as_eth(),938 token_id: token.into(),939 }940 .to_log(collection_id_to_address(collection.id)),941 );942 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(943 collection.id,944 token,945 from.clone(),946 to.clone(),947 1,948 ));949 Ok(())950 }951952 /// Batch operation to mint multiple NFT tokens.953 ///954 /// The sender should be the owner/admin of the collection or collection should be configured955 /// to allow public minting.956 /// Throws if amount of tokens reached it's limit for the collection or if caller reached957 /// token ownership limit.958 ///959 /// - `data`: Contains list of token properties and users who will become the owners of the960 /// corresponging tokens.961 /// - `nesting_budget`: Limit for token nesting depth962 pub fn create_multiple_items(963 collection: &NonfungibleHandle<T>,964 sender: &T::CrossAccountId,965 data: Vec<CreateItemData<T>>,966 nesting_budget: &dyn Budget,967 ) -> DispatchResult {968 if !collection.is_owner_or_admin(sender) {969 ensure!(970 collection.permissions.mint_mode(),971 <CommonError<T>>::PublicMintingNotAllowed972 );973 collection.check_allowlist(sender)?;974975 for item in data.iter() {976 collection.check_allowlist(&item.owner)?;977 }978 }979980 for data in data.iter() {981 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;982 }983984 let first_token = <TokensMinted<T>>::get(collection.id);985 let tokens_minted = first_token986 .checked_add(data.len() as u32)987 .ok_or(ArithmeticError::Overflow)?;988 ensure!(989 tokens_minted <= collection.limits.token_limit(),990 <CommonError<T>>::CollectionTokenLimitExceeded991 );992993 let mut balances = BTreeMap::new();994 for data in &data {995 let balance = balances996 .entry(&data.owner)997 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));998 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;9991000 ensure!(1001 *balance <= collection.limits.account_token_ownership_limit(),1002 <CommonError<T>>::AccountTokenLimitExceeded,1003 );1004 }10051006 for (i, data) in data.iter().enumerate() {1007 let token = TokenId(first_token + i as u32 + 1);10081009 <PalletStructure<T>>::check_nesting(1010 sender.clone(),1011 &data.owner,1012 collection.id,1013 token,1014 nesting_budget,1015 )?;1016 }10171018 // =========10191020 with_transaction(|| {1021 for (i, data) in data.iter().enumerate() {1022 let token = first_token + i as u32 + 1;10231024 <TokenData<T>>::insert(1025 (collection.id, token),1026 ItemData {1027 // const_data: data.const_data.clone(),1028 owner: data.owner.clone(),1029 },1030 );10311032 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1033 &data.owner,1034 collection.id,1035 TokenId(token),1036 );10371038 if let Err(e) = Self::set_token_properties(1039 collection,1040 sender,1041 TokenId(token),1042 data.properties.clone().into_iter(),1043 true,1044 nesting_budget,1045 ) {1046 return TransactionOutcome::Rollback(Err(e));1047 }1048 }1049 TransactionOutcome::Commit(Ok(()))1050 })?;10511052 <TokensMinted<T>>::insert(collection.id, tokens_minted);1053 for (account, balance) in balances {1054 <AccountBalance<T>>::insert((collection.id, account), balance);1055 }1056 for (i, data) in data.into_iter().enumerate() {1057 let token = first_token + i as u32 + 1;1058 <Owned<T>>::insert((collection.id, &data.owner, token), true);10591060 <PalletEvm<T>>::deposit_log(1061 ERC721Events::Transfer {1062 from: H160::default(),1063 to: *data.owner.as_eth(),1064 token_id: token.into(),1065 }1066 .to_log(collection_id_to_address(collection.id)),1067 );1068 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1069 collection.id,1070 TokenId(token),1071 data.owner.clone(),1072 1,1073 ));1074 }1075 Ok(())1076 }10771078 pub fn set_allowance_unchecked(1079 collection: &NonfungibleHandle<T>,1080 sender: &T::CrossAccountId,1081 token: TokenId,1082 spender: Option<&T::CrossAccountId>,1083 assume_implicit_eth: bool,1084 ) {1085 if let Some(spender) = spender {1086 let old_spender = <Allowance<T>>::get((collection.id, token));1087 <Allowance<T>>::insert((collection.id, token), spender);1088 // In ERC721 there is only one possible approved user of token, so we set1089 // approved user to spender1090 <PalletEvm<T>>::deposit_log(1091 ERC721Events::Approval {1092 owner: *sender.as_eth(),1093 approved: *spender.as_eth(),1094 token_id: token.into(),1095 }1096 .to_log(collection_id_to_address(collection.id)),1097 );1098 // In Unique chain, any token can have any amount of approved users, so we need to1099 // set allowance of old owner to 0, and allowance of new owner to 11100 if old_spender.as_ref() != Some(spender) {1101 if let Some(old_owner) = old_spender {1102 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1103 collection.id,1104 token,1105 sender.clone(),1106 old_owner,1107 0,1108 ));1109 }1110 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1111 collection.id,1112 token,1113 sender.clone(),1114 spender.clone(),1115 1,1116 ));1117 }1118 } else {1119 let old_spender = <Allowance<T>>::take((collection.id, token));1120 if !assume_implicit_eth {1121 // In ERC721 there is only one possible approved user of token, so we set1122 // approved user to zero address1123 <PalletEvm<T>>::deposit_log(1124 ERC721Events::Approval {1125 owner: *sender.as_eth(),1126 approved: H160::default(),1127 token_id: token.into(),1128 }1129 .to_log(collection_id_to_address(collection.id)),1130 );1131 }1132 // In Unique chain, any token can have any amount of approved users, so we need to1133 // set allowance of old owner to 01134 if let Some(old_spender) = old_spender {1135 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1136 collection.id,1137 token,1138 sender.clone(),1139 old_spender,1140 0,1141 ));1142 }1143 }1144 }11451146 /// Set allowance for the spender to `transfer` or `burn` sender's token.1147 ///1148 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1149 pub fn set_allowance(1150 collection: &NonfungibleHandle<T>,1151 sender: &T::CrossAccountId,1152 token: TokenId,1153 spender: Option<&T::CrossAccountId>,1154 ) -> DispatchResult {1155 if collection.permissions.access() == AccessMode::AllowList {1156 collection.check_allowlist(sender)?;1157 if let Some(spender) = spender {1158 collection.check_allowlist(spender)?;1159 }1160 }11611162 if let Some(spender) = spender {1163 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1164 }11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if &token_data.owner != sender {1169 ensure!(1170 collection.ignores_owned_amount(sender),1171 <CommonError<T>>::CantApproveMoreThanOwned1172 );1173 }11741175 // =========11761177 Self::set_allowance_unchecked(collection, sender, token, spender, false);1178 Ok(())1179 }11801181 /// Checks allowance for the spender to use the token.1182 fn check_allowed(1183 collection: &NonfungibleHandle<T>,1184 spender: &T::CrossAccountId,1185 from: &T::CrossAccountId,1186 token: TokenId,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 if spender.conv_eq(from) {1190 return Ok(());1191 }1192 if collection.permissions.access() == AccessMode::AllowList {1193 // `from`, `to` checked in [`transfer`]1194 collection.check_allowlist(spender)?;1195 }11961197 if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {1198 return Ok(());1199 }12001201 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1202 ensure!(1203 <PalletStructure<T>>::check_indirectly_owned(1204 spender.clone(),1205 source.0,1206 source.1,1207 None,1208 nesting_budget1209 )?,1210 <CommonError<T>>::ApprovedValueTooLow,1211 );1212 return Ok(());1213 }1214 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1215 return Ok(());1216 }1217 ensure!(1218 collection.ignores_allowance(spender),1219 <CommonError<T>>::ApprovedValueTooLow1220 );1221 Ok(())1222 }12231224 /// Transfer NFT token from one account to another.1225 ///1226 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1227 /// The owner should set allowance for the spender to transfer token.1228 ///1229 /// [`transfer`]: struct.Pallet.html#method.transfer1230 pub fn transfer_from(1231 collection: &NonfungibleHandle<T>,1232 spender: &T::CrossAccountId,1233 from: &T::CrossAccountId,1234 to: &T::CrossAccountId,1235 token: TokenId,1236 nesting_budget: &dyn Budget,1237 ) -> DispatchResult {1238 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12391240 // =========12411242 // Allowance is reset in [`transfer`]1243 Self::transfer(collection, from, to, token, nesting_budget)1244 }12451246 /// Burn NFT token for `from` account.1247 ///1248 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1249 /// set allowance for the spender to burn token.1250 ///1251 /// [`burn`]: struct.Pallet.html#method.burn1252 pub fn burn_from(1253 collection: &NonfungibleHandle<T>,1254 spender: &T::CrossAccountId,1255 from: &T::CrossAccountId,1256 token: TokenId,1257 nesting_budget: &dyn Budget,1258 ) -> DispatchResult {1259 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12601261 // =========12621263 Self::burn(collection, from, token)1264 }12651266 /// Check that `from` token could be nested in `under` token.1267 ///1268 pub fn check_nesting(1269 handle: &NonfungibleHandle<T>,1270 sender: T::CrossAccountId,1271 from: (CollectionId, TokenId),1272 under: TokenId,1273 nesting_budget: &dyn Budget,1274 ) -> DispatchResult {1275 let nesting = handle.permissions.nesting();12761277 #[cfg(not(feature = "runtime-benchmarks"))]1278 let permissive = false;1279 #[cfg(feature = "runtime-benchmarks")]1280 let permissive = nesting.permissive;12811282 if permissive {1283 // Pass1284 } else if nesting.token_owner1285 && <PalletStructure<T>>::check_indirectly_owned(1286 sender.clone(),1287 handle.id,1288 under,1289 Some(from),1290 nesting_budget,1291 )? {1292 // Pass1293 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1294 // Pass1295 } else {1296 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1297 }12981299 if let Some(whitelist) = &nesting.restricted {1300 ensure!(1301 whitelist.contains(&from.0),1302 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1303 );1304 }1305 Ok(())1306 }13071308 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1309 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1310 }13111312 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1313 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1314 }13151316 fn collection_has_tokens(collection_id: CollectionId) -> bool {1317 <TokenData<T>>::iter_prefix((collection_id,))1318 .next()1319 .is_some()1320 }13211322 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1323 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1324 .next()1325 .is_some()1326 }13271328 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1329 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1330 .map(|((child_collection_id, child_id), _)| TokenChild {1331 collection: child_collection_id,1332 token: child_id,1333 })1334 .collect()1335 }13361337 /// Mint single NFT token.1338 ///1339 /// Delegated to [`create_multiple_items`]1340 ///1341 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1342 pub fn create_item(1343 collection: &NonfungibleHandle<T>,1344 sender: &T::CrossAccountId,1345 data: CreateItemData<T>,1346 nesting_budget: &dyn Budget,1347 ) -> DispatchResult {1348 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1349 }1350}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//! # 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 weights::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyPermission, PropertyKey,105 PropertyValue, PropertyKeyPermission, Properties, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue,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,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::H160;116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap, collections::btree_set::BTreeSet};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::account::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Token data, stored independently from other data used to describe it134/// for the convenience of database access. Notably contains the owner account address.135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;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::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 #[pallet::generate_store(pub(super) trait Store)]179 pub struct Pallet<T>(_);180181 /// Total amount of minted tokens in a collection.182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 /// Amount of burnt tokens in a collection.187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 /// Token data, used to partially describe a token.192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 /// Map of key-value pairs, describing the metadata of a token.200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = Properties,205 QueryKind = ValueQuery,206 OnEmpty = up_data_structs::TokenProperties,207 >;208209 /// Custom data of a token that is serialized to bytes,210 /// primarily reserved for on-chain operations,211 /// normally obscured from the external users.212 ///213 /// Auxiliary properties are slightly different from214 /// usual [`TokenProperties`] due to an unlimited number215 /// and separately stored and written-to key-value pairs.216 ///217 /// Currently used to store RMRK data.218 #[pallet::storage]219 #[pallet::getter(fn token_aux_property)]220 pub type TokenAuxProperties<T: Config> = StorageNMap<221 Key = (222 Key<Twox64Concat, CollectionId>,223 Key<Twox64Concat, TokenId>,224 Key<Twox64Concat, PropertyScope>,225 Key<Twox64Concat, PropertyKey>,226 ),227 Value = AuxPropertyValue,228 QueryKind = OptionQuery,229 >;230231 /// Used to enumerate tokens owned by account.232 #[pallet::storage]233 pub type Owned<T: Config> = StorageNMap<234 Key = (235 Key<Twox64Concat, CollectionId>,236 Key<Blake2_128Concat, T::CrossAccountId>,237 Key<Twox64Concat, TokenId>,238 ),239 Value = bool,240 QueryKind = ValueQuery,241 >;242243 /// Used to enumerate token's children.244 #[pallet::storage]245 #[pallet::getter(fn token_children)]246 pub type TokenChildren<T: Config> = StorageNMap<247 Key = (248 Key<Twox64Concat, CollectionId>,249 Key<Twox64Concat, TokenId>,250 Key<Twox64Concat, (CollectionId, TokenId)>,251 ),252 Value = bool,253 QueryKind = ValueQuery,254 >;255256 /// Amount of tokens owned by an account in a collection.257 #[pallet::storage]258 pub type AccountBalance<T: Config> = StorageNMap<259 Key = (260 Key<Twox64Concat, CollectionId>,261 Key<Blake2_128Concat, T::CrossAccountId>,262 ),263 Value = u32,264 QueryKind = ValueQuery,265 >;266267 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.268 #[pallet::storage]269 pub type Allowance<T: Config> = StorageNMap<270 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),271 Value = T::CrossAccountId,272 QueryKind = OptionQuery,273 >;274275 /// Upgrade from the old schema to properties.276 #[pallet::hooks]277 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {278 fn on_runtime_upgrade() -> Weight {279 if StorageVersion::get::<Pallet<T>>() < StorageVersion::new(1) {280 let mut had_consts = BTreeSet::new();281 <TokenData<T>>::translate::<ItemDataVersion1<T::CrossAccountId>, _>(282 |(collection, token), v| {283 let mut props = vec![];284 if !v.const_data.is_empty() {285 props.push(Property {286 key: b"_old_constData".to_vec().try_into().unwrap(),287 value: v288 .const_data289 .clone()290 .into_inner()291 .try_into()292 .expect("const too long"),293 });294 had_consts.insert(collection);295 }296 if !v.variable_data.is_empty() {297 props.push(Property {298 key: b"_old_variableData".to_vec().try_into().unwrap(),299 value: v300 .variable_data301 .clone()302 .into_inner()303 .try_into()304 .expect("variable too long"),305 })306 }307 if !props.is_empty() {308 Self::set_scoped_token_properties(309 collection,310 token,311 PropertyScope::None,312 props.into_iter(),313 )314 .expect("existing token data exceeds property storage");315 }316 Some(<ItemDataVersion2<T::CrossAccountId>>::from(v))317 },318 );319 for collection in had_consts {320 <PalletCommon<T>>::set_property_permission_unchecked(321 collection,322 PropertyKeyPermission {323 key: b"_old_constData".to_vec().try_into().unwrap(),324 permission: PropertyPermission {325 mutable: false,326 collection_admin: true,327 token_owner: false,328 },329 },330 )331 .expect("failed to configure permission");332 }333 }334335 0336 }337 }338}339340pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);341impl<T: Config> NonfungibleHandle<T> {342 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {343 Self(inner)344 }345 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {346 self.0347 }348 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {349 &mut self.0350 }351}352impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {353 fn recorder(&self) -> &SubstrateRecorder<T> {354 self.0.recorder()355 }356 fn into_recorder(self) -> SubstrateRecorder<T> {357 self.0.into_recorder()358 }359}360impl<T: Config> Deref for NonfungibleHandle<T> {361 type Target = pallet_common::CollectionHandle<T>;362363 fn deref(&self) -> &Self::Target {364 &self.0365 }366}367368impl<T: Config> Pallet<T> {369 /// Get number of NFT tokens in collection.370 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {371 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)372 }373374 /// Check that NFT token exists.375 ///376 /// - `token`: Token ID.377 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {378 <TokenData<T>>::contains_key((collection.id, token))379 }380381 /// Set the token property with the scope.382 ///383 /// - `property`: Contains key-value pair.384 pub fn set_scoped_token_property(385 collection_id: CollectionId,386 token_id: TokenId,387 scope: PropertyScope,388 property: Property,389 ) -> DispatchResult {390 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {391 properties.try_scoped_set(scope, property.key, property.value)392 })393 .map_err(<CommonError<T>>::from)?;394395 Ok(())396 }397398 /// Batch operation to set multiple properties with the same scope.399 pub fn set_scoped_token_properties(400 collection_id: CollectionId,401 token_id: TokenId,402 scope: PropertyScope,403 properties: impl Iterator<Item = Property>,404 ) -> DispatchResult {405 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {406 stored_properties.try_scoped_set_from_iter(scope, properties)407 })408 .map_err(<CommonError<T>>::from)?;409410 Ok(())411 }412413 /// Add or edit auxiliary data for the property.414 ///415 /// - `f`: function that adds or edits auxiliary data.416 pub fn try_mutate_token_aux_property<R, E>(417 collection_id: CollectionId,418 token_id: TokenId,419 scope: PropertyScope,420 key: PropertyKey,421 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,422 ) -> Result<R, E> {423 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)424 }425426 /// Remove auxiliary data for the property.427 pub fn remove_token_aux_property(428 collection_id: CollectionId,429 token_id: TokenId,430 scope: PropertyScope,431 key: PropertyKey,432 ) {433 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));434 }435436 /// Get all auxiliary data in a given scope.437 ///438 /// Returns iterator over Property Key - Data pairs.439 pub fn iterate_token_aux_properties(440 collection_id: CollectionId,441 token_id: TokenId,442 scope: PropertyScope,443 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {444 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))445 }446447 /// Get ID of the last minted token448 pub fn current_token_id(collection_id: CollectionId) -> TokenId {449 TokenId(<TokensMinted<T>>::get(collection_id))450 }451}452453// unchecked calls skips any permission checks454impl<T: Config> Pallet<T> {455 /// Create NFT collection456 ///457 /// `init_collection` will take non-refundable deposit for collection creation.458 ///459 /// - `data`: Contains settings for collection limits and permissions.460 pub fn init_collection(461 owner: T::CrossAccountId,462 data: CreateCollectionData<T::AccountId>,463 is_external: bool,464 ) -> Result<CollectionId, DispatchError> {465 <PalletCommon<T>>::init_collection(owner, data, is_external)466 }467468 /// Destroy NFT collection469 ///470 /// `destroy_collection` will throw error if collection contains any tokens.471 /// Only owner can destroy collection.472 pub fn destroy_collection(473 collection: NonfungibleHandle<T>,474 sender: &T::CrossAccountId,475 ) -> DispatchResult {476 let id = collection.id;477478 if Self::collection_has_tokens(id) {479 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());480 }481482 // =========483484 PalletCommon::destroy_collection(collection.0, sender)?;485486 <TokenData<T>>::remove_prefix((id,), None);487 <TokenChildren<T>>::remove_prefix((id,), None);488 <Owned<T>>::remove_prefix((id,), None);489 <TokensMinted<T>>::remove(id);490 <TokensBurnt<T>>::remove(id);491 <Allowance<T>>::remove_prefix((id,), None);492 <AccountBalance<T>>::remove_prefix((id,), None);493 Ok(())494 }495496 /// Burn NFT token497 ///498 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token499 /// if the token is nested.500 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.501 /// Also removes all corresponding properties and auxiliary properties.502 ///503 /// - `token`: Token that should be burned504 /// - `collection`: Collection that contains the token505 pub fn burn(506 collection: &NonfungibleHandle<T>,507 sender: &T::CrossAccountId,508 token: TokenId,509 ) -> DispatchResult {510 let token_data =511 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;512 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);513514 if collection.permissions.access() == AccessMode::AllowList {515 collection.check_allowlist(sender)?;516 }517518 if Self::token_has_children(collection.id, token) {519 return Err(<Error<T>>::CantBurnNftWithChildren.into());520 }521522 let burnt = <TokensBurnt<T>>::get(collection.id)523 .checked_add(1)524 .ok_or(ArithmeticError::Overflow)?;525526 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))527 .checked_sub(1)528 .ok_or(ArithmeticError::Overflow)?;529530 // =========531532 if balance == 0 {533 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));534 } else {535 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);536 }537538 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);539540 <Owned<T>>::remove((collection.id, &token_data.owner, token));541 <TokensBurnt<T>>::insert(collection.id, burnt);542 <TokenData<T>>::remove((collection.id, token));543 <TokenProperties<T>>::remove((collection.id, token));544 <TokenAuxProperties<T>>::remove_prefix((collection.id, token), None);545 let old_spender = <Allowance<T>>::take((collection.id, token));546547 if let Some(old_spender) = old_spender {548 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(549 collection.id,550 token,551 token_data.owner.clone(),552 old_spender,553 0,554 ));555 }556557 <PalletEvm<T>>::deposit_log(558 ERC721Events::Transfer {559 from: *token_data.owner.as_eth(),560 to: H160::default(),561 token_id: token.into(),562 }563 .to_log(collection_id_to_address(collection.id)),564 );565 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(566 collection.id,567 token,568 token_data.owner,569 1,570 ));571 Ok(())572 }573574 /// Same as [`burn`] but burns all the tokens that are nested in the token first575 ///576 /// - `self_budget`: Limit for searching children in depth.577 /// - `breadth_budget`: Limit of breadth of searching children.578 ///579 /// [`burn`]: struct.Pallet.html#method.burn580 #[transactional]581 pub fn burn_recursively(582 collection: &NonfungibleHandle<T>,583 sender: &T::CrossAccountId,584 token: TokenId,585 self_budget: &dyn Budget,586 breadth_budget: &dyn Budget,587 ) -> DispatchResultWithPostInfo {588 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);589590 let current_token_account =591 T::CrossTokenAddressMapping::token_to_address(collection.id, token);592593 let mut weight = 0 as Weight;594595 // This method is transactional, if user in fact doesn't have permissions to remove token -596 // tokens removed here will be restored after rejected transaction597 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {598 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);599 let PostDispatchInfo { actual_weight, .. } =600 <PalletStructure<T>>::burn_item_recursively(601 current_token_account.clone(),602 collection,603 token,604 self_budget,605 breadth_budget,606 )?;607 if let Some(actual_weight) = actual_weight {608 weight = weight.saturating_add(actual_weight);609 }610 }611612 Self::burn(collection, sender, token)?;613 DispatchResultWithPostInfo::Ok(PostDispatchInfo {614 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),615 pays_fee: Pays::Yes,616 })617 }618619 /// Batch operation to add, edit or remove properties for the token620 ///621 /// All affected properties should have mutable permission and sender should have622 /// permission to edit those properties.623 ///624 /// - `nesting_budget`: Limit for searching parents in depth to check ownership.625 /// - `is_token_create`: Indicates that method is called during token initialization.626 /// Allows to bypass ownership check.627 #[transactional]628 fn modify_token_properties(629 collection: &NonfungibleHandle<T>,630 sender: &T::CrossAccountId,631 token_id: TokenId,632 properties: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,633 is_token_create: bool,634 nesting_budget: &dyn Budget,635 ) -> DispatchResult {636 let mut collection_admin_status = None;637 let mut token_owner_result = None;638639 let mut is_collection_admin =640 || *collection_admin_status.get_or_insert_with(|| collection.is_owner_or_admin(sender));641642 let mut is_token_owner = || {643 *token_owner_result.get_or_insert_with(|| -> Result<bool, DispatchError> {644 let is_owned = <PalletStructure<T>>::check_indirectly_owned(645 sender.clone(),646 collection.id,647 token_id,648 None,649 nesting_budget,650 )?;651652 Ok(is_owned)653 })654 };655656 for (key, value) in properties {657 let permission = <PalletCommon<T>>::property_permissions(collection.id)658 .get(&key)659 .cloned()660 .unwrap_or_else(PropertyPermission::none);661662 let is_property_exists = TokenProperties::<T>::get((collection.id, token_id))663 .get(&key)664 .is_some();665666 match permission {667 PropertyPermission { mutable: false, .. } if is_property_exists => {668 return Err(<CommonError<T>>::NoPermission.into());669 }670671 PropertyPermission {672 collection_admin,673 token_owner,674 ..675 } => {676 //TODO: investigate threats during public minting.677 if is_token_create && (collection_admin || token_owner) && value.is_some() {678 // Pass679 } else if collection_admin && is_collection_admin() {680 // Pass681 } else if token_owner && is_token_owner()? {682 // Pass683 } else {684 fail!(<CommonError<T>>::NoPermission);685 }686 }687 }688689 match value {690 Some(value) => {691 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {692 properties.try_set(key.clone(), value)693 })694 .map_err(<CommonError<T>>::from)?;695696 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertySet(697 collection.id,698 token_id,699 key,700 ));701 }702 None => {703 <TokenProperties<T>>::try_mutate((collection.id, token_id), |properties| {704 properties.remove(&key)705 })706 .map_err(<CommonError<T>>::from)?;707708 <PalletCommon<T>>::deposit_event(CommonEvent::TokenPropertyDeleted(709 collection.id,710 token_id,711 key,712 ));713 }714 }715 }716717 Ok(())718 }719720 /// Batch operation to add or edit properties for the token721 ///722 /// Same as [`modify_token_properties`] but doesn't allow to remove properties723 ///724 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties725 pub fn set_token_properties(726 collection: &NonfungibleHandle<T>,727 sender: &T::CrossAccountId,728 token_id: TokenId,729 properties: impl Iterator<Item = Property>,730 is_token_create: bool,731 nesting_budget: &dyn Budget,732 ) -> DispatchResult {733 Self::modify_token_properties(734 collection,735 sender,736 token_id,737 properties.map(|p| (p.key, Some(p.value))),738 is_token_create,739 nesting_budget,740 )741 }742743 /// Add or edit single property for the token744 ///745 /// Calls [`set_token_properties`] internally746 ///747 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties748 pub fn set_token_property(749 collection: &NonfungibleHandle<T>,750 sender: &T::CrossAccountId,751 token_id: TokenId,752 property: Property,753 nesting_budget: &dyn Budget,754 ) -> DispatchResult {755 let is_token_create = false;756757 Self::set_token_properties(758 collection,759 sender,760 token_id,761 [property].into_iter(),762 is_token_create,763 nesting_budget,764 )765 }766767 /// Batch operation to remove properties from the token768 ///769 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties770 ///771 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties772 pub fn delete_token_properties(773 collection: &NonfungibleHandle<T>,774 sender: &T::CrossAccountId,775 token_id: TokenId,776 property_keys: impl Iterator<Item = PropertyKey>,777 nesting_budget: &dyn Budget,778 ) -> DispatchResult {779 let is_token_create = false;780781 Self::modify_token_properties(782 collection,783 sender,784 token_id,785 property_keys.into_iter().map(|key| (key, None)),786 is_token_create,787 nesting_budget,788 )789 }790791 /// Remove single property from the token792 ///793 /// Calls [`delete_token_properties`] internally794 ///795 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties796 pub fn delete_token_property(797 collection: &NonfungibleHandle<T>,798 sender: &T::CrossAccountId,799 token_id: TokenId,800 property_key: PropertyKey,801 nesting_budget: &dyn Budget,802 ) -> DispatchResult {803 Self::delete_token_properties(804 collection,805 sender,806 token_id,807 [property_key].into_iter(),808 nesting_budget,809 )810 }811812 /// Add or edit properties for the collection813 pub fn set_collection_properties(814 collection: &NonfungibleHandle<T>,815 sender: &T::CrossAccountId,816 properties: Vec<Property>,817 ) -> DispatchResult {818 <PalletCommon<T>>::set_collection_properties(collection, sender, properties)819 }820821 /// Remove properties from the collection822 pub fn delete_collection_properties(823 collection: &CollectionHandle<T>,824 sender: &T::CrossAccountId,825 property_keys: Vec<PropertyKey>,826 ) -> DispatchResult {827 <PalletCommon<T>>::delete_collection_properties(collection, sender, property_keys)828 }829830 /// Set property permissions for the token.831 ///832 /// Sender should be the owner or admin of token's collection.833 pub fn set_token_property_permissions(834 collection: &CollectionHandle<T>,835 sender: &T::CrossAccountId,836 property_permissions: Vec<PropertyKeyPermission>,837 ) -> DispatchResult {838 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)839 }840841 /// Set property permissions for the collection.842 ///843 /// Sender should be the owner or admin of the collection.844 pub fn set_property_permission(845 collection: &CollectionHandle<T>,846 sender: &T::CrossAccountId,847 permission: PropertyKeyPermission,848 ) -> DispatchResult {849 <PalletCommon<T>>::set_property_permission(collection, sender, permission)850 }851852 /// Transfer NFT token from one account to another.853 ///854 /// `from` account stops being the owner and `to` account becomes the owner of the token.855 /// If `to` is token than `to` becomes owner of the token and the token become nested.856 /// Unnests token from previous parent if it was nested before.857 /// Removes allowance for the token if there was any.858 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.859 ///860 /// - `nesting_budget`: Limit for token nesting depth861 pub fn transfer(862 collection: &NonfungibleHandle<T>,863 from: &T::CrossAccountId,864 to: &T::CrossAccountId,865 token: TokenId,866 nesting_budget: &dyn Budget,867 ) -> DispatchResult {868 ensure!(869 collection.limits.transfers_enabled(),870 <CommonError<T>>::TransferNotAllowed871 );872873 let token_data =874 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;875 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);876877 if collection.permissions.access() == AccessMode::AllowList {878 collection.check_allowlist(from)?;879 collection.check_allowlist(to)?;880 }881 <PalletCommon<T>>::ensure_correct_receiver(to)?;882883 let balance_from = <AccountBalance<T>>::get((collection.id, from))884 .checked_sub(1)885 .ok_or(<CommonError<T>>::TokenValueTooLow)?;886 let balance_to = if from != to {887 let balance_to = <AccountBalance<T>>::get((collection.id, to))888 .checked_add(1)889 .ok_or(ArithmeticError::Overflow)?;890891 ensure!(892 balance_to < collection.limits.account_token_ownership_limit(),893 <CommonError<T>>::AccountTokenLimitExceeded,894 );895896 Some(balance_to)897 } else {898 None899 };900901 <PalletStructure<T>>::nest_if_sent_to_token(902 from.clone(),903 to,904 collection.id,905 token,906 nesting_budget,907 )?;908909 // =========910911 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);912913 <TokenData<T>>::insert(914 (collection.id, token),915 ItemData {916 owner: to.clone(),917 ..token_data918 },919 );920921 if let Some(balance_to) = balance_to {922 // from != to923 if balance_from == 0 {924 <AccountBalance<T>>::remove((collection.id, from));925 } else {926 <AccountBalance<T>>::insert((collection.id, from), balance_from);927 }928 <AccountBalance<T>>::insert((collection.id, to), balance_to);929 <Owned<T>>::remove((collection.id, from, token));930 <Owned<T>>::insert((collection.id, to, token), true);931 }932 Self::set_allowance_unchecked(collection, from, token, None, true);933934 <PalletEvm<T>>::deposit_log(935 ERC721Events::Transfer {936 from: *from.as_eth(),937 to: *to.as_eth(),938 token_id: token.into(),939 }940 .to_log(collection_id_to_address(collection.id)),941 );942 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(943 collection.id,944 token,945 from.clone(),946 to.clone(),947 1,948 ));949 Ok(())950 }951952 /// Batch operation to mint multiple NFT tokens.953 ///954 /// The sender should be the owner/admin of the collection or collection should be configured955 /// to allow public minting.956 /// Throws if amount of tokens reached it's limit for the collection or if caller reached957 /// token ownership limit.958 ///959 /// - `data`: Contains list of token properties and users who will become the owners of the960 /// corresponging tokens.961 /// - `nesting_budget`: Limit for token nesting depth962 pub fn create_multiple_items(963 collection: &NonfungibleHandle<T>,964 sender: &T::CrossAccountId,965 data: Vec<CreateItemData<T>>,966 nesting_budget: &dyn Budget,967 ) -> DispatchResult {968 if !collection.is_owner_or_admin(sender) {969 ensure!(970 collection.permissions.mint_mode(),971 <CommonError<T>>::PublicMintingNotAllowed972 );973 collection.check_allowlist(sender)?;974975 for item in data.iter() {976 collection.check_allowlist(&item.owner)?;977 }978 }979980 for data in data.iter() {981 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;982 }983984 let first_token = <TokensMinted<T>>::get(collection.id);985 let tokens_minted = first_token986 .checked_add(data.len() as u32)987 .ok_or(ArithmeticError::Overflow)?;988 ensure!(989 tokens_minted <= collection.limits.token_limit(),990 <CommonError<T>>::CollectionTokenLimitExceeded991 );992993 let mut balances = BTreeMap::new();994 for data in &data {995 let balance = balances996 .entry(&data.owner)997 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));998 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;9991000 ensure!(1001 *balance <= collection.limits.account_token_ownership_limit(),1002 <CommonError<T>>::AccountTokenLimitExceeded,1003 );1004 }10051006 for (i, data) in data.iter().enumerate() {1007 let token = TokenId(first_token + i as u32 + 1);10081009 <PalletStructure<T>>::check_nesting(1010 sender.clone(),1011 &data.owner,1012 collection.id,1013 token,1014 nesting_budget,1015 )?;1016 }10171018 // =========10191020 with_transaction(|| {1021 for (i, data) in data.iter().enumerate() {1022 let token = first_token + i as u32 + 1;10231024 <TokenData<T>>::insert(1025 (collection.id, token),1026 ItemData {1027 // const_data: data.const_data.clone(),1028 owner: data.owner.clone(),1029 },1030 );10311032 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(1033 &data.owner,1034 collection.id,1035 TokenId(token),1036 );10371038 if let Err(e) = Self::set_token_properties(1039 collection,1040 sender,1041 TokenId(token),1042 data.properties.clone().into_iter(),1043 true,1044 nesting_budget,1045 ) {1046 return TransactionOutcome::Rollback(Err(e));1047 }1048 }1049 TransactionOutcome::Commit(Ok(()))1050 })?;10511052 <TokensMinted<T>>::insert(collection.id, tokens_minted);1053 for (account, balance) in balances {1054 <AccountBalance<T>>::insert((collection.id, account), balance);1055 }1056 for (i, data) in data.into_iter().enumerate() {1057 let token = first_token + i as u32 + 1;1058 <Owned<T>>::insert((collection.id, &data.owner, token), true);10591060 <PalletEvm<T>>::deposit_log(1061 ERC721Events::Transfer {1062 from: H160::default(),1063 to: *data.owner.as_eth(),1064 token_id: token.into(),1065 }1066 .to_log(collection_id_to_address(collection.id)),1067 );1068 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1069 collection.id,1070 TokenId(token),1071 data.owner.clone(),1072 1,1073 ));1074 }1075 Ok(())1076 }10771078 pub fn set_allowance_unchecked(1079 collection: &NonfungibleHandle<T>,1080 sender: &T::CrossAccountId,1081 token: TokenId,1082 spender: Option<&T::CrossAccountId>,1083 assume_implicit_eth: bool,1084 ) {1085 if let Some(spender) = spender {1086 let old_spender = <Allowance<T>>::get((collection.id, token));1087 <Allowance<T>>::insert((collection.id, token), spender);1088 // In ERC721 there is only one possible approved user of token, so we set1089 // approved user to spender1090 <PalletEvm<T>>::deposit_log(1091 ERC721Events::Approval {1092 owner: *sender.as_eth(),1093 approved: *spender.as_eth(),1094 token_id: token.into(),1095 }1096 .to_log(collection_id_to_address(collection.id)),1097 );1098 // In Unique chain, any token can have any amount of approved users, so we need to1099 // set allowance of old owner to 0, and allowance of new owner to 11100 if old_spender.as_ref() != Some(spender) {1101 if let Some(old_owner) = old_spender {1102 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1103 collection.id,1104 token,1105 sender.clone(),1106 old_owner,1107 0,1108 ));1109 }1110 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1111 collection.id,1112 token,1113 sender.clone(),1114 spender.clone(),1115 1,1116 ));1117 }1118 } else {1119 let old_spender = <Allowance<T>>::take((collection.id, token));1120 if !assume_implicit_eth {1121 // In ERC721 there is only one possible approved user of token, so we set1122 // approved user to zero address1123 <PalletEvm<T>>::deposit_log(1124 ERC721Events::Approval {1125 owner: *sender.as_eth(),1126 approved: H160::default(),1127 token_id: token.into(),1128 }1129 .to_log(collection_id_to_address(collection.id)),1130 );1131 }1132 // In Unique chain, any token can have any amount of approved users, so we need to1133 // set allowance of old owner to 01134 if let Some(old_spender) = old_spender {1135 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1136 collection.id,1137 token,1138 sender.clone(),1139 old_spender,1140 0,1141 ));1142 }1143 }1144 }11451146 /// Set allowance for the spender to `transfer` or `burn` sender's token.1147 ///1148 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1149 pub fn set_allowance(1150 collection: &NonfungibleHandle<T>,1151 sender: &T::CrossAccountId,1152 token: TokenId,1153 spender: Option<&T::CrossAccountId>,1154 ) -> DispatchResult {1155 if collection.permissions.access() == AccessMode::AllowList {1156 collection.check_allowlist(sender)?;1157 if let Some(spender) = spender {1158 collection.check_allowlist(spender)?;1159 }1160 }11611162 if let Some(spender) = spender {1163 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1164 }11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if &token_data.owner != sender {1169 ensure!(1170 collection.ignores_owned_amount(sender),1171 <CommonError<T>>::CantApproveMoreThanOwned1172 );1173 }11741175 // =========11761177 Self::set_allowance_unchecked(collection, sender, token, spender, false);1178 Ok(())1179 }11801181 /// Checks allowance for the spender to use the token.1182 fn check_allowed(1183 collection: &NonfungibleHandle<T>,1184 spender: &T::CrossAccountId,1185 from: &T::CrossAccountId,1186 token: TokenId,1187 nesting_budget: &dyn Budget,1188 ) -> DispatchResult {1189 if spender.conv_eq(from) {1190 return Ok(());1191 }1192 if collection.permissions.access() == AccessMode::AllowList {1193 // `from`, `to` checked in [`transfer`]1194 collection.check_allowlist(spender)?;1195 }11961197 if collection.limits.owner_can_transfer() && collection.is_owner_or_admin(spender) {1198 return Ok(());1199 }12001201 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1202 ensure!(1203 <PalletStructure<T>>::check_indirectly_owned(1204 spender.clone(),1205 source.0,1206 source.1,1207 None,1208 nesting_budget1209 )?,1210 <CommonError<T>>::ApprovedValueTooLow,1211 );1212 return Ok(());1213 }1214 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1215 return Ok(());1216 }1217 ensure!(1218 collection.ignores_allowance(spender),1219 <CommonError<T>>::ApprovedValueTooLow1220 );1221 Ok(())1222 }12231224 /// Transfer NFT token from one account to another.1225 ///1226 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1227 /// The owner should set allowance for the spender to transfer token.1228 ///1229 /// [`transfer`]: struct.Pallet.html#method.transfer1230 pub fn transfer_from(1231 collection: &NonfungibleHandle<T>,1232 spender: &T::CrossAccountId,1233 from: &T::CrossAccountId,1234 to: &T::CrossAccountId,1235 token: TokenId,1236 nesting_budget: &dyn Budget,1237 ) -> DispatchResult {1238 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12391240 // =========12411242 // Allowance is reset in [`transfer`]1243 Self::transfer(collection, from, to, token, nesting_budget)1244 }12451246 /// Burn NFT token for `from` account.1247 ///1248 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1249 /// set allowance for the spender to burn token.1250 ///1251 /// [`burn`]: struct.Pallet.html#method.burn1252 pub fn burn_from(1253 collection: &NonfungibleHandle<T>,1254 spender: &T::CrossAccountId,1255 from: &T::CrossAccountId,1256 token: TokenId,1257 nesting_budget: &dyn Budget,1258 ) -> DispatchResult {1259 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12601261 // =========12621263 Self::burn(collection, from, token)1264 }12651266 /// Check that `from` token could be nested in `under` token.1267 ///1268 pub fn check_nesting(1269 handle: &NonfungibleHandle<T>,1270 sender: T::CrossAccountId,1271 from: (CollectionId, TokenId),1272 under: TokenId,1273 nesting_budget: &dyn Budget,1274 ) -> DispatchResult {1275 let nesting = handle.permissions.nesting();12761277 #[cfg(not(feature = "runtime-benchmarks"))]1278 let permissive = false;1279 #[cfg(feature = "runtime-benchmarks")]1280 let permissive = nesting.permissive;12811282 if permissive {1283 // Pass1284 } else if nesting.token_owner1285 && <PalletStructure<T>>::check_indirectly_owned(1286 sender.clone(),1287 handle.id,1288 under,1289 Some(from),1290 nesting_budget,1291 )? {1292 // Pass1293 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1294 // Pass1295 } else {1296 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1297 }12981299 if let Some(whitelist) = &nesting.restricted {1300 ensure!(1301 whitelist.contains(&from.0),1302 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1303 );1304 }1305 Ok(())1306 }13071308 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1309 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1310 }13111312 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1313 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1314 }13151316 fn collection_has_tokens(collection_id: CollectionId) -> bool {1317 <TokenData<T>>::iter_prefix((collection_id,))1318 .next()1319 .is_some()1320 }13211322 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1323 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1324 .next()1325 .is_some()1326 }13271328 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1329 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1330 .map(|((child_collection_id, child_id), _)| TokenChild {1331 collection: child_collection_id,1332 token: child_id,1333 })1334 .collect()1335 }13361337 /// Mint single NFT token.1338 ///1339 /// Delegated to [`create_multiple_items`]1340 ///1341 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1342 pub fn create_item(1343 collection: &NonfungibleHandle<T>,1344 sender: &T::CrossAccountId,1345 data: CreateItemData<T>,1346 nesting_budget: &dyn Budget,1347 ) -> DispatchResult {1348 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1349 }1350}pallets/structure/src/lib.rsdiffbeforeafterboth--- a/pallets/structure/src/lib.rs
+++ b/pallets/structure/src/lib.rs
@@ -78,11 +78,11 @@
#[pallet::error]
pub enum Error<T> {
- /// While searching for the owner, encountered an already checked account, detecting a loop.
+ /// While nesting, encountered an already checked account, detecting a loop.
OuroborosDetected,
- /// While searching for the owner, reached the depth limit.
+ /// While nesting, reached the depth limit of nesting, exceeding the provided budget.
DepthLimit,
- /// While iterating over children, reached the breadth limit.
+ /// While nesting, reached the breadth limit of nesting, exceeding the provided budget.
BreadthLimit,
/// Couldn't find the token owner that is itself a token.
TokenNotFound,