difftreelog
fix use OptionQuery for TokenProperties
in: master
9 files changed
pallets/balances-adapter/src/common.rsdiffbeforeafterboth--- a/pallets/balances-adapter/src/common.rs
+++ b/pallets/balances-adapter/src/common.rs
@@ -172,18 +172,16 @@
fail!(<pallet_common::Error<T>>::UnsupportedOperation);
}
- fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ _token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
// No token properties are defined on fungibles
- up_data_structs::TokenProperties::new()
+ None
}
- fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
- // No token properties are defined on fungibles
- }
-
- fn properties_exist(&self, _token: TokenId) -> bool {
+ fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
// No token properties are defined on fungibles
- false
}
fn set_token_property_permissions(
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -2098,18 +2098,13 @@
/// Get token properties raw map.
///
/// * `token_id` - The token which properties are needed.
- fn get_token_properties_map(&self, token_id: TokenId) -> TokenProperties;
+ fn get_token_properties_raw(&self, token_id: TokenId) -> Option<TokenProperties>;
/// Set token properties raw map.
///
/// * `token_id` - The token for which the properties are being set.
/// * `map` - The raw map containing the token's properties.
- fn set_token_properties_map(&self, token_id: TokenId, map: TokenProperties);
-
- /// Whether the given token has properties.
- ///
- /// * `token_id` - The token in question.
- fn properties_exist(&self, token: TokenId) -> bool;
+ fn set_token_properties_raw(&self, token_id: TokenId, map: TokenProperties);
/// Set token property permissions.
///
@@ -2590,7 +2585,7 @@
<PalletEvm<T>>::deposit_log(log);
self.collection
- .set_token_properties_map(token_id, stored_properties.into_inner());
+ .set_token_properties_raw(token_id, stored_properties.into_inner());
}
Ok(())
@@ -2624,7 +2619,7 @@
true
},
get_properties: |token_id| {
- debug_assert!(!collection.properties_exist(token_id));
+ debug_assert!(collection.get_token_properties_raw(token_id).is_none());
TokenProperties::new()
},
_phantom: PhantomData,
@@ -2686,7 +2681,11 @@
is_collection_admin: LazyValue::new(|| collection.is_owner_or_admin(sender)),
property_permissions: LazyValue::new(|| <Pallet<T>>::property_permissions(collection.id)),
check_token_exist: |token_id| collection.token_exists(token_id),
- get_properties: |token_id| collection.get_token_properties_map(token_id),
+ get_properties: |token_id| {
+ collection
+ .get_token_properties_raw(token_id)
+ .unwrap_or_default()
+ },
_phantom: PhantomData,
}
}
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -364,18 +364,16 @@
fail!(<Error<T>>::SettingPropertiesNotAllowed)
}
- fn get_token_properties_map(&self, _token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ _token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
// No token properties are defined on fungibles
- up_data_structs::TokenProperties::new()
+ None
}
- fn set_token_properties_map(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
- // No token properties are defined on fungibles
- }
-
- fn properties_exist(&self, _token: TokenId) -> bool {
+ fn set_token_properties_raw(&self, _token_id: TokenId, _map: up_data_structs::TokenProperties) {
// No token properties are defined on fungibles
- false
}
fn check_nesting(
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -265,12 +265,15 @@
)
}
- fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
<TokenProperties<T>>::get((self.id, token_id))
}
- fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
- <TokenProperties<T>>::set((self.id, token_id), map)
+ fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::insert((self.id, token_id), map)
}
fn set_token_property_permissions(
@@ -287,10 +290,6 @@
)
}
- fn properties_exist(&self, token: TokenId) -> bool {
- <TokenProperties<T>>::contains_key((self.id, token))
- }
-
fn burn_item(
&self,
sender: T::CrossAccountId,
@@ -482,13 +481,15 @@
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
- <Pallet<T>>::token_properties((self.id, token_id))
+ <Pallet<T>>::token_properties((self.id, token_id))?
.get(key)
.cloned()
}
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
- let properties = <Pallet<T>>::token_properties((self.id, token_id));
+ let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+ return vec![];
+ };
keys.map(|keys| {
keys.into_iter()
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -272,7 +272,8 @@
.try_into()
.map_err(|_| "key too long")?;
- let props = <TokenProperties<T>>::get((self.id, token_id));
+ let props =
+ <TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
let prop = props.get(&key).ok_or("key not found")?;
Ok(prop.to_vec().into())
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, CustomDataLimit, TokenId, CreateCollectionData, CreateNftExData,104 mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey, PropertyValue,105 PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild, AuxPropertyValue,106 PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Token data, stored independently from other data used to describe it135/// for the convenience of database access. Notably contains the owner account address.136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139 #[version(..2)]140 pub const_data: BoundedVec<u8, CustomDataLimit>,141142 #[version(..2)]143 pub variable_data: BoundedVec<u8, CustomDataLimit>,144145 pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150 use super::*;151 use frame_support::{152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153 };154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 /// Not Nonfungible item data used to mint in Nonfungible collection.160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 /// Used amount > 1 with NFT162 NonfungibleItemsHaveNoAmount,163 /// Unable to burn NFT with children164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::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 >;284285 #[pallet::genesis_config]286 pub struct GenesisConfig<T>(PhantomData<T>);287288 #[cfg(feature = "std")]289 impl<T: Config> Default for GenesisConfig<T> {290 fn default() -> Self {291 Self(Default::default())292 }293 }294295 #[pallet::genesis_build]296 impl<T: Config> GenesisBuild<T> for GenesisConfig<T> {297 fn build(&self) {298 StorageVersion::new(1).put::<Pallet<T>>();299 }300 }301}302303pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);304impl<T: Config> NonfungibleHandle<T> {305 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {306 Self(inner)307 }308 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {309 self.0310 }311 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {312 &mut self.0313 }314}315316impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {317 fn recorder(&self) -> &SubstrateRecorder<T> {318 self.0.recorder()319 }320 fn into_recorder(self) -> SubstrateRecorder<T> {321 self.0.into_recorder()322 }323}324impl<T: Config> Deref for NonfungibleHandle<T> {325 type Target = pallet_common::CollectionHandle<T>;326327 fn deref(&self) -> &Self::Target {328 &self.0329 }330}331332impl<T: Config> Pallet<T> {333 /// Get number of NFT tokens in collection.334 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {335 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)336 }337338 /// Check that NFT token exists.339 ///340 /// - `token`: Token ID.341 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {342 <TokenData<T>>::contains_key((collection.id, token))343 }344345 /// Set the token property with the scope.346 ///347 /// - `property`: Contains key-value pair.348 pub fn set_scoped_token_property(349 collection_id: CollectionId,350 token_id: TokenId,351 scope: PropertyScope,352 property: Property,353 ) -> DispatchResult {354 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {355 properties.try_scoped_set(scope, property.key, property.value)356 })357 .map_err(<CommonError<T>>::from)?;358359 Ok(())360 }361362 /// Batch operation to set multiple properties with the same scope.363 pub fn set_scoped_token_properties(364 collection_id: CollectionId,365 token_id: TokenId,366 scope: PropertyScope,367 properties: impl Iterator<Item = Property>,368 ) -> DispatchResult {369 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {370 stored_properties.try_scoped_set_from_iter(scope, properties)371 })372 .map_err(<CommonError<T>>::from)?;373374 Ok(())375 }376377 /// Add or edit auxiliary data for the property.378 ///379 /// - `f`: function that adds or edits auxiliary data.380 pub fn try_mutate_token_aux_property<R, E>(381 collection_id: CollectionId,382 token_id: TokenId,383 scope: PropertyScope,384 key: PropertyKey,385 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,386 ) -> Result<R, E> {387 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)388 }389390 /// Remove auxiliary data for the property.391 pub fn remove_token_aux_property(392 collection_id: CollectionId,393 token_id: TokenId,394 scope: PropertyScope,395 key: PropertyKey,396 ) {397 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));398 }399400 /// Get all auxiliary data in a given scope.401 ///402 /// Returns iterator over Property Key - Data pairs.403 pub fn iterate_token_aux_properties(404 collection_id: CollectionId,405 token_id: TokenId,406 scope: PropertyScope,407 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {408 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))409 }410411 /// Get ID of the last minted token412 pub fn current_token_id(collection_id: CollectionId) -> TokenId {413 TokenId(<TokensMinted<T>>::get(collection_id))414 }415}416417// unchecked calls skips any permission checks418impl<T: Config> Pallet<T> {419 /// Create NFT collection420 ///421 /// `init_collection` will take non-refundable deposit for collection creation.422 ///423 /// - `data`: Contains settings for collection limits and permissions.424 pub fn init_collection(425 owner: T::CrossAccountId,426 payer: T::CrossAccountId,427 data: CreateCollectionData<T::CrossAccountId>,428 ) -> Result<CollectionId, DispatchError> {429 <PalletCommon<T>>::init_collection(owner, payer, data)430 }431432 /// Destroy NFT collection433 ///434 /// `destroy_collection` will throw error if collection contains any tokens.435 /// Only owner can destroy collection.436 pub fn destroy_collection(437 collection: NonfungibleHandle<T>,438 sender: &T::CrossAccountId,439 ) -> DispatchResult {440 let id = collection.id;441442 if Self::collection_has_tokens(id) {443 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());444 }445446 // =========447448 PalletCommon::destroy_collection(collection.0, sender)?;449450 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);451 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);453 <TokensMinted<T>>::remove(id);454 <TokensBurnt<T>>::remove(id);455 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);456 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);457 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);458 Ok(())459 }460461 /// Burn NFT token462 ///463 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token464 /// if the token is nested.465 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.466 /// Also removes all corresponding properties and auxiliary properties.467 ///468 /// - `token`: Token that should be burned469 /// - `collection`: Collection that contains the token470 pub fn burn(471 collection: &NonfungibleHandle<T>,472 sender: &T::CrossAccountId,473 token: TokenId,474 ) -> DispatchResult {475 let token_data =476 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;477 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);478479 if collection.permissions.access() == AccessMode::AllowList {480 collection.check_allowlist(sender)?;481 }482483 if Self::token_has_children(collection.id, token) {484 return Err(<Error<T>>::CantBurnNftWithChildren.into());485 }486487 let burnt = <TokensBurnt<T>>::get(collection.id)488 .checked_add(1)489 .ok_or(ArithmeticError::Overflow)?;490491 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))492 .checked_sub(1)493 .ok_or(ArithmeticError::Overflow)?;494495 // =========496497 if balance == 0 {498 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));499 } else {500 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);501 }502503 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);504505 <Owned<T>>::remove((collection.id, &token_data.owner, token));506 <TokensBurnt<T>>::insert(collection.id, burnt);507 <TokenData<T>>::remove((collection.id, token));508 <TokenProperties<T>>::remove((collection.id, token));509 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);510 let old_spender = <Allowance<T>>::take((collection.id, token));511512 if let Some(old_spender) = old_spender {513 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(514 collection.id,515 token,516 token_data.owner.clone(),517 old_spender,518 0,519 ));520 }521522 <PalletEvm<T>>::deposit_log(523 ERC721Events::Transfer {524 from: *token_data.owner.as_eth(),525 to: H160::default(),526 token_id: token.into(),527 }528 .to_log(collection_id_to_address(collection.id)),529 );530 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(531 collection.id,532 token,533 token_data.owner,534 1,535 ));536 Ok(())537 }538539 /// Same as [`burn`] but burns all the tokens that are nested in the token first540 ///541 /// - `self_budget`: Limit for searching children in depth.542 /// - `breadth_budget`: Limit of breadth of searching children.543 ///544 /// [`burn`]: struct.Pallet.html#method.burn545 #[transactional]546 pub fn burn_recursively(547 collection: &NonfungibleHandle<T>,548 sender: &T::CrossAccountId,549 token: TokenId,550 self_budget: &dyn Budget,551 breadth_budget: &dyn Budget,552 ) -> DispatchResultWithPostInfo {553 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);554555 let current_token_account =556 T::CrossTokenAddressMapping::token_to_address(collection.id, token);557558 let mut weight = Weight::zero();559560 // This method is transactional, if user in fact doesn't have permissions to remove token -561 // tokens removed here will be restored after rejected transaction562 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {563 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);564 let PostDispatchInfo { actual_weight, .. } =565 <PalletStructure<T>>::burn_item_recursively(566 current_token_account.clone(),567 collection,568 token,569 self_budget,570 breadth_budget,571 )?;572 if let Some(actual_weight) = actual_weight {573 weight = weight.saturating_add(actual_weight);574 }575 }576577 Self::burn(collection, sender, token)?;578 DispatchResultWithPostInfo::Ok(PostDispatchInfo {579 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),580 pays_fee: Pays::Yes,581 })582 }583584 /// A batch operation to add, edit or remove properties for a token.585 ///586 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.587 ///588 /// All affected properties should have `mutable` permission589 /// to be **deleted** or to be **set more than once**,590 /// and the sender should have permission to edit those properties.591 ///592 /// This function fires an event for each property change.593 /// In case of an error, all the changes (including the events) will be reverted594 /// since the function is transactional.595 #[transactional]596 fn modify_token_properties(597 collection: &NonfungibleHandle<T>,598 sender: &T::CrossAccountId,599 token_id: TokenId,600 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,601 nesting_budget: &dyn Budget,602 ) -> DispatchResult {603 let mut property_writer =604 pallet_common::property_writer_for_existing_token(collection, sender);605606 property_writer.write_token_properties(607 sender,608 token_id,609 properties_updates,610 nesting_budget,611 erc::ERC721TokenEvent::TokenChanged {612 token_id: token_id.into(),613 }614 .to_log(T::ContractAddress::get()),615 )616 }617618 pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {619 let next_token_id = <TokensMinted<T>>::get(collection.id)620 .checked_add(1)621 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;622623 ensure!(624 collection.limits.token_limit() >= next_token_id,625 <CommonError<T>>::CollectionTokenLimitExceeded626 );627628 Ok(TokenId(next_token_id))629 }630631 /// Batch operation to add or edit properties for the token632 ///633 /// Same as [`modify_token_properties`] but doesn't allow to remove properties634 ///635 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties636 pub fn set_token_properties(637 collection: &NonfungibleHandle<T>,638 sender: &T::CrossAccountId,639 token_id: TokenId,640 properties: impl Iterator<Item = Property>,641 nesting_budget: &dyn Budget,642 ) -> DispatchResult {643 Self::modify_token_properties(644 collection,645 sender,646 token_id,647 properties.map(|p| (p.key, Some(p.value))),648 nesting_budget,649 )650 }651652 /// Add or edit single property for the token653 ///654 /// Calls [`set_token_properties`] internally655 ///656 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties657 pub fn set_token_property(658 collection: &NonfungibleHandle<T>,659 sender: &T::CrossAccountId,660 token_id: TokenId,661 property: Property,662 nesting_budget: &dyn Budget,663 ) -> DispatchResult {664 Self::set_token_properties(665 collection,666 sender,667 token_id,668 [property].into_iter(),669 nesting_budget,670 )671 }672673 /// Batch operation to remove properties from the token674 ///675 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties676 ///677 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties678 pub fn delete_token_properties(679 collection: &NonfungibleHandle<T>,680 sender: &T::CrossAccountId,681 token_id: TokenId,682 property_keys: impl Iterator<Item = PropertyKey>,683 nesting_budget: &dyn Budget,684 ) -> DispatchResult {685 Self::modify_token_properties(686 collection,687 sender,688 token_id,689 property_keys.into_iter().map(|key| (key, None)),690 nesting_budget,691 )692 }693694 /// Remove single property from the token695 ///696 /// Calls [`delete_token_properties`] internally697 ///698 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties699 pub fn delete_token_property(700 collection: &NonfungibleHandle<T>,701 sender: &T::CrossAccountId,702 token_id: TokenId,703 property_key: PropertyKey,704 nesting_budget: &dyn Budget,705 ) -> DispatchResult {706 Self::delete_token_properties(707 collection,708 sender,709 token_id,710 [property_key].into_iter(),711 nesting_budget,712 )713 }714715 /// Add or edit properties for the collection716 pub fn set_collection_properties(717 collection: &NonfungibleHandle<T>,718 sender: &T::CrossAccountId,719 properties: Vec<Property>,720 ) -> DispatchResult {721 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())722 }723724 /// Remove properties from the collection725 pub fn delete_collection_properties(726 collection: &CollectionHandle<T>,727 sender: &T::CrossAccountId,728 property_keys: Vec<PropertyKey>,729 ) -> DispatchResult {730 <PalletCommon<T>>::delete_collection_properties(731 collection,732 sender,733 property_keys.into_iter(),734 )735 }736737 /// Set property permissions for the token.738 ///739 /// Sender should be the owner or admin of token's collection.740 pub fn set_token_property_permissions(741 collection: &CollectionHandle<T>,742 sender: &T::CrossAccountId,743 property_permissions: Vec<PropertyKeyPermission>,744 ) -> DispatchResult {745 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)746 }747748 /// Set property permissions for the token with scope.749 ///750 /// Sender should be the owner or admin of token's collection.751 pub fn set_scoped_token_property_permissions(752 collection: &CollectionHandle<T>,753 sender: &T::CrossAccountId,754 scope: PropertyScope,755 property_permissions: Vec<PropertyKeyPermission>,756 ) -> DispatchResult {757 <PalletCommon<T>>::set_scoped_token_property_permissions(758 collection,759 sender,760 scope,761 property_permissions,762 )763 }764765 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {766 <PalletCommon<T>>::property_permissions(collection_id)767 }768769 pub fn check_token_immediate_ownership(770 collection: &NonfungibleHandle<T>,771 token: TokenId,772 possible_owner: &T::CrossAccountId,773 ) -> DispatchResult {774 let token_data =775 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;776 ensure!(777 &token_data.owner == possible_owner,778 <CommonError<T>>::NoPermission779 );780 Ok(())781 }782783 /// Transfer NFT token from one account to another.784 ///785 /// `from` account stops being the owner and `to` account becomes the owner of the token.786 /// If `to` is token than `to` becomes owner of the token and the token become nested.787 /// Unnests token from previous parent if it was nested before.788 /// Removes allowance for the token if there was any.789 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.790 ///791 /// - `nesting_budget`: Limit for token nesting depth792 pub fn transfer(793 collection: &NonfungibleHandle<T>,794 from: &T::CrossAccountId,795 to: &T::CrossAccountId,796 token: TokenId,797 nesting_budget: &dyn Budget,798 ) -> DispatchResultWithPostInfo {799 ensure!(800 collection.limits.transfers_enabled(),801 <CommonError<T>>::TransferNotAllowed802 );803804 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();805 let token_data =806 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;807 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);808809 if collection.permissions.access() == AccessMode::AllowList {810 collection.check_allowlist(from)?;811 collection.check_allowlist(to)?;812 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;813 }814 <PalletCommon<T>>::ensure_correct_receiver(to)?;815816 let balance_from = <AccountBalance<T>>::get((collection.id, from))817 .checked_sub(1)818 .ok_or(<CommonError<T>>::TokenValueTooLow)?;819 let balance_to = if from != to {820 let balance_to = <AccountBalance<T>>::get((collection.id, to))821 .checked_add(1)822 .ok_or(ArithmeticError::Overflow)?;823824 ensure!(825 balance_to < collection.limits.account_token_ownership_limit(),826 <CommonError<T>>::AccountTokenLimitExceeded,827 );828829 Some(balance_to)830 } else {831 None832 };833834 <PalletStructure<T>>::nest_if_sent_to_token(835 from.clone(),836 to,837 collection.id,838 token,839 nesting_budget,840 )?;841842 // =========843844 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);845846 <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });847848 if let Some(balance_to) = balance_to {849 // from != to850 if balance_from == 0 {851 <AccountBalance<T>>::remove((collection.id, from));852 } else {853 <AccountBalance<T>>::insert((collection.id, from), balance_from);854 }855 <AccountBalance<T>>::insert((collection.id, to), balance_to);856 <Owned<T>>::remove((collection.id, from, token));857 <Owned<T>>::insert((collection.id, to, token), true);858 }859 Self::set_allowance_unchecked(collection, from, token, None, true);860861 <PalletEvm<T>>::deposit_log(862 ERC721Events::Transfer {863 from: *from.as_eth(),864 to: *to.as_eth(),865 token_id: token.into(),866 }867 .to_log(collection_id_to_address(collection.id)),868 );869 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(870 collection.id,871 token,872 from.clone(),873 to.clone(),874 1,875 ));876877 Ok(PostDispatchInfo {878 actual_weight: Some(actual_weight),879 pays_fee: Pays::Yes,880 })881 }882883 /// Batch operation to mint multiple NFT tokens.884 ///885 /// The sender should be the owner/admin of the collection or collection should be configured886 /// to allow public minting.887 /// Throws if amount of tokens reached it's limit for the collection or if caller reached888 /// token ownership limit.889 ///890 /// - `data`: Contains list of token properties and users who will become the owners of the891 /// corresponging tokens.892 /// - `nesting_budget`: Limit for token nesting depth893 pub fn create_multiple_items(894 collection: &NonfungibleHandle<T>,895 sender: &T::CrossAccountId,896 data: Vec<CreateItemData<T>>,897 nesting_budget: &dyn Budget,898 ) -> DispatchResult {899 if !collection.is_owner_or_admin(sender) {900 ensure!(901 collection.permissions.mint_mode(),902 <CommonError<T>>::PublicMintingNotAllowed903 );904 collection.check_allowlist(sender)?;905906 for item in data.iter() {907 collection.check_allowlist(&item.owner)?;908 }909 }910911 for data in data.iter() {912 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;913 }914915 let first_token = <TokensMinted<T>>::get(collection.id);916 let tokens_minted = first_token917 .checked_add(data.len() as u32)918 .ok_or(ArithmeticError::Overflow)?;919 ensure!(920 tokens_minted <= collection.limits.token_limit(),921 <CommonError<T>>::CollectionTokenLimitExceeded922 );923924 let mut balances = BTreeMap::new();925 for data in &data {926 let balance = balances927 .entry(&data.owner)928 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));929 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;930931 ensure!(932 *balance <= collection.limits.account_token_ownership_limit(),933 <CommonError<T>>::AccountTokenLimitExceeded,934 );935 }936937 for (i, data) in data.iter().enumerate() {938 let token = TokenId(first_token + i as u32 + 1);939940 <PalletStructure<T>>::check_nesting(941 sender.clone(),942 &data.owner,943 collection.id,944 token,945 nesting_budget,946 )?;947 }948949 // =========950951 let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);952953 with_transaction(|| {954 for (i, data) in data.iter().enumerate() {955 let token = first_token + i as u32 + 1;956957 <TokenData<T>>::insert(958 (collection.id, token),959 ItemData {960 // const_data: data.const_data.clone(),961 owner: data.owner.clone(),962 },963 );964965 let token = TokenId(token);966967 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(968 &data.owner,969 collection.id,970 token,971 );972973 if let Err(e) = property_writer.write_token_properties(974 sender.conv_eq(&data.owner),975 token,976 data.properties.clone().into_iter(),977 erc::ERC721TokenEvent::TokenChanged {978 token_id: token.into(),979 }980 .to_log(T::ContractAddress::get()),981 ) {982 return TransactionOutcome::Rollback(Err(e));983 }984 }985 TransactionOutcome::Commit(Ok(()))986 })?;987988 <TokensMinted<T>>::insert(collection.id, tokens_minted);989 for (account, balance) in balances {990 <AccountBalance<T>>::insert((collection.id, account), balance);991 }992 for (i, data) in data.into_iter().enumerate() {993 let token = first_token + i as u32 + 1;994 <Owned<T>>::insert((collection.id, &data.owner, token), true);995996 <PalletEvm<T>>::deposit_log(997 ERC721Events::Transfer {998 from: H160::default(),999 to: *data.owner.as_eth(),1000 token_id: token.into(),1001 }1002 .to_log(collection_id_to_address(collection.id)),1003 );1004 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1005 collection.id,1006 TokenId(token),1007 data.owner.clone(),1008 1,1009 ));1010 }1011 Ok(())1012 }10131014 pub fn set_allowance_unchecked(1015 collection: &NonfungibleHandle<T>,1016 sender: &T::CrossAccountId,1017 token: TokenId,1018 spender: Option<&T::CrossAccountId>,1019 assume_implicit_eth: bool,1020 ) {1021 if let Some(spender) = spender {1022 let old_spender = <Allowance<T>>::get((collection.id, token));1023 <Allowance<T>>::insert((collection.id, token), spender);1024 // In ERC721 there is only one possible approved user of token, so we set1025 // approved user to spender1026 <PalletEvm<T>>::deposit_log(1027 ERC721Events::Approval {1028 owner: *sender.as_eth(),1029 approved: *spender.as_eth(),1030 token_id: token.into(),1031 }1032 .to_log(collection_id_to_address(collection.id)),1033 );1034 // In Unique chain, any token can have any amount of approved users, so we need to1035 // set allowance of old owner to 0, and allowance of new owner to 11036 if old_spender.as_ref() != Some(spender) {1037 if let Some(old_owner) = old_spender {1038 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1039 collection.id,1040 token,1041 sender.clone(),1042 old_owner,1043 0,1044 ));1045 }1046 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1047 collection.id,1048 token,1049 sender.clone(),1050 spender.clone(),1051 1,1052 ));1053 }1054 } else {1055 let old_spender = <Allowance<T>>::take((collection.id, token));1056 if !assume_implicit_eth {1057 // In ERC721 there is only one possible approved user of token, so we set1058 // approved user to zero address1059 <PalletEvm<T>>::deposit_log(1060 ERC721Events::Approval {1061 owner: *sender.as_eth(),1062 approved: H160::default(),1063 token_id: token.into(),1064 }1065 .to_log(collection_id_to_address(collection.id)),1066 );1067 }1068 // In Unique chain, any token can have any amount of approved users, so we need to1069 // set allowance of old owner to 01070 if let Some(old_spender) = old_spender {1071 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1072 collection.id,1073 token,1074 sender.clone(),1075 old_spender,1076 0,1077 ));1078 }1079 }1080 }10811082 pub fn get_allowance(1083 collection: &NonfungibleHandle<T>,1084 token_id: TokenId,1085 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1086 ensure!(1087 <TokenData<T>>::get((collection.id, token_id)).is_some(),1088 <CommonError<T>>::TokenNotFound1089 );1090 Ok(<Allowance<T>>::get((collection.id, token_id)))1091 }10921093 /// Set allowance for the spender to `transfer` or `burn` sender's token.1094 ///1095 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1096 pub fn set_allowance(1097 collection: &NonfungibleHandle<T>,1098 sender: &T::CrossAccountId,1099 token: TokenId,1100 spender: Option<&T::CrossAccountId>,1101 ) -> DispatchResult {1102 if collection.permissions.access() == AccessMode::AllowList {1103 collection.check_allowlist(sender)?;1104 if let Some(spender) = spender {1105 collection.check_allowlist(spender)?;1106 }1107 }11081109 if let Some(spender) = spender {1110 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1111 }11121113 let token_data =1114 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1115 if &token_data.owner != sender {1116 ensure!(1117 collection.ignores_owned_amount(sender),1118 <CommonError<T>>::CantApproveMoreThanOwned1119 );1120 }11211122 // =========11231124 Self::set_allowance_unchecked(collection, sender, token, spender, false);1125 Ok(())1126 }11271128 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1129 ///1130 /// - `from`: Address of sender's eth mirror.1131 /// - `to`: Adress of spender.1132 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1133 pub fn set_allowance_from(1134 collection: &NonfungibleHandle<T>,1135 sender: &T::CrossAccountId,1136 from: &T::CrossAccountId,1137 token: TokenId,1138 to: Option<&T::CrossAccountId>,1139 ) -> DispatchResult {1140 if collection.permissions.access() == AccessMode::AllowList {1141 collection.check_allowlist(sender)?;1142 collection.check_allowlist(from)?;1143 if let Some(to) = to {1144 collection.check_allowlist(to)?;1145 }1146 }11471148 if let Some(to) = to {1149 <PalletCommon<T>>::ensure_correct_receiver(to)?;1150 }11511152 ensure!(1153 sender.conv_eq(from),1154 <CommonError<T>>::AddressIsNotEthMirror1155 );11561157 let token_data =1158 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1159 if token_data.owner != *from {1160 ensure!(1161 collection.limits.owner_can_transfer()1162 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1163 <CommonError<T>>::CantApproveMoreThanOwned1164 );1165 }11661167 // =========11681169 Self::set_allowance_unchecked(collection, from, token, to, false);1170 Ok(())1171 }11721173 /// Checks allowance for the spender to use the token.1174 fn check_allowed(1175 collection: &NonfungibleHandle<T>,1176 spender: &T::CrossAccountId,1177 from: &T::CrossAccountId,1178 token: TokenId,1179 nesting_budget: &dyn Budget,1180 ) -> DispatchResult {1181 if spender.conv_eq(from) {1182 return Ok(());1183 }1184 if collection.permissions.access() == AccessMode::AllowList {1185 // `from`, `to` checked in [`transfer`]1186 collection.check_allowlist(spender)?;1187 }11881189 if collection.ignores_token_restrictions(spender) {1190 return Ok(());1191 }11921193 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1194 ensure!(1195 <PalletStructure<T>>::check_indirectly_owned(1196 spender.clone(),1197 source.0,1198 source.1,1199 None,1200 nesting_budget1201 )?,1202 <CommonError<T>>::ApprovedValueTooLow,1203 );1204 return Ok(());1205 }1206 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1207 return Ok(());1208 }1209 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1210 return Ok(());1211 }12121213 Err(<CommonError<T>>::ApprovedValueTooLow.into())1214 }12151216 /// Transfer NFT token from one account to another.1217 ///1218 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1219 /// The owner should set allowance for the spender to transfer token.1220 ///1221 /// [`transfer`]: struct.Pallet.html#method.transfer1222 pub fn transfer_from(1223 collection: &NonfungibleHandle<T>,1224 spender: &T::CrossAccountId,1225 from: &T::CrossAccountId,1226 to: &T::CrossAccountId,1227 token: TokenId,1228 nesting_budget: &dyn Budget,1229 ) -> DispatchResultWithPostInfo {1230 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12311232 // =========12331234 // Allowance is reset in [`transfer`]1235 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1236 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1237 result1238 }12391240 /// Burn NFT token for `from` account.1241 ///1242 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1243 /// set allowance for the spender to burn token.1244 ///1245 /// [`burn`]: struct.Pallet.html#method.burn1246 pub fn burn_from(1247 collection: &NonfungibleHandle<T>,1248 spender: &T::CrossAccountId,1249 from: &T::CrossAccountId,1250 token: TokenId,1251 nesting_budget: &dyn Budget,1252 ) -> DispatchResult {1253 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12541255 // =========12561257 Self::burn(collection, from, token)1258 }12591260 /// Check that `from` token could be nested in `under` token.1261 ///1262 pub fn check_nesting(1263 handle: &NonfungibleHandle<T>,1264 sender: T::CrossAccountId,1265 from: (CollectionId, TokenId),1266 under: TokenId,1267 nesting_budget: &dyn Budget,1268 ) -> DispatchResult {1269 let nesting = handle.permissions.nesting();12701271 #[cfg(not(feature = "runtime-benchmarks"))]1272 let permissive = false;1273 #[cfg(feature = "runtime-benchmarks")]1274 let permissive = nesting.permissive;12751276 if permissive {1277 ensure!(1278 <TokenData<T>>::contains_key((handle.id, under)),1279 <CommonError<T>>::TokenNotFound1280 );1281 } else if nesting.token_owner1282 && <PalletStructure<T>>::check_indirectly_owned(1283 sender.clone(),1284 handle.id,1285 under,1286 Some(from),1287 nesting_budget,1288 )? {1289 // Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1290 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1291 // token existence and ouroboros checks are done in `get_checked_topmost_owner`1292 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1293 handle.id,1294 under,1295 Some(from),1296 nesting_budget,1297 )?1298 .ok_or(<CommonError<T>>::TokenNotFound)?;1299 } else {1300 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1301 }13021303 if let Some(whitelist) = &nesting.restricted {1304 ensure!(1305 whitelist.contains(&from.0),1306 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1307 );1308 }1309 Ok(())1310 }13111312 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1313 if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1314 <TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1315 }1316 }13171318 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1319 if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1320 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1321 }1322 }13231324 fn collection_has_tokens(collection_id: CollectionId) -> bool {1325 <TokenData<T>>::iter_prefix((collection_id,))1326 .next()1327 .is_some()1328 }13291330 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1331 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1332 .next()1333 .is_some()1334 }13351336 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1337 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1338 .map(|((child_collection_id, child_id), _)| TokenChild {1339 collection: child_collection_id,1340 token: child_id,1341 })1342 .collect()1343 }13441345 /// Mint single NFT token.1346 ///1347 /// Delegated to [`create_multiple_items`]1348 ///1349 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1350 pub fn create_item(1351 collection: &NonfungibleHandle<T>,1352 sender: &T::CrossAccountId,1353 data: CreateItemData<T>,1354 nesting_budget: &dyn Budget,1355 ) -> DispatchResult {1356 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1357 }13581359 /// Sets or unsets the approval of a given operator.1360 ///1361 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1362 /// - `owner`: Token owner1363 /// - `operator`: Operator1364 /// - `approve`: Should operator status be granted or revoked?1365 pub fn set_allowance_for_all(1366 collection: &NonfungibleHandle<T>,1367 owner: &T::CrossAccountId,1368 operator: &T::CrossAccountId,1369 approve: bool,1370 ) -> DispatchResult {1371 <PalletCommon<T>>::set_allowance_for_all(1372 collection,1373 owner,1374 operator,1375 approve,1376 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1377 ERC721Events::ApprovalForAll {1378 owner: *owner.as_eth(),1379 operator: *operator.as_eth(),1380 approved: approve,1381 }1382 .to_log(collection_id_to_address(collection.id)),1383 )1384 }13851386 /// Tells whether the given `owner` approves the `operator`.1387 pub fn allowance_for_all(1388 collection: &NonfungibleHandle<T>,1389 owner: &T::CrossAccountId,1390 operator: &T::CrossAccountId,1391 ) -> bool {1392 <CollectionAllowance<T>>::get((collection.id, owner, operator))1393 }13941395 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1396 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1397 properties.recompute_consumed_space();1398 });13991400 Ok(())1401 }1402}pallets/refungible/src/common.rsdiffbeforeafterboth--- a/pallets/refungible/src/common.rs
+++ b/pallets/refungible/src/common.rs
@@ -435,16 +435,15 @@
)
}
- fn get_token_properties_map(&self, token_id: TokenId) -> up_data_structs::TokenProperties {
+ fn get_token_properties_raw(
+ &self,
+ token_id: TokenId,
+ ) -> Option<up_data_structs::TokenProperties> {
<TokenProperties<T>>::get((self.id, token_id))
}
- fn set_token_properties_map(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
- <TokenProperties<T>>::set((self.id, token_id), map)
- }
-
- fn properties_exist(&self, token: TokenId) -> bool {
- <TokenProperties<T>>::contains_key((self.id, token))
+ fn set_token_properties_raw(&self, token_id: TokenId, map: up_data_structs::TokenProperties) {
+ <TokenProperties<T>>::insert((self.id, token_id), map)
}
fn check_nesting(
@@ -514,13 +513,15 @@
}
fn token_property(&self, token_id: TokenId, key: &PropertyKey) -> Option<PropertyValue> {
- <Pallet<T>>::token_properties((self.id, token_id))
+ <Pallet<T>>::token_properties((self.id, token_id))?
.get(key)
.cloned()
}
fn token_properties(&self, token_id: TokenId, keys: Option<Vec<PropertyKey>>) -> Vec<Property> {
- let properties = <Pallet<T>>::token_properties((self.id, token_id));
+ let Some(properties) = <Pallet<T>>::token_properties((self.id, token_id)) else {
+ return vec![];
+ };
keys.map(|keys| {
keys.into_iter()
pallets/refungible/src/erc.rsdiffbeforeafterboth--- a/pallets/refungible/src/erc.rs
+++ b/pallets/refungible/src/erc.rs
@@ -283,7 +283,8 @@
.try_into()
.map_err(|_| "key too long")?;
- let props = <TokenProperties<T>>::get((self.id, token_id));
+ let props =
+ <TokenProperties<T>>::get((self.id, token_id)).ok_or("Token properties not found")?;
let prop = props.get(&key).ok_or("key not found")?;
Ok(prop.to_vec().into())
pallets/refungible/src/lib.rsdiffbeforeafterboth--- a/pallets/refungible/src/lib.rs
+++ b/pallets/refungible/src/lib.rs
@@ -106,8 +106,8 @@
use up_data_structs::{
AccessMode, budget::Budget, CollectionId, CreateCollectionData, mapping::TokenAddressMapping,
MAX_REFUNGIBLE_PIECES, Property, PropertyKey, PropertyKeyPermission, PropertyScope,
- PropertyValue, TokenId, TrySetProperty, PropertiesPermissionMap,
- CreateRefungibleExMultipleOwners, TokenOwnerError, TokenProperties as TokenPropertiesT,
+ PropertyValue, TokenId, PropertiesPermissionMap, CreateRefungibleExMultipleOwners,
+ TokenOwnerError, TokenProperties as TokenPropertiesT,
};
pub use pallet::*;
@@ -175,7 +175,7 @@
pub type TokenProperties<T: Config> = StorageNMap<
Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),
Value = TokenPropertiesT,
- QueryKind = ValueQuery,
+ QueryKind = OptionQuery,
>;
/// Total amount of pieces for token
@@ -292,35 +292,7 @@
/// - `token`: Token ID.
pub fn token_exists(collection: &RefungibleHandle<T>, token: TokenId) -> bool {
<TotalSupply<T>>::contains_key((collection.id, token))
- }
-
- pub fn set_scoped_token_property(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- property: Property,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {
- properties.try_scoped_set(scope, property.key, property.value)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
}
-
- pub fn set_scoped_token_properties(
- collection_id: CollectionId,
- token_id: TokenId,
- scope: PropertyScope,
- properties: impl Iterator<Item = Property>,
- ) -> DispatchResult {
- TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {
- stored_properties.try_scoped_set_from_iter(scope, properties)
- })
- .map_err(<CommonError<T>>::from)?;
-
- Ok(())
- }
}
// unchecked calls skips any permission checks
@@ -1426,7 +1398,9 @@
pub fn repair_item(collection: &RefungibleHandle<T>, token: TokenId) -> DispatchResult {
<TokenProperties<T>>::mutate((collection.id, token), |properties| {
- properties.recompute_consumed_space();
+ if let Some(properties) = properties {
+ properties.recompute_consumed_space();
+ }
});
Ok(())