difftreelog
feat(pallet nft) added GenesisConfig
in: master
3 files changed
node/cli/src/chain_spec.rsdiffbeforeafterboth--- a/node/cli/src/chain_spec.rs
+++ b/node/cli/src/chain_spec.rs
@@ -168,6 +168,7 @@
.collect(),
},
common: Default::default(),
+ nonfungible: Default::default(),
treasury: Default::default(),
tokens: TokensConfig { balances: vec![] },
sudo: SudoConfig {
@@ -227,6 +228,7 @@
.to_vec(),
},
common: Default::default(),
+ nonfungible: Default::default(),
balances: BalancesConfig {
balances: $endowed_accounts
.iter()
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -496,6 +496,7 @@
StorageVersion::new(1).put::<Pallet<T>>();
}
}
+
impl<T: Config> Pallet<T> {
/// Helper function that handles deposit events
pub fn deposit_event(event: Event<T>) {
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,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::{Get, H160};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};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::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 pub struct Pallet<T>(_);179180 /// Total amount of minted tokens in a collection.181 #[pallet::storage]182 pub type TokensMinted<T: Config> =183 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185 /// Amount of burnt tokens in a collection.186 #[pallet::storage]187 pub type TokensBurnt<T: Config> =188 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190 /// Token data, used to partially describe a token.191 #[pallet::storage]192 pub type TokenData<T: Config> = StorageNMap<193 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194 Value = ItemData<T::CrossAccountId>,195 QueryKind = OptionQuery,196 >;197198 /// Map of key-value pairs, describing the metadata of a token.199 #[pallet::storage]200 #[pallet::getter(fn token_properties)]201 pub type TokenProperties<T: Config> = StorageNMap<202 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203 Value = TokenPropertiesT,204 QueryKind = ValueQuery,205 >;206207 /// Custom data of a token that is serialized to bytes,208 /// primarily reserved for on-chain operations,209 /// normally obscured from the external users.210 ///211 /// Auxiliary properties are slightly different from212 /// usual [`TokenProperties`] due to an unlimited number213 /// and separately stored and written-to key-value pairs.214 ///215 /// Currently unused.216 #[pallet::storage]217 #[pallet::getter(fn token_aux_property)]218 pub type TokenAuxProperties<T: Config> = StorageNMap<219 Key = (220 Key<Twox64Concat, CollectionId>,221 Key<Twox64Concat, TokenId>,222 Key<Twox64Concat, PropertyScope>,223 Key<Twox64Concat, PropertyKey>,224 ),225 Value = AuxPropertyValue,226 QueryKind = OptionQuery,227 >;228229 /// Used to enumerate tokens owned by account.230 #[pallet::storage]231 pub type Owned<T: Config> = StorageNMap<232 Key = (233 Key<Twox64Concat, CollectionId>,234 Key<Blake2_128Concat, T::CrossAccountId>,235 Key<Twox64Concat, TokenId>,236 ),237 Value = bool,238 QueryKind = ValueQuery,239 >;240241 /// Used to enumerate token's children.242 #[pallet::storage]243 #[pallet::getter(fn token_children)]244 pub type TokenChildren<T: Config> = StorageNMap<245 Key = (246 Key<Twox64Concat, CollectionId>,247 Key<Twox64Concat, TokenId>,248 Key<Twox64Concat, (CollectionId, TokenId)>,249 ),250 Value = bool,251 QueryKind = ValueQuery,252 >;253254 /// Amount of tokens owned by an account in a collection.255 #[pallet::storage]256 pub type AccountBalance<T: Config> = StorageNMap<257 Key = (258 Key<Twox64Concat, CollectionId>,259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u32,262 QueryKind = ValueQuery,263 >;264265 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.266 #[pallet::storage]267 pub type Allowance<T: Config> = StorageNMap<268 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269 Value = T::CrossAccountId,270 QueryKind = OptionQuery,271 >;272273 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.274 #[pallet::storage]275 pub type CollectionAllowance<T: Config> = StorageNMap<276 Key = (277 Key<Twox64Concat, CollectionId>,278 Key<Blake2_128Concat, T::CrossAccountId>,279 Key<Blake2_128Concat, T::CrossAccountId>,280 ),281 Value = bool,282 QueryKind = ValueQuery,283 >;284}285286pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);287impl<T: Config> NonfungibleHandle<T> {288 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {289 Self(inner)290 }291 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {292 self.0293 }294 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {295 &mut self.0296 }297}298299impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {300 fn recorder(&self) -> &SubstrateRecorder<T> {301 self.0.recorder()302 }303 fn into_recorder(self) -> SubstrateRecorder<T> {304 self.0.into_recorder()305 }306}307impl<T: Config> Deref for NonfungibleHandle<T> {308 type Target = pallet_common::CollectionHandle<T>;309310 fn deref(&self) -> &Self::Target {311 &self.0312 }313}314315impl<T: Config> Pallet<T> {316 /// Get number of NFT tokens in collection.317 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {318 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)319 }320321 /// Check that NFT token exists.322 ///323 /// - `token`: Token ID.324 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {325 <TokenData<T>>::contains_key((collection.id, token))326 }327328 /// Set the token property with the scope.329 ///330 /// - `property`: Contains key-value pair.331 pub fn set_scoped_token_property(332 collection_id: CollectionId,333 token_id: TokenId,334 scope: PropertyScope,335 property: Property,336 ) -> DispatchResult {337 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {338 properties.try_scoped_set(scope, property.key, property.value)339 })340 .map_err(<CommonError<T>>::from)?;341342 Ok(())343 }344345 /// Batch operation to set multiple properties with the same scope.346 pub fn set_scoped_token_properties(347 collection_id: CollectionId,348 token_id: TokenId,349 scope: PropertyScope,350 properties: impl Iterator<Item = Property>,351 ) -> DispatchResult {352 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {353 stored_properties.try_scoped_set_from_iter(scope, properties)354 })355 .map_err(<CommonError<T>>::from)?;356357 Ok(())358 }359360 /// Add or edit auxiliary data for the property.361 ///362 /// - `f`: function that adds or edits auxiliary data.363 pub fn try_mutate_token_aux_property<R, E>(364 collection_id: CollectionId,365 token_id: TokenId,366 scope: PropertyScope,367 key: PropertyKey,368 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,369 ) -> Result<R, E> {370 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)371 }372373 /// Remove auxiliary data for the property.374 pub fn remove_token_aux_property(375 collection_id: CollectionId,376 token_id: TokenId,377 scope: PropertyScope,378 key: PropertyKey,379 ) {380 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));381 }382383 /// Get all auxiliary data in a given scope.384 ///385 /// Returns iterator over Property Key - Data pairs.386 pub fn iterate_token_aux_properties(387 collection_id: CollectionId,388 token_id: TokenId,389 scope: PropertyScope,390 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {391 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))392 }393394 /// Get ID of the last minted token395 pub fn current_token_id(collection_id: CollectionId) -> TokenId {396 TokenId(<TokensMinted<T>>::get(collection_id))397 }398}399400// unchecked calls skips any permission checks401impl<T: Config> Pallet<T> {402 /// Create NFT collection403 ///404 /// `init_collection` will take non-refundable deposit for collection creation.405 ///406 /// - `data`: Contains settings for collection limits and permissions.407 pub fn init_collection(408 owner: T::CrossAccountId,409 payer: T::CrossAccountId,410 data: CreateCollectionData<T::AccountId>,411 flags: CollectionFlags,412 ) -> Result<CollectionId, DispatchError> {413 <PalletCommon<T>>::init_collection(owner, payer, data, flags)414 }415416 /// Destroy NFT collection417 ///418 /// `destroy_collection` will throw error if collection contains any tokens.419 /// Only owner can destroy collection.420 pub fn destroy_collection(421 collection: NonfungibleHandle<T>,422 sender: &T::CrossAccountId,423 ) -> DispatchResult {424 let id = collection.id;425426 if Self::collection_has_tokens(id) {427 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());428 }429430 // =========431432 PalletCommon::destroy_collection(collection.0, sender)?;433434 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);435 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);436 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);437 <TokensMinted<T>>::remove(id);438 <TokensBurnt<T>>::remove(id);439 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);440 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);441 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);442 Ok(())443 }444445 /// Burn NFT token446 ///447 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token448 /// if the token is nested.449 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.450 /// Also removes all corresponding properties and auxiliary properties.451 ///452 /// - `token`: Token that should be burned453 /// - `collection`: Collection that contains the token454 pub fn burn(455 collection: &NonfungibleHandle<T>,456 sender: &T::CrossAccountId,457 token: TokenId,458 ) -> DispatchResult {459 let token_data =460 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;461 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);462463 if collection.permissions.access() == AccessMode::AllowList {464 collection.check_allowlist(sender)?;465 }466467 if Self::token_has_children(collection.id, token) {468 return Err(<Error<T>>::CantBurnNftWithChildren.into());469 }470471 let burnt = <TokensBurnt<T>>::get(collection.id)472 .checked_add(1)473 .ok_or(ArithmeticError::Overflow)?;474475 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))476 .checked_sub(1)477 .ok_or(ArithmeticError::Overflow)?;478479 // =========480481 if balance == 0 {482 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));483 } else {484 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);485 }486487 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);488489 <Owned<T>>::remove((collection.id, &token_data.owner, token));490 <TokensBurnt<T>>::insert(collection.id, burnt);491 <TokenData<T>>::remove((collection.id, token));492 <TokenProperties<T>>::remove((collection.id, token));493 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);494 let old_spender = <Allowance<T>>::take((collection.id, token));495496 if let Some(old_spender) = old_spender {497 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(498 collection.id,499 token,500 token_data.owner.clone(),501 old_spender,502 0,503 ));504 }505506 <PalletEvm<T>>::deposit_log(507 ERC721Events::Transfer {508 from: *token_data.owner.as_eth(),509 to: H160::default(),510 token_id: token.into(),511 }512 .to_log(collection_id_to_address(collection.id)),513 );514 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(515 collection.id,516 token,517 token_data.owner,518 1,519 ));520 Ok(())521 }522523 /// Same as [`burn`] but burns all the tokens that are nested in the token first524 ///525 /// - `self_budget`: Limit for searching children in depth.526 /// - `breadth_budget`: Limit of breadth of searching children.527 ///528 /// [`burn`]: struct.Pallet.html#method.burn529 #[transactional]530 pub fn burn_recursively(531 collection: &NonfungibleHandle<T>,532 sender: &T::CrossAccountId,533 token: TokenId,534 self_budget: &dyn Budget,535 breadth_budget: &dyn Budget,536 ) -> DispatchResultWithPostInfo {537 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);538539 let current_token_account =540 T::CrossTokenAddressMapping::token_to_address(collection.id, token);541542 let mut weight = Weight::zero();543544 // This method is transactional, if user in fact doesn't have permissions to remove token -545 // tokens removed here will be restored after rejected transaction546 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {547 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);548 let PostDispatchInfo { actual_weight, .. } =549 <PalletStructure<T>>::burn_item_recursively(550 current_token_account.clone(),551 collection,552 token,553 self_budget,554 breadth_budget,555 )?;556 if let Some(actual_weight) = actual_weight {557 weight = weight.saturating_add(actual_weight);558 }559 }560561 Self::burn(collection, sender, token)?;562 DispatchResultWithPostInfo::Ok(PostDispatchInfo {563 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),564 pays_fee: Pays::Yes,565 })566 }567568 /// A batch operation to add, edit or remove properties for a token.569 ///570 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.571 /// - `is_token_create`: Indicates that method is called during token initialization.572 /// Allows to bypass ownership check.573 ///574 /// All affected properties should have `mutable` permission575 /// to be **deleted** or to be **set more than once**,576 /// and the sender should have permission to edit those properties.577 ///578 /// This function fires an event for each property change.579 /// In case of an error, all the changes (including the events) will be reverted580 /// since the function is transactional.581 #[transactional]582 fn modify_token_properties(583 collection: &NonfungibleHandle<T>,584 sender: &T::CrossAccountId,585 token_id: TokenId,586 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,587 is_token_create: bool,588 nesting_budget: &dyn Budget,589 ) -> DispatchResult {590 let is_token_owner = || {591 let is_owned = <PalletStructure<T>>::check_indirectly_owned(592 sender.clone(),593 collection.id,594 token_id,595 None,596 nesting_budget,597 )?;598599 Ok(is_owned)600 };601602 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));603604 <PalletCommon<T>>::modify_token_properties(605 collection,606 sender,607 token_id,608 properties_updates,609 is_token_create,610 stored_properties,611 is_token_owner,612 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),613 erc::ERC721TokenEvent::TokenChanged {614 token_id: token_id.into(),615 }616 .to_log(T::ContractAddress::get()),617 )618 }619620 /// Batch operation to add or edit properties for the token621 ///622 /// Same as [`modify_token_properties`] but doesn't allow to remove properties623 ///624 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties625 pub fn set_token_properties(626 collection: &NonfungibleHandle<T>,627 sender: &T::CrossAccountId,628 token_id: TokenId,629 properties: impl Iterator<Item = Property>,630 is_token_create: bool,631 nesting_budget: &dyn Budget,632 ) -> DispatchResult {633 Self::modify_token_properties(634 collection,635 sender,636 token_id,637 properties.map(|p| (p.key, Some(p.value))),638 is_token_create,639 nesting_budget,640 )641 }642643 /// Add or edit single property for the token644 ///645 /// Calls [`set_token_properties`] internally646 ///647 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties648 pub fn set_token_property(649 collection: &NonfungibleHandle<T>,650 sender: &T::CrossAccountId,651 token_id: TokenId,652 property: Property,653 nesting_budget: &dyn Budget,654 ) -> DispatchResult {655 let is_token_create = false;656657 Self::set_token_properties(658 collection,659 sender,660 token_id,661 [property].into_iter(),662 is_token_create,663 nesting_budget,664 )665 }666667 /// Batch operation to remove properties from the token668 ///669 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties670 ///671 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties672 pub fn delete_token_properties(673 collection: &NonfungibleHandle<T>,674 sender: &T::CrossAccountId,675 token_id: TokenId,676 property_keys: impl Iterator<Item = PropertyKey>,677 nesting_budget: &dyn Budget,678 ) -> DispatchResult {679 let is_token_create = false;680681 Self::modify_token_properties(682 collection,683 sender,684 token_id,685 property_keys.into_iter().map(|key| (key, None)),686 is_token_create,687 nesting_budget,688 )689 }690691 /// Remove single property from the token692 ///693 /// Calls [`delete_token_properties`] internally694 ///695 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties696 pub fn delete_token_property(697 collection: &NonfungibleHandle<T>,698 sender: &T::CrossAccountId,699 token_id: TokenId,700 property_key: PropertyKey,701 nesting_budget: &dyn Budget,702 ) -> DispatchResult {703 Self::delete_token_properties(704 collection,705 sender,706 token_id,707 [property_key].into_iter(),708 nesting_budget,709 )710 }711712 /// Add or edit properties for the collection713 pub fn set_collection_properties(714 collection: &NonfungibleHandle<T>,715 sender: &T::CrossAccountId,716 properties: Vec<Property>,717 ) -> DispatchResult {718 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())719 }720721 /// Remove properties from the collection722 pub fn delete_collection_properties(723 collection: &CollectionHandle<T>,724 sender: &T::CrossAccountId,725 property_keys: Vec<PropertyKey>,726 ) -> DispatchResult {727 <PalletCommon<T>>::delete_collection_properties(728 collection,729 sender,730 property_keys.into_iter(),731 )732 }733734 /// Set property permissions for the token.735 ///736 /// Sender should be the owner or admin of token's collection.737 pub fn set_token_property_permissions(738 collection: &CollectionHandle<T>,739 sender: &T::CrossAccountId,740 property_permissions: Vec<PropertyKeyPermission>,741 ) -> DispatchResult {742 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)743 }744745 /// Set property permissions for the token with scope.746 ///747 /// Sender should be the owner or admin of token's collection.748 pub fn set_scoped_token_property_permissions(749 collection: &CollectionHandle<T>,750 sender: &T::CrossAccountId,751 scope: PropertyScope,752 property_permissions: Vec<PropertyKeyPermission>,753 ) -> DispatchResult {754 <PalletCommon<T>>::set_scoped_token_property_permissions(755 collection,756 sender,757 scope,758 property_permissions,759 )760 }761762 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {763 <PalletCommon<T>>::property_permissions(collection_id)764 }765766 pub fn check_token_immediate_ownership(767 collection: &NonfungibleHandle<T>,768 token: TokenId,769 possible_owner: &T::CrossAccountId,770 ) -> DispatchResult {771 let token_data =772 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;773 ensure!(774 &token_data.owner == possible_owner,775 <CommonError<T>>::NoPermission776 );777 Ok(())778 }779780 /// Transfer NFT token from one account to another.781 ///782 /// `from` account stops being the owner and `to` account becomes the owner of the token.783 /// If `to` is token than `to` becomes owner of the token and the token become nested.784 /// Unnests token from previous parent if it was nested before.785 /// Removes allowance for the token if there was any.786 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.787 ///788 /// - `nesting_budget`: Limit for token nesting depth789 pub fn transfer(790 collection: &NonfungibleHandle<T>,791 from: &T::CrossAccountId,792 to: &T::CrossAccountId,793 token: TokenId,794 nesting_budget: &dyn Budget,795 ) -> DispatchResult {796 ensure!(797 collection.limits.transfers_enabled(),798 <CommonError<T>>::TransferNotAllowed799 );800801 let token_data =802 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;803 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);804805 if collection.permissions.access() == AccessMode::AllowList {806 collection.check_allowlist(from)?;807 collection.check_allowlist(to)?;808 }809 <PalletCommon<T>>::ensure_correct_receiver(to)?;810811 let balance_from = <AccountBalance<T>>::get((collection.id, from))812 .checked_sub(1)813 .ok_or(<CommonError<T>>::TokenValueTooLow)?;814 let balance_to = if from != to {815 let balance_to = <AccountBalance<T>>::get((collection.id, to))816 .checked_add(1)817 .ok_or(ArithmeticError::Overflow)?;818819 ensure!(820 balance_to < collection.limits.account_token_ownership_limit(),821 <CommonError<T>>::AccountTokenLimitExceeded,822 );823824 Some(balance_to)825 } else {826 None827 };828829 <PalletStructure<T>>::nest_if_sent_to_token(830 from.clone(),831 to,832 collection.id,833 token,834 nesting_budget,835 )?;836837 // =========838839 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);840841 <TokenData<T>>::insert(842 (collection.id, token),843 ItemData {844 owner: to.clone(),845 ..token_data846 },847 );848849 if let Some(balance_to) = balance_to {850 // from != to851 if balance_from == 0 {852 <AccountBalance<T>>::remove((collection.id, from));853 } else {854 <AccountBalance<T>>::insert((collection.id, from), balance_from);855 }856 <AccountBalance<T>>::insert((collection.id, to), balance_to);857 <Owned<T>>::remove((collection.id, from, token));858 <Owned<T>>::insert((collection.id, to, token), true);859 }860 Self::set_allowance_unchecked(collection, from, token, None, true);861862 <PalletEvm<T>>::deposit_log(863 ERC721Events::Transfer {864 from: *from.as_eth(),865 to: *to.as_eth(),866 token_id: token.into(),867 }868 .to_log(collection_id_to_address(collection.id)),869 );870 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(871 collection.id,872 token,873 from.clone(),874 to.clone(),875 1,876 ));877 Ok(())878 }879880 /// Batch operation to mint multiple NFT tokens.881 ///882 /// The sender should be the owner/admin of the collection or collection should be configured883 /// to allow public minting.884 /// Throws if amount of tokens reached it's limit for the collection or if caller reached885 /// token ownership limit.886 ///887 /// - `data`: Contains list of token properties and users who will become the owners of the888 /// corresponging tokens.889 /// - `nesting_budget`: Limit for token nesting depth890 pub fn create_multiple_items(891 collection: &NonfungibleHandle<T>,892 sender: &T::CrossAccountId,893 data: Vec<CreateItemData<T>>,894 nesting_budget: &dyn Budget,895 ) -> DispatchResult {896 if !collection.is_owner_or_admin(sender) {897 ensure!(898 collection.permissions.mint_mode(),899 <CommonError<T>>::PublicMintingNotAllowed900 );901 collection.check_allowlist(sender)?;902903 for item in data.iter() {904 collection.check_allowlist(&item.owner)?;905 }906 }907908 for data in data.iter() {909 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;910 }911912 let first_token = <TokensMinted<T>>::get(collection.id);913 let tokens_minted = first_token914 .checked_add(data.len() as u32)915 .ok_or(ArithmeticError::Overflow)?;916 ensure!(917 tokens_minted <= collection.limits.token_limit(),918 <CommonError<T>>::CollectionTokenLimitExceeded919 );920921 let mut balances = BTreeMap::new();922 for data in &data {923 let balance = balances924 .entry(&data.owner)925 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));926 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;927928 ensure!(929 *balance <= collection.limits.account_token_ownership_limit(),930 <CommonError<T>>::AccountTokenLimitExceeded,931 );932 }933934 for (i, data) in data.iter().enumerate() {935 let token = TokenId(first_token + i as u32 + 1);936937 <PalletStructure<T>>::check_nesting(938 sender.clone(),939 &data.owner,940 collection.id,941 token,942 nesting_budget,943 )?;944 }945946 // =========947948 with_transaction(|| {949 for (i, data) in data.iter().enumerate() {950 let token = first_token + i as u32 + 1;951952 <TokenData<T>>::insert(953 (collection.id, token),954 ItemData {955 // const_data: data.const_data.clone(),956 owner: data.owner.clone(),957 },958 );959960 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(961 &data.owner,962 collection.id,963 TokenId(token),964 );965966 if let Err(e) = Self::set_token_properties(967 collection,968 sender,969 TokenId(token),970 data.properties.clone().into_iter(),971 true,972 nesting_budget,973 ) {974 return TransactionOutcome::Rollback(Err(e));975 }976 }977 TransactionOutcome::Commit(Ok(()))978 })?;979980 <TokensMinted<T>>::insert(collection.id, tokens_minted);981 for (account, balance) in balances {982 <AccountBalance<T>>::insert((collection.id, account), balance);983 }984 for (i, data) in data.into_iter().enumerate() {985 let token = first_token + i as u32 + 1;986 <Owned<T>>::insert((collection.id, &data.owner, token), true);987988 <PalletEvm<T>>::deposit_log(989 ERC721Events::Transfer {990 from: H160::default(),991 to: *data.owner.as_eth(),992 token_id: token.into(),993 }994 .to_log(collection_id_to_address(collection.id)),995 );996 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(997 collection.id,998 TokenId(token),999 data.owner.clone(),1000 1,1001 ));1002 }1003 Ok(())1004 }10051006 pub fn set_allowance_unchecked(1007 collection: &NonfungibleHandle<T>,1008 sender: &T::CrossAccountId,1009 token: TokenId,1010 spender: Option<&T::CrossAccountId>,1011 assume_implicit_eth: bool,1012 ) {1013 if let Some(spender) = spender {1014 let old_spender = <Allowance<T>>::get((collection.id, token));1015 <Allowance<T>>::insert((collection.id, token), spender);1016 // In ERC721 there is only one possible approved user of token, so we set1017 // approved user to spender1018 <PalletEvm<T>>::deposit_log(1019 ERC721Events::Approval {1020 owner: *sender.as_eth(),1021 approved: *spender.as_eth(),1022 token_id: token.into(),1023 }1024 .to_log(collection_id_to_address(collection.id)),1025 );1026 // In Unique chain, any token can have any amount of approved users, so we need to1027 // set allowance of old owner to 0, and allowance of new owner to 11028 if old_spender.as_ref() != Some(spender) {1029 if let Some(old_owner) = old_spender {1030 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1031 collection.id,1032 token,1033 sender.clone(),1034 old_owner,1035 0,1036 ));1037 }1038 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1039 collection.id,1040 token,1041 sender.clone(),1042 spender.clone(),1043 1,1044 ));1045 }1046 } else {1047 let old_spender = <Allowance<T>>::take((collection.id, token));1048 if !assume_implicit_eth {1049 // In ERC721 there is only one possible approved user of token, so we set1050 // approved user to zero address1051 <PalletEvm<T>>::deposit_log(1052 ERC721Events::Approval {1053 owner: *sender.as_eth(),1054 approved: H160::default(),1055 token_id: token.into(),1056 }1057 .to_log(collection_id_to_address(collection.id)),1058 );1059 }1060 // In Unique chain, any token can have any amount of approved users, so we need to1061 // set allowance of old owner to 01062 if let Some(old_spender) = old_spender {1063 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1064 collection.id,1065 token,1066 sender.clone(),1067 old_spender,1068 0,1069 ));1070 }1071 }1072 }10731074 pub fn get_allowance(1075 collection: &NonfungibleHandle<T>,1076 token_id: TokenId,1077 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1078 ensure!(1079 <TokenData<T>>::get((collection.id, token_id)).is_some(),1080 <CommonError<T>>::TokenNotFound1081 );1082 Ok(<Allowance<T>>::get((collection.id, token_id)))1083 }10841085 /// Set allowance for the spender to `transfer` or `burn` sender's token.1086 ///1087 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1088 pub fn set_allowance(1089 collection: &NonfungibleHandle<T>,1090 sender: &T::CrossAccountId,1091 token: TokenId,1092 spender: Option<&T::CrossAccountId>,1093 ) -> DispatchResult {1094 if collection.permissions.access() == AccessMode::AllowList {1095 collection.check_allowlist(sender)?;1096 if let Some(spender) = spender {1097 collection.check_allowlist(spender)?;1098 }1099 }11001101 if let Some(spender) = spender {1102 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1103 }11041105 let token_data =1106 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1107 if &token_data.owner != sender {1108 ensure!(1109 collection.ignores_owned_amount(sender),1110 <CommonError<T>>::CantApproveMoreThanOwned1111 );1112 }11131114 // =========11151116 Self::set_allowance_unchecked(collection, sender, token, spender, false);1117 Ok(())1118 }11191120 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1121 ///1122 /// - `from`: Address of sender's eth mirror.1123 /// - `to`: Adress of spender.1124 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1125 pub fn set_allowance_from(1126 collection: &NonfungibleHandle<T>,1127 sender: &T::CrossAccountId,1128 from: &T::CrossAccountId,1129 token: TokenId,1130 to: Option<&T::CrossAccountId>,1131 ) -> DispatchResult {1132 if collection.permissions.access() == AccessMode::AllowList {1133 collection.check_allowlist(sender)?;1134 collection.check_allowlist(from)?;1135 if let Some(to) = to {1136 collection.check_allowlist(to)?;1137 }1138 }11391140 if let Some(to) = to {1141 <PalletCommon<T>>::ensure_correct_receiver(to)?;1142 }11431144 ensure!(1145 sender.conv_eq(from),1146 <CommonError<T>>::AddressIsNotEthMirror1147 );11481149 let token_data =1150 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1151 if token_data.owner != *from {1152 ensure!(1153 collection.limits.owner_can_transfer()1154 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1155 <CommonError<T>>::CantApproveMoreThanOwned1156 );1157 }11581159 // =========11601161 Self::set_allowance_unchecked(collection, from, token, to, false);1162 Ok(())1163 }11641165 /// Checks allowance for the spender to use the token.1166 fn check_allowed(1167 collection: &NonfungibleHandle<T>,1168 spender: &T::CrossAccountId,1169 from: &T::CrossAccountId,1170 token: TokenId,1171 nesting_budget: &dyn Budget,1172 ) -> DispatchResult {1173 if spender.conv_eq(from) {1174 return Ok(());1175 }1176 if collection.permissions.access() == AccessMode::AllowList {1177 // `from`, `to` checked in [`transfer`]1178 collection.check_allowlist(spender)?;1179 }11801181 if collection.ignores_token_restrictions(spender) {1182 return Ok(());1183 }11841185 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1186 ensure!(1187 <PalletStructure<T>>::check_indirectly_owned(1188 spender.clone(),1189 source.0,1190 source.1,1191 None,1192 nesting_budget1193 )?,1194 <CommonError<T>>::ApprovedValueTooLow,1195 );1196 return Ok(());1197 }1198 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1199 return Ok(());1200 }1201 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1202 return Ok(());1203 }12041205 Err(<CommonError<T>>::ApprovedValueTooLow.into())1206 }12071208 /// Transfer NFT token from one account to another.1209 ///1210 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1211 /// The owner should set allowance for the spender to transfer token.1212 ///1213 /// [`transfer`]: struct.Pallet.html#method.transfer1214 pub fn transfer_from(1215 collection: &NonfungibleHandle<T>,1216 spender: &T::CrossAccountId,1217 from: &T::CrossAccountId,1218 to: &T::CrossAccountId,1219 token: TokenId,1220 nesting_budget: &dyn Budget,1221 ) -> DispatchResult {1222 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12231224 // =========12251226 // Allowance is reset in [`transfer`]1227 Self::transfer(collection, from, to, token, nesting_budget)1228 }12291230 /// Burn NFT token for `from` account.1231 ///1232 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1233 /// set allowance for the spender to burn token.1234 ///1235 /// [`burn`]: struct.Pallet.html#method.burn1236 pub fn burn_from(1237 collection: &NonfungibleHandle<T>,1238 spender: &T::CrossAccountId,1239 from: &T::CrossAccountId,1240 token: TokenId,1241 nesting_budget: &dyn Budget,1242 ) -> DispatchResult {1243 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12441245 // =========12461247 Self::burn(collection, from, token)1248 }12491250 /// Check that `from` token could be nested in `under` token.1251 ///1252 pub fn check_nesting(1253 handle: &NonfungibleHandle<T>,1254 sender: T::CrossAccountId,1255 from: (CollectionId, TokenId),1256 under: TokenId,1257 nesting_budget: &dyn Budget,1258 ) -> DispatchResult {1259 let nesting = handle.permissions.nesting();12601261 #[cfg(not(feature = "runtime-benchmarks"))]1262 let permissive = false;1263 #[cfg(feature = "runtime-benchmarks")]1264 let permissive = nesting.permissive;12651266 if permissive {1267 ensure!(1268 <TokenData<T>>::contains_key((handle.id, under)),1269 <CommonError<T>>::TokenNotFound1270 );1271 } else if nesting.token_owner1272 && <PalletStructure<T>>::check_indirectly_owned(1273 sender.clone(),1274 handle.id,1275 under,1276 Some(from),1277 nesting_budget,1278 )? {1279 // Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1280 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1281 // token existence and ouroboros checks are done in `get_checked_topmost_owner`1282 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1283 handle.id,1284 under,1285 Some(from),1286 nesting_budget,1287 )?1288 .ok_or(<CommonError<T>>::TokenNotFound)?;1289 } else {1290 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1291 }12921293 if let Some(whitelist) = &nesting.restricted {1294 ensure!(1295 whitelist.contains(&from.0),1296 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1297 );1298 }1299 Ok(())1300 }13011302 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1303 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1304 }13051306 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1307 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1308 }13091310 fn collection_has_tokens(collection_id: CollectionId) -> bool {1311 <TokenData<T>>::iter_prefix((collection_id,))1312 .next()1313 .is_some()1314 }13151316 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1317 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1318 .next()1319 .is_some()1320 }13211322 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1323 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1324 .map(|((child_collection_id, child_id), _)| TokenChild {1325 collection: child_collection_id,1326 token: child_id,1327 })1328 .collect()1329 }13301331 /// Mint single NFT token.1332 ///1333 /// Delegated to [`create_multiple_items`]1334 ///1335 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1336 pub fn create_item(1337 collection: &NonfungibleHandle<T>,1338 sender: &T::CrossAccountId,1339 data: CreateItemData<T>,1340 nesting_budget: &dyn Budget,1341 ) -> DispatchResult {1342 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1343 }13441345 /// Sets or unsets the approval of a given operator.1346 ///1347 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1348 /// - `owner`: Token owner1349 /// - `operator`: Operator1350 /// - `approve`: Should operator status be granted or revoked?1351 pub fn set_allowance_for_all(1352 collection: &NonfungibleHandle<T>,1353 owner: &T::CrossAccountId,1354 operator: &T::CrossAccountId,1355 approve: bool,1356 ) -> DispatchResult {1357 <PalletCommon<T>>::set_allowance_for_all(1358 collection,1359 owner,1360 operator,1361 approve,1362 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1363 ERC721Events::ApprovalForAll {1364 owner: *owner.as_eth(),1365 operator: *operator.as_eth(),1366 approved: approve,1367 }1368 .to_log(collection_id_to_address(collection.id)),1369 )1370 }13711372 /// Tells whether the given `owner` approves the `operator`.1373 pub fn allowance_for_all(1374 collection: &NonfungibleHandle<T>,1375 owner: &T::CrossAccountId,1376 operator: &T::CrossAccountId,1377 ) -> bool {1378 <CollectionAllowance<T>>::get((collection.id, owner, operator))1379 }13801381 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1382 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1383 properties.recompute_consumed_space();1384 });13851386 Ok(())1387 }1388}