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, TokenChild, AuxPropertyValue, PropertiesPermissionMap,106 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 = OptionQuery,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 /// Add or edit auxiliary data for the property.346 ///347 /// - `f`: function that adds or edits auxiliary data.348 pub fn try_mutate_token_aux_property<R, E>(349 collection_id: CollectionId,350 token_id: TokenId,351 scope: PropertyScope,352 key: PropertyKey,353 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,354 ) -> Result<R, E> {355 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)356 }357358 /// Remove auxiliary data for the property.359 pub fn remove_token_aux_property(360 collection_id: CollectionId,361 token_id: TokenId,362 scope: PropertyScope,363 key: PropertyKey,364 ) {365 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));366 }367368 /// Get all auxiliary data in a given scope.369 ///370 /// Returns iterator over Property Key - Data pairs.371 pub fn iterate_token_aux_properties(372 collection_id: CollectionId,373 token_id: TokenId,374 scope: PropertyScope,375 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {376 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))377 }378379 /// Get ID of the last minted token380 pub fn current_token_id(collection_id: CollectionId) -> TokenId {381 TokenId(<TokensMinted<T>>::get(collection_id))382 }383}384385// unchecked calls skips any permission checks386impl<T: Config> Pallet<T> {387 /// Create NFT collection388 ///389 /// `init_collection` will take non-refundable deposit for collection creation.390 ///391 /// - `data`: Contains settings for collection limits and permissions.392 pub fn init_collection(393 owner: T::CrossAccountId,394 payer: T::CrossAccountId,395 data: CreateCollectionData<T::CrossAccountId>,396 ) -> Result<CollectionId, DispatchError> {397 <PalletCommon<T>>::init_collection(owner, payer, data)398 }399400 /// Destroy NFT collection401 ///402 /// `destroy_collection` will throw error if collection contains any tokens.403 /// Only owner can destroy collection.404 pub fn destroy_collection(405 collection: NonfungibleHandle<T>,406 sender: &T::CrossAccountId,407 ) -> DispatchResult {408 let id = collection.id;409410 if Self::collection_has_tokens(id) {411 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());412 }413414 // =========415416 PalletCommon::destroy_collection(collection.0, sender)?;417418 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);419 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);420 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);421 <TokensMinted<T>>::remove(id);422 <TokensBurnt<T>>::remove(id);423 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);424 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);425 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);426 Ok(())427 }428429 /// Burn NFT token430 ///431 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token432 /// if the token is nested.433 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.434 /// Also removes all corresponding properties and auxiliary properties.435 ///436 /// - `token`: Token that should be burned437 /// - `collection`: Collection that contains the token438 pub fn burn(439 collection: &NonfungibleHandle<T>,440 sender: &T::CrossAccountId,441 token: TokenId,442 ) -> DispatchResult {443 let token_data =444 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;445 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);446447 if collection.permissions.access() == AccessMode::AllowList {448 collection.check_allowlist(sender)?;449 }450451 if Self::token_has_children(collection.id, token) {452 return Err(<Error<T>>::CantBurnNftWithChildren.into());453 }454455 let burnt = <TokensBurnt<T>>::get(collection.id)456 .checked_add(1)457 .ok_or(ArithmeticError::Overflow)?;458459 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))460 .checked_sub(1)461 .ok_or(ArithmeticError::Overflow)?;462463 // =========464465 if balance == 0 {466 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));467 } else {468 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);469 }470471 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);472473 <Owned<T>>::remove((collection.id, &token_data.owner, token));474 <TokensBurnt<T>>::insert(collection.id, burnt);475 <TokenData<T>>::remove((collection.id, token));476 <TokenProperties<T>>::remove((collection.id, token));477 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);478 let old_spender = <Allowance<T>>::take((collection.id, token));479480 if let Some(old_spender) = old_spender {481 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(482 collection.id,483 token,484 token_data.owner.clone(),485 old_spender,486 0,487 ));488 }489490 <PalletEvm<T>>::deposit_log(491 ERC721Events::Transfer {492 from: *token_data.owner.as_eth(),493 to: H160::default(),494 token_id: token.into(),495 }496 .to_log(collection_id_to_address(collection.id)),497 );498 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(499 collection.id,500 token,501 token_data.owner,502 1,503 ));504 Ok(())505 }506507 /// Same as [`burn`] but burns all the tokens that are nested in the token first508 ///509 /// - `self_budget`: Limit for searching children in depth.510 /// - `breadth_budget`: Limit of breadth of searching children.511 ///512 /// [`burn`]: struct.Pallet.html#method.burn513 #[transactional]514 pub fn burn_recursively(515 collection: &NonfungibleHandle<T>,516 sender: &T::CrossAccountId,517 token: TokenId,518 self_budget: &dyn Budget,519 breadth_budget: &dyn Budget,520 ) -> DispatchResultWithPostInfo {521 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);522523 let current_token_account =524 T::CrossTokenAddressMapping::token_to_address(collection.id, token);525526 let mut weight = Weight::zero();527528 // This method is transactional, if user in fact doesn't have permissions to remove token -529 // tokens removed here will be restored after rejected transaction530 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {531 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);532 let PostDispatchInfo { actual_weight, .. } =533 <PalletStructure<T>>::burn_item_recursively(534 current_token_account.clone(),535 collection,536 token,537 self_budget,538 breadth_budget,539 )?;540 if let Some(actual_weight) = actual_weight {541 weight = weight.saturating_add(actual_weight);542 }543 }544545 Self::burn(collection, sender, token)?;546 DispatchResultWithPostInfo::Ok(PostDispatchInfo {547 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),548 pays_fee: Pays::Yes,549 })550 }551552 /// A batch operation to add, edit or remove properties for a token.553 ///554 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.555 ///556 /// All affected properties should have `mutable` permission557 /// to be **deleted** or to be **set more than once**,558 /// and the sender should have permission to edit those properties.559 ///560 /// This function fires an event for each property change.561 /// In case of an error, all the changes (including the events) will be reverted562 /// since the function is transactional.563 #[transactional]564 fn modify_token_properties(565 collection: &NonfungibleHandle<T>,566 sender: &T::CrossAccountId,567 token_id: TokenId,568 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,569 nesting_budget: &dyn Budget,570 ) -> DispatchResult {571 let mut property_writer =572 pallet_common::property_writer_for_existing_token(collection, sender);573574 property_writer.write_token_properties(575 sender,576 token_id,577 properties_updates,578 nesting_budget,579 erc::ERC721TokenEvent::TokenChanged {580 token_id: token_id.into(),581 }582 .to_log(T::ContractAddress::get()),583 )584 }585586 pub fn next_token_id(collection: &NonfungibleHandle<T>) -> Result<TokenId, DispatchError> {587 let next_token_id = <TokensMinted<T>>::get(collection.id)588 .checked_add(1)589 .ok_or(<CommonError<T>>::CollectionTokenLimitExceeded)?;590591 ensure!(592 collection.limits.token_limit() >= next_token_id,593 <CommonError<T>>::CollectionTokenLimitExceeded594 );595596 Ok(TokenId(next_token_id))597 }598599 /// Batch operation to add or edit properties for the token600 ///601 /// Same as [`modify_token_properties`] but doesn't allow to remove properties602 ///603 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties604 pub fn set_token_properties(605 collection: &NonfungibleHandle<T>,606 sender: &T::CrossAccountId,607 token_id: TokenId,608 properties: impl Iterator<Item = Property>,609 nesting_budget: &dyn Budget,610 ) -> DispatchResult {611 Self::modify_token_properties(612 collection,613 sender,614 token_id,615 properties.map(|p| (p.key, Some(p.value))),616 nesting_budget,617 )618 }619620 /// Add or edit single property for the token621 ///622 /// Calls [`set_token_properties`] internally623 ///624 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties625 pub fn set_token_property(626 collection: &NonfungibleHandle<T>,627 sender: &T::CrossAccountId,628 token_id: TokenId,629 property: Property,630 nesting_budget: &dyn Budget,631 ) -> DispatchResult {632 Self::set_token_properties(633 collection,634 sender,635 token_id,636 [property].into_iter(),637 nesting_budget,638 )639 }640641 /// Batch operation to remove properties from the token642 ///643 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties644 ///645 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties646 pub fn delete_token_properties(647 collection: &NonfungibleHandle<T>,648 sender: &T::CrossAccountId,649 token_id: TokenId,650 property_keys: impl Iterator<Item = PropertyKey>,651 nesting_budget: &dyn Budget,652 ) -> DispatchResult {653 Self::modify_token_properties(654 collection,655 sender,656 token_id,657 property_keys.into_iter().map(|key| (key, None)),658 nesting_budget,659 )660 }661662 /// Remove single property from the token663 ///664 /// Calls [`delete_token_properties`] internally665 ///666 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties667 pub fn delete_token_property(668 collection: &NonfungibleHandle<T>,669 sender: &T::CrossAccountId,670 token_id: TokenId,671 property_key: PropertyKey,672 nesting_budget: &dyn Budget,673 ) -> DispatchResult {674 Self::delete_token_properties(675 collection,676 sender,677 token_id,678 [property_key].into_iter(),679 nesting_budget,680 )681 }682683 /// Add or edit properties for the collection684 pub fn set_collection_properties(685 collection: &NonfungibleHandle<T>,686 sender: &T::CrossAccountId,687 properties: Vec<Property>,688 ) -> DispatchResult {689 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())690 }691692 /// Remove properties from the collection693 pub fn delete_collection_properties(694 collection: &CollectionHandle<T>,695 sender: &T::CrossAccountId,696 property_keys: Vec<PropertyKey>,697 ) -> DispatchResult {698 <PalletCommon<T>>::delete_collection_properties(699 collection,700 sender,701 property_keys.into_iter(),702 )703 }704705 /// Set property permissions for the token.706 ///707 /// Sender should be the owner or admin of token's collection.708 pub fn set_token_property_permissions(709 collection: &CollectionHandle<T>,710 sender: &T::CrossAccountId,711 property_permissions: Vec<PropertyKeyPermission>,712 ) -> DispatchResult {713 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)714 }715716 /// Set property permissions for the token with scope.717 ///718 /// Sender should be the owner or admin of token's collection.719 pub fn set_scoped_token_property_permissions(720 collection: &CollectionHandle<T>,721 sender: &T::CrossAccountId,722 scope: PropertyScope,723 property_permissions: Vec<PropertyKeyPermission>,724 ) -> DispatchResult {725 <PalletCommon<T>>::set_scoped_token_property_permissions(726 collection,727 sender,728 scope,729 property_permissions,730 )731 }732733 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {734 <PalletCommon<T>>::property_permissions(collection_id)735 }736737 pub fn check_token_immediate_ownership(738 collection: &NonfungibleHandle<T>,739 token: TokenId,740 possible_owner: &T::CrossAccountId,741 ) -> DispatchResult {742 let token_data =743 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;744 ensure!(745 &token_data.owner == possible_owner,746 <CommonError<T>>::NoPermission747 );748 Ok(())749 }750751 /// Transfer NFT token from one account to another.752 ///753 /// `from` account stops being the owner and `to` account becomes the owner of the token.754 /// If `to` is token than `to` becomes owner of the token and the token become nested.755 /// Unnests token from previous parent if it was nested before.756 /// Removes allowance for the token if there was any.757 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.758 ///759 /// - `nesting_budget`: Limit for token nesting depth760 pub fn transfer(761 collection: &NonfungibleHandle<T>,762 from: &T::CrossAccountId,763 to: &T::CrossAccountId,764 token: TokenId,765 nesting_budget: &dyn Budget,766 ) -> DispatchResultWithPostInfo {767 ensure!(768 collection.limits.transfers_enabled(),769 <CommonError<T>>::TransferNotAllowed770 );771772 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();773 let token_data =774 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;775 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);776777 if collection.permissions.access() == AccessMode::AllowList {778 collection.check_allowlist(from)?;779 collection.check_allowlist(to)?;780 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;781 }782 <PalletCommon<T>>::ensure_correct_receiver(to)?;783784 let balance_from = <AccountBalance<T>>::get((collection.id, from))785 .checked_sub(1)786 .ok_or(<CommonError<T>>::TokenValueTooLow)?;787 let balance_to = if from != to {788 let balance_to = <AccountBalance<T>>::get((collection.id, to))789 .checked_add(1)790 .ok_or(ArithmeticError::Overflow)?;791792 ensure!(793 balance_to < collection.limits.account_token_ownership_limit(),794 <CommonError<T>>::AccountTokenLimitExceeded,795 );796797 Some(balance_to)798 } else {799 None800 };801802 <PalletStructure<T>>::nest_if_sent_to_token(803 from.clone(),804 to,805 collection.id,806 token,807 nesting_budget,808 )?;809810 // =========811812 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);813814 <TokenData<T>>::insert((collection.id, token), ItemData { owner: to.clone() });815816 if let Some(balance_to) = balance_to {817 // from != to818 if balance_from == 0 {819 <AccountBalance<T>>::remove((collection.id, from));820 } else {821 <AccountBalance<T>>::insert((collection.id, from), balance_from);822 }823 <AccountBalance<T>>::insert((collection.id, to), balance_to);824 <Owned<T>>::remove((collection.id, from, token));825 <Owned<T>>::insert((collection.id, to, token), true);826 }827 Self::set_allowance_unchecked(collection, from, token, None, true);828829 <PalletEvm<T>>::deposit_log(830 ERC721Events::Transfer {831 from: *from.as_eth(),832 to: *to.as_eth(),833 token_id: token.into(),834 }835 .to_log(collection_id_to_address(collection.id)),836 );837 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(838 collection.id,839 token,840 from.clone(),841 to.clone(),842 1,843 ));844845 Ok(PostDispatchInfo {846 actual_weight: Some(actual_weight),847 pays_fee: Pays::Yes,848 })849 }850851 /// Batch operation to mint multiple NFT tokens.852 ///853 /// The sender should be the owner/admin of the collection or collection should be configured854 /// to allow public minting.855 /// Throws if amount of tokens reached it's limit for the collection or if caller reached856 /// token ownership limit.857 ///858 /// - `data`: Contains list of token properties and users who will become the owners of the859 /// corresponging tokens.860 /// - `nesting_budget`: Limit for token nesting depth861 pub fn create_multiple_items(862 collection: &NonfungibleHandle<T>,863 sender: &T::CrossAccountId,864 data: Vec<CreateItemData<T>>,865 nesting_budget: &dyn Budget,866 ) -> DispatchResult {867 if !collection.is_owner_or_admin(sender) {868 ensure!(869 collection.permissions.mint_mode(),870 <CommonError<T>>::PublicMintingNotAllowed871 );872 collection.check_allowlist(sender)?;873874 for item in data.iter() {875 collection.check_allowlist(&item.owner)?;876 }877 }878879 for data in data.iter() {880 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;881 }882883 let first_token = <TokensMinted<T>>::get(collection.id);884 let tokens_minted = first_token885 .checked_add(data.len() as u32)886 .ok_or(ArithmeticError::Overflow)?;887 ensure!(888 tokens_minted <= collection.limits.token_limit(),889 <CommonError<T>>::CollectionTokenLimitExceeded890 );891892 let mut balances = BTreeMap::new();893 for data in &data {894 let balance = balances895 .entry(&data.owner)896 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));897 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;898899 ensure!(900 *balance <= collection.limits.account_token_ownership_limit(),901 <CommonError<T>>::AccountTokenLimitExceeded,902 );903 }904905 for (i, data) in data.iter().enumerate() {906 let token = TokenId(first_token + i as u32 + 1);907908 <PalletStructure<T>>::check_nesting(909 sender.clone(),910 &data.owner,911 collection.id,912 token,913 nesting_budget,914 )?;915 }916917 // =========918919 let mut property_writer = pallet_common::property_writer_for_new_token(collection, sender);920921 with_transaction(|| {922 for (i, data) in data.iter().enumerate() {923 let token = first_token + i as u32 + 1;924925 <TokenData<T>>::insert(926 (collection.id, token),927 ItemData {928 // const_data: data.const_data.clone(),929 owner: data.owner.clone(),930 },931 );932933 let token = TokenId(token);934935 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(936 &data.owner,937 collection.id,938 token,939 );940941 if let Err(e) = property_writer.write_token_properties(942 sender.conv_eq(&data.owner),943 token,944 data.properties.clone().into_iter(),945 erc::ERC721TokenEvent::TokenChanged {946 token_id: token.into(),947 }948 .to_log(T::ContractAddress::get()),949 ) {950 return TransactionOutcome::Rollback(Err(e));951 }952 }953 TransactionOutcome::Commit(Ok(()))954 })?;955956 <TokensMinted<T>>::insert(collection.id, tokens_minted);957 for (account, balance) in balances {958 <AccountBalance<T>>::insert((collection.id, account), balance);959 }960 for (i, data) in data.into_iter().enumerate() {961 let token = first_token + i as u32 + 1;962 <Owned<T>>::insert((collection.id, &data.owner, token), true);963964 <PalletEvm<T>>::deposit_log(965 ERC721Events::Transfer {966 from: H160::default(),967 to: *data.owner.as_eth(),968 token_id: token.into(),969 }970 .to_log(collection_id_to_address(collection.id)),971 );972 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(973 collection.id,974 TokenId(token),975 data.owner.clone(),976 1,977 ));978 }979 Ok(())980 }981982 pub fn set_allowance_unchecked(983 collection: &NonfungibleHandle<T>,984 sender: &T::CrossAccountId,985 token: TokenId,986 spender: Option<&T::CrossAccountId>,987 assume_implicit_eth: bool,988 ) {989 if let Some(spender) = spender {990 let old_spender = <Allowance<T>>::get((collection.id, token));991 <Allowance<T>>::insert((collection.id, token), spender);992 // In ERC721 there is only one possible approved user of token, so we set993 // approved user to spender994 <PalletEvm<T>>::deposit_log(995 ERC721Events::Approval {996 owner: *sender.as_eth(),997 approved: *spender.as_eth(),998 token_id: token.into(),999 }1000 .to_log(collection_id_to_address(collection.id)),1001 );1002 // In Unique chain, any token can have any amount of approved users, so we need to1003 // set allowance of old owner to 0, and allowance of new owner to 11004 if old_spender.as_ref() != Some(spender) {1005 if let Some(old_owner) = old_spender {1006 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1007 collection.id,1008 token,1009 sender.clone(),1010 old_owner,1011 0,1012 ));1013 }1014 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1015 collection.id,1016 token,1017 sender.clone(),1018 spender.clone(),1019 1,1020 ));1021 }1022 } else {1023 let old_spender = <Allowance<T>>::take((collection.id, token));1024 if !assume_implicit_eth {1025 // In ERC721 there is only one possible approved user of token, so we set1026 // approved user to zero address1027 <PalletEvm<T>>::deposit_log(1028 ERC721Events::Approval {1029 owner: *sender.as_eth(),1030 approved: H160::default(),1031 token_id: token.into(),1032 }1033 .to_log(collection_id_to_address(collection.id)),1034 );1035 }1036 // In Unique chain, any token can have any amount of approved users, so we need to1037 // set allowance of old owner to 01038 if let Some(old_spender) = old_spender {1039 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1040 collection.id,1041 token,1042 sender.clone(),1043 old_spender,1044 0,1045 ));1046 }1047 }1048 }10491050 pub fn get_allowance(1051 collection: &NonfungibleHandle<T>,1052 token_id: TokenId,1053 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1054 ensure!(1055 <TokenData<T>>::get((collection.id, token_id)).is_some(),1056 <CommonError<T>>::TokenNotFound1057 );1058 Ok(<Allowance<T>>::get((collection.id, token_id)))1059 }10601061 /// Set allowance for the spender to `transfer` or `burn` sender's token.1062 ///1063 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1064 pub fn set_allowance(1065 collection: &NonfungibleHandle<T>,1066 sender: &T::CrossAccountId,1067 token: TokenId,1068 spender: Option<&T::CrossAccountId>,1069 ) -> DispatchResult {1070 if collection.permissions.access() == AccessMode::AllowList {1071 collection.check_allowlist(sender)?;1072 if let Some(spender) = spender {1073 collection.check_allowlist(spender)?;1074 }1075 }10761077 if let Some(spender) = spender {1078 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1079 }10801081 let token_data =1082 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1083 if &token_data.owner != sender {1084 ensure!(1085 collection.ignores_owned_amount(sender),1086 <CommonError<T>>::CantApproveMoreThanOwned1087 );1088 }10891090 // =========10911092 Self::set_allowance_unchecked(collection, sender, token, spender, false);1093 Ok(())1094 }10951096 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1097 ///1098 /// - `from`: Address of sender's eth mirror.1099 /// - `to`: Adress of spender.1100 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1101 pub fn set_allowance_from(1102 collection: &NonfungibleHandle<T>,1103 sender: &T::CrossAccountId,1104 from: &T::CrossAccountId,1105 token: TokenId,1106 to: Option<&T::CrossAccountId>,1107 ) -> DispatchResult {1108 if collection.permissions.access() == AccessMode::AllowList {1109 collection.check_allowlist(sender)?;1110 collection.check_allowlist(from)?;1111 if let Some(to) = to {1112 collection.check_allowlist(to)?;1113 }1114 }11151116 if let Some(to) = to {1117 <PalletCommon<T>>::ensure_correct_receiver(to)?;1118 }11191120 ensure!(1121 sender.conv_eq(from),1122 <CommonError<T>>::AddressIsNotEthMirror1123 );11241125 let token_data =1126 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1127 if token_data.owner != *from {1128 ensure!(1129 collection.limits.owner_can_transfer()1130 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1131 <CommonError<T>>::CantApproveMoreThanOwned1132 );1133 }11341135 // =========11361137 Self::set_allowance_unchecked(collection, from, token, to, false);1138 Ok(())1139 }11401141 /// Checks allowance for the spender to use the token.1142 fn check_allowed(1143 collection: &NonfungibleHandle<T>,1144 spender: &T::CrossAccountId,1145 from: &T::CrossAccountId,1146 token: TokenId,1147 nesting_budget: &dyn Budget,1148 ) -> DispatchResult {1149 if spender.conv_eq(from) {1150 return Ok(());1151 }1152 if collection.permissions.access() == AccessMode::AllowList {1153 // `from`, `to` checked in [`transfer`]1154 collection.check_allowlist(spender)?;1155 }11561157 if collection.ignores_token_restrictions(spender) {1158 return Ok(());1159 }11601161 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1162 ensure!(1163 <PalletStructure<T>>::check_indirectly_owned(1164 spender.clone(),1165 source.0,1166 source.1,1167 None,1168 nesting_budget1169 )?,1170 <CommonError<T>>::ApprovedValueTooLow,1171 );1172 return Ok(());1173 }1174 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1175 return Ok(());1176 }1177 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1178 return Ok(());1179 }11801181 Err(<CommonError<T>>::ApprovedValueTooLow.into())1182 }11831184 /// Transfer NFT token from one account to another.1185 ///1186 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1187 /// The owner should set allowance for the spender to transfer token.1188 ///1189 /// [`transfer`]: struct.Pallet.html#method.transfer1190 pub fn transfer_from(1191 collection: &NonfungibleHandle<T>,1192 spender: &T::CrossAccountId,1193 from: &T::CrossAccountId,1194 to: &T::CrossAccountId,1195 token: TokenId,1196 nesting_budget: &dyn Budget,1197 ) -> DispatchResultWithPostInfo {1198 Self::check_allowed(collection, spender, from, token, nesting_budget)?;11991200 // =========12011202 // Allowance is reset in [`transfer`]1203 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1204 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1205 result1206 }12071208 /// Burn NFT token for `from` account.1209 ///1210 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1211 /// set allowance for the spender to burn token.1212 ///1213 /// [`burn`]: struct.Pallet.html#method.burn1214 pub fn burn_from(1215 collection: &NonfungibleHandle<T>,1216 spender: &T::CrossAccountId,1217 from: &T::CrossAccountId,1218 token: TokenId,1219 nesting_budget: &dyn Budget,1220 ) -> DispatchResult {1221 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12221223 // =========12241225 Self::burn(collection, from, token)1226 }12271228 /// Check that `from` token could be nested in `under` token.1229 ///1230 pub fn check_nesting(1231 handle: &NonfungibleHandle<T>,1232 sender: T::CrossAccountId,1233 from: (CollectionId, TokenId),1234 under: TokenId,1235 nesting_budget: &dyn Budget,1236 ) -> DispatchResult {1237 let nesting = handle.permissions.nesting();12381239 #[cfg(not(feature = "runtime-benchmarks"))]1240 let permissive = false;1241 #[cfg(feature = "runtime-benchmarks")]1242 let permissive = nesting.permissive;12431244 if permissive {1245 ensure!(1246 <TokenData<T>>::contains_key((handle.id, under)),1247 <CommonError<T>>::TokenNotFound1248 );1249 } else if nesting.token_owner1250 && <PalletStructure<T>>::check_indirectly_owned(1251 sender.clone(),1252 handle.id,1253 under,1254 Some(from),1255 nesting_budget,1256 )? {1257 // Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1258 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1259 // token existence and ouroboros checks are done in `get_checked_topmost_owner`1260 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1261 handle.id,1262 under,1263 Some(from),1264 nesting_budget,1265 )?1266 .ok_or(<CommonError<T>>::TokenNotFound)?;1267 } else {1268 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1269 }12701271 if let Some(whitelist) = &nesting.restricted {1272 ensure!(1273 whitelist.contains(&from.0),1274 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1275 );1276 }1277 Ok(())1278 }12791280 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1281 if to_nest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1282 <TokenChildren<T>>::insert((under.0, under.1, to_nest), true);1283 }1284 }12851286 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1287 if to_unnest.0 != pallet_common::NATIVE_FUNGIBLE_COLLECTION_ID {1288 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1289 }1290 }12911292 fn collection_has_tokens(collection_id: CollectionId) -> bool {1293 <TokenData<T>>::iter_prefix((collection_id,))1294 .next()1295 .is_some()1296 }12971298 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1299 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1300 .next()1301 .is_some()1302 }13031304 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1305 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1306 .map(|((child_collection_id, child_id), _)| TokenChild {1307 collection: child_collection_id,1308 token: child_id,1309 })1310 .collect()1311 }13121313 /// Mint single NFT token.1314 ///1315 /// Delegated to [`create_multiple_items`]1316 ///1317 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1318 pub fn create_item(1319 collection: &NonfungibleHandle<T>,1320 sender: &T::CrossAccountId,1321 data: CreateItemData<T>,1322 nesting_budget: &dyn Budget,1323 ) -> DispatchResult {1324 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1325 }13261327 /// Sets or unsets the approval of a given operator.1328 ///1329 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1330 /// - `owner`: Token owner1331 /// - `operator`: Operator1332 /// - `approve`: Should operator status be granted or revoked?1333 pub fn set_allowance_for_all(1334 collection: &NonfungibleHandle<T>,1335 owner: &T::CrossAccountId,1336 operator: &T::CrossAccountId,1337 approve: bool,1338 ) -> DispatchResult {1339 <PalletCommon<T>>::set_allowance_for_all(1340 collection,1341 owner,1342 operator,1343 approve,1344 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1345 ERC721Events::ApprovalForAll {1346 owner: *owner.as_eth(),1347 operator: *operator.as_eth(),1348 approved: approve,1349 }1350 .to_log(collection_id_to_address(collection.id)),1351 )1352 }13531354 /// Tells whether the given `owner` approves the `operator`.1355 pub fn allowance_for_all(1356 collection: &NonfungibleHandle<T>,1357 owner: &T::CrossAccountId,1358 operator: &T::CrossAccountId,1359 ) -> bool {1360 <CollectionAllowance<T>>::get((collection.id, owner, operator))1361 }13621363 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1364 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1365 if let Some(properties) = properties {1366 properties.recompute_consumed_space();1367 }1368 });13691370 Ok(())1371 }1372}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(())