difftreelog
Merge pull request #907 from UniqueNetwork/feature/nft-transfer-correct-weight
in: master
feat(weight): added benchs for decompose weight
23 files changed
Cargo.lockdiffbeforeafterboth--- a/Cargo.lock
+++ b/Cargo.lock
@@ -6262,7 +6262,7 @@
[[package]]
name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
dependencies = [
"ethereum",
"evm-coder",
@@ -6558,7 +6558,7 @@
[[package]]
name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
dependencies = [
"evm-coder",
"frame-benchmarking",
@@ -6814,7 +6814,7 @@
[[package]]
name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
dependencies = [
"evm-coder",
"frame-benchmarking",
pallets/app-promotion/src/lib.rsdiffbeforeafterboth--- a/pallets/app-promotion/src/lib.rs
+++ b/pallets/app-promotion/src/lib.rs
@@ -845,7 +845,6 @@
/// - `staker`: staker account.
pub fn total_staked_by_id(staker: impl EncodeLike<T::AccountId>) -> Option<BalanceOf<T>> {
let staked = Staked::<T>::iter_prefix((staker,))
- .into_iter()
.fold(<BalanceOf<T>>::default(), |acc, (_, (amount, _))| {
acc + amount
});
@@ -864,7 +863,6 @@
staker: impl EncodeLike<T::AccountId>,
) -> Option<Vec<(T::BlockNumber, BalanceOf<T>)>> {
let mut staked = Staked::<T>::iter_prefix((staker,))
- .into_iter()
.map(|(block, (amount, _))| (block, amount))
.collect::<Vec<_>>();
staked.sort_by_key(|(block, _)| *block);
@@ -883,12 +881,6 @@
Self::total_staked_by_id(s.as_sub())
})
}
-
- // pub fn cross_id_locked_balance(staker: T::CrossAccountId) -> BalanceOf<T> {
- // Self::get_locked_balance(staker.as_sub())
- // .map(|l| l.amount)
- // .unwrap_or_default()
- // }
/// Returns all relay block numbers when stake was made,
/// the amount of the stake.
pallets/common/CHANGELOG.mddiffbeforeafterboth--- a/pallets/common/CHANGELOG.md
+++ b/pallets/common/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.14] - 2023-03-28
+
+### Added
+
+- Added benchmark to check if user is contained in AllowList (`check_accesslist()`).
+
## [0.1.13] - 2023-01-20
### Changed
pallets/common/Cargo.tomldiffbeforeafterboth--- a/pallets/common/Cargo.toml
+++ b/pallets/common/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-common"
-version = "0.1.13"
+version = "0.1.14"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/common/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/common/src/benchmarking.rs
+++ b/pallets/common/src/benchmarking.rs
@@ -22,8 +22,9 @@
use frame_benchmarking::{benchmarks, account};
use up_data_structs::{
CollectionMode, CollectionFlags, CreateCollectionData, CollectionId, Property, PropertyKey,
- PropertyValue, CollectionPermissions, NestingPermissions, MAX_COLLECTION_NAME_LENGTH,
- MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH, MAX_PROPERTIES_PER_ITEM,
+ PropertyValue, CollectionPermissions, NestingPermissions, AccessMode,
+ MAX_COLLECTION_NAME_LENGTH, MAX_COLLECTION_DESCRIPTION_LENGTH, MAX_TOKEN_PREFIX_LENGTH,
+ MAX_PROPERTIES_PER_ITEM,
};
use frame_support::{
traits::{Currency, Get},
@@ -193,4 +194,28 @@
<Pallet<T>>::set_collection_properties(&collection, &owner, props.into_iter())?;
let to_delete = (0..b).map(|p| property_key(p as usize)).collect::<Vec<_>>();
}: {<Pallet<T>>::delete_collection_properties(&collection, &owner, to_delete.into_iter())?}
+
+ check_accesslist{
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ sender: cross_from_sub(owner);
+ };
+
+ let mut collection_handle = <CollectionHandle<T>>::try_get(collection.id)?;
+ <Pallet<T>>::update_permissions(
+ &sender,
+ &mut collection_handle,
+ CollectionPermissions { access: Some(AccessMode::AllowList), ..Default::default() }
+ )?;
+
+ <Pallet<T>>::toggle_allowlist(
+ &collection,
+ &sender,
+ &sender,
+ true,
+ )?;
+
+ assert_eq!(collection_handle.permissions.access(), AccessMode::AllowList);
+
+ }: {collection_handle.check_allowlist(&sender)?;}
}
pallets/common/src/helpers.rsdiffbeforeafterboth--- /dev/null
+++ b/pallets/common/src/helpers.rs
@@ -0,0 +1,30 @@
+//! # Helpers module
+//!
+//! The module contains helpers.
+//!
+use frame_support::{
+ pallet_prelude::DispatchResultWithPostInfo,
+ weights::Weight,
+ dispatch::{DispatchErrorWithPostInfo, PostDispatchInfo},
+};
+
+/// Add weight for a `DispatchResultWithPostInfo`
+///
+/// - `target`: DispatchResultWithPostInfo to which weight will be added
+/// - `additional_weight`: Weight to be added
+pub fn add_weight_to_post_info(target: &mut DispatchResultWithPostInfo, additional_weight: Weight) {
+ match target {
+ Ok(PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ })
+ | Err(DispatchErrorWithPostInfo {
+ post_info: PostDispatchInfo {
+ actual_weight: Some(weight),
+ ..
+ },
+ ..
+ }) => *weight += additional_weight,
+ _ => {}
+ }
+}
pallets/common/src/lib.rsdiffbeforeafterboth--- a/pallets/common/src/lib.rs
+++ b/pallets/common/src/lib.rs
@@ -92,9 +92,9 @@
pub mod dispatch;
pub mod erc;
pub mod eth;
+pub mod helpers;
#[allow(missing_docs)]
pub mod weights;
-
/// Weight info.
pub type SelfWeightOf<T> = <T as Config>::WeightInfo;
pallets/common/src/weights.rsdiffbeforeafterboth--- a/pallets/common/src/weights.rs
+++ b/pallets/common/src/weights.rs
@@ -36,6 +36,7 @@
pub trait WeightInfo {
fn set_collection_properties(b: u32, ) -> Weight;
fn delete_collection_properties(b: u32, ) -> Weight;
+ fn check_accesslist() -> Weight;
}
/// Weights for pallet_common using the Substrate node and recommended hardware.
@@ -69,6 +70,16 @@
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
+ /// Storage: Common Allowlist (r:1 w:0)
+ /// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+ fn check_accesslist() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `340`
+ // Estimated: `2545`
+ // Minimum execution time: 2_887_000 picoseconds.
+ Weight::from_parts(3_072_000, 2545)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
+ }
}
// For backwards compatibility and tests
@@ -101,5 +112,15 @@
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
+ /// Storage: Common Allowlist (r:1 w:0)
+ /// Proof: Common Allowlist (max_values: None, max_size: Some(70), added: 2545, mode: MaxEncodedLen)
+ fn check_accesslist() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `340`
+ // Estimated: `2545`
+ // Minimum execution time: 2_887_000 picoseconds.
+ Weight::from_parts(3_072_000, 2545)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
+ }
}
pallets/foreign-assets/src/impl_fungibles.rsdiffbeforeafterboth--- a/pallets/foreign-assets/src/impl_fungibles.rs
+++ b/pallets/foreign-assets/src/impl_fungibles.rs
@@ -452,7 +452,8 @@
&T::CrossAccountId::from_sub(dest.clone()),
amount.into(),
&Value::new(0),
- )?;
+ )
+ .map_err(|e| e.error)?;
Ok(amount)
}
pallets/fungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/fungible/CHANGELOG.md
+++ b/pallets/fungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.11] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
## [0.1.10] - 2023-02-01
### Added
pallets/fungible/Cargo.tomldiffbeforeafterboth--- a/pallets/fungible/Cargo.toml
+++ b/pallets/fungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-fungible"
-version = "0.1.10"
+version = "0.1.11"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/fungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/fungible/src/benchmarking.rs
+++ b/pallets/fungible/src/benchmarking.rs
@@ -66,7 +66,7 @@
<Pallet<T>>::create_item(&collection, &owner, (burner.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::burn(&collection, &burner, 100)?}
- transfer {
+ transfer_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; to: cross_sub;
@@ -92,14 +92,22 @@
<Pallet<T>>::create_item(&collection, &owner, (owner_eth.clone(), 200), &Unlimited)?;
}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, &spender, 100)?}
- transfer_from {
+ check_allowed_raw {
bench_init!{
owner: sub; collection: collection(owner);
- owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
};
<Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
<Pallet<T>>::set_allowance(&collection, &sender, &spender, 200)?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, 100, &Unlimited)?}
+ }: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, 200, &Unlimited)?;}
+
+ set_allowance_unchecked_raw {
+ bench_init!{
+ owner: sub; collection: collection(owner);
+ owner: cross_from_sub; sender: cross_sub; spender: cross_sub;
+ };
+ <Pallet<T>>::create_item(&collection, &owner, (sender.clone(), 200), &Unlimited)?;
+ }: {<Pallet<T>>::set_allowance_unchecked(&collection, &sender, &spender, 200);}
burn_from {
bench_init!{
pallets/fungible/src/common.rsdiffbeforeafterboth--- a/pallets/fungible/src/common.rs
+++ b/pallets/fungible/src/common.rs
@@ -22,7 +22,7 @@
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _,
+ weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
};
use pallet_structure::Error as StructureError;
use sp_runtime::ArithmeticError;
@@ -78,7 +78,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer()
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
@@ -90,7 +90,9 @@
}
fn transfer_from() -> Weight {
- <SelfWeightOf<T>>::transfer_from()
+ Self::transfer()
+ + <SelfWeightOf<T>>::check_allowed_raw()
+ + <SelfWeightOf<T>>::set_allowance_unchecked_raw()
}
fn burn_from() -> Weight {
@@ -232,10 +234,7 @@
<Error<T>>::FungibleItemsHaveNoId
);
- with_weight(
- <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget),
- <CommonWeights<T>>::transfer(),
- )
+ <Pallet<T>>::transfer(self, &from, &to, amount, nesting_budget)
}
fn approve(
@@ -289,10 +288,7 @@
<Error<T>>::FungibleItemsHaveNoId
);
- with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget),
- <CommonWeights<T>>::transfer_from(),
- )
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, amount, nesting_budget)
}
fn burn_from(
pallets/fungible/src/erc.rsdiffbeforeafterboth--- a/pallets/fungible/src/erc.rs
+++ b/pallets/fungible/src/erc.rs
@@ -26,6 +26,7 @@
CollectionHandle,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall},
eth::CrossAddress,
+ CommonWeightInfo as _,
};
use sp_std::vec::Vec;
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
@@ -39,7 +40,7 @@
use crate::{
Allowance, Balance, Config, FungibleHandle, Pallet, TotalSupply, SelfWeightOf,
- weights::WeightInfo,
+ weights::WeightInfo, common::CommonWeights,
};
frontier_contract! {
@@ -99,7 +100,7 @@
let balance = <Balance<T>>::get((self.id, owner));
Ok(balance.into())
}
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer(&mut self, caller: Caller, to: Address, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -112,7 +113,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: Caller,
@@ -129,7 +130,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(true)
}
#[weight(<SelfWeightOf<T>>::approve())]
@@ -201,7 +202,7 @@
let budget = self
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::create_item(&self, &caller, (to, amount), &budget)
+ <Pallet<T>>::create_item(self, &caller, (to, amount), &budget)
.map_err(dispatch_to_evm::<T>)?;
Ok(true)
}
@@ -289,7 +290,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer_cross(&mut self, caller: Caller, to: CrossAddress, amount: U256) -> Result<bool> {
let caller = T::CrossAccountId::from_eth(caller);
let to = to.into_sub_cross_account::<T>()?;
@@ -302,7 +303,7 @@
Ok(true)
}
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from_cross(
&mut self,
caller: Caller,
@@ -319,7 +320,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, amount, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(true)
}
pallets/fungible/src/lib.rsdiffbeforeafterboth--- a/pallets/fungible/src/lib.rs
+++ b/pallets/fungible/src/lib.rs
@@ -80,7 +80,11 @@
use core::ops::Deref;
use evm_coder::ToLog;
-use frame_support::ensure;
+use frame_support::{
+ ensure,
+ pallet_prelude::{DispatchResultWithPostInfo, Pays},
+ dispatch::PostDispatchInfo,
+};
use pallet_evm::account::CrossAccountId;
use up_data_structs::{
AccessMode, CollectionId, CollectionFlags, TokenId, CreateCollectionData,
@@ -88,7 +92,8 @@
};
use pallet_common::{
Error as CommonError, Event as CommonEvent, Pallet as PalletCommon,
- eth::collection_id_to_address,
+ eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,
+ weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,
};
use pallet_evm::Pallet as PalletEvm;
use pallet_structure::Pallet as PalletStructure;
@@ -96,7 +101,7 @@
use sp_core::H160;
use sp_runtime::{ArithmeticError, DispatchError, DispatchResult};
use sp_std::{collections::btree_map::BTreeMap, vec::Vec};
-
+use weights::WeightInfo;
pub use pallet::*;
use crate::erc::ERC20Events;
@@ -389,18 +394,20 @@
to: &T::CrossAccountId,
amount: u128,
nesting_budget: &dyn Budget,
- ) -> DispatchResult {
+ ) -> DispatchResultWithPostInfo {
ensure!(
collection.limits.transfers_enabled(),
<CommonError<T>>::TransferNotAllowed,
);
+ let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();
+
if collection.permissions.access() == AccessMode::AllowList {
collection.check_allowlist(from)?;
collection.check_allowlist(to)?;
+ actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;
}
<PalletCommon<T>>::ensure_correct_receiver(to)?;
-
let balance_from = <Balance<T>>::get((collection.id, from))
.checked_sub(amount)
.ok_or(<CommonError<T>>::TokenValueTooLow)?;
@@ -451,7 +458,11 @@
to.clone(),
amount,
));
- Ok(())
+
+ Ok(PostDispatchInfo {
+ actual_weight: Some(actual_weight),
+ pays_fee: Pays::Yes,
+ })
}
/// Minting tokens for multiple IDs.
@@ -464,8 +475,8 @@
nesting_budget: &dyn Budget,
) -> DispatchResult {
let total_supply = data
- .iter()
- .map(|(_, v)| *v)
+ .values()
+ .copied()
.try_fold(<TotalSupply<T>>::get(collection.id), |acc, v| {
acc.checked_add(v)
})
@@ -718,7 +729,6 @@
/// Same as the [`transfer`][`Pallet::transfer`] but spender doesn't needs to be an owner of the token pieces.
/// The owner should set allowance for the spender to transfer pieces.
/// See [`set_allowance`][`Pallet::set_allowance`] for more details.
-
pub fn transfer_from(
collection: &FungibleHandle<T>,
spender: &T::CrossAccountId,
@@ -726,16 +736,23 @@
to: &T::CrossAccountId,
amount: u128,
nesting_budget: &dyn Budget,
- ) -> DispatchResult {
+ ) -> DispatchResultWithPostInfo {
let allowance = Self::check_allowed(collection, spender, from, amount, nesting_budget)?;
// =========
- Self::transfer(collection, from, to, amount, nesting_budget)?;
+ let mut result = Self::transfer(collection, from, to, amount, nesting_budget);
+ add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());
+ result?;
+
if let Some(allowance) = allowance {
Self::set_allowance_unchecked(collection, from, spender, allowance);
+ add_weight_to_post_info(
+ &mut result,
+ <SelfWeightOf<T>>::set_allowance_unchecked_raw(),
+ )
}
- Ok(())
+ result
}
/// Burn fungible tokens from the account.
pallets/fungible/src/weights.rsdiffbeforeafterboth--- a/pallets/fungible/src/weights.rs
+++ b/pallets/fungible/src/weights.rs
@@ -37,10 +37,11 @@
fn create_item() -> Weight;
fn create_multiple_items_ex(b: u32, ) -> Weight;
fn burn_item() -> Weight;
- fn transfer() -> Weight;
+ fn transfer_raw() -> Weight;
fn approve() -> Weight;
fn approve_from() -> Weight;
- fn transfer_from() -> Weight;
+ fn check_allowed_raw() -> Weight;
+ fn set_allowance_unchecked_raw() -> Weight;
fn burn_from() -> Weight;
}
@@ -94,12 +95,12 @@
}
/// Storage: Fungible Balance (r:2 w:2)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `182`
// Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
+ // Minimum execution time: 6_678_000 picoseconds.
+ Weight::from_parts(7_151_000, 5104)
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(2_u64))
}
@@ -129,19 +130,26 @@
.saturating_add(T::DbWeight::get().reads(1_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
- /// Storage: Fungible Allowance (r:1 w:1)
+ /// Storage: Fungible Allowance (r:1 w:0)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `300`
- // Estimated: `7672`
- // Minimum execution time: 21_667_000 picoseconds.
- Weight::from_parts(22_166_000, 7672)
- .saturating_add(T::DbWeight::get().reads(3_u64))
- .saturating_add(T::DbWeight::get().writes(3_u64))
+ // Measured: `210`
+ // Estimated: `2568`
+ // Minimum execution time: 2_842_000 picoseconds.
+ Weight::from_parts(3_077_000, 2568)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
}
+ /// Storage: Fungible Allowance (r:0 w:1)
+ /// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+ fn set_allowance_unchecked_raw() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `0`
+ // Estimated: `0`
+ // Minimum execution time: 2_532_000 picoseconds.
+ Weight::from_parts(2_680_000, 0)
+ .saturating_add(T::DbWeight::get().writes(1_u64))
+ }
/// Storage: Fungible Allowance (r:1 w:1)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
/// Storage: Fungible TotalSupply (r:1 w:1)
@@ -208,12 +216,12 @@
}
/// Storage: Fungible Balance (r:2 w:2)
/// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `182`
// Estimated: `5104`
- // Minimum execution time: 13_832_000 picoseconds.
- Weight::from_parts(14_064_000, 5104)
+ // Minimum execution time: 6_678_000 picoseconds.
+ Weight::from_parts(7_151_000, 5104)
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(2_u64))
}
@@ -243,18 +251,25 @@
.saturating_add(RocksDbWeight::get().reads(1_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
- /// Storage: Fungible Allowance (r:1 w:1)
+ /// Storage: Fungible Allowance (r:1 w:0)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
- /// Storage: Fungible Balance (r:2 w:2)
- /// Proof: Fungible Balance (max_values: None, max_size: Some(77), added: 2552, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `300`
- // Estimated: `7672`
- // Minimum execution time: 21_667_000 picoseconds.
- Weight::from_parts(22_166_000, 7672)
- .saturating_add(RocksDbWeight::get().reads(3_u64))
- .saturating_add(RocksDbWeight::get().writes(3_u64))
+ // Measured: `210`
+ // Estimated: `2568`
+ // Minimum execution time: 2_842_000 picoseconds.
+ Weight::from_parts(3_077_000, 2568)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
+ }
+ /// Storage: Fungible Allowance (r:0 w:1)
+ /// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
+ fn set_allowance_unchecked_raw() -> Weight {
+ // Proof Size summary in bytes:
+ // Measured: `0`
+ // Estimated: `0`
+ // Minimum execution time: 2_532_000 picoseconds.
+ Weight::from_parts(2_680_000, 0)
+ .saturating_add(RocksDbWeight::get().writes(1_u64))
}
/// Storage: Fungible Allowance (r:1 w:1)
/// Proof: Fungible Allowance (max_values: None, max_size: Some(93), added: 2568, mode: MaxEncodedLen)
pallets/nonfungible/CHANGELOG.mddiffbeforeafterboth--- a/pallets/nonfungible/CHANGELOG.md
+++ b/pallets/nonfungible/CHANGELOG.md
@@ -4,6 +4,12 @@
<!-- bureaucrate goes here -->
+## [0.1.14] - 2023-03-28
+
+### Fixed
+
+- The weight of `transfer` and `transfer_from`.
+
## [0.1.13] - 2023-01-20
### Fixed
pallets/nonfungible/Cargo.tomldiffbeforeafterboth--- a/pallets/nonfungible/Cargo.toml
+++ b/pallets/nonfungible/Cargo.toml
@@ -2,7 +2,7 @@
edition = "2021"
license = "GPLv3"
name = "pallet-nonfungible"
-version = "0.1.13"
+version = "0.1.14"
[dependencies]
# Note: `package = "parity-scale-codec"` must be supplied since the `Encode` macro searches for it.
pallets/nonfungible/src/benchmarking.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/benchmarking.rs
+++ b/pallets/nonfungible/src/benchmarking.rs
@@ -121,7 +121,7 @@
}
}: {<Pallet<T>>::burn_recursively(&collection, &burner, item, &Unlimited, &Unlimited)?}
- transfer {
+ transfer_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; receiver: cross_sub;
@@ -146,14 +146,14 @@
let item = create_max_item(&collection, &owner, owner_eth.clone())?;
}: {<Pallet<T>>::set_allowance_from(&collection, &sender, &owner_eth, item, Some(&spender))?}
- transfer_from {
+ check_allowed_raw {
bench_init!{
owner: sub; collection: collection(owner);
owner: cross_from_sub; sender: cross_sub; spender: cross_sub; receiver: cross_sub;
};
let item = create_max_item(&collection, &owner, sender.clone())?;
<Pallet<T>>::set_allowance(&collection, &sender, item, Some(&spender))?;
- }: {<Pallet<T>>::transfer_from(&collection, &spender, &sender, &receiver, item, &Unlimited)?}
+ }: {<Pallet<T>>::check_allowed(&collection, &spender, &sender, item, &Unlimited)?}
burn_from {
bench_init!{
pallets/nonfungible/src/common.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/common.rs
+++ b/pallets/nonfungible/src/common.rs
@@ -23,7 +23,7 @@
};
use pallet_common::{
CommonCollectionOperations, CommonWeightInfo, RefungibleExtensions, with_weight,
- weights::WeightInfo as _,
+ weights::WeightInfo as _, SelfWeightOf as PalletCommonWeightOf,
};
use sp_runtime::DispatchError;
use sp_std::{vec::Vec, vec};
@@ -91,7 +91,7 @@
}
fn transfer() -> Weight {
- <SelfWeightOf<T>>::transfer()
+ <SelfWeightOf<T>>::transfer_raw() + <PalletCommonWeightOf<T>>::check_accesslist() * 2
}
fn approve() -> Weight {
@@ -103,7 +103,7 @@
}
fn transfer_from() -> Weight {
- <SelfWeightOf<T>>::transfer_from()
+ Self::transfer() + <SelfWeightOf<T>>::check_allowed_raw()
}
fn burn_from() -> Weight {
@@ -325,10 +325,7 @@
) -> DispatchResultWithPostInfo {
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
- with_weight(
- <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget),
- <CommonWeights<T>>::transfer(),
- )
+ <Pallet<T>>::transfer(self, &from, &to, token, nesting_budget)
} else {
<Pallet<T>>::check_token_immediate_ownership(self, token, &from)?;
Ok(().into())
@@ -386,10 +383,7 @@
ensure!(amount <= 1, <Error<T>>::NonfungibleItemsHaveNoAmount);
if amount == 1 {
- with_weight(
- <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget),
- <CommonWeights<T>>::transfer_from(),
- )
+ <Pallet<T>>::transfer_from(self, &sender, &from, &to, token, nesting_budget)
} else {
<Pallet<T>>::check_allowed(self, &sender, &from, token, nesting_budget)?;
pallets/nonfungible/src/erc.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/erc.rs
+++ b/pallets/nonfungible/src/erc.rs
@@ -39,6 +39,7 @@
CollectionHandle, CollectionPropertyPermissions, CommonCollectionOperations,
erc::{CommonEvmHandler, PrecompileResult, CollectionCall, static_property::key},
eth::{self, TokenUri},
+ CommonWeightInfo,
};
use pallet_evm::{account::CrossAccountId, PrecompileHandle};
use pallet_evm_coder_substrate::call;
@@ -47,7 +48,7 @@
use crate::{
AccountBalance, Config, CreateItemData, NonfungibleHandle, Pallet, TokenData, TokensMinted,
- TokenProperties, SelfWeightOf, weights::WeightInfo,
+ TokenProperties, SelfWeightOf, weights::WeightInfo, common::CommonWeights,
};
/// Nft events.
@@ -458,7 +459,7 @@
/// @param from The current owner of the NFT
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer_from())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from(
&mut self,
caller: Caller,
@@ -475,7 +476,7 @@
.weight_calls_budget(<StructureWeight<T>>::find_parent());
<Pallet<T>>::transfer_from(self, &caller, &from, &to, token, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -824,7 +825,7 @@
/// is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer(&mut self, caller: Caller, to: Address, token_id: U256) -> Result<()> {
let caller = T::CrossAccountId::from_eth(caller);
let to = T::CrossAccountId::from_eth(to);
@@ -833,7 +834,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -842,7 +844,7 @@
/// is the zero address. Throws if `tokenId` is not a valid NFT.
/// @param to The new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer())]
fn transfer_cross(
&mut self,
caller: Caller,
@@ -856,7 +858,8 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
- <Pallet<T>>::transfer(self, &caller, &to, token, &budget).map_err(dispatch_to_evm::<T>)?;
+ <Pallet<T>>::transfer(self, &caller, &to, token, &budget)
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
@@ -866,7 +869,7 @@
/// @param from Cross acccount address of current owner
/// @param to Cross acccount address of new owner
/// @param tokenId The NFT to transfer
- #[weight(<SelfWeightOf<T>>::transfer())]
+ #[weight(<CommonWeights<T>>::transfer_from())]
fn transfer_from_cross(
&mut self,
caller: Caller,
@@ -882,7 +885,7 @@
.recorder
.weight_calls_budget(<StructureWeight<T>>::find_parent());
Pallet::<T>::transfer_from(self, &caller, &from, &to, token_id, &budget)
- .map_err(dispatch_to_evm::<T>)?;
+ .map_err(|e| dispatch_to_evm::<T>(e.error))?;
Ok(())
}
pallets/nonfungible/src/lib.rsdiffbeforeafterboth1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//! Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//! an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//! it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//! attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//! with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//! Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,105 PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address,112};113use pallet_structure::{Pallet as PalletStructure, Error as StructureError};114use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};115use sp_core::{Get, H160};116use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};117use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};118use core::ops::Deref;119use codec::{Encode, Decode, MaxEncodedLen};120use scale_info::TypeInfo;121122pub use pallet::*;123use weights::WeightInfo;124#[cfg(feature = "runtime-benchmarks")]125pub mod benchmarking;126pub mod common;127pub mod erc;128pub mod weights;129130pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;131pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;132133/// Token data, stored independently from other data used to describe it134/// for the convenience of database access. Notably contains the owner account address.135#[struct_versioning::versioned(version = 2, upper)]136#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]137pub struct ItemData<CrossAccountId> {138 #[version(..2)]139 pub const_data: BoundedVec<u8, CustomDataLimit>,140141 #[version(..2)]142 pub variable_data: BoundedVec<u8, CustomDataLimit>,143144 pub owner: CrossAccountId,145}146147#[frame_support::pallet]148pub mod pallet {149 use super::*;150 use frame_support::{151 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,152 };153 use frame_system::pallet_prelude::*;154 use up_data_structs::{CollectionId, TokenId};155 use super::weights::WeightInfo;156157 #[pallet::error]158 pub enum Error<T> {159 /// Not Nonfungible item data used to mint in Nonfungible collection.160 NotNonfungibleDataUsedToMintFungibleCollectionToken,161 /// Used amount > 1 with NFT162 NonfungibleItemsHaveNoAmount,163 /// Unable to burn NFT with children164 CantBurnNftWithChildren,165 }166167 #[pallet::config]168 pub trait Config:169 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config170 {171 type WeightInfo: WeightInfo;172 }173174 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);175176 #[pallet::pallet]177 #[pallet::storage_version(STORAGE_VERSION)]178 pub struct Pallet<T>(_);179180 /// Total amount of minted tokens in a collection.181 #[pallet::storage]182 pub type TokensMinted<T: Config> =183 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;184185 /// Amount of burnt tokens in a collection.186 #[pallet::storage]187 pub type TokensBurnt<T: Config> =188 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;189190 /// Token data, used to partially describe a token.191 #[pallet::storage]192 pub type TokenData<T: Config> = StorageNMap<193 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),194 Value = ItemData<T::CrossAccountId>,195 QueryKind = OptionQuery,196 >;197198 /// Map of key-value pairs, describing the metadata of a token.199 #[pallet::storage]200 #[pallet::getter(fn token_properties)]201 pub type TokenProperties<T: Config> = StorageNMap<202 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),203 Value = TokenPropertiesT,204 QueryKind = ValueQuery,205 >;206207 /// Custom data of a token that is serialized to bytes,208 /// primarily reserved for on-chain operations,209 /// normally obscured from the external users.210 ///211 /// Auxiliary properties are slightly different from212 /// usual [`TokenProperties`] due to an unlimited number213 /// and separately stored and written-to key-value pairs.214 ///215 /// Currently unused.216 #[pallet::storage]217 #[pallet::getter(fn token_aux_property)]218 pub type TokenAuxProperties<T: Config> = StorageNMap<219 Key = (220 Key<Twox64Concat, CollectionId>,221 Key<Twox64Concat, TokenId>,222 Key<Twox64Concat, PropertyScope>,223 Key<Twox64Concat, PropertyKey>,224 ),225 Value = AuxPropertyValue,226 QueryKind = OptionQuery,227 >;228229 /// Used to enumerate tokens owned by account.230 #[pallet::storage]231 pub type Owned<T: Config> = StorageNMap<232 Key = (233 Key<Twox64Concat, CollectionId>,234 Key<Blake2_128Concat, T::CrossAccountId>,235 Key<Twox64Concat, TokenId>,236 ),237 Value = bool,238 QueryKind = ValueQuery,239 >;240241 /// Used to enumerate token's children.242 #[pallet::storage]243 #[pallet::getter(fn token_children)]244 pub type TokenChildren<T: Config> = StorageNMap<245 Key = (246 Key<Twox64Concat, CollectionId>,247 Key<Twox64Concat, TokenId>,248 Key<Twox64Concat, (CollectionId, TokenId)>,249 ),250 Value = bool,251 QueryKind = ValueQuery,252 >;253254 /// Amount of tokens owned by an account in a collection.255 #[pallet::storage]256 pub type AccountBalance<T: Config> = StorageNMap<257 Key = (258 Key<Twox64Concat, CollectionId>,259 Key<Blake2_128Concat, T::CrossAccountId>,260 ),261 Value = u32,262 QueryKind = ValueQuery,263 >;264265 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.266 #[pallet::storage]267 pub type Allowance<T: Config> = StorageNMap<268 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),269 Value = T::CrossAccountId,270 QueryKind = OptionQuery,271 >;272273 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.274 #[pallet::storage]275 pub type CollectionAllowance<T: Config> = StorageNMap<276 Key = (277 Key<Twox64Concat, CollectionId>,278 Key<Blake2_128Concat, T::CrossAccountId>,279 Key<Blake2_128Concat, T::CrossAccountId>,280 ),281 Value = bool,282 QueryKind = ValueQuery,283 >;284285 /// Upgrade from the old schema to properties.286 #[pallet::hooks]287 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {288 fn on_runtime_upgrade() -> Weight {289 StorageVersion::new(1).put::<Pallet<T>>();290291 Weight::zero()292 }293 }294}295296pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);297impl<T: Config> NonfungibleHandle<T> {298 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {299 Self(inner)300 }301 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {302 self.0303 }304 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {305 &mut self.0306 }307}308309impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {310 fn recorder(&self) -> &SubstrateRecorder<T> {311 self.0.recorder()312 }313 fn into_recorder(self) -> SubstrateRecorder<T> {314 self.0.into_recorder()315 }316}317impl<T: Config> Deref for NonfungibleHandle<T> {318 type Target = pallet_common::CollectionHandle<T>;319320 fn deref(&self) -> &Self::Target {321 &self.0322 }323}324325impl<T: Config> Pallet<T> {326 /// Get number of NFT tokens in collection.327 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {328 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)329 }330331 /// Check that NFT token exists.332 ///333 /// - `token`: Token ID.334 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {335 <TokenData<T>>::contains_key((collection.id, token))336 }337338 /// Set the token property with the scope.339 ///340 /// - `property`: Contains key-value pair.341 pub fn set_scoped_token_property(342 collection_id: CollectionId,343 token_id: TokenId,344 scope: PropertyScope,345 property: Property,346 ) -> DispatchResult {347 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {348 properties.try_scoped_set(scope, property.key, property.value)349 })350 .map_err(<CommonError<T>>::from)?;351352 Ok(())353 }354355 /// Batch operation to set multiple properties with the same scope.356 pub fn set_scoped_token_properties(357 collection_id: CollectionId,358 token_id: TokenId,359 scope: PropertyScope,360 properties: impl Iterator<Item = Property>,361 ) -> DispatchResult {362 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {363 stored_properties.try_scoped_set_from_iter(scope, properties)364 })365 .map_err(<CommonError<T>>::from)?;366367 Ok(())368 }369370 /// Add or edit auxiliary data for the property.371 ///372 /// - `f`: function that adds or edits auxiliary data.373 pub fn try_mutate_token_aux_property<R, E>(374 collection_id: CollectionId,375 token_id: TokenId,376 scope: PropertyScope,377 key: PropertyKey,378 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,379 ) -> Result<R, E> {380 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)381 }382383 /// Remove auxiliary data for the property.384 pub fn remove_token_aux_property(385 collection_id: CollectionId,386 token_id: TokenId,387 scope: PropertyScope,388 key: PropertyKey,389 ) {390 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));391 }392393 /// Get all auxiliary data in a given scope.394 ///395 /// Returns iterator over Property Key - Data pairs.396 pub fn iterate_token_aux_properties(397 collection_id: CollectionId,398 token_id: TokenId,399 scope: PropertyScope,400 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {401 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))402 }403404 /// Get ID of the last minted token405 pub fn current_token_id(collection_id: CollectionId) -> TokenId {406 TokenId(<TokensMinted<T>>::get(collection_id))407 }408}409410// unchecked calls skips any permission checks411impl<T: Config> Pallet<T> {412 /// Create NFT collection413 ///414 /// `init_collection` will take non-refundable deposit for collection creation.415 ///416 /// - `data`: Contains settings for collection limits and permissions.417 pub fn init_collection(418 owner: T::CrossAccountId,419 payer: T::CrossAccountId,420 data: CreateCollectionData<T::AccountId>,421 flags: CollectionFlags,422 ) -> Result<CollectionId, DispatchError> {423 <PalletCommon<T>>::init_collection(owner, payer, data, flags)424 }425426 /// Destroy NFT collection427 ///428 /// `destroy_collection` will throw error if collection contains any tokens.429 /// Only owner can destroy collection.430 pub fn destroy_collection(431 collection: NonfungibleHandle<T>,432 sender: &T::CrossAccountId,433 ) -> DispatchResult {434 let id = collection.id;435436 if Self::collection_has_tokens(id) {437 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());438 }439440 // =========441442 PalletCommon::destroy_collection(collection.0, sender)?;443444 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);445 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);446 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);447 <TokensMinted<T>>::remove(id);448 <TokensBurnt<T>>::remove(id);449 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);450 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);451 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);452 Ok(())453 }454455 /// Burn NFT token456 ///457 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token458 /// if the token is nested.459 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.460 /// Also removes all corresponding properties and auxiliary properties.461 ///462 /// - `token`: Token that should be burned463 /// - `collection`: Collection that contains the token464 pub fn burn(465 collection: &NonfungibleHandle<T>,466 sender: &T::CrossAccountId,467 token: TokenId,468 ) -> DispatchResult {469 let token_data =470 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;471 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);472473 if collection.permissions.access() == AccessMode::AllowList {474 collection.check_allowlist(sender)?;475 }476477 if Self::token_has_children(collection.id, token) {478 return Err(<Error<T>>::CantBurnNftWithChildren.into());479 }480481 let burnt = <TokensBurnt<T>>::get(collection.id)482 .checked_add(1)483 .ok_or(ArithmeticError::Overflow)?;484485 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))486 .checked_sub(1)487 .ok_or(ArithmeticError::Overflow)?;488489 // =========490491 if balance == 0 {492 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));493 } else {494 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);495 }496497 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);498499 <Owned<T>>::remove((collection.id, &token_data.owner, token));500 <TokensBurnt<T>>::insert(collection.id, burnt);501 <TokenData<T>>::remove((collection.id, token));502 <TokenProperties<T>>::remove((collection.id, token));503 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);504 let old_spender = <Allowance<T>>::take((collection.id, token));505506 if let Some(old_spender) = old_spender {507 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(508 collection.id,509 token,510 token_data.owner.clone(),511 old_spender,512 0,513 ));514 }515516 <PalletEvm<T>>::deposit_log(517 ERC721Events::Transfer {518 from: *token_data.owner.as_eth(),519 to: H160::default(),520 token_id: token.into(),521 }522 .to_log(collection_id_to_address(collection.id)),523 );524 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(525 collection.id,526 token,527 token_data.owner,528 1,529 ));530 Ok(())531 }532533 /// Same as [`burn`] but burns all the tokens that are nested in the token first534 ///535 /// - `self_budget`: Limit for searching children in depth.536 /// - `breadth_budget`: Limit of breadth of searching children.537 ///538 /// [`burn`]: struct.Pallet.html#method.burn539 #[transactional]540 pub fn burn_recursively(541 collection: &NonfungibleHandle<T>,542 sender: &T::CrossAccountId,543 token: TokenId,544 self_budget: &dyn Budget,545 breadth_budget: &dyn Budget,546 ) -> DispatchResultWithPostInfo {547 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);548549 let current_token_account =550 T::CrossTokenAddressMapping::token_to_address(collection.id, token);551552 let mut weight = Weight::zero();553554 // This method is transactional, if user in fact doesn't have permissions to remove token -555 // tokens removed here will be restored after rejected transaction556 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {557 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);558 let PostDispatchInfo { actual_weight, .. } =559 <PalletStructure<T>>::burn_item_recursively(560 current_token_account.clone(),561 collection,562 token,563 self_budget,564 breadth_budget,565 )?;566 if let Some(actual_weight) = actual_weight {567 weight = weight.saturating_add(actual_weight);568 }569 }570571 Self::burn(collection, sender, token)?;572 DispatchResultWithPostInfo::Ok(PostDispatchInfo {573 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),574 pays_fee: Pays::Yes,575 })576 }577578 /// A batch operation to add, edit or remove properties for a token.579 ///580 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.581 /// - `is_token_create`: Indicates that method is called during token initialization.582 /// Allows to bypass ownership check.583 ///584 /// All affected properties should have `mutable` permission585 /// to be **deleted** or to be **set more than once**,586 /// and the sender should have permission to edit those properties.587 ///588 /// This function fires an event for each property change.589 /// In case of an error, all the changes (including the events) will be reverted590 /// since the function is transactional.591 #[transactional]592 fn modify_token_properties(593 collection: &NonfungibleHandle<T>,594 sender: &T::CrossAccountId,595 token_id: TokenId,596 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,597 is_token_create: bool,598 nesting_budget: &dyn Budget,599 ) -> DispatchResult {600 let is_token_owner = || {601 let is_owned = <PalletStructure<T>>::check_indirectly_owned(602 sender.clone(),603 collection.id,604 token_id,605 None,606 nesting_budget,607 )?;608609 Ok(is_owned)610 };611612 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));613614 <PalletCommon<T>>::modify_token_properties(615 collection,616 sender,617 token_id,618 properties_updates,619 is_token_create,620 stored_properties,621 is_token_owner,622 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),623 erc::ERC721TokenEvent::TokenChanged {624 token_id: token_id.into(),625 }626 .to_log(T::ContractAddress::get()),627 )628 }629630 /// Batch operation to add or edit properties for the token631 ///632 /// Same as [`modify_token_properties`] but doesn't allow to remove properties633 ///634 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties635 pub fn set_token_properties(636 collection: &NonfungibleHandle<T>,637 sender: &T::CrossAccountId,638 token_id: TokenId,639 properties: impl Iterator<Item = Property>,640 is_token_create: bool,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 is_token_create,649 nesting_budget,650 )651 }652653 /// Add or edit single property for the token654 ///655 /// Calls [`set_token_properties`] internally656 ///657 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties658 pub fn set_token_property(659 collection: &NonfungibleHandle<T>,660 sender: &T::CrossAccountId,661 token_id: TokenId,662 property: Property,663 nesting_budget: &dyn Budget,664 ) -> DispatchResult {665 let is_token_create = false;666667 Self::set_token_properties(668 collection,669 sender,670 token_id,671 [property].into_iter(),672 is_token_create,673 nesting_budget,674 )675 }676677 /// Batch operation to remove properties from the token678 ///679 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties680 ///681 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties682 pub fn delete_token_properties(683 collection: &NonfungibleHandle<T>,684 sender: &T::CrossAccountId,685 token_id: TokenId,686 property_keys: impl Iterator<Item = PropertyKey>,687 nesting_budget: &dyn Budget,688 ) -> DispatchResult {689 let is_token_create = false;690691 Self::modify_token_properties(692 collection,693 sender,694 token_id,695 property_keys.into_iter().map(|key| (key, None)),696 is_token_create,697 nesting_budget,698 )699 }700701 /// Remove single property from the token702 ///703 /// Calls [`delete_token_properties`] internally704 ///705 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties706 pub fn delete_token_property(707 collection: &NonfungibleHandle<T>,708 sender: &T::CrossAccountId,709 token_id: TokenId,710 property_key: PropertyKey,711 nesting_budget: &dyn Budget,712 ) -> DispatchResult {713 Self::delete_token_properties(714 collection,715 sender,716 token_id,717 [property_key].into_iter(),718 nesting_budget,719 )720 }721722 /// Add or edit properties for the collection723 pub fn set_collection_properties(724 collection: &NonfungibleHandle<T>,725 sender: &T::CrossAccountId,726 properties: Vec<Property>,727 ) -> DispatchResult {728 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())729 }730731 /// Remove properties from the collection732 pub fn delete_collection_properties(733 collection: &CollectionHandle<T>,734 sender: &T::CrossAccountId,735 property_keys: Vec<PropertyKey>,736 ) -> DispatchResult {737 <PalletCommon<T>>::delete_collection_properties(738 collection,739 sender,740 property_keys.into_iter(),741 )742 }743744 /// Set property permissions for the token.745 ///746 /// Sender should be the owner or admin of token's collection.747 pub fn set_token_property_permissions(748 collection: &CollectionHandle<T>,749 sender: &T::CrossAccountId,750 property_permissions: Vec<PropertyKeyPermission>,751 ) -> DispatchResult {752 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)753 }754755 /// Set property permissions for the token with scope.756 ///757 /// Sender should be the owner or admin of token's collection.758 pub fn set_scoped_token_property_permissions(759 collection: &CollectionHandle<T>,760 sender: &T::CrossAccountId,761 scope: PropertyScope,762 property_permissions: Vec<PropertyKeyPermission>,763 ) -> DispatchResult {764 <PalletCommon<T>>::set_scoped_token_property_permissions(765 collection,766 sender,767 scope,768 property_permissions,769 )770 }771772 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {773 <PalletCommon<T>>::property_permissions(collection_id)774 }775776 pub fn check_token_immediate_ownership(777 collection: &NonfungibleHandle<T>,778 token: TokenId,779 possible_owner: &T::CrossAccountId,780 ) -> DispatchResult {781 let token_data =782 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;783 ensure!(784 &token_data.owner == possible_owner,785 <CommonError<T>>::NoPermission786 );787 Ok(())788 }789790 /// Transfer NFT token from one account to another.791 ///792 /// `from` account stops being the owner and `to` account becomes the owner of the token.793 /// If `to` is token than `to` becomes owner of the token and the token become nested.794 /// Unnests token from previous parent if it was nested before.795 /// Removes allowance for the token if there was any.796 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.797 ///798 /// - `nesting_budget`: Limit for token nesting depth799 pub fn transfer(800 collection: &NonfungibleHandle<T>,801 from: &T::CrossAccountId,802 to: &T::CrossAccountId,803 token: TokenId,804 nesting_budget: &dyn Budget,805 ) -> DispatchResult {806 ensure!(807 collection.limits.transfers_enabled(),808 <CommonError<T>>::TransferNotAllowed809 );810811 let token_data =812 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;813 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);814815 if collection.permissions.access() == AccessMode::AllowList {816 collection.check_allowlist(from)?;817 collection.check_allowlist(to)?;818 }819 <PalletCommon<T>>::ensure_correct_receiver(to)?;820821 let balance_from = <AccountBalance<T>>::get((collection.id, from))822 .checked_sub(1)823 .ok_or(<CommonError<T>>::TokenValueTooLow)?;824 let balance_to = if from != to {825 let balance_to = <AccountBalance<T>>::get((collection.id, to))826 .checked_add(1)827 .ok_or(ArithmeticError::Overflow)?;828829 ensure!(830 balance_to < collection.limits.account_token_ownership_limit(),831 <CommonError<T>>::AccountTokenLimitExceeded,832 );833834 Some(balance_to)835 } else {836 None837 };838839 <PalletStructure<T>>::nest_if_sent_to_token(840 from.clone(),841 to,842 collection.id,843 token,844 nesting_budget,845 )?;846847 // =========848849 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);850851 <TokenData<T>>::insert(852 (collection.id, token),853 ItemData {854 owner: to.clone(),855 ..token_data856 },857 );858859 if let Some(balance_to) = balance_to {860 // from != to861 if balance_from == 0 {862 <AccountBalance<T>>::remove((collection.id, from));863 } else {864 <AccountBalance<T>>::insert((collection.id, from), balance_from);865 }866 <AccountBalance<T>>::insert((collection.id, to), balance_to);867 <Owned<T>>::remove((collection.id, from, token));868 <Owned<T>>::insert((collection.id, to, token), true);869 }870 Self::set_allowance_unchecked(collection, from, token, None, true);871872 <PalletEvm<T>>::deposit_log(873 ERC721Events::Transfer {874 from: *from.as_eth(),875 to: *to.as_eth(),876 token_id: token.into(),877 }878 .to_log(collection_id_to_address(collection.id)),879 );880 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(881 collection.id,882 token,883 from.clone(),884 to.clone(),885 1,886 ));887 Ok(())888 }889890 /// Batch operation to mint multiple NFT tokens.891 ///892 /// The sender should be the owner/admin of the collection or collection should be configured893 /// to allow public minting.894 /// Throws if amount of tokens reached it's limit for the collection or if caller reached895 /// token ownership limit.896 ///897 /// - `data`: Contains list of token properties and users who will become the owners of the898 /// corresponging tokens.899 /// - `nesting_budget`: Limit for token nesting depth900 pub fn create_multiple_items(901 collection: &NonfungibleHandle<T>,902 sender: &T::CrossAccountId,903 data: Vec<CreateItemData<T>>,904 nesting_budget: &dyn Budget,905 ) -> DispatchResult {906 if !collection.is_owner_or_admin(sender) {907 ensure!(908 collection.permissions.mint_mode(),909 <CommonError<T>>::PublicMintingNotAllowed910 );911 collection.check_allowlist(sender)?;912913 for item in data.iter() {914 collection.check_allowlist(&item.owner)?;915 }916 }917918 for data in data.iter() {919 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;920 }921922 let first_token = <TokensMinted<T>>::get(collection.id);923 let tokens_minted = first_token924 .checked_add(data.len() as u32)925 .ok_or(ArithmeticError::Overflow)?;926 ensure!(927 tokens_minted <= collection.limits.token_limit(),928 <CommonError<T>>::CollectionTokenLimitExceeded929 );930931 let mut balances = BTreeMap::new();932 for data in &data {933 let balance = balances934 .entry(&data.owner)935 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));936 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;937938 ensure!(939 *balance <= collection.limits.account_token_ownership_limit(),940 <CommonError<T>>::AccountTokenLimitExceeded,941 );942 }943944 for (i, data) in data.iter().enumerate() {945 let token = TokenId(first_token + i as u32 + 1);946947 <PalletStructure<T>>::check_nesting(948 sender.clone(),949 &data.owner,950 collection.id,951 token,952 nesting_budget,953 )?;954 }955956 // =========957958 with_transaction(|| {959 for (i, data) in data.iter().enumerate() {960 let token = first_token + i as u32 + 1;961962 <TokenData<T>>::insert(963 (collection.id, token),964 ItemData {965 // const_data: data.const_data.clone(),966 owner: data.owner.clone(),967 },968 );969970 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(971 &data.owner,972 collection.id,973 TokenId(token),974 );975976 if let Err(e) = Self::set_token_properties(977 collection,978 sender,979 TokenId(token),980 data.properties.clone().into_iter(),981 true,982 nesting_budget,983 ) {984 return TransactionOutcome::Rollback(Err(e));985 }986 }987 TransactionOutcome::Commit(Ok(()))988 })?;989990 <TokensMinted<T>>::insert(collection.id, tokens_minted);991 for (account, balance) in balances {992 <AccountBalance<T>>::insert((collection.id, account), balance);993 }994 for (i, data) in data.into_iter().enumerate() {995 let token = first_token + i as u32 + 1;996 <Owned<T>>::insert((collection.id, &data.owner, token), true);997998 <PalletEvm<T>>::deposit_log(999 ERC721Events::Transfer {1000 from: H160::default(),1001 to: *data.owner.as_eth(),1002 token_id: token.into(),1003 }1004 .to_log(collection_id_to_address(collection.id)),1005 );1006 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1007 collection.id,1008 TokenId(token),1009 data.owner.clone(),1010 1,1011 ));1012 }1013 Ok(())1014 }10151016 pub fn set_allowance_unchecked(1017 collection: &NonfungibleHandle<T>,1018 sender: &T::CrossAccountId,1019 token: TokenId,1020 spender: Option<&T::CrossAccountId>,1021 assume_implicit_eth: bool,1022 ) {1023 if let Some(spender) = spender {1024 let old_spender = <Allowance<T>>::get((collection.id, token));1025 <Allowance<T>>::insert((collection.id, token), spender);1026 // In ERC721 there is only one possible approved user of token, so we set1027 // approved user to spender1028 <PalletEvm<T>>::deposit_log(1029 ERC721Events::Approval {1030 owner: *sender.as_eth(),1031 approved: *spender.as_eth(),1032 token_id: token.into(),1033 }1034 .to_log(collection_id_to_address(collection.id)),1035 );1036 // In Unique chain, any token can have any amount of approved users, so we need to1037 // set allowance of old owner to 0, and allowance of new owner to 11038 if old_spender.as_ref() != Some(spender) {1039 if let Some(old_owner) = old_spender {1040 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1041 collection.id,1042 token,1043 sender.clone(),1044 old_owner,1045 0,1046 ));1047 }1048 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1049 collection.id,1050 token,1051 sender.clone(),1052 spender.clone(),1053 1,1054 ));1055 }1056 } else {1057 let old_spender = <Allowance<T>>::take((collection.id, token));1058 if !assume_implicit_eth {1059 // In ERC721 there is only one possible approved user of token, so we set1060 // approved user to zero address1061 <PalletEvm<T>>::deposit_log(1062 ERC721Events::Approval {1063 owner: *sender.as_eth(),1064 approved: H160::default(),1065 token_id: token.into(),1066 }1067 .to_log(collection_id_to_address(collection.id)),1068 );1069 }1070 // In Unique chain, any token can have any amount of approved users, so we need to1071 // set allowance of old owner to 01072 if let Some(old_spender) = old_spender {1073 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1074 collection.id,1075 token,1076 sender.clone(),1077 old_spender,1078 0,1079 ));1080 }1081 }1082 }10831084 pub fn get_allowance(1085 collection: &NonfungibleHandle<T>,1086 token_id: TokenId,1087 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1088 ensure!(1089 <TokenData<T>>::get((collection.id, token_id)).is_some(),1090 <CommonError<T>>::TokenNotFound1091 );1092 Ok(<Allowance<T>>::get((collection.id, token_id)))1093 }10941095 /// Set allowance for the spender to `transfer` or `burn` sender's token.1096 ///1097 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1098 pub fn set_allowance(1099 collection: &NonfungibleHandle<T>,1100 sender: &T::CrossAccountId,1101 token: TokenId,1102 spender: Option<&T::CrossAccountId>,1103 ) -> DispatchResult {1104 if collection.permissions.access() == AccessMode::AllowList {1105 collection.check_allowlist(sender)?;1106 if let Some(spender) = spender {1107 collection.check_allowlist(spender)?;1108 }1109 }11101111 if let Some(spender) = spender {1112 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1113 }11141115 let token_data =1116 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1117 if &token_data.owner != sender {1118 ensure!(1119 collection.ignores_owned_amount(sender),1120 <CommonError<T>>::CantApproveMoreThanOwned1121 );1122 }11231124 // =========11251126 Self::set_allowance_unchecked(collection, sender, token, spender, false);1127 Ok(())1128 }11291130 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1131 ///1132 /// - `from`: Address of sender's eth mirror.1133 /// - `to`: Adress of spender.1134 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1135 pub fn set_allowance_from(1136 collection: &NonfungibleHandle<T>,1137 sender: &T::CrossAccountId,1138 from: &T::CrossAccountId,1139 token: TokenId,1140 to: Option<&T::CrossAccountId>,1141 ) -> DispatchResult {1142 if collection.permissions.access() == AccessMode::AllowList {1143 collection.check_allowlist(sender)?;1144 collection.check_allowlist(from)?;1145 if let Some(to) = to {1146 collection.check_allowlist(to)?;1147 }1148 }11491150 if let Some(to) = to {1151 <PalletCommon<T>>::ensure_correct_receiver(to)?;1152 }11531154 ensure!(1155 sender.conv_eq(from),1156 <CommonError<T>>::AddressIsNotEthMirror1157 );11581159 let token_data =1160 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1161 if token_data.owner != *from {1162 ensure!(1163 collection.limits.owner_can_transfer()1164 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1165 <CommonError<T>>::CantApproveMoreThanOwned1166 );1167 }11681169 // =========11701171 Self::set_allowance_unchecked(collection, from, token, to, false);1172 Ok(())1173 }11741175 /// Checks allowance for the spender to use the token.1176 fn check_allowed(1177 collection: &NonfungibleHandle<T>,1178 spender: &T::CrossAccountId,1179 from: &T::CrossAccountId,1180 token: TokenId,1181 nesting_budget: &dyn Budget,1182 ) -> DispatchResult {1183 if spender.conv_eq(from) {1184 return Ok(());1185 }1186 if collection.permissions.access() == AccessMode::AllowList {1187 // `from`, `to` checked in [`transfer`]1188 collection.check_allowlist(spender)?;1189 }11901191 if collection.ignores_token_restrictions(spender) {1192 return Ok(());1193 }11941195 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1196 ensure!(1197 <PalletStructure<T>>::check_indirectly_owned(1198 spender.clone(),1199 source.0,1200 source.1,1201 None,1202 nesting_budget1203 )?,1204 <CommonError<T>>::ApprovedValueTooLow,1205 );1206 return Ok(());1207 }1208 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1209 return Ok(());1210 }1211 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1212 return Ok(());1213 }12141215 Err(<CommonError<T>>::ApprovedValueTooLow.into())1216 }12171218 /// Transfer NFT token from one account to another.1219 ///1220 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1221 /// The owner should set allowance for the spender to transfer token.1222 ///1223 /// [`transfer`]: struct.Pallet.html#method.transfer1224 pub fn transfer_from(1225 collection: &NonfungibleHandle<T>,1226 spender: &T::CrossAccountId,1227 from: &T::CrossAccountId,1228 to: &T::CrossAccountId,1229 token: TokenId,1230 nesting_budget: &dyn Budget,1231 ) -> DispatchResult {1232 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12331234 // =========12351236 // Allowance is reset in [`transfer`]1237 Self::transfer(collection, from, to, token, nesting_budget)1238 }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 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1314 }13151316 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1317 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1318 }13191320 fn collection_has_tokens(collection_id: CollectionId) -> bool {1321 <TokenData<T>>::iter_prefix((collection_id,))1322 .next()1323 .is_some()1324 }13251326 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1327 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1328 .next()1329 .is_some()1330 }13311332 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1333 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1334 .map(|((child_collection_id, child_id), _)| TokenChild {1335 collection: child_collection_id,1336 token: child_id,1337 })1338 .collect()1339 }13401341 /// Mint single NFT token.1342 ///1343 /// Delegated to [`create_multiple_items`]1344 ///1345 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1346 pub fn create_item(1347 collection: &NonfungibleHandle<T>,1348 sender: &T::CrossAccountId,1349 data: CreateItemData<T>,1350 nesting_budget: &dyn Budget,1351 ) -> DispatchResult {1352 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1353 }13541355 /// Sets or unsets the approval of a given operator.1356 ///1357 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1358 /// - `owner`: Token owner1359 /// - `operator`: Operator1360 /// - `approve`: Should operator status be granted or revoked?1361 pub fn set_allowance_for_all(1362 collection: &NonfungibleHandle<T>,1363 owner: &T::CrossAccountId,1364 operator: &T::CrossAccountId,1365 approve: bool,1366 ) -> DispatchResult {1367 <PalletCommon<T>>::set_allowance_for_all(1368 collection,1369 owner,1370 operator,1371 approve,1372 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1373 ERC721Events::ApprovalForAll {1374 owner: *owner.as_eth(),1375 operator: *operator.as_eth(),1376 approved: approve,1377 }1378 .to_log(collection_id_to_address(collection.id)),1379 )1380 }13811382 /// Tells whether the given `owner` approves the `operator`.1383 pub fn allowance_for_all(1384 collection: &NonfungibleHandle<T>,1385 owner: &T::CrossAccountId,1386 operator: &T::CrossAccountId,1387 ) -> bool {1388 <CollectionAllowance<T>>::get((collection.id, owner, operator))1389 }13901391 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1392 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1393 properties.recompute_consumed_space();1394 });13951396 Ok(())1397 }1398}1// Copyright 2019-2022 Unique Network (Gibraltar) Ltd.2// This file is part of Unique Network.34// Unique Network is free software: you can redistribute it and/or modify5// it under the terms of the GNU General Public License as published by6// the Free Software Foundation, either version 3 of the License, or7// (at your option) any later version.89// Unique Network is distributed in the hope that it will be useful,10// but WITHOUT ANY WARRANTY; without even the implied warranty of11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the12// GNU General Public License for more details.1314// You should have received a copy of the GNU General Public License15// along with Unique Network. If not, see <http://www.gnu.org/licenses/>.1617//! # Nonfungible Pallet18//!19//! The Nonfungible pallet provides functionality for handling nonfungible collections and tokens.20//!21//! - [`Config`]22//! - [`NonfungibleHandle`]23//! - [`Pallet`]24//! - [`CommonWeights`](common::CommonWeights)25//!26//! ## Overview27//!28//! The Nonfungible pallet provides functions for:29//!30//! - NFT collection creation and removal31//! - Minting and burning of NFT tokens32//! - Retrieving account balances33//! - Transfering NFT tokens34//! - Setting and checking allowance for NFT tokens35//! - Setting properties and permissions for NFT collections and tokens36//! - Nesting and unnesting tokens37//!38//! ### Terminology39//!40//! - **NFT token:** Non fungible token.41//!42//! - **NFT Collection:** A collection of NFT tokens. All NFT tokens are part of a collection.43//! Each collection can define it's own properties, properties for it's tokens and set of permissions.44//!45//! - **Balance:** Number of NFT tokens owned by an account46//!47//! - **Allowance:** NFT tokens owned by one account that another account is allowed to make operations on48//!49//! - **Burning:** The process of “deleting” a token from a collection and from50//! an account balance of the owner.51//!52//! - **Nesting:** Setting up parent-child relationship between tokens. Nested tokens are inhereting53//! owner from their parent. There could be multiple levels of nesting. Token couldn't be nested in54//! it's child token i.e. parent-child relationship graph shouldn't have cycles.55//!56//! - **Properties:** Key-Values pairs. Token properties are attached to a token. Collection properties are57//! attached to a collection. Set of permissions could be defined for each property.58//!59//! ### Implementations60//!61//! The Nonfungible pallet provides implementations for the following traits. If these traits provide62//! the functionality that you need, then you can avoid coupling with the Nonfungible pallet.63//!64//! - [`CommonWeightInfo`](pallet_common::CommonWeightInfo): Functions for retrieval of transaction weight65//! - [`CommonCollectionOperations`](pallet_common::CommonCollectionOperations): Functions for dealing66//! with collections67//!68//! ## Interface69//!70//! ### Dispatchable Functions71//!72//! - `init_collection` - Create NFT collection. NFT collection can be configured to allow or deny access for73//! some accounts.74//! - `destroy_collection` - Destroy exising NFT collection. There should be no tokens in the collection.75//! - `burn` - Burn NFT token owned by account.76//! - `transfer` - Transfer NFT token. Transfers should be enabled for NFT collection.77//! Nests the NFT token if it is sent to another token.78//! - `create_item` - Mint NFT token in collection. Sender should have permission to mint tokens.79//! - `set_allowance` - Set allowance for another account.80//! - `set_token_property` - Set token property value.81//! - `delete_token_property` - Remove property from the token.82//! - `set_collection_properties` - Set collection properties.83//! - `delete_collection_properties` - Remove properties from the collection.84//! - `set_property_permission` - Set collection property permission.85//! - `set_token_property_permissions` - Set token property permissions.86//!87//! ## Assumptions88//!89//! * To perform operations on tokens sender should be in collection's allow list if collection access mode is `AllowList`.9091#![cfg_attr(not(feature = "std"), no_std)]9293use erc::ERC721Events;94use evm_coder::ToLog;95use frame_support::{96 BoundedVec, ensure, fail, transactional,97 storage::with_transaction,98 pallet_prelude::DispatchResultWithPostInfo,99 pallet_prelude::Weight,100 dispatch::{PostDispatchInfo, Pays},101};102use up_data_structs::{103 AccessMode, CollectionId, CollectionFlags, CustomDataLimit, TokenId, CreateCollectionData,104 CreateNftExData, mapping::TokenAddressMapping, budget::Budget, Property, PropertyKey,105 PropertyValue, PropertyKeyPermission, PropertyScope, TrySetProperty, TokenChild,106 AuxPropertyValue, PropertiesPermissionMap, TokenProperties as TokenPropertiesT,107};108use pallet_evm::{account::CrossAccountId, Pallet as PalletEvm};109use pallet_common::{110 Error as CommonError, Pallet as PalletCommon, Event as CommonEvent, CollectionHandle,111 eth::collection_id_to_address, SelfWeightOf as PalletCommonWeightOf,112 weights::WeightInfo as CommonWeightInfo, helpers::add_weight_to_post_info,113};114use pallet_structure::{Pallet as PalletStructure, Error as StructureError};115use pallet_evm_coder_substrate::{SubstrateRecorder, WithRecorder};116use sp_core::{Get, H160};117use sp_runtime::{ArithmeticError, DispatchError, DispatchResult, TransactionOutcome};118use sp_std::{vec::Vec, vec, collections::btree_map::BTreeMap};119use core::ops::Deref;120use codec::{Encode, Decode, MaxEncodedLen};121use scale_info::TypeInfo;122123pub use pallet::*;124use weights::WeightInfo;125#[cfg(feature = "runtime-benchmarks")]126pub mod benchmarking;127pub mod common;128pub mod erc;129pub mod weights;130131pub type CreateItemData<T> = CreateNftExData<<T as pallet_evm::Config>::CrossAccountId>;132pub(crate) type SelfWeightOf<T> = <T as Config>::WeightInfo;133134/// Token data, stored independently from other data used to describe it135/// for the convenience of database access. Notably contains the owner account address.136#[struct_versioning::versioned(version = 2, upper)]137#[derive(Encode, Decode, TypeInfo, MaxEncodedLen)]138pub struct ItemData<CrossAccountId> {139 #[version(..2)]140 pub const_data: BoundedVec<u8, CustomDataLimit>,141142 #[version(..2)]143 pub variable_data: BoundedVec<u8, CustomDataLimit>,144145 pub owner: CrossAccountId,146}147148#[frame_support::pallet]149pub mod pallet {150 use super::*;151 use frame_support::{152 Blake2_128Concat, Twox64Concat, pallet_prelude::*, storage::Key, traits::StorageVersion,153 };154 use frame_system::pallet_prelude::*;155 use up_data_structs::{CollectionId, TokenId};156 use super::weights::WeightInfo;157158 #[pallet::error]159 pub enum Error<T> {160 /// Not Nonfungible item data used to mint in Nonfungible collection.161 NotNonfungibleDataUsedToMintFungibleCollectionToken,162 /// Used amount > 1 with NFT163 NonfungibleItemsHaveNoAmount,164 /// Unable to burn NFT with children165 CantBurnNftWithChildren,166 }167168 #[pallet::config]169 pub trait Config:170 frame_system::Config + pallet_common::Config + pallet_structure::Config + pallet_evm::Config171 {172 type WeightInfo: WeightInfo;173 }174175 const STORAGE_VERSION: StorageVersion = StorageVersion::new(1);176177 #[pallet::pallet]178 #[pallet::storage_version(STORAGE_VERSION)]179 pub struct Pallet<T>(_);180181 /// Total amount of minted tokens in a collection.182 #[pallet::storage]183 pub type TokensMinted<T: Config> =184 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;185186 /// Amount of burnt tokens in a collection.187 #[pallet::storage]188 pub type TokensBurnt<T: Config> =189 StorageMap<Hasher = Twox64Concat, Key = CollectionId, Value = u32, QueryKind = ValueQuery>;190191 /// Token data, used to partially describe a token.192 #[pallet::storage]193 pub type TokenData<T: Config> = StorageNMap<194 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),195 Value = ItemData<T::CrossAccountId>,196 QueryKind = OptionQuery,197 >;198199 /// Map of key-value pairs, describing the metadata of a token.200 #[pallet::storage]201 #[pallet::getter(fn token_properties)]202 pub type TokenProperties<T: Config> = StorageNMap<203 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),204 Value = TokenPropertiesT,205 QueryKind = ValueQuery,206 >;207208 /// Custom data of a token that is serialized to bytes,209 /// primarily reserved for on-chain operations,210 /// normally obscured from the external users.211 ///212 /// Auxiliary properties are slightly different from213 /// usual [`TokenProperties`] due to an unlimited number214 /// and separately stored and written-to key-value pairs.215 ///216 /// Currently unused.217 #[pallet::storage]218 #[pallet::getter(fn token_aux_property)]219 pub type TokenAuxProperties<T: Config> = StorageNMap<220 Key = (221 Key<Twox64Concat, CollectionId>,222 Key<Twox64Concat, TokenId>,223 Key<Twox64Concat, PropertyScope>,224 Key<Twox64Concat, PropertyKey>,225 ),226 Value = AuxPropertyValue,227 QueryKind = OptionQuery,228 >;229230 /// Used to enumerate tokens owned by account.231 #[pallet::storage]232 pub type Owned<T: Config> = StorageNMap<233 Key = (234 Key<Twox64Concat, CollectionId>,235 Key<Blake2_128Concat, T::CrossAccountId>,236 Key<Twox64Concat, TokenId>,237 ),238 Value = bool,239 QueryKind = ValueQuery,240 >;241242 /// Used to enumerate token's children.243 #[pallet::storage]244 #[pallet::getter(fn token_children)]245 pub type TokenChildren<T: Config> = StorageNMap<246 Key = (247 Key<Twox64Concat, CollectionId>,248 Key<Twox64Concat, TokenId>,249 Key<Twox64Concat, (CollectionId, TokenId)>,250 ),251 Value = bool,252 QueryKind = ValueQuery,253 >;254255 /// Amount of tokens owned by an account in a collection.256 #[pallet::storage]257 pub type AccountBalance<T: Config> = StorageNMap<258 Key = (259 Key<Twox64Concat, CollectionId>,260 Key<Blake2_128Concat, T::CrossAccountId>,261 ),262 Value = u32,263 QueryKind = ValueQuery,264 >;265266 /// Allowance set by a token owner for another user to perform one of certain transactions on a token.267 #[pallet::storage]268 pub type Allowance<T: Config> = StorageNMap<269 Key = (Key<Twox64Concat, CollectionId>, Key<Twox64Concat, TokenId>),270 Value = T::CrossAccountId,271 QueryKind = OptionQuery,272 >;273274 /// Operator set by a wallet owner that could perform certain transactions on all tokens in the wallet.275 #[pallet::storage]276 pub type CollectionAllowance<T: Config> = StorageNMap<277 Key = (278 Key<Twox64Concat, CollectionId>,279 Key<Blake2_128Concat, T::CrossAccountId>,280 Key<Blake2_128Concat, T::CrossAccountId>,281 ),282 Value = bool,283 QueryKind = ValueQuery,284 >;285286 /// Upgrade from the old schema to properties.287 #[pallet::hooks]288 impl<T: Config> Hooks<BlockNumberFor<T>> for Pallet<T> {289 fn on_runtime_upgrade() -> Weight {290 StorageVersion::new(1).put::<Pallet<T>>();291292 Weight::zero()293 }294 }295}296297pub struct NonfungibleHandle<T: Config>(pallet_common::CollectionHandle<T>);298impl<T: Config> NonfungibleHandle<T> {299 pub fn cast(inner: pallet_common::CollectionHandle<T>) -> Self {300 Self(inner)301 }302 pub fn into_inner(self) -> pallet_common::CollectionHandle<T> {303 self.0304 }305 pub fn common_mut(&mut self) -> &mut pallet_common::CollectionHandle<T> {306 &mut self.0307 }308}309310impl<T: Config> WithRecorder<T> for NonfungibleHandle<T> {311 fn recorder(&self) -> &SubstrateRecorder<T> {312 self.0.recorder()313 }314 fn into_recorder(self) -> SubstrateRecorder<T> {315 self.0.into_recorder()316 }317}318impl<T: Config> Deref for NonfungibleHandle<T> {319 type Target = pallet_common::CollectionHandle<T>;320321 fn deref(&self) -> &Self::Target {322 &self.0323 }324}325326impl<T: Config> Pallet<T> {327 /// Get number of NFT tokens in collection.328 pub fn total_supply(collection: &NonfungibleHandle<T>) -> u32 {329 <TokensMinted<T>>::get(collection.id) - <TokensBurnt<T>>::get(collection.id)330 }331332 /// Check that NFT token exists.333 ///334 /// - `token`: Token ID.335 pub fn token_exists(collection: &NonfungibleHandle<T>, token: TokenId) -> bool {336 <TokenData<T>>::contains_key((collection.id, token))337 }338339 /// Set the token property with the scope.340 ///341 /// - `property`: Contains key-value pair.342 pub fn set_scoped_token_property(343 collection_id: CollectionId,344 token_id: TokenId,345 scope: PropertyScope,346 property: Property,347 ) -> DispatchResult {348 TokenProperties::<T>::try_mutate((collection_id, token_id), |properties| {349 properties.try_scoped_set(scope, property.key, property.value)350 })351 .map_err(<CommonError<T>>::from)?;352353 Ok(())354 }355356 /// Batch operation to set multiple properties with the same scope.357 pub fn set_scoped_token_properties(358 collection_id: CollectionId,359 token_id: TokenId,360 scope: PropertyScope,361 properties: impl Iterator<Item = Property>,362 ) -> DispatchResult {363 TokenProperties::<T>::try_mutate((collection_id, token_id), |stored_properties| {364 stored_properties.try_scoped_set_from_iter(scope, properties)365 })366 .map_err(<CommonError<T>>::from)?;367368 Ok(())369 }370371 /// Add or edit auxiliary data for the property.372 ///373 /// - `f`: function that adds or edits auxiliary data.374 pub fn try_mutate_token_aux_property<R, E>(375 collection_id: CollectionId,376 token_id: TokenId,377 scope: PropertyScope,378 key: PropertyKey,379 f: impl FnOnce(&mut Option<AuxPropertyValue>) -> Result<R, E>,380 ) -> Result<R, E> {381 <TokenAuxProperties<T>>::try_mutate((collection_id, token_id, scope, key), f)382 }383384 /// Remove auxiliary data for the property.385 pub fn remove_token_aux_property(386 collection_id: CollectionId,387 token_id: TokenId,388 scope: PropertyScope,389 key: PropertyKey,390 ) {391 <TokenAuxProperties<T>>::remove((collection_id, token_id, scope, key));392 }393394 /// Get all auxiliary data in a given scope.395 ///396 /// Returns iterator over Property Key - Data pairs.397 pub fn iterate_token_aux_properties(398 collection_id: CollectionId,399 token_id: TokenId,400 scope: PropertyScope,401 ) -> impl Iterator<Item = (PropertyKey, AuxPropertyValue)> {402 <TokenAuxProperties<T>>::iter_prefix((collection_id, token_id, scope))403 }404405 /// Get ID of the last minted token406 pub fn current_token_id(collection_id: CollectionId) -> TokenId {407 TokenId(<TokensMinted<T>>::get(collection_id))408 }409}410411// unchecked calls skips any permission checks412impl<T: Config> Pallet<T> {413 /// Create NFT collection414 ///415 /// `init_collection` will take non-refundable deposit for collection creation.416 ///417 /// - `data`: Contains settings for collection limits and permissions.418 pub fn init_collection(419 owner: T::CrossAccountId,420 payer: T::CrossAccountId,421 data: CreateCollectionData<T::AccountId>,422 flags: CollectionFlags,423 ) -> Result<CollectionId, DispatchError> {424 <PalletCommon<T>>::init_collection(owner, payer, data, flags)425 }426427 /// Destroy NFT collection428 ///429 /// `destroy_collection` will throw error if collection contains any tokens.430 /// Only owner can destroy collection.431 pub fn destroy_collection(432 collection: NonfungibleHandle<T>,433 sender: &T::CrossAccountId,434 ) -> DispatchResult {435 let id = collection.id;436437 if Self::collection_has_tokens(id) {438 return Err(<CommonError<T>>::CantDestroyNotEmptyCollection.into());439 }440441 // =========442443 PalletCommon::destroy_collection(collection.0, sender)?;444445 let _ = <TokenData<T>>::clear_prefix((id,), u32::MAX, None);446 let _ = <TokenChildren<T>>::clear_prefix((id,), u32::MAX, None);447 let _ = <Owned<T>>::clear_prefix((id,), u32::MAX, None);448 <TokensMinted<T>>::remove(id);449 <TokensBurnt<T>>::remove(id);450 let _ = <Allowance<T>>::clear_prefix((id,), u32::MAX, None);451 let _ = <AccountBalance<T>>::clear_prefix((id,), u32::MAX, None);452 let _ = <CollectionAllowance<T>>::clear_prefix((id,), u32::MAX, None);453 Ok(())454 }455456 /// Burn NFT token457 ///458 /// `burn` removes `token` from the `collection`, from it's owner and from the parent token459 /// if the token is nested.460 /// Only the owner can `burn` the token. The `token` shouldn't have any nested tokens.461 /// Also removes all corresponding properties and auxiliary properties.462 ///463 /// - `token`: Token that should be burned464 /// - `collection`: Collection that contains the token465 pub fn burn(466 collection: &NonfungibleHandle<T>,467 sender: &T::CrossAccountId,468 token: TokenId,469 ) -> DispatchResult {470 let token_data =471 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;472 ensure!(&token_data.owner == sender, <CommonError<T>>::NoPermission);473474 if collection.permissions.access() == AccessMode::AllowList {475 collection.check_allowlist(sender)?;476 }477478 if Self::token_has_children(collection.id, token) {479 return Err(<Error<T>>::CantBurnNftWithChildren.into());480 }481482 let burnt = <TokensBurnt<T>>::get(collection.id)483 .checked_add(1)484 .ok_or(ArithmeticError::Overflow)?;485486 let balance = <AccountBalance<T>>::get((collection.id, token_data.owner.clone()))487 .checked_sub(1)488 .ok_or(ArithmeticError::Overflow)?;489490 // =========491492 if balance == 0 {493 <AccountBalance<T>>::remove((collection.id, token_data.owner.clone()));494 } else {495 <AccountBalance<T>>::insert((collection.id, token_data.owner.clone()), balance);496 }497498 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);499500 <Owned<T>>::remove((collection.id, &token_data.owner, token));501 <TokensBurnt<T>>::insert(collection.id, burnt);502 <TokenData<T>>::remove((collection.id, token));503 <TokenProperties<T>>::remove((collection.id, token));504 let _ = <TokenAuxProperties<T>>::clear_prefix((collection.id, token), u32::MAX, None);505 let old_spender = <Allowance<T>>::take((collection.id, token));506507 if let Some(old_spender) = old_spender {508 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(509 collection.id,510 token,511 token_data.owner.clone(),512 old_spender,513 0,514 ));515 }516517 <PalletEvm<T>>::deposit_log(518 ERC721Events::Transfer {519 from: *token_data.owner.as_eth(),520 to: H160::default(),521 token_id: token.into(),522 }523 .to_log(collection_id_to_address(collection.id)),524 );525 <PalletCommon<T>>::deposit_event(CommonEvent::ItemDestroyed(526 collection.id,527 token,528 token_data.owner,529 1,530 ));531 Ok(())532 }533534 /// Same as [`burn`] but burns all the tokens that are nested in the token first535 ///536 /// - `self_budget`: Limit for searching children in depth.537 /// - `breadth_budget`: Limit of breadth of searching children.538 ///539 /// [`burn`]: struct.Pallet.html#method.burn540 #[transactional]541 pub fn burn_recursively(542 collection: &NonfungibleHandle<T>,543 sender: &T::CrossAccountId,544 token: TokenId,545 self_budget: &dyn Budget,546 breadth_budget: &dyn Budget,547 ) -> DispatchResultWithPostInfo {548 ensure!(self_budget.consume(), <StructureError<T>>::DepthLimit,);549550 let current_token_account =551 T::CrossTokenAddressMapping::token_to_address(collection.id, token);552553 let mut weight = Weight::zero();554555 // This method is transactional, if user in fact doesn't have permissions to remove token -556 // tokens removed here will be restored after rejected transaction557 for ((collection, token), _) in <TokenChildren<T>>::iter_prefix((collection.id, token)) {558 ensure!(breadth_budget.consume(), <StructureError<T>>::BreadthLimit,);559 let PostDispatchInfo { actual_weight, .. } =560 <PalletStructure<T>>::burn_item_recursively(561 current_token_account.clone(),562 collection,563 token,564 self_budget,565 breadth_budget,566 )?;567 if let Some(actual_weight) = actual_weight {568 weight = weight.saturating_add(actual_weight);569 }570 }571572 Self::burn(collection, sender, token)?;573 DispatchResultWithPostInfo::Ok(PostDispatchInfo {574 actual_weight: Some(weight + <SelfWeightOf<T>>::burn_item()),575 pays_fee: Pays::Yes,576 })577 }578579 /// A batch operation to add, edit or remove properties for a token.580 ///581 /// - `nesting_budget`: Limit for searching parents in-depth to check ownership.582 /// - `is_token_create`: Indicates that method is called during token initialization.583 /// Allows to bypass ownership check.584 ///585 /// All affected properties should have `mutable` permission586 /// to be **deleted** or to be **set more than once**,587 /// and the sender should have permission to edit those properties.588 ///589 /// This function fires an event for each property change.590 /// In case of an error, all the changes (including the events) will be reverted591 /// since the function is transactional.592 #[transactional]593 fn modify_token_properties(594 collection: &NonfungibleHandle<T>,595 sender: &T::CrossAccountId,596 token_id: TokenId,597 properties_updates: impl Iterator<Item = (PropertyKey, Option<PropertyValue>)>,598 is_token_create: bool,599 nesting_budget: &dyn Budget,600 ) -> DispatchResult {601 let is_token_owner = || {602 let is_owned = <PalletStructure<T>>::check_indirectly_owned(603 sender.clone(),604 collection.id,605 token_id,606 None,607 nesting_budget,608 )?;609610 Ok(is_owned)611 };612613 let stored_properties = <TokenProperties<T>>::get((collection.id, token_id));614615 <PalletCommon<T>>::modify_token_properties(616 collection,617 sender,618 token_id,619 properties_updates,620 is_token_create,621 stored_properties,622 is_token_owner,623 |properties| <TokenProperties<T>>::set((collection.id, token_id), properties),624 erc::ERC721TokenEvent::TokenChanged {625 token_id: token_id.into(),626 }627 .to_log(T::ContractAddress::get()),628 )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 is_token_create: bool,642 nesting_budget: &dyn Budget,643 ) -> DispatchResult {644 Self::modify_token_properties(645 collection,646 sender,647 token_id,648 properties.map(|p| (p.key, Some(p.value))),649 is_token_create,650 nesting_budget,651 )652 }653654 /// Add or edit single property for the token655 ///656 /// Calls [`set_token_properties`] internally657 ///658 /// [`set_token_properties`]: struct.Pallet.html#method.set_token_properties659 pub fn set_token_property(660 collection: &NonfungibleHandle<T>,661 sender: &T::CrossAccountId,662 token_id: TokenId,663 property: Property,664 nesting_budget: &dyn Budget,665 ) -> DispatchResult {666 let is_token_create = false;667668 Self::set_token_properties(669 collection,670 sender,671 token_id,672 [property].into_iter(),673 is_token_create,674 nesting_budget,675 )676 }677678 /// Batch operation to remove properties from the token679 ///680 /// Same as [`modify_token_properties`] but doesn't allow to add or edit properties681 ///682 /// [`modify_token_properties`]: struct.Pallet.html#method.modify_token_properties683 pub fn delete_token_properties(684 collection: &NonfungibleHandle<T>,685 sender: &T::CrossAccountId,686 token_id: TokenId,687 property_keys: impl Iterator<Item = PropertyKey>,688 nesting_budget: &dyn Budget,689 ) -> DispatchResult {690 let is_token_create = false;691692 Self::modify_token_properties(693 collection,694 sender,695 token_id,696 property_keys.into_iter().map(|key| (key, None)),697 is_token_create,698 nesting_budget,699 )700 }701702 /// Remove single property from the token703 ///704 /// Calls [`delete_token_properties`] internally705 ///706 /// [`delete_token_properties`]: struct.Pallet.html#method.delete_token_properties707 pub fn delete_token_property(708 collection: &NonfungibleHandle<T>,709 sender: &T::CrossAccountId,710 token_id: TokenId,711 property_key: PropertyKey,712 nesting_budget: &dyn Budget,713 ) -> DispatchResult {714 Self::delete_token_properties(715 collection,716 sender,717 token_id,718 [property_key].into_iter(),719 nesting_budget,720 )721 }722723 /// Add or edit properties for the collection724 pub fn set_collection_properties(725 collection: &NonfungibleHandle<T>,726 sender: &T::CrossAccountId,727 properties: Vec<Property>,728 ) -> DispatchResult {729 <PalletCommon<T>>::set_collection_properties(collection, sender, properties.into_iter())730 }731732 /// Remove properties from the collection733 pub fn delete_collection_properties(734 collection: &CollectionHandle<T>,735 sender: &T::CrossAccountId,736 property_keys: Vec<PropertyKey>,737 ) -> DispatchResult {738 <PalletCommon<T>>::delete_collection_properties(739 collection,740 sender,741 property_keys.into_iter(),742 )743 }744745 /// Set property permissions for the token.746 ///747 /// Sender should be the owner or admin of token's collection.748 pub fn set_token_property_permissions(749 collection: &CollectionHandle<T>,750 sender: &T::CrossAccountId,751 property_permissions: Vec<PropertyKeyPermission>,752 ) -> DispatchResult {753 <PalletCommon<T>>::set_token_property_permissions(collection, sender, property_permissions)754 }755756 /// Set property permissions for the token with scope.757 ///758 /// Sender should be the owner or admin of token's collection.759 pub fn set_scoped_token_property_permissions(760 collection: &CollectionHandle<T>,761 sender: &T::CrossAccountId,762 scope: PropertyScope,763 property_permissions: Vec<PropertyKeyPermission>,764 ) -> DispatchResult {765 <PalletCommon<T>>::set_scoped_token_property_permissions(766 collection,767 sender,768 scope,769 property_permissions,770 )771 }772773 pub fn token_property_permission(collection_id: CollectionId) -> PropertiesPermissionMap {774 <PalletCommon<T>>::property_permissions(collection_id)775 }776777 pub fn check_token_immediate_ownership(778 collection: &NonfungibleHandle<T>,779 token: TokenId,780 possible_owner: &T::CrossAccountId,781 ) -> DispatchResult {782 let token_data =783 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;784 ensure!(785 &token_data.owner == possible_owner,786 <CommonError<T>>::NoPermission787 );788 Ok(())789 }790791 /// Transfer NFT token from one account to another.792 ///793 /// `from` account stops being the owner and `to` account becomes the owner of the token.794 /// If `to` is token than `to` becomes owner of the token and the token become nested.795 /// Unnests token from previous parent if it was nested before.796 /// Removes allowance for the token if there was any.797 /// Throws if transfers aren't allowed for collection or if receiver reached token ownership limit.798 ///799 /// - `nesting_budget`: Limit for token nesting depth800 pub fn transfer(801 collection: &NonfungibleHandle<T>,802 from: &T::CrossAccountId,803 to: &T::CrossAccountId,804 token: TokenId,805 nesting_budget: &dyn Budget,806 ) -> DispatchResultWithPostInfo {807 ensure!(808 collection.limits.transfers_enabled(),809 <CommonError<T>>::TransferNotAllowed810 );811812 let mut actual_weight = <SelfWeightOf<T>>::transfer_raw();813 let token_data =814 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;815 ensure!(&token_data.owner == from, <CommonError<T>>::NoPermission);816817 if collection.permissions.access() == AccessMode::AllowList {818 collection.check_allowlist(from)?;819 collection.check_allowlist(to)?;820 actual_weight += <PalletCommonWeightOf<T>>::check_accesslist() * 2;821 }822 <PalletCommon<T>>::ensure_correct_receiver(to)?;823824 let balance_from = <AccountBalance<T>>::get((collection.id, from))825 .checked_sub(1)826 .ok_or(<CommonError<T>>::TokenValueTooLow)?;827 let balance_to = if from != to {828 let balance_to = <AccountBalance<T>>::get((collection.id, to))829 .checked_add(1)830 .ok_or(ArithmeticError::Overflow)?;831832 ensure!(833 balance_to < collection.limits.account_token_ownership_limit(),834 <CommonError<T>>::AccountTokenLimitExceeded,835 );836837 Some(balance_to)838 } else {839 None840 };841842 <PalletStructure<T>>::nest_if_sent_to_token(843 from.clone(),844 to,845 collection.id,846 token,847 nesting_budget,848 )?;849850 // =========851852 <PalletStructure<T>>::unnest_if_nested(&token_data.owner, collection.id, token);853854 <TokenData<T>>::insert(855 (collection.id, token),856 ItemData {857 owner: to.clone(),858 ..token_data859 },860 );861862 if let Some(balance_to) = balance_to {863 // from != to864 if balance_from == 0 {865 <AccountBalance<T>>::remove((collection.id, from));866 } else {867 <AccountBalance<T>>::insert((collection.id, from), balance_from);868 }869 <AccountBalance<T>>::insert((collection.id, to), balance_to);870 <Owned<T>>::remove((collection.id, from, token));871 <Owned<T>>::insert((collection.id, to, token), true);872 }873 Self::set_allowance_unchecked(collection, from, token, None, true);874875 <PalletEvm<T>>::deposit_log(876 ERC721Events::Transfer {877 from: *from.as_eth(),878 to: *to.as_eth(),879 token_id: token.into(),880 }881 .to_log(collection_id_to_address(collection.id)),882 );883 <PalletCommon<T>>::deposit_event(CommonEvent::Transfer(884 collection.id,885 token,886 from.clone(),887 to.clone(),888 1,889 ));890891 Ok(PostDispatchInfo {892 actual_weight: Some(actual_weight),893 pays_fee: Pays::Yes,894 })895 }896897 /// Batch operation to mint multiple NFT tokens.898 ///899 /// The sender should be the owner/admin of the collection or collection should be configured900 /// to allow public minting.901 /// Throws if amount of tokens reached it's limit for the collection or if caller reached902 /// token ownership limit.903 ///904 /// - `data`: Contains list of token properties and users who will become the owners of the905 /// corresponging tokens.906 /// - `nesting_budget`: Limit for token nesting depth907 pub fn create_multiple_items(908 collection: &NonfungibleHandle<T>,909 sender: &T::CrossAccountId,910 data: Vec<CreateItemData<T>>,911 nesting_budget: &dyn Budget,912 ) -> DispatchResult {913 if !collection.is_owner_or_admin(sender) {914 ensure!(915 collection.permissions.mint_mode(),916 <CommonError<T>>::PublicMintingNotAllowed917 );918 collection.check_allowlist(sender)?;919920 for item in data.iter() {921 collection.check_allowlist(&item.owner)?;922 }923 }924925 for data in data.iter() {926 <PalletCommon<T>>::ensure_correct_receiver(&data.owner)?;927 }928929 let first_token = <TokensMinted<T>>::get(collection.id);930 let tokens_minted = first_token931 .checked_add(data.len() as u32)932 .ok_or(ArithmeticError::Overflow)?;933 ensure!(934 tokens_minted <= collection.limits.token_limit(),935 <CommonError<T>>::CollectionTokenLimitExceeded936 );937938 let mut balances = BTreeMap::new();939 for data in &data {940 let balance = balances941 .entry(&data.owner)942 .or_insert_with(|| <AccountBalance<T>>::get((collection.id, &data.owner)));943 *balance = balance.checked_add(1).ok_or(ArithmeticError::Overflow)?;944945 ensure!(946 *balance <= collection.limits.account_token_ownership_limit(),947 <CommonError<T>>::AccountTokenLimitExceeded,948 );949 }950951 for (i, data) in data.iter().enumerate() {952 let token = TokenId(first_token + i as u32 + 1);953954 <PalletStructure<T>>::check_nesting(955 sender.clone(),956 &data.owner,957 collection.id,958 token,959 nesting_budget,960 )?;961 }962963 // =========964965 with_transaction(|| {966 for (i, data) in data.iter().enumerate() {967 let token = first_token + i as u32 + 1;968969 <TokenData<T>>::insert(970 (collection.id, token),971 ItemData {972 // const_data: data.const_data.clone(),973 owner: data.owner.clone(),974 },975 );976977 <PalletStructure<T>>::nest_if_sent_to_token_unchecked(978 &data.owner,979 collection.id,980 TokenId(token),981 );982983 if let Err(e) = Self::set_token_properties(984 collection,985 sender,986 TokenId(token),987 data.properties.clone().into_iter(),988 true,989 nesting_budget,990 ) {991 return TransactionOutcome::Rollback(Err(e));992 }993 }994 TransactionOutcome::Commit(Ok(()))995 })?;996997 <TokensMinted<T>>::insert(collection.id, tokens_minted);998 for (account, balance) in balances {999 <AccountBalance<T>>::insert((collection.id, account), balance);1000 }1001 for (i, data) in data.into_iter().enumerate() {1002 let token = first_token + i as u32 + 1;1003 <Owned<T>>::insert((collection.id, &data.owner, token), true);10041005 <PalletEvm<T>>::deposit_log(1006 ERC721Events::Transfer {1007 from: H160::default(),1008 to: *data.owner.as_eth(),1009 token_id: token.into(),1010 }1011 .to_log(collection_id_to_address(collection.id)),1012 );1013 <PalletCommon<T>>::deposit_event(CommonEvent::ItemCreated(1014 collection.id,1015 TokenId(token),1016 data.owner.clone(),1017 1,1018 ));1019 }1020 Ok(())1021 }10221023 pub fn set_allowance_unchecked(1024 collection: &NonfungibleHandle<T>,1025 sender: &T::CrossAccountId,1026 token: TokenId,1027 spender: Option<&T::CrossAccountId>,1028 assume_implicit_eth: bool,1029 ) {1030 if let Some(spender) = spender {1031 let old_spender = <Allowance<T>>::get((collection.id, token));1032 <Allowance<T>>::insert((collection.id, token), spender);1033 // In ERC721 there is only one possible approved user of token, so we set1034 // approved user to spender1035 <PalletEvm<T>>::deposit_log(1036 ERC721Events::Approval {1037 owner: *sender.as_eth(),1038 approved: *spender.as_eth(),1039 token_id: token.into(),1040 }1041 .to_log(collection_id_to_address(collection.id)),1042 );1043 // In Unique chain, any token can have any amount of approved users, so we need to1044 // set allowance of old owner to 0, and allowance of new owner to 11045 if old_spender.as_ref() != Some(spender) {1046 if let Some(old_owner) = old_spender {1047 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1048 collection.id,1049 token,1050 sender.clone(),1051 old_owner,1052 0,1053 ));1054 }1055 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1056 collection.id,1057 token,1058 sender.clone(),1059 spender.clone(),1060 1,1061 ));1062 }1063 } else {1064 let old_spender = <Allowance<T>>::take((collection.id, token));1065 if !assume_implicit_eth {1066 // In ERC721 there is only one possible approved user of token, so we set1067 // approved user to zero address1068 <PalletEvm<T>>::deposit_log(1069 ERC721Events::Approval {1070 owner: *sender.as_eth(),1071 approved: H160::default(),1072 token_id: token.into(),1073 }1074 .to_log(collection_id_to_address(collection.id)),1075 );1076 }1077 // In Unique chain, any token can have any amount of approved users, so we need to1078 // set allowance of old owner to 01079 if let Some(old_spender) = old_spender {1080 <PalletCommon<T>>::deposit_event(CommonEvent::Approved(1081 collection.id,1082 token,1083 sender.clone(),1084 old_spender,1085 0,1086 ));1087 }1088 }1089 }10901091 pub fn get_allowance(1092 collection: &NonfungibleHandle<T>,1093 token_id: TokenId,1094 ) -> Result<Option<T::CrossAccountId>, DispatchError> {1095 ensure!(1096 <TokenData<T>>::get((collection.id, token_id)).is_some(),1097 <CommonError<T>>::TokenNotFound1098 );1099 Ok(<Allowance<T>>::get((collection.id, token_id)))1100 }11011102 /// Set allowance for the spender to `transfer` or `burn` sender's token.1103 ///1104 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1105 pub fn set_allowance(1106 collection: &NonfungibleHandle<T>,1107 sender: &T::CrossAccountId,1108 token: TokenId,1109 spender: Option<&T::CrossAccountId>,1110 ) -> DispatchResult {1111 if collection.permissions.access() == AccessMode::AllowList {1112 collection.check_allowlist(sender)?;1113 if let Some(spender) = spender {1114 collection.check_allowlist(spender)?;1115 }1116 }11171118 if let Some(spender) = spender {1119 <PalletCommon<T>>::ensure_correct_receiver(spender)?;1120 }11211122 let token_data =1123 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1124 if &token_data.owner != sender {1125 ensure!(1126 collection.ignores_owned_amount(sender),1127 <CommonError<T>>::CantApproveMoreThanOwned1128 );1129 }11301131 // =========11321133 Self::set_allowance_unchecked(collection, sender, token, spender, false);1134 Ok(())1135 }11361137 /// Set allowance for the spender to `transfer` or `burn` sender's token from eth mirror.1138 ///1139 /// - `from`: Address of sender's eth mirror.1140 /// - `to`: Adress of spender.1141 /// - `token`: Token the spender is allowed to `transfer` or `burn`.1142 pub fn set_allowance_from(1143 collection: &NonfungibleHandle<T>,1144 sender: &T::CrossAccountId,1145 from: &T::CrossAccountId,1146 token: TokenId,1147 to: Option<&T::CrossAccountId>,1148 ) -> DispatchResult {1149 if collection.permissions.access() == AccessMode::AllowList {1150 collection.check_allowlist(sender)?;1151 collection.check_allowlist(from)?;1152 if let Some(to) = to {1153 collection.check_allowlist(to)?;1154 }1155 }11561157 if let Some(to) = to {1158 <PalletCommon<T>>::ensure_correct_receiver(to)?;1159 }11601161 ensure!(1162 sender.conv_eq(from),1163 <CommonError<T>>::AddressIsNotEthMirror1164 );11651166 let token_data =1167 <TokenData<T>>::get((collection.id, token)).ok_or(<CommonError<T>>::TokenNotFound)?;1168 if token_data.owner != *from {1169 ensure!(1170 collection.limits.owner_can_transfer()1171 && (collection.is_owner_or_admin(sender) || collection.is_owner_or_admin(from)),1172 <CommonError<T>>::CantApproveMoreThanOwned1173 );1174 }11751176 // =========11771178 Self::set_allowance_unchecked(collection, from, token, to, false);1179 Ok(())1180 }11811182 /// Checks allowance for the spender to use the token.1183 fn check_allowed(1184 collection: &NonfungibleHandle<T>,1185 spender: &T::CrossAccountId,1186 from: &T::CrossAccountId,1187 token: TokenId,1188 nesting_budget: &dyn Budget,1189 ) -> DispatchResult {1190 if spender.conv_eq(from) {1191 return Ok(());1192 }1193 if collection.permissions.access() == AccessMode::AllowList {1194 // `from`, `to` checked in [`transfer`]1195 collection.check_allowlist(spender)?;1196 }11971198 if collection.ignores_token_restrictions(spender) {1199 return Ok(());1200 }12011202 if let Some(source) = T::CrossTokenAddressMapping::address_to_token(from) {1203 ensure!(1204 <PalletStructure<T>>::check_indirectly_owned(1205 spender.clone(),1206 source.0,1207 source.1,1208 None,1209 nesting_budget1210 )?,1211 <CommonError<T>>::ApprovedValueTooLow,1212 );1213 return Ok(());1214 }1215 if <Allowance<T>>::get((collection.id, token)).as_ref() == Some(spender) {1216 return Ok(());1217 }1218 if <CollectionAllowance<T>>::get((collection.id, from, spender)) {1219 return Ok(());1220 }12211222 Err(<CommonError<T>>::ApprovedValueTooLow.into())1223 }12241225 /// Transfer NFT token from one account to another.1226 ///1227 /// Same as the [`transfer`] but spender doesn't needs to be the owner of the token.1228 /// The owner should set allowance for the spender to transfer token.1229 ///1230 /// [`transfer`]: struct.Pallet.html#method.transfer1231 pub fn transfer_from(1232 collection: &NonfungibleHandle<T>,1233 spender: &T::CrossAccountId,1234 from: &T::CrossAccountId,1235 to: &T::CrossAccountId,1236 token: TokenId,1237 nesting_budget: &dyn Budget,1238 ) -> DispatchResultWithPostInfo {1239 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12401241 // =========12421243 // Allowance is reset in [`transfer`]1244 let mut result = Self::transfer(collection, from, to, token, nesting_budget);1245 add_weight_to_post_info(&mut result, <SelfWeightOf<T>>::check_allowed_raw());1246 result1247 }12481249 /// Burn NFT token for `from` account.1250 ///1251 /// Same as the [`burn`] but spender doesn't need to be an owner of the token. The owner should1252 /// set allowance for the spender to burn token.1253 ///1254 /// [`burn`]: struct.Pallet.html#method.burn1255 pub fn burn_from(1256 collection: &NonfungibleHandle<T>,1257 spender: &T::CrossAccountId,1258 from: &T::CrossAccountId,1259 token: TokenId,1260 nesting_budget: &dyn Budget,1261 ) -> DispatchResult {1262 Self::check_allowed(collection, spender, from, token, nesting_budget)?;12631264 // =========12651266 Self::burn(collection, from, token)1267 }12681269 /// Check that `from` token could be nested in `under` token.1270 ///1271 pub fn check_nesting(1272 handle: &NonfungibleHandle<T>,1273 sender: T::CrossAccountId,1274 from: (CollectionId, TokenId),1275 under: TokenId,1276 nesting_budget: &dyn Budget,1277 ) -> DispatchResult {1278 let nesting = handle.permissions.nesting();12791280 #[cfg(not(feature = "runtime-benchmarks"))]1281 let permissive = false;1282 #[cfg(feature = "runtime-benchmarks")]1283 let permissive = nesting.permissive;12841285 if permissive {1286 ensure!(1287 <TokenData<T>>::contains_key((handle.id, under)),1288 <CommonError<T>>::TokenNotFound1289 );1290 } else if nesting.token_owner1291 && <PalletStructure<T>>::check_indirectly_owned(1292 sender.clone(),1293 handle.id,1294 under,1295 Some(from),1296 nesting_budget,1297 )? {1298 // Pass, token existence and ouroboros checks are done in `check_indirectly_owned`1299 } else if nesting.collection_admin && handle.is_owner_or_admin(&sender) {1300 // token existence and ouroboros checks are done in `get_checked_topmost_owner`1301 let _ = <PalletStructure<T>>::get_checked_topmost_owner(1302 handle.id,1303 under,1304 Some(from),1305 nesting_budget,1306 )?1307 .ok_or(<CommonError<T>>::TokenNotFound)?;1308 } else {1309 fail!(<CommonError<T>>::UserIsNotAllowedToNest);1310 }13111312 if let Some(whitelist) = &nesting.restricted {1313 ensure!(1314 whitelist.contains(&from.0),1315 <CommonError<T>>::SourceCollectionIsNotAllowedToNest1316 );1317 }1318 Ok(())1319 }13201321 fn nest(under: (CollectionId, TokenId), to_nest: (CollectionId, TokenId)) {1322 <TokenChildren<T>>::insert((under.0, under.1, (to_nest.0, to_nest.1)), true);1323 }13241325 fn unnest(under: (CollectionId, TokenId), to_unnest: (CollectionId, TokenId)) {1326 <TokenChildren<T>>::remove((under.0, under.1, to_unnest));1327 }13281329 fn collection_has_tokens(collection_id: CollectionId) -> bool {1330 <TokenData<T>>::iter_prefix((collection_id,))1331 .next()1332 .is_some()1333 }13341335 fn token_has_children(collection_id: CollectionId, token_id: TokenId) -> bool {1336 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1337 .next()1338 .is_some()1339 }13401341 pub fn token_children_ids(collection_id: CollectionId, token_id: TokenId) -> Vec<TokenChild> {1342 <TokenChildren<T>>::iter_prefix((collection_id, token_id))1343 .map(|((child_collection_id, child_id), _)| TokenChild {1344 collection: child_collection_id,1345 token: child_id,1346 })1347 .collect()1348 }13491350 /// Mint single NFT token.1351 ///1352 /// Delegated to [`create_multiple_items`]1353 ///1354 /// [`create_multiple_items`]: struct.Pallet.html#method.create_multiple_items1355 pub fn create_item(1356 collection: &NonfungibleHandle<T>,1357 sender: &T::CrossAccountId,1358 data: CreateItemData<T>,1359 nesting_budget: &dyn Budget,1360 ) -> DispatchResult {1361 Self::create_multiple_items(collection, sender, vec![data], nesting_budget)1362 }13631364 /// Sets or unsets the approval of a given operator.1365 ///1366 /// The `operator` is allowed to transfer all token pieces of the `owner` on their behalf.1367 /// - `owner`: Token owner1368 /// - `operator`: Operator1369 /// - `approve`: Should operator status be granted or revoked?1370 pub fn set_allowance_for_all(1371 collection: &NonfungibleHandle<T>,1372 owner: &T::CrossAccountId,1373 operator: &T::CrossAccountId,1374 approve: bool,1375 ) -> DispatchResult {1376 <PalletCommon<T>>::set_allowance_for_all(1377 collection,1378 owner,1379 operator,1380 approve,1381 || <CollectionAllowance<T>>::insert((collection.id, owner, operator), approve),1382 ERC721Events::ApprovalForAll {1383 owner: *owner.as_eth(),1384 operator: *operator.as_eth(),1385 approved: approve,1386 }1387 .to_log(collection_id_to_address(collection.id)),1388 )1389 }13901391 /// Tells whether the given `owner` approves the `operator`.1392 pub fn allowance_for_all(1393 collection: &NonfungibleHandle<T>,1394 owner: &T::CrossAccountId,1395 operator: &T::CrossAccountId,1396 ) -> bool {1397 <CollectionAllowance<T>>::get((collection.id, owner, operator))1398 }13991400 pub fn repair_item(collection: &NonfungibleHandle<T>, token: TokenId) -> DispatchResult {1401 <TokenProperties<T>>::mutate((collection.id, token), |properties| {1402 properties.recompute_consumed_space();1403 });14041405 Ok(())1406 }1407}pallets/nonfungible/src/weights.rsdiffbeforeafterboth--- a/pallets/nonfungible/src/weights.rs
+++ b/pallets/nonfungible/src/weights.rs
@@ -40,10 +40,10 @@
fn burn_item() -> Weight;
fn burn_recursively_self_raw() -> Weight;
fn burn_recursively_breadth_plus_self_plus_self_per_each_raw(b: u32, ) -> Weight;
- fn transfer() -> Weight;
+ fn transfer_raw() -> Weight;
fn approve() -> Weight;
fn approve_from() -> Weight;
- fn transfer_from() -> Weight;
+ fn check_allowed_raw() -> Weight;
fn burn_from() -> Weight;
fn set_token_property_permissions(b: u32, ) -> Weight;
fn set_token_properties(b: u32, ) -> Weight;
@@ -217,12 +217,12 @@
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
/// Storage: Nonfungible Owned (r:0 w:2)
/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `412`
// Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
+ // Minimum execution time: 9_307_000 picoseconds.
+ Weight::from_parts(10_108_000, 10144)
.saturating_add(T::DbWeight::get().reads(4_u64))
.saturating_add(T::DbWeight::get().writes(5_u64))
}
@@ -252,22 +252,15 @@
.saturating_add(T::DbWeight::get().reads(2_u64))
.saturating_add(T::DbWeight::get().writes(1_u64))
}
- /// Storage: Nonfungible Allowance (r:1 w:1)
+ /// Storage: Nonfungible Allowance (r:1 w:0)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible TokenData (r:1 w:1)
- /// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible AccountBalance (r:2 w:2)
- /// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
- /// Storage: Nonfungible Owned (r:0 w:2)
- /// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `527`
- // Estimated: `10144`
- // Minimum execution time: 24_919_000 picoseconds.
- Weight::from_parts(25_333_000, 10144)
- .saturating_add(T::DbWeight::get().reads(4_u64))
- .saturating_add(T::DbWeight::get().writes(6_u64))
+ // Measured: `394`
+ // Estimated: `2532`
+ // Minimum execution time: 2_668_000 picoseconds.
+ Weight::from_parts(2_877_000, 2532)
+ .saturating_add(T::DbWeight::get().reads(1_u64))
}
/// Storage: Nonfungible Allowance (r:1 w:1)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
@@ -543,12 +536,12 @@
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
/// Storage: Nonfungible Owned (r:0 w:2)
/// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer() -> Weight {
+ fn transfer_raw() -> Weight {
// Proof Size summary in bytes:
// Measured: `412`
// Estimated: `10144`
- // Minimum execution time: 18_629_000 picoseconds.
- Weight::from_parts(18_997_000, 10144)
+ // Minimum execution time: 9_307_000 picoseconds.
+ Weight::from_parts(10_108_000, 10144)
.saturating_add(RocksDbWeight::get().reads(4_u64))
.saturating_add(RocksDbWeight::get().writes(5_u64))
}
@@ -578,22 +571,15 @@
.saturating_add(RocksDbWeight::get().reads(2_u64))
.saturating_add(RocksDbWeight::get().writes(1_u64))
}
- /// Storage: Nonfungible Allowance (r:1 w:1)
+ /// Storage: Nonfungible Allowance (r:1 w:0)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible TokenData (r:1 w:1)
- /// Proof: Nonfungible TokenData (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)
- /// Storage: Nonfungible AccountBalance (r:2 w:2)
- /// Proof: Nonfungible AccountBalance (max_values: None, max_size: Some(65), added: 2540, mode: MaxEncodedLen)
- /// Storage: Nonfungible Owned (r:0 w:2)
- /// Proof: Nonfungible Owned (max_values: None, max_size: Some(74), added: 2549, mode: MaxEncodedLen)
- fn transfer_from() -> Weight {
+ fn check_allowed_raw() -> Weight {
// Proof Size summary in bytes:
- // Measured: `527`
- // Estimated: `10144`
- // Minimum execution time: 24_919_000 picoseconds.
- Weight::from_parts(25_333_000, 10144)
- .saturating_add(RocksDbWeight::get().reads(4_u64))
- .saturating_add(RocksDbWeight::get().writes(6_u64))
+ // Measured: `394`
+ // Estimated: `2532`
+ // Minimum execution time: 2_668_000 picoseconds.
+ Weight::from_parts(2_877_000, 2532)
+ .saturating_add(RocksDbWeight::get().reads(1_u64))
}
/// Storage: Nonfungible Allowance (r:1 w:1)
/// Proof: Nonfungible Allowance (max_values: None, max_size: Some(57), added: 2532, mode: MaxEncodedLen)